Skip to content

feat(deploy,control-plane): a Vault variant of the sbx credential store, and a measurable KEK rotation - #976

Merged
pdettori merged 4 commits into
mainfrom
feat/823-vault-credential-store
Nov 21, 2026
Merged

pdettori merged 4 commits into
mainfrom
feat/823-vault-credential-store

Conversation

@mrsabath

Copy link
Copy Markdown
Member

Summary

Wires Vault as the sbx credential store, and makes a KEK rotation's terminating condition
measurable. Refs #823.

The Vault store itself already existed (vault-store.ts, SH_CREDENTIAL_STORE=vault) and the sbx
egress path already accepted it — what was missing was a deploy template (configuration.md said so
outright: "no template wires it"), a documented rotation procedure, and a number an operator can
watch. No new backend, no change to the credential API or the envelope format.

What this does

1. A Vault variant of the egress-credentials Component.
SBX_CREDENTIAL_STORE=vault + SBX_VAULT_ADDR lists
ocp-sbx/egress-credentials-vault instead of the file one. Exactly one of the two is ever listed —
both set SH_CREDENTIAL_STORE, so listing both would leave the later one deciding.

  • The token is VAULT_TOKEN_FILE=/run/vault/token on an in-memory volume, re-read per request, so a
    Vault Agent sidecar can own login and renewal. Never a static VAULT_TOKEN (setting both refuses
    to start). The sidecar is deliberately not in the Component: its auth method is a per-deployment
    decision, and a half-configured one would crash-loop the pod.
  • The KEK stays in the sbx-egress Secret. Vault holds only ciphertext, so the key that opens it
    must not live there.
  • No PVC and no Recreate. That constraint came from an RWO volume; KV v2 check-and-set makes
    concurrent writers safe, so this lifts it. replicas stays at the base's 1 — the other
    single-replica assumptions are unchecked, and Vault alone does not settle them (Stand up Vault for secret management #823).

2. credential_nonprimary_kek_reads on GET /metrics.
openOrBlameSubject already logged every read that landed on a retired KEK; nothing counted them.
Re-sealing is write-driven (seal uses the primary key), so a credential nobody writes keeps the old
key, and the terminating condition for dropping a retired key is "this stopped moving" — which was
only observable by scraping logs. The log line still names which credential; the counter answers
whether any.

3. Docs. A KEK rotation procedure in the runbook (it had one for the signing key and the CA, but
not for the KEK — the one rotation #823 requires exercising), the minimum Vault policy, and the new
settings in the install reference.

Two things reviewers should look at

The NetworkPolicy gap is documented, not fixed — on purpose. The control plane's egress policy
allows port 443 to public addresses only; it excepts 10/8, 172.16/12, 192.168/16,
100.64/10, 169.254/16. An internal Vault is typically in one of those ranges and on 8200, so it
will be unreachable until a narrow egress rule for that address and port is added in the deployment's
own overlay. I did not add one: it names a host this repo does not know, and widening the policy to
"any private address, any port" to make a demo work would quietly undo the containment the policy
exists for. Flagged in the Component header and the runbook. This is upstream of every other
Vault task in #823.

The Vault policy needs three capabilities, not four.

path "secret/data/moca/credentials/*" {
  capabilities = ["create", "read", "update"]
}

No list (one object per subject, by hash, read by exact name — the property the store is built
around), and no delete: deleting a credential removes one entry from the subject's document and
writes it back, which is a check-and-set update. Granting delete would exceed what the code does.

What this does NOT close on #823

Deliberately. Getting a Vault to point at is the gating question that issue opens with, and it is
host-side:

  • Whether IBM Research already runs a Vault we can be a tenant of (ask before deploying anything)
  • Seal/unseal, auto-unseal, HA, backup, upgrade ownership
  • Applying the policy to a live server; the Vault Agent sidecar and its auth method
  • Running test/vault-store.live.test.ts against internal Vault as the acceptance check
  • Migrating off the file store and decommissioning it (both backends share subject-document.ts and
    the envelope, so this should be a re-upload of existing ciphertext, not a decrypt/re-encrypt —
    nothing in-tree performs it yet)
  • Raising the replica count against evidence; CA rotation; the blast-radius document

A KEK re-wrap tool was considered and dropped. envelope.ts states the design: because /v1
exposes no read-back path, "nobody — not even the control plane's own admin surface — can export and
re-seal", so rotation is prepend / let writes re-seal forward / drop. Building a re-wrap pass would
need subject enumeration, which all three backends forbid on purpose (the Vault policy omits list
so "a bug or an injection cannot enumerate users"; the test fake refuses LIST so a store that started
enumerating would fail), and the AAD is subject|name, so re-sealing needs the plaintext subject —
object names are one-way hashes. MembersStore.list() is not a substitute: it is optional
(SH_PROVENANCE_DIR) and tracks enrollment, not credential ownership, so a pass over it would miss
subjects and still report success.

ADR-0046

Amended in place, not superseded — the decision stands, the tree moved. Status left Proposed.
Two lines were stale: "Vault now: none is deployed", and the Recreate-until-Vault cost.

Testing

  • packages/control-plane: 1926 pass. The 5 failing suites (*-redis, turn-e2e) fail identically
    on clean main in my environment — ECONNREFUSED 127.0.0.1:6379, no Redis — and are untouched by
    this change. metrics-route.test.ts asserts the whole /metrics body, so the new counter broke it
    by design; updated, plus a case for the counter.
  • storeContract gains two cases (run against both the file and Vault stores): every read under a
    retired KEK is counted and not deduplicated, counting stops once re-sealed, and list — which
    decrypts nothing — does not count.
  • deploy/sbx/tests/overlay.test.sh: a third render asserting store=vault, no PVC, strategy not
    Recreate, VAULT_ADDR required while the rest are optional, the token sink writable and
    in-memory, no static token anywhere in the render, and the full projected source list.
  • deploy/sbx/tests/setup.test.sh: the vault Component chosen instead of the file one (and never
    both), the settings carried into sbx-settings under the names the control plane reads, unset
    optionals omitted, the KEK still generated into sbx-egress, file still the default, and the
    store settings refused when egress is off.
  • make check-links: 242 files, 0 broken.

Caveat, stated plainly: the deploy/sbx suites never completed in one pass in my sandbox. Two
assertions abort early there and both do so on untouched main as well — diff <(...) is blocked
(/dev/fd/63: Operation not permitted) and one SBX_MODES_ALLOWED regex assertion fails under the
local bash. I verified my blocks by bypassing those two lines locally (60 assertions, 0 failures),
but CI is the first clean end-to-end signal on setup.sh.

Checklist

  • Commits are signed off (git commit -s).
  • Tests for the touched packages pass (see Testing, including the stated caveat). make lint runs
    pre-commit, which is not available in my environment; prettier --check is clean on every
    file this touches.
  • Docs: the new environment variables are in docs/operate/sandbox-service/install.md and
    docs/reference/configuration.md; behaviour is in the runbook.
  • Docs: make check-links passes.
  • No new spec or ADR — ADR-0046 is amended in place, so no registry change.

…re, and a measurable KEK rotation

The Vault store has existed since MU1 (`SH_CREDENTIAL_STORE=vault`,
vault-store.ts) and the sbx egress path already accepts it, but no deploy
template wired it and configuration.md said so. `SBX_CREDENTIAL_STORE=vault`
with `SBX_VAULT_ADDR` now lists a second Component,
`ocp-sbx/egress-credentials-vault`, instead of the file one: the connection
settings come from sbx-settings, the token is a file a Vault Agent writes
(`VAULT_TOKEN_FILE`, re-read per request) rather than a static `VAULT_TOKEN`,
and the KEK stays in the sbx-egress Secret, because Vault holds only
ciphertext and the key that opens it must not live there. Exactly one of the
two Components is ever listed: both set `SH_CREDENTIAL_STORE`.

The variant renders no PVC and no `Recreate`. That constraint followed from an
RWO volume, and KV v2 check-and-set makes concurrent writers safe, so this
lifts it; `replicas` stays at the base's 1, because the other single-replica
assumptions are unchecked. The Component does NOT add an egress rule for
Vault: the control plane's NetworkPolicy allows 443 to public addresses only,
so an internal Vault needs a narrow rule in the deployment's own overlay --
widening it here to make a demo work would undo the containment it exists for.
That, and the private-CA case, are written down rather than papered over.

A KEK rotation is also now measurable. Re-sealing is write-driven: `seal` uses
the primary key, so a credential nobody writes keeps the old key, and dropping
a retired key is unrecoverable -- no API returns a stored secret, so nothing can
export and re-seal. The terminating condition is therefore "nothing has opened
under a non-primary key", which `openOrBlameSubject` already logged per read but
which no number reported. It now also increments
`credential_nonprimary_kek_reads` on `GET /metrics`, so an operator can watch it
reach zero without scraping logs. The runbook gains that procedure, which it had
for the signing key and the CA but not for the KEK -- prepend, watch, then drop --
plus the Vault policy (no `list`, and no `delete`: removing a credential is a
check-and-set `update`).

ADR-0046's "Vault now: none is deployed" and its `Recreate`-until-Vault line are
amended in place rather than superseded: the decision stands, the tree moved.

No new credential backend, no change to the credential API or the envelope
format. Standing up a Vault, its policy and token supply, and migrating the file
store remain open on the issue.

Refs #823

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
`EGRESS_STORE=file` reads as an attempt to assign the output of the `file`
command rather than the string, which shellcheck flags at -S warning and the
`lint` and `shellcheck` CI jobs both fail on (one cause: `make lint` runs
pre-commit, which runs shellcheck). Quoting both arms says what is meant.

No behaviour change: the values were already literal strings.

Refs #823

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
@mrsabath

Copy link
Copy Markdown
Member Author

a05d0ee fixes the one thing CI caught: shellcheck SC2209 at setup.sh:473 — EGRESS_STORE=file reads as assigning the output of the file command, so both arms are now quoted. No behaviour change; the values were already literal strings. lint and shellcheck were the same failure (make lint runs pre-commit, which runs shellcheck).

This retracts the caveat in the description. I had noted that the deploy/sbx suites never completed in one pass in my environment, so CI would be the first clean signal on setup.sh. It now is, and it is green: deploy-scripts (8m6s), deploy-scripts-bash32 and shellcheck all pass, so the new setup.sh and overlay assertions have run end-to-end somewhere that is not my sandbox. All 18 checks pass, including k8s-kind-e2e.

Worth noting the local gap was real and this is exactly what it hid: shellcheck and pre-commit are not available in my environment, so a warning-level lint error reached CI. The two bypasses I described (diff <(...), the SBX_MODES_ALLOWED regex) were genuinely environmental — both suites pass here untouched.

…s counter was unreadable

Review of #976 against the file variant and the control plane's own boot checks
found three defects that a green CI did not: the render and the lint pass, but
nothing in CI starts the pod.

The component omitted SH_EGRESS_HOSTS and SH_EGRESS_CREDENTIAL_TTL_SECONDS. Both
are wired by the file variant and by nothing else in the chain, so with the KEK
still projected the control plane hit egress-config.ts's "set both or neither"
and refused to BOOT -- a crash loop on the one configuration the component
exists to enable. Added, with a comment saying why they are not optional here.
The overlay test asserted the VAULT_* env in full and the absence of the
file-store keys, but never that the egress pair was PRESENT, so it confirmed
what was written rather than what the control plane reads; it now asserts
presence and diffs the two components' env names. Removing the keys again fails
it.

/metrics was harness-only, which was right while async_quota_refusals was the
only counter (structurally zero on sandbox, which runs no turns). It is wrong
for credential_nonprimary_kek_reads: the sandbox profile is the ONLY one that
runs a file or Vault credential store with egress credentials, so it is the only
profile where that counter can move -- and harness-only made it the one profile
that could not read it. The runbook's curl returned 404 on every deployment it
was written for. Now BOTH, still admin-only. route-profile.test.ts's shared-route
allow list earned its keep here: it caught the change and now records it.

The docs claimed an empty token sink makes the store answer "not answering"
(503). It does not: vault-store.ts reads the sink once, synchronously, at boot,
so with no Agent sidecar the pod fails to start with ENOENT. The runbook and the
component now say the component is not startable on its own and what to expect
on the first roll. Also noted that `read` is required for writes (check-and-set
names the version it read) and that the policy path must track
SBX_VAULT_KV_MOUNT/SBX_VAULT_PATH.

OpenAPI: the new counter was undocumented. openapi.yaml now declares it, with a
note on which counters can move under which profile, and the version goes to
1.35.0 with a changelog entry and the two change-policy references. Nothing
caught this because openapi-contract.test.ts checks routes, not response bodies.

setup.sh guarded the storage-class patch and its preflight on EGRESS_ON, so
SBX_CREDENTIAL_STORE=vault emitted a patch targeting a PVC the vault component
does not render. kustomize tolerates an unmatched target silently, so the class
was simply never applied; a file->vault migration also hit a spurious die about
a claim the run no longer manages. Both now test EGRESS_STORE, with coverage.

Test strength, from the same review: three assertions could not fail (two greps
for a VAULT_TOKEN form nothing emits, and a grep for the SH_CREDENTIAL_STORE key
name that never checked its value -- it would pass if the file component had been
listed). Replaced with value assertions. "does not count a list" asserted a
property of code it never exercised, since describeAll does not decrypt; it now
also reads the stale entry and counts it. Two comments cited
deploy/sbx/RUNBOOK.md and "RUNBOOK §7" after the docs moved; repointed.

Refs #823

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 21, 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.

The store wiring, the setup logic and the counter are sound; two deploy-side gaps block the deployment this PR exists to enable.

1. must-fix — the Vault Component never passes SH_EGRESS_HOSTS/TTL, so the control plane will not start

deploy/k8s/overlays/ocp-sbx/egress-credentials/patch-control-plane.yaml:18-23 is the only place that injects SH_EGRESS_HOSTS and SH_EGRESS_CREDENTIAL_TTL_SECONDS, and the new vault Component does not repeat them. That is a boot failure, not a degraded mode: egress-config.ts:46-53 treats egress as on iff SH_EGRESS_HOSTS and SH_CREDENTIAL_KEK are both set, and otherwise throws SH_EGRESS_HOSTS and SH_CREDENTIAL_KEK go together (egress credentials, SBX0.2b): set both or neither. In the vault stack the KEK is present — sbx-egress is projected into CREDENTIALS_DIRECTORY=/run/credentials, so withCredentials resolves it — so sandboxConfigFromEnv (main.ts:471) throws during startup and the pod CrashLoopBackOffs. If the KEK file were absent it would instead boot with egress silently off, which is the same feature not working.

Verified by rendering deploy/k8s/overlays/ocp-sbx + egress-credentials-vault with kubectl kustomize: the control-plane container has no SH_EGRESS_* env at all, while the same render with the file Component has both. See the inline comment on patch-control-plane.yaml:37.

2. must-fix — GET /metrics is not mounted on the sandbox profile, so the rotation procedure's step 2 returns 404

/metrics is declared profiles: HARNESS (routes.ts:126), and mountsOn unmounts it on sandbox. SBX0 renders SH_ROUTE_PROFILE=sandbox (deploy/k8s/overlays/ocp-sbx), and SBX_EGRESS_CREDENTIALS=1 — the only setting that produces non-primary KEK reads — is refused on combined (setup.sh:386), the other profile where the route mounts. So the counter is unreadable in every deployment where it can be non-zero, and the runbook's curl … /metrics tells the operator to scrape a 404. See the inline comment on runbook.md:517 for the two ways out (mount it on sandbox and update the route test, or say the number is unavailable on SBX0 and make the log line the procedure).

Suggestion

docs/api/openapi.yaml:1146 describes /metrics with only async_quota_refusals under counters. Adding an optional property is not breaking, but that file is the API as a product, and the runbook now tells operators to read .counters.credential_nonprimary_kek_reads. Please add it to the schema and decide the version convention there (1.34.0 → 1.35.0 with a change-policy line, as that document's history records each addition).

What I checked and found sound

  • Render: SH_CREDENTIAL_STORE=vault; VAULT_ADDR required from sbx-settings; mount/path/namespace optional; VAULT_TOKEN_FILE=/run/vault/token on a writable in-memory emptyDir; no PVC; no Recreate; sbx-egress still projected (the KEK stays out of Vault); automountServiceAccountToken: false; NetworkPolicy untouched. The secret: null + restated source list matches how the file and template-store Components replace the same volume, and the four sources and their keys are complete.
  • setup.sh: exactly one store Component is listed; file remains the default and the unchanged shape; vault requires an absolute http(s) SBX_VAULT_ADDR; the vault settings are refused with egress off and with store=file; optionals reach sbx-settings under the names the control plane reads and are omitted when unset; the KEK still lands in sbx-egress.
  • Counter: readCredential is the single read path for the file and Vault stores and calls openOrBlameSubject, so every decrypt is counted (the Kubernetes store calls it directly); list uses describeAll and decrypts nothing, so not counting it is right; the ring is newest-first and re-sealing is write-driven, so "this stopped moving" is the correct terminating condition; resetAsyncCounters driven by the ZERO key set cannot miss a counter added later.
  • Docs: the no-migration note for an existing PVC store, the three-capability policy (no list, no delete), the NetworkPolicy gap with NODE_EXTRA_CA_CERTS, and the ADR-0046 amendments all match the tree.

No .claude/ or .vscode/ changes; no injection content found; both commits signed off; all checks green at this head.

Assisted-By: Claude Code

# The path is this deployment's contract with whatever writes the sink; the Agent sidecar
# itself is not added here, because its auth method is a per-deployment decision
# (moca#823) and a half-configured sidecar would crash-loop the pod.
- { name: VAULT_TOKEN_FILE, value: /run/vault/token }

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. This env list never adds SH_EGRESS_HOSTS or SH_EGRESS_CREDENTIAL_TTL_SECONDS — the file Component (egress-credentials/patch-control-plane.yaml:18-23) is the only place that does — so the vault stack renders with SH_CREDENTIAL_STORE=vault and no egress hosts. That is a boot failure, not a degraded mode: egress-config.ts:46-53 treats egress as on iff SH_EGRESS_HOSTS and SH_CREDENTIAL_KEK are both set, and otherwise throws "SH_EGRESS_HOSTS and SH_CREDENTIAL_KEK go together (egress credentials, SBX0.2b): set both or neither". Here the KEK is present — sbx-egress is projected below into CREDENTIALS_DIRECTORY=/run/credentials, so withCredentials resolves it — so sandboxConfigFromEnv throws at startup and the pod CrashLoopBackOffs. (If the KEK file were absent it would instead boot with egress silently off, which is the same feature not working.)

I rendered ocp-sbx + this Component with kubectl kustomize: no SH_EGRESS_* env at all, where the file Component renders both. Please copy the two entries from the file Component — SH_EGRESS_HOSTS from sbx-settings, and the optional SH_EGRESS_CREDENTIAL_TTL_SECONDS (without it a non-default SBX_EGRESS_CREDENTIAL_TTL_SECONDS is silently ignored) — and assert both in the vault block of deploy/sbx/tests/overlay.test.sh, whose whole purpose is to catch an env or source dropped from this variant.

# 2. Watch for reads still landing on the retired key. Both signals are the same event:
kubectl logs deployment/moca-control-plane -n <namespace> | grep 'NON-PRIMARY KEK'
# -> names the subject hash and credential, i.e. WHICH credential is still stale
curl -sS -H @"$HDR" "$CP/metrics" | jq .counters.credential_nonprimary_kek_reads

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. GET /metrics is declared profiles: HARNESS (packages/control-plane/src/routes.ts:126), and mountsOn unmounts it on the sandbox profile, which is what SBX0 runs (deploy/k8s/overlays/ocp-sbx renders SH_ROUTE_PROFILE=sandbox). So this curl returns 404 on exactly the deployment this section is for: SBX_EGRESS_CREDENTIALS=1 only exists on the sandbox profile, and validate_profile refuses egress on combined (setup.sh:386), the other profile where the route mounts. The counter is therefore unreadable in every deployment where it can be non-zero.

Two ways out, either fine: add sandbox to the route's profile list — the comment's rationale, "the sandbox profile runs no turns, so the number is structurally zero", is true of async_quota_refusals but not of this counter — updating the harness profile only assertion in test/metrics-route.test.ts and that rationale comment; or say plainly in this section that the number is unavailable on SBX0 and make the NON-PRIMARY KEK log line the procedure. As written, the PR's second objective does not reach the deployment the PR wires.

Comment thread docs/operate/sandbox-service/runbook.md Outdated
# plausibly been rewritten -- a quiet counter across a full cycle of use, not a quiet hour -- drop
# the retired entry, leaving the new key alone:
kubectl patch secret sbx-egress -n <namespace> --type=merge \
-p "{\"data\":{\"SH_CREDENTIAL_KEK\":\"$(printf '%s' "$new" | base64 | tr -d '\n')\"}}"

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. $new is a variable from step 1's shell; these three blocks are copy-pasteable on their own, and in a fresh shell $new is empty, so this patches SH_CREDENTIAL_KEK to the empty string. The control plane then refuses to boot (SH_CREDENTIAL_KEK is not set) and the ring is gone from the Secret — so unless the operator still has the old value, every stored credential becomes unreadable. Worth one line: run steps 1–3 in the same shell, or print/save the new key before step 3, and consider re-reading the current value and refusing to patch when $new is empty.

});

/**
* The counter is what an operator watches to decide the retired key is unused (RUNBOOK §7), so

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. §7 of that runbook is "The janitor"; the new "Rotating the credential KEK" section above it is unnumbered. Either number the two new sections (which renumbers 7–14) or cite it by title/anchor (runbook.md#rotating-the-credential-kek).

@clawgenti clawgenti 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 Vault variant of the egress credential store, the credential_nonprimary_kek_reads counter, and the KEK rotation runbook. I read the diff against the code and ran both deploy suites on this head: they pass, and the claims in the PR body hold. No must-fix issues — one suggestion on the storage-class path the two components share, and one nit on a runbook cross-reference.

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Kustomize/Component, Shell (setup.sh), TypeScript (counters.ts, subject-document.ts), Tests (overlay, setup, vitest), Docs (ADR, install, runbook, configuration)
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (18/18, incl. deploy-scripts, deploy-scripts-bash32, shellcheck, check, lint, codeql)

Verified by:

  • bash deploy/sbx/tests/overlay.test.sh on this head: 22 ok, exit 0 — including the new vault render assertion (no PVC, no Recreate, VAULT_ADDR required, the token sink in-memory, the full projected source list).
  • bash deploy/sbx/tests/setup.test.sh on this head: exit 0, every block ok — including the four new vault blocks (component choice, settings, defaults, refusal with egress off).
  • kubectl kustomize (v5.8.1) over ocp-sbx + egress-credentials-vault: renders 24 objects, SH_CREDENTIAL_STORE=vault, no PVC, strategy left at the base's rolling update; positive control with the file component renders the PVC and applies the same SBX_STORAGE_CLASS patch, so the patch format is right.
  • Claim check on the counter: open is reached only through openOrBlameSubject (subject-document.ts:145 via readCredential, and k8s-secret-store.ts:239), so "every read that landed on a retired KEK is counted" holds for all three stores, and storeContract runs the new cases against the file and Vault stores.
  • The storage-class probe below, run in setup.test.sh's mock harness; the probe was appended to a scratch copy and removed afterwards (tree clean).

Not checked:

  • packages/control-plane vitest — not run here (no node_modules in this sandbox); CI's check leg is green on this exact SHA.
  • A live Vault — none available, so the store's 503-on-unreadable-token path was read, not exercised.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

Comment thread deploy/sbx/setup.sh
# and delete any PVC whose class must change (its contents do not
# survive). A claim class the cluster's default StorageClass filled in
# (no SBX_STORAGE_CLASS run applied it) is left alone with the knob unset.
# With SBX_CREDENTIAL_STORE=vault there is no egress credential PVC to

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 — this line is right ("with SBX_CREDENTIAL_STORE=vault there is no egress credential PVC to carry a class"), but two places further down still key on EGRESS_ON rather than on the store:

  • rendered_pvc_claims (setup.sh:762) prints moca-sbx-credentials whenever egress is on, so check_claim_class reads a claim this run does not render.
  • write_overlay emits the SBX_STORAGE_CLASS patch targeting that claim (setup.sh:1389), which the vault component does not render.

That contradicts the comment above rendered_pvc_claims ("a claim this run does not render is neither patched nor checked").

Concrete case, run in setup.test.sh's mock on this head — a PVC left behind by an earlier file-store run that applied a class (pvc_class moca-sbx-credentials old-class), then SBX_EGRESS_CREDENTIALS=1 SBX_CREDENTIAL_STORE=vault SBX_VAULT_ADDR=https://vault.invalid with SBX_STORAGE_CLASS unset:

PROBE: REFUSED -> setup.sh: PVC moca-sbx-credentials in moca-sbx-test carries storageClassName
'old-class' an earlier SBX_STORAGE_CLASS run set, and this run has SBX_STORAGE_CLASS unset: the
apply would remove the field ... Set SBX_STORAGE_CLASS=old-class

The apply would not remove the field: the vault render has no such claim. So the file→vault switch this PR documents is refused, with a message describing something that cannot happen, until the operator re-passes the class of a claim the deployment no longer uses. Setting the knob makes it pass, and a fresh namespace passes with the knob set too, so it is only the stale-claim case — but that is the case a switch is.

Suggested fix — gate both on the store:

[[ -z "$EGRESS_ON" || "$EGRESS_STORE" == vault ]] || printf 'moca-sbx-credentials\n'
...
if [[ -n "$EGRESS_ON" && "$EGRESS_STORE" != vault ]]; then
  printf '  - target: { kind: PersistentVolumeClaim, name: moca-sbx-credentials }\n ...'
fi

Worth taking now: switching an existing deployment is the operation the runbook's new section describes, and this is the one place the new store is not carried through.

Predicted side effect, for what it is worth: on kustomize v5.8.1 an unmatched patches: target is skipped silently, so the stale patch does not fail the render today — but the comment in write_overlay says a patch naming an absent PVC fails the build, so leaving it in makes that comment untrue for the vault path.

});

/**
* The counter is what an operator watches to decide the retired key is unused (RUNBOOK §7), so

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 — RUNBOOK §7 is "The janitor". The KEK rotation procedure this PR adds is an unnumbered section ("Rotating the credential KEK", inserted between §6 and §7) in docs/operate/sandbox-service/runbook.md, and deploy/sbx/RUNBOOK.md states that the numbers its scripts cite are that file's. An operator following this comment lands on the wrong section.

Suggested fix: name the section rather than numbering it, which also survives the next renumbering:

* The counter is what an operator watches to decide the retired key is unused (runbook.md,
* "Rotating the credential KEK"), so

@mrsabath

Copy link
Copy Markdown
Member Author

481ba3ec fixes three defects a review found against the file variant and the control plane's own boot checks. All three were invisible to CI, because nothing in CI starts the pod — the render passes, the lint passes, and the component still could not boot.

The component could not boot

It omitted SH_EGRESS_HOSTS and SH_EGRESS_CREDENTIAL_TTL_SECONDS. The file variant wires both, and nothing else in the chain does — not the base, not the sbx overlay, not the template-store component. With the KEK still projected from sbx-egress, the control plane hit egress-config.ts's "set both or neither" and refused to boot: CrashLoopBackOff on the one configuration this PR exists to enable.

The overlay test could not catch it. It asserted the VAULT_* env in full and the absence of the file-store keys, but never that the egress pair was present — it confirmed what the patch said rather than what the control plane reads. It now asserts presence and diffs the two components' env names. Removing the keys again fails it:

FAIL: the vault store does not read SH_EGRESS_HOSTS from sbx-settings:
      with the KEK mounted and no hosts, the control plane refuses to boot

/metrics was unreadable exactly where the counter moves

profiles: HARNESS → BOTH. Harness-only was right while async_quota_refusals was the only counter — it is structurally zero on sandbox, which runs no turns. It is wrong for credential_nonprimary_kek_reads: the sandbox profile is the only one that runs a file or Vault credential store with egress credentials, so it is the only profile where that counter can move, and harness-only made it the one profile that could not read it. The runbook's curl $CP/metrics returned 404 on every deployment it was written for, which undercut the counter's whole justification.

route-profile.test.ts's shared-route allow list did its job here — it caught the change rather than letting a route quietly appear on a second profile. The entry is now listed with its reason.

The 503 claim was false

The docs and the component comment both said an empty token sink makes the store answer "not answering" (503). vault-store.ts reads the sink once, synchronously, at boot, so with no Agent sidecar the pod fails to start with ENOENT — it never comes up to serve a 503. Both now say the component is not startable on its own and what to expect on the first roll after the switch.

Also

  • OpenAPI — the new counter was undocumented on a published surface. openapi.yaml now declares it (plus which counters can move under which profile), version 1.34.0 → 1.35.0, with a changelog entry and the two change-policy.md references the contract test enforces. Nothing caught this because openapi-contract.test.ts checks routes and operations, not response-body properties.
  • setup.sh — the storage-class patch and its preflight guarded on EGRESS_ON, so SBX_CREDENTIAL_STORE=vault emitted a patch targeting a PVC the vault component never renders. Worth being precise: kustomize tolerates an unmatched target silently (verified), which is worse than refusing — the class would simply never be applied. A file→vault migration also hit a spurious die about a claim the run no longer manages. Both now test EGRESS_STORE, with coverage that had been missing entirely.
  • Test strength — three assertions could not fail: two greps for a VAULT_TOKEN form nothing emits, and a grep for the SH_CREDENTIAL_STORE key name that never checked its value (it would have passed if the file component had been listed). Replaced with value assertions. does not count a list asserted a property of code it never exercised, since describeAll does not decrypt; it now also reads the stale entry and counts it.
  • Stale references — counters.ts and store-contract.ts cited deploy/sbx/RUNBOOK.md and "RUNBOOK §7" after the docs moved. Repointed.
  • Policy gaps — read is required for writes (check-and-set names the version it read, so create+update alone fails in a way that looks like a concurrency problem), and the policy path must track SBX_VAULT_KV_MOUNT/SBX_VAULT_PATH.

Verification

All 18 checks pass, including deploy-scripts (7m26s), deploy-scripts-bash32, check, lint, shellcheck, docs and k8s-kind-e2e. Locally: 1926 control-plane tests pass (the 5 failing suites need Redis and fail identically on clean main), deploy/sbx setup assertions 60 → 84, typecheck and doc links clean.

Still open, by design — read before merging

Two things this component deliberately does not do, and together they mean it cannot start a real deployment unaided:

  1. No Vault Agent sidecar. Its auth method is a per-deployment decision, so nothing writes /run/vault/token and the pod will not start until something does.
  2. No NetworkPolicy egress rule. The control plane allows 443 to public addresses only; an internal Vault is typically on a private address and port 8200.

Both are now documented rather than implied to work, but whether the PR should land in that state — or wait on the Vault-tenancy answer that gates #823 — is a reviewer's call, not something this PR settles.

…y the ring

Review finding on #976 (ingpaolodettori-dev, runbook.md:532). Step 3 took the
key to keep from `$new`, a variable set in step 1. The three blocks are
copy-pasteable on their own, so in a fresh shell `$new` is empty and the patch
wrote an EMPTY SH_CREDENTIAL_KEK: the control plane then refuses to boot
(`keksFromBase64`: "SH_CREDENTIAL_KEK is not set") and the ring is gone from the
Secret, so unless the operator still held the old value every stored credential
became unreadable. That is the exact loss the procedure exists to avoid, and
step 1 had the same exposure through `$old`.

Step 3 now derives the surviving key from the LIVE ring's first entry instead of
from a variable, so the steps are safe in separate shells. Both steps refuse
rather than patch when what they read is not what they expect: step 1 on an
absent KEK, step 3 unless the value is a ring with a non-empty first entry
(checked against "a,b", a single key, empty, and ",b"). `NS` is set once rather
than repeating a placeholder that is easy to half-substitute.

No key is echoed. The earlier draft printed the new KEK so step 3 could reuse
it; step 3 no longer needs it, and deploy/sbx/tests/setup.test.sh asserts "no
token or key reaches argv or the log" for setup.sh, so a procedure that put one
on a terminal and in shell history would contradict the convention it documents.
Both refusal messages are single-quoted literals naming no value; the keys reach
only `kubectl patch -p`, as in setup.sh.

Refs #823

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

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

Approving. The one suggestion left by the previous round is fixed properly, and the delta is docs-only (runbook.md, +24/-10). Four optional notes are inline.

The previous suggestion — fixed

Step 3 of the KEK rotation no longer reads $new from step 1's shell. It re-reads sbx-egress's live SH_CREDENTIAL_KEK, keeps ${ring%%,*}, and refuses unless the value is a ring with a non-empty first entry — so a fresh shell can no longer patch the KEK to "" and drop the ring. Step 1 also refuses when the Secret holds no KEK, and the new preamble says NS must be set first. Neither step echoes key material. The return 2>/dev/null || exit 1 idiom is correct both when the block is sourced and when it is pasted.

Nothing outside runbook.md changed (compare 481ba3ec...8e89b52), so the earlier verification of the Component, the route profile, the counter, the tests and the OpenAPI/CHANGELOG updates still stands.

Optional notes (inline)

  • runbook.md:543 (suggestion) — step 3 writes only primary, so it drops every entry after the first. A three-entry ring (step 1 run twice before step 3) passes the *,* guard and silently loses two keys — the unrecoverable case the section warns about. Guard the entry count or state that it drops all retired entries.
  • runbook.md:524 (nit) — the preamble says set NS first, but step 2 still uses -n <namespace>, and nothing refuses an empty $NS (kubectl then falls back to the default namespace). Use "$NS" and add one [[ -n "$NS" ]] guard.
  • setup.sh:1393 (nit, carried) — "it tolerates that silently" contradicts the block comment above it. I verified on kustomize v5.8.1 with this exact inline JSON-patch form: an unmatched patches: target is skipped and the build exits 0, so the inline sentence is right — please fix the older "fails the kustomize build" sentence instead.
  • egress-credentials-vault/patch-control-plane.yaml:49 (nit, carried) — "reads the sink ONCE, SYNCHRONOUSLY, at boot" contradicts "re-reads it on every request"; vaultTokenSource does both (readFileSync once, then readFile per request). Say "validates the sink at boot, then re-reads it per request".

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Docs (runbook delta in full); the rest of the PR was verified in the previous round at 481ba3ec and is unchanged
Agent/IDE config (.claude/.vscode): none
Commits: 4 commits, all signed-off: yes
CI status: 15/18 green, 3 pending at draft time (check, deploy-scripts, k8s-kind-e2e); all were green at 481ba3ec
Injection: none found in the PR title, body, diff, commits or comments.

Assisted-By: Claude Code

# from $new, so a fresh shell cannot write an empty key, and refused if the ring is not a ring.
ring="$(kubectl get secret sbx-egress -n "$NS" -o jsonpath='{.data.SH_CREDENTIAL_KEK}' | base64 -d)"
primary="${ring%%,*}"
[[ "$ring" == *,* && -n "$primary" ]] || # names no value: the ring is key material

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. This guard accepts any comma-separated value, but the patch below writes only primary (${ring%%,*}) — so every entry after the first is dropped, not just the retired one. A ring that already holds three keys (step 1 run twice before step 3, e.g. after an aborted rotation) passes *,* and silently loses two, which is the unrecoverable case this section opens with. Either refuse anything but exactly two entries ([[ "$ring" != *,*,* ]]), or say in the comment that this drops all retired entries and requires the operator to confirm the ring is two-key.


```bash
# 2. Watch for reads still landing on the retired key. Both signals are the same event:
kubectl logs deployment/moca-control-plane -n <namespace> | grep 'NON-PRIMARY KEK'

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. The new preamble says "Set NS first", but this step still uses -n <namespace>, and no step refuses an empty $NS. With NS unset, kubectl falls back to the default namespace: if a sbx-egress Secret happens to exist there, step 1's [[ -n "$old" ]] guard passes and the rotation is applied to the wrong deployment. Use "$NS" here too, and add one [[ -n "$NS" ]] || { echo 'refusing: set NS'; return 2>/dev/null || exit 1; } to the preamble.

Comment thread deploy/sbx/setup.sh
fi
if [[ -n "$EGRESS_ON" ]]; then
# Mirrors rendered_pvc_claims: the vault store renders no credential PVC, so emitting the patch
# would leave a target kustomize matches nothing for (it tolerates that silently, which is worse

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 — still open from the previous round. "it tolerates that silently" contradicts the block comment a dozen lines above, which says "a patch naming an absent PVC fails the kustomize build". I checked the actual behaviour with this exact inline JSON-patch form on kustomize v5.8.1 (the version bundled with the kubectl the e2e job uses): an unmatched patches: target is skipped and the build exits 0. So this sentence is the correct one — please fix the older sentence instead, so the guard is not described two contradictory ways.

# sidecar can log in (AppRole) and renew without the control plane holding a long-lived
# token or restarting. Setting both VAULT_TOKEN and VAULT_TOKEN_FILE refuses to start.
#
# THIS COMPONENT IS NOT STARTABLE ON ITS OWN. vault-store.ts reads the sink ONCE,

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 — still open from the previous round. "reads the sink ONCE, SYNCHRONOUSLY, at boot" contradicts the sentence above it ("re-reads it on every request"), and vaultTokenSource (vault-store.ts) does both: a synchronous readFileSync at startup to fail fast, then an async readFile per request. The operational claim (missing/empty → crash at boot, not 503) is right; say "validates the sink at boot, then re-reads it per request" so the two lines agree. The same wording appears in the runbook.

@pdettori
pdettori merged commit 49cce28 into main Nov 21, 2026
18 checks passed
@pdettori
pdettori deleted the feat/823-vault-credential-store branch November 21, 2026 14:33
@mrsabath

Copy link
Copy Markdown
Member Author

Grazie @ingpaolodettori-dev, and thanks @clawgenti — every finding is addressed. Both reviews landed on a05d0ee; 481ba3e (pushed just before your reviews) already carried the two must-fixes and the OpenAPI suggestion, and 8e89b52 fixes the rotation-safety finding, which is the one nobody else caught.

The finding that mattered most

runbook.md:532 — $new in step 3. This was the best catch in either review, and it is worse than a copy-paste annoyance: in a fresh shell $new is empty, so the patch wrote an empty SH_CREDENTIAL_KEK. The control plane then refuses to boot (keksFromBase64: "SH_CREDENTIAL_KEK is not set") and the ring is gone from the Secret — so unless the operator still held the old value, every stored credential became unreadable. That is precisely the loss the procedure exists to prevent. Step 1 had the same exposure through $old.

Fixed in 8e89b52: step 3 now takes the surviving key from the live ring's first entry rather than from a variable, so the steps are safe in separate shells. Both steps refuse instead of patching when what they read is not what they expect — step 1 on an absent KEK, step 3 unless the value is a ring with a non-empty first entry. Checked against a,b, a single key, empty, and ,b; only the first proceeds.

One deviation from your suggestion worth flagging: I did not print the new key. An earlier draft echoed it so step 3 could reuse it, but step 3 no longer needs it, and deploy/sbx/tests/setup.test.sh asserts "no token or key reaches argv or the log" for setup.sh — a procedure that put a KEK on a terminal and in shell history would contradict the convention it documents. Both refusal messages are single-quoted literals naming no value.

Already fixed in 481ba3e

  • must-fix 1, the missing SH_EGRESS_HOSTS/TTL. Your diagnosis is exactly right, including that the KEK is present via sbx-egress, so it is a boot failure rather than a degraded mode. Added both. The overlay test could not have caught it — it asserted the VAULT_* env in full and the absence of the file-store keys, but never that the egress pair was present, so it confirmed what the patch said rather than what the control plane reads. It now asserts presence and diffs the two components' env names; removing the keys again fails it.
  • must-fix 2, /metrics on profiles: HARNESS. Took your first option: BOTH, with the route test updated. route-profile.test.ts's shared-route allow list caught the change and now records it with the reason — that allow list earned its keep here.
  • The OpenAPI suggestion. Declared the counter, 1.34.0 → 1.35.0, changelog entry, and both change-policy.md references the contract test enforces. Also noted which counters can move under which profile. openapi-contract.test.ts checks routes and operations, not response bodies, which is why nothing caught it.
  • @clawgenti's EGRESS_ON vs the store. Both rendered_pvc_claims and the write_overlay patch now test EGRESS_STORE, with coverage that was missing entirely. One correction to the framing: kustomize tolerates an unmatched patch target silently (I verified), so this was not a failed render — the class would simply never have been applied, which is quieter and worse.
  • The RUNBOOK §7 nit (both of you): now cited by path and section title.

Also fixed from a self-review pass

  • The docs claimed an empty token sink makes the store answer 503. It does not: vault-store.ts reads the sink once, synchronously, at boot, so with no Agent sidecar the pod fails with ENOENT. The runbook and the component now say the component is not startable on its own.
  • Three test assertions could not fail (two greps for a VAULT_TOKEN form nothing emits; one grep for the SH_CREDENTIAL_STORE key name that never checked its value, so it would have passed if the file component had been listed). Replaced with value assertions.
  • does not count a list asserted a property of code it never exercised, since describeAll does not decrypt. It now also reads the stale entry and counts it.
  • Noted that Vault read is required for writes (check-and-set names the version it read), and that the policy path must track SBX_VAULT_KV_MOUNT/SBX_VAULT_PATH.

Worth saying plainly

Three of these were boot or data-loss failures that CI cannot catch, because nothing in CI starts the pod — the render and the lint pass either way. All 18 checks were green on the version that could not boot. Two of them were also cases where I had written a comment asserting the correct behaviour and not implemented it: the strategic-merge warning sat directly above the patch that forgot two env vars, and the "answers 503" claim sat directly above a readFileSync that fails at startup.

Still open by design

Unchanged by these fixes, and a reviewer's call rather than something this PR settles: there is no Vault Agent sidecar (its auth method is per-deployment) and no NetworkPolicy egress rule for an internal Vault on a private address. Together those mean the component cannot start a real deployment unaided. Both are now documented rather than implied to work — but whether this should land in that state or wait on the Vault-tenancy answer that gates #823 is worth your view.

webchang added a commit to webchang/moca that referenced this pull request Nov 22, 2026
57 commits past Moca v0.11.0 (rossoctl#953-rossoctl#976), among them rossoctl#959 (the member
routes write audit lines), rossoctl#960 (gate-image.py, Moca's general gate),
rossoctl#976 (the vault credential store, inert with egress credentials off)
and the lease-mode vmpool changes. No conflict; the fork-only set is
unchanged.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang pushed a commit to webchang/moca that referenced this pull request Nov 23, 2026
…not one

The four optional notes from the approving review of rossoctl#976
(ingpaolodettori-dev), the first of which is a data-loss bug introduced by that
PR's own safety fix.

Step 3 keeps `${ring%%,*}` and writes it as the whole value, so it drops
EVERY entry after the first, not just the retired one. A ring of three -- step 1
run twice before step 3 ever ran -- passed the "has a comma" guard and silently
discarded two keys at once, which is exactly the unrecoverable loss the section
warns about. It now requires EXACTLY TWO non-empty entries and refuses
otherwise, so a longer ring stops the operator instead of destroying keys, and
says to rotate one key at a time. Checked against "a,b" (proceeds), "a,b,c",
a single key, empty, ",b", "a," and "a,,b" (all refuse).

`NS` is guarded: unset, empty or the literal placeholder now refuses, because
kubectl otherwise falls back to the current context's default namespace -- the
wrong place to patch a Secret or read a ring from. Step 2's remaining
`-n <namespace>` uses "$NS" like the other two.

Two comments contradicted themselves, both written by rossoctl#976 and both carried in
that review:

- setup.sh:758 said the render "has no patch target" for a claim this run does
  not render, which reads as though that were a problem, while the block at 1393
  correctly says kustomize tolerates it. Verified on kustomize v5.8.1: an
  unmatched `patches:` target is skipped and the build exits 0, so the class is
  simply never applied rather than failing. Says that now.
- the vault component said "re-reads it on every request" and "reads the sink
  ONCE, SYNCHRONOUSLY, at boot" four lines apart. `vaultTokenSource` does both:
  it validates the sink once at boot (`readFileSync`) and re-reads it per
  request (`readFile`). Both the component and the runbook now say validate at
  boot, then re-read per request.

Refs rossoctl#823

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[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.

4 participants