Skip to content

design: A general multi-tenant egress core in Cortex, with moca's code behind one build tag #2042

Open
12 of 21 issues completed

Description

@huang195

This issue replaces epic #1490 (closed on 2026-11-23). It is the one place that tracks Cortex as moca's multi-tenant egress proxy. Every issue of #1490 is now a sub-issue here.

Why

moca-egress serves one tenant only. It refuses MOCA_TENANCY=multi and any grant. moca needs one egress proxy per KVM host that serves many users at once. We choose to build that once, in Cortex, as a new and general Cortex role: a shared, multi-tenant egress proxy on a host. moca is its first user, and Cortex then retires moca-egress (#1490, shape A).

This changes moca's MI1 plan, which puts multi-tenancy inside moca-egress (S2 + S4) and Cortex later (S6). MI1 §10.2 and §14 need an amendment (decision D1 below).

Status

Problem

Seven PRs implemented #1490's children by copying moca's contract word for word: #1537, #1539, #1548, #1549, #1569, #1673 and #1857. That put moca into Cortex's core and into builds that never run on a moca host:

  • The general forward proxy answers its refusals in moca's format. pipeline.MocaRefusal sets X-Moca-Egress-Error for destination_denied (core/listener/forwardproxy/record.go:187) and for upstream_unverified (tunnel.go:484).
  • The general egress allowlist also reads MOCA_EGRESS_ALLOW (cmd/cortex/main.go:292).
  • core/listener/vmcontrol (Feat: Per-VM socket handover and control channel for MOCA SBX #1569) is compiled into every cortex binary, laptop included. Its only build tag is unix.
  • scripts/profile-tags prints only include_plugin_* tags, so a build cannot leave out a listener.

And every Cortex deployment today assumes one tenant per process. A shared proxy breaks that assumption in the session store, the budgets, the cost data and the recordings.

Goal

  1. A general multi-tenant core in Cortex, with three internal seams and one shared mode. moca plugs in drivers.
  2. All moca code in one place, behind one build tag, in one build for the host-egress role.
  3. moca's wire contract stays as it is. Cortex passes moca's conformance suite with MOCA_TENANCY=multi.

The seams are internal Go interfaces, not published contracts. They are justified now: moca itself needs two identity sources (see Facts).

Non-goals

  • A published, versioned contract or modules for partners. Not until another platform needs one.
  • Other drivers (SPIFFE, a proxy token, Vault). The seams leave room for them. Nobody builds them now. The RFC 8693 token exchange is not in this list: it is moca's designed multi-tenant lookup for harness sessions (MI1 §6.3).
  • One Cortex process per tenant (option B in the discussion). We chose one shared process.
  • A model gateway for moca's agent processes ("Cortex 1").
  • State kept per tenant: a session store, budgets or cost data for each tenant. On this role the design keeps no tenant state (recording off, feat: Write one complete, asynchronous audit event per request through Binding.Record #2089). Add it only when someone needs it.
  • A core list of decision names with one reporter for refusals and audit. The formats stay in the driver as two small functions. Revisit when a second platform exists.
  • The host-egress role on Praxis. Not before Tracker: Move the laptop data plane to Praxis when the upstream gaps close #1714 phase D, and not before Praxis can serve a listener on a socket that another process hands over (see Praxis below).
  • Changes to the laptop. Shared mode is off on a laptop, and nothing there changes.

Shared contract

Every sub-issue uses these names, and each one repeats the part it needs. Each issue adds only the part it owns, marked in brackets. Read at Cortex main 7f3eec7 and moca main e464dd6 (egress code unchanged at 3b53f15), 2026-11-23.

// core/pipeline/caller.go  [#2087]

// Caller is who sent a request, as the connection's identity source says.
// The fields follow Praxis's AuthenticatedIdentity, so a later port copies them.
type Caller struct {
	SessionID   string            // never empty for a bound request
	Subject     string            // the user, when the source knows one (the demo driver #2091; the moca driver from #2090)
	Claims      map[string]string // for example "tenant". Read-only after Admit.
	Credentials []string          // credential names the caller may use. nil: no limit from the source.
	Expires     time.Time         // zero: no expiry
	Grant       []byte            // opaque to the core. Only the driver reads it (#2090).
}

// Binding is what an identity source attaches to a connection it accepted.
type Binding interface {
	// Admit runs once for each request on the connection, decrypted requests
	// included, before anything else reads the request. host is the destination
	// without its port (for a decrypted request, the tunnel's host). Admit may
	// remove headers from r. With ok false, Admit has answered w, and nothing
	// else runs for r.  [#2087]
	Admit(w http.ResponseWriter, r *http.Request, host string) (c Caller, ok bool)

	// 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.  [#2086]
	Refusal(a Action, host string) Action

	// Record receives the one terminal outcome of each request.  [#2089]
	Record(r *http.Request, o Outcome)
}

func WithBinding(ctx context.Context, b Binding) context.Context // [#2087]
func BindingFrom(ctx context.Context) (Binding, bool)            // [#2087]

The core's rules (core/listener/forwardproxy):

Order: #2085 → #2087 → #2086 → #2088 → #2091 → #2089 → (moca step 6) → #2090 → #1489.

Design

General core (no moca names)

Two seams (Binding, Resolver) and one mode. An identity source writes one thing: the binding for a connection. The core does the rest, so a new source cannot forget a step.

Part What it does Replaces in the earlier plan
Binding (seam 1) The identity source stamps one Binding on each connection it accepts. The TLS bridge copies it into each decrypted request, as it copies connProcKey today (forwardproxy/bridging.go:333-335). Three methods: Admit runs once for every request, before anything reads it, and returns the Caller (it may strip headers, charge caps, or refuse, for example after a grant expires). Refusal formats the connection's refusals. Record gets each request's outcome for the audit line. TrustedSessionID / TrustedCaller and AdoptBridgedRequest (server.go:182-206), deleted. The refusal formatter hook and the audit path.
Caller SessionID, Subject, Claims (for example the tenant), Credentials (allowed names), Expires, and an opaque Grant. Its shape follows Praxis's AuthenticatedIdentity (subject, roles, teams, claims), so a later port is a field copy. Plugins see it as pctx.Caller, and as pctx.Identity when Subject is set. A fixed struct with moca-shaped fields
Resolver (seam 2) (caller, host) → credentials, each with a port, a path prefix, 1–4 headers and a subject. One cache in the core: keyed on the caller from the binding only, TTL clamped to 5–300 s, one lookup at a time per key. Entries end on Unregister and at expiry, not only at TTL. —
Interception On the shared role, the core intercepts a host only when the resolver returns a credential for it. That is moca's rule today (moca handler.go:239-260). On a laptop, tls_bridge keeps its own rule. InterceptFor, deleted
Injection Envoy credential_injector rules: on a match, overwrite the header and remove the guest's Authorization. With no match, the request passes unchanged. moca's header rules (a value with CR, LF or NUL is refused). Never over plain HTTP. A bound, intercepted connection always fails closed. Injection runs last in the outbound pipeline, so no other plugin or recorder sees the secret. The rule applies to source: resolver only, so sidecar configs keep loading. —
Shared mode (Config.SharedMode, set in code, never in YAML) cmd/cortex turns it on when it starts a multi-tenant identity source, moca or not. The core then refuses every request that has no binding (403 no_binding). The presets and Validate keep the role safe: roles: [forward], no transparent listener, no praxis, loopback addresses and no pprof, no session store or session API, no inference-router, no cost ledger, nothing written to disk. Start-up checks keyed on "the moca control channel is on" in #2085, #2087, #2089, #2090
Output formats Binding.Refusal and Binding.Record. The core's default is Cortex's own JSON refusal and no audit line. pipeline.MocaRefusal in general code (record.go:187, tunnel.go:484)
Egress policy Allowlist, SSRF check, caps per connection and per session, fail closed Built (#1480, #1483, #1484, #1485). Unchanged.

moca drivers (behind one build tag)

Driver What it does
Identity source 1: microVM Returns a Binding for each per-VM listener. Handed-over socket (SCM_RIGHTS) plus a grant in Register and Rebind. Keeps today's vmcontrol codec. The grant is a different token on each path: harness sessions use moca's grant (typ moca-grant+jwt, MI1 §6.1). The sandbox service uses its sandbox token (typ moca-sandbox+jwt), which its egress-credentials spec makes the grant (§9).
Identity source 2: container tier (later, MI1 S5) TCP listener on the sandbox network. Returns a Binding from the source address: address → sandbox ID → owner. The relay sends grants with Rebind.
Grant check Each path accepts only its own token type. Harness: typ moca-grant+jwt, alg EdDSA, aud moca-sandbox, exp, sid, keys from MOCA_GRANT_PUBLIC_KEYS (<kid>:<base64 SPKI>). Sandbox service: the sandbox token, which the control plane also verifies at each credential lookup (phase 2).
Binding lifecycle Register, Unregister, Rebind. Bindings keyed by (control connection, VM ID).
Credential resolver Today: POST /v1/egress/credential with the host's token (the sandbox service's phase 1). Under multi, the lookup must carry the grant. Sandbox service: phase 2 adds the sandbox token to the same request. Harness: MI1 §6.3's POST /internal/token, an RFC 8693 exchange. The driver calls the existing tokenexchange/exchange.Client library, with one new option for subject_token_type. The token-exchange plugin does not change. A cache and one lookup at a time per key, in every case.
Output formats X-Moca-Egress-Error and the body <code>: <name>. moca's audit event with via: "moca-egress".
Start-up MOCA_TENANCY. The driver declares itself multi-tenant, so shared mode applies. It adds only moca's own rules: under multi, the grant keys for the enabled path and the control-plane token (MI1 §10.1).

Build

scripts/profile-tags learns to emit a non-plugin tag. Only the host-egress build carries the moca tag. The local, full, lite and envoy builds contain no moca code. The general core is in every build, inert where no identity source is configured.

Praxis

#1714 moves the laptop data plane to Praxis. This role stays on the Go forward proxy, and shared mode turns praxis off here. The seams are chosen so that they survive a later port:

This design Praxis 0.8.0
Binding → Caller An identity filter publishes AuthenticatedIdentity in the request extensions. PPE's policy filter reads it (policy/filter.rs:1295-1317).
Resolver and injection DeferredCredential: a secret bound to a host or host:port, with one header, and refused on Host, framing and hop-by-hop headers (credentials.rs:127-205)
Shared mode A check in the generator of gateway.yaml
Policy for each tenant (IBAC #1487, an allowlist per tenant) PPE policies on AuthenticatedIdentity. Do not build them in Go first.

Gap: no listener on a socket handed over by another process was found in praxis 0.8.0. moca's per-VM sockets need one.

Security model

What "multi-tenant" means here. One Cortex process serves many tenants on one host. For each connection, it knows which tenant sent it. It selects that tenant's credentials, counts that tenant's use, and stores nothing that another tenant can read. This is logical isolation inside one shared process. It is not isolation between processes.

Guarantees

# Guarantee Holds if Where it stops
G1 Attribution. A request belongs to the tenant of the connection it arrived on, never to what the request claims. The guest cannot forge the identity source, and no other listener carries egress on this role (#2087 closes :8081, :8082 and praxis). microVM tier: sound. The guest has no NIC, only its own vsock (MI1 §8.3). Container tier: source address plus cap_drop: ALL (MI1 §9.3), which is weaker. Demo driver (#2091): not sound. Any local process can connect to any loopback port.
G2 Credential routing. A tenant's credential goes only into that tenant's requests, and only to the host, port and path in its scope. It never goes over plain HTTP or into a log. G1, and a resolver and cache keyed on the caller from the connection only (#2088). All tenants' credentials are in one process's memory. Only correct code keeps them apart.
G3 Use limits per tenant. Connection caps per VM, request caps per session. The request cap is keyed by the caller's session, not by a header (#2087). Only counts are limited. CPU, memory, bandwidth and DNS are not limited per tenant, so one tenant can slow down the others.
G4 No stored data across tenants. Recording is off. Audit events hold metadata only. #2089's start-up checks, with the session API, stats and health listeners closed to tenants. Audit lines (host, path without query, sid, sub) go to the host's journal. Host administrators can read them, as intended.
G5 Fail closed. No binding, an expired grant, or a failed lookup means no request. — Holds as designed.

What Cortex does not guarantee

  1. Protection from the host or its operator. Cortex decrypts intercepted traffic and holds every tenant's credentials in memory. Root on the host can read them.
  2. Protection from a bug in Cortex. One shared process means that one bug can cross tenants, for example a wrong cache key or a header kept between requests. One process per tenant would prevent this. This design does not.
  3. Limits on a tenant's own credential. After Cortex adds a tenant's token, the guest can do anything that token allows on the allowed hosts. moca's docs say the same: the token's scope is the limit.
  4. An allowlist per tenant. The allowlist is one list for the process. Every tenant can reach every host on it. This is an open question, not a promise.
  5. Availability isolation. A crash or a restart stops egress for every tenant on the host (MI1 §11 accepts this).

The weakest point until moca builds D10

Today's credential lookup takes the host's token and a sandbox ID (the sandbox service's phase 1, ADR-0046). The control plane answers for any sandbox on that host. So the Cortex process, or anyone who steals the host token, can fetch the credentials of every live sandbox on that host. Grants (#2090) stop a VM worker from binding a session it does not hold. They do not limit what a stolen host token can fetch. D10 closes this: the sandbox service's phase 2 and MI1 §6.3's token endpoint bind each lookup to the grant.

Assessment

Decisions

One table for every decision that the sub-issues and the explainer name. "Proposed" is this design's suggestion, not an agreement.

# Decision Owner State
D1 Multi-tenancy in Cortex, not in moca-egress both Assumed yes, not confirmed. A moca ADR must amend MI1 §10.2 and §14. §14 has a condition: Cortex replaces moca-egress only when it passes the suite and moca needs a capability that only Cortex has. The ADR must name that capability (multi-tenancy built once, in a general core, and the plugins of #1487), or move #1487 before the switch.
D2 What proves a VM's session to the egress proxy moca Decided by moca's design: a grant in Register. Harness: moca's grant. Sandbox service: the sandbox token.
D3 Where the sandbox service gets a grant moca Answered by moca's design: the sandbox token (sandbox egress-credentials spec §9, phase 2, owed).
D4 The field for the grant on Exec moca Both specs say field 7, which is now mode. Fields 1–12 are used, so 13 is the next free one.
D5 The shape of Rebind moca MI1 §8.3 and the sandbox spec §9 say Rebind{sid, grant}. Only MI1 §9.3 (container tier) says Rebind{sandbox_id, grant}. ControlRequest field 3 is reserved.
D6 A worker field in egress audit events moca Needed because vm_id repeats across workers. moca's control plane drops events that have unknown fields, so the control plane must change first (#2089).
D7 Which credentials a session may use Cortex Proposed: under multi, filter by the grant's egress names (#2088).
D8 Recording decrypted traffic on a shared host Cortex Proposed: off for this role (#2089).
D9 The host agent's journal filter moca It reads moca-egress.service and keeps .via == "moca-egress". It must also read Cortex's unit, and the drop-in and credential names must match.
D10 Bind each credential lookup to the grant moca Designed, not built: sandbox phase 2, and MI1 §6.3 POST /internal/token. Until then, a stolen host token exposes every live sandbox on that host (ADR-0046).
D11 Process, keys and start-up Cortex Proposed: DynamicUser, keys by LoadCredential=, Type=notify with sd_notify (#2085). Under multi, refuse to start without the CA key, the allowlist, the control-plane token, the keys for the enabled path, and the SSRF guard (#2090).
D12 The user's intent for IBAC (#1487) both Later. On the sandbox service, the prompt is in Claude Code on the laptop, not in the guest.
D13 WebSocket and HTTP/2 on intercepted connections both moca phase 1 allows HTTP/1.1 only and removes Upgrade. Cortex forwards WebSocket today (#1488). MI1 §8.5 allows both. To decide for this role.
D14 Allow-all (MOCA_EGRESS_ALLOW=*) under multi both moca supports *. Proposed: refuse it under multi.
D15 Credentials for a lease VM between Execs moca A lease VM lives up to 8 h, but phase 2 caps credentials at the sandbox token's life (15 min by default). Who sends Rebind with a fresh token? moca's documents do not say.

Facts this rests on

Read on 2026-11-23, in full, by three independent reviews: moca main at e464dd6, Cortex main at 7f3eec7. Read, not run.

Fact Evidence
moca-egress is single-tenant: it refuses MOCA_TENANCY=multi and a non-empty grant remote-worker/internal/egress/config.go:56-62 (tenancy) · proxy.go:177-179 (grant)
moca has two identity sources: socket identity on the microVM tier, source-address identity on the container tier MI1 §8.3, §9.3
The control plane mints sandbox grants on the harness path. Nothing verifies them on egress yet. microvm-worker has no grant code. packages/control-plane/src/grant.ts, grant-exchange.ts
Exec field 7 is mode, not grant proto/sandbox/v1/sandbox.proto
Today's credential endpoint is the sandbox service's phase 1: {"sandbox","host"} with the host's token → {subject, ttlSeconds, credentials[]}. Phase 2 (owed) adds the sandbox token. remote-worker/internal/egress/cpcreds.go:223-262 · docs/specs/2026-10-26-sbx-egress-credentials-design.md §4.2, §9 · ADR-0046
MI1's multi-tenant lookup for harness sessions is POST /internal/token, RFC 8693, with the grant as subject_token, callable only by the egress proxy. It is not built: the control plane has no such route. MI1 §6.3 · packages/control-plane/src/routes.ts
Each VM worker numbers its VMs from vm-1. A Register from another connection with the same vm_id replaces the binding, in both proxies. moca's Unregister is not scoped to its connection. So two workers on one host cut each other off in both directions. The sandbox installer connects every template worker to one proxy. Nobody has run it. moca vmpool/pool.go:921-924, egress/control/server.go:150-159, 184-200, deploy/sbx/install-host.sh:27-31 · Cortex vmcontrol/registry.go:115-120
The host agent reads the audit events from the journal and posts them unchanged deploy/sbx/host-agent.sh:37-60, 806-807
Cortex has no sd_notify. moca-egress.service is Type=notify. No NOTIFY_SOCKET in Cortex's core/ or cmd/
moca's conformance suite has 30 cases: 13 transport, 2 timeout, and 15 interception cases from the sandbox service. Only grant_refused_under_single involves grants, and it requires that MOCA_TENANCY=multi fails to start. No case runs under multi. remote-worker/egress/conformance/conformance.go:80-111, cases.go:908-921
The suite's runner starts the binary with only the case's environment: no arguments and no config file. The binary is ready when the control socket accepts. The runner stops it with SIGTERM, then SIGKILL after 5 s. remote-worker/egress/conformance/process.go, cmd/moca-egress-conformance/main.go
The suite expects moca's refusal shape for destination_private. Cortex answers in JSON, so Cortex fails those cases today. cases.go:254, 297, 309, 321 · Cortex forwardproxy/server.go:885
moca has no inspect list. MOCA_EGRESS_INSPECT is in MI1 §15, not in the code. moca intercepts only where a credential applies. remote-worker/internal/egress/config.go, handler.go:239-260
On a KVM host, Cortex's transparent listener (:8082) checks neither the allowlist nor the caller. The TCP forward proxy (:8081) takes its session from headers. Both bind on every interface by default. Cortex core/config/presets.go:30, 34, forwardproxy/server.go:129-145

Sub-issues, in order

# Step Issue Needs Blocked on moca?
1 The include_driver_moca tag and the hostegress build. vmcontrol moves behind it. The build starts from the environment alone, with a built-in loopback-only config, and sends sd_notify. moca's conformance suite runs in Cortex CI, pinned to one moca commit, with a list of known failures. #2085 — No
2 Binding.Admit and Caller in the core, copied into decrypted requests. TrustedSessionID and AdoptBridgedRequest deleted. Bindings keyed by (control connection, vm_id). Shared mode. #2087 #2085 No
3 Binding.Refusal: Cortex's own refusal shape by default, moca's on handed-over connections. Every MOCA_* setting moves into the moca driver, with moca's allowlist grammar. #2086 #2087 No
4 Resolver and its cache, with eviction on unbind. Interception follows the resolver and always fails closed when bound. Injection last, with Envoy's rules. moca's resolver. #2088 #2087, #2086 No
5 The demo driver, built here as the second user of the seams. A seam that needs anything from the moca driver gets fixed now. #2091 #2087, #2086, #2088 No
6a Binding.Record: one complete, asynchronous audit event per request, decrypted requests included. The credential cases that wait for an audit event pass here. #2089 #2087, #2088 No
6b moca builds the grant path: the sandbox service's phase 2 (the token on Exec, in Register and Rebind, and in the credential lookup), and for harness sessions MI1 §6.3's token endpoint moca (drafted) D4, D5, D10 Yes
7 Grant check on both paths, with expiry in Binding.Admit. Lookups bound to the grant, through exchange.Client. Rebind. MOCA_TENANCY=multi. #2090 #2087, #2088, #2089, step 6b Yes
8 moca's suite with MOCA_TENANCY=multi against the hostegress build. The CI job from step 1 ends with no known failures. #1489 multi-tenant cases, and a split of grant_refused_under_single (moca, drafted) Yes
9 moca installs Cortex in place of moca-egress, then retires it moca (drafted) 1–8, a published hostegress artifact Yes
10 Later: the container-tier identity source (MI1 S5), body plugins with intent (#1487) — — —

Issues carried over from #1490

Done before #2042. They copied moca's contract into Cortex, and #2086 moves their moca formats into the moca driver:

Issue What it delivered
#1477 Per-VM socket handover and the control channel (vmcontrol)
#1480 Fail closed for hosts that have a credential (tls_bridge.fail_closed)
#1481 No credential over plain HTTP (403 plaintext_credential)
#1483 Deny-by-default egress allowlist
#1484 SSRF guard
#1485 Caps per VM and per session
#1488 WebSocket upgrades on intercepted connections

Closed as replaced by this issue's steps (2026-11-23). Each one has a comment that names its replacement:

Issue Replaced by
#1476 identity #2087 (caller from the connection), then #2090 (subject from the grant)
#1478 resolver #2088. Its RFC 8693 shape is MI1 §6.3's designed multi-tenant endpoint, not yet built. Today's endpoint is the sandbox service's phase 1.
#1479 injection #2088. The binding comes from the resolver's reply, and a placeholder is not required.
#1482 audit #2089
#1486 recording #2089 (off for this role)

Open, and still their own work:

Issue When
#1487 body plugins After #2088 and #2089 (step 10)
#1489 conformance gate Last: after #2085–#2090 and moca's multi-tenant conformance cases (step 8)

Open questions

  • The names of the build tag and of the host-egress build.
  • Do Cortex users outside moca depend on X-Moca-Egress-Error today? Step 2 changes what they see.
  • D13, D14 and D15 above.
  • Can Praxis serve a listener on a socket that another process hands over? Needed before this role can move to Praxis. Ask upstream only when that move is planned.
  • Confirm the two-worker clash with a test on a sandbox-service host (moca draft issue 1). The code says it happens in both directions.

Related: #1490 (the epic this replaces, closed), moca MI1 §6, §8, §9.3, §10, §11, §14.

Sub-issues

Sub-issues

12 of 21 Issues completed
Loading 21 sub-issues

Activity

  1. changed the title [-]design: Make Cortex's shared egress proxy a generic contract, with moca as its first user[/-] [+]design: Contain moca's egress code behind one build tag, out of Cortex's core[/+] on Nov 20, 2026
  2. changed the title [-]design: Contain moca's egress code behind one build tag, out of Cortex's core[/-] [+]design: A general multi-tenant egress core in Cortex, with moca's code behind one build tag[/+] on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions