Skip to content

feat(egress): TLS interception and user-scoped credential injection in moca-egress (SBX0.2b phase 1) - #641

Merged
pdettori merged 9 commits into
mainfrom
feat/sbx-egress-proxy
Oct 28, 2026
Merged

pdettori merged 9 commits into
mainfrom
feat/sbx-egress-proxy

Conversation

@pdettori

Copy link
Copy Markdown
Member

What

This is chunk 3 of the SBX0.2b plan: moca-egress gains user-scoped credential injection for mocactl sbx microVMs. The design is spec docs/specs/2026-10-26-sbx-egress-credentials-design.md v1.2 §5 and §10.2, ADR-0046 phase 1. The control plane side (#630) is already on main. The branch is based on main @ ac4f3fd.

Nothing changes until you configure it. Without MOCA_EGRESS_CREDENTIALS_URL, the policy is NoCredentials and the behaviour is v0.8.0's: every existing unit test and all 15 existing conformance cases pass unchanged. If any of the other credential settings is set without the URL, boot is refused.

Changes

  • CredentialPolicy becomes a set lookup (credpolicy.go, handler.go).
    • The lookup runs after the allowlist and address checks.
    • A lookup error returns 503 credential_unavailable, with no dial and no tunnel.
    • A plain-HTTP request to a host that has a credential for that port returns 403 plaintext_credential.
    • A CONNECT is handed to the interceptor only when some element of the set matches its port.
  • Control-plane client (cpcreds.go). It sends POST /v1/egress/credential with this host's bearer. It does not follow redirects, uses Proxy: nil, and accepts plain http only for 127.0.0.1.
    • Cache: a TTL cache keyed by (sid, host), holding at most 4096 entries. TTLs are clamped to 5–300 s and to the earliest expiresAt. Both 404s are cached.
    • Single-flight: one request at a time per key. A failure is not cached, and it wakes every waiter so the next call retries.
    • Validation: the whole response is checked against the control plane's write-time grammar.
    • No values in logs: String/GoString print names only.
  • TLS interception (intercept.go, leafca.go).
    • Upstream first: before the proxy answers CONNECT, it verifies the upstream (system roots plus MOCA_EGRESS_UPSTREAM_CA, SNI set to the CONNECT host). On failure it answers 502 upstream_unverified and mints no leaf.
    • Leaves: the guest is served a per-host ECDSA P-256 leaf, valid 24 h. The guest's SNI and Host must equal the CONNECT host, or the answer is 421.
    • Header injection: the credential's headers are set, so they overwrite the guest's placeholder or are added if absent.
    • Choosing the credential, per request: same port, then the longest prefix on a / boundary.
    • Path-confusion guard: when a host is path-scoped, the raw request-target is refused 400 if it contains ./.. segments, \, ;, any %, // or #.
    • Revocation: checked per connection, before selection. A deleted /a returns 401 credential_revoked, never /'s token.
    • TRACE/TRACK: refused with 405. Without this, a reflecting upstream would echo the injected token back to the guest, which a security review found. Non-100 1xx responses are skipped.
    • Idle timeouts: Fix: bound moca-egress connections in time on CONNECT tunnels and the forward path #619's idle and response-header bounds apply to both TLS legs.
    • Audit: each request is audited with the credential name and sub, never a value.
  • Conformance suite. 14 new cases are appended after the existing 15. They are the spec's 13 plus trace_refused_on_intercepted_conn, and each is mutation-checked. The fake control plane speaks the merged wire.
    • doc.go now makes the deferred list part of the contract.
    • Failure messages never print credential values: there is a redaction self-test.
    • MI1 §12.3 points to the cases.

Tests

  • go test -race ./internal/egress/... ./egress/conformance/... ./cmd/moca-egress/... passes. Running TestIntercept* 15 times in a row shows no flakes.
  • The conformance binary passes 29/29.
  • go vet ./... and gofmt are clean.

Each task had an independent review. The interception core was reviewed on the most capable model. Two fix rounds closed real issues: TRACE reflecting the injected credential, and conformance failure messages that printed fixture tokens.

Known and accepted (recorded for the final review)

  • An upstream Set-Cookie minted from the injected token reaches the guest. That cookie is a derived credential. An upstream endpoint that echoes request headers is inherent to header injection. Both will be stated in the spec's risk section in the docs task.
  • Two conformance cases each wait about 5.5 s, because of the 5 s TTL floor.

Next is chunk 4, the snapshot CA, host CA and egress bundle, setup.sh/overlay, mocactl sbx credentials and the live smoke test.

Assisted-By: Claude Code

…efusals

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…2b phase 1)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…hosts

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ass non-100 1xx

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Fourteen cases appended to the public suite: the thirteen of SBX0.2b spec
10.2 plus trace_refused_on_intercepted_conn. The harness gains a fake
control plane, test CAs and a TLS upstream; existing cases run with
credentials off. doc.go moves the deferred list into the contract.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ten two cases

Failure messages and audit dumps carry names and counts, never values, with
a self-test. The SNI half of inner_host_mismatch_421 now requires a
successful CONNECT before the handshake refusal; the path-prefix case checks
its premise. doc.go states the forward and credential_revoked event contract.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 27, 2026

@cwiklik cwiklik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the three new core files in full (intercept.go, leafca.go, cpcreds.go) plus the modified handler.go / config.go / proxy.go / credpolicy.go, and cross-checked the control-plane side on main (egress-handlers.ts, egress-binding.ts, egress-destination.ts, egress-resolver.ts).

The shape of this is good: upstream-verify-before-200 with no leaf minted on failure, revocation before selection, the raw-target path guard only when the set is path-scoped, TTL clamped to the earliest expiresAt (with the TTLSeconds overflow guard), single-flight that does not cache errors and wakes every waiter, and String/GoString redaction on both Header and Credential. NewProxy's interceptor-required guard and event()'s Sub fallback are both right. I could not find a goroutine leak in upReader.

One blocking item, in validElement.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: Go (egress proxy, TLS interception, credential client), conformance suite, docs/spec cross-reference
Agent/IDE config (.claude/.vscode): none
Commits: 6, all signed off
CI status: all green (aggregate check still pending at review time)


Verdict rationale

Comment 1 is the only blocker. It is not reachable through today's control-plane writer, so there is a reasonable case for downgrading it to a suggestion — but the function's own doc and the PR description both claim parity with the control plane's write-time grammar, and that parity is what lets a reader stop worrying about the post-scrubHeaders injection order. Closing the gap is cheaper than relying on a cross-repo invariant that nothing local asserts.

Comments 2-5 are non-blocking.

Assisted-By: Claude Code

return fmt.Errorf("%d headers (want 1-%d)", n, maxHeaders)
}
for _, h := range e.Headers {
if h.Name == "" || strings.ContainsAny(h.Name, "\r\n\x00: \t") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix — validElement does not actually mirror the control plane's write-time header grammar.

The control plane enforces, in packages/control-plane/src/egress-binding.ts:

  • HEADER_RE = /^[A-Za-z0-9-]{1,64}$/ (lines 15, 78)
  • a REFUSED_HEADERS set: host, connection, content-length, transfer-encoding, te, trailer, upgrade, keep-alive, cookie, set-cookie (lines 16-27)
  • a ban on the proxy- and x-moca- prefixes (line 82)

Here the only rejections are CR/LF/NUL/:/space/tab in the name, and CR/LF/NUL in the value.

That matters because of injection order. In intercept.go, scrubHeaders(req.Header) runs at line 285, then the credential's headers are Set at lines 290-292 — after the scrub. So a control-plane element named Proxy-Remote-User or X-Moca-Subject would be written past the scrub and reach the upstream. That defeats the exact invariant forward.go:22-27 promises:

a guest's Proxy-Tenant or Proxy-Remote-User must not reach an upstream that might trust it, and the conformance contract (egress/conformance) promises the prefix

Same reasoning for Content-Length / Transfer-Encoding: Setting either one after req.Write has already computed framing is a request-smuggling shape.

None of this is reachable through the current CP writer. But this function's doc says it exists precisely so that "a bad stored value can never become a selection the proxy trusts," and the PR description states the whole response is "checked against the control plane's write-time grammar" — so the gap is between the code and its own stated contract, not just a theoretical path. Suggest mirroring HEADER_RE, the refused set, and the two prefixes here, ideally with a comment pointing at egress-binding.ts so the two stay linked.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7. validElement now enforces the same header-name rules as egress-binding.ts, with a comment linking the two files:

  • names must match ^[A-Za-z0-9-]{1,64}$;
  • the refused set is identical, character for character: host, connection, content-length, transfer-encoding, te, trailer, upgrade, keep-alive, cookie, set-cookie;
  • the proxy- and x-moca- prefixes are refused;
  • duplicate names are refused, case-insensitively.

Any violation fails the whole response as an uncached error, so a bad stored element can never be Set after the scrub. TestLookupRefusesCPRefusedHeaderNames is table-driven and also covers non-token names such as a/b.

stop()
ev.BytesUp = bytesUp.Load()
ev.Status, ev.Decision = http.StatusBadGateway, DecisionUpstreamUnreachable
ev.Credential = ""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — ev.Credential = "" drops the credential name from the audit on the upstream-failure path.

By the time this runs, req.Write(c.ubw) (line 351) has already sent the injected header upstream. So this is a request that did carry the token, audited without naming which credential it carried. ev.Decision already says upstream_unreachable, so the name is not misleading — and MI1 §12.3's "which requests carried credential X" query needs it.

Suggest keeping ev.Credential and letting Decision carry the failure. If the intent was "do not imply a successful injection," a distinct decision value would say that more precisely than erasing the name.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7. The upstream-failure path keeps ev.Credential, and Decision carries the failure (upstream_unreachable), so "which requests carried credential X" still answers. A test checks for an upstream that closes after reading the request: the event has both the name and the decision, and no value.

case u.Scheme == "https":
case u.Scheme == "http" && u.Hostname() == "127.0.0.1":
default:
return nil, errors.New("credentials URL must be https")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — the URL validation accepts forms that then get mangled by string concatenation.

This checks scheme and non-empty host, and line 120 builds the endpoint with strings.TrimRight(o.URL, "/") + "/v1/egress/credential". Two consequences:

  • https://cp/?x=1 → https://cp/?x=1/v1/egress/credential, i.e. the query string swallows the path and every POST goes to /.
  • https://user:pass@cp carries userinfo on every request, and Host() (line 338) deliberately strips it from the boot log — so the operator sees cp and has no signal that credentials are being presented in the URL.

Given that credentialsFromEnv goes out of its way to ensure "a half-configured host never runs silently without credentials," rejecting these at boot fits the same posture. Suggest refusing u.User != nil, u.RawQuery != "", u.Fragment != "", and a path other than ""/"/".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7. NewCPCredentials refuses userinfo, a query (including a bare ?), a fragment, and any path other than empty or /. Boot fails naming MOCA_EGRESS_CREDENTIALS_URL, and the message does not echo the URL. The endpoint is now built with u.JoinPath("v1", "egress", "credential") instead of string concatenation. Each refusal has a test.

if err != nil {
return nil, err
}
notAfter := now.Add(leafLifetime)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — two missing bounds on leaf minting.

1. notAfter is not clamped to the CA's own NotAfter. NewLeafCA validates CA-ness and key match but never checks validity dates, so a CA inside its last 24 h (or already expired) still mints 24 h leaves. The guest then fails the handshake with a chain error that points at the leaf rather than at the real cause. Clamping notAfter to ca.cert.NotAfter — and failing the mint outright once the CA is past it — turns a confusing runtime symptom into a clear one.

2. ca.cache is unbounded. It is the only unbounded map in the new code, and keyed by a host that originates from the guest's CONNECT. It is bounded in practice: handler.go only reaches the interceptor when forPort(set, port) is non-empty, and egress-destination.ts matches hosts exactly, so the key space is the owner's credential set. That is a cross-repo invariant, though, and each miss costs a P-256 keygen plus a CA signature. cpcreds.go already applies a maxCacheEntries bound for the same class of risk; the same treatment here would make the bound local and obvious.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7, both parts.

  1. NewLeafCA refuses a CA that is expired or not yet valid, naming the CA cert variable and never key material. Leaf notAfter is min(now+24h, ca.NotAfter). Once the CA has expired, Leaf returns an error instead of minting: the guest sees a failed handshake, audited as the new leaf_unavailable decision (listed in the conformance doc.go in 4e4cfd8).
  2. The leaf cache is capped at 1024 hosts and evicts the entry with the earliest notAfter, so the bound is local instead of resting on the cross-repo invariant.

// The upstream sees the checked target as Host, whatever the guest said.
req.Host = c.t.host
if c.t.port != 443 {
req.Host = net.JoinHostPort(c.t.host, itoa(int(c.t.port)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — two small things on this line and the helper it calls.

itoa (lines 476-488) reimplements strconv.Itoa and returns "" for any n <= 0 rather than failing. c.t.port is a uint16 that reached here through the allowlist so it cannot be 0 in practice, but strconv is already imported by package neighbours (allow.go) and carries no allocation penalty worth this.

Separately: the port != 443 guard means an IP-literal target on port 443 gets req.Host = c.t.host bare, which for IPv6 is an unbracketed Host: header. sniMatches (line 149) explicitly contemplates IP-literal targets, so the code is not assuming they cannot occur — the only thing preventing it is parseDestination in egress-destination.ts:22 refusing [ ("IPv6 literal hosts are not supported in phase 1"). Calling net.JoinHostPort unconditionally, or noting the cross-repo guard here, would keep this correct when phase 2 lifts that restriction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7. The hand-rolled itoa is gone in favour of strconv.Itoa. req.Host uses net.JoinHostPort when the port is not 443 or the host contains :, so an IPv6 literal is bracketed even on 443. A comment notes that the control plane's parseDestination refuses IPv6 in phase 1. There is no dedicated test, because an IPv6 destination cannot reach the proxy today.

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The interception path follows the spec's ordering, and I found no blockers. I checked these points by reading the code:

  • The allowlist and address checks run before the lookup; a lookup error gives 503 and nothing is dialled; plain HTTP gives 403.
  • Upstream TLS is verified (SNI = the CONNECT host) before the 200 is sent or a leaf is minted. ALPN is http/1.1 on both legs, and only origin-form HTTP/1.1 is accepted.
  • SNI and Host are checked (421). Upgrade headers are scrubbed and a 101 is never relayed. TRACE/TRACK are refused whatever their case.
  • Lookup runs per request (intercept.go:253), so revocation applies on keep-alive connections within one TTL.
  • The single-flight is detached from the caller's context, and failures wake every waiter.
  • Plain http is accepted only for Hostname()=="127.0.0.1". Redirects are not followed, and errors never include the response body.

Inline: 5 suggestions and 1 nit. The most important are the spec/code env-name drift (chunk 4 depends on it) and the header-name validation, which falls short of the write-time grammar the PR body claims.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: Go (egress proxy, interception, CP credential client, conformance), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 6 commits, all signed-off: yes
CI status: passing

}
if !t.IsZero() {
cred.ExpiresAt = t
if rem := t.Sub(now); rem < ttl {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Expired elements are accepted and injected. decode lowers ttl to t.Sub(now) but never drops an element whose expiresAt is already past, and Credential.ExpiresAt is not read anywhere else. Take an element that expired 2 s ago: ttl goes negative, so fly does not cache it, but the set is still returned and the expired header is injected. Every request to that host then costs a fresh control-plane round trip, which also bypasses the spec's 5 s floor (§4.2). Suggest dropping or refusing elements with expiresAt <= now + minTTL. This is latent in phase 1, where static credentials have a null expiresAt.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7. decode now drops any element whose expiresAt is before now + 5s (the §4.2 floor) before computing the TTL. The rest of the set stays. An all-dropped set becomes an empty set cached at the floor, so it can never be cached longer than 5 s, and nothing expired is ever injected. TestLookupDropsExpiredElements covers both cases. §5.1 documents the rule.

return fmt.Errorf("%d headers (want 1-%d)", n, maxHeaders)
}
for _, h := range e.Headers {
if h.Name == "" || strings.ContainsAny(h.Name, "\r\n\x00: \t") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The PR body says the response is checked against the control plane's write-time grammar, but spec §4.2 also bans hop-by-hop headers, Host, Cookie/Set-Cookie, Proxy-*, X-Moca-* and duplicate names. This check rejects only CR/LF/NUL/:/SP/HT, so names that are not tokens (e.g. a/b) also pass. Injection happens after scrubHeaders (intercept.go:285 then :291). So a bad stored element such as Connection: close, Proxy-Authorization or Cookie would reach the upstream, bypassing the proxy's own scrub. Suggest mirroring the name rules (RFC 9110 token plus the deny-list), so the defence-in-depth claim holds.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same fix as the thread above (e14b1c7). Header names now follow the control plane's grammar exactly: the [A-Za-z0-9-]{1,64} token, the refused set including hop-by-hop headers, Host, Cookie and Set-Cookie, the Proxy-*/X-Moca-* prefixes, and no duplicates. So Connection, Proxy-Authorization, Cookie and a/b can no longer reach the upstream through the post-scrub Set.

envIdleTimeout = "MOCA_EGRESS_IDLE_TIMEOUT_S"
envRespHeaderTime = "MOCA_EGRESS_RESPONSE_HEADER_TIMEOUT_S"
envCredURL = "MOCA_EGRESS_CREDENTIALS_URL"
envCredTokenFile = "MOCA_EGRESS_CREDENTIALS_TOKEN_FILE"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The env names differ from spec §5.3 (docs/specs/2026-10-26-sbx-egress-credentials-design.md:374-376). The code reads MOCA_EGRESS_CREDENTIALS_TOKEN_FILE, MOCA_EGRESS_CA_CERT_FILE and MOCA_EGRESS_CA_KEY_FILE, while the spec says MOCA_EGRESS_CREDENTIALS_TOKEN, MOCA_EGRESS_CA_CERT and MOCA_EGRESS_CA_KEY. The implicit $CREDENTIALS_DIRECTORY defaults (egress-token, egress-ca.crt, egress-ca.key, egress-api-ca.crt) are not in the spec either. Chunk 4 (setup.sh / unit LoadCredential=) will be written against one of the two, and a mismatch either fails boot or silently falls back to the directory default. Please update the spec table in this PR, or rename here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7 by updating the spec to match the code. §5.3 now lists MOCA_EGRESS_CREDENTIALS_TOKEN_FILE, MOCA_EGRESS_CA_CERT_FILE and MOCA_EGRESS_CA_KEY_FILE, with their $CREDENTIALS_DIRECTORY defaults (egress-token, egress-ca.crt, egress-ca.key), and egress-api-ca.crt for MOCA_EGRESS_CREDENTIALS_CA. The _FILE names say what they hold, and chunk 4's LoadCredential= lines will be written against this table.

Error string `json:"error"`
}
if json.Unmarshal(raw, &e) == nil && (e.Error == "no_credential" || e.Error == "sandbox_not_found") {
return nil, c.noneTTL, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Both 404s (no_credential and sandbox_not_found) are cached for a hard-wired 60 s noneTTL (set at :106). ConfigFromEnv doesn't expose it, and it ignores SH_EGRESS_CREDENTIAL_TTL_SECONDS. So even with a 5 s operator TTL, a newly added credential takes up to 60 s to start injecting. A lookup made before the control plane reports the sandbox ready would also pin "none" for a minute, and the guest would see confusing upstream 401s. Suggest having the 404 carry ttlSeconds (or using the floor for sandbox_not_found), and documenting the behaviour in §5.1.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7. The "none" TTL is now MOCA_EGRESS_NONE_TTL_S: default 60, range 5–300, parsed like the other *_S settings.

  • no_credential is cached for that value.
  • sandbox_not_found is cached only at the 5 s floor, so a sandbox that has just become ready is not pinned to "none" for a minute.
  • A 404 that carries a numeric ttlSeconds is honoured, clamped to [5, 300], so the client is forward-compatible if the control plane starts sending it.

TestLookupNoneTTLs and TestConfigNoneTTL cover this. §5.1 documents it, and the setting is in the conformance Env* constants.

scrubHeaders(req.Header)
// The guest only ever holds a placeholder: whatever it put in
// Authorization does not reach an intercepted upstream.
req.Header.Del("Authorization")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Authorization is deleted on every intercepted request, including ones no element covers. Spec §5.2 says an uncovered request is "forwarded without injection… with the guest's own headers scrubbed as on any other request", which reads as ordinary scrubbing. Example: a host whose only credential is /a is fully intercepted on :443, and a guest's own legitimate token on /b is silently stripped, so the upstream answers 401. Conformance case 10 (/other) sends no guest Authorization, so it can't tell the two readings apart. Either state this behaviour in the spec and pin it with a test, or only delete the header when an element matched.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7, following the spec. The unconditional Del("Authorization") is removed, so an uncovered request gets only ordinary scrubbing and the guest's own Authorization passes through. On a matched request the credential's headers are Set. Since ReadRequest and Set both canonicalize keys, a guest authorization is replaced, not duplicated. TestInterceptUncoveredKeepsGuestAuthorization pins the pass-through, and TestInterceptSelectsByPrefix's /docs expectation is updated. §5.2 now says this explicitly.

if err != nil {
return nil, err
}
notAfter := now.Add(leafLifetime)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: notAfter isn't capped at ca.cert.NotAfter. In the CA's last 24 h, leaves would outlive their issuer, and strict clients reject that chain. Suggest min(now.Add(leafLifetime), ca.cert.NotAfter).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e14b1c7: notAfter = min(now+24h, ca.cert.NotAfter), and minting is refused once the CA has expired. See the reply on the other leafca thread.

@pdettori
pdettori marked this pull request as ready for review October 27, 2026 19:15
…e-TTL, URL, leaf bounds

Mirror the control plane's header grammar, drop near-expiry elements,
make the none-answer TTL configurable (sandbox_not_found at the floor),
refuse userinfo/query/fragment/path in the credentials URL, keep the
credential in the audit line on upstream failure, bound leaf minting by
the CA's validity and the cache at 1024 hosts, let a guest's own
Authorization pass on uncovered requests, and align the spec env names.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori

Copy link
Copy Markdown
Member Author

All 11 inline comments are addressed in e14b1c7, plus 4e4cfd8, which lists the new leaf_unavailable decision in the conformance doc.go. Each thread has a reply. An independent re-review checked all items.

  • Blocker, header-grammar parity: validElement now enforces the same rules as egress-binding.ts: the token pattern, the refused set, the proxy-/x-moca- prefixes, and no duplicates. Any violation is an uncached error.
  • Expiry: elements expiring within the 5 s floor are dropped.
  • "None" TTL: it is configurable with MOCA_EGRESS_NONE_TTL_S. sandbox_not_found is cached only at the floor, and a 404 that carries ttlSeconds is honoured.
  • URL: userinfo, query, fragment and path are refused, and the endpoint is built with JoinPath.
  • Audit: the credential name is kept on an upstream failure after injection.
  • Leaf CA: an expired or not-yet-valid CA is refused, a leaf is capped at the CA's NotAfter, and the cache is bounded at 1024.
  • Host header: built with strconv.Itoa and JoinHostPort, so IPv6 is bracketed.
  • Guest Authorization on an uncovered request: it passes through, per spec §5.2.
  • Spec §5.1–§5.3: updated. The settings table now matches the code's *_FILE names and defaults.

go test -race passes across internal/egress, egress/conformance and cmd/moca-egress, and conformance passes 29/29. vet and gofmt are clean.

Assisted-By: Claude Code

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review at 4e4cfd8: e14b1c7 and 4e4cfd8 address all 11 open threads from the 9be5feb round, and I checked each fix against the code at the head. The header-name grammar now matches egress-binding.ts exactly (token regex, refused set, proxy-/x-moca- prefixes, duplicates). Expired elements are dropped at the 5 s floor. The spec §5.3 env table matches the code. The none TTL is configurable, and sandbox_not_found is cached at the floor. Uncovered requests keep the guest's Authorization, as documented in §5.2. The leaf CA validity window, notAfter cap and bounded cache are in place. The audit keeps the credential name on upstream_unreachable, and the URL shape is refused at boot. CI is all green.

One new suggestion inline: a side effect of the Authorization change on matched requests.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: Go (egress interception, CP credential client, leaf CA, config), conformance doc, spec
Agent/IDE config (.claude/.vscode): none
Commits: 2 new, all signed-off: yes
CI status: passing

}

scrubHeaders(req.Header)
// An uncovered request gets ordinary scrubbing only (spec 5.2), so the

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Dropping the unconditional Del("Authorization") changes matched requests as well as uncovered ones. If an element injects a header other than Authorization (e.g. X-Api-Key, or PRIVATE-TOKEN for GitLab), the guest's own Authorization, typically the image's moca-placeholder, now reaches the upstream next to the real credential. Some APIs reject a request carrying an invalid Authorization even when the API-key header is valid, and the spec's "the placeholder never reaches the upstream" (§5.2) no longer holds there. Suggest deleting Authorization only when matched and the element doesn't set it (or always on a match), with a test covering a non-Authorization element.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a423364. On a match, the guest's Authorization is now deleted before the element's headers are set, so a matched X-Api-Key or PRIVATE-TOKEN element no longer lets the placeholder through. An Authorization element is unaffected, because Set writes it right after the delete. An uncovered request still keeps the guest's own Authorization.

  • TestInterceptMatchedDropsGuestAuthorization: the element sets X-Api-Key, and the guest sends Authorization: Bearer moca-placeholder plus its own X-Api-Key. Upstream sees only the real X-Api-Key, and no Authorization.
  • Conformance credential_sets_every_header gains a second element that sets only X-Api-Key, and asserts that no Authorization reaches the upstream. The failure messages are redacted.
  • I checked the mutation: removing the delete fails both the unit test and the conformance case.
  • Spec §5.2 now states both halves.

Race tests, conformance (29/29), vet and gofmt are clean.

A matched element that sets a header other than Authorization (X-Api-Key,
PRIVATE-TOKEN) let the guest's placeholder Authorization reach the
upstream next to the real credential. Delete it on every match; an
uncovered request still keeps it (spec 5.2).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori dismissed cwiklik’s stale review October 28, 2026 01:35

all feedback addressed and verified

@pdettori
pdettori merged commit 1ef2af9 into main Oct 28, 2026
15 checks passed
@pdettori
pdettori deleted the feat/sbx-egress-proxy branch October 28, 2026 01:35
aslom added a commit to aslom/moca that referenced this pull request Oct 28, 2026
Two more undersized `need` values, and a test so the next one is found by CI
rather than by hand:

  internal/egress      len("/vm-1.sock")=10, but rossoctl#641 added "vm-quiet" -> 14
  egress/conformance   len("/c.sock")=7, but cases.go registers "vm-a" -> 10

The egress one is the instructive case. That need was CORRECT when written and
became wrong when an unrelated PR added a longer VM id, which is a failure mode
the hand-audit cannot be relied on to catch: `need` sits at the call site while
the names bound under it are hundreds of lines away, in another file, and grow
when someone adds a test. Four of fifteen call sites were undersized this way --
I got this wrong three times in a row, including once while explicitly auditing
for it.

So `callers_test.go` reads the module's own source, finds every shortdir.New /
Make need, and compares it against the longest socket name that scope binds. It
checks what the reviewer's original must-fix was really about: that the declared
margin matches the path the code actually binds.

Scoping is per-file with a package fallback, because both shapes occur: a
directory used by one test is bounded by that test (cmd/moca-egress's notify
dir only ever holds "/notify", so charging it the package maximum was a false
positive), while a helper in one file with names in another must use the whole
package -- and a file joining a VARIABLE id, as conformance.go does with
id+".sock", likewise cannot be bounded by its own literals.

Socket detection is a deliberately narrow name heuristic (.sock, .socket,
v.sock_<port>, and the one plain "notify"), not dataflow: these names reach bind
through locals, helper parameters and shell scripts, so following them properly
needs a type-checked SSA pass. The two errors are asymmetric -- a missed socket
costs one call site's coverage, while a regular file mistaken for a socket fails
correct code, which is how the first draft flagged vmpool's jailer-was-spawned
marker.

Verified against all four real bugs: each one reverted individually makes the
test fail, and the clean tree passes. An undersized need does not fail on a
short base like /tmp, which is why none of these showed up in CI and why the
test is source-level rather than a runtime assertion -- it reports every call
site at once instead of only the paths one run happens to take. It also floors
at 14 sites, so a refactor that breaks the scan fails loudly instead of passing
vacuously; the first draft silently scanned only internal/ because it walked
".." from internal/shortdir, and missed cmd/moca-egress entirely.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Aleksander Slominski <[email protected]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 16, 2026
Sixteen ADRs still said Proposed although their decisions are in code
on main. Each status line now names the merged PRs that implemented it
and the date the core landed (format of ADR-0042), and notes what is
still owed where only part is built:

- 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041)
- 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225)
- 0032 (rossoctl#249, rossoctl#350, as amended by MI1)
- 0035 (rossoctl#251; ADR-0048 adds lease mode beside it)
- 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481)
- 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620)
- 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed)
- 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed)
- 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the
  security review's lease sections are signed off)

The README index follows, and its 0033 row, which still said Proposed
after rossoctl#249 accepted the ADR, is corrected.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
pdettori added a commit that referenced this pull request Nov 16, 2026
Docs and agent-facing text that the code no longer matches, found by an
issue triage against main:

- The microVM guest and the SBX sandbox have no network device, but
  reach the hosts on moca-egress's allowlist through the host's proxy
  (P4.1 #581-#583; SBX egress #641/#646). Concepts, guides, P4-ON-P6,
  the VM README, research-smoke, hardening, maturity, the demo's limits,
  the SBX user guide and direct-client doc said "no network" outright.
  So did the sandbox MCP instructions, the tool descriptions and the
  sbx status text agents read, which made agents refuse allowlisted
  calls (#779).
- openapi.yaml said the worker enforces a turn's caps; nothing does
  yet (#391).
- harness-openapi.yaml called /turn and /runs "deliberately not
  described", while change-policy decision 3 makes them supported
  aliases (#507).
- The changelog is now the API changelog for both documents, with an
  index of the data-plane versions; both OpenAPI files point at it, and
  change-policy decision 5's follow-up is done (#511).
- upgrades.md and change-policy: the configRef ordering only matters
  from before v0.5.0 or for a bundle-format change (#512, #510).
- dispatch-archetypes and maturity: deploy/k8s's async drain is proven
  by its smoke claims (#688, #765).
- Specs: slice 3's relay restart is graceful since #462 (#453); MI1
  §2.2 gains a status note for the scrub (#350) and the vsock hop.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants