Skip to content

feat(control-plane): enroll subjects and grant the admin role through the API - #762

Merged
webchang merged 35 commits into
rossoctl:mainfrom
webchang:pr/i16-enrollment
Nov 14, 2026
Merged

webchang merged 35 commits into
rossoctl:mainfrom
webchang:pr/i16-enrollment

Conversation

@webchang

@webchang webchang commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Closes #739. On main (906482c): #756 and #760, which this branch used to stack on, are merged. Its own change is the commits on top of main (the enrollment and roles API, its review fixes, and merges of main).

What it does: subjects are enrolled, and the admin role granted, through the API. The change is recorded, and roles are evaluated on every request. Three signed-off commits:

  1. The control plane:
  2. mocactl sbx admin subjects: list, enroll, unenroll, grant --until, revoke.
  3. An unenroll refuses a subject an admin grant keeps enrolled (409 admin_granted), plus the design's note that a members record is an attempted change.

Notes for review:

  • Who may change what. Any admin reads the list, but only an admin named in SH_ADMIN_SUBJECTS changes it. Subjects named in the settings can't be changed through the API (409 bootstrap_subject).
  • OIDC isn't verified end to end. mocactl sbx login on an OIDC deployment isn't verified here; the tests use oidc: subjects directly.
  • openapi 1.20.0 here, after main's 1.19.0. feat(control-plane,mocactl): admin quotas, and rejecting a registered build after the fact #786 renumbers after this merges.

Tests on the tip:

  • control plane: 1,271 passed, 3 skipped (with Redis);
  • mocactl admin, contract and cli: 97 of 97;
  • tsc is clean, and no shell script changes.

29 files, +1,896 / -37, counted against #760's tip.

Assisted-By: Claude Code

… the API

Who may use the sandbox service (SH_ALLOWED_SUBJECTS) and who is an admin
(SH_ADMIN_SUBJECTS) were settings only: every change was a setup.sh run, effective at
the subject's next refresh, and left no record.

With SH_PROVENANCE_DIR set, a members store (members.json beside the template catalog)
adds to those lists; the settings stay the bootstrap and are never edited by the API.

- GET /v1/subjects (any admin), PUT/DELETE /v1/subjects/{subject} and
  PUT/DELETE /v1/subjects/{subject}/roles/admin (an admin named in SH_ADMIN_SUBJECTS
  only; an API-granted admin gets 403), on both route profiles. A grant may carry
  `until` (epoch seconds) and lapses by itself.
- A settings subject cannot be unenrolled or revoked through the API
  (409 bootstrap_subject), and no admin revokes itself (409 self_revoke).
- Roles and enrollment are evaluated per request: the router replaces a verified
  token's roles with the subject's roles now, and the logins, the refresh and the
  egress owner check use the same evaluation (membershipNow). Without a store the
  token's claims stand, as before.
- Each change is a record on a new `members` provenance stream, with the new kinds
  `member` and `role` (an `expired` written once, by the first request that sees the
  lapse). provenance.ts and verify-provenance.py accept those kinds on that stream
  only.
- MEMBER_SUBJECT_RE in identity.ts: github:<id> or oidc:<sub>, built from the pattern
  the OIDC login verifies (rossoctl#701); never test:<n>.

API 1.5.0 (openapi, CHANGELOG), the design spec and the HTTP API reference.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…evoke

The client side of enrollment and roles through the API:

- `mocactl sbx admin subjects [--json]` lists every enrolled subject with its roles
  and where each comes from (env or api).
- `... enroll|unenroll SUBJECT`, `... grant SUBJECT [--until 30m|2h|1d|EPOCH]` and
  `... revoke SUBJECT`. Each change reads the subjects first, writes, then compares:
  it prints old -> new with the record written, and exits 1 loudly when the subject
  changed between its read and its write. A login issued for another control plane
  or issuer is refused before any write.

The RUNBOOK's enrollment section says what the API changes for an operator: the
settings stay the bootstrap, roles come from the store per request, and an access
review reads GET /v1/subjects and the members stream.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…e subject in

An admin is enrolled by its role, so `DELETE /v1/subjects/{subject}` on a subject holding a live
admin grant answered 200, wrote nothing, and changed nothing the subject could do. It now answers
`409 admin_granted` ("revoke the role first"), with nothing written; after the revoke the unenroll goes
through as before. openapi documents the code (no version change beyond this PR's 1.5.0).

The design's limits now say what a `members` record is: an attempted change, appended before the file
is replaced, so a failed write leaves a record for a change not in effect and a retry appends another
with the same body; members.json and GET /v1/subjects are the state. The RUNBOOK says to revoke
before unenrolling.

Tests: control plane passes with Redis, including the refusal (no record written) and the revoke-then-
unenroll path.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…andle

CodeQL's file-system race rule flagged MembersStore.doc(): it took the file's mtime with stat(path)
and then, when it had moved, read the file again by path, so a write landing between the two could
pair one version's mtime with another's bytes. doc() now opens the file once and takes both the mtime
(fh.stat) and, when it moved, the bytes (fh.readFile) from that handle; since the store replaces the
file by rename, the handle always holds the version whose mtime it reported. write() likewise takes
the new file's mtime from the temp file's own handle before the rename (which keeps it), not from a
later stat of the path. ENOENT at the open is still an empty store.

Tests: control plane passes with Redis (the members suite included).

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…o pr/i16-enrollment

No conflicts: the parent PR's branch, now merged with upstream main, brought in as one merge so the
stack carries the same main.

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

@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

Reviewed the PR's own three commits (members store, /v1/subjects routes, per-request roles, mocactl sbx admin subjects, the 409 admin_granted guard) on top of the stacked #756/#760 commits. The design holds up: roles are re-evaluated per request in server.ts, a token can never carry enrolled, and only settings admins can change membership. No must-fix issues. Two suggestions inline: a corrupt members.json locks out the settings admins too, and the unenroll guard runs outside the store's serial lock.

Verified on head: tsc --noEmit is clean; vitest run test/members.test.ts test/sandbox-handlers.test.ts test/route-profile.test.ts gives 55/55 passed; prettier is clean on the new files. A throwaway probe (deleted afterwards) wrote a truncated members.json and called membershipNow for a SH_ADMIN_SUBJECTS subject. With a valid file it returned {"roles":["admin"],"enrolled":false}. With the truncated file it threw Unexpected end of JSON input.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, mocactl), K8s/kustomize overlay, OpenAPI/docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 12 commits, all signed-off: yes
CI status: passing (all 17 checks green, DCO included)

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

if (!deps.members) return { roles: fallbackRoles, enrolled: false };
const nowS = seconds(deps);
return {
roles: await deps.members.rolesNow(subject, nowS),

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: A settings admin is locked out when members.json is unreadable.

membershipNow always goes through MembersStore.doc(), which JSON.parses the file (members.ts:101). rolesNow does short-circuit for bootstrap.admins (members.ts:165), but this line then calls storeEnrolled(), which reads the file anyway. So when the file fails to parse, every authenticated request throws, settings admins included. That covers login, refresh and the egress credential lookup too.

Probe on head: with a truncated members.json, membershipNow(deps, 'github:1' /* SH_ADMIN_SUBJECTS */, []) threw Unexpected end of JSON input. With the valid file it returned {"roles":["admin"],"enrolled":false}.

The writes are atomic (tmp + fsync + rename), so this needs outside damage, such as a hand edit or a disk problem. Still, the members-handlers doc promises that "the deployment can always recover", and today recovery means editing the volume by hand.

Suggested fix: for subjects in bootstrap.allowed or bootstrap.admins, answer from the settings before touching the store. For example, return { roles: [ADMIN], enrolled: false } without calling storeEnrolled. You could also log and fail closed for store-only subjects, rather than throwing for everyone.

const nowS = seconds(deps);
// An admin is enrolled whatever its enrollment says, so an unenroll that left a live admin
// grant in place would answer 200 and change nothing the subject can do: refuse it instead.
if ((await members.rolesNow(subject, nowS)).includes('admin'))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: The admin_granted guard runs before members.change() and outside its serial queue. A grantAdmin that lands between this check and the change can therefore still produce the state this commit set out to refuse: the unenroll returns 200, but the live admin grant keeps the subject enrolled.

The window is small, and both callers have to be settings admins, so this is not blocking.

Suggested fix: move the check inside the change callback, which reads the doc under the lock (doc.members[subject].roles with a live until), and throw admin_granted from there.

@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 authz model holds up:

  • Only SH_ADMIN_SUBJECTS admins change access, and an API-granted admin can't escalate (403).
  • Bootstrap admins can't be revoked, so no lockout is possible through the API. self_revoke is unreachable defence in depth.
  • Token roles are replaced per request, so a forged or stale admin claim no longer counts.
  • until is in seconds on both sides and lapses at the next request, with the expired record written once.
  • The grammar is case-sensitive, and test: and unknown prefixes are refused.

I checked the CodeQL fix in 927486f and it is correct. doc() now fstats and reads one open handle, and writes are tmp, then fsync, then atomic rename. The handle always reads the inode whose mtime it reported, so the check-then-read race is gone. In-process writes refresh the cache directly, so mtime granularity only matters for out-of-process edits. That is acceptable with the single-replica RWO/Recreate deployment, though comparing ino/size as well would be cheap hardening.

One must-fix: an enroll of a subject the settings already enroll writes a hidden store enrollment. That enrollment outlives removal from SH_ALLOWED_SUBJECTS, and it makes mocactl report a false race (exit 1). There are also two suggestions: bound until so a value in milliseconds can't become a permanent admin, and don't let an unreadable members.json 500 every request, bootstrap admins included.

Author: webchang (MEMBER, maintainer)
Areas reviewed: members store (members.ts), the five /v1/subjects routes on both profiles (member-handlers.ts, routes.ts), per-request role/enrollment evaluation (server.ts, handler-util.ts, login/refresh/egress), members provenance stream and both verifiers, subject grammar, mocactl sbx admin subjects, openapi/CHANGELOG/RUNBOOK/spec
Agent/IDE config: none
Commits: 4, all signed-off: yes
CI status: passing

throw new CpError('invalid_request', 'the body is {"enrolled": true}');
const nowS = seconds(deps);
const record = await members.change((doc) => {
const m = (doc.members[subject] ??= blank(subject, p.sub, nowS));

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: enrollSubject accepts a subject the settings already enroll (SH_ALLOWED_SUBJECTS, or an admin in SH_ADMIN_SUBJECTS). It then writes a store enrollment and a member record, and the CLI flags the result as a race.

  • Server side: for github:2 in SH_ALLOWED_SUBJECTS, doc.members[subject] is absent, blank() gives enrolled: false, so line 71 doesn't short-circuit. The handler writes enrolled: true to members.json and appends a member {enrolled: true, before: false} record.
  • Hidden in the list: list() reports that subject as source: 'env', so GET /v1/subjects gives no sign the store also enrolls it.
  • Access survives removal: later the operator removes github:2 from SH_ALLOWED_SUBJECTS with setup.sh to revoke access. storeEnrolled keeps it enrolled, and the review the RUNBOOK asks for (GET /v1/subjects before the change) never showed why.
  • False race in the CLI: mocactl sbx admin subjects enroll github:2 reads enrolled: true, so alreadyThere (commands.ts:449) says "already so". It then gets a non-null record and calls raced(), printing "changed by someone else" and exiting 1, although nobody else wrote. The same false race happens for a subject enrolled only by an API admin grant (list() folds roles.length > 0 into enrolled).

Fix: make enroll mirror unenroll. Either refuse a bootstrap subject with 409 bootstrap_subject or answer it as a no-op (record: null). In the CLI, compare against store enrollment, not the folded enrolled; for example, expose storeEnrolled/source per fact in the view. Add tests for both cases.

const subject = subjectParam(ctx);
const raw = asRecord(ctx.body).until;
const nowS = seconds(deps);
if (raw !== undefined && raw !== null && !(Number.isSafeInteger(raw) && (raw as number) > nowS))

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: until has a lower bound but no upper bound, so a value given in milliseconds is accepted and becomes a permanent admin.

Number.isSafeInteger(raw) && raw > nowS accepts 1731400000000 (a pasted Date.now(), or a JS client that forgot /1000). That until is roughly the year 56,800. The grant shows until as a number, so nobody notices, and a "temporary" admin, which the RUNBOOK recommends for exactly this, never lapses. parseUntil in mocactl has the same gap on its epoch branch.

Fix: refuse an until beyond a sane horizon, for example until <= nowS + 366*86400, or anything above about 1e11 (which can only be milliseconds), with invalid_request naming seconds. Apply the same bound in parseUntil, and add a test.

const nowS = seconds(deps);
return {
roles: await deps.members.rolesNow(subject, nowS),
enrolled: await deps.members.storeEnrolled(subject),

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: every authenticated request now depends on members.json being readable, including requests from the bootstrap admins, who are meant to be the recovery path.

membershipNow calls storeEnrolled() without the bootstrap short-circuit that rolesNow has. If members.json fails to parse (a hand edit on the volume, a truncated restore) or open fails (EIO, EMFILE), doc() throws. The router then answers 500 on every route, for SH_ADMIN_SUBJECTS as well, so nobody can use the API until someone fixes the file on the PVC.

Separately, each request does two open + fstat + close sequences (rolesNow, then storeEnrolled), not "one stat at most" as the class comment and spec §8 say.

Fix: read doc() once in membershipNow and derive both facts from it. Short-circuit bootstrap subjects (allowed or admin) before touching the file, so the settings still work with an unreadable store; keep fail-closed for everyone else. Then update the comment.

…nd the list shows the store's own enrollment

The review asked that enrolling a subject the settings already enroll (SH_ALLOWED_SUBJECTS or
SH_ADMIN_SUBJECTS) not write a store enrollment: hidden behind `source: env`, it kept the subject
enrolled after the settings dropped it, and mocactl reported a false race for it.

- PUT /v1/subjects/{subject} answers a settings subject unchanged (`record: null`) and writes
  nothing, as DELETE refuses it.
- Each Subject carries `storeEnrolled`, the store's own enrollment apart from the settings and any
  admin role; the list prints `enrolled (env, api too)` where both hold.
- mocactl compares an enroll or unenroll with `storeEnrolled`, not the folded `enrolled`, so a
  subject enrolled only by an API admin grant no longer reads as a race.
- openapi, CHANGELOG, the spec and the RUNBOOK say so; the RUNBOOK's access review checks
  `storeEnrolled` before a subject is removed from the settings.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…rs store's lock

The review asked that the `admin_granted` guard run inside the change, not before it: checked
outside the store's serial queue, a grant landing between the check and the change still let the
unenroll answer 200 while the live grant kept the subject enrolled. The check now reads the doc the
change edits, under the lock; a test starts a grant and an unenroll at once and gets 409.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… milliseconds are refused

The review asked for an upper bound on `until`: only a lower one was checked, so a value given in
milliseconds (a pasted Date.now()) was accepted as a date tens of thousands of years away, a
"temporary" admin that never lapses. The grant route now refuses an `until` more than 366 days
ahead with `400 invalid_request` naming seconds, and mocactl's `--until` applies the same bound to
a duration and to epoch seconds. openapi, CHANGELOG, the spec and the RUNBOOK say so; tests cover
milliseconds, the bound and one past it.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…ad, and keep the settings' subjects working when it fails

The review asked that the per-request evaluation not depend on members.json for the settings'
subjects, and that it read the store once. `membershipNow` called `rolesNow` and then
`storeEnrolled`, two open/fstat/close sequences, and the second had no bootstrap short-circuit: an
unparseable or unreadable file answered 500 on every route, for SH_ADMIN_SUBJECTS too.

`MembersStore.membershipNow` now answers both facts from one read. An admin named in the settings
is answered without reading the file; a subject on the allow list is answered from the settings,
with a warning, when the file can't be read; anyone else still fails closed. The class comment, the
spec's as-built section and the RUNBOOK say so; tests count the reads and truncate the file.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…e as well as its mtime

The review's summary suggested comparing `ino` and `size` as well as the mtime, as cheap hardening:
an out-of-process edit of members.json within the mtime's granularity would otherwise be missed.
The cache now keys on all three, read from the same handle as the bytes; a test rewrites the file
and restores its mtime.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… drop the unused enrolledNow

The settings-only fallback for an unreadable members.json warned on every request from an
allow-list subject. It now warns at most once a minute per process, on the request clock, and the
line carries the count of such answers since the last warning; a test with the injected clock
gives one line for many requests and, a minute later, a line with the count. The spec and the
RUNBOOK say so.

`MembersStore.enrolledNow` had no caller anywhere in the repository, tests included, and lacked the
bootstrap short-circuit that `membershipNow` now has: it is removed.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
@webchang

Copy link
Copy Markdown
Member Author

ingpaolodettori-dev, packages/control-plane/src/member-handlers.ts:70 (must-fix)

"enrollSubject accepts a subject the settings already enroll ... It then writes a store enrollment and a member record, and the CLI flags the result as a race."

Fixed in d00cf29. PUT /v1/subjects/{subject} now answers a subject in SH_ALLOWED_SUBJECTS or SH_ADMIN_SUBJECTS unchanged (record: null) and writes nothing, so it no longer leaves a store enrollment behind that outlives removal from the settings. Each Subject also carries a new storeEnrolled field: the store's own enrollment, kept apart from the settings and any admin role. The list prints enrolled (env, api too) where both hold, so an enrollment written earlier is no longer hidden. mocactl compares enroll and unenroll against storeEnrolled, not the folded enrolled, so a subject enrolled only by an API admin grant no longer reads as a race. openapi, CHANGELOG, the spec (§4, §8) and the RUNBOOK are updated. The RUNBOOK's access review now checks storeEnrolled before a subject is removed from the settings. Tests: answers an enroll of a settings subject unchanged, and writes no store enrollment and shows the store enrollment apart from an admin role (storeEnrolled) (control-plane), and compares an enroll with the store enrollment, not the folded one (no false race) (mocactl).

ingpaolodettori-dev, packages/control-plane/src/member-handlers.ts:118 (suggestion)

"until has a lower bound but no upper bound, so a value given in milliseconds is accepted and becomes a permanent admin."

Fixed in c16317c. The grant route refuses an until more than 366 days ahead with 400 invalid_request, and the message names seconds (not milliseconds). The bound is MAX_GRANT_SECONDS in members.ts. mocactl's parseUntil applies the same bound to both a duration and epoch seconds. openapi, CHANGELOG, the spec and the RUNBOOK are updated. Tests: refuses an until that is not a future whole number of seconds within 366 days (it covers milliseconds, the bound itself and one past it) and parseUntil (mocactl).

ingpaolodettori-dev, packages/control-plane/src/handler-util.ts:61 (suggestion)

"every authenticated request now depends on members.json being readable, including requests from the bootstrap admins, who are meant to be the recovery path."

Fixed in daf2f0c. A new MembersStore.membershipNow reads the store once and derives both the roles and the store enrollment from that one read. A subject in SH_ADMIN_SUBJECTS is answered without touching the file. A subject in SH_ALLOWED_SUBJECTS is answered from the settings alone, with a warning logged, when the file can't be read: no API role and no store enrollment count until the file is fixed. Everyone else still fails closed. ddc5aad rate-limits that warning to at most once a minute per process: the line carries the count of settings-only answers since the last warning, so a damaged file can't flood the log. The class comment, the spec's §8 and the RUNBOOK now describe one open and fstat per request (none for a settings admin) in place of "one stat at most". Tests: reads the store once per request, and not at all for a settings admin and still answers the settings' subjects when members.json can't be read; others fail closed. The second test also covers the rate limit with the injected clock: many requests give one line, and a minute later the next line carries the count.

From the review summary: following the ino/size hardening suggestion, f77cfa2 keys the cache on the file's inode, size and mtime, all from the handle that reads the bytes. Test: sees an out-of-process edit that keeps the mtime (the cache keys on inode and size too). ddc5aad also removes MembersStore.enrolledNow: nothing in the repository called it, tests included, and it lacked the bootstrap short-circuit membershipNow now has.

clawgenti, packages/control-plane/src/handler-util.ts:60 (suggestion)

"A settings admin is locked out when members.json is unreadable."

Fixed in daf2f0c, as in the thread above: settings admins skip the file, and allow-list subjects fall back to the settings when it can't be read.

clawgenti, packages/control-plane/src/member-handlers.ts:94 (suggestion)

"The admin_granted guard runs before members.change() and outside its serial queue."

Fixed in e65f32d. The check now runs inside the change callback, on the doc the change edits under the store's serial lock: a live admin grant (no until, or an until still ahead) throws admin_granted. Test: refuses admin_granted under the store lock, for a grant that lands just before starts a grant and an unenroll at once and gets 409. It fails on the old code.

github-advanced-security, packages/control-plane/src/members.ts:95 (resolved, outdated)

Still holds on the new tip: doc() fstats and reads one open handle, and the cache key change in f77cfa2 reads the inode and size from that same handle.

New tip: ddc5aad

Assisted-By: Claude Code

@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

This PR adds a members store (members.json) and the /v1/subjects admin routes for enroll, unenroll and the admin grant with until, and records every change on a members provenance stream. It is stacked on the provenance chain and template-catalog work. Authorization, the until bound, write-once and verifier parity all check out. There are two must-fixes:

  1. MembersStore.doc() returns the shared this.cache, not the doc the call actually read. A concurrent reader can roll back the cache, and the next change() then writes over newer changes. One effect: a revoked admin grant comes back on disk. Reproduced with real stores, details inline.
  2. redact-provenance.py deletes records that the rewritten chain still references whenever a redaction leaves bytes unchanged. After that, ProvenanceStore.chain() throws "record … is missing".

The rest are a suggestion (a provenance failure turns a successful create into a 500 and stops the janitor) and a docs nit.

CodeQL (1 high, test/members.test.ts:399): this looks like a false positive. The stat-then-write in that test is deliberate: it simulates an out-of-band edit that keeps the mtime, in a mkdtemp directory the test owns. The production path reads the stat and the bytes from one handle. Suggest dismissing it as "used in tests".

Author: webchang (MEMBER, maintainer)
Areas reviewed: TypeScript (control-plane, mocactl), Python, Shell, K8s/Kustomize, OpenAPI/Docs
Agent/IDE config (.claude/.vscode): none
Commits: 18 commits, all signed off: yes
CI status: everything passes except CodeQL (1 new alert, see above)

Verified by: control-plane vitest (members, provenance, template-catalog, sandbox-handlers, routes, route-profile, openapi-contract, errors): 159 of 159 passed. mocactl (sbx-admin-subjects, sbx-templates, contract): 62 of 62 passed. tsc --noEmit is clean. Throwaway concurrency, redaction and failing-provenance probes were run against head and then deleted.

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

Comment thread packages/control-plane/src/members.ts Outdated
} finally {
await fh.close();
}
return this.cache;

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: doc() ends with return this.cache, which is shared state, instead of the doc this call read or matched.

change() clones await this.doc() under the serial lock, but readers such as membershipNow (called on every request) run outside the lock. This interleaving happens:

  1. A reader opens version N and is suspended in fh.stat() or readFile.
  2. write() sets the cache to N+1.
  3. The reader resumes, sees its key differs, and sets the cache back to N.
  4. The next change() opens N+1, finds the key matches, and gets N from this.cache.
  5. It clones N, applies its edit, and renames the result over N+1.

The N+1 change is lost from disk while its provenance record stays on the chain.

Probe against the real MembersStore and ProvenanceStore, with 8 concurrent membershipNow loops:

  • 150 sequential enrolls left 85 of 150 members on disk.
  • grant, then revoke, then an unrelated change: the revoked grant was back on disk in 184 of 200 runs.
  • With the fix below, 150 of 150 survived.

Suggested fix: return a local variable, and don't let a slower reader overwrite a newer cache:

let out: MembersDoc;
if (key !== this.cacheKey) { /* parse */ this.cache = parsed; this.cacheKey = key; out = parsed; }
else out = this.cache;
return out;

Please also add a regression test with concurrent readers during change().

prev = d
write_atomic(head_path, canonical({"stream": stream, "head": prev, "count": len(chain)}).encode())
new_head = prev
keep = {os.path.join(store, "records", new_head[7:] + ".json")}

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: when a hit's redaction leaves the bytes unchanged, this deletes records that the rewritten chain still references.

old_files covers every record from the first hit on, but keep holds only the new head. A hit can rewrite nothing:

  • The hit test searches canonical(r), but scrub works per string value, so a pattern can match the canonical text without matching any single value.
  • A pattern can match only inside a key, which scrub never touches.

In either case the digests are unchanged and the files get removed anyway.

Probe on a real 3-record template/web stream:

  • --pattern sandboxId --apply printed "head X -> X". records/ went from 3 files to 2, and then ProvenanceStore.chain() threw provenance record sha256:… is missing.
  • --pattern '"description":"d"' left 1 file, with the same error.

Suggested fix:

  • Set keep to the set of every new digest written.
  • Count a hit as scrub(r) != r rather than as a regex match on the canonical text.
  • Print "nothing to redact" when the head doesn't change.

throw new CpError('name_conflict', `you already have a live sandbox named '${rec.name}'`);
}
await audit(deps, p.sub, id, 'sandbox_created');
await sandboxCreated(deps, rec, p.sub);

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: sandboxCreated is awaited after store.create. If provenance.append throws (ENOSPC, a read-only volume, a bad head), the client gets a 500 for a sandbox that exists and counts against its quota. Lines 484 and 546 have the same pattern.

The janitor is affected too. recordExpiries calls provenance.chain(), which throws on any missing record (see the redact finding), so janitorSandboxes fails as a whole and the host stops reaping.

A probe with a throwing append or chain stub reproduced both cases.

Suggested fix: treat these appends like auditBestEffort (catch and log), and compute the janitor response before recordExpiries runs. Otherwise, document that a failed write fails the request, and roll the create back.

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.

This is in main's code (the sandbox create's provenance append), not this PR's, so it's filed as #806 with options for the provenance owners. Closing the point here.

Assisted-By: Claude Code

Comment thread docs/reference/configuration.md Outdated
| `SH_REFRESH_REUSE_GRACE_SECONDS` | `30` | Invalid or `0` silently becomes 30, so the grace cannot be disabled; above 300 throws | Grace for a retried refresh |
| `SH_SANDBOX_TIERS` / `SH_SANDBOX_DEFAULT_TIER` | as for the worker | Must match the supervisor's exactly | Tiers a session may choose |
| `SH_SANDBOX_TEMPLATES` | unset (no templates) | Sandbox profile. JSON `[{id, worker, description, tools}]`; malformed throws. With `SH_PROVENANCE_DIR` set, imported into the template store once (owner `null`) and ignored after that | The templates a sandbox may be created from |
| `SH_PROVENANCE_DIR` | unset | Absolute path on a persistent volume; either profile; one control-plane process per directory. Opens the provenance store and the template store together. Unset: templates come from `SH_SANDBOX_TEMPLATES` at every start and nothing is recorded | Template store and provenance records |

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: this row says SH_PROVENANCE_DIR opens the provenance and template stores. Since this PR it also opens the members store. That enables the /v1/subjects routes, and every request then re-evaluates roles from members.json, the harness profile included. Since this changes who is admin, it's worth saying here.

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Follow-up to our review at f8a72b8. I reviewed the 6 new commits (git diff f8a72b8 ddc5aad, 12 files). All 3 of our items are fixed, along with the other bot's 2 suggestions:

  1. must-fix, enroll of a settings subject (d00cf29): fixed. enrollSubject now answers a subject in SH_ALLOWED_SUBJECTS/SH_ADMIN_SUBJECTS unchanged (record: null) and writes nothing. MemberView.storeEnrolled exposes the store's own enrollment, and mocactl's alreadyThere compares against it (source === 'env' || storeEnrolled), so the false race no longer happens. The RUNBOOK now says to check storeEnrolled before you drop a subject from the settings.
  2. suggestion, until bound (c16317c): fixed. The server and parseUntil both refuse values more than 366 days ahead, so epoch milliseconds are refused. The docs and openapi are updated.
  3. suggestion, unreadable members.json (daf2f0c, f77cfa2, ddc5aad): fixed. MembersStore.membershipNow reads the store once per request. It doesn't read the file at all for a settings admin. If the read fails, a subject on the allow list is answered from the settings alone (with a rate-limited warning), and everyone else fails closed. The cache key is now inode+size+mtime. Spec §8 and the class comment now match.

The admin_granted check now runs inside members.change(), under the serial lock (e65f32d), which closes the check-then-grant race.

Two nits, neither blocking:

  • CodeQL is red on this head because of a new alert in a test (members.test.ts:399, statSync → writeFileSync). It's a false positive in a tmp-dir test, but either restructure it to use one fd or dismiss the alert, so the check is green before merge.
  • At the 366-day boundary, --until 366d is computed from the client's clock. If the client's clock is ahead of the server's, the server refuses it.

Author: webchang (MEMBER — maintainer)
Areas reviewed: control-plane members store, member handlers, handler-util; mocactl sbx admin subjects (api/cli/commands); tests; openapi/CHANGELOG/RUNBOOK/spec
Agent/IDE config (.claude/.vscode): none
Commits: 6 new, all signed-off: yes
CI status: passing except CodeQL (1 new high alert, test-only); k8s-kind-e2e pending

const d = setup();
await call(d, 'grantAdmin', who(ENV_ADMIN), { subject: CAROL }, {});
const file = (d.members as unknown as { path: string }).path;
const { mtime } = statSync(file);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: this is the CodeQL "file system race condition" alert that keeps the CodeQL check red on this head. It's a false positive (a test in a tmp dir), but the check is still failing. You can keep the test's intent and satisfy the query by doing it all through one descriptor: const fd = openSync(file, 'r+'); const { mtime } = fstatSync(fd); ftruncateSync(fd); writeSync(fd, JSON.stringify({ members: {} }), 0); futimesSync(fd, mtime, mtime); closeSync(fd);. Or dismiss alert #123 as "used in tests".

: /^[1-9][0-9]*$/.test(raw)
? Number(raw)
: Number.NaN;
return Number.isSafeInteger(n) && n > nowS && n <= nowS + MAX_GRANT_SECONDS ? n : undefined;

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: --until 366d is computed from the client's clock (nowS + 366*86400). The server then checks until <= serverNow + 366d. If the client's clock is even 1s ahead of the server's, the maximum the help text advertises gets a 400. You could leave a little slack on one side, for example cap the CLI at 365d, or let the server accept a small skew allowance. Alternatively, document "just under 366 days".

@ingpaolodettori-dev
ingpaolodettori-dev dismissed their stale review November 13, 2026 02:06

Dismissing our approval until clawgenti's two must-fixes are resolved: MembersStore.doc() returns the shared cache, so a concurrent reader can roll it back and a revoked admin grant reappears on disk (#762 (comment)); and redact-provenance.py deletes records the rewritten chain still references when a redaction changes no bytes (#762 (comment)).

…e handle

CodeQL's file-system race rule flagged the test's stat, rewrite and
utimes by path. The edit that keeps the mtime now reads the times,
truncates, writes and resets the times through one open handle; the
test checks the same thing.

Refs rossoctl#739

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

@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

Re-review of the push since my last review (ddc5aad..7b0b9c7, review 5884424220). New: 7b0b9c70 (test-only, members.test.ts, +20/−4).

passing

Author: webchang (MEMBER — maintainer)
Areas reviewed: The out-of-band edit that keeps the mtime now reads the times, truncates, writes and resets the times through one r+ handle (fstatSync/ftruncateSync/writeSync/futimesSync). The test still checks the same behaviour, and CodeQL now passes. That clears the CodeQL alert I suggested dismissing. No new findings. The two earlier must-fixes are not addressed by this push and still stand:

  1. MembersStore.doc() returns the shared this.cache rather than the doc the call read, so a concurrent reader can roll back the cache and a later change() writes over newer changes.
  2. redact-provenance.py deletes records that the rewritten chain still references when a redaction leaves bytes unchanged.
    Agent/IDE config (.claude/.vscode): none
    Commits: 19 commits, all signed-off: yes
    CI status: TypeScript tests (control-plane members.test.ts)

Verified by: control-plane test/members.test.ts 23 of 23 passed and tsc --noEmit is clean on head (the temporary worktree was removed afterwards)

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

@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

Careful, well-tested feature — the members store's lock/cache design (generation-counted cache, one-handle stat+read, serialized writes, record-before-replace) is sound and specifically exercised by the race tests, and the authorization ladder (settings admins change, API admins read-only, bootstrap_subject, self_revoke, the under-lock admin_granted check) is enforced consistently on every route. Two documentation-level suggestions below; nothing blocking found.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, mocactl), Python (provenance tools), docs/openapi, tests, security
Agent/IDE config (.claude/.vscode): none
Commits: 22 commits, all signed-off: yes
CI status: core checks (lint, check, shellcheck, proto, CodeQL, Trivy, docs, microvm-gates) passing; deploy-scripts and k8s-kind-e2e pending at review time

Verified locally on head 5964b11: control-plane suite 1509 passed / 3 skipped with Redis, mocactl 1820 passed / 6 skipped (the one sbx-up.test.ts chmod failure also fails on origin/main — environmental, not from this PR), tsc --noEmit clean on both packages.

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

Comment thread docs/reference/http-api.md Outdated
`digest_mismatch`, `configRef_invalid`, `credential_required`, `credential_ambiguous`, `endpoint_unresolved`, `model_unavailable`), 401 (`token_required`,
`token_invalid`, `token_expired`, `unauthorized`), 403 `forbidden`, 404 (`session_not_found`, `config_bundle_not_found`,
`credential_not_found`, `template_not_found`, `turn_not_found`), 409 (`template_exists`, `turn_not_cancellable`, `turn_not_claimable`), 410 `device_code_expired`, 422 `policy_refused`, 428 `authorization_pending`, 429
`credential_not_found`, `template_not_found`, `turn_not_found`), 409 (`template_exists`, `turn_not_cancellable`, `turn_not_claimable`, `bootstrap_subject`, `self_revoke`), 410 `device_code_expired`, 422 `policy_refused`, 428 `authorization_pending`, 429

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — The 409 code list here picks up bootstrap_subject and self_revoke but not admin_granted, which this PR also adds (errors.ts:41, openapi documents it on DELETE /v1/subjects/{subject}), and the CHANGELOG's 1.9.0 "New error codes" line likewise names only the two. The spec's §4 table has all three, so a reader of just the reference/CHANGELOG would miss a wire-visible 409. Suggested fix: add admin_granted to this list and to the CHANGELOG's enumeration — it matters now because 1.9.0 is the version clients will code against.

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

const g = m?.roles.find((r) => r.role === ADMIN);
if (!g) return [];
if (g.until === undefined || g.until > nowS) return [ADMIN];
if (!g.expiredRecorded) await this.recordExpiry(subject, nowS).catch(() => undefined);

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 once-only lapse recording is correct (the re-check under the lock in recordExpiry makes it idempotent), but note it puts a full change() — clone, provenance append, file replace, on the store lock — on the read path of the first request that sees a lapse, contending with real admin writes, and the .catch(() => undefined) here swallows persistent store failures with no log line at all. A one-line warning in that catch (like the rate-limited fallback warning in membershipNow) would make a broken provenance dir visible. Not blocking — the design doc's "an expired written once, by the first request that sees the lapse" covers the behavior.

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

@webchang

Copy link
Copy Markdown
Member Author

Main (ab8d10e) merged in. Besides resolving the conflicts with #774, the merge makes one change that this PR's own diff doesn't show:

The openapi version moves to 1.9.0, above #774's 1.8.0.

Assisted-By: Claude Code

@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

Careful, well-tested feature — the members store's lock/cache design (generation-counted cache, one-handle stat+read, serialized writes, record-before-replace) is sound and specifically exercised by the race tests, and the authorization ladder (settings admins change, API admins read-only, bootstrap_subject, self_revoke, the under-lock admin_granted check) is enforced consistently on every route. Two documentation-level suggestions below; nothing blocking found.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, mocactl), Python (provenance tools), docs/openapi, tests, security
Agent/IDE config (.claude/.vscode): none
Commits: 22 commits, all signed-off: yes
CI status: core checks (lint, check, shellcheck, proto, CodeQL, Trivy, docs, microvm-gates) passing; deploy-scripts and k8s-kind-e2e pending at review time

Verified locally on head 5964b11: control-plane suite 1509 passed / 3 skipped with Redis, mocactl 1820 passed / 6 skipped (the one sbx-up.test.ts chmod failure also fails on origin/main — environmental, not from this PR), tsc --noEmit clean on both packages.

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

Main's subject trust for gate records took API 1.9.0, so this branch's
enrollment and the admin role move to 1.10.0.

Conflicts:
- docs/api/CHANGELOG.md: both added a 1.9.0 section. Main's 1.9.0 kept
  as main has it; this branch's section is now 1.10.0, above it.
- docs/api/openapi.yaml: the error code enum keeps main's self_attested
  and this branch's bootstrap_subject, self_revoke and admin_granted;
  the Policy view keeps main's gateRecordSchema, followed by this
  branch's Subject schema. info.version 1.10.0.
- docs/reference/change-policy.md: main's list, then "then enrollment
  and the admin role"; the control plane at 1.10.0, the harness at 1.0.0.
- docs/reference/configuration.md: this branch's SH_PROVENANCE_DIR row
  (the members store), then main's new SH_GATE_RECORD_SCHEMA row.
- packages/control-plane/src/errors.ts, test/errors.test.ts: both sets
  of codes, main's self_attested first, with their statuses.

Also: docs/reference/http-api.md's subjects mentions, added by this
branch, say API 1.10.0. The auto-merged owner transfer checks the new
owner's enrollment through the members store, then refuses a
self-attested template (main's check).

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

@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

Reviewed the enrollment-and-roles feature end to end: the MembersStore (file cache, serial-lock writes, provenance ordering), the /v1/subjects routes and their authorization split (any admin reads, settings admins write), the per-request role replacement in server.ts/handlers.ts/egress-handlers.ts, the mocactl CLI with its read-compare-write race detection, and the docs/OpenAPI/changelog updates. The design holds together well: the bootstrap-list invariants (409 bootstrap_subject/self_revoke/admin_granted) are enforced under the store's serial lock, the record-before-file-write ordering is documented as intent-log semantics, and the cache keyed on inode+size+mtime with the writes generation guard is carefully done. No must-fix issues found; the inline comments are suggestions/nits.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control plane, mocactl), Python (verifiers), OpenAPI/docs, tests, security
Agent/IDE config (.claude/.vscode): none
Commits: 29 commits, all signed-off: yes (DCO check passing)
CI status: passing (CodeQL, Trivy, shellcheck, lint, docs, proto, microvm-gates, hadolint; k8s-kind-e2e and deploy-scripts pending at review time)

Verified against the PR branch: authorize() in server.ts only verifies the token (no role gating), so replacing ctx.principal.roles after it is safe — handler-level isAdmin sees the per-request roles; sameControlPlane, adminSubjectsFromEnv, MEMBER_SUBJECT_RE/MEMBER_SUBJECT_FORMS all exist as referenced; the OpenAPI version bump to 1.10.0 is consistent across openapi.yaml, CHANGELOG.md, change-policy.md and http-api.md.

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

raw !== null &&
!(
Number.isSafeInteger(raw) &&
(raw as number) > nowS &&

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 — until is validated against nowS captured before the change enters members.change()'s serial queue. Under contention (another change holding the lock), a queued grantAdmin can accept an until that is a few seconds in the past, or marginally past the 366-day bound, by the time it writes. The window is small and the consequence mild (a grant that lapses almost immediately), so this is not blocking — but computing nowS inside the change() callback (as unenrollSubject already does for its liveness check) would make the bound exact at write time.

Suggested fix: move const nowS = seconds(deps); inside the fn passed to members.change() (keeping a separate one for the response view()), or note the tolerance as accepted.

}

/** One subject's view (enrolled false, no roles, when neither the settings nor the store has it). */
async view(subject: string, nowS: number): Promise<MemberView> {

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 — view() scans the full list() (every subject, sorted, with a fresh doc() read) just to answer one subject, and every change handler calls it right after its write. At current scale this is fine, but a direct single-subject construction from the doc (the same folding list() does for one entry) would avoid the O(all-subjects) scan and the second file read per change.

Suggested fix: build the MemberView for subject directly from doc.members[subject] plus the bootstrap lists, and let list() share that helper.

}

/** An API-granted admin role's state: `none`, or `admin` with its `until` (null: no expiry). */
const roleOf = (s: SbxSubject | undefined) => {

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 — alreadyThere's grant case compares roleOf(s) === \admin until ${until ?? 'no expiry'}`, i.e. equality of two formatted strings. It works today because both sides format identically, but it breaks silently if roleOf's formatting ever changes (e.g. the untildisplay). Comparing structured values — the grant'suntil(withundefined/null` normalized) against the requested one — would be sturdier.

Suggested fix: have roleOf return { live: boolean, until: number | null } (or similar) and compare that.

this.fallbacks += 1;
if (nowS - this.fallbackWarnedAtS >= FALLBACK_WARN_EVERY_S) {
const why = (err as NodeJS.ErrnoException).code ?? (err as Error).name;
console.warn(

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 — membershipNow warns via console.warn directly. If the control plane has a logging seam elsewhere (audit log / deps.log), routing this through it would keep output configurable in tests and deployments; the test currently spies on console.warn, which is what pins this. Fine to keep if console is the established pattern for boot-time/style warnings in this package.

… in the settings

Decision 1 of the enrollment and roles spec keeps changes to access with
the admins named in SH_ADMIN_SUBJECTS: an admin by an API grant cannot
widen access. With subject trust in main, a PUT /v1/policy can widen
what the deployment trusts in the same way. Trusting a gate record makes
self-attested templates visible to everyone and transferable, and
allowing a registry or a repository widens what any subject may build
from.

A PUT /v1/policy that adds to trustedGateRecords or allowedRegistries,
or adds to or drops a registry's allowedRepositories list, is now
refused 403 forbidden for an admin by an API grant when a members store
is kept. Such an admin may still narrow the policy and change its
quotas. Registries and repository keys compare case-insensitively, as
the policy reads them.

Test: an API-granted admin's four widenings (a gate record, a registry,
a repository, a dropped list) are each refused with the policy
unchanged. A narrowing with a quota change goes through, and a settings
admin's widening goes through. Without the check, the test fails.

Refs rossoctl#739

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

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

Automated review pass (Clawgenti Code Review). No must-fix findings — the authz core checks out: settings admins are the only mutators (bootstrap comes from env and is never written by the store, so an API-granted admin gets 403), bootstrap subjects are protected from unenroll/revoke with no TOCTOU, per-request role evaluation defeats token-claims escalation, and the members-file read is single-handle with an inode+size+mtime cache key and a serial write lock. Input validation (subject grammar, until epoch-ms rejection and 366-day bound), path safety (fixed members.json path, wx 0600 temps), and provenance-kind confinement are all sound, and the race tests cover the admin-grant-vs-unenroll interleaving.

The rest are suggestions/nits below — nothing blocking.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, mocactl), Python (provenance scripts), Docs/openapi, Security
Agent/IDE config (.claude/.vscode): none
Commits: 23, all signed-off: yes
CI status: passing (all checks green on 79be286)

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

Comment thread packages/control-plane/src/members.ts Outdated
// The cache and its key are set together, synchronously, so a matching key means this cache.
if (key === this.cacheKey) return this.cache;
const parsed = JSON.parse(await fh.readFile('utf8')) as MembersDoc;
if (!parsed || typeof parsed.members !== 'object') throw new Error('members.json is invalid');

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 — doc() validates the store only shallowly: typeof parsed.members !== 'object' lets "members": [] and malformed member records through, so a hand-edited {"members": {"x": "oops"}} makes m?.roles.find(...) in storeRoles throw a TypeError. Everything fails closed (a throw denies access), so this isn't a security hole, but a corrupted store surfaces as an opaque 500 internal_error on every request instead of a dedicated error, and the malformed record is written back verbatim by the next change(). Suggested fix: validate the member shape (subject string, enrolled boolean, roles array) in doc() and reject with a specific error code. Why now: the members file is operator-writable JSON, and the API version bump (1.10.0) is the natural place to settle the error contract.

const fh = await openFile(tmp, 'wx', 0o600);
try {
await fh.writeFile(JSON.stringify(doc));
await fh.sync();

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 — write() fsyncs the temp file but not the directory after rename(tmp, this.path). A crash after the rename returns can lose the rename while the provenance record (appended earlier in change()) survives — widening the documented "record without state" gap (spec §9) into a silent loss of an acknowledged change: the caller got 200 with a record digest, but the enrollment/grant is gone after restart. Suggested fix: one fsync of the directory after the rename. This is the file authorization depends on, so it's worth the durability even if ProvenanceStore.append has the same property.

// a members store the subject's current ones replace them, so a grant, revoke or lapse takes
// effect at the next request. Without a store the token's claims stand, as before.
if (ctx.principal && deps.members) {
const m = await membershipNow(deps, ctx.principal.sub, ctx.principal.roles ?? []);

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 step replaces ctx.principal.roles wholesale with membershipNow's answer, which today is only ever ['admin'] or [] (storeRoles). Any role the identity provider minted other than admin is silently dropped on deployments with a store. With only admin existing this is correct, but it's a trap for the next role anyone adds to rolesFor: it will work without a store and silently vanish with one. Suggested fix: a comment stating the invariant here, or an assert/debug check that no non-admin token role is being discarded.

if (ctx.principal && deps.members) {
const m = await membershipNow(deps, ctx.principal.sub, ctx.principal.roles ?? []);
ctx.principal = { ...ctx.principal, roles: m.roles, enrolled: m.enrolled };
} else if (ctx.principal) {

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 — for a subject in neither SH_ALLOWED_SUBJECTS nor SH_ADMIN_SUBJECTS, an unreadable or invalid members.json propagates the raw error (ENOENT / EACCES / "members.json is invalid") out of the router. Fail-closed is right, but these surface as 500 internal_error, indistinguishable from a code bug. A 503 with a store-specific code (cf. redis_unavailable) would let operators and clients tell corruption from breakage.

hits = [i for i, r in enumerate(chain) if any(p.search(canonical(r)) for p in pats)]
# A hit is a record the redaction changes, not a match in its canonical text: scrub() rewrites
# string values only, so a match inside a key, or across values, changes no byte.
hits = [i for i, r in enumerate(chain) if scrub(r, pats) != r]

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 hit detection scrub(r, pats) != r is only correct if scrub() is pure (returns a new structure, never mutates r). If scrub mutated in place and returned the same object, the comparison would always be False by identity and redaction would silently become a no-op that still prints "nothing to redact" under --apply. The existing tests appear to pin the pure behavior, but since scrub's definition is outside this diff, a one-line comment (or a test asserting scrub(r, pats) is not r when it changes something) would lock the invariant down.

Main's template host agents took API 1.10.0 and its activation leases
1.11.0, so this branch's enrollment and the admin role move to 1.12.0.

Conflicts:
- docs/api/CHANGELOG.md: both added a 1.10.0 section. Main's 1.11.0 and
  1.10.0 kept as main has them; this branch's section is now 1.12.0,
  above them.
- docs/api/openapi.yaml: info.version 1.12.0. Both added paths before
  /v1/sandboxes: main's /v1/hosts paths kept, this branch's /v1/subjects
  paths after them; both sets of error codes and schemas kept.
- docs/reference/change-policy.md: main's list kept, then "then
  enrollment and the admin role"; the control plane at 1.12.0.
- docs/reference/http-api.md: main's Host agents and Activation rows,
  then this branch's Subjects row (API 1.12.0); the 409 list holds
  main's codes and this branch's bootstrap_subject and self_revoke.
- packages/control-plane/src/handlers.ts: both imports, both CpDeps
  fields (hosts, members) and both handler spreads kept.
- packages/control-plane/src/routes.ts: main's host routes, then this
  branch's /v1/subjects routes.
- packages/control-plane/test/route-profile.test.ts, routes.test.ts:
  both route lists, in the table's order.
- packages/mocactl/src/sbx/cli.ts: main's templates activate and
  deactivate help, then this branch's admin subjects help.

Also: packages/mocactl/test/contract.test.ts scripts 25 replies, one per
call: main's activate and deactivate and this branch's five subject
calls. Main's activate, deactivate and first-use activation read the
caller's roles and enrollment from the request's principal, which the
router sets per request (membershipNow) on this branch; no other change
was needed.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… across differently-cased registry keys

policyWidens read allowedRepositories into a map keyed by the lowercased
registry, so of two keys that differ only in case the later one
replaced the earlier. admitBuild unions the lists of every key that
names the registry in any case. An admin by an API grant could add a
second key in another case, ahead of the existing one, with a new
repository: the registry's effective list widened while the check saw
only the last key's list.

Each registry's list is now the union of every key that names it, for
the current and the next policy, as admitBuild reads them. A registry
that had a list widens when the next policy's list gains an entry or
is gone; a new list for a registry that had none still narrows it.

The members test adds both orders of a second, differently-cased key
with a new repository: each is refused 403 with the policy unchanged
(the key-first order passed the old check).

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
errors.ts and openapi have the code (an unenroll refused while an admin
grant keeps the subject enrolled); the reference's list left it out.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
@webchang

Copy link
Copy Markdown
Member Author

Main (ec0f840) merged in, with one design change. This round makes three changes:

  1. Widening the template policy needs an admin named in the settings (97fb831, cd205ac). A PUT /v1/policy by an admin whose role comes from an API grant is refused 403 when it would widen the policy: adding a trusted gate record, an allowed registry or an allowed repository, or dropping a registry's repository list. Registry keys that differ only in case are unioned the way admitBuild reads them, so a case variant can't slip a widening through. API-granted admins may still narrow the policy and change quotas. This extends the spec's decision 1 to trust, and is in the openapi, the CHANGELOG and a test.
  2. The merge audit: main's activate, deactivate and first-use activation read the per-request roles (membershipNow). No enrollment or role check that reads only the settings is left on those paths.
  3. http-api's 409 list now names admin_granted (2861a3c).

This head is at openapi 1.12.0; #776 has since merged at 1.12.0, so this PR takes the next free number in its next merge of main.

Assisted-By: Claude Code

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

Review of this PR (automated pass, comments only — severity-tagged inline; the rest of this body is the summary).

Author: webchang (MEMBER — maintainer)
Areas reviewed: control-plane handlers/members/token/routes, mocactl CLI, Python provenance scripts, openapi + docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 27 commits, all signed-off
CI status: passing

Overall this is a well-engineered change: the privilege model is conservative (only settings-named admins can change access; API-granted admins are read-only on these routes and blocked from widening the template policy), per-request role evaluation defeats stale token claims, and the members.json write path (tmp + 0600 + fsync + rename under a serial lock) is sound. No must-fix findings; 5 suggestions and 2 nits inline.

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

Comment thread packages/control-plane/src/members.ts Outdated
// The cache and its key are set together, synchronously, so a matching key means this cache.
if (key === this.cacheKey) return this.cache;
const parsed = JSON.parse(await fh.readFile('utf8')) as MembersDoc;
if (!parsed || typeof parsed.members !== 'object') throw new Error('members.json is invalid');

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 — {"members": null} (or an array) passes this validation: typeof null === 'object' and typeof [] === 'object', so a hand-edited file crashes downstream with a raw TypeError (doc.members[subject] on null) instead of the intended clean error. The damaged-file test only covers truncated JSON. Suggested fix: if (!parsed || typeof parsed.members !== 'object' || parsed.members === null || Array.isArray(parsed.members)), and optionally validate each member's enrolled/roles shape; add a test. Fail-closed either way, but the error path is unintentional.

* A file version's identity for the cache: an out-of-process edit within the mtime's granularity
* still moves the inode (a replace) or, mostly, the size.
*/
const statKey = (st: { ino: number; size: number; mtimeMs: number }): string =>

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 — an in-place rewrite that keeps the byte size and restores the mtime (ftruncate/write/futimes — exactly what some operators and restore tools do, same inode) produces an identical statKey, so the cache is never invalidated and revoked grants keep answering as before. The comment concedes "mostly". Since the control plane is the only writer via rename this needs an out-of-process edit, but the inode/size key exists precisely for out-of-process edits. Suggested fix: on a statKey hit, also compare a cheap content fingerprint (first/last N bytes, or byte-compare on size match), or document the residual window explicitly.

}

/** The API token issuer each profile's control plane mints under (control-plane token.ts). */
const ISSUER_BY_PROFILE: Record<string, string> = {

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 — loginMismatch looks up ISSUER_BY_PROFILE[d.profile ?? '']; for a harness-profile (or unmapped-profile) deployment want is undefined and the issuer comparison is silently skipped, leaving only the stored-URL check. The design advertises "a login issued for another deployment is refused before any write" as a general guard. Not a security hole (the server verifies the token), but the guard is a no-op for half the deployments. Suggested fix: add the harness issuer to the map, or refuse when the profile is known-but-unmapped.

'bootstrap_subject',
`${subject} is enrolled by the deployment's settings (SH_ALLOWED_SUBJECTS or SH_ADMIN_SUBJECTS); remove it there`,
);
const nowS = seconds(deps);

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 — nowS is captured before members.change(...), but the admin_granted liveness check runs under the store's serial lock, potentially after other queued changes. A grant whose until lapsed while this request waited is still treated as live, producing a spurious 409 (the safe direction, but a wrong answer); grantAdmin's live/before computation has the same skew. Suggested fix: recompute seconds(deps) inside the change callback so the comparison uses the time the decision is actually made.

});

export const MEMBER_HANDLERS: Record<string, Handler> = {
listSubjects: async (ctx, deps) => {

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 — unlike membershipNow, the admin read paths (listSubjects → doc()) have no error mapping for a damaged members.json: the JSON parse error propagates as a 500 internal_error. The openapi for /v1/subjects lists only 200/400/401/403, and http-api.md's error table doesn't cover this either. The "settings stay the recovery path" intent is implemented for request evaluation but not for the admin's own read. Suggested fix: catch the read error and answer 503 (or a distinct 500 code) naming members.json, add it to openapi; or serve the bootstrap subjects with a warning as membershipNow does.

});
return {
status: 200,
body: { ...(await members.view(subject, seconds(deps))), record },

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 response spreads members.view(subject, ...) after the change, re-reading the doc outside the serial lock. A concurrent change by another admin landing in between means the returned Subject may not be the state this write produced, muddying the CLI's read-vs-write race detection. Have change() return the post-change doc and build the response from that.

: extra.length === 0 && (arg === undefined || TAKES_ID_ARG.has(command)));
if (!argsOk) {
io.err(
`sbx: ${command === 'put' ? 'put takes exactly one PATH' : `too many arguments for ${command}`}\n${SBX_USAGE}`,

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 argsOk check requires extra.length === 2, so mocactl sbx admin subjects enroll (subject omitted) falls through to the generic "too many arguments for admin" message — wrong on two counts for a missing-argument case. Give admin subjects its own usage message naming the expected SUBJECT argument.

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

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Follow-up at 2861a3c (79be286..2861a3c): a merge of upstream main ec0f840 (#772, #775) plus 3 own commits: 97fb831 (an API-granted admin can't widen the template policy), cd205ac (the widening check unions repository lists across differently-cased registry keys, as admitBuild does) and 2861a3c (http-api's 409 list names admin_granted). The merge resolutions are correct (checked with git show --remerge-diff and a dropped-lines check). Enrollment moves to API 1.12.0, http-api's 409 list keeps both code sets, and the mocactl contract count goes 23→25. The new check matches admitBuild for registries and repositories. Two gaps are inline: the check doesn't look at profiles/defaultProfile, and it reads the policy outside the write.

Still open: the members.ts must-fix from our 72f9193 review. doc() (members.ts:142) still checks only typeof parsed.members !== 'object', so {"members":null} passes. A member without a roles array still throws in storeRoles. Either one gives an allow-listed subject a 500. Validate the shape in doc(), and test both cases. clawgenti's members.ts:142 suggestion at 79be286 is about the same check.

Needs another rebase: main moved to 3efcf9a (#776), which took API 1.12.0. The PR is dirty again, with conflicts in CHANGELOG, change-policy.md and mocactl sbx/api.ts/sbx/cli.ts. Enrollment will need 1.13.0.

Author: webchang (MEMBER — maintainer)
Areas reviewed: control-plane TS (putPolicy, policyWidens), tests, docs, merge resolutions
Agent/IDE config (.claude/.vscode): none
Commits: 3 own + 1 merge since 79be286, all signed-off: yes (DCO pass)
CI status: all 17 checks pass at this head (checked before the new conflict)

AI-assisted review, approved by a maintainer before posting.

* was not, or a registry's repository list that gains an entry or is dropped (no list allows every
* repository). Registries and their keys compare case-insensitively, as the policy reads them.
*/
function policyWidens(cur: Policy, next: Policy): string[] {

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 — policyWidens compares only trustedGateRecords, allowedRegistries and allowedRepositories. profiles and defaultProfile go through unchecked, but they widen what the deployment admits just as much. An API-granted admin could drop X1/X11 from benchmark.requires, set requireOfflineGate: false or selfAttestEgress: true on benchmark-self, raise an envelope, or point defaultProfile at base. Builds created under the loosened profile are deployment-attested and default to visibility: 'deployment'. Treat any profile change other than tightening (or simply any change to profiles/defaultProfile) as a widening, and add a test case for it. The spec/openapi wording ('may narrow it and change its quotas') would then match.

// roles spec, decision 1): an admin by an API grant may narrow the policy and change its quotas,
// but adding a trusted gate record, a registry or a repository needs an admin named in the
// settings. Without a members store every admin is one.
const widened = policyWidens((await store.current()).policy, ctx.body as Policy);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — the widening check reads store.current() here, but store.set runs later, outside any serialized update. This is the putPolicy lost-update issue that is still open on #786. With this check it becomes a bypass. Say a settings admin removes trust for record G, and an API-granted admin concurrently PUTs a quota change built from the older policy (which still has G). The check compares against the pre-removal policy and sees no widening. set then lands after the removal, and G is trusted again. Do the read, the check and the write as one serialized step (a lock or queue in the policy store), or compare-and-set against the digest that was read.

Upstream main d227d41. The branch's API section moves from 1.12.0 to 1.18.0,
above main's 1.17.0; main's sections are unchanged.

Conflicts:
- docs/api/CHANGELOG.md: the branch's section, renumbered 1.18.0, above main's
  1.17.0 to 1.12.0 sections, which are kept as main has them.
- docs/api/openapi.yaml: info.version 1.18.0; main's /v1/hosts/{host}/egress
  path, then the branch's /v1/subjects paths.
- docs/reference/change-policy.md: main's list, then "then enrollment and the
  admin role"; control plane 1.18.0, harness 1.3.0.
- docs/reference/configuration.md: main's SH_ROUTE_PROFILE and
  SH_SANDBOX_TEMPLATES rows; the branch's SH_PROVENANCE_DIR row (the members
  store).
- docs/reference/http-api.md: both table rows and both paragraphs; the
  branch's notes say API 1.18.0.
- packages/control-plane/src/sandbox-config.ts: main's split into isEnrolled
  (login) and isEnrolledForSandbox (the sandbox routes and template writes),
  both taking the branch's storeEnrolled through onAllowList.
- packages/control-plane/src/handler-util.ts: requireEnrolledPrincipal uses
  isEnrolledForSandbox with the request's per-request enrollment; main's
  requireReader kept.
- packages/control-plane/src/egress-handlers.ts and sandbox-handlers.ts: the
  egress owner check and the owner transfer use isEnrolledForSandbox on the
  subject's membership now (membershipNow).
- packages/control-plane/src/routes.ts, test/routes.test.ts,
  test/route-profile.test.ts: both sides' routes (the subjects routes and
  POST /v1/hosts/{host}/egress).
- packages/mocactl/src/sbx/api.ts: SbxSubject and main's readiness and
  egress types.
- packages/mocactl/src/sbx/cli.ts: both usage blocks (hosts, then admin
  subjects), the command list (admin, get, mode, reset), the argument check
  (credentials list and mode), and the dispatch (admin and hosts).
- packages/mocactl/src/sbx/commands.ts: both imports.
- packages/mocactl/test/contract.test.ts: main's reply shape, and the scripted
  replies raised to 30, the calls of both sides.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…r hold read enrollment per request

The combined profile's first-use activation (a session create) and the
worker hold a pinned session's turns take read the allow list and the
token's roles alone, so a subject enrolled through /v1/subjects was
treated as not enrolled there, and one unenrolled kept its hold. The
create now passes the request's own enrollment, and the hold evaluates
the owner's membership now, as the other enrollment checks do.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…rong shape as a corrupt one

doc() checked only that `members` was an object, so `{"members": null}`
passed, and a member without a `roles` array threw in storeRoles: a
TypeError outside membershipNow's fallback, a 500 even for a subject on
the allow list. doc() now checks the document's whole shape (members a
plain object; each entry a member under its own subject, with a boolean
enrolled, an array of admin grants, since and by) and refuses another as
it refuses an unparseable file: the settings' subjects are answered from
the settings, with the rate-limited warning, and anyone else fails
closed.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…n one step

The widening check read the policy, and the write came later, with
nothing holding the two together: a PUT by an admin by an API grant,
built from an older policy, could pass the check against it and land
after a settings admin's PUT that removed a trusted gate record,
restoring it. PolicyStore has no update() on main, so putPolicy now
runs its read, its widening check, the narrowed-build scan and its
write under one lock per policy store, as the catalog's quota and
activation locks do.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… is a policy widening

PUT /v1/policy's widening check covered trusted gate records,
registries and repositories only, so an admin by an API grant could
still accept more through the profiles. policyWidens now also flags a
new profile; an existing one that drops a rule from requires, stops
requiring the offline gate, turns on selfAttest or selfAttestEgress,
raises or removes an envelope bound, or changes or removes its exact
size; and a defaultProfile change unless the new default accepts no
more than the old one (nothing ranks profiles, so it must meet every
one of the old default's requires, flags and bounds). A removed
profile, every narrowing and every quota change stay open to any admin.
The spec's decision 1, the openapi description and the changelog list
the profile cases.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… refused, not a 500

checkCreate looked the profile up with policy.profiles[profileName]. A
create naming `constructor`, `__proto__` or `toString` got an inherited
object, not undefined. The envelope check then threw, and the caller got
a 500 where the policy refuses an unknown profile (422, rule `profile`).
The lookup now takes own keys only, as the policy-widening check does.
No rule was skipped: the throw came before any other check.

Test: the refusal table refuses each of the three names with rule
`profile`. Without the fix, all three fail.

Refs rossoctl#739

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
@webchang

Copy link
Copy Markdown
Member Author

Follow-up to the review at 2861a3c, with main (d227d41) merged in. Each point has its own commit:

  1. The must-fix: members.json's shape is validated (0e3dc52). A document with members: null, or a member without a roles array, is now treated as a corrupt file: allow-listed subjects are answered from the settings, and every other subject fails closed. No more 500. Tests cover both cases.
  2. The lost update: PUT /v1/policy checks for a widening and writes in one locked step (003bbe2), so a concurrent write built from an older policy can't put back trust a settings admin just removed. A test runs two concurrent PUTs.
  3. Profiles count as widening (31ea606), as the review suggested. A settings admin is needed to add a profile, drop a requirement from a profile's requires, turn off requireOfflineGate, turn on selfAttest or selfAttestEgress, raise or remove an envelope bound, or move defaultProfile to a weaker profile. Any admin may still narrow. The spec's decision 1, the openapi and the CHANGELOG say so.
  4. Found in the merge with feat(control-plane,sbx,deploy): one control plane for sessions and sandboxes; sessions pinned to a template build #789 (10db2c0): two of the combined plane's checks read enrollment from the settings only, namely a session's activation gate and its pinned-worker hold. Both now read the per-request membership, like the rest of this PR.
  5. A create naming constructor or __proto__ as its profile is refused instead of answering 500 (8729f73).

The openapi version is 1.18.0 on this head. #781 also claims it, so whichever merges later renumbers.

Assisted-By: Claude Code

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Follow-up at 8729f73 (2861a3c..8729f73): a merge of main d227d41 (#789, #790) plus 5 own commits. This closes our open must-fix and both suggestions from 2861a3c.

  • members.ts doc() shape (must-fix from 72f9193): fixed in 0e3dc52. isMembersDoc checks that members is a plain object and that each entry is a Member under its own subject, with a boolean enrolled, a roles array of admin grants, and since/by. A document of the wrong shape is refused the same way as an unparseable one: the settings' subjects get their answer from the settings, and everyone else fails closed. Tests cover null, an array, a missing roles and a non-grant role.
  • policyWidens and profiles/defaultProfile: fixed in 31ea606. A new profile counts as a widening. So does a profile that drops a rule, stops requiring the offline gate, turns on selfAttest or selfAttestEgress, or raises or removes an envelope bound or the exact size. A default that accepts more than the old one counts too. The spec, openapi and changelog all list these cases.
  • The check and the write are one step: fixed in 003bbe2. policyLock runs the read, the widening check, the narrowed-build scan and store.set under one queue, and there's a test for the stale-PUT restore case.
  • 10db2c0: on combined, first-use activation now reads the request's store enrollment, and holdPinnedWorker reads membershipNow. This was the second enrollment site that #789 noted.
  • 8729f73: an own-key profile lookup in checkCreate.

The merge resolutions are OK. We checked them with git show --remerge-diff and a dropped-lines check across all 16 files. The API claims 1.18.0 over main's 1.17.0 everywhere: openapi, CHANGELOG, change-policy and http-api. The mocactl contract count is 30 (25 + 5). The branch merges cleanly into current main.

One suggestion is inline: a defaultProfile that names a prototype key still gets a 500 from PUT /v1/policy. It's the same class of bug 8729f73 fixed for creates.

Author: webchang (MEMBER — maintainer)
Areas reviewed: control-plane TS (members store, putPolicy / policyWidens, activation and worker hold, checkCreate), tests, docs, merge resolution
Agent/IDE config (.claude/.vscode): none
Commits: 5 own + 1 merge since 2861a3c, all signed-off: yes (DCO pass)
CI status: all 17 checks green

AI-assisted review, approved by a maintainer before posting.

const oldDefault = Object.hasOwn(cur.profiles, cur.defaultProfile)
? cur.profiles[cur.defaultProfile]
: undefined;
const newDefault = next.profiles[next.defaultProfile]!;

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: policyProblems checks the default with o.profiles?.[o.defaultProfile] (template-policy.ts:696), so "defaultProfile": "constructor" (or toString, or __proto__) passes validation. Here next.profiles[next.defaultProfile]! then resolves to an inherited function, and profileWidens reads next.envelope.maxGuestMb on undefined. The result is a TypeError, and every admin gets a 500 instead of a 400. If the old default were missing, the !oldDefault || short-circuit would skip the throw. A settings admin's PUT would then store a default that checkCreate (own keys since 8729f73) refuses for every create that names no profile. This is the same class of bug 8729f73 fixed. Use Object.hasOwn(o.profiles, o.defaultProfile) in policyProblems, and add a refusal-table case.

Brings rossoctl#781 (template retire, API 1.18.0).

Conflicts:
- docs/api/CHANGELOG.md: this branch's section above main's ## 1.18.0
  and the sections below it, which are unchanged.
- docs/reference/change-policy.md: main's list, then "enrollment and the
  admin role".
- docs/reference/http-api.md: main's Retire row and paragraph, then the
  Subjects row and paragraph. The 409 list holds main's build_in_use
  plus this branch's bootstrap_subject, self_revoke and admin_granted.
- packages/mocactl/test/contract.test.ts: 32 scripted replies (main's
  2 retire calls plus this branch's 5 subject calls).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings rossoctl#785 (retired build removal, API 1.19.0). This branch's
enrollment section takes the next number, 1.20.0.

Conflicts:
- docs/api/CHANGELOG.md: ## 1.20.0 above main's ## 1.19.0 and the
  sections below it, which are unchanged.
- docs/api/openapi.yaml: info.version 1.20.0.
- docs/reference/change-policy.md: main's list, then "enrollment and the
  admin role"; control plane 1.20.0.

Also moved to 1.20.0: http-api.md's Subjects row and its "Who is enrolled"
paragraph.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
@webchang
webchang merged commit e921272 into rossoctl:main Nov 14, 2026
18 checks passed
@pdettori pdettori added this to the v0.11.0 milestone Nov 17, 2026
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.

Enroll subjects and grant the admin role through the API, recorded and effective per request

5 participants