Skip to content

feat: MU1 control plane in the compose trial, with file and Vault credential stores (#348) - #364

Merged
pdettori merged 6 commits into
rossoctl:mainfrom
pdettori:fix/348-compose-control-plane
Sep 29, 2026
Merged

pdettori merged 6 commits into
rossoctl:mainfrom
pdettori:fix/348-compose-control-plane

Conversation

@pdettori

Copy link
Copy Markdown
Member

Summary

Fixes #348. The Docker Compose trial gets the MU1 control plane, so mocactl --control-plane-url http://127.0.0.1:8090 works with no other URL. That needed a credential store that doesn't depend on Kubernetes, so this also adds a file store (for compose) and a HashiCorp Vault store (for VM test, staging and production), selected by SH_CREDENTIAL_STORE.

Three commits:

  1. fix(turn-stream): a clean turn ends in done, not error. This bug predates Compose deployment: add a control plane so mocactl works (credential store without Kubernetes, MU1 auth wiring) #348, and this PR's live smoke found it.
    • executeTurn reports pi's normalized stop reason (stop, length, toolUse, error, aborted).
    • terminalFrame treated only the Anthropic wire's end_turn and max_tokens as clean. So every real turn that finished cleanly over SSE ended with an error frame, and mocactl run would show an error after every reply.
    • Every test fixture used end_turn, so no test caught it.
    • mocactl's sync-JSON fallback had the same check. Both are fixed and tested with pi's real values.
  2. feat(control-plane): file and Vault credential stores.
    • SH_CREDENTIAL_STORE picks the store:
      • kubernetes: the default, unchanged.
      • file: one 0600 file per subject, written atomically.
      • vault: KV v2 under check-and-set. Its policy needs no list capability. It takes VAULT_TOKEN, or a VAULT_TOKEN_FILE that is re-read on every request, for a Vault Agent sink.
    • An unknown value fails startup.
    • Every store keeps the existing invariants:
      • lookup by exact name, keyed on the subject's hash;
      • envelope encryption under SH_CREDENTIAL_KEK, with subject|name as the AAD;
      • a list that decrypts nothing.
    • The KEK-rotation logging is shared by all three stores.
    • Also: makeSigner accepts the signing key as one line of base64 PKCS#8 DER (for env files). src/genkeys.ts prints the four MU1 secrets, so a host needs no openssl.
  3. feat(deploy/compose): the control plane in compose.
    • A control-plane service, published on 127.0.0.1:${SH_CP_PORT:-8090}.
      • It uses the file store on the moca-credentials named volume.
      • SH_PUBLIC_HARNESS_URL follows SH_PORT, so discovery advertises the harness where the user reaches it.
      • It sits under a control-plane profile because it can't boot without SH_GITHUB_CLIENT_ID. Compose checks :? required variables even for services whose profile is off, so the control plane's secrets are passed through unrequired, and main.ts refuses to boot if one is missing.
    • The supervisor gets SH_SESSION_TOKEN_PUBLIC_KEYS, SH_CONTROL_PLANE_URL, SH_EXCHANGE_TOKEN and SH_REQUIRE_AUTH (default false), mirrored in deploy/vm/env/supervisor.env.example.
    • install.sh:
      • generates the four secrets with the harness image's own key generator (docker run --rm --network none … genkeys.ts);
      • writes them to .env from stdout only, never through an argv;
      • never replaces one on a re-run, because a new KEK would strand every stored credential;
      • refuses half a signing keypair, or garbled generator output, before writing anything;
      • turns the profile on when given SH_GITHUB_CLIENT_ID.
    • The operator-key fallback stays opt-in; .env documents how to enable it.
    • The Dockerfile creates /var/lib/moca/credentials owned by uid 1000, so a fresh named volume is writable.

Decisions (from #348's open items)

  • Login: a GitHub OAuth app with device flow enabled (option a). The README walks through registering one.
  • Credential store: an interface with backends. The file store is for dev and compose; Vault is for installs on a VM.
  • Operator fallback: opt-in only.

Operator impact

  • Existing Kubernetes deployments: no change. SH_CREDENTIAL_STORE defaults to kubernetes.
  • Existing compose installs: re-run install.sh. It adds the four MU1 secrets, and adds SH_GITHUB_CLIENT_ID plus the profile if you pass one. Without the profile the stack behaves as before, and plain curl /turn still works (SH_REQUIRE_AUTH=false).
  • The published :latest image gains genkeys.ts only after this merges (build.yaml republishes on merge). Until then, curl | sh needs SH_HARNESS_IMAGE pointing at a build of this branch.

Test plan

  • make typecheck
  • make test: all 11 vitest packages green, no unhandled errors.
    • control-plane: 375 tests.
    • A shared CredentialStore contract suite runs against both new stores. It covers exact-name lookup, isolation between subjects, what is at rest, list without the KEK, concurrent puts, delete, and KEK rotation. Store-specific tests cover a relabelled-ciphertext AAD attack, check-and-set races, and failure typing (503, not 500).
  • make test-deploy, including new cases in compose.test.sh, install.test.sh and images.test.sh.
  • make lint
  • Vault, live: test/vault-store.live.test.ts against a real hashicorp/vault:1.18 dev server (3/3), including two stores writing one subject concurrently. The soft-delete (404 with metadata) and check-and-set mismatch (400) response shapes were confirmed by hand.
  • Compose, live: COMPOSE_LIVE_SMOKE=1 SH_COMPOSE_BUILD=1 ./deploy/compose/smoke.sh passes 7/7 on the rebased branch. Its new claims:
    • the control plane is ready, and GET /v1/discovery advertises http://127.0.0.1:$SH_PORT;
    • an authenticated POST /v1/turn with Accept: text/event-stream streams text frames and a done frame, on the caller's own stored credential (credential → session → session token → exchange);
    • the stored credential survives docker compose down && up.
  • Not run: the real GitHub device-flow login, which needs an OAuth app. The smoke mints the api token inside the control-plane container instead. The manual mocactl login → doctor → run check is tracked in MU1 follow-ups from #348: VM control plane on Vault, dev identity provider, inference-credential binding #362.

Follow-ups

Tracked in #362:

  • a control plane on deploy/vm, backed by Vault;
  • an optional loopback-only development identity provider (needs its own ADR);
  • how a per-user inference credential is delivered: it is sent as Bearer, which fits gateway tokens but likely not a raw sk-ant-api key;
  • the manual acceptance run above.

🤖 Generated with Claude Code

… in done, not error (rossoctl#348)

executeTurn reports the last message's stopReason, which is pi's normalized
vocabulary (stop | length | toolUse | error | aborted). terminalFrame treated
only the Anthropic wire's end_turn/max_tokens as clean, so every real, cleanly
finished SSE turn ended in an `error` frame. Every fixture used end_turn, so
no test saw it. mocactl's sync-JSON fallback had the same check.

Found by rossoctl#348's live compose smoke (authenticated /v1/turn).

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

The control plane could only store credentials as Kubernetes Secrets through
kubectl. SH_CREDENTIAL_STORE now picks one of:

- kubernetes (default; unchanged)
- file: one 0600 file per subject, for the compose trial on a named volume
- vault: HashiCorp Vault KV v2, for VM test/staging/prod. It writes under
  check-and-set and needs no list capability in its policy. It accepts
  VAULT_TOKEN or a VAULT_TOKEN_FILE that is re-read per request, for a Vault
  Agent sink.

All three keep the store invariants: exact-name lookup by subject hash,
envelope encryption under SH_CREDENTIAL_KEK with subject|name as AAD, and a
list that decrypts nothing. The KEK-rotation logging is shared. A shared
contract suite runs against both new stores, and the Vault store also runs
against a real Vault 1.18 in a gated live test.

Also:
- makeSigner accepts the private key as one line of base64 PKCS#8 DER, for
  env files.
- src/genkeys.ts prints the four MU1 secrets, so a host needs no openssl.

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

- control-plane service under the control-plane profile, published on
  127.0.0.1:${SH_CP_PORT:-8090}. It uses the file credential store on the
  moca-credentials named volume, and SH_PUBLIC_HARNESS_URL tracks SH_PORT so
  mocactl needs one URL.
- The supervisor gets SH_SESSION_TOKEN_PUBLIC_KEYS, SH_CONTROL_PLANE_URL,
  SH_EXCHANGE_TOKEN and SH_REQUIRE_AUTH (default false). They are mirrored in
  deploy/vm/env/supervisor.env.example.
- install.sh generates the four MU1 secrets in the harness image (offline,
  stdout only, never argv) and never replaces one on a re-run. It refuses half
  a keypair and garbled generator output. SH_GITHUB_CLIENT_ID turns the
  profile on. The operator-key fallback stays opt-in.
- The Dockerfile creates /var/lib/moca/credentials owned by uid 1000, so a
  fresh named volume is writable.
- smoke.sh adds discovery, an authenticated /v1/turn streamed over SSE on a
  stored per-user credential, and credential survival across down && up.
- compose.test.sh, install.test.sh and images.test.sh cover the new service,
  settings and secrets.

Login uses a GitHub OAuth app (issue option a); a loopback dev IdP is left as
a follow-up.

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

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Solid PR: the three stores keep the existing guarantees and are well tested, including a live Vault run. The stop/length fix is real and now covered. The main suggestion is the first inline comment: the file and Vault stores should write back what they can't parse instead of deleting it on the next write. The second is an install regression for machines with docker-compose but no docker CLI. None of these block the merge.

The proto failure is unrelated: TestWaitForUnixSocketBackoffGrowsAndIsCapped in remote-worker/internal/vmpool counted 99 probes where it wants 120–400, and this PR touches no Go code. Re-running that job should clear it.

}
const out = emptyDocument();
for (const [name, entry] of Object.entries(raw.credentials)) {
if (!isRecord(entry) || typeof entry.sealed !== 'string') continue;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion — the file and Vault stores can delete data they don't recognize. parseDocument skips any entry it can't read, and rebuilds each descriptor with only the fields it knows. withCredential and withoutCredential then write that rebuilt document back. So the first put or delete for a subject permanently removes every skipped entry and every unknown descriptor field for that subject. The Kubernetes store only skips bad keys when reading, so it doesn't have this problem.

It matters most with Vault and several replicas: during a rolling upgrade or rollback, an older replica would erase any credential a newer one wrote.

Fix: write unrecognized entries back unchanged, and use the parsed form only for get and list. A test to match: write a malformed row, put an unrelated credential, and check the raw row is still there.

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 5d5e949. The subject document is now kept exactly as stored. parseDocument checks only the envelope (v: 1, a credentials object), and entries are parsed only to answer get and list. withCredential and withoutCredential change one named entry and carry everything else back untouched: unreadable rows, unknown descriptor fields and unknown top-level fields. A document with any v other than 1 is still refused for reads and writes, since this code can't know what a write would lose. The contract suite now has your test for both stores: it plants an unreadable row, an extra descriptor field and an extra top-level field, then puts and deletes an unrelated credential and checks all three are still at rest. It fails against the previous code for both the file and Vault stores.

Comment thread deploy/compose/install.sh
if [ -n "$have_priv" ] && [ -n "$have_kek" ] && [ -n "$have_xchg" ]; then
return 0
fi
command -v docker >/dev/null 2>&1 ||

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion — a fresh install now needs the docker CLI even without the control plane. ensure_mu1_secrets runs on every install, but detect_compose still accepts a machine with docker-compose and no docker. Those machines now fail with no SH_GITHUB_CLIENT_ID given, which isn't opt-in.

There's also a window after merge: install.sh on main updates immediately, but :latest gains genkeys.ts only once build.yaml republishes. During that window every curl | sh fails, not just control-plane installs.

Suggest generating the keys only when the control plane is wanted: run ensure_control_plane_profile first and skip when it leaves CONTROL_PLANE empty. A later re-run with a client id still fills them in, because the function is idempotent. install.test.sh's mock always supplies docker, so a docker-compose-only case would catch this.

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 632b9b0. ensure_control_plane_profile now runs first, and ensure_mu1_secrets runs only when the control plane will actually run. Without a client ID, nothing is generated and no docker CLI or genkeys.ts is needed, so plain installs are unaffected during the window before :latest is republished. A later re-run with a client ID fills the keys in. install.test.sh now covers a docker-compose-only machine both ways: it installs without a control plane, and with one it refuses (naming the docker CLI) before starting anything. It also checks that a no-client-ID install never runs the generator.

Comment thread deploy/compose/install.sh
CONTROL_PLANE=''
[ -n "$(env_file_value SH_GITHUB_CLIENT_ID "$env_file")" ] || return 0
CONTROL_PLANE=1
if ! grep -Eq '^COMPOSE_PROFILES=' "$env_file"; then

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion — the closing message can claim a control plane that isn't running. If .env already has a COMPOSE_PROFILES line without control-plane, the line is left alone, which is right. But CONTROL_PLANE=1 is still set, so line 254 prints "control plane: http://127.0.0.1:8090" when that profile never started. Either warn when the existing line doesn't include control-plane, or set CONTROL_PLANE from the line's contents.

The URL printed on line 254 is also hardcoded to 8090 and ignores SH_CP_PORT.

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 632b9b0. CONTROL_PLANE is now set from what COMPOSE_PROFILES actually enables (comma-separated, spaces tolerated). An operator's own line without control-plane gets a WARNING naming the fix; it isn't claimed in the closing message, and no keys are generated for it. Both URLs in the closing message now come from SH_PORT and SH_CP_PORT, with the caller's environment winning over .env as it does for compose. Tests cover a line without control-plane, a mine, control-plane list, and non-default ports.

Comment thread deploy/compose/smoke.sh Outdated
dc down >/dev/null 2>&1
dc up -d >/dev/null 2>&1
if wait_for 90 cp_ready; then
LISTED="$(curl -s -H @"$API_HDR" "$CP/v1/credentials" | jq -r '[.credentials[]?.name] | join(",")' 2>/dev/null || true)"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion — claim 7 doesn't prove a credential survives a restart. It only checks that the name still shows in GET /v1/credentials, and list never decrypts (the contract suite checks exactly that). The check would still pass if the KEK changed or the ciphertext were damaged, which are the failures that matter for "survives down && up". Running one authenticated turn after up, as claim 6 does, would exercise the stored secret.

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 632b9b0. Claim 7 now waits for the control plane, the worker pool and the sandbox after down && up, then runs a full authenticated turn: a new session (the old one went with Redis), its session token, and an SSE /v1/turn that must end in done. The exchange has to decrypt the stored credential and the gateway has to accept it, so a changed KEK or damaged ciphertext now fails the claim. Live run: 7/7.

Comment thread deploy/compose/docker-compose.yml Outdated
# control plane's PUBLIC keys and swaps them for the caller's credential over the exchange hop.
# A present-but-invalid token is refused even with SH_REQUIRE_AUTH=false (turn-auth.ts), so
# these must match the control plane's, which install.sh guarantees by generating both halves
# together. Passed only when .env sets them: without the control-plane profile they are inert.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: the comment says these are "passed only when .env sets them", but SH_CONTROL_PLANE_URL on line 99 is hardcoded. Also, install.sh now always writes the keys, so the supervisor always gets them. They're still harmless without the profile, since nothing can mint a token, but the comment no longer describes what happens.

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 632b9b0. The comment now says that the keyset and exchange token pass through only when .env sets them, which happens once the control plane is enabled; that SH_CONTROL_PLANE_URL is always the service address; and that without the profile all of it is inert.

if (direct) return () => direct;
if (file) {
const readToken = (): string => {
const t = readFileSync(file, 'utf8').trim();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: readFileSync of VAULT_TOKEN_FILE runs on every Vault request, which blocks Node while it reads. The file is tiny, so this is minor. The async readFile would do, since headers() already runs inside async code.

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 5d5e949. The per-request read is now an async readFile, and headers() is async. The startup check stays synchronous so a bad file still fails at boot with its name. Added a test: a token file emptied after startup fails that request as credential_unavailable.

Comment thread harness/src/turn-stream.ts Outdated
* Anthropic wire's (`end_turn`, `max_tokens` -- run-turn.ts's own default when there is no message).
* Matching only the wire's made every real, cleanly finished SSE turn end in an `error` frame.
*/
const CLEAN_STOP_REASONS = new Set(['stop', 'length', 'end_turn', 'max_tokens']);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: CLEAN_STOP_REASONS is also defined in packages/mocactl/src/api/harness.ts. That bug came from these two lists drifting apart, so either share one constant or add a test that checks the two sets match.

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.

Addressed in 1cdfc99 with the parity test. mocactl deliberately takes no workspace dependency (importing @sh/harness would pull pi into the client), so it keeps its own copy. test/harness.test.ts reads CLEAN_STOP_REASONS from harness/src/turn-stream.ts and asserts the two sets are equal. I checked it fails when either side drops an entry.

…ossoctl#364 review)

parseDocument rebuilt each subject document from the entries and fields
this version understood, and the write path persisted that rebuild. So the
first put or delete erased every row it had skipped. With several Vault
replicas, that means a rolling upgrade or rollback where an older replica
deletes credentials a newer one wrote.

The document is now kept as stored. Writes change one named entry and carry
the rest back untouched, and entries are parsed only for get and list. A
contract test plants an unreadable row, an unknown descriptor field and an
unknown top-level field. It fails on the old code for both stores.

Also: VAULT_TOKEN_FILE is read asynchronously per request (the startup check
stays synchronous), so a Vault request never blocks the event loop.

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

The stop-reason bug came from two lists drifting away from pi's vocabulary.
mocactl takes no workspace dependency, so it cannot import the harness's set.
A test reads it from harness/src/turn-stream.ts and asserts the two match; it
fails if either side drops an entry.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…st closing message (rossoctl#364 review)

- install.sh decides on the control plane first and generates the four
  secrets only when it will run. A docker-compose-only machine without the
  profile installs as before. Until :latest ships genkeys.ts, plain installs
  are unaffected.
- CONTROL_PLANE follows what COMPOSE_PROFILES actually enables. An
  operator's own line without control-plane is warned about and not claimed
  as running. The closing message prints SH_PORT and SH_CP_PORT instead of
  8080 and 8090.
- smoke.sh claim 7 runs an authenticated turn after down && up. The old
  list-only check never decrypted, so it would pass with a changed KEK or
  damaged ciphertext.
- The compose comment now matches what the supervisor receives.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit fc4fc57 into rossoctl:main Sep 29, 2026
13 checks passed
@pdettori
pdettori deleted the fix/348-compose-control-plane branch September 29, 2026 20:25
pdettori added a commit to pdettori/moca that referenced this pull request Sep 30, 2026
Mechanical rename per RA1 Phase 1 (spec §11): @sh/* -> @moca/*, the Go module
path's org+repo segment, ghcr.io image names, and Serverless Harness -> MOCA
in prose. Kubernetes/Knative/KEDA code is renamed in place, not removed or
deprecated -- that's a separate, later, still-gated phase.

Rebased onto rossoctl/main after PRs rossoctl#350 (MI1 S1 hardening) and rossoctl#364 (MU1
control plane in the compose trial) landed -- regenerated from scratch rather
than replaying old commits through the ~37 files those two PRs touched, since
several carry real functional changes, not just branding.

Includes fixes already found and verified in the first pass through this
rename (case-insensitive "serverless harness" leftovers, the mocactl layering
test's escaped-regex miss, buf codegen drift, the RA1 spec's own before/after
table + a new §0.9 amendment, and a handful of factual/historical-accuracy
corrections: a promote.ts comment, the out-of-scope personal-notes path, and
the still-unrenamed moca-experiments package name) -- applied directly this
time instead of being caught by a second review round.

Assisted-By: Claude Sonnet 5 <[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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compose deployment: add a control plane so mocactl works (credential store without Kubernetes, MU1 auth wiring)

2 participants