durability 3a: born-HA hosts publish their secrets sealed (#477)
Region HA published an instance's secrets raw: <host>.env as the raw env
item, and instance.key and report.token as file entries, including in
the release's final publish, which synced the whole tree with no skip.
They now leave the box only sealed (durability spec §5.4).
- ExecBackend.EscrowKey, CARLOS_SECRETS_KEY parsed by the agent
(haEscrowKey; unset or unparseable is logged and nil). sealerFor binds
an ItemSealer to {RouteAccount(rt), rt.App} and the host. Without a key
newHostFiles errors: openHostFiles and haSecretsReady refuse before any
read, stageWakeFiles and stageKeptFiles log and stage nothing.
- hostFiles carries the sealer and the classifier's skip
(pubclass.FilesDirSkip). syncFiles takes no skip and always passes
f.skip, so the snapshot and Final publish only App paths. haTrio,
trioOnly and snapshotSkip are gone; the platform pass syncs no tree.
A directory named instance.key or report.token at the files root is
now skipped too (the classifier judges by name).
- stageItemsLocked stages each of pubclass.SealedRels through
StageSealed (read beneath the instance directory, 1 MiB cap; absent:
the sealed item is deleted), then DropRawSecrets on the constant raw
trio names, so the first sealed commit drops the raw env item and
tombstones raw trio entries. Manifest only: no object is deleted.
- envAcknowledged compares the sealed env item's keyed digest
(SealedAcknowledged).
- restoreFilesClean opens each sealed trio item with ReadSealed and
writes it 0600 into the restore directory before the rename, over any
raw entry of that name; the env comes from the sealed env item, else
the raw env item an older box wrote. A tombstoned raw entry is never
restored.
Tests rewritten to read the sealed items, plus witnesses through the
real backend and store: no object under the prefix holds a secret's
plaintext; Final publishes only a.txt live; the first sealed commit
drops the raw items and both old objects still read; restores from
sealed and from older raw manifests; a deleted sealed key is not
resurrected from the raw entry; no key refuses and writes nothing.
A first wake now writes three objects (sealed env, cutover marker,
wake state) and the manifest.
Census: claims for runAgent, sealerFor (new), newHostFiles,
openHostFiles, stageKeptFiles, stageWakeFiles, haSecretsReady and
restoreFilesClean appended; census-propose re-run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/notes/census-durability-3a-escrow-claims.md+8 −0docs/superpowers/notes/census-proposal-durability-3a-escrow.md+24 −3internal/activator/backend_exec.go+5 −0internal/activator/hafiles.go+110 −65internal/activator/hafiles_test.go+177 −22internal/activator/harelease_test.go+14 −6internal/activator/hasecrets.go+24 −18internal/activator/hasecrets_test.go+47 −7internal/activator/hawake.go+63 −6internal/activator/hawake_test.go+127 −3internal/host/agent.go+16 −0internal/host/hawake_wiring_test.go+26 −2internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-durability-3a-escrow.tsv+19 −3
Intent
<task-notification> <task-id>adcec79dd7913d651</task-id> <tool-use-id>toolu_01VTcyduriHKs4qERMUdM336</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/adcec79dd7913d651.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: sealed hostfiles items" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE Commit: e9a46567 durability 3a: sealed platform items in hostfiles Tests: all pass. The 9 new hostfiles tests (the brief's 7, the `EnvItem` == "host.env" pin, a bad-input test) and the full hostfiles package; `TestOnlySealKeyForBuildsSealers`, which fails without the new row (naming `ItemSealer).seal`), restored; the provision census and root-deps tests; the activator guard tests; vet, gofmt and the darwin and windows builds. Concerns: - The census needs a reviewer verdict on #280 at Task 8. The new unit is `hostfiles/sealed.go:ReadSealed`; the "+file:Open" it is flagged for is really `appconfig.Open`, which decrypts in memory and opens no file. The hostfiles envelope was also re-pinned, the claims line added and the seal is now 0da3b2b5. `census-card` is clean. - `CutoverItem` is declared in Task 2's `sealed.go`. Task 5 should use it, not declare it again. - Choices beyond the brief, all stricter: - `StageSealed` refuses a path that belongs to another host. - `ReadSealed` refuses a v1 envelope even when the entry is marked "v2". - The cutover marker is staged after the item, and whenever it is missing. - A zero `ItemSealer{}` is refused everywhere; it would have made `ReadSealed` panic. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/durability-3a/.superpowers/sdd/2026-10-30-durability-step3-escrow-fence-restore/task-2-report.md</result> <usage><subagent_tokens>157044</subagent_tokens><tool_uses>46</tool_uses><duration_ms>702334</duration_ms></usage> </task-notification>
<task-notification> <task-id>a2cac82d5423f0ed2</task-id> <tool-use-id>toolu_019mQnWWNduzPcLSAMh22qq1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/a2cac82d5423f0ed2.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ Spec compliant. I checked the brief file by file. - `manifest.go` adds the two additive `Entry` fields with the right JSON tags (`manifest.go` diff, +7). - `sealed.go` has every listed symbol with the brief's signatures: `SealedEnvItem`, `ItemSealer`, `NewItemSealer`, `MAC`, `seal`, `StageSealed`, `ReadSealed`, `SealedAcknowledged` and `DropRawSecrets`. - The guard row and its comment are verbatim at `sealkey_guard_test.go:+70-73`. - All seven brief tests are present, with the `countingStore` the brief asked for (`sealed_test.go:398`). - ✅ Controller's extra item is present. `TestEnvItemIsTheClassifiersRawEnvItem` (`sealed_test.go:687-696`) asserts `pubclass.IsRawSecretItem(PlatformItems(), EnvItem)` is true. - Per the report, that predicate matches only pubclass's unexported `rawEnvItem` (`pubclass.go:86`, compared at `:267`), so this pins `EnvItem == "host.env"`. - It also asserts the predicate is false for `SealedEnvItem`, the two trio names, `CutoverItem` and `WakeItem`. - I did not open `EnvItem`'s definition, so I did not confirm the string value directly. - ⚠️ Cannot verify from the diff, for the controller to check: - The `TestOnlySealKeyForBuildsSealers` pass/fail pair (row present, row removed). I relied on the report. - `EnvItem` is not defined in this diff. - The census re-pin (seal `0da3b2b5…` and the plan14 chain line) would need `make census-card`. - The report says it did not advance the amadan task for Task 2, so that is still for the controller to do. ### Strengths - **Tight funnel.** `seal` (`sealed.go:225`) is the only `SealBound` call, and the guard row names exactly it. - **Sound MAC.** It uses length-prefixed fields so no two field splits collide (`sealed.go:213-221`). It uses an HKDF key separate from the sealing key, `hmac.Equal` for comparisons, and covers account, app, host and item. - **No-op path costs nothing.** An unchanged item takes no Put, no Get and no sequence number (`sealed.go:259`). The test asserts all three (`sealed_test.go:543`), and also that a changed key reseals. - **`ReadSealed` goes beyond the brief and the extras are correct.** - It refuses a v1 envelope via `EnvelopeBound` (`sealed.go:313`). `Open` would accept a v1 envelope under any binding, so this closes a real hole. - It checks the MAC after opening, which stops an envelope being moved to another item or host. - Tests cover both cases, including "v1 marked v2 with a correct MAC" (`sealed_test.go:608-625`). - **No panic on a zero sealer.** `usable()` guards all three entry points (`sealed.go:206`), because `&ItemSealer{}` can be built outside the package and `Open` would panic on a nil key. The zero sealer is tested in all three. - **`StageSealed` also refuses a `SealedRel` from another host.** `SealedPath(Nested, s.host, r.Rel())` must equal `r` (`sealed.go:252`). - I checked `SealedRel{rel, item}` (`pubclass.go:186`) and that rels are the same in both layouts (`pubclass.go:211-213`). So fixing `Nested` here cannot wrongly refuse a Flat-layout verdict. - The zero `SealedRel` is refused too. - **`DropRawSecrets` is atomic and touches no object.** It validates every path first (`sealed.go:344-353`). The test pins exactly one Put, zero Gets and zero Deletes, and that the old objects still read back. - **Additive wire shape.** A manifest without sealed items writes neither new key (`sealed_test.go:766`), and a manifest with them passes `decode`, `checkManifest`, `ValidateManifest` and `Restore`. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) - `sealed.go:240-242`: the doc comment says "(Task 5)", a plan-internal reference that will read oddly in the code. The report says it was kept verbatim from the brief. I would drop it at the whole-branch pass. - `sealed.go:361-367`: `DropRawSecrets` tombstones any named non-deleted entry, not only raw secret names. This is deliberate, and the brief's signature is general. Task 3 passes the two trio names, so it is safe today. If Task 3 ever passes a user-derived path, this becomes a delete-anything-in-the-manifest primitive. A reviewer on Task 3 should check that its call sites pass only constants. - `sealed.go:274-280`: the cutover marker is staged even when the sealed item was a no-op. This is the intended repair on retry. The report says it is tested only indirectly, and I did not see a test that stages the item, loses the marker, and re-stages. Coverage gap only. - `CutoverItem` is declared in Task 2's `sealed.go`, but Task 5's plan text also lists it under "Produces". The report flags this, and Task 5 must reuse the constant. ### Assessment **Task quality:** Approved **Reasoning:** Every brief item is present and behaves as specified. The extras (v1 refusal, host-mismatch refusal, zero-sealer guard, MAC-binds-item) all tighten the escrow and are tested. I found no defects, only the minor notes above.</result> <usage><subagent_tokens>77643</subagent_tokens><tool_uses>9</tool_uses><duration_ms>49747</duration_ms></usage> </task-notification>
Attributed to this commit: 25.0 g CO₂e (3,232,198 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on durability-3a-escrow, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/notes/census-durability-3a-escrow-claims.md b/docs/superpowers/notes/census-durability-3a-escrow-claims.md| index 6c329079a..3426be188 100644 |
| --- a/docs/superpowers/notes/census-durability-3a-escrow-claims.md |
| +++ b/docs/superpowers/notes/census-durability-3a-escrow-claims.md |
| @@ -5,3 +5,11 @@ |
| internal/layout/inventory.go:Inventory durability 3a Task 1: new. One os.ReadDir of the host's inventory root, provision.InstanceDir(dataDir, host) nested or dataDir flat, after refusing a host that fails controlname.ValidHostShape and a layout that is neither flat nor nested; reads only the listing's names and types (DirEntry.IsDir), opens and follows nothing; flat ownership is the extras scan's own (hostEntries over knownHosts); each top-level name is classified by pubclass.Of, a pure function of the name. A missing directory is an empty inventory. No caller in this task; later tasks call it from the publisher. |
| internal/layout/plan.go:NestedPlatformNames durability 3a Task 1: now a one-line wrapper for pubclass.NestedPlatformNames, which builds the same set (byte-identical, checked before and after) from pubclass.FileBases and the same instancectl/instancekey names, without nestedFiles or rawInstanceDir; it never read anything, and reads nothing now |
| internal/hostfiles/sealed.go:ReadSealed durability 3a Task 2: new. Reads one sealed platform item of a files manifest the caller already loaded: the object at exactly the key the entry names, through the existing fetch (checkEntry: origin admitted, key shape, sha256 and size verified), only for an entry marked sealed "v2". The "Open" the scanner sees is appconfig.Open, an in-memory AES-GCM decryption of the fetched bytes, not a file open: no filesystem path is opened, read or followed. It refuses a v1 envelope (appconfig.EnvelopeBound), and after opening under the caller-supplied key and (account, app) binding it checks the HMAC digest over account, app, host and item against the entry. Writes nothing. No production caller in this task; Tasks 3 and 4 call it from the activator. |
| +internal/host/agent.go:runAgent durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. |
| +internal/activator/hafiles.go:ExecBackend.sealerFor durability 3a Task 3: new. Builds the host's hostfiles.ItemSealer from the backend's EscrowKey (the box's own CARLOS_SECRETS_KEY, set once by runAgent) and the binding {release.RouteAccount(rt), rt.App} for rt.Host (NewItemSealer validates the account, app and host shape); nil key is an error. Pure in memory: opens, reads and writes nothing. |
| +internal/activator/hafiles.go:ExecBackend.newHostFiles durability 3a Task 3: now also sets the publisher's sealer (sealerFor(rt); its error is returned and nothing is built) and its skip, pubclass.FilesDirSkip(Nested, rt.Host), a pure function of the name, so every tree pass publishes only App paths and never the trio raw. Still no I/O; the new +registry:Host and +whole:Route sites are the sealer's and the classifier's arguments. |
| +internal/activator/hafiles.go:ExecBackend.openHostFiles durability 3a Task 3: asks sealerFor before hostfiles.Open, so a box without an escrow key refuses before it reads the manifest; newHostFiles's error is returned. The same manifest GET otherwise; the new +whole:Route site is sealerFor's argument. Opens nothing new. |
| +internal/activator/hafiles.go:ExecBackend.stageKeptFiles durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. The same baseline read; nothing new opened or read. |
| +internal/activator/hafiles.go:ExecBackend.stageWakeFiles durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. No read, as before. |
| +internal/activator/hasecrets.go:ExecBackend.haSecretsReady durability 3a Task 3: asks sealerFor before its own hostfiles.Open (a box without an escrow key fails the launch before any read), and newHostFiles's error fails the launch. envAcknowledged now compares the sealed env item's keyed digest (hostfiles.SealedAcknowledged, no read) instead of the raw env item's SHA-256. The publish it triggers stages the trio sealed: <host>.env, <host>/instance.key and <host>/report.token are each read with instancefs.ReadBeneathLimitOrAbsent beneath the instance directory (openat2, no symlink, regular files only, 1 MiB cap), the same reader the env already used, then sealed in memory; nothing else is opened. |
| +internal/activator/hawake.go:ExecBackend.restoreFilesClean durability 3a Task 3: after the unchanged RestoreRootBaseline into <host>.restore, each sealed trio item the manifest holds (instance.key.sealed, report.token.sealed) is fetched and opened with hostfiles.ReadSealed (key, sha256, v2 envelope, binding and MAC checked) and written with instancefs.WriteAtomic (openat2 directory, no symlink, O_EXCL temp, rename, 0600) into the restore directory this function created, then that directory is synced; then the same no-replace rename. The env file comes from the sealed env item through ReadSealed when present, else from the raw env item as before, written as before. The source is still the host's files manifest in the hibernate bucket; the destinations are the same restore directory and env file; no new path is opened, followed or named from input; the sealer (sealerFor) is built only when a sealed item is present. |
diff --git a/docs/superpowers/notes/census-proposal-durability-3a-escrow.md b/docs/superpowers/notes/census-proposal-durability-3a-escrow.md| index 8eb0ab6ea..39c7af482 100644 |
| --- a/docs/superpowers/notes/census-proposal-durability-3a-escrow.md |
| +++ b/docs/superpowers/notes/census-proposal-durability-3a-escrow.md |
| @@ -1,17 +1,38 @@ |
| # Census approval: durability-3a-escrow |
| -Ruling `census-ruling-durability-3a-escrow`. The independent reviewer approves or rejects every change below, 3 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| +Ruling `census-ruling-durability-3a-escrow`. The independent reviewer approves or rejects every change below, 4 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| -Envelopes re-pinned: `internal/activator`, `internal/hostfiles`, `internal/layout`, `internal/layout/pubclass`. |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/agent.go` `runAgent` | body | unchanged (6) | durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. | |
| +| `internal/activator/hafiles.go` `ExecBackend.newHostFiles` | sites | +registry:Host, +whole:Route | durability 3a Task 3: now also sets the publisher's sealer (sealerFor(rt); its error is returned and nothing is built) and its skip, pubclass.FilesDirSkip(Nested, rt.Host), a pure function of the name, so every tree pass publishes only App paths and never the trio raw. Still no I/O; the new +registry:Host and +whole:Route sites are the sealer's and the classifier's arguments. | |
| +| `internal/activator/hafiles.go` `ExecBackend.openHostFiles` | sites | +whole:Route | durability 3a Task 3: asks sealerFor before hostfiles.Open, so a box without an escrow key refuses before it reads the manifest; newHostFiles's error is returned. The same manifest GET otherwise; the new +whole:Route site is sealerFor's argument. Opens nothing new. | |
| +| `internal/activator/hafiles.go` `ExecBackend.stageKeptFiles` | sites | +registry:Host | durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. The same baseline read; nothing new opened or read. | |
| +| `internal/activator/hafiles.go` `ExecBackend.stageWakeFiles` | sites | +registry:Host | durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. No read, as before. | |
| +| `internal/activator/hasecrets.go` `ExecBackend.haSecretsReady` | sites | +whole:Route | durability 3a Task 3: asks sealerFor before its own hostfiles.Open (a box without an escrow key fails the launch before any read), and newHostFiles's error fails the launch. envAcknowledged now compares the sealed env item's keyed digest (hostfiles.SealedAcknowledged, no read) instead of the raw env item's SHA-256. The publish it triggers stages the trio sealed: <host>.env, <host>/instance.key and <host>/report.token are each read with instancefs.ReadBeneathLimitOrAbsent beneath the instance directory (openat2, no symlink, regular files only, 1 MiB cap), the same reader the env already used, then sealed in memory; nothing else is opened. | |
| +| `internal/activator/hawake.go` `ExecBackend.restoreFilesClean` | sites | +whole:Route | durability 3a Task 3: after the unchanged RestoreRootBaseline into <host>.restore, each sealed trio item the manifest holds (instance.key.sealed, report.token.sealed) is fetched and opened with hostfiles.ReadSealed (key, sha256, v2 envelope, binding and MAC checked) and written with instancefs.WriteAtomic (openat2 directory, no symlink, O_EXCL temp, rename, 0600) into the restore directory this function created, then that directory is synced; then the same no-replace rename. The env file comes from the sealed env item through ReadSealed when present, else from the raw env item as before, written as before. The source is still the host's files manifest in the hibernate bucket; the destinations are the same restore directory and env file; no new path is opened, followed or named from input; the sealer (sealerFor) is built only when a sealed item is present. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/host`, `internal/hostfiles`, `internal/layout`, `internal/layout/pubclass`. |
| Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added |
| +- `internal/activator/hafiles.go` `ExecBackend.newHostFiles`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: builds a hostFiles publisher for rt (its instance paths from pathsFor(rt), rt.Host, the backend's registry, the 1 s platform and 15 min snapshot cadences); +registry:Host, +whole:Route; no I/O |
| +- `internal/activator/hafiles.go` `ExecBackend.openHostFiles`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the entry's files publisher: refuses without a FilesStore or outside the nested layout, takes the one this wake's restore staged, else hostfiles.Open on <hibernate prefix>/files/0/ (one GET of the manifest from the hibernate bucket, the scanner's +file:Open); +registry:Host x2, +whole:Route x2; the manifest is written by the agents of the boxes that hold the host, through the same files store |
| +- `internal/activator/hafiles.go` `ExecBackend.stageKeptFiles`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: on a kept wake, reads the manifest baseline the release kept beside its local record (<db>.release.files.json via readFilesBaseline, capped at 32 MiB, O_NOFOLLOW, regular files only) and stages a publisher on it only when its revision (Gen, which carries the body's SHA-256) equals the files_gen in the lock's release marker; the file is on ground the tenant can write, and anything that does not match stages nothing, so the entry re-reads the manifest from the store; it never decides the keep; +registry:Host x4, +whole:Route x2 |
| +- `internal/activator/hafiles.go` `ExecBackend.stageWakeFiles`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: opens a publisher on a manifest baseline the HA restore already holds (hostfiles.OpenBaseline, no read) and keeps it for the wake's entry; without a FilesStore it stages nothing; +registry:Host x3, +whole:Route |
| +- `internal/activator/hasecrets.go` `ExecBackend.haSecretsReady`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: before an HA host's launch, checks that env, the bytes the launch captured (captureLaunchEnv; a new parameter, final fix F2), has the SHA-256 of the committed manifest's env item (envAcknowledged, which now reads no file); else publishes the platform items (env, trio, wake state) through the wake's, the entry's or its own publisher (hostfiles.Open, the +file:Open site: one manifest GET) and checks again, so an env replaced after the capture is committed as other bytes and fails the launch; it no longer classifies the host itself (launchEnvLayer has); every error fails the launch; +file:Open, +registry:Host x3, +whole:Route |
| +- `internal/activator/hawake.go` `ExecBackend.restoreFilesClean`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: restores the HA host's published files into a fresh <host>.restore directory beneath the instance data dir (instancefs, no link followed), renames it into place without replacing anything, writes the manifest's env item as <host>.env (instancefs.WriteAtomic, 0600) and imports the manifest's wake state into the registry (hostfiles.ImportWake, then the class for restoredReplication); the source is the host's files manifest in the hibernate bucket, written by the agents of the boxes that held the host; every failure fails the wake; +registry:Host, +whole:Route x2 |
| + |
| New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| +- new `internal/activator/hafiles.go:ExecBackend.sealerFor`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen |
| - new `internal/hostfiles/sealed.go:ReadSealed`: reads +file:Open; written legacy, accepted-legacy, frozen |
| - new `internal/layout/inventory.go:Inventory`: reads +file:ReadDir; written legacy, accepted-legacy, frozen |
| - quiet `internal/layout/plan.go:NestedPlatformNames`: reads nothing now; retired while it reads nothing (or its row keeps no sites) |
| -Seal: `eaeb153ab7a7a849edc9c6e92f2ac5c709c6e39044a647971cf1fa5ebcb660c8` → `0da3b2b5686a83332323f61821f53b7f3070135f4ca54005946c4c4b1ee70f09`. |
| +Seal: `eaeb153ab7a7a849edc9c6e92f2ac5c709c6e39044a647971cf1fa5ebcb660c8` → `bd11e15cc2b64af3aa78c88e91dc151cfe3096ac671687ca8d015bfb8c331542`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-durability-3a-escrow.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 3bde4f030..f718ceb06 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -4,6 +4,7 @@ package activator |
| import ( |
| "context" |
| + "crypto/ecdh" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -334,6 +335,10 @@ type ExecBackend struct { |
| // host's files are published (<hibernate prefix>/files/0/). Nil: an HA |
| // restore that needs the files fails. |
| FilesStore release.Store |
| + // EscrowKey is CARLOS_SECRETS_KEY parsed: what this box seals an |
| + // instance's secrets to (its public half) and opens them with. Nil: HA |
| + // publication refuses, and escrow is not ready (Task 4). |
| + EscrowKey *ecdh.PrivateKey |
| // Lifetimes is the box's lifetime index (provision.LifetimeIndex), |
| // filled by the reconcile pass and read by the HA classification |
| // before every wake. Nil: every provisioned instance reads its record. |
diff --git a/internal/activator/hafiles.go b/internal/activator/hafiles.go| index c93543527..3b5a7b411 100644 |
| --- a/internal/activator/hafiles.go |
| +++ b/internal/activator/hafiles.go |
| @@ -12,20 +12,30 @@ import ( |
| "sync" |
| "time" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/hostfiles" |
| "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/layout/pubclass" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // Region HA P1a, files publication (spec §8.2): while an HA host is awake |
| // its entry owns one publisher of the host's files, under its hibernate |
| -// prefix's files/0/. The H6 trio (instance.key and report.token at the |
| -// root of the files directory, and <host>.env as the manifest's env item) |
| -// and the wake state publish within about a second of a change, on every |
| -// plan; the app's files publish as a snapshot every |
| -// files_snapshot_interval (snapshot only in P1a). At sleep the entry stops |
| -// the publisher, joins it, and makes one final full publish (Final), whose |
| -// completeness decides whether the release marker can say clean. |
| +// prefix's files/0/. The H6 trio (<host>.env, and instance.key and |
| +// report.token at the root of the files directory) and the wake state |
| +// publish within about a second of a change, on every plan; the app's |
| +// files publish as a snapshot every files_snapshot_interval (snapshot only |
| +// in P1a). At sleep the entry stops the publisher, joins it, and makes one |
| +// final full publish (Final), whose completeness decides whether the |
| +// release marker can say clean. |
| +// |
| +// The trio never leaves the box raw (durability 3a, #477): each goes as a |
| +// sealed platform item (hostfiles.StageSealed), sealed to the box's own |
| +// CARLOS_SECRETS_KEY and bound to the instance's account and app, and |
| +// every tree pass skips whatever the classifier (pubclass) does not call |
| +// App, so no pass publishes the trio as bytes. A box without the key |
| +// publishes nothing. |
| const ( |
| // haPlatformEvery is the trio's and the wake state's cadence. |
| @@ -37,20 +47,11 @@ const ( |
| haEnvReadLimit = 1 << 20 |
| ) |
| -// haTrio is the H6 trio's members inside the files directory: the instance |
| -// key and the report token, at its root (hostrelocate.InstanceKeyPath). |
| -// The third, <host>.env, lives beside the directory and publishes as the |
| -// env item. |
| -var haTrio = map[string]bool{"instance.key": true, "report.token": true} |
| - |
| -// trioOnly is the platform pass's skip: everything but the trio, so a pass |
| -// lists the files directory's root and reads nothing else. |
| -func trioOnly(rel string, isDir bool) bool { return isDir || !haTrio[rel] } |
| - |
| -// snapshotSkip is the snapshot pass's skip: the trio, which the platform |
| -// pass owns. A snapshot runs beside platform passes, so it neither stages |
| -// nor tombstones a trio file one of them may be publishing. |
| -func snapshotSkip(rel string, isDir bool) bool { return !isDir && haTrio[rel] } |
| +// rawSecretEntries are the trio's raw entries an older box published at the |
| +// files directory's root. The first sealed commit tombstones them in the |
| +// manifest (DropRawSecrets); no object is deleted. Constant names only: |
| +// DropRawSecrets tombstones whatever it is handed. |
| +var rawSecretEntries = []string{"instance.key", "report.token"} |
| // syncFilesAt is the one sync of the files tree (a test seam). |
| var syncFilesAt = hostfiles.SyncDirAt |
| @@ -66,6 +67,11 @@ type hostFiles struct { |
| paths instancePaths |
| host string |
| reg *registry.Registry |
| + // seal seals and opens the host's secrets (sealerFor); skip is the |
| + // classifier's verdict on the files directory: only what is App |
| + // publishes as bytes. |
| + seal *hostfiles.ItemSealer |
| + skip func(rel string, isDir bool) bool |
| platformEvery, snapshotEvery time.Duration |
| @@ -79,10 +85,25 @@ type hostFiles struct { |
| // last write, so nothing publishes once the final publish has been made. |
| var errFilesFinal = errors.New("the host's files were published for the last time") |
| +// sealerFor is the sealer of rt's secrets: bound to the route's account |
| +// and app, under the box's own key (EscrowKey). No key, or a route the |
| +// binding refuses, is an error, and nothing of the host publishes. |
| +func (b *ExecBackend) sealerFor(rt registry.Route) (*hostfiles.ItemSealer, error) { |
| + if b.EscrowKey == nil { |
| + return nil, errors.New("this box has no CARLOS_SECRETS_KEY to seal the host's secrets with; HA publication refuses") |
| + } |
| + return hostfiles.NewItemSealer(b.EscrowKey, appconfig.Binding{Account: release.RouteAccount(rt), App: rt.App}, rt.Host) |
| +} |
| + |
| // newHostFiles is rt's publisher over pub. |
| -func (b *ExecBackend) newHostFiles(rt registry.Route, pub *hostfiles.Publisher) *hostFiles { |
| +func (b *ExecBackend) newHostFiles(rt registry.Route, pub *hostfiles.Publisher) (*hostFiles, error) { |
| + seal, err := b.sealerFor(rt) |
| + if err != nil { |
| + return nil, err |
| + } |
| return &hostFiles{pub: pub, paths: b.pathsFor(rt), host: rt.Host, reg: b.Registry, |
| - platformEvery: haPlatformEvery, snapshotEvery: haSnapshotEvery} |
| + seal: seal, skip: pubclass.FilesDirSkip(pubclass.Nested, rt.Host), |
| + platformEvery: haPlatformEvery, snapshotEvery: haSnapshotEvery}, nil |
| } |
| // stageWakeFiles opens this wake's files publisher on a manifest the HA |
| @@ -99,7 +120,12 @@ func (b *ExecBackend) stageWakeFiles(rt registry.Route, base hostfiles.Baseline) |
| log.Printf("activator: %s: files: %v (the publisher reads the manifest again)", rt.Host, err) |
| return |
| } |
| - b.haWakes.setFiles(rt.Host, b.newHostFiles(rt, pub)) |
| + f, err := b.newHostFiles(rt, pub) |
| + if err != nil { |
| + log.Printf("activator: %s: files: %v", rt.Host, err) |
| + return |
| + } |
| + b.haWakes.setFiles(rt.Host, f) |
| } |
| // filesBaselinePath is where a release keeps the manifest it committed |
| @@ -171,7 +197,12 @@ func (b *ExecBackend) stageKeptFiles(rt registry.Route, gen string) { |
| log.Printf("activator: %s: files: the kept manifest is not the marker's (%v); the publisher reads it again", rt.Host, err) |
| return |
| } |
| - b.haWakes.setFiles(rt.Host, b.newHostFiles(rt, pub)) |
| + f, err := b.newHostFiles(rt, pub) |
| + if err != nil { |
| + log.Printf("activator: %s: files: %v", rt.Host, err) |
| + return |
| + } |
| + b.haWakes.setFiles(rt.Host, f) |
| } |
| // wakeFiles is the files publisher this wake's HA restore opened for the |
| @@ -197,11 +228,15 @@ func (b *ExecBackend) openHostFiles(ctx context.Context, rt registry.Route) (*ho |
| if f, ok := b.haWakes.takeFiles(rt.Host); ok { |
| return f, nil |
| } |
| + // The sealer first: a box that cannot seal reads nothing either. |
| + if _, err := b.sealerFor(rt); err != nil { |
| + return nil, err |
| + } |
| pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host)) |
| if err != nil { |
| return nil, err |
| } |
| - return b.newHostFiles(rt, pub), nil |
| + return b.newHostFiles(rt, pub) |
| } |
| // Run publishes until ctx ends: the trio and the wake state every |
| @@ -262,17 +297,15 @@ func (f *hostFiles) Run(ctx context.Context) { |
| } |
| } |
| -// PublishPlatformNow publishes the trio, the env item and the wake state |
| -// now, and commits if anything changed (nothing changed, no request). |
| +// PublishPlatformNow publishes the sealed trio and the wake state now, and |
| +// commits if anything changed (nothing changed, no request). It syncs no |
| +// tree. |
| func (f *hostFiles) PublishPlatformNow(ctx context.Context) error { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| if f.final { |
| return errFilesFinal |
| } |
| - if _, _, err := f.syncFiles(ctx, trioOnly); err != nil { |
| - return err |
| - } |
| if err := f.stageItemsLocked(ctx); err != nil { |
| return err |
| } |
| @@ -280,13 +313,13 @@ func (f *hostFiles) PublishPlatformNow(ctx context.Context) error { |
| return err |
| } |
| -// publishSnapshot is the snapshot pass: the tree but the trio, then the |
| -// platform items, committed. It is skipped when the tree's metadata |
| -// digest is the one the last complete, committed snapshot recorded (where |
| -// the digest cannot be read, it always runs). A pass that was not |
| -// complete (a file unreadable, replaced or torn, say) records nothing, so |
| -// the next snapshot runs again even if no metadata changed. The tree is |
| -// read without mu, so platform passes go on meanwhile. |
| +// publishSnapshot is the snapshot pass: the tree as the classifier admits |
| +// it (f.skip), then the platform items, committed. It is skipped when the |
| +// tree's metadata digest is the one the last complete, committed snapshot |
| +// recorded (where the digest cannot be read, it always runs). A pass that |
| +// was not complete (a file unreadable, replaced or torn, say) records |
| +// nothing, so the next snapshot runs again even if no metadata changed. |
| +// The tree is read without mu, so platform passes go on meanwhile. |
| func (f *hostFiles) publishSnapshot(ctx context.Context) error { |
| f.snapMu.Lock() |
| defer f.snapMu.Unlock() |
| @@ -300,7 +333,7 @@ func (f *hostFiles) publishSnapshot(ctx context.Context) error { |
| if derr == nil && digest != "" && digest == last { |
| return nil |
| } |
| - st, _, err := f.syncFiles(ctx, snapshotSkip) |
| + st, _, err := f.syncFiles(ctx) |
| if err != nil { |
| return err |
| } |
| @@ -325,11 +358,11 @@ func (f *hostFiles) publishSnapshot(ctx context.Context) error { |
| return nil |
| } |
| -// Final is the last publish: the whole tree and the platform items, |
| -// committed. gen is the committed revision (Publisher.Gen), the marker's |
| -// files_gen. complete holds only when the pass was complete |
| -// (SyncStats.Complete), the platform items were read and the commit |
| -// landed. A files directory that is absent is complete only while the |
| +// Final is the last publish: the tree as the classifier admits it |
| +// (f.skip, so never the trio raw) and the platform items, committed. gen |
| +// is the committed revision (Publisher.Gen), the marker's files_gen. |
| +// complete holds only when the pass was complete (SyncStats.Complete), |
| +// the platform items were read and the commit landed. A files directory that is absent is complete only while the |
| // manifest holds no file, since absence proves nothing about one it does. |
| // After Final no pass publishes. |
| func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err error) { |
| @@ -338,7 +371,7 @@ func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err e |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.final = true |
| - st, present, err := f.syncFiles(ctx, nil) |
| + st, present, err := f.syncFiles(ctx) |
| if err != nil { |
| return f.pub.Gen(), false, err |
| } |
| @@ -364,11 +397,13 @@ func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err e |
| // keeps it beside its local record (writeFilesBaseline). |
| func (f *hostFiles) baseline() hostfiles.Baseline { return f.pub.Baseline() } |
| -// syncFiles syncs the files directory (skip as SyncDirAt takes it), |
| -// opened beneath the instance directory without following a link: the |
| -// directory is the tenant's to write. present is false when there is no |
| +// syncFiles syncs the files directory with f.skip, the classifier's, so |
| +// no caller can hand it another: only App paths publish, and a path it |
| +// skips (the trio among them) is left as the manifest has it. The |
| +// directory is opened beneath the instance directory without following a |
| +// link: it is the tenant's to write. present is false when there is no |
| // files directory, and nothing is staged then. |
| -func (f *hostFiles) syncFiles(ctx context.Context, skip func(string, bool) bool) (hostfiles.SyncStats, bool, error) { |
| +func (f *hostFiles) syncFiles(ctx context.Context) (hostfiles.SyncStats, bool, error) { |
| root, err := instancefs.OpenDirBeneath(f.paths.dataDir, f.host) |
| if errors.Is(err, fs.ErrNotExist) { |
| return hostfiles.SyncStats{}, false, nil |
| @@ -377,28 +412,38 @@ func (f *hostFiles) syncFiles(ctx context.Context, skip func(string, bool) bool) |
| return hostfiles.SyncStats{}, false, fmt.Errorf("open the files directory: %w", err) |
| } |
| defer root.Close() |
| - st, err := syncFilesAt(ctx, f.pub, root, skip) |
| + st, err := syncFilesAt(ctx, f.pub, root, f.skip) |
| return st, true, err |
| } |
| -// stageItemsLocked stages the env item (<host>.env, read beneath its |
| -// directory; absent, the item is deleted) and the wake state from the |
| -// registry. f.mu is held. |
| +// stageItemsLocked stages each of the trio sealed (pubclass.SealedRels: |
| +// <host>.env, <host>/instance.key, <host>/report.token, each read beneath |
| +// the instance directory with no link followed; absent, its sealed item is |
| +// deleted), then drops any raw secret an older box published (the raw env |
| +// item and the raw trio entries, in the manifest only), then the wake |
| +// state from the registry. f.mu is held. |
| func (f *hostFiles) stageItemsLocked(ctx context.Context) error { |
| - dir, name := filepath.Dir(f.paths.envFile), filepath.Base(f.paths.envFile) |
| - env, absent, err := instancefs.ReadBeneathLimitOrAbsent(dir, name, haEnvReadLimit) |
| - switch { |
| - case err != nil && !errors.Is(err, os.ErrNotExist): |
| - return fmt.Errorf("read %s: %w", name, err) |
| - case absent || err != nil: |
| - if err := f.pub.StagePlatformDelete(hostfiles.EnvItem); err != nil { |
| - return err |
| - } |
| - default: |
| - if err := f.pub.StagePlatform(ctx, hostfiles.EnvItem, env); err != nil { |
| - return err |
| + for _, r := range pubclass.SealedRels(pubclass.Nested, f.host) { |
| + rel := filepath.FromSlash(r.Rel()) |
| + plain, absent, err := instancefs.ReadBeneathLimitOrAbsent(f.paths.dataDir, rel, haEnvReadLimit) |
| + switch { |
| + case err != nil && !errors.Is(err, os.ErrNotExist): |
| + return fmt.Errorf("read %s: %w", r.Rel(), err) |
| + case absent || err != nil: |
| + if err := f.pub.StagePlatformDelete(r.Item()); err != nil { |
| + return err |
| + } |
| + default: |
| + if err := f.pub.StageSealed(ctx, r, plain, f.seal); err != nil { |
| + return err |
| + } |
| } |
| } |
| + // Staged after the sealed items, so the commit that drops a raw |
| + // secret is the one that carries its sealed form. |
| + if err := f.pub.DropRawSecrets(rawSecretEntries); err != nil { |
| + return err |
| + } |
| if f.reg == nil { |
| return nil |
| } |
diff --git a/internal/activator/hafiles_test.go b/internal/activator/hafiles_test.go| index 7c79054f1..a97d4a521 100644 |
| --- a/internal/activator/hafiles_test.go |
| +++ b/internal/activator/hafiles_test.go |
| @@ -1,18 +1,108 @@ |
| package activator |
| import ( |
| + "bytes" |
| "context" |
| + "crypto/ecdh" |
| + "crypto/rand" |
| "os" |
| + "sort" |
| "sync" |
| "sync/atomic" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/hostfiles" |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| -// The trio and the wake state publish within about a second; the app's |
| -// files wait for the snapshot interval. |
| +// testEscrowKey is a CARLOS_SECRETS_KEY for a test box. |
| +func testEscrowKey(t *testing.T) *ecdh.PrivateKey { |
| + t.Helper() |
| + k, err := ecdh.P256().GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return k |
| +} |
| + |
| +// sealerOf is the sealer b publishes and restores rt's secrets with. |
| +func sealerOf(t *testing.T, b *ExecBackend, rt registry.Route) *hostfiles.ItemSealer { |
| + t.Helper() |
| + s, err := b.sealerFor(rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +func loadManifest(t *testing.T, b *ExecBackend, rt registry.Route) hostfiles.Manifest { |
| + t.Helper() |
| + m, _, err := hostfiles.Load(context.Background(), b.FilesStore, b.filesPrefix(rt.Host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return m |
| +} |
| + |
| +// prefixObjects is every object under rt's files prefix, by key. |
| +func prefixObjects(t *testing.T, b *ExecBackend, rt registry.Route) map[string][]byte { |
| + t.Helper() |
| + ctx := context.Background() |
| + keys, err := b.FilesStore.List(ctx, b.filesPrefix(rt.Host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out := map[string][]byte{} |
| + for _, k := range keys { |
| + body, _, err := b.FilesStore.Get(ctx, k) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out[k] = body |
| + } |
| + return out |
| +} |
| + |
| +// liveEntries is the manifest's live file entries. |
| +func liveEntries(m hostfiles.Manifest) []string { |
| + var out []string |
| + for p, e := range m.Entries { |
| + if !e.Deleted { |
| + out = append(out, p) |
| + } |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +// seedRawManifest publishes the shape a box before 3a wrote: the env as |
| +// the raw EnvItem and the trio as raw file entries. |
| +func seedRawManifest(t *testing.T, b *ExecBackend, rt registry.Route, env string, files map[string]string) hostfiles.Manifest { |
| + t.Helper() |
| + ctx := context.Background() |
| + p, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, body := range files { |
| + if err := p.Stage(ctx, name, []byte(body), 0o600, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := p.StagePlatform(ctx, hostfiles.EnvItem, []byte(env)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := p.Commit(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + return loadManifest(t, b, rt) |
| +} |
| + |
| +// The trio and the wake state publish within about a second, sealed: the |
| +// env and the instance key as sealed platform items, no raw entry, and no |
| +// object under the prefix holding a secret's bytes. The app's files wait |
| +// for the snapshot interval. |
| func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| b, rt := haBackend(t, "shop.example.com") |
| f, err := b.openHostFiles(context.Background(), rt) |
| @@ -24,26 +114,27 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| defer cancel() |
| go f.Run(ctx) |
| p := b.pathsFor(rt) |
| - writeFiles(t, b, rt, map[string]string{"a.txt": "app", "instance.key": "k1"}) |
| - if err := os.WriteFile(p.envFile, []byte("CARLOS_INSTANCE_KEY=k1\n"), 0o600); err != nil { |
| + const env = "CARLOS_ADMIN_TOKEN=tok-5f2e9c\nCARLOS_INSTANCE_KEY=k1\n" |
| + writeFiles(t, b, rt, map[string]string{"a.txt": "app", "instance.key": "key-8b41d7"}) |
| + if err := os.WriteFile(p.envFile, []byte(env), 0o600); err != nil { |
| t.Fatal(err) |
| } |
| - load := func() hostfiles.Manifest { |
| - m, _, err := hostfiles.Load(context.Background(), b.FilesStore, b.filesPrefix(rt.Host)) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - return m |
| - } |
| deadline := time.Now().Add(2 * time.Second) |
| for { |
| - m := load() |
| - _, env := m.Platform[hostfiles.EnvItem] |
| + m := loadManifest(t, b, rt) |
| + _, senv := m.Platform[hostfiles.SealedEnvItem] |
| + _, skey := m.Platform["instance.key.sealed"] |
| _, wake := m.Platform[hostfiles.WakeItem] |
| - if env && wake && m.Entries["instance.key"].Object != "" { |
| - body, err := hostfiles.ReadPlatform(context.Background(), b.FilesStore, b.filesPrefix(rt.Host), m, hostfiles.EnvItem, nil) |
| - if err != nil || string(body) != "CARLOS_INSTANCE_KEY=k1\n" { |
| - t.Fatalf("env item %q, %v", body, err) |
| + if senv && skey && wake { |
| + if _, ok := m.Entries["instance.key"]; ok { |
| + t.Fatal("the instance key was published as a raw entry") |
| + } |
| + if _, ok := m.Platform[hostfiles.EnvItem]; ok { |
| + t.Fatal("the env was published as the raw env item") |
| + } |
| + body, err := hostfiles.ReadSealed(context.Background(), b.FilesStore, b.filesPrefix(rt.Host), m, hostfiles.SealedEnvItem, nil, sealerOf(t, b, rt)) |
| + if err != nil || string(body) != env { |
| + t.Fatalf("sealed env item %q, %v", body, err) |
| } |
| if _, ok := m.Entries["a.txt"]; ok { |
| t.Fatal("an app file published on the trio's cadence") |
| @@ -51,10 +142,15 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| break |
| } |
| if time.Now().After(deadline) { |
| - t.Fatalf("the trio and wake state were not published within the deadline: %+v", m) |
| + t.Fatalf("the sealed trio and wake state were not published within the deadline: %+v", m) |
| } |
| time.Sleep(50 * time.Millisecond) |
| } |
| + for k, body := range prefixObjects(t, b, rt) { |
| + if bytes.Contains(body, []byte("tok-5f2e9c")) || bytes.Contains(body, []byte("key-8b41d7")) { |
| + t.Fatalf("object %s holds a secret's plaintext", k) |
| + } |
| + } |
| // The snapshot cadence publishes the app's files. |
| f2, err := b.openHostFiles(context.Background(), rt) |
| @@ -66,7 +162,66 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| ctx2, cancel2 := context.WithCancel(context.Background()) |
| defer cancel2() |
| go f2.Run(ctx2) |
| - waitFor(t, "the snapshot of a.txt", func() bool { return load().Entries["a.txt"].Object != "" }) |
| + waitFor(t, "the snapshot of a.txt", func() bool { return loadManifest(t, b, rt).Entries["a.txt"].Object != "" }) |
| +} |
| + |
| +// #477: the release's final publish carries the trio sealed, never raw. |
| +// A directory at a trio name is not published either (the classifier |
| +// judges by name). |
| +func TestFinalNeverPublishesTheTrioRaw(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com") |
| + writeFiles(t, b, rt, map[string]string{"a.txt": "app", "instance.key": "k1", "report.token": "r1"}) |
| + f, err := b.openHostFiles(context.Background(), rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, complete, err := f.Final(context.Background()); err != nil || !complete { |
| + t.Fatalf("final: complete %v, %v", complete, err) |
| + } |
| + m := loadManifest(t, b, rt) |
| + if got := liveEntries(m); len(got) != 1 || got[0] != "a.txt" { |
| + t.Fatalf("live entries %v, want [a.txt]", got) |
| + } |
| + for _, item := range []string{"instance.key.sealed", "report.token.sealed"} { |
| + if _, ok := m.Platform[item]; !ok { |
| + t.Fatalf("%s not published", item) |
| + } |
| + } |
| +} |
| + |
| +// A publisher over a manifest an older box wrote drops the raw secrets in |
| +// its first commit, in the manifest only: both old objects are still there. |
| +func TestFirstSealedCommitDropsRawSecretsAndDeletesNothing(t *testing.T) { |
| + ctx := context.Background() |
| + b, rt := haBackend(t, "shop.example.com") |
| + const env = "CARLOS_ADMIN_TOKEN=t1\n" |
| + old := seedRawManifest(t, b, rt, env, map[string]string{"instance.key": "k1"}) |
| + writeEnv(t, b, rt, env) |
| + writeFiles(t, b, rt, map[string]string{"instance.key": "k1"}) |
| + f, err := b.openHostFiles(ctx, rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.PublishPlatformNow(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := loadManifest(t, b, rt) |
| + if _, ok := m.Platform[hostfiles.EnvItem]; ok { |
| + t.Fatal("the raw env item survived the first sealed commit") |
| + } |
| + if !m.Entries["instance.key"].Deleted { |
| + t.Fatalf("the raw instance key entry is %+v, want a tombstone", m.Entries["instance.key"]) |
| + } |
| + for _, item := range []string{hostfiles.SealedEnvItem, "instance.key.sealed", hostfiles.CutoverItem} { |
| + if _, ok := m.Platform[item]; !ok { |
| + t.Fatalf("%s not in the first sealed commit", item) |
| + } |
| + } |
| + for _, key := range []string{old.Platform[hostfiles.EnvItem].Object, old.Entries["instance.key"].Object} { |
| + if _, _, err := b.FilesStore.Get(ctx, key); err != nil { |
| + t.Fatalf("old object %s: %v (3a deletes no object)", key, err) |
| + } |
| + } |
| } |
| // A snapshot that was not complete records no digest: the next one runs |
| @@ -115,7 +270,7 @@ func TestPlatformPublishesDuringASnapshot(t *testing.T) { |
| var once sync.Once |
| prev := syncFilesAt |
| syncFilesAt = func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) { |
| - if skip != nil && !skip("a.txt", false) { // the snapshot's read, not the trio's |
| + if skip != nil && !skip("a.txt", false) { // the snapshot's read (the platform pass syncs no tree) |
| once.Do(func() { close(blocked) }) |
| <-unblock |
| } |
| @@ -137,8 +292,8 @@ func TestPlatformPublishesDuringASnapshot(t *testing.T) { |
| for { |
| m, _, err := hostfiles.Load(context.Background(), b.FilesStore, b.filesPrefix(rt.Host)) |
| if err == nil { |
| - if _, ok := m.Platform[hostfiles.EnvItem]; ok { |
| - body, err := hostfiles.ReadPlatform(context.Background(), b.FilesStore, b.filesPrefix(rt.Host), m, hostfiles.EnvItem, nil) |
| + if _, ok := m.Platform[hostfiles.SealedEnvItem]; ok { |
| + body, err := hostfiles.ReadSealed(context.Background(), b.FilesStore, b.filesPrefix(rt.Host), m, hostfiles.SealedEnvItem, nil, sealerOf(t, b, rt)) |
| if err == nil && string(body) == "CARLOS_INSTANCE_KEY=k2\n" { |
| break |
| } |
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go| index 750ea14c1..31b006482 100644 |
| --- a/internal/activator/harelease_test.go |
| +++ b/internal/activator/harelease_test.go |
| @@ -307,6 +307,9 @@ func (s *haSvc) peer(t *testing.T) *haSvc { |
| b.Cfg = old.Cfg |
| b.OptDir, b.DataDir, b.RunDirOverride = old.OptDir, old.DataDir, old.RunDirOverride |
| b.StartupSwept, b.FilesStore, b.Lifetimes, b.Registry = old.StartupSwept, old.FilesStore, old.Lifetimes, old.Registry |
| + // The same deployment's CARLOS_SECRETS_KEY: every box of it seals to |
| + // and opens with the one key (plan 3a choice 2). |
| + b.EscrowKey = old.EscrowKey |
| haFixtures.Store(b, haFixOf(old)) |
| t.Cleanup(func() { haFixtures.Delete(b) }) |
| s2 := &haSvc{t: t, b: b, rt: s.rt, fx: s.fx, ctl: s.ctl, unit: s.unit, owedDir: s.owedDir} |
| @@ -628,9 +631,12 @@ func TestCleanReleaseRecordMatchesMarkerAndKeeps(t *testing.T) { |
| t.Fatalf("the record %+v does not match the marker %+v (%v)", now.Record.Marker, v.Lock.Release, err) |
| } |
| m, found := s.manifest(t) |
| - if !found || !strings.HasPrefix(v.Lock.Release.FilesGen, strconv.FormatInt(m.Seq, 10)+":") || m.Entries["a.txt"].Object == "" || m.Entries["instance.key"].Object == "" { |
| + if !found || !strings.HasPrefix(v.Lock.Release.FilesGen, strconv.FormatInt(m.Seq, 10)+":") || m.Entries["a.txt"].Object == "" || m.Platform["instance.key.sealed"].Object == "" { |
| t.Fatalf("files gen %q, manifest %+v", v.Lock.Release.FilesGen, m) |
| } |
| + if _, raw := m.Entries["instance.key"]; raw { |
| + t.Fatal("the release published the instance key raw") |
| + } |
| e, err = s.wakeForTest(context.Background()) |
| if err != nil { |
| t.Fatal(err) |
| @@ -841,11 +847,13 @@ func TestHAWakeRequestCounts(t *testing.T) { |
| } |
| e, reqs := wake() |
| // A first wake: the lock's three, then the launch's publish of its |
| - // minted secrets (Task 11): the env and wake state objects and the |
| - // first manifest, a create, with no read of it. |
| - if want := []string{"GET " + lock, "LIST " + s.b.Cfg.hibernatePrefix(s.rt.Host) + "/", "PUT " + lock}; len(reqs) != 6 || strings.Join(reqs[:3], ",") != strings.Join(want, ",") || |
| - !strings.HasPrefix(reqs[3], "PUT "+s.b.filesPrefix(s.rt.Host)+"objects/") || !strings.HasPrefix(reqs[4], "PUT "+s.b.filesPrefix(s.rt.Host)+"objects/") || reqs[5] != "PUT "+manifest { |
| - t.Fatalf("a first wake made %v, want %v, two objects and the manifest", reqs, want) |
| + // minted secrets (Task 11): the sealed env, the sealed cutover marker |
| + // (durability 3a) and the wake state objects, and the first manifest, |
| + // a create, with no read of it. |
| + objects := "PUT " + s.b.filesPrefix(s.rt.Host) + "objects/" |
| + if want := []string{"GET " + lock, "LIST " + s.b.Cfg.hibernatePrefix(s.rt.Host) + "/", "PUT " + lock}; len(reqs) != 7 || strings.Join(reqs[:3], ",") != strings.Join(want, ",") || |
| + !strings.HasPrefix(reqs[3], objects) || !strings.HasPrefix(reqs[4], objects) || !strings.HasPrefix(reqs[5], objects) || reqs[6] != "PUT "+manifest { |
| + t.Fatalf("a first wake made %v, want %v, three objects and the manifest", reqs, want) |
| } |
| writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "app"}) |
| s.stopForTest(e) |
diff --git a/internal/activator/hasecrets.go b/internal/activator/hasecrets.go| index cc7b06f33..b3371db23 100644 |
| --- a/internal/activator/hasecrets.go |
| +++ b/internal/activator/hasecrets.go |
| @@ -2,8 +2,6 @@ package activator |
| import ( |
| "context" |
| - "crypto/sha256" |
| - "encoding/hex" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -21,8 +19,9 @@ import ( |
| // Region HA P1a, the instance's secrets (spec §8.2, r2.3, r3.8). An HA |
| // host's CARLOS_ADMIN_TOKEN and CARLOS_INSTANCE_KEY travel in its env file, |
| -// which publishes as the files manifest's env item, so any box that wakes |
| -// the host next restores the same pair. Two rules keep them one pair: |
| +// which publishes as the files manifest's sealed env item (durability 3a), |
| +// so any box that wakes the host next restores the same pair. Two rules |
| +// keep them one pair: |
| // |
| // - one mint decision (haMintGuard) inside every producer of either |
| // secret, asked in its missing-secret branch at the moment it would |
| @@ -33,8 +32,8 @@ import ( |
| // pair minted there would fork the instance's secrets. The launch is |
| // deferred instead (ErrInstanceKeyDeferred). |
| // - before every launch of an HA host, retries included, the launch's |
| -// env is read once (captureLaunchEnv), those bytes are the env item of |
| -// the manifest last committed (haSecretsReady), or are published and |
| +// env is read once (captureLaunchEnv), those bytes are the sealed env |
| +// item of the manifest last committed (haSecretsReady), or are published and |
| // the commit acknowledged first, and the launch is handed the env |
| // parsed from those same bytes, never a later read (launchEnvLayer). |
| // A launch whose publish fails, or whose env changed under its |
| @@ -206,14 +205,16 @@ func (b *ExecBackend) haManifestFound(ctx context.Context, rt registry.Route) (b |
| } |
| // haSecretsReady is the step between an HA host's ensure calls and its |
| -// launch: nil once env, the bytes the launch captured, has the SHA-256 of |
| -// the env item of the manifest last committed. Otherwise it publishes the |
| -// platform items (the env, the trio and the wake state) through the wake's |
| -// or the entry's publisher, or a publisher of its own when there is |
| -// neither (one read), waits for the commit, and checks again: an env file |
| +// launch: nil once env, the bytes the launch captured, is the plaintext of |
| +// the sealed env item of the manifest last committed (its keyed digest). |
| +// Otherwise it publishes the platform items (the sealed trio and the wake |
| +// state) through the wake's or the entry's publisher, or a publisher of |
| +// its own when there is neither (one read), waits for the commit, and |
| +// checks again: an env file |
| // that changed after the capture is committed as other bytes, and fails |
| -// the launch. Every error fails the launch. The caller has classified rt |
| -// HA (launchEnvLayer). |
| +// the launch. A box with no escrow key (EscrowKey) publishes nothing and |
| +// fails the launch. Every error fails the launch. The caller has |
| +// classified rt HA (launchEnvLayer). |
| func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route, env []byte) error { |
| f := b.haPublisherNow(rt.Host) |
| own := false |
| @@ -221,11 +222,17 @@ func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route, env |
| if b.FilesStore == nil { |
| return errors.New("publish the host's secrets: no files store configured") |
| } |
| + if _, err := b.sealerFor(rt); err != nil { |
| + return fmt.Errorf("publish the host's secrets: %w", err) |
| + } |
| pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host)) |
| if err != nil { |
| return fmt.Errorf("publish the host's secrets: %w", err) |
| } |
| - f, own = b.newHostFiles(rt, pub), true |
| + if f, err = b.newHostFiles(rt, pub); err != nil { |
| + return fmt.Errorf("publish the host's secrets: %w", err) |
| + } |
| + own = true |
| } |
| ok, err := f.envAcknowledged(env) |
| if err != nil { |
| @@ -251,7 +258,8 @@ func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route, env |
| } |
| // envAcknowledged reports whether env, the bytes a launch captured, are |
| -// the env item of the manifest f last committed. It reads no file. |
| +// the sealed env item of the manifest f last committed (its keyed digest |
| +// of the plaintext). It reads no file and no object. |
| func (f *hostFiles) envAcknowledged(env []byte) (bool, error) { |
| base := f.pub.Baseline() |
| if !base.Found { |
| @@ -261,9 +269,7 @@ func (f *hostFiles) envAcknowledged(env []byte) (bool, error) { |
| if err := json.Unmarshal(base.Body, &m); err != nil { |
| return false, fmt.Errorf("the committed files manifest: %w", err) |
| } |
| - item, ok := m.Platform[hostfiles.EnvItem] |
| - sum := sha256.Sum256(env) |
| - return ok && !item.Deleted && item.SHA256 == hex.EncodeToString(sum[:]), nil |
| + return hostfiles.SealedAcknowledged(m, hostfiles.SealedEnvItem, env, f.seal), nil |
| } |
| // entryFilesUser is the Backend capability New hands the service's entry |
diff --git a/internal/activator/hasecrets_test.go b/internal/activator/hasecrets_test.go| index 38411d021..fbd127ba0 100644 |
| --- a/internal/activator/hasecrets_test.go |
| +++ b/internal/activator/hasecrets_test.go |
| @@ -90,8 +90,8 @@ func envValues(t *testing.T, b *ExecBackend, rt registry.Route, names ...string) |
| return out |
| } |
| -// platformEnv is the env item of the host's files manifest as stored now, |
| -// "" when there is none. |
| +// platformEnv is the sealed env item of the host's files manifest as |
| +// stored now, opened, "" when there is none. |
| func platformEnv(t *testing.T, b *ExecBackend, rt registry.Route) string { |
| t.Helper() |
| ctx := context.Background() |
| @@ -103,16 +103,30 @@ func platformEnv(t *testing.T, b *ExecBackend, rt registry.Route) string { |
| if !found { |
| return "" |
| } |
| - if _, ok := m.Platform[hostfiles.EnvItem]; !ok { |
| + if _, ok := m.Platform[hostfiles.SealedEnvItem]; !ok { |
| return "" |
| } |
| - env, err := hostfiles.ReadPlatform(ctx, b.FilesStore, prefix, m, hostfiles.EnvItem, nil) |
| + env, err := hostfiles.ReadSealed(ctx, b.FilesStore, prefix, m, hostfiles.SealedEnvItem, nil, sealerOf(t, b, rt)) |
| if err != nil { |
| t.Fatal(err) |
| } |
| return string(env) |
| } |
| +// publishSealedEnv publishes env as the host's sealed env item, through the |
| +// host's own publisher, as a launch before this one did. |
| +func publishSealedEnv(t *testing.T, b *ExecBackend, rt registry.Route, env string) { |
| + t.Helper() |
| + writeEnv(t, b, rt, env) |
| + f, err := b.openHostFiles(context.Background(), rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.PublishPlatformNow(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| // failingCommits is a files store whose next n manifest writes fail. |
| type failingCommits struct { |
| release.Store |
| @@ -193,14 +207,37 @@ func TestHALaunchRetryPublishesPendingSecretFirst(t *testing.T) { |
| func TestHALaunchAcknowledgedEnvWritesNothing(t *testing.T) { |
| b, rt := haLaunchBackend(t, "shop.example.com") |
| env := "CARLOS_ADMIN_TOKEN=t1\n" + InstanceKeyVar + "=k1\n" |
| - publishManifest(t, b, rt, nil, env) |
| - writeEnv(t, b, rt, env) |
| + publishSealedEnv(t, b, rt, env) |
| failFilesCommitOnce(t, b) // a write would fail the launch |
| if err := b.launchForTest(rt); err != nil { |
| t.Fatal(err) |
| } |
| } |
| +// A box whose CARLOS_SECRETS_KEY did not parse publishes nothing: its |
| +// publisher does not open, a launch's publish fails, and nothing is |
| +// written under the prefix. |
| +func TestHAPublicationRefusesWithoutAKey(t *testing.T) { |
| + ctx := context.Background() |
| + b, rt := haLaunchBackend(t, "shop.example.com") |
| + b.EscrowKey = nil |
| + writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=t1\n") |
| + writeFiles(t, b, rt, map[string]string{"instance.key": "k1"}) |
| + if _, err := b.openHostFiles(ctx, rt); err == nil { |
| + t.Fatal("a publisher opened with no escrow key") |
| + } |
| + if err := b.haSecretsReady(ctx, rt, []byte("CARLOS_ADMIN_TOKEN=t1\n")); err == nil { |
| + t.Fatal("a launch's secrets were acknowledged with no escrow key") |
| + } |
| + b.stageWakeFiles(rt, hostfiles.Baseline{}) |
| + if _, ok := b.wakeFiles(rt.Host); ok { |
| + t.Fatal("a wake publisher was staged with no escrow key") |
| + } |
| + if objs := prefixObjects(t, b, rt); len(objs) != 0 { |
| + t.Fatalf("written under the prefix with no escrow key: %d object(s)", len(objs)) |
| + } |
| +} |
| + |
| // A launch while the host is awake publishes through the entry's own |
| // publisher, never a second one (which would supersede it). |
| func TestHALaunchUsesTheEntryPublisher(t *testing.T) { |
| @@ -210,7 +247,10 @@ func TestHALaunchUsesTheEntryPublisher(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - entry := b.newHostFiles(rt, pub) |
| + entry, err := b.newHostFiles(rt, pub) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| asked := 0 |
| b.useEntryFiles(func(host string) *hostFiles { asked++; return entry }) |
| if err := b.launchForTest(rt); err != nil { |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index b643dd40e..91cb78301 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -6,6 +6,7 @@ import ( |
| "fmt" |
| "io/fs" |
| "log" |
| + "path" |
| "path/filepath" |
| "strings" |
| "sync" |
| @@ -14,6 +15,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/hostfiles" |
| "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/layout/pubclass" |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -580,9 +582,18 @@ const restoreSuffix = ".restore" |
| // tree: into <host>.restore/ (a leftover one removed first), which is |
| // renamed into place as the files directory, never over one (setAside |
| // moved the old one away; anything there now refuses). The manifest's |
| -// env item becomes <host>.env, and its wake state goes into the registry |
| -// (hostfiles.ImportWake). A host with no manifest gets an empty files |
| -// directory and no env file. Every failure fails the wake. |
| +// sealed env item, opened, becomes <host>.env (a manifest an older box |
| +// wrote holds the raw env item instead, restored as before), and its wake |
| +// state goes into the registry (hostfiles.ImportWake). A host with no |
| +// manifest gets an empty files directory and no env file. Every failure |
| +// fails the wake. |
| +// |
| +// The trio (durability 3a): each sealed trio item the manifest holds is |
| +// opened and written into the restore directory, mode 0600, before the |
| +// rename, over any raw entry of that name an older box published. A raw |
| +// trio entry is restored only when no sealed item of its name is there |
| +// and the entry is live: the first sealed commit tombstoned it |
| +// (DropRawSecrets), so a key deleted since is never resurrected. |
| func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) error { |
| host := rt.Host |
| if b.FilesStore == nil { |
| @@ -612,14 +623,60 @@ func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) |
| if len(st.Skipped) > 0 { |
| log.Printf("activator: %s: %d file(s) the manifest holds as unpublished were not restored: %s", host, len(st.Skipped), strings.Join(st.Skipped, ", ")) |
| } |
| + // The sealer is made only for a manifest that holds a sealed item: one |
| + // an older box wrote restores on a box without a key as before (its |
| + // wake still needs one to publish). |
| + var seal *hostfiles.ItemSealer |
| + openSealed := func(item string) ([]byte, error) { |
| + if seal == nil { |
| + s, err := b.sealerFor(rt) |
| + if err != nil { |
| + return nil, fmt.Errorf("restore %s: %w", item, err) |
| + } |
| + seal = s |
| + } |
| + return hostfiles.ReadSealed(ctx, b.FilesStore, prefix, rm, item, nil, seal) |
| + } |
| + sealedTrio := false |
| + for _, r := range pubclass.SealedRels(pubclass.Nested, host) { |
| + dir, name := path.Split(r.Rel()) |
| + if r.Item() == hostfiles.SealedEnvItem || dir != host+"/" { |
| + continue // the env file is restored beside the directory, below |
| + } |
| + if _, ok := rm.Platform[r.Item()]; !ok { |
| + continue |
| + } |
| + plain, err := openSealed(r.Item()) |
| + if err != nil { |
| + return err |
| + } |
| + if err := instancefs.WriteAtomic(filepath.Join(p.dataDir, tmp), name, plain, 0o600); err != nil { |
| + return fmt.Errorf("restore %s: %w", r.Rel(), err) |
| + } |
| + sealedTrio = true |
| + } |
| + if sealedTrio { |
| + if err := syncDirIfThere(filepath.Join(p.dataDir, tmp)); err != nil { |
| + return err |
| + } |
| + } |
| if err := instancefs.RenameBetweenNoReplace(p.dataDir, tmp, p.dataDir, host); err != nil { |
| return err |
| } |
| - if _, ok := rm.Platform[hostfiles.EnvItem]; ok { |
| - env, err := hostfiles.ReadPlatform(ctx, b.FilesStore, prefix, rm, hostfiles.EnvItem, nil) |
| - if err != nil { |
| + var env []byte |
| + haveEnv := false |
| + if _, ok := rm.Platform[hostfiles.SealedEnvItem]; ok { |
| + if env, err = openSealed(hostfiles.SealedEnvItem); err != nil { |
| + return err |
| + } |
| + haveEnv = true |
| + } else if _, ok := rm.Platform[hostfiles.EnvItem]; ok { |
| + if env, err = hostfiles.ReadPlatform(ctx, b.FilesStore, prefix, rm, hostfiles.EnvItem, nil); err != nil { |
| return err |
| } |
| + haveEnv = true |
| + } |
| + if haveEnv { |
| if err := instancefs.WriteAtomic(filepath.Dir(p.envFile), filepath.Base(p.envFile), env, 0o600); err != nil { |
| return err |
| } |
diff --git a/internal/activator/hawake_test.go b/internal/activator/hawake_test.go| index ccccc1e58..7b803da74 100644 |
| --- a/internal/activator/hawake_test.go |
| +++ b/internal/activator/hawake_test.go |
| @@ -59,9 +59,10 @@ func haRecord(host string, ha bool) provision.Record { |
| // haBackendEmptyIndex is a production-shaped ExecBackend for a provisioned |
| // instance on the nested layout: the real lease against the lock fixture |
| // (this box is Self{a, i-a}, an obligation store set), NestedOK nil with a |
| -// control channel, StartupSwept true, a files store, a registry holding |
| -// the route, the restoreReplica seam counting calls, and a record in the |
| -// deployment store saying the host is HA. Its lifetime index is empty. |
| +// control channel, StartupSwept true, a files store and an escrow key |
| +// (EscrowKey), a registry holding the route, the restoreReplica seam |
| +// counting calls, and a record in the deployment store saying the host is |
| +// HA. Its lifetime index is empty. |
| func haBackendEmptyIndex(t *testing.T, host string) (*ExecBackend, registry.Route) { |
| t.Helper() |
| fx := locktest.NewLockFixture(t) |
| @@ -82,6 +83,7 @@ func haBackendEmptyIndex(t *testing.T, host string) (*ExecBackend, registry.Rout |
| b.Control = ctl |
| b.StartupSwept = func() bool { return true } |
| b.FilesStore = release.NewDirStore(t.TempDir()) |
| + b.EscrowKey = testEscrowKey(t) |
| b.Lifetimes = &provision.LifetimeIndex{} |
| if err := os.MkdirAll(b.DataDir, 0o755); err != nil { |
| t.Fatal(err) |
| @@ -440,6 +442,128 @@ func TestRestoreHAFilesIntoCleanTree(t *testing.T) { |
| } |
| } |
| +// clearLocal removes the host's files directory and env file, as setAside |
| +// moves them away before a restore. |
| +func clearLocal(t *testing.T, b *ExecBackend, rt registry.Route) { |
| + t.Helper() |
| + if err := os.RemoveAll(filesDirOf(b, rt)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Remove(b.pathsFor(rt).envFile); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// restoredSecret is a restored file's bytes, failing unless it is a |
| +// regular file of mode 0600. |
| +func restoredSecret(t *testing.T, path string) string { |
| + t.Helper() |
| + st, err := os.Lstat(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !st.Mode().IsRegular() || st.Mode().Perm() != 0o600 { |
| + t.Fatalf("%s: mode %v, want a regular file of 0600", path, st.Mode()) |
| + } |
| + body, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(body) |
| +} |
| + |
| +// An HA wake restores the sealed env and trio as plaintext, mode 0600. |
| +func TestRestoreFromASealedManifest(t *testing.T) { |
| + ctx := context.Background() |
| + b, rt := haBackend(t, "shop.example.com") |
| + const env = "CARLOS_ADMIN_TOKEN=t1\nCARLOS_INSTANCE_KEY=k1\n" |
| + writeEnv(t, b, rt, env) |
| + writeFiles(t, b, rt, map[string]string{"a.txt": "app", "instance.key": "k1", "report.token": "r1"}) |
| + f, err := b.openHostFiles(ctx, rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := f.Final(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + clearLocal(t, b, rt) |
| + if err := b.restoreFilesClean(ctx, rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := filesDirOf(b, rt) |
| + if got := restoredSecret(t, b.pathsFor(rt).envFile); got != env { |
| + t.Fatalf("env %q, want %q", got, env) |
| + } |
| + if got := restoredSecret(t, filepath.Join(dir, "instance.key")); got != "k1" { |
| + t.Fatalf("instance.key %q", got) |
| + } |
| + if got := restoredSecret(t, filepath.Join(dir, "report.token")); got != "r1" { |
| + t.Fatalf("report.token %q", got) |
| + } |
| + if readFile(t, b, rt, "a.txt") != "app" || exists(dir+restoreSuffix) { |
| + t.Fatal("the app's files were not restored cleanly") |
| + } |
| +} |
| + |
| +// A manifest an older box wrote (the raw env item and raw trio entries) |
| +// restores both, as before. |
| +func TestRestoreFromAnOlderRawManifest(t *testing.T) { |
| + ctx := context.Background() |
| + b, rt := haBackend(t, "shop.example.com") |
| + const env = "CARLOS_ADMIN_TOKEN=t1\n" |
| + seedRawManifest(t, b, rt, env, map[string]string{"a.txt": "app", "instance.key": "k1", "report.token": "r1"}) |
| + if err := os.MkdirAll(b.pathsFor(rt).dataDir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.restoreFilesClean(ctx, rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := restoredSecret(t, b.pathsFor(rt).envFile); got != env { |
| + t.Fatalf("env %q", got) |
| + } |
| + if readFile(t, b, rt, "instance.key") != "k1" || readFile(t, b, rt, "report.token") != "r1" || readFile(t, b, rt, "a.txt") != "app" { |
| + t.Fatal("the raw manifest's files were not restored") |
| + } |
| +} |
| + |
| +// A sealed commit tombstoned the raw instance key; the key is then removed |
| +// and its sealed item deleted. A restore writes no instance.key: the raw |
| +// entry an older box wrote is never resurrected. |
| +func TestDeletedSealedTrioDoesNotResurrectTheRawEntry(t *testing.T) { |
| + ctx := context.Background() |
| + b, rt := haBackend(t, "shop.example.com") |
| + const env = "CARLOS_ADMIN_TOKEN=t1\n" |
| + seedRawManifest(t, b, rt, env, map[string]string{"instance.key": "k1"}) |
| + writeEnv(t, b, rt, env) |
| + writeFiles(t, b, rt, map[string]string{"instance.key": "k1"}) |
| + f, err := b.openHostFiles(ctx, rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.PublishPlatformNow(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Remove(filepath.Join(filesDirOf(b, rt), "instance.key")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.PublishPlatformNow(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := loadManifest(t, b, rt).Platform["instance.key.sealed"]; ok { |
| + t.Fatal("the sealed instance key outlived the file") |
| + } |
| + clearLocal(t, b, rt) |
| + if err := b.restoreFilesClean(ctx, rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if exists(filepath.Join(filesDirOf(b, rt), "instance.key")) { |
| + t.Fatal("a deleted instance key was restored from the raw entry") |
| + } |
| + if got := restoredSecret(t, b.pathsFor(rt).envFile); got != env { |
| + t.Fatalf("env %q", got) |
| + } |
| +} |
| + |
| // A no-marker restore (r P15): the stale <host>.env goes with the tree, and |
| // with no manifest nothing replaces it, so the next launch mints afresh. |
| func TestRestoreHANoMarkerRemovesStaleEnv(t *testing.T) { |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 8d2a63fb4..01ee8f53d 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -482,6 +482,9 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| } else { |
| eb.FilesStore = fs |
| } |
| + // Durability 3a: an HA host's secrets publish sealed to this |
| + // box's own key, and nothing publishes without one. |
| + eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")) |
| if err := lease.SetObligationDir(filepath.Join(dd, ".ha-owed")); err != nil { |
| log.Printf("agent: region HA: obligation store: %v (every HA wake on this box refuses until it opens)", err) |
| } |
| @@ -3588,6 +3591,19 @@ func BoxProvisionConfig(reg *registry.Registry, getenv func(string) string, judg |
| // reconcile pass fills it, the activator's HA classification reads it. |
| var boxLifetimes = &provision.LifetimeIndex{} |
| +// haEscrowKey is CARLOS_SECRETS_KEY parsed, as the moves pass parses it, |
| +// for region HA's sealed publication (ExecBackend.EscrowKey). A key that |
| +// is unset or does not parse is logged and nil: HA publication and escrow |
| +// refuse on this box. |
| +func haEscrowKey(raw string) *ecdh.PrivateKey { |
| + priv, err := appconfig.ParsePrivateKey(strings.TrimSpace(raw), "CARLOS_SECRETS_KEY") |
| + if err != nil { |
| + log.Printf("agent: escrow: CARLOS_SECRETS_KEY does not parse; HA publication and escrow refuse on this box") |
| + return nil |
| + } |
| + return priv |
| +} |
| + |
| // haRecordFacts is activator.Config.Record on this box: the host's record |
| // read from the deployment store under the box's judge (judgedRecord, under |
| // the route's effective account) and made a lifetime entry. A record its |
diff --git a/internal/host/hawake_wiring_test.go b/internal/host/hawake_wiring_test.go| index dc71be7bb..88bce6e96 100644 |
| --- a/internal/host/hawake_wiring_test.go |
| +++ b/internal/host/hawake_wiring_test.go |
| @@ -2,6 +2,9 @@ package host |
| import ( |
| "context" |
| + "crypto/ecdh" |
| + "crypto/rand" |
| + "encoding/base64" |
| "errors" |
| "os" |
| "strings" |
| @@ -92,8 +95,9 @@ func TestHARecordFactsJudgesTheLifetime(t *testing.T) { |
| } |
| // RunAgent wires the HA wake before the Service starts: the record facts, |
| -// the identity, the index, the registry, the startup sweep's proof and the |
| -// obligation store (syntactic, like the policy cache's wiring test). |
| +// the identity, the index, the registry, the startup sweep's proof, the |
| +// escrow key and the obligation store (syntactic, like the policy cache's |
| +// wiring test). |
| func TestAgentWiresTheHAWake(t *testing.T) { |
| src, err := os.ReadFile("agent.go") |
| if err != nil { |
| @@ -108,6 +112,7 @@ func TestAgentWiresTheHAWake(t *testing.T) { |
| "eb.Registry = reg", |
| "eb.StartupSwept = seedSweptAtStart.Load", |
| "eb.FilesStore = fs", |
| + `eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY"))`, |
| `lease.SetObligationDir(filepath.Join(dd, ".ha-owed"))`, |
| } { |
| i := strings.Index(body, want) |
| @@ -117,6 +122,25 @@ func TestAgentWiresTheHAWake(t *testing.T) { |
| } |
| } |
| +// The escrow key is CARLOS_SECRETS_KEY parsed (surrounding space |
| +// trimmed); one that is unset or does not parse is nil, and HA publication |
| +// refuses on the box. |
| +func TestHAEscrowKeyParsesTheSecretsKey(t *testing.T) { |
| + priv, err := ecdh.P256().GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw := base64.StdEncoding.EncodeToString(priv.Bytes()) |
| + if got := haEscrowKey(" " + raw + "\n"); got == nil || !got.Equal(priv) { |
| + t.Fatalf("the escrow key is %v, want the configured one", got) |
| + } |
| + for _, bad := range []string{"", "not-a-key"} { |
| + if got := haEscrowKey(bad); got != nil { |
| + t.Fatalf("%q parsed as an escrow key", bad) |
| + } |
| + } |
| +} |
| + |
| // The files store an HA wake restores from and publishes to is the one |
| // builder lease shares (Task 10): it reaches a CARLOS_S3_ENDPOINT store |
| // even when no region is configured anywhere, signing as the lease does, |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 66cc38659..6768d413c 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -45,4 +45,4 @@ plan14-root-reads-fleet-public-routes.tsv bca6ef741a96b72767b1747789cd01b3111d61 |
| plan14-root-reads-fleet-routes-followups.tsv 1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7 |
| plan14-root-reads-tunnel-websockets.tsv 949bc734a293366e6b2700244af5110dd6e84b5432023e991c09e806afd62483 |
| plan14-root-reads-console-protection-tab.tsv eaeb153ab7a7a849edc9c6e92f2ac5c709c6e39044a647971cf1fa5ebcb660c8 |
| -plan14-root-reads-durability-3a-escrow.tsv 0da3b2b5686a83332323f61821f53b7f3070135f4ca54005946c4c4b1ee70f09 |
| +plan14-root-reads-durability-3a-escrow.tsv bd11e15cc2b64af3aa78c88e91dc151cfe3096ac671687ca8d015bfb8c331542 |
diff --git a/internal/provision/testdata/plan14-root-reads-durability-3a-escrow.tsv b/internal/provision/testdata/plan14-root-reads-durability-3a-escrow.tsv| index 01706c9be..c2d825291 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-durability-3a-escrow.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-durability-3a-escrow.tsv |
| @@ -1,13 +1,29 @@ |
| # Census overlay durability-3a-escrow, written by census-propose (#369). census-ruling-durability-3a-escrow, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-durability-3a-escrow.md. |
| -# 0 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| -# 3 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 0 other. |
| +# 1 body, 6 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 4 new dispositions: 0 reads re-frozen at their disposition with the claim, 3 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 0 other. |
| +@legacy 8cac704f54ddfe06f00165aec337a93f0540c990d0f353d1379c9adacb464d86 internal/activator/hafiles.go ExecBackend.sealerFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: new. Builds the host's hostfiles.ItemSealer from the backend's EscrowKey (the box's own CARLOS_SECRETS_KEY, set once by runAgent) and the binding {release.RouteAccount(rt), rt.App} for rt.Host (NewItemSealer validates the account, app and host shape); nil key is an error. Pure in memory: opens, reads and writes nothing. registry:App@334,registry:Host@343,whole:Route@324 0225e79c376c0bad00460a6b520b3f9f0cdf2468a0319f2370e0aa3fb6af091a |
| @legacy 51297417f7d25f895c3793014740994855e599bf8731cf3295ea836820ae4f13 internal/hostfiles/sealed.go ReadSealed legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 2: new. Reads one sealed platform item of a files manifest the caller already loaded: the object at exactly the key the entry names, through the existing fetch (checkEntry: origin admitted, key shape, sha256 and size verified), only for an entry marked sealed "v2". The "Open" the scanner sees is appconfig.Open, an in-memory AES-GCM decryption of the fetched bytes, not a file open: no filesystem path is opened, read or followed. It refuses a v1 envelope (appconfig.EnvelopeBound), and after opening under the caller-supplied key and (account, app) binding it checks the HMAC digest over account, app, host and item against the entry. Writes nothing. No production caller in this task; Tasks 3 and 4 call it from the activator. file:Open@898 7c2b887b6e0b45472fd8d1a63a2b78eb565c4e93c89cb329eeeaef429ab0b010 |
| @legacy 7520abf7fe01442d3fcca5cc9c46cd22346ae2ad193162ed8df7ba9371914028 internal/layout/inventory.go Inventory legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 1: new. One os.ReadDir of the host's inventory root, provision.InstanceDir(dataDir, host) nested or dataDir flat, after refusing a host that fails controlname.ValidHostShape and a layout that is neither flat nor nested; reads only the listing's names and types (DirEntry.IsDir), opens and follows nothing; flat ownership is the extras scan's own (hostEntries over knownHosts); each top-level name is classified by pubclass.Of, a pure function of the name. A missing directory is an empty inventory. No caller in this task; later tasks call it from the publisher. file:ReadDir@449 9662e465abb7f9c60e908952740384479009c9987c8a6ae65d98fb19cb3d4d7e |
| +@legacy 0aa879d05dedfa2a097504534e62f3637c77470bf70177df6f32efcc9b051965 internal/activator/hafiles.go ExecBackend.newHostFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: builds a hostFiles publisher for rt (its instance paths from pathsFor(rt), rt.Host, the backend's registry, the 1 s platform and 15 min snapshot cadences); +registry:Host, +whole:Route; no I/O;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: now also sets the publisher's sealer (sealerFor(rt); its error is returned and nothing is built) and its skip, pubclass.FilesDirSkip(Nested, rt.Host), a pure function of the name, so every tree pass publishes only App paths and never the trio raw. Still no I/O; the new +registry:Host and +whole:Route sites are the sealer's and the classifier's arguments. registry:Host@228,registry:Host@313,whole:Route@128,whole:Route@217 69d03f586dc59cbc9555cc79b34d024854359b8d2a3d9ae0625ae5e8a4ad0a52 |
| +@legacy 9575d7fd08d19a1422bf49b03160394ab13436e5ca4bc4259c5faa14f0362147 internal/activator/hafiles.go ExecBackend.openHostFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the entry's files publisher: refuses without a FilesStore or outside the nested layout, takes the one this wake's restore staged, else hostfiles.Open on <hibernate prefix>/files/0/ (one GET of the manifest from the hibernate bucket, the scanner's +file:Open); +registry:Host x2, +whole:Route x2; the manifest is written by the agents of the boxes that hold the host, through the same files store;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: asks sealerFor before hostfiles.Open, so a box without an escrow key refuses before it reads the manifest; newHostFiles's error is returned. The same manifest GET otherwise; the new +whole:Route site is sealerFor's argument. Opens nothing new. file:Open@521,registry:Host@342,registry:Host@569,whole:Route@198,whole:Route@469,whole:Route@640 f193b187884a24cd093cc19e08ad77be581005ac84c746cef8db52f1beb8dbe8 |
| +@legacy 7150dace5e7f9f29faeb2e6a78df22881534291b9d66006194d90c769082a772 internal/activator/hafiles.go ExecBackend.stageKeptFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: on a kept wake, reads the manifest baseline the release kept beside its local record (<db>.release.files.json via readFilesBaseline, capped at 32 MiB, O_NOFOLLOW, regular files only) and stages a publisher on it only when its revision (Gen, which carries the body's SHA-256) equals the files_gen in the lock's release marker; the file is on ground the tenant can write, and anything that does not match stages nothing, so the entry re-reads the manifest from the store; it never decides the keep; +registry:Host x4, +whole:Route x2;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. The same baseline read; nothing new opened or read. registry:Host@254,registry:Host@344,registry:Host@508,registry:Host@627,registry:Host@673,whole:Route@151,whole:Route@560 d740082bbfda130c1b0b8e71dae3ff9804dbf36131bc659d147d3d41921674d2 |
| +@legacy cdd0c029924e783aa6acc1b26a6bf4b91e038511acdd5291a7dd1ca39c81c734 internal/activator/hafiles.go ExecBackend.stageWakeFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: opens a publisher on a manifest baseline the HA restore already holds (hostfiles.OpenBaseline, no read) and keeps it for the wake's entry; without a FilesStore it stages nothing; +registry:Host x3, +whole:Route;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. No read, as before. registry:Host@185,registry:Host@300,registry:Host@419,registry:Host@465,whole:Route@352 2a9b49c4cdd022038db91a72126a31c4b0c7e81de038f9c57747522136aa361a |
| +@legacy 192df384d784a7d1ac579802fd8ad96206ff78ee8164d09ab6e8093b968602ba internal/activator/hasecrets.go ExecBackend.haSecretsReady legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: before an HA host's launch, checks that env, the bytes the launch captured (captureLaunchEnv; a new parameter, final fix F2), has the SHA-256 of the committed manifest's env item (envAcknowledged, which now reads no file); else publishes the platform items (env, trio, wake state) through the wake's, the entry's or its own publisher (hostfiles.Open, the +file:Open site: one manifest GET) and checks again, so an env replaced after the capture is committed as other bytes and fails the launch; it no longer classifies the host itself (launchEnvLayer has); every error fails the launch; +file:Open, +registry:Host x3, +whole:Route;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: asks sealerFor before its own hostfiles.Open (a box without an escrow key fails the launch before any read), and newHostFiles's error fails the launch. envAcknowledged now compares the sealed env item's keyed digest (hostfiles.SealedAcknowledged, no read) instead of the raw env item's SHA-256. The publish it triggers stages the trio sealed: <host>.env, <host>/instance.key and <host>/report.token are each read with instancefs.ReadBeneathLimitOrAbsent beneath the instance directory (openat2, no symlink, regular files only, 1 MiB cap), the same reader the env already used, then sealed in memory; nothing else is opened. file:Open@390,registry:Host@1187,registry:Host@120,registry:Host@438,whole:Route@294,whole:Route@559 4f4584786d3f90a54aa3ddc1c39ffed8a62fcfd593127f534bea787c3d9b7829 |
| +@legacy 28637d8aaf3691a7f53208f8e0a009fd9287b4ca7f0fa3278be8f2fb1b466130 internal/activator/hawake.go ExecBackend.restoreFilesClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: restores the HA host's published files into a fresh <host>.restore directory beneath the instance data dir (instancefs, no link followed), renames it into place without replacing anything, writes the manifest's env item as <host>.env (instancefs.WriteAtomic, 0600) and imports the manifest's wake state into the registry (hostfiles.ImportWake, then the class for restoredReplication); the source is the host's files manifest in the hibernate bucket, written by the agents of the boxes that held the host; every failure fails the wake; +registry:Host, +whole:Route x2;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: after the unchanged RestoreRootBaseline into <host>.restore, each sealed trio item the manifest holds (instance.key.sealed, report.token.sealed) is fetched and opened with hostfiles.ReadSealed (key, sha256, v2 envelope, binding and MAC checked) and written with instancefs.WriteAtomic (openat2 directory, no symlink, O_EXCL temp, rename, 0600) into the restore directory this function created, then that directory is synced; then the same no-replace rename. The env file comes from the sealed env item through ReadSealed when present, else from the raw env item as before, written as before. The source is still the host's files manifest in the hibernate bucket; the destinations are the same restore directory and env file; no new path is opened, followed or named from input; the sealer (sealerFor) is built only when a sealed item is present. registry:Host@97,whole:Route@1320,whole:Route@200,whole:Route@820 fe4d25409705112e6c6ad18cc1be261388b6e954fd8675344e7ce5d3c598d461 |
| +internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. file:Exec@17224,file:Open@1150,file:Statfs@42902,registry:App@11199,whole:Route@11191,whole:Route@27157 8db44678a89e88c2f7fcec2a54b0a73ce0088786968d6dd10ca3c4b88586a591 |
| +internal/activator/hafiles.go ExecBackend.sealerFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: new. Builds the host's hostfiles.ItemSealer from the backend's EscrowKey (the box's own CARLOS_SECRETS_KEY, set once by runAgent) and the binding {release.RouteAccount(rt), rt.App} for rt.Host (NewItemSealer validates the account, app and host shape); nil key is an error. Pure in memory: opens, reads and writes nothing. registry:App@334,registry:Host@343,whole:Route@324 0225e79c376c0bad00460a6b520b3f9f0cdf2468a0319f2370e0aa3fb6af091a |
| internal/hostfiles/sealed.go ReadSealed legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 2: new. Reads one sealed platform item of a files manifest the caller already loaded: the object at exactly the key the entry names, through the existing fetch (checkEntry: origin admitted, key shape, sha256 and size verified), only for an entry marked sealed "v2". The "Open" the scanner sees is appconfig.Open, an in-memory AES-GCM decryption of the fetched bytes, not a file open: no filesystem path is opened, read or followed. It refuses a v1 envelope (appconfig.EnvelopeBound), and after opening under the caller-supplied key and (account, app) binding it checks the HMAC digest over account, app, host and item against the entry. Writes nothing. No production caller in this task; Tasks 3 and 4 call it from the activator. file:Open@898 7c2b887b6e0b45472fd8d1a63a2b78eb565c4e93c89cb329eeeaef429ab0b010 |
| internal/layout/inventory.go Inventory legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 1: new. One os.ReadDir of the host's inventory root, provision.InstanceDir(dataDir, host) nested or dataDir flat, after refusing a host that fails controlname.ValidHostShape and a layout that is neither flat nor nested; reads only the listing's names and types (DirEntry.IsDir), opens and follows nothing; flat ownership is the extras scan's own (hostEntries over knownHosts); each top-level name is classified by pubclass.Of, a pure function of the name. A missing directory is an empty inventory. No caller in this task; later tasks call it from the publisher. file:ReadDir@449 9662e465abb7f9c60e908952740384479009c9987c8a6ae65d98fb19cb3d4d7e |
| +internal/activator/hafiles.go ExecBackend.newHostFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: builds a hostFiles publisher for rt (its instance paths from pathsFor(rt), rt.Host, the backend's registry, the 1 s platform and 15 min snapshot cadences); +registry:Host, +whole:Route; no I/O;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: now also sets the publisher's sealer (sealerFor(rt); its error is returned and nothing is built) and its skip, pubclass.FilesDirSkip(Nested, rt.Host), a pure function of the name, so every tree pass publishes only App paths and never the trio raw. Still no I/O; the new +registry:Host and +whole:Route sites are the sealer's and the classifier's arguments. registry:Host@228,registry:Host@313,whole:Route@128,whole:Route@217 69d03f586dc59cbc9555cc79b34d024854359b8d2a3d9ae0625ae5e8a4ad0a52 |
| +internal/activator/hafiles.go ExecBackend.openHostFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the entry's files publisher: refuses without a FilesStore or outside the nested layout, takes the one this wake's restore staged, else hostfiles.Open on <hibernate prefix>/files/0/ (one GET of the manifest from the hibernate bucket, the scanner's +file:Open); +registry:Host x2, +whole:Route x2; the manifest is written by the agents of the boxes that hold the host, through the same files store;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: asks sealerFor before hostfiles.Open, so a box without an escrow key refuses before it reads the manifest; newHostFiles's error is returned. The same manifest GET otherwise; the new +whole:Route site is sealerFor's argument. Opens nothing new. file:Open@521,registry:Host@342,registry:Host@569,whole:Route@198,whole:Route@469,whole:Route@640 f193b187884a24cd093cc19e08ad77be581005ac84c746cef8db52f1beb8dbe8 |
| +internal/activator/hafiles.go ExecBackend.stageKeptFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: on a kept wake, reads the manifest baseline the release kept beside its local record (<db>.release.files.json via readFilesBaseline, capped at 32 MiB, O_NOFOLLOW, regular files only) and stages a publisher on it only when its revision (Gen, which carries the body's SHA-256) equals the files_gen in the lock's release marker; the file is on ground the tenant can write, and anything that does not match stages nothing, so the entry re-reads the manifest from the store; it never decides the keep; +registry:Host x4, +whole:Route x2;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. The same baseline read; nothing new opened or read. registry:Host@254,registry:Host@344,registry:Host@508,registry:Host@627,registry:Host@673,whole:Route@151,whole:Route@560 d740082bbfda130c1b0b8e71dae3ff9804dbf36131bc659d147d3d41921674d2 |
| +internal/activator/hafiles.go ExecBackend.stageWakeFiles legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: opens a publisher on a manifest baseline the HA restore already holds (hostfiles.OpenBaseline, no read) and keeps it for the wake's entry; without a FilesStore it stages nothing; +registry:Host x3, +whole:Route;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: newHostFiles now answers an error (no escrow key), which is logged and stages nothing, as an OpenBaseline failure already did. No read, as before. registry:Host@185,registry:Host@300,registry:Host@419,registry:Host@465,whole:Route@352 2a9b49c4cdd022038db91a72126a31c4b0c7e81de038f9c57747522136aa361a |
| +internal/activator/hasecrets.go ExecBackend.haSecretsReady legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: before an HA host's launch, checks that env, the bytes the launch captured (captureLaunchEnv; a new parameter, final fix F2), has the SHA-256 of the committed manifest's env item (envAcknowledged, which now reads no file); else publishes the platform items (env, trio, wake state) through the wake's, the entry's or its own publisher (hostfiles.Open, the +file:Open site: one manifest GET) and checks again, so an env replaced after the capture is committed as other bytes and fails the launch; it no longer classifies the host itself (launchEnvLayer has); every error fails the launch; +file:Open, +registry:Host x3, +whole:Route;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: asks sealerFor before its own hostfiles.Open (a box without an escrow key fails the launch before any read), and newHostFiles's error fails the launch. envAcknowledged now compares the sealed env item's keyed digest (hostfiles.SealedAcknowledged, no read) instead of the raw env item's SHA-256. The publish it triggers stages the trio sealed: <host>.env, <host>/instance.key and <host>/report.token are each read with instancefs.ReadBeneathLimitOrAbsent beneath the instance directory (openat2, no symlink, regular files only, 1 MiB cap), the same reader the env already used, then sealed in memory; nothing else is opened. file:Open@390,registry:Host@1187,registry:Host@120,registry:Host@438,whole:Route@294,whole:Route@559 4f4584786d3f90a54aa3ddc1c39ffed8a62fcfd593127f534bea787c3d9b7829 |
| +internal/activator/hawake.go ExecBackend.restoreFilesClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: restores the HA host's published files into a fresh <host>.restore directory beneath the instance data dir (instancefs, no link followed), renames it into place without replacing anything, writes the manifest's env item as <host>.env (instancefs.WriteAtomic, 0600) and imports the manifest's wake state into the registry (hostfiles.ImportWake, then the class for restoredReplication); the source is the host's files manifest in the hibernate bucket, written by the agents of the boxes that held the host; every failure fails the wake; +registry:Host, +whole:Route x2;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: after the unchanged RestoreRootBaseline into <host>.restore, each sealed trio item the manifest holds (instance.key.sealed, report.token.sealed) is fetched and opened with hostfiles.ReadSealed (key, sha256, v2 envelope, binding and MAC checked) and written with instancefs.WriteAtomic (openat2 directory, no symlink, O_EXCL temp, rename, 0600) into the restore directory this function created, then that directory is synced; then the same no-replace rename. The env file comes from the sealed env item through ReadSealed when present, else from the raw env item as before, written as before. The source is still the host's files manifest in the hibernate bucket; the destinations are the same restore directory and env file; no new path is opened, followed or named from input; the sealer (sealerFor) is built only when a sealed item is present. registry:Host@97,whole:Route@1320,whole:Route@200,whole:Route@820 fe4d25409705112e6c6ad18cc1be261388b6e954fd8675344e7ce5d3c598d461 |
| @remove internal/layout/plan.go NestedPlatformNames |
| @removed internal/layout/plan.go NestedPlatformNames H3 census-ruling-durability-3a-escrow;basis=durability 3a Task 1: now a one-line wrapper for pubclass.NestedPlatformNames, which builds the same set (byte-identical, checked before and after) from pubclass.FileBases and the same instancectl/instancekey names, without nestedFiles or rawInstanceDir; it never read anything, and reads nothing now |
| -@coverage internal/activator a9f6de4b8b6267b13a954ab27ceaa93ae811da0f88c1ea9d8ed817b64b1f51a8 |
| +@coverage internal/activator 06763882dfc9b434a9a4dc46f17ad450664026e891ab6a49b0681f46659c52db |
| +@coverage internal/host c2b42d5db1c921cb0e722d50eb8cc6d19c4977a9fae0a57d1d4a6bf9e4a55242 |
| @coverage internal/hostfiles 87c6a7acbc7a2b318e564c0426e480477e10912c10deb06181cd740e322734a2 |
| @coverage internal/layout 5d8b1d3bcd0b247e8088e4fb32bc26378ece37f41dc40f1d999e23913eccc9d0 |
| @coverage internal/layout/pubclass bd3938f002a5dca044378b71670e904736653d4914a8b1e06275e2b4dc79ed67 |