Skip to content

feat(control-plane): record template provenance in a hash chain, verifiable offline - #756

Merged
pdettori merged 2 commits into
rossoctl:mainfrom
webchang:pr/i6-provenance
Nov 13, 2026
Merged

pdettori merged 2 commits into
rossoctl:mainfrom
webchang:pr/i6-provenance

Conversation

@webchang

Copy link
Copy Markdown
Member

Closes #730.

What it adds:

  • The provenance store: an append-only hash chain per stream, with export and verifyExport.
  • A stdlib-only verifier: deploy/sbx/template-onboarding/verify-provenance.py, which checks an export offline: each record's hash, the chain links and the stream heads.
  • A redaction tool.
  • The sandbox-record hooks, inert for now.

Nothing is recorded yet. The hooks only take effect once the template store (#736) opens a store from SH_PROVENANCE_DIR, so merging this changes no behavior today.

How to verify:

  • pnpm -C packages/control-plane test -- provenance sandbox-handlers: 51 passed. The full control-plane suite with Redis: 1,222 passed, 3 skipped (the vault live test).
  • tsc --noEmit is clean.
  • python3 deploy/sbx/template-onboarding/verify-provenance.py <export> on an export.

9 files, +1,536 / -2, most of them tests.

Assisted-By: Claude Code

…fiable offline

Add an append-only provenance store to the control plane: one hash
chain per stream (`policy`, `template/<id>`), kept in a directory on the
control plane's persistent volume, exportable as one JSON document and
verifiable offline with the Python standard library alone.

- provenance.ts: ProvenanceStore (one file per record named by the
  sha256 of its canonical JSON, one head per stream, cited documents
  under blobs/; a record is written before its head moves, appends to
  a stream are serialized, the directory is checked writable at start),
  canonicalJson, export() (moca-provenance-export/1) and verifyExport.
  Record kinds: policy, create, gate, build, check, activate,
  deactivate, tag, visibility, owner, retire, reject, use, sandbox,
  session.
- sandbox-handlers.ts: with deps.provenance set, a sandbox's create, its
  delete, and its expiry (once, from the janitor's sweep) are recorded
  as `sandbox` records on its template's chain. Without a store nothing
  is recorded and no behavior changes; main.ts does not open a store
  yet (that comes with the template store, rossoctl#736, which shares the directory).
- deploy/sbx/template-onboarding/verify-provenance.py: the same checks
  as verifyExport, plus --head to compare a head kept elsewhere.
  redact-provenance.py: rewrites one stream from its first match, moves
  the head and logs counts only; dry run by default.
- Tests run the Python verifier on the same exports as verifyExport,
  cover tampering, concurrent appends, restart continuity and
  redaction, and the sandbox span on its template's chain.
- Docs: the provenance section (§7) of the template lifecycle design.

Refs rossoctl#730

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

CodeQL's file-system race rule flagged writeOnce(): after an exclusive open failed with EEXIST, it
read the existing file by path to compare the bytes. writeOnce now writes the bytes to a temp file in
the same directory (exclusive create, fsync), puts it at the record's name with link(2), which is
atomic and fails with EEXIST, and on EEXIST reads the existing file through its own handle (O_RDONLY |
O_NOFOLLOW) to compare, never by a second lookup of the path. The temp file is always removed. As a
side effect a crash mid-write can no longer leave a torn file under a record's name.

Test: a file under a blob's name with other bytes is refused and left as it is, and no temp file is
left behind in blobs/ or records/.

Refs rossoctl#730

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.

Clawgenti Code Review

Summary

Solid foundation: canonical JSON is restricted so the TS and stdlib-Python implementations can agree, and the test suite runs the Python verifier against the same exports. Records are written once (temp + fsync + link) before the head moves, appends are serialized per stream, and the sandbox hooks are inert without a store, so merging changes no behavior today. No must-fix issues. Three suggestions inline: one is a redaction-tool gap I reproduced, two are about the hooks before #736 turns them on.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane provenance store, sandbox handlers), Python (verifier, redaction tool), tests, docs/spec
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing

All checks pass. Ready for human review.

Verified by: a throwaway probe that builds a 3-record template/t1 chain (create → activate → sandbox with lease = the activate digest) and runs redact-provenance.py --apply on a match in the create record. I also fed the Python verifier a lone-surrogate record; it rejected it, as verifyExport does. I deleted the probes afterwards.

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

if hits and i >= hits[0]:
old_files.append(os.path.join(store, "records", (("sha256:" + sha(canonical(r).encode()))[7:]) + ".json"))
r = dict(scrub(r, pats))
r["prev"] = prev

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 redaction rewrites prev but leaves digest references inside bodies pointing at records it renamed. Probe: chain create → activate → sandbox (lease = the activate digest), redact a match in create. The activate digest goes from sha256:207b5f2d… to sha256:180e9576…, the sandbox record still says lease: sha256:207b5f2d…, and that file is deleted (exists: False). The same applies to check.body.policy when a policy record is redacted, and to gate.body.record_sha256 when a blob holds the matched text. Blobs are never scrubbed, so the secret survives in blobs/. verifyExport does not check lease yet, so this passes verification today. Suggested fix: keep an old→new digest map while rewriting and substitute it in bodies (or refuse when a rewritten digest is cited), and report or scrub matching blobs. Why now: the spec says the lease is "the activate record's digest", and the activation work will rely on that reference resolving.

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 runs after the sandbox has been stored and audited, and an append failure (a full or read-only volume, a malformed head) turns a successful create into a 5xx while the sandbox exists. A retry then hits name_conflict. The DELETE path has the same shape. That is inert today, but it matters once #736 opens a real store. Suggested fix: decide explicitly. Either record best-effort (log, like auditBestEffort), or write the record before the store commit so a failure leaves nothing behind. Whichever you choose, add a test with a store whose append throws.

for (const r of expired) byTemplate.set(r.template, [...(byTemplate.get(r.template) ?? []), r]);
for (const [template, rs] of byTemplate) {
const ended = new Set(
(await deps.provenance.chain(`template/${template}`))

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: recordExpiries runs in the janitor sweep for every template with an expired sandbox. It walks the template's entire chain with chain(), which reads and re-hashes every record file, and it does this on every sweep until retention evicts the record. A long-lived template accumulates two records per sandbox forever, so the sweep cost grows without bound. Suggested fix: keep a small per-template index of terminated sandbox ids (or the last scanned head + seq, and walk only the new records), or record expiry in the sandbox store, which is already being read 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.

Summary

This adds an append-only provenance store with one hash chain per stream, an offline verifier in TS and in stdlib Python (cross-checked by a test), a redaction tool, and sandbox create/end hooks that stay inert until #736 opens a store. The core chain and canonical-JSON logic looks right, and the two verifiers agree. No blockers, because nothing is recorded yet. Before #736 enables the store, though: the hooks turn a provenance failure into a 500 after the sandbox state has already changed (and can fail the janitor's read), the janitor re-walks the full chain on every sweep, the write path doesn't fsync directories (the crash guarantee depends on it), and redaction leaves digest references in record bodies pointing at deleted records.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane), Python, Docs/spec
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (all 17 checks; CodeQL's fs-race alert on ca821cd was addressed by 1100f09's tmp+link rewrite)

On clawgenti's three comments at this head (sandbox-handlers.ts:259 and :190, redact-provenance.py:133): I agree with all three and won't repeat them inline. A few things they don't cover:

  • :259: on DELETE, a failed append also loses the terminated record for good, because the sandbox is already marked deleted and nothing retries it. A test with a failing store would pin whichever behaviour you pick.
  • :190: the "already ended?" check and the append aren't serialized, so two janitor sweeps running at once can both append expired for the same sandbox. Doing the check inside queue.run fixes that, and fits with the index clawgenti suggests.
  • :133: the verifier doesn't check digest references inside bodies either, so a chain left with dangling references after redaction still verifies. Either redaction should remap them (old→new digest map) or the verifier should flag them.

if (v.state === 'ready') live.push({ wsk: v.wsk, wrk: v.worker });
else terminated.push({ wsk: v.wsk, wrk: v.worker, terminatedAt: v.terminatedAt! });
}
await recordExpiries(deps, all, now);

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: If recordExpiries throws, GET /v1/janitor/sandboxes returns 500 and the janitor frees no disk (SBX0 §8.3). Expiry records are a side effect of this read, so it shouldn't depend on them. Catch and log here, or run it after the response is built.

await fh.close();
}
try {
await link(tmp, path);

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: There are two durability and portability gaps here, both on the write path the spec's crash guarantee depends on (§7.2: "a crash leaves an orphan record, never a head naming a missing one").

  1. Neither the records/ directory nor the heads/ directory is fsync'd after link/rename. After a power loss, ext4 and xfs can persist the head's rename without the record's new directory entry. Opening the directory and calling sync() on it after the link, before writeReplace moves the head, closes that gap.
  2. link needs hard-link support. Some RWO volume types don't have it (e.g. SMB/CIFS-backed CSI), and there every append fails with EPERM/ENOTSUP. The constructor's accessSync check passes on those volumes anyway. Probing a link once at construction would make such a volume fail at start, as the doc comment promises.

doc = json.load(open(cat_path)) if os.path.exists(cat_path) else None
cat_hits = 0
if doc:
cat_hits = sum(1 for p in pats if p.search(json.dumps(doc)))

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 catalog is matched against json.dumps(doc), which defaults to ensure_ascii=True, but scrubbed value by value. A pattern with a non-ASCII character (a name, say) never matches the \uXXXX-escaped dump, so the entry is reported clean and left in place. A pattern that only matches JSON syntax or escapes (\") reports matches and then changes nothing. The record path (canonical(r) vs scrub) has the same mismatch. scrub also skips dict keys, so a secret used as a label key survives. Matching on each string value (and key) the way scrub walks them would make the count and the rewrite agree.

@pdettori
pdettori merged commit 1100f09 into rossoctl:main Nov 13, 2026
17 checks passed
webchang added a commit that referenced this pull request Nov 14, 2026
The host agent stands on both parents: the template store and self-serve create (#766, with #760 and
#756) and the template build tooling (#740's branch, with #757). No conflicts.

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

Record template provenance in a hash chain, verifiable offline

5 participants