feat: Add a connection Binding and shared mode, and key VM bindings by control connection

Đang mở
#2,087 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
8/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
go
Lĩnh vực
backend, security

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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_id alone, 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
  1. Add core/pipeline/caller.go with the contract above, and a field pctx.Caller *Caller (nil for a request with no binding). Set it where handleConnect and serveOutbound build their pipeline.Context, and copy it, with pctx.Identity, in newTurnContext (websocket.go:796-842), so every WebSocket turn keeps it.
  2. Admit at the two entry points. At the top of handleConnect and of serveOutbound, before anything reads the request: when BindingFrom(r.Context()) finds a binding, call Admit(w, r, host). host is r.URL.Hostname(), or the Host header's host for a CONNECT. For a decrypted request that is the tunnel's authority, because the bridged handler sets r.URL.Host first (bridging.go:346). When Admit returns false, return. When it returns a Caller with an empty SessionID, answer 500 binding_error (a driver bug). Otherwise store the Caller in the request context.
  3. Replace trustedSessionOf with a read of the stored Caller's SessionID, at all four sites (record.go:50, server.go:493, tunnel.go:144, tunnel.go:243). pctx.Session and SessionSourceConnection work exactly as today.
  4. Identity for plugins: when Caller.Subject is not empty, set pctx.Identity to an unexported adapter whose Subject() returns it, and whose ClientID() and Scopes() return empty values. It implements no other interface. The moca driver leaves Subject empty 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, SnapshotIdentity included.
  5. Decrypted requests: replace tl.connect with tl.binding pipeline.Binding, set in handleConnect from the CONNECT's context. In the bridged handler, put tl.binding into r's context with pipeline.WithBinding, next to the connProcKey copy. serveOutbound then admits it.
  6. Delete Server.TrustedSessionID, Server.AdoptBridgedRequest, trustedSessionOf, tl.connect, and the call at bridging.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
  1. vmBinding implements Binding:
    • Admit calls stripGuestHeaders(r) and chargeRequest(w, r, host) (unchanged, still moca's request_cap answer), and returns Caller{SessionID: b.sid}.
    • ServeHTTP keeps the live set, the aborted answer and the terminal audit line. It no longer strips or charges, and it stamps the binding with pipeline.WithBinding.
    • One line per request stays true. When Admit refuses (the cap), chargeRequest already wrote the request_cap line. Mark the request refused on vmcontrol's statusWriter (reached as w.(*statusWriter) in Admit), and let ServeHTTP skip emit for it. A decrypted request has no wrapper, so nothing changes there.
    • Delete SessionIDFromRequest, AdoptBridgedRequest and bindingCtxKey.
  2. Key bindings by (control connection, vm_id) in both vmcontrol.Server.bindings and vmcontrol.Registry.vms. The Handler interface gets the connection: Register(owner ConnKey, vmID, sid string, grant []byte, ln net.Listener) and Unregister(owner ConnKey, vmID string), with ConnKey an opaque value per control connection. Update recordingHandler in vmcontrol/server_test.go.
    • A Register for a vm_id that another connection holds creates a second binding. It no longer replaces the first one.
    • A Register for a vm_id that the same connection holds is still duplicate_vm.
    • Unregister{vm_id} removes only the sending connection's binding.
    • dropConn removes only that connection's bindings.
    • A worker that redials ends bound: its new connection's Register adds a binding, and the old connection's close removes only the old one. Add that test, after moca's TestReRegisterRacingADroppedConnectionEndsBound (moca remote-worker/internal/egress/control/rebind_test.go:68). Rewrite TestServerRedialSupersedes (vmcontrol/server_test.go:276-307), which asserts the old supersede.
    • Register with an empty sid is bad_request.
  3. 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.
  4. Audit events keep vm_id alone. A worker field is moca's decision (D6 in #2042).
C. Shared mode
  1. Add Config.SharedMode bool with yaml:"-". It never comes from a file. cmd/cortex sets 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 before ApplyPreset:
    • Move resolveControlConfig(os.Getenv) (main.go:1103) above the first buildPipelines() call.
    • Set c.SharedMode inside buildPipelines before ApplyPreset (main.go:563), and in supervisorConfig (fallback.go:84-94).
    • set forwardproxy.Server.SharedMode from it before any listener serves.
  2. The core rule: with Server.SharedMode, a request at handleConnect or serveOutbound with no binding gets 403 no_binding (pipeline.DenyStatus(403, "no_binding", "request did not arrive on a bound listener") through httpx.WriteRejection), with no session row, and nothing is dialed. That covers the TCP forward proxy. HandleTransparentConn and NewEgressHandler never reach those functions, so shared mode must not start them (items 13 and 14), and a test checks that neither runs.
  3. Presets under SharedMode (in ApplyPreset):
    • Set listener.roles to [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 pass WithLoopbackOnly(true) to the stats server. Do not set BindLoopbackOnly, because it also turns on pprof, and a heap profile holds credentials.
    • Default session.enabled to 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.
  4. Validate under SharedMode refuses, each with an error that names the setting:
    • transparent_proxy_addr set.
    • praxis.enabled: true.
    • session.enabled: true.
    • An explicit reverse role.
    • inference-router in either pipeline.
    • cost_ledger.enabled: true or cost_ledger.dir.
    • tls_bridge.generate_ca, spiffe.mirror_files, and any plugin config that names a file to write (litellm-budget-track's spend_file, the script plugin's folders).
  5. Nothing is written to disk in shared mode, because moca's unit runs with DynamicUser (moca-egress.service:51), ProtectSystem=strict (:63) and MemoryDenyWriteExecute (:76). Check it with the test below.
  6. The built-in config of #2085 is not changed for this: cmd/cortex sets the flag in code.
D. Docs
  1. docs/framework-architecture.md: a short section on Binding, Caller and shared mode. core/listener/vmcontrol/CLAUDE.md: the hooks are gone, and the driver implements Binding.

Not in scope

  • Refusal formats (#2086). Until then, no_binding uses 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 Binding on a plain request, a CONNECT and a decrypted request: Admit runs once for each, and pctx.Session comes from its Caller. A guest session header changes nothing.
  • A test Binding whose Admit returns false: nothing after it runs, and nothing is dialed.
  • A test Binding with Subject: "alice": a plugin reads pctx.Identity.Subject() == "alice", on a plain and on a decrypted request.
  • TestBridgedRequestKeepsTheVMBinding and the request-cap tests pass with their fixtures updated, now through Admit. A refused over-cap request writes exactly one audit line (registry_test.go:806).
  • A WebSocket with a test binding: every turn's pctx.Caller equals the handshake's.
  • Two control connections each register vm-3 with different sessions. Both listeners stay live, and each request gets its own session.
  • Unregister{vm-3} on connection A leaves B's vm-3 bound, and the other way round. Closing A leaves B's bindings.
  • The same connection registering vm-3 twice gets duplicate_vm. The new redial test passes, and the rewritten TestServerRedialSupersedes passes.
  • 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: roles defaults to [forward], no transparent listener, loopback addresses, no pprof, no session store, no session API, no ledger. One table test for each Validate refusal. The supervisor's fallback config also gets loopback addresses.
  • Shared mode with a read-only working directory and HOME unset: the binary starts, serves a bound request, and stops cleanly. This test is in cmd/cortex, Unix only, behind include_driver_moca, and drives a real control socket.
  • Every shipped profile without shared mode: no change (the existing suites pass).

Done when

  • TrustedSessionID and AdoptBridgedRequest are gone. Binding.Admit is the only identity path.
  • Two VM workers on one host can use the same vm_id without 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 vmcontrol and forwardproxy tests pass for every shipped profile.
Ngôn ngữ chính
Go
Star
31
Fork
49
Merge trung bình
9 giờ 43 phút
Pull request đã merge (30 ngày)
367

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của rossoctl/cortex

Tất cả issue của rossoctl/cortex

Issue tương tự

Thêm issue về Go

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.