Skip to content

feat(control-plane): user-scoped sandbox-egress credentials and the owner lookup (SBX0.2b phase 1) - #630

Merged
pdettori merged 6 commits into
mainfrom
feat/sbx-egress-cp
Oct 27, 2026
Merged

pdettori merged 6 commits into
mainfrom
feat/sbx-egress-cp

Conversation

@pdettori

Copy link
Copy Markdown
Member

Stacked on #627. Review only the commits after caf45b17: 702762a, 86a258f, d0d0118, 4cf3a05 and 1f89321.

What

This is chunk 2 of the SBX0.2b plan: the control plane for user-scoped egress credentials (spec docs/specs/2026-10-26-sbx-egress-credentials-design.md v1.2, ADR-0046, phase 1). No deployment change: all of it is inert until SH_EGRESS_HOSTS and SH_CREDENTIAL_KEK are both set. Setting only one of them fails startup.

  • Configuration (src/egress-config.ts).

    • SH_EGRESS_HOSTS is JSON [{id, workers}].
    • Each host has its own token, SH_EGRESS_TOKEN_<ID>, read as a systemd/K8s credential file.
    • SH_EGRESS_CREDENTIAL_TTL_SECONDS takes 5–300 and defaults to 60.
    • Startup refuses: an unknown worker, a worker listed under two hosts, a malformed or duplicate host token, or a bad KEK. Errors name the variable and never print a value.
    • When the feature is on, the sandbox profile wires the real CredentialStore (the file store on a PVC, with Vault later as configuration only).
  • Routes (src/routes.ts, server.ts). GET/PUT/DELETE /v1/credentials* are mounted on the sandbox profile only when the feature is on (RouteSpec.requiresEgress). With the feature off, they return the unknown-path 404. On the sandbox profile:

    • enrollment is required;
    • only the sandbox-egress consumer is accepted;
    • list shows only those credentials.

    The harness profile is unchanged.

  • Destinations and bindings (src/egress-destination.ts, src/egress-binding.ts).

    • Destinations are host[:port][/prefix], normalized and stored in the existing destination.hosts.
    • A binding is one binding or a list of 1–4.
    • A header format can use only {field} and {base64(a:b)}.
    • Headers that can't be set: hop-by-hop, Host, Cookie/Set-Cookie, Proxy-* and X-Moca-*.
    • An identical destination under another name returns 409 destination_conflict.
    • All three store read paths accept array bindings. The inference and control-plane consumers are untouched.
  • The lookup (POST /v1/egress/credential, src/egress-handlers.ts, src/egress-resolver.ts).

    • Auth is a new egress kind: the bearer is compared in constant time against every host's token.
    • Unknown, terminated and other-host sandboxes all return the same 404 sandbox_not_found.
    • An owner who is no longer enrolled gets no_credential.
    • The response is the owner's set for the host: {name, port, pathPrefix, headers[], expiresAt}, sorted by port, then by prefix length descending.
    • Values come through the resolver seam (staticResolver). ttlSeconds is capped by expiresAt, with a 5 s floor.
    • Audit lines are egress_credential_issued and egress_credential_none, and carry names only, never values.
  • New error codes:

    • no_credential 404
    • destination_ambiguous 500 (stored state from a write race)
    • destination_conflict 409
    • credential_unsafe 500

    docs/api/openapi.yaml is updated (path, schemas, the egress security scheme).

Tests

The @moca/control-plane vitest suite has 920 passed. Two suites, refresh-redis and sandbox-redis, need a live Redis and fail the same way at baseline in the local sandbox. CI has Redis. tsc --noEmit is clean.

The route-profile and authz enumeration tests cover the off and on route tables. The router tests use real buildHandler:

  • each host's token reaches only its own sandboxes;
  • a user API token and the janitor token both get 401.

Other tests cover secret-free errors, audit and logs, the TTL seam, and Vault/file/K8s round-trips of multi-header, host:8443/a descriptors.

Each task had an independent review. The follow-up commit fixed two real defects the reviews surfaced:

  • a duplicate host token is now refused at boot;
  • audit credential names are de-duplicated.

Next is chunk 3: moca-egress (lookup client, cache, interception, conformance cases).

🤖 Generated with Claude Code

@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 27, 2026

@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.

Summary

The control-plane half of SBX0.2b phase 1 (config, sandbox-profile credential routes, host[:port][/prefix] destinations, multi-header bindings, and the POST /v1/egress/credential owner lookup) is carefully built. It matches spec v1.2 §4.1–4.3 and is well tested. There is one must-fix: the destination_ambiguous fail-closed check can miss a duplicate (port, pathPrefix) when another prefix of the same length sorts between the two copies. There is also one suggestion: when egress is enabled, refuse at boot if the store would fall back to kubernetes.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane src + tests), OpenAPI
Agent/IDE config (.claude/.vscode): none
Commits: 5 commits (702762a..1f89321, on top of #627 @ caf45b1), all signed-off: yes
CI status: only DCO (pass) and k8s-kind-e2e (pending) ran. ci.yml triggers only on PRs to main, so the unit/typecheck suite has not run on this stacked head. Please get it run once the base becomes main.

Checked and fine: constant-time bearer comparison across all hosts with no early return; 404 sandbox_not_found used for unknown, terminated and other-host sandboxes alike; owner re-enrollment checked on every lookup; header refusal list and CR/LF/NUL refusal; secret-free errors and audit (names only); boot-time refusals in egress-config.ts (duplicate worker/token, TTL range); the harness profile's route table unchanged.

elements.sort(
(x, y) =>
x.port - y.port ||
y.pathPrefix.length - x.pathPrefix.length ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — the destination_ambiguous check only compares adjacent elements, but the sort only groups equal (port, pathPrefix) pairs together when no other prefix of the same length sorts between them. The name tiebreak can split them apart.

Repro with this exact comparator: elements a:/aa, b:/bb, c:/aa (all port 443) sort to a/aa, b/bb, c/aa. The adjacent-pair loop sees no duplicate, so both /aa credentials are returned and moca-egress resolves the tie by order. Spec §4.2 step 3 / MI1 §6.3 item 4 says this must never happen. The state can be reached through the PUT list→put race the spec calls out. The test at egress-handlers.test.ts:251 only covers the two-element case, so it passes.

Fix: tiebreak on the prefix string before the name, so equal pairs are always adjacent:

x.port - y.port ||
  y.pathPrefix.length - x.pathPrefix.length ||
  (x.pathPrefix < y.pathPrefix ? -1 : x.pathPrefix > y.pathPrefix ? 1 : 0) ||
  (x.name < y.name ? -1 : x.name > y.name ? 1 : 0)

You could also check with a Set of `${port} ${pathPrefix}` keys. Please add a three-element test with an interleaved same-length prefix.

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 dc18f98.

  • Detection no longer depends on the sort order. It uses a Set keyed on `${port} ${pathPrefix}`.
  • The sort is now fully deterministic: port, then prefix length descending, then the prefix string, then the name.
  • The new three-element test seeds a:/aa, b:/bb, c:/aa and expects destination_ambiguous. It failed on the old code. The two-element test is kept.

credentials: sandboxProfile ? new UnavailableCredentialStore() : credentialStoreFromEnv(env),
// The sandbox profile stores credentials only when egress is configured (SBX0.2b).
credentials:
sandboxProfile && !config.sandbox?.egress

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 — when egress is on, this calls credentialStoreFromEnv(env), which defaults to SH_CREDENTIAL_STORE=kubernetes. The ocp-sbx overlay deletes SH_CREDENTIAL_STORE, and the sandbox control plane has no Kubernetes API access (spec E5, automountServiceAccountToken: false). So a deployment that sets SH_EGRESS_HOSTS + KEK but forgets the store switch boots healthy, then fails every /v1/credentials call and every lookup at runtime. The rest of this feature refuses bad config at boot, so do the same here: on the sandbox profile, refuse kubernetes (or an unset store) when egress is configured, and name SH_CREDENTIAL_STORE=file|vault. Add a test next to sandbox-config.test.ts "wires the real credential store".

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 dc18f98. On the sandbox profile with egress configured, boot now fails when SH_CREDENTIAL_STORE is unset, empty or kubernetes, with the message SH_CREDENTIAL_STORE must be file or vault on the sandbox profile with egress credentials (it has no Kubernetes API access).

It cannot fire on the harness profile, or with egress off. Tests beside "wires the real credential store" cover:

  • unset, empty and kubernetes are refused;
  • file and vault are accepted.

The vault case only asserts that the refusal doesn't fire. No Vault call is made.

export const staticResolver: EgressResolver = async (owner, d, deps) => {
const stored = await deps.credentials.get(owner, d.name);
// Deleted between the list and this read: the owner has no such credential any more.
if (!stored) throw new CpError('no_credential', 'no credential for this destination');

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 — if a credential is deleted between list and this get, the whole lookup throws no_credential, even when the owner has other matching elements for the host. It also skips the egress_credential_none audit that the handler's own none() path writes. Consider omitting the element (the CONTRACT comment above already allows "omit") and letting the handler's empty-set path decide. Related: a credential with two entries for one host is decrypted once per element, so you could memoize per name within one lookup.

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.

Both done in dc18f98.

  • Omit instead of fail. staticResolver now returns null (omit) when get finds nothing, and the CONTRACT comment is updated. The handler skips omitted elements, so they never appear on the wire as null. If nothing is left, the handler takes its own empty-set path, which writes the egress_credential_none audit.
  • Decrypt once. A per-lookup Map, local to the handler with no module-level cache, decrypts each credential name once.
  • Tests:
    • the survivor is returned when one credential is deleted mid-flight;
    • all deleted gives no_credential plus the none audit;
    • a single get is made for one credential with two entries for the host.

@pdettori
pdettori force-pushed the feat/623-sbx-host-egress branch from caf45b1 to 86d8691 Compare October 27, 2026 14:43

@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.

Re-reviewed at 45bf12f. This is a pure rebase onto #627's new head 86d8691: git range-diff shows all 5 commits (c1a2153, 283d45e, 1d6fd67, fb4b203, 45bf12f) identical (=) to 702762a..1f89321. Nothing in the control-plane changed, and the three review threads have no replies yet. All items from the 1f89321 review are still open:

  • must-fix packages/control-plane/src/egress-handlers.ts:88. The destination_ambiguous check compares only adjacent elements after a port → prefix-length → name sort, so a:/aa, b:/bb, c:/aa slips past the check. Add a prefix-string tiebreak before the name (or check with a Set keyed on port pathPrefix), plus a three-element test.
  • suggestion packages/control-plane/src/main.ts:388. With egress on, the store defaults to kubernetes, which is unreachable on the sandbox profile (E5). Refuse it at boot and name SH_CREDENTIAL_STORE=file|vault.
  • nit packages/control-plane/src/egress-resolver.ts:31. A credential deleted between list and get fails the whole lookup with no_credential. Omit the element instead.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane), OpenAPI (incremental: none changed)
Agent/IDE config (.claude/.vscode): none
Commits: 5 commits, all signed-off: yes
CI status: DCO and k8s-kind-e2e pass. ci.yml (unit/typecheck/lint) has not run, because the base is still #627's branch, not main.

…re (SBX0.2b)

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

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

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…8s store with egress; omit mid-flight deletes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori changed the base branch from feat/623-sbx-host-egress to main October 27, 2026 15:32
@pdettori

Copy link
Copy Markdown
Member Author

All three points are addressed in dc18f98, with replies on each thread. A re-review checked each one and found no new breakage.

Rebase and CI. This PR is rebased onto main, since #627 has merged. Its base is now main, so ci.yml runs on this head.

Tests. @moca/control-plane passes 928. Locally, refresh-redis and sandbox-redis need a live Redis and fail as at baseline; CI has Redis. tsc and Prettier are clean.

@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.

Re-reviewed at dc18f98. The PR is now rebased onto main b374519 (#627 merged). git range-diff shows the 5 earlier commits are identical (=). The new commit dc18f98 closes all three items from our 1f89321/45bf12f reviews, and I verified each against the code:

  • must-fix (fixed), egress-handlers.ts. destination_ambiguous detection now uses a Set keyed on ${port} ${pathPrefix}, so it no longer depends on sort order. The sort is fully deterministic: port, then prefix length descending, then prefix string, then name. The new three-element a:/aa, b:/bb, c:/aa test covers the interleaved case, and the spec §10 test list is updated to match.
  • suggestion (fixed), main.ts. On the sandbox profile with egress configured, depsFromEnv refuses an unset, empty or kubernetes SH_CREDENTIAL_STORE at boot. Tests cover the refused values and file/vault.
  • nit (fixed), egress-resolver.ts. staticResolver returns null for a credential deleted mid-flight, and the handler omits that element. If nothing is left, it falls through to none(), which writes the egress_credential_none audit. The issued audit now names only the kept credentials. A per-lookup Map decrypts each credential once. Tests cover the survivor, all-vanished and single-get cases.

No new issues found in the incremental diff.

CI: ci.yml (unit/typecheck/lint) has not run on this head. The push happened while the base was still feat/623-sbx-host-egress, and ci.yml triggers only on pull_request: branches: [main]. The base change afterwards does not re-trigger it. Please push again, or close/reopen, so the full CI runs before merging. DCO and k8s-kind-e2e pass.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane), spec docs (incremental)
Agent/IDE config (.claude/.vscode): none
Commits: 6 commits, all signed-off: yes
CI status: DCO + k8s-kind-e2e pass; ci.yml not run on this head

@pdettori
pdettori marked this pull request as ready for review October 27, 2026 16:39
@pdettori
pdettori merged commit e7b5453 into main Oct 27, 2026
2 checks passed
@pdettori
pdettori deleted the feat/sbx-egress-cp branch October 27, 2026 16:39
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]>
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.

2 participants