feat: Add a connection Binding and shared mode, and key VM bindings by control connection
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 8/100
調査の方向性
Start with core/pipeline/caller.go for the Caller and Binding contract, then read where forwardproxy's trustedSessionOf and the AdoptBridgedRequest hook are used in server.go, tunnel.go and bridging.go. vmcontrol/handler.go and registry.go hold the moca side. Done means the two hooks are gone, bindings are keyed by control connection and vm_id, and the listed tests pass.
索引モデルが issue の本文から書いたものです。
説明
Parent: #2042, step 2 of the build order (#2085 → #2087 → #2086 → #2088 → #2091 → #2089 → #2090). Needs #2085 (the include_driver_moca tag and the hostegress build).
Problem
A shared egress proxy must know, for every request, which caller sent it, and a guest must never be able to change that answer. Today:
- Cortex learns only a session ID from the connection, through a hook (
TrustedSessionID). - A decrypted request inside an intercepted tunnel needs a second hook (
AdoptBridgedRequest). Without it, the guest's own headers decide the session. - The role's safety rules (other listeners closed, no session store, and so on) do not exist yet. The earlier plan spread them over four issues, each keyed on "the moca control channel is on". A second identity source would have to repeat every one of them.
- Bindings are keyed by
vm_idalone, so two VM workers on one host cut each other off.
This issue replaces both hooks with one Binding that the identity source attaches to the connection, adds shared mode as one place for the role's rules, and keys bindings by control connection. It changes nothing on the wire.
Shared contract
This issue creates Caller, Binding (with Admit only), WithBinding, BindingFrom and shared mode, as #2042's "Shared contract" defines them:
// core/pipeline/caller.go
type Caller struct {
SessionID string
Subject string
Claims map[string]string
Credentials []string
Expires time.Time
Grant []byte
}
type Binding interface {
Admit(w http.ResponseWriter, r *http.Request, host string) (c Caller, ok bool)
}
func WithBinding(ctx context.Context, b Binding) context.Context
func BindingFrom(ctx context.Context) (Binding, bool)
Refusal (#2086) and Record (#2089) join the interface later. The context key is a named type, as bindingCtxKey is today (vmcontrol/handler.go:115). The Caller is stored under an unexported key in forwardproxy.
Today
Read at Cortex main 7f3eec7 and moca main e464dd6 (2026-11-23).
| What | Where |
|---|---|
| The session hook | forwardproxy.Server.TrustedSessionID func(r *http.Request) string (core/listener/forwardproxy/server.go:182-189), read by trustedSessionOf (identity.go:59-64) |
| Where the trusted session is read | record.go:50, server.go:493 (in serveOutbound, :450), tunnel.go:144, tunnel.go:243 (in handleConnect, :223) |
| The bridged-request hook | Server.AdoptBridgedRequest (server.go:191-206), called in the bridged handler (bridging.go:340-345) after it copies connProcKey from the tunnel (:333-335). The handler then sets r.URL.Host = authority and calls serveOutbound (:346-348). |
| What vmcontrol's hooks do | SessionIDFromRequest (vmcontrol/handler.go:121-126). AdoptBridgedRequest (:145-157) does three things: it strips the guest's identity headers (stripGuestHeaders, :174-183, list at :164-170), charges the session's request cap (chargeRequest, :82-95, which also emits the request_cap audit line), and stamps the binding. vmBinding.ServeHTTP (:189-223) does the same for plain requests and CONNECTs. It also keeps the live set and writes the terminal audit line (emit, :222), except after a cap refusal (:216-218). |
| Who sets the hooks | startVMControl (cmd/cortex/vmcontrol_unix.go:17-29), before any listener serves (main.go:1215-1228). The tunnel keeps its CONNECT in tl.connect only for AdoptBridgedRequest (tunnel.go:375-378, 711-714). |
| Per-turn contexts | A WebSocket builds a new pipeline.Context for each turn and copies the session fields from the handshake (newTurnContext, websocket.go:796-842) |
The existing field named Shared |
forwardproxy.Server.Shared pipeline.SharedStore is the memstore (server.go:96, read at :469, transparent.go:103, websocket.go:827), and so is pctx.Shared (pipeline/context.go:290). The new flag must have another name: SharedMode. |
| Identity for plugins | pipeline.Identity (Subject(), ClientID(), Scopes(), core/pipeline/context.go:30). In production code, pctx.Identity (:203) is set only by jwt-validation (jwtvalidation/plugin.go:440), so it is nil on the forward path. SnapshotIdentity copies it into every session event (pipeline/snapshot_context.go:43-58). |
Plugins that read pctx.Identity |
opa (opa/plugin.go:528-533, input.identity), tokenexchange (the delegation subject, tokenexchange/plugin.go:767), tokenexchangeaiac (plugin.go:553), lineage (plugin.go:991), contextguru (plugin.go:486), cpex (manager_cpex.go:832). ibac reads pctx.LastIntent() (ibac/plugin.go:451). session-budget reads pctx.SessionID (sessionbudget/plugin.go:814). |
Bindings keyed by vm_id |
vmcontrol.Registry.vms map[string]*vmBinding (registry.go:79). Register (:109-128) replaces an existing entry. Unregister (:138). vmcontrol.Server.bindings "vmID → owning connection" (server.go:38). register supersedes another connection's binding (:219-236). The Unregister case accepts a vm_id from any connection (about :186-194). dropConn (:259-277). The Handler interface carries no connection: Register(vmID, sid, grant, ln), Unregister(vmID) (control.go:43-49). |
| The request cap | Counted per session ID (registry.go, sessions, acquire/release) |
| The same clash in moca | remote-worker/internal/egress/control/server.go:150-159 (Unregister from any connection) and :184-200 (supersede). Every worker numbers VMs from vm-1 (vmpool/pool.go:921-924). The sandbox installer connects every template worker to one proxy (deploy/sbx/install-host.sh:27-31). So two workers cut each other off in both directions. |
| Listeners a guest could use instead | The transparent listener checks neither the allowlist nor the session hook (EgressAllow is read only at server.go:519, 816 and tunnel.go:255). The preset binds it on :8082 (core/config/presets.go:34), and setDefault refills an empty value (:81-85). The TCP forward proxy binds :8081 on every interface (presets.go:30, listenerplan.go:37), and a request there takes its session from headers or ActiveSession() (server.go:129-145). Praxis mode adds a praxis-egress listener and fpSrv.Hop (main.go:1229-1247). |
| Listeners that show data | Stats (:9093) and health (:9091) bind on every interface by default (core/config/config.go:1339, presets.go:46). /config (observe/statserver.go:110) returns the whole config through redact.JSON (:167). The stats server's DNS-rebinding guard is WithLoopbackOnly(cfg.Listener.BindLoopbackOnly) (main.go:1284-1286), and BindLoopbackOnly also turns on pprof. The session API has 14 routes (core/sessionapi/server.go:226-249), served whenever the store exists (cmd/cortex/main.go:1295). The cost ledger opens only when the store exists (about main.go:770). session.enabled is on when unset (SessionConfig.Enabled *bool, config.go:564). |
| State shared by all callers | One memstore (main.go:1063). inference-router keeps limits, pins and refusals there (core/plugins/inferencerouter/limits.go:152). The cost ledger turns on when cost_ledger.dir is set or the config is under ~/.cortex (main.go:228-242). |
| Where presets run | config.ApplyPreset (core/config/presets.go), called after Load in buildPipelines (main.go:553-563) and in the supervisor's fallback config (cmd/cortex/fallback.go:84-94). The boot load (main.go:485) does not call it. BindLoopbackOnly runs last and wins (presets.go:60-78). ctrlCfg is resolved at main.go:1103, after the first buildPipelines() call (:637). An empty listener.roles means both roles (config.go:1293-1296). |
| Other paths into the forward proxy | HandleTransparentConn (transparent.go:63, passes an empty trusted session at :113) and NewEgressHandler (praxis, praxis.go:66) never reach handleConnect or serveOutbound |
| Writes to disk that config can cause | tls_bridge.generate_ca (tlsbridge/ca.go:141-157), spiffe.mirror_files (spiffe/mirror.go:26), litellm-budget-track's spend_file (plugin.go:343), script folders (reloader.go:285) |
Change
A. Binding and Caller
- Add
core/pipeline/caller.gowith the contract above, and a fieldpctx.Caller *Caller(nil for a request with no binding). Set it wherehandleConnectandserveOutboundbuild theirpipeline.Context, and copy it, withpctx.Identity, innewTurnContext(websocket.go:796-842), so every WebSocket turn keeps it. - Admit at the two entry points. At the top of
handleConnectand ofserveOutbound, before anything reads the request: whenBindingFrom(r.Context())finds a binding, callAdmit(w, r, host).hostisr.URL.Hostname(), or theHostheader's host for a CONNECT. For a decrypted request that is the tunnel's authority, because the bridged handler setsr.URL.Hostfirst (bridging.go:346). WhenAdmitreturns false, return. When it returns aCallerwith an emptySessionID, answer500 binding_error(a driver bug). Otherwise store theCallerin the request context. - Replace
trustedSessionOfwith a read of the storedCaller'sSessionID, at all four sites (record.go:50,server.go:493,tunnel.go:144,tunnel.go:243).pctx.SessionandSessionSourceConnectionwork exactly as today. - Identity for plugins: when
Caller.Subjectis not empty, setpctx.Identityto an unexported adapter whoseSubject()returns it, and whoseClientID()andScopes()return empty values. It implements no other interface. The moca driver leavesSubjectempty until #2090, so no plugin sees a change from it. The demo driver (#2091) sets it. The PR lists the effect on each reader in the table above,SnapshotIdentityincluded. - Decrypted requests: replace
tl.connectwithtl.binding pipeline.Binding, set inhandleConnectfrom the CONNECT's context. In the bridged handler, puttl.bindingintor's context withpipeline.WithBinding, next to theconnProcKeycopy.serveOutboundthen admits it. - Delete
Server.TrustedSessionID,Server.AdoptBridgedRequest,trustedSessionOf,tl.connect, and the call atbridging.go:340-345. Update the tests that set the deleted fields:forwardproxy/session_source_test.go:65-71,project_test.go:92, 138, 218,parent_test.go:164,vmcontrol/registry_test.go:132(newVMEgressStack),caps_test.go:30,bridge_binding_test.go:87-89.
B. The moca driver
vmBindingimplementsBinding:AdmitcallsstripGuestHeaders(r)andchargeRequest(w, r, host)(unchanged, still moca'srequest_capanswer), and returnsCaller{SessionID: b.sid}.ServeHTTPkeeps the live set, theabortedanswer and the terminal audit line. It no longer strips or charges, and it stamps the binding withpipeline.WithBinding.- One line per request stays true. When
Admitrefuses (the cap),chargeRequestalready wrote therequest_capline. Mark the request refused on vmcontrol'sstatusWriter(reached asw.(*statusWriter)inAdmit), and letServeHTTPskipemitfor it. A decrypted request has no wrapper, so nothing changes there. - Delete
SessionIDFromRequest,AdoptBridgedRequestandbindingCtxKey.
- Key bindings by (control connection,
vm_id) in bothvmcontrol.Server.bindingsandvmcontrol.Registry.vms. TheHandlerinterface gets the connection:Register(owner ConnKey, vmID, sid string, grant []byte, ln net.Listener)andUnregister(owner ConnKey, vmID string), withConnKeyan opaque value per control connection. UpdaterecordingHandlerinvmcontrol/server_test.go.- A
Registerfor avm_idthat another connection holds creates a second binding. It no longer replaces the first one. - A
Registerfor avm_idthat the same connection holds is stillduplicate_vm. Unregister{vm_id}removes only the sending connection's binding.dropConnremoves only that connection's bindings.- A worker that redials ends bound: its new connection's
Registeradds a binding, and the old connection's close removes only the old one. Add that test, after moca'sTestReRegisterRacingADroppedConnectionEndsBound(mocaremote-worker/internal/egress/control/rebind_test.go:68). RewriteTestServerRedialSupersedes(vmcontrol/server_test.go:276-307), which asserts the old supersede. Registerwith an emptysidisbad_request.
- A
- The request cap stays per session ID: two workers that register VMs of one session share one counter. A session is one user's budget, so that is right. Say so in a code comment.
- Audit events keep
vm_idalone. A worker field is moca's decision (D6 in #2042).
C. Shared mode
- Add
Config.SharedMode boolwithyaml:"-". It never comes from a file.cmd/cortexsets it when it starts a multi-tenant identity source. Today that is the moca driver (ctrlCfg.Socket != ""), and #2091 adds the demo driver. To set it beforeApplyPreset:- Move
resolveControlConfig(os.Getenv)(main.go:1103) above the firstbuildPipelines()call. - Set
c.SharedModeinsidebuildPipelinesbeforeApplyPreset(main.go:563), and insupervisorConfig(fallback.go:84-94). - set
forwardproxy.Server.SharedModefrom it before any listener serves.
- Move
- The core rule: with
Server.SharedMode, a request athandleConnectorserveOutboundwith no binding gets403 no_binding(pipeline.DenyStatus(403, "no_binding", "request did not arrive on a bound listener")throughhttpx.WriteRejection), with no session row, and nothing is dialed. That covers the TCP forward proxy.HandleTransparentConnandNewEgressHandlernever reach those functions, so shared mode must not start them (items 13 and 14), and a test checks that neither runs. - Presets under
SharedMode(inApplyPreset):- Set
listener.rolesto[forward]when it is empty. - Do not default
transparent_proxy_addr, so the transparent listener does not start. - Force the forward proxy, health, stats and session API addresses to loopback with
forceLocalhost, and passWithLoopbackOnly(true)to the stats server. Do not setBindLoopbackOnly, because it also turns on pprof, and a heap profile holds credentials. - Default
session.enabledto false when it is not set. That also turns off the session API, the archive and the cost ledger, which opens only with the store.
- Set
ValidateunderSharedModerefuses, each with an error that names the setting:transparent_proxy_addrset.praxis.enabled: true.session.enabled: true.- An explicit
reverserole. inference-routerin either pipeline.cost_ledger.enabled: trueorcost_ledger.dir.tls_bridge.generate_ca,spiffe.mirror_files, and any plugin config that names a file to write (litellm-budget-track'sspend_file, thescriptplugin's folders).
- Nothing is written to disk in shared mode, because moca's unit runs with
DynamicUser(moca-egress.service:51),ProtectSystem=strict(:63) andMemoryDenyWriteExecute(:76). Check it with the test below. - The built-in config of #2085 is not changed for this:
cmd/cortexsets the flag in code.
D. Docs
docs/framework-architecture.md: a short section onBinding,Callerand shared mode.core/listener/vmcontrol/CLAUDE.md: the hooks are gone, and the driver implementsBinding.
Not in scope
- Refusal formats (#2086). Until then,
no_bindinguses Cortex's JSON shape. - Credentials and interception (#2088). The demo driver (#2091). Audit for decrypted requests (#2089). Grants (#2090).
Tests
Use the existing helpers: newVMEgressStack, registerTCPVM, captureSink (awaitEvent, forVM) and sessionProbe (core/listener/vmcontrol/registry_test.go:43-154). They drive the real forward proxy over TCP stand-ins, so they run on macOS. plugintesting sets a test Identity (plugintesting.go:69).
- A test
Bindingon a plain request, a CONNECT and a decrypted request:Admitruns once for each, andpctx.Sessioncomes from itsCaller. A guest session header changes nothing. - A test
BindingwhoseAdmitreturns false: nothing after it runs, and nothing is dialed. - A test
BindingwithSubject: "alice": a plugin readspctx.Identity.Subject() == "alice", on a plain and on a decrypted request. TestBridgedRequestKeepsTheVMBindingand the request-cap tests pass with their fixtures updated, now throughAdmit. A refused over-cap request writes exactly one audit line (registry_test.go:806).- A WebSocket with a test binding: every turn's
pctx.Callerequals the handshake's. - Two control connections each register
vm-3with different sessions. Both listeners stay live, and each request gets its own session. Unregister{vm-3}on connection A leaves B'svm-3bound, and the other way round. Closing A leaves B's bindings.- The same connection registering
vm-3twice getsduplicate_vm. The new redial test passes, and the rewrittenTestServerRedialSupersedespasses. - Shared mode: a request on the TCP forward proxy with a forged session header gets
403 no_binding, and nothing is dialed. - Shared mode presets:
rolesdefaults to[forward], no transparent listener, loopback addresses, no pprof, no session store, no session API, no ledger. One table test for eachValidaterefusal. The supervisor's fallback config also gets loopback addresses. - Shared mode with a read-only working directory and
HOMEunset: the binary starts, serves a bound request, and stops cleanly. This test is incmd/cortex, Unix only, behindinclude_driver_moca, and drives a real control socket. - Every shipped profile without shared mode: no change (the existing suites pass).
Done when
TrustedSessionIDandAdoptBridgedRequestare gone.Binding.Admitis the only identity path.- Two VM workers on one host can use the same
vm_idwithout cutting each other off, in either direction. - In shared mode, no request without a binding reaches an upstream, and none of the listeners or stores listed above runs.
- All
vmcontrolandforwardproxytests pass for every shipped profile.
- 主要言語
- Go
- スター
- 31
- フォーク
- 49
- 平均マージ
- 9時間 43分
- マージ済み PR(30日)
- 367
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートなし
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
rossoctl/cortex のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
難易度 1/5 1時間未満 初心者へのやさしさ 82/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
メンテナーはふだん 1 日以内に返信
-
bug laptop
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
難易度 4/5 3〜5日 初心者へのやさしさ 55/100
メンテナーはふだん 1 日以内に返信
rossoctl/cortex の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
メンテナーはふだん 1 日以内に返信
-
taskmanager: a failed v1alpha1 backup leaves the partial backup behind対応中かも @arshil42 が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 80/100
ether/etherpad-go#571 ·
メンテナーはふだん 1 日以内に返信
-
labeler: read a limit above math.MaxInt as math.MaxInt in nonNegative (CodeQL alerts #20 and #21)オープンcost:approved factory:queued factory:tracking priority:p2 rank:12 ready-for-doing task:approved tokens:50k
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
sisaku-security/sisakulint#860 · コメント 2 件 ·