Repository navigation
feat(control-plane): enroll subjects and grant the admin role through the API - #762
Conversation
… 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
left a comment
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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')) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
The authz model holds up:
- Only
SH_ADMIN_SUBJECTSadmins 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_revokeis unreachable defence in depth. - Token
rolesare replaced per request, so a forged or staleadminclaim no longer counts. untilis in seconds on both sides and lapses at the next request, with theexpiredrecord 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)); |
There was a problem hiding this comment.
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:2inSH_ALLOWED_SUBJECTS,doc.members[subject]is absent,blank()givesenrolled: false, so line 71 doesn't short-circuit. The handler writesenrolled: truetomembers.jsonand appends amember {enrolled: true, before: false}record. - Hidden in the list:
list()reports that subject assource: 'env', soGET /v1/subjectsgives no sign the store also enrolls it. - Access survives removal: later the operator removes
github:2fromSH_ALLOWED_SUBJECTSwithsetup.shto revoke access.storeEnrolledkeeps it enrolled, and the review the RUNBOOK asks for (GET /v1/subjectsbefore the change) never showed why. - False race in the CLI:
mocactl sbx admin subjects enroll github:2readsenrolled: true, soalreadyThere(commands.ts:449) says "already so". It then gets a non-nullrecordand callsraced(), 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()foldsroles.length > 0intoenrolled).
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)) |
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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]>
ingpaolodettori-dev,
|
clawgenti
left a comment
There was a problem hiding this comment.
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:
MembersStore.doc()returns the sharedthis.cache, not the doc the call actually read. A concurrent reader can roll back the cache, and the nextchange()then writes over newer changes. One effect: a revoked admin grant comes back on disk. Reproduced with real stores, details inline.redact-provenance.pydeletes 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).
| } finally { | ||
| await fh.close(); | ||
| } | ||
| return this.cache; |
There was a problem hiding this comment.
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:
- A reader opens version N and is suspended in
fh.stat()orreadFile. write()sets the cache to N+1.- The reader resumes, sees its key differs, and sets the cache back to N.
- The next
change()opens N+1, finds the key matches, and gets N fromthis.cache. - 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")} |
There was a problem hiding this comment.
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), butscrubworks 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
scrubnever 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 --applyprinted "head X -> X".records/went from 3 files to 2, and thenProvenanceStore.chain()threwprovenance record sha256:… is missing.--pattern '"description":"d"'left 1 file, with the same error.
Suggested fix:
- Set
keepto the set of every new digest written. - Count a hit as
scrub(r) != rrather 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| | `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 | |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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:
- must-fix, enroll of a settings subject (d00cf29): fixed.
enrollSubjectnow answers a subject inSH_ALLOWED_SUBJECTS/SH_ADMIN_SUBJECTSunchanged (record: null) and writes nothing.MemberView.storeEnrolledexposes the store's own enrollment, and mocactl'salreadyTherecompares against it (source === 'env' || storeEnrolled), so the false race no longer happens. The RUNBOOK now says to checkstoreEnrolledbefore you drop a subject from the settings. - suggestion,
untilbound (c16317c): fixed. The server andparseUntilboth refuse values more than 366 days ahead, so epoch milliseconds are refused. The docs and openapi are updated. - suggestion, unreadable members.json (daf2f0c, f77cfa2, ddc5aad): fixed.
MembersStore.membershipNowreads 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 366dis 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); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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".
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
left a comment
There was a problem hiding this comment.
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:
MembersStore.doc()returns the sharedthis.cacherather than the doc the call read, so a concurrent reader can roll back the cache and a laterchange()writes over newer changes.redact-provenance.pydeletes 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-planemembers.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
left a comment
There was a problem hiding this comment.
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).
| `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 |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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).
|
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 && |
There was a problem hiding this comment.
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> { |
There was a problem hiding this comment.
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) => { |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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).
| // 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'); |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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 ?? []); |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
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]>
|
Main (ec0f840) merged in, with one design change. This round makes three changes:
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
left a comment
There was a problem hiding this comment.
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).
| // 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'); |
There was a problem hiding this comment.
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 => |
There was a problem hiding this comment.
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> = { |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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) => { |
There was a problem hiding this comment.
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 }, |
There was a problem hiding this comment.
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}`, |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
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[] { |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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]>
|
Follow-up to the review at 2861a3c, with main (d227d41) merged in. Each point has its own commit:
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
left a comment
There was a problem hiding this comment.
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.isMembersDocchecks thatmembersis a plain object and that each entry is a Member under its own subject, with a booleanenrolled, arolesarray of admin grants, andsince/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 missingrolesand 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.
policyLockruns the read, the widening check, the narrowed-build scan andstore.setunder 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
holdPinnedWorkerreadsmembershipNow. 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]!; |
There was a problem hiding this comment.
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]>
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:
/v1/subjectsroutes, on both profiles;membersprovenance stream;github:<id>andoidc:<sub>, adapted to feat: generic OIDC identity provider (w3id) behind the login seam #701's identity providers.sbx admin subjects: list, enroll, unenroll,grant --until, revoke.409 admin_granted), plus the design's note that a members record is an attempted change.Notes for review:
SH_ADMIN_SUBJECTSchanges it. Subjects named in the settings can't be changed through the API (409 bootstrap_subject).mocactl sbx loginon an OIDC deployment isn't verified here; the tests useoidc:subjects directly.Tests on the tip:
tscis clean, and no shell script changes.29 files, +1,896 / -37, counted against #760's tip.
Assisted-By: Claude Code