feat: Answer egress refusals in Cortex's own shape and move moca's format and MOCA_EGRESS_ALLOW into the moca driver

Abierto
#2,086 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
8/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
go

Línea de trabajo

This is design-heavy and depends on #2087 (Binding) landing first. Start in core/pipeline/action.go (MocaRefusal and DenyStatus) and core/listener/httpx/render.go, then follow the refusal call sites in core/listener/forwardproxy/record.go and tunnel.go. Done means every client-facing error goes through one writer, Cortex's JSON shape is the default, and the moca conformance suite still passes.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Parent: #2042, step 3 of the build order (#2085 → #2087 → #2086 → #2088 → #2091 → #2089 → #2090). Needs #2087 (Binding).

Problem

moca's formats leak into Cortex's general forward proxy, so every Cortex user gets them:

  1. Refusals. For an off-list destination and for an upstream that fails verification, the forward proxy answers in moca's format: the header X-Moca-Egress-Error: <code> and a text/plain body <code>: <name>. Other refusals on the same listener use Cortex's JSON shape, so one listener speaks two formats.
  2. Configuration. The general egress allowlist falls back to MOCA_EGRESS_ALLOW when listener.egress_allow_hosts is empty.

moca's conformance suite must still see moca's exact format on the connections that moca hands over, for every refusal, plugin refusals included. And moca's settings use a grammar that Cortex's allowlist refuses today.

This issue makes Cortex's JSON shape the default, adds Binding.Refusal so that a connection's identity source chooses the format, and moves every MOCA_* setting into the moca driver.

Shared contract

This issue adds one method to Binding (#2042, "Shared contract"):

// Refusal returns the answer for a refusal that the core or a plugin makes
// for a request on this connection. a is the refusal in Cortex's shape (its
// Violation keeps the code, the reason and any headers); host is the
// destination host. A source that keeps Cortex's shape returns a.
Refusal(a Action, host string) Action

Every type that implements pipeline.Binding when this lands gets the method: vmBinding (core/listener/vmcontrol/handler.go:27) and each test binding that #2087 added.

Today

Read at Cortex main 7f3eec7 and moca main e464dd6 (2026-11-23).

What Where
moca's refusal builder, in the general package core/pipeline/action.go:169-205, MocaRefusal(status int, code, name string) Action
General callers core/listener/forwardproxy/record.go:187 (egressAllowRefusal, destination_denied), tunnel.go:484 (fail-closed CONNECT, upstream_unverified)
moca-driver callers vmcontrol/handler.go:93 (request_cap), registry.go:299 (conn_cap)
Refusals written from an Action httpx.WriteRejection at record.go:80, server.go:531, 829, 885, tunnel.go:271, 402, 484, egress.go:51. httpx.WriteRejectionForRequest (plugin results) at server.go:669, 678, tunnel.go:328. Both are in core/listener/httpx/render.go:22, 49.
Error answers written with http.Error or WriteHeader server.go:909 (502 after a failed upstream request. The suite expects upstream_unreachable, cases.go:1022, 1199), tunnel.go:136 (refuseMisdirected, 421. The suite expects misdirected_request, cases.go:1387), tunnel.go:426, 457 (CONNECT resolve or dial failure, 502), server.go:595 (body read errors), tunnel.go:362, upgrade.go:141, 396, websocket.go:154, 182, 190, hop.go:179, server.go:1416, 1419, egress.go:61, 66, 76
The JSON shape pipeline.DenyStatus(status, code, reason) renders {"error": <code>, "message": <reason>} (Violation.Render, action.go)
A neutral header that exists headerEgressError = "X-Cortex-Egress-Error" (forwardproxy/hopheaders.go:18), set by the praxis egress listener (egress.go:49, 60) and read and removed by cortex-gateway (praxis/filters/src/record/row.rs:33, 395)
Plugin refusals moca's suite checks plaintext_credential from static-inject (core/plugins/staticinject/plugin.go:266-275)
Connections closed with no answer refuseFailClosed (forwardproxy/bridging.go:103, called at :176, :191, transparent.go:247, tunnel.go:546)
The idle timeout startVMControl sets fp.BridgedIdleTimeout = vmcontrol.IdleTimeout (cmd/cortex/vmcontrol_unix.go:27). It applies to every bridged tunnel of the proxy (server.go:123-127, bridging.go:307), and to no opaque tunnel. vmcontrol.IdleTimeout is a fixed 60 s (handler.go:23), also used as the per-VM http.Server's IdleTimeout (:52). moca's default is 300 s (moca proxy.go:82).
MOCA_EGRESS_ALLOW in general code cmd/cortex/main.go:290-296 (envEgressAllow) and :1142 (the fallback). Tested by TestResolveEgressAllow (cmd/cortex/egressallow_test.go:10).
moca's allowlist grammar Entries without a port (443 for CONNECT, 80 for plain HTTP), *.suffix wildcards, and * alone for allow-all (moca remote-worker/internal/egress/allow.go:12-13, 42-64, config.go:68-80, proxy.go:24-30). moca's deploy defaults are portless (deploy/microvm/setup-microvm.sh:61). Allow-all still refuses link-local, metadata and multicast addresses (handler.go:263-319). Cortex's listener.egress_allow_hosts refuses portless entries and */** at start-up (core/listener/egressallow/egressallow.go:91). *.example.com:443 is accepted as a literal that never matches. moca requires MOCA_EGRESS_ALLOW (moca config.go).
Settings Cortex already has listener.egress_guard.permit_cidrs (core/config/config.go:1215-1220, used at main.go:906). The guard resolves names with net.DefaultResolver (core/listener/egressguard/guard.go:70, check the path). The forward proxy's transport leaves ResponseHeaderTimeout unset on purpose (forwardproxy/server.go:315).
moca settings the suite sets MOCA_EGRESS_RESOLVER (DNS server), MOCA_EGRESS_PERMIT_CIDRS (ranges exempt from the private-address check, 127.0.0.1/32 in the cases), MOCA_EGRESS_IDLE_TIMEOUT_S (default 300, zero refused, every byte on either leg resets it), MOCA_EGRESS_RESPONSE_HEADER_TIMEOUT_S (default: the idle value. Then 502 upstream_unreachable). moca egress/conformance/doc.go, conformance.go:210-215, 777, internal/egress/config.go:82-123, proxy.go:51-90. Cases: connect_tunnel_idle_deadline, forward_response_header_timeout.
A moca start-up rule A credential setting without a credentials URL is a boot failure (moca config.go:155-164). The settings are MOCA_EGRESS_CREDENTIALS_TOKEN_FILE, _CREDENTIALS_CA, _CREDENTIALS_TIMEOUT, _NONE_TTL_S, _CA_CERT_FILE, _CA_KEY_FILE, _UPSTREAM_CA (moca config.go:39-45, 157).
What the suite expects for destination_private moca's shape (cases.go:254, 297, 309, 321). Cortex answers JSON (server.go:885, tunnel.go:402), so it fails those cases today.
Tests that assert moca's format in general code forwardproxy/egressallow_gate_test.go:78-86, failclosed_test.go:97, core/pipeline/action_test.go:226-260. vmcontrol/caps_test.go:54 keeps moca's header.
Docs that state moca's format or setting root CLAUDE.md:381, 386, docs/session-api.md:1117-1119, docs/troubleshooting.md:381, comments in core/config/config.go:1095-1193 and forwardproxy/server.go:109-113

Change

  1. One refusal writer in the forward proxy. Every client-facing error answer goes through it: the Action sites and the http.Error sites in the table above. Give each http.Error site a code:

    • upstream_unreachable (502): server.go:909, tunnel.go:426, 457.
    • misdirected_request (421): tunnel.go:136.
    • bad_request (400): server.go:595, tunnel.go:362.
    • the WebSocket, hop and praxis sites (upgrade.go, websocket.go, hop.go, egress.go:61-76, server.go:1416, 1419) keep their status and get a code that names their failure. Shared mode (#2087) turns praxis off, and #2088 removes Upgrade for bound requests.

    The writer works like this:

    • It builds the Action (pipeline.DenyStatus for a site that had none). The status comes from Violation.Render(), and the code from Violation.Code, or denied when it is empty.
    • With a binding in the request context, it writes Binding.Refusal(a, host). host is the CONNECT's host or the request's host, and for a decrypted request the tunnel's host. The MCP JSON-RPC rewrite of WriteRejectionForRequest does not run for a bound request.
    • Without one, it writes the action as today (JSON, or the MCP shape that WriteRejectionForRequest chooses). For egress refusals (destination_denied, destination_private, upstream_unverified, upstream_unreachable), it sets X-Cortex-Egress-Error: <code> with Set, never Add, because egress.go:49 sets it already.
    • refuseFailClosed keeps closing the connection with no answer. Add a comment that says why.
    • The http.Error sites change their body to JSON for everyone. Put that in the release notes.
  2. Cortex's own codes become JSON: record.go:187 and tunnel.go:484 use pipeline.DenyStatus, not MocaRefusal, with the reasons destination not on the egress allow list and upstream certificate did not verify.

  3. Move MocaRefusal into the moca driver (core/listener/vmcontrol), with its tests. vmBinding.Refusal(a, host) returns MocaRefusal(status, code, host) from a's Violation. After this, core/pipeline has no moca identifier. Removing pipeline.MocaRefusal removes exported API from core. moca's repo does not import it.

  4. Move the idle timeout to the binding's connections. vmcontrol.IdleTimeout becomes a field of vmcontrol.Limits, set from MOCA_EGRESS_IDLE_TIMEOUT_S (default 300 s, zero refused). The driver's listener wraps each accepted connection so that every read and write refreshes a deadline. That bounds opaque tunnels too, which case connect_tunnel_idle_deadline uses (moca cases.go:934-970). Remove fp.BridgedIdleTimeout from startVMControl, so other tunnels keep the default.

  5. Move every MOCA_* setting into the moca driver (cmd/cortex/vmcontrol*.go, behind include_driver_moca):

    • MOCA_EGRESS_ALLOW: remove envEgressAllow and its fallback from main.go, and move TestResolveEgressAllow with it (it then runs only in the Linux hostegress row). The setting is required when the control socket is set, as in moca. listener.egress_allow_hosts still wins when both are set. The driver parses moca's grammar:
      • A portless entry means 443 for CONNECT and 80 for plain HTTP, and nothing else. Give core/listener/egressallow a scheme-aware default-port entry for it. Do not expand it to two host:port entries, which would also allow CONNECT to :80.
      • *.suffix matches any depth below the suffix and not the apex (moca allow.go:144-146). Add plain suffix matching to egressallow behind an option, egressallow.New(entries, egressallow.AllowWildcards()). Do not use hostglob, which confines * to one label.
      • * alone means allow-all. As in moca, allow-all skips the private and loopback check and keeps refusing link-local, metadata, multicast and broadcast addresses (moca proxy.go:24-29, handler.go:277-282). Under multi, #2090 refuses * (D14).
      • listener.egress_allow_hosts keeps its strict grammar.
    • MOCA_EGRESS_RESOLVER: one DNS server for every lookup: the dialer, the egress guard (which uses net.DefaultResolver today) and the TLS bridge's upstream. Add a general setting for it.
    • MOCA_EGRESS_PERMIT_CIDRS: set listener.egress_guard.permit_cidrs, which exists. An error never prints the value.
    • MOCA_EGRESS_RESPONSE_HEADER_TIMEOUT_S (default: the idle value): add a general response-header timeout, off by default, and answer 502 upstream_unreachable through the writer when it fires.
    • The driver refuses to start when a credential setting from the table is set without MOCA_EGRESS_CREDENTIALS_URL.
  6. Update the docs and comments in the table above.

Behavior change, for the release notes

  • In builds without the moca driver (local, full, lite, envoy, cpex), an off-list destination and an unverified upstream now answer in Cortex's JSON shape, with X-Cortex-Egress-Error. They no longer send X-Moca-Egress-Error.
  • MOCA_EGRESS_ALLOW has no effect there. Use listener.egress_allow_hosts.
  • The hostegress build answers in moca's format on handed-over connections, for every refusal.

Not in scope

  • The format of audit lines (#2089).
  • Refusals for credentials (credential_unavailable, credential_revoked). #2088 makes them through the same writer.

Tests

  • forwardproxy without a binding: destination_denied, destination_private and upstream_unverified answer JSON with X-Cortex-Egress-Error and no X-Moca-* header. A plugin refusal answers as today.
  • forwardproxy with a test binding: every site in both tables writes the binding's Refusal, plugin results included. A plugin's WWW-Authenticate or Retry-After header reaches a binding that returns its input.
  • Rewrite egressallow_gate_test.go:78-86, failclosed_test.go:97 and action_test.go:226-260 for the new shape.
  • vmcontrol: vmBinding.Refusal returns moca's exact bytes for each code above (HTTP/1.1 <status>, Content-Type: text/plain, X-Moca-Egress-Error: <code>, body <code>: <name>). conn_cap and request_cap keep moca's format.
  • The moca allowlist grammar: portless, *.suffix and * entries, each with an allowed and a refused destination. A malformed entry is a start-up error. Allow-all still refuses a link-local address.
  • Each new setting: its default, a bad value refused at start-up, and its effect (connect_tunnel_idle_deadline and forward_response_header_timeout shapes, with a fake DNS server and a permitted range).
  • cmd/cortex with the local tags: MOCA_EGRESS_ALLOW is ignored. With the hostegress tags: it fills the allowlist when the field is empty, and the field wins when both are set.
  • The moca-conformance job (#2085): remove each case that this issue fixes from known-failures.txt, at least the four destination_private cases.

Done when

  • grep -rn 'MocaRefusal\|X-Moca-Egress-Error\|MOCA_' core/pipeline core/listener/forwardproxy core/listener/egressallow core/config cmd/cortex/main.go finds no code. Comments that explain may stay.
  • Every refusal on a handed-over connection is in moca's format. Every other refusal is in Cortex's shape.
  • known-failures.txt is shorter by the cases this issue fixes.
Lenguaje dominante
Go
Estrellas
31
Forks
49
Merge medio
9 h 43 min
PR fusionados (30 d)
367

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de rossoctl/cortex

Todos los issues de rossoctl/cortex

Issues similares

Más issues de Go

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.