carlos / platform Public

Merge main into code-health-plan

claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7916377ca7e6ee18fcdc61395c042bfff7265ec9 parent a7460d3parent fdc912b
20 files changed, +645 −24
  • AGENTS.md +5 −3
  • apimode_test.go +56 −0
  • cli.go +27 −3
  • docs/superpowers/notes/census-proposal-audit-bugs-2.md +25 −0
  • docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md +38 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md +48 −0
  • internal/activator/escrow.go +25 −5
  • internal/activator/escrow_alert_test.go +91 −0
  • internal/console/apisubdomain.go +5 −1
  • internal/console/apisubdomain_test.go +43 −0
  • internal/console/ownership.go +8 −3
  • internal/console/store_test.go +26 −0
  • internal/host/haplacement.go +6 −1
  • internal/host/haplacement_wiring_test.go +22 −0
  • internal/ledger/verify.go +34 −0
  • internal/ledger/verify_test.go +38 −0
  • internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv +14 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • system.go +49 −8
  • system_test.go +84 −0

CI passed — run details

diff --git a/AGENTS.md b/AGENTS.md
index 022fca76c..7e8fa550d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -300,9 +300,11 @@ anything.
into the CLI, which people run on Macs, so a Linux-only type assumption
breaks `go build .` for them. Cross-compiling is enough to catch it —
no Mac required.
-- Sandbox note: use `GOCACHE=/tmp/claude-1001/gocache GOFLAGS=-mod=mod
- GOPROXY=off`; go commands may need the sandbox disabled ("read-only file
- system" from the toolchain is the tell).
+- Sandbox note: leave `GOCACHE` at its default; the machine policy bans
+ pointing it anywhere else, `/tmp` above all. If the sandbox makes the
+ default cache read-only ("read-only file system" from the toolchain is
+ the tell), run the go command with the sandbox off. `GOFLAGS=-mod=mod
+ GOPROXY=off` still apply.
## Console mockups use the kit (Paul, 2026-11-08)
diff --git a/apimode_test.go b/apimode_test.go
index 185a87ed3..e9ab975e2 100644
--- a/apimode_test.go
+++ b/apimode_test.go
@@ -2661,6 +2661,62 @@ func TestLedgerVerifyVerb(t *testing.T) {
}
}
+// TestLedgerVerifyRefusesEmptyHead: a status host that serves {} or null as
+// HEAD.json gets a refusal, not a "verified" line. Before the fix this
+// returned success with an empty head digest and the verb panicked slicing
+// it for display.
+func TestLedgerVerifyRefusesEmptyHead(t *testing.T) {
+ for _, body := range []string{`{}`, `null`} {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(body))
+ }))
+ res, err := verifyPublishedLedger(ts.URL+"/", "bab", "platform", "carbon")
+ ts.Close()
+ if err == nil {
+ t.Fatalf("HEAD %s verified: %+v", body, res)
+ }
+ if !strings.Contains(err.Error(), "HEAD malformed") {
+ t.Fatalf("HEAD %s: error = %v, want a malformed-HEAD refusal", body, err)
+ }
+ }
+ if got := short12("abc"); got != "abc" {
+ t.Fatalf("short12(abc) = %q", got)
+ }
+}
+
+// TestLedgerVerifyIsBounded: a status host that accepts the request and never
+// answers fails the walk within ledgerVerifyTimeout instead of hanging the
+// command. The old verb used http.DefaultClient, which has no timeout.
+func TestLedgerVerifyIsBounded(t *testing.T) {
+ hold := make(chan struct{})
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-hold:
+ case <-r.Context().Done():
+ }
+ }))
+ defer ts.Close()
+ defer close(hold)
+
+ old := ledgerVerifyTimeout
+ ledgerVerifyTimeout = 200 * time.Millisecond
+ defer func() { ledgerVerifyTimeout = old }()
+
+ done := make(chan error, 1)
+ go func() {
+ _, err := verifyPublishedLedger(ts.URL, "bab", "platform", "carbon")
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if err == nil {
+ t.Fatal("a status host that never answered verified")
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("ledger verify still waiting on a silent status host after 10s")
+ }
+}
+
// ---- Task 3: config client methods (configGet/configApply/configSync) ----
// TestAPISessionConfigGetFullShape pins configGet's decode of the full wire
diff --git a/cli.go b/cli.go
index c9a63816c..26f6018cd 100644
--- a/cli.go
+++ b/cli.go
@@ -3824,12 +3824,36 @@ func runLedgerVerify(args []string) {
log.Fatalf("ledger verify: invalid ledger name %q", name)
}
- g := ledger.HTTPGetter(http.DefaultClient, strings.TrimRight(*urlBase, "/"))
- res, err := ledger.Verify(context.Background(), g, *account, *app, name)
+ res, err := verifyPublishedLedger(*urlBase, *account, *app, name)
if err != nil {
log.Fatal(err)
}
- fmt.Fprintf(stdout, "%s %d entries, head %s\n", colorFor(stdout).ok("verified:"), res.Count, res.HeadSHA256[:12])
+ fmt.Fprintf(stdout, "%s %d entries, head %s\n", colorFor(stdout).ok("verified:"), res.Count, short12(res.HeadSHA256))
+}
+
+// ledgerVerifyTimeout bounds each GET of a `carlos ledger verify` walk, the
+// header wait and the body together. Every object is a HEAD or one entry of
+// at most ledger.MaxBlob, so 30 s is generous; without it a status host that
+// accepts the connection and never answers hangs the command for good.
+var ledgerVerifyTimeout = 30 * time.Second
+
+// verifyPublishedLedger walks a published ledger over plain HTTPS with a
+// bounded client. The public status host needs no credential, so this is
+// a client of its own rather than a console session's.
+func verifyPublishedLedger(urlBase, account, app, name string) (ledger.VerifyResult, error) {
+ client := &http.Client{Timeout: ledgerVerifyTimeout}
+ g := ledger.HTTPGetter(client, strings.TrimRight(urlBase, "/"))
+ return ledger.Verify(context.Background(), g, account, app, name)
+}
+
+// short12 is the first 12 characters of a digest for display, or the whole
+// string when it is shorter: a display helper must never panic on a value a
+// remote server supplied.
+func short12(s string) string {
+ if len(s) > 12 {
+ return s[:12]
+ }
+ return s
}
// defaultGrantTTL is how long a scoped key lives when the operator does not
diff --git a/docs/superpowers/notes/census-proposal-audit-bugs-2.md b/docs/superpowers/notes/census-proposal-audit-bugs-2.md
new file mode 100644
index 000000000..0e0891548
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-audit-bugs-2.md
@@ -0,0 +1,25 @@
+# Census approval: audit-bugs-2
+
+Ruling `census-ruling-audit-bugs-2`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/escrow.go` `ExecBackend.EscrowSweep` | body | unchanged (31) | a failed publish is logged as an alert when isEscrowAlert (errors.As on the new escrowAlert type) says so, instead of strings.HasPrefix(err.Error(), "ALERT: "), so a joined or wrapped alert is logged plainly rather than once an hour as a routine failure; logging only, no new read |
+| `internal/activator/escrow.go` `ExecBackend.escrowConflict` | body | unchanged (1) | the refusal is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same Lstat, no new read |
+| `internal/activator/escrow.go` `ExecBackend.escrowConflictFound` | body | unchanged (4) | the alert is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same marker write, no new read |
+| `internal/activator/escrow.go` `ExecBackend.escrowedLaunchEnv` | body | unchanged (40) | the publish's alert branch matches isEscrowAlert(err) (errors.As) instead of the "ALERT: " prefix, so a joined or wrapped alert also refuses the launch as an alert; a joined alert was already refused via errEscrowUnreadable; only refuses, no new read |
+
+Envelopes re-pinned: `.`, `internal/activator`, `internal/host`, `internal/ledger`.
+
+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/activator/escrow.go` `ExecBackend.EscrowSweep`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the agent as carlos (carlos-edge.service), no root caller, from escrowLoop: classifies each row against the rows handed in (Classify), keeps eligible rows known not HA from memory (haKnown, no read), and in host order from a round-robin cursor stats each escrowed file (stampAt) and publishes the changed ones, 8 at a time, at most 256 a sweep (sweepPublish); a box without a files store or key does nothing; opens nothing outside the rows' own data directories; writes only the hibernate bucket's files/0 prefix and the ledger Fix round 1: a host whose instance lease this box does not hold (holdsLease) is skipped, and one with a conflict marker counts as failing and is not published; the report is tallied through one lock (P1-4). Durability 3a Task 5: for each lease-held candidate, the host's held publisher (st.pub under the escrow lock) is handed to noteRawBaseline. Reads only manifests this process already holds (no request, no file opened); calls the detector, which logs and calls ExecBackend.OnRawSecret; nothing else changes. The +registry:Host sites are rt.Host as the state key and the detector's argument.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: use coordinator authority for stateless projections and the unchanged serving lease for stateful rows; followers are skipped without I/O; no new poll loop or file path.
+- `internal/activator/escrow.go` `ExecBackend.escrowConflict`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 1: new: os.Lstat of <data>/.escrow/<host>.conflict, the agent's own directory; present, every launch, mint and publish of the host is refused with an alert naming the file for an operator to remove; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 2: the alert text names the divergence generally (local secrets differ from the escrow); the same Lstat.
+- `internal/activator/escrow.go` `ExecBackend.escrowConflictFound`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 2: new: the refusal for a divergent trio item: tries to write the host's conflict marker (writeEscrowMarker: EnsureDirBeneath <data>/.escrow 0700, a 0600 temp, rename, fsync), logs if it cannot, and returns the alert; the refusal holds either way, since every later publish finds the same divergence; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 3: the alert names the env file too, since a platform-minted env variable can diverge; the same marker write.
+- `internal/activator/escrow.go` `ExecBackend.escrowedLaunchEnv`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the launch path for an eligible host: captureLaunchEnv once, publishEscrowAt over those bytes, SealedAcknowledged on the commit, and the env parsed from the captured bytes; on a supersession escrowReread and the launch preparation again (ensureAdminTokenFor, ensureInstanceKeyFor) once; a not-ready box launches only a host its ledger shows escrowed; the agent as carlos (carlos-edge.service), no root caller Fix round 0 (controller readiness ruling): before the capture, the box's mode: no files store, instanceEnvLayer exactly as before 3a (logged once); no sealing key, a host whose ledger shows it escrowed launches on instanceEnvLayer (logged), otherwise keylessEscrowed (the answer this launch's restore read, within haSecretsBudget, else one GET) refuses when the bucket holds an escrow and launches on instanceEnvLayer when it holds none; nothing is published in either. Fix round 1: ends the launch's preparation; refuses while the conflict marker exists, and with a key while this box does not hold the host's lease; an ALERT from the publish fails the launch; the keyless decision uses the preparation's read. Fix round 3: a publish that answers errEscrowNoLease (the lease lost before the commit) refuses the launch with an error saying so, never the later-launch fallback. Fix round 4: a publish that answers errEscrowUnreadable or ErrEscrowNotReady (the manifest or sealed env could not be read, or does not open here) refuses the launch, never the later-launch fallback; only refuses.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: followers take read-only escrow verification/restore and never open the publisher; stateless coordinator requires ready escrow. Existing stateful publish, first-launch and conflict branches preserved.
+
+Seal: `8df52839a0c961d3721f3a5c3247d06202dae4e00d011844b7117f8e918803d4` → `1610abfc476fe45d259494242243756dac9cfec49cdd7f7f7b238329392241a1`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md b/docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md
new file mode 100644
index 000000000..1d0f8e49b
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md
@@ -0,0 +1,38 @@
+Reviewed `origin/main...7a8aa1726585d4bb6403a4d54fc1322a98535d87`, based on `c4b44c34e5deec90e6d3fa5cdffe62c7d8cad9e9`. The requested tip differs from the brief’s `6658a8db` only by adding the brief. This is round 1 of 3.
+
+Findings: **P1: none. P2: none. P3: none.** Under the stopping rule, no further review round is needed.
+
+The seven checks:
+
+1. **Ledger verification:** `Append` stores the entry before publishing HEAD, with a positive count and a lowercase SHA-256 digest. There is no legitimate empty HEAD produced by this writer. The new validation preserves valid published chains, while rejecting `{}`, `null`, missing keys and malformed digests. The timeout bounds each HTTP request, including its body, to 30 seconds; it does not bound the entire chain walk. See [append.go:74](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/ledger/append.go:74), [verify.go:48](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/ledger/verify.go:48), and [cli.go:3834](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/cli.go:3834).
+
+2. **System update and rollback:** The status-decode refusal occurs before upload or promote, so “nothing was promoted” is accurate. After acceptance, malformed or job-less responses explicitly acknowledge acceptance and direct the operator to status. An unreadable progress response says the promote may still be running. Rollback retains success when its completed operation’s response cannot supply a version. None of these added paths recommends repeating the mutation. See [system.go:379](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:379), [system.go:497](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:497), and [system.go:727](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:727).
+
+3. **Ops-account sentinel:** Both the early deletion refusal and `Store.DeleteAccount` use the sentinel. `errors.Is` recognizes wrapped refusals; unrelated errors containing “ops” receive generic advice. See [ownership.go:161](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/ownership.go:161), [ownership.go:716](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/ownership.go:716), and [ownership.go:790](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/ownership.go:790).
+
+4. **Lost subdomain-create race:** The assignment removes the shadowed `err`. The reread updates `cur`, `etag` and `err` together. Read failures refuse; occupied claims remain untouched; retired-claim writes retain their conditional-write checks. See [apisubdomain.go:468](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/apisubdomain.go:468).
+
+5. **Capacity paging:** Failed delivery is now logged with host, region and error. The callback, warning level and five-second context remain unchanged. See [haplacement.go:13](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/host/haplacement.go:13).
+
+6. **Escrow alerts:** All three constructors preserve their text. Both consumers use `errors.As`. The joined sealed-open failure already refused launch through `errEscrowUnreadable`; recognizing its alert directly preserves that refusal. The sweep now logs it through the alert branch. Repository searches found text assertions and documented alert text, but no additional production classifier depending on the old concrete error type.
+
+7. **Sandbox guidance:** The change removes the conflicting `/tmp` cache instruction and preserves the existing offline module flags.
+
+Census verdicts for this tip:
+
+| Unit or envelope | Verdict and basis |
+|---|---|
+| `ExecBackend.EscrowSweep` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:1590](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:1590), including the changed classification at 1673. Eligibility, authority checks, publication limits and reads are unchanged. |
+| `ExecBackend.escrowConflict` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:497](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:497). Same `Lstat`, same refusal conditions and text; only the error representation changes. |
+| `ExecBackend.escrowConflictFound` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:1049](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:1049). Marker creation, logging and unconditional refusal remain intact. |
+| `ExecBackend.escrowedLaunchEnv` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:1394](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:1394), including 1458–1482. No readiness, lease, conflict or sealed-acknowledgement check is weakened. |
+| Envelope `.` | **APPROVE.** Reviewed changed functions in [cli.go:3812](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/cli.go:3812) and [system.go:359](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:359), plus their request paths. No new authority or root-controlled input path. |
+| Envelope `internal/activator` | **APPROVE.** Reviewed the four units, the [error helpers at 510](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:510), `errEscrowWriter` at 1328, and publication/error propagation. No new read or write authority. |
+| Envelope `internal/host` | **APPROVE.** The sole production change is [haplacement.go:13](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/host/haplacement.go:13); it adds failure logging only. |
+| Envelope `internal/ledger` | **APPROVE.** Reviewed [verify.go:48](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/ledger/verify.go:48) through the verifier, HTTP getter and writer contract. Validation tightens acceptance without expanding reads. |
+
+The added tests cover the previous failures by source inspection. The race fixture is deterministic; timeout tests have generous margins; modified globals are restored and these tests do not run in parallel. I found no material flake risk.
+
+Changed Go files pass `gofmt -l`; the committed diff passes `git diff --check`. Runtime tests and the census gate were **not verified**: the targeted ledger test stopped before compilation because Go attempted to update `go.mod` in the read-only sandbox. No files were edited, reviewers spawned, or full suites run.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md
new file mode 100644
index 000000000..2a036ac74
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md
@@ -0,0 +1,48 @@
+# Review brief: branch audit-bugs-2, round 1 of 3
+
+Repo carlos/platform, branch `audit-bugs-2`, commit 6658a8dbdb595c16ccaae9813defc1385f4e4c64.
+Under review: the diff `origin/main...6658a8dbdb595c16ccaae9813defc1385f4e4c64` (base c4b44c34).
+Authorities: AGENTS.md on main ("The census", "Stopping rules"). Context:
+amadan #1123 batch 2, and #1141.
+
+You are the independent reviewer and the census reviewer. Card:
+`docs/superpowers/notes/census-proposal-audit-bugs-2.md`. Give a verdict
+for every unit and envelope, citing the lines you read.
+
+## What to check (one commit per item)
+
+1. ledger verify (cli.go, internal/ledger/verify.go): `checkHead` refuses
+ a malformed HEAD; the claim that no empty-ledger HEAD exists (Append
+ writes HEAD only after the first entry): true? Could a legitimate
+ published ledger now fail verification? 30 s client bound.
+2. system update (system.go): status read, systemUpdateJob and
+ watchSystemJob refuse unreadable answers and empty job ids; the
+ rollback path reports an unknown version without failing. Any case
+ where a promote that DID start is now reported as not started, or where
+ an operator is told to retry something that would double-run?
+3. console ownership.go: `errOpsAccountUndeletable` sentinel, every path
+ that returned the old text now returns the sentinel (wrapped or not)?
+4. #1141 apisubdomain.go: the lost-race path now judges the winning claim;
+ all branches after it see the right err, cur and etag.
+5. host/haplacement.go: failed capacity page now logged.
+6. activator/escrow.go: `escrowAlert` type with identical text; both call
+ sites use errors.As. Behaviour identical except a joined alert is now
+ recognised; at the sweep site the joined alert is logged as an alert
+ instead of a routine failure. Does anything else consume these
+ errors' text (tests, log scanners, runbooks, alerting) that the type
+ change could break?
+7. AGENTS.md sandbox note.
+Tests: each new one fails on the old code; any flake risk.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. Then
+the census verdict per unit and envelope. End with exactly one verdict:
+READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn
+reviewers or run full suites.
diff --git a/internal/activator/escrow.go b/internal/activator/escrow.go
index cfc7b0542..fc1b3e113 100644
--- a/internal/activator/escrow.go
+++ b/internal/activator/escrow.go
@@ -499,7 +499,27 @@ func (b *ExecBackend) escrowConflict(host string) error {
if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) {
return nil
}
- return fmt.Errorf("ALERT: %s: escrow: the host's local secrets differ from its escrow in the bucket; every launch of the host on this box is refused until an operator settles them against the escrow and removes %s", host, path)
+ return newEscrowAlert("ALERT: %s: escrow: the host's local secrets differ from its escrow in the bucket; every launch of the host on this box is refused until an operator settles them against the escrow and removes %s", host, path)
+}
+
+// escrowAlert is an escrow refusal an operator has to act on. Its text is
+// unchanged, "ALERT: " first (operators and tests read it), but callers
+// recognise one by type with isEscrowAlert, never by that prefix: an alert
+// errors.Join puts second (stageEscrowReads joins a SealedOpenError ahead of
+// one), or one wrapped with context, does not start with it.
+type escrowAlert struct{ msg string }
+
+func (e *escrowAlert) Error() string { return e.msg }
+
+// newEscrowAlert formats an escrowAlert exactly as fmt.Errorf would.
+func newEscrowAlert(format string, args ...any) error {
+ return &escrowAlert{msg: fmt.Sprintf(format, args...)}
+}
+
+// isEscrowAlert reports whether err is, wraps or joins an escrowAlert.
+func isEscrowAlert(err error) bool {
+ var a *escrowAlert
+ return errors.As(err, &a)
}
// writeEscrowConflict persists host's conflict marker, durably.
@@ -1031,7 +1051,7 @@ func (b *ExecBackend) escrowConflictFound(rt registry.Route, p instancePaths, di
if err := b.writeEscrowConflict(rt.Host, diverged); err != nil {
log.Printf("activator: %s: escrow: the conflict marker %s was not written: %v (the launch stays refused while the divergence lasts)", rt.Host, path, err)
}
- err := fmt.Errorf("ALERT: %s: escrow: %s differs from what the host's escrow in the bucket holds, and an escrowed instance.key, report.token or platform-minted env variable is never replaced; the bucket's copy came first, so this launch stops and the local files (%s and the files directory) are left for an operator; every launch of the host on this box is refused until the operator settles them against the escrow and removes %s",
+ err := newEscrowAlert("ALERT: %s: escrow: %s differs from what the host's escrow in the bucket holds, and an escrowed instance.key, report.token or platform-minted env variable is never replaced; the bucket's copy came first, so this launch stops and the local files (%s and the files directory) are left for an operator; every launch of the host on this box is refused until the operator settles them against the escrow and removes %s",
rt.Host, strings.Join(diverged, " and "), p.envFile, path)
log.Print(err)
return err
@@ -1306,7 +1326,7 @@ func (b *ExecBackend) escrowEnvOf(ctx context.Context, rt registry.Route, m host
// errEscrowWriter is the alert a second supersession raises.
func errEscrowWriter(host string) error {
- return fmt.Errorf("ALERT: %s: escrow: another writer publishes this host's escrow", host)
+ return newEscrowAlert("ALERT: %s: escrow: another writer publishes this host's escrow", host)
}
// escrowReread is a superseded publish's second look: the bucket's
@@ -1435,7 +1455,7 @@ func (b *ExecBackend) escrowedLaunchEnv(ctx context.Context, rt registry.Route)
return nil, instancekey.LayerNone, fmt.Errorf("instance key for %s: %w", rt.Host, err)
}
continue
- case err != nil && strings.HasPrefix(err.Error(), "ALERT: "):
+ case isEscrowAlert(err):
return nil, instancekey.LayerNone, err
case errors.Is(err, errEscrowNoLease):
// The lease was lost on the way to the commit, and nothing was
@@ -1650,7 +1670,7 @@ func (b *ExecBackend) EscrowSweep(ctx context.Context, rows []registry.Route) Es
tally.add(func(r *EscrowSweepReport) { r.Failing = append(r.Failing, c.rt.Host) })
// A failure that repeats every sweep (a file the tenant made
// unreadable, say) is said once an hour; an alert every time.
- if strings.HasPrefix(err.Error(), "ALERT: ") {
+ if isEscrowAlert(err) {
log.Print(err)
} else {
logPerFile("escrow", c.rt.Host, fmt.Sprintf("activator: %s: escrow: %v (retried every sweep)", c.rt.Host, err))
diff --git a/internal/activator/escrow_alert_test.go b/internal/activator/escrow_alert_test.go
new file mode 100644
index 000000000..dff6ae942
--- /dev/null
+++ b/internal/activator/escrow_alert_test.go
@@ -0,0 +1,91 @@
+package activator
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestEscrowAlertsAreRecognisedJoinedOrWrapped: each of the three escrow
+// alerts keeps its "ALERT: " text, and is recognised by type whether it is
+// bare, wrapped with %w, or second in an errors.Join, as stageEscrowReads
+// puts it behind a SealedOpenError. A prefix test on the message missed the
+// joined and wrapped forms; an error that merely says "ALERT: " is not one.
+func TestEscrowAlertsAreRecognisedJoinedOrWrapped(t *testing.T) {
+ b, rt := escrowBackend(t, escrowHost)
+ if err := writeEscrowMarker(b.DataDir, rt.Host, []byte("{}")); err != nil {
+ t.Fatal(err)
+ }
+ alerts := map[string]error{
+ "conflict marker": b.escrowConflict(rt.Host),
+ "divergence": b.escrowConflictFound(rt, b.pathsFor(rt), []string{"instance.key"}),
+ "second writer": errEscrowWriter(rt.Host),
+ }
+ other := errors.New("hostfiles: sealed item env: the envelope does not open")
+ for name, alert := range alerts {
+ if alert == nil || !strings.HasPrefix(alert.Error(), "ALERT: "+rt.Host+": escrow: ") {
+ t.Fatalf("%s: %v, want the ALERT text unchanged", name, alert)
+ }
+ for form, err := range map[string]error{
+ "bare": alert,
+ "wrapped": fmt.Errorf("secrets for %s: %w", rt.Host, alert),
+ "joined": errors.Join(other, alert),
+ } {
+ if !isEscrowAlert(err) {
+ t.Errorf("%s, %s: %q not recognised as an alert", name, form, err)
+ }
+ }
+ }
+ for _, err := range []error{nil, other, errors.New("ALERT: not an escrow alert"), errEscrowUnreadable} {
+ if isEscrowAlert(err) {
+ t.Errorf("%v recognised as an escrow alert", err)
+ }
+ }
+}
+
+// TestSweepLogsAJoinedAlertAsAnAlert: after a key change the sealed env no
+// longer opens, so stageEscrowReads joins that read failure with the
+// conflict alert, the read failure first. The sweep must still treat it as
+// an alert: logged as it stands, every time, not as an hourly "retried every
+// sweep" failure. The old prefix test saw only the read failure's text.
+func TestSweepLogsAJoinedAlertAsAnAlert(t *testing.T) {
+ // A host of its own: logPerFile's once-an-hour memory is per process.
+ const host = "alertjoin.example.com"
+ ctx := context.Background()
+ b, rt := escrowBackend(t, host)
+ b.EscrowKey = testEscrowKey(t)
+ writeEnv(t, b, rt, envA)
+ mustPublish(t, b, rt)
+
+ nb := restartEscrow(t, b)
+ nb.EscrowKey = testEscrowKey(t)
+ holdLease(t, nb, rt)
+
+ var buf bytes.Buffer
+ prev := log.Writer()
+ log.SetOutput(&buf)
+ defer log.SetOutput(prev)
+ rep := nb.EscrowSweep(ctx, []registry.Route{rt})
+ log.SetOutput(prev)
+
+ if len(rep.Failing) != 1 || rep.Failing[0] != host {
+ t.Fatalf("sweep = %+v, want %s failing", rep, host)
+ }
+ if _, err := os.Lstat(escrowConflictPath(nb.DataDir, host)); err != nil {
+ t.Fatalf("no conflict marker, so the joined alert was not raised: %v", err)
+ }
+ out := buf.String()
+ if !strings.Contains(out, "ALERT: "+host+": escrow: ") {
+ t.Fatalf("log = %q, want the alert", out)
+ }
+ if strings.Contains(out, "(retried every sweep)") {
+ t.Fatalf("the joined alert was logged as a routine sweep failure:\n%s", out)
+ }
+}
diff --git a/internal/console/apisubdomain.go b/internal/console/apisubdomain.go
index 6c1484c31..341d905da 100644
--- a/internal/console/apisubdomain.go
+++ b/internal/console/apisubdomain.go
@@ -467,7 +467,11 @@ func (s *Server) subdomainWrite(w http.ResponseWriter, ctx context.Context, acct
}
cur, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
if errors.Is(err, os.ErrNotExist) {
- newETag, created, err := domains.AttachAccountNamespace(ctx, s.cfg.Releases, name, domain, acct.Sqid,
+ // Plain assignment, not :=, so the re-read below a lost race sets
+ // the err the check after this block reads (#1141).
+ var newETag string
+ var created bool
+ newETag, created, err = domains.AttachAccountNamespace(ctx, s.cfg.Releases, name, domain, acct.Sqid,
now.UTC().Format(time.RFC3339), addr)
if err != nil {
unreadable("write", err)
diff --git a/internal/console/apisubdomain_test.go b/internal/console/apisubdomain_test.go
index ebe947589..a910c6fb7 100644
--- a/internal/console/apisubdomain_test.go
+++ b/internal/console/apisubdomain_test.go
@@ -240,6 +240,49 @@ func TestSubdomainDoorRollsBackOnRace(t *testing.T) {
}
}
+// nsLoseCreateStore lands before the door's create-only write of key, once:
+// another writer's claim reaches the key first, so the create loses with a
+// CAS conflict, as it would to a concurrent set from another console.
+type nsLoseCreateStore struct {
+ release.Store
+ key string
+ before func()
+ once sync.Once
+}
+
+func (s *nsLoseCreateStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key == s.key && ifMatch == "" && s.before != nil {
+ s.once.Do(s.before)
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+// TestSubdomainSetJudgesTheClaimThatWonTheCreateRace (#1141): the key was
+// empty when the door read it, but bcd's namespace claim landed before the
+// door's create-only write, so the create lost. The door re-reads and judges
+// the claim that won: harbour is bcd's, so the answer is occupied, naming
+// it. The lost-race branch used to shadow err with :=, so the re-read's
+// result never reached the check after it and the set was refused as
+// unreadable (a 502) instead.
+func TestSubdomainSetJudgesTheClaimThatWonTheCreateRace(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-lost-create")
+ nsAccount(t, fx, 49, "bcd")
+ fx.srv.cfg.Releases = &nsLoseCreateStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost),
+ before: func() { nsHold(t, fx, "harbour", "bcd") }}
+ fx.srv.claims.Reset()
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
+ want := fmt.Sprintf(subdomainRefuseOccupiedCopy, "harbour."+nsApps)
+ if code != http.StatusConflict || a.Error != want || a.Code != string(domains.SubdomainOccupied) {
+ t.Fatalf("set after losing the create race = %d %s, want 409 %q", code, out, want)
+ }
+ if wantHosts := []sdHost{{Host: nsHarbourHost, Account: "bcd", Source: occupantClaim}}; !reflect.DeepEqual(a.Hosts, wantHosts) {
+ t.Errorf("occupants = %+v, want %+v", a.Hosts, wantHosts)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil || c.Account != "bcd" {
+ t.Errorf("claim after the lost race = %+v, want bcd's untouched", c)
+ }
+}
+
// nsCachingRaceStore is nsRaceStore over a store that answers ListMod (the
// fixture's DirStore under its deletableStore), so the claim cache caches as
// it does in production, and it counts the reads of each key.
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 6157b416d..09a060570 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -160,7 +160,7 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
// act on by dropping its registry row.
func (s *Server) deletionRefused(w http.ResponseWriter, r *http.Request, acct *Account) bool {
if acct.ID == OpsAccountID {
- s.setFlash(w, "err", deletionAdvice(fmt.Errorf("console: ops")))
+ s.setFlash(w, "err", deletionAdvice(errOpsAccountUndeletable))
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
return true
}
@@ -718,12 +718,17 @@ func deletionAdvice(err error) string {
return "This account still holds apps. Move or retire them first — deleting an account " +
"never deletes an app."
}
- if strings.Contains(err.Error(), "ops") {
+ if errors.Is(err, errOpsAccountUndeletable) {
return "The ops account is the platform's own and cannot be deleted."
}
return "Could not delete this account."
}
+// errOpsAccountUndeletable is DeleteAccount's refusal of the ops account.
+// deletionAdvice matches it with errors.Is: matching "ops" in the message
+// also matched any store error that happened to contain those letters.
+var errOpsAccountUndeletable = errors.New("console: the ops account cannot be deleted")
+
// ---- store ------------------------------------------------------------------
// TransferOwnership promotes `to` and demotes `from`, atomically. Both must
@@ -784,7 +789,7 @@ func (s *Store) TransferOwnership(accountID int64, from, to string, now time.Tim
// done, and a deletion is not a reason to lose it.
func (s *Store) DeleteAccount(accountID int64, now time.Time) error {
if accountID == OpsAccountID {
- return fmt.Errorf("console: the ops account cannot be deleted")
+ return errOpsAccountUndeletable
}
tx, err := s.db.Begin()
if err != nil {
diff --git a/internal/console/store_test.go b/internal/console/store_test.go
index afac6ef3f..38d36bd80 100644
--- a/internal/console/store_test.go
+++ b/internal/console/store_test.go
@@ -1,6 +1,8 @@
package console
import (
+ "errors"
+ "fmt"
"path/filepath"
"reflect"
"sort"
@@ -641,6 +643,30 @@ func TestDeleteAccountRefusesOps(t *testing.T) {
}
}
+// TestDeletionAdviceNamesOpsOnlyForTheOpsRefusal: the ops-account advice is
+// given for DeleteAccount's ops refusal, wrapped or not, and for nothing else.
+// It used to be chosen by finding "ops" anywhere in the error text, so a
+// store failure such as one naming a "workshops" table told the owner their
+// account was the platform's own.
+func TestDeletionAdviceNamesOpsOnlyForTheOpsRefusal(t *testing.T) {
+ const opsAdvice = "The ops account is the platform's own and cannot be deleted."
+ s := openTestStore(t)
+ refusal := s.DeleteAccount(OpsAccountID, time.Now())
+ for _, err := range []error{refusal, fmt.Errorf("delete: %w", refusal)} {
+ if got := deletionAdvice(err); got != opsAdvice {
+ t.Fatalf("deletionAdvice(%v) = %q, want the ops advice", err, got)
+ }
+ }
+ for _, err := range []error{
+ errors.New("no such table: workshops"),
+ errors.New("database is locked; ops retried"),
+ } {
+ if got := deletionAdvice(err); got != "Could not delete this account." {
+ t.Fatalf("deletionAdvice(%v) = %q, want the generic advice", err, got)
+ }
+ }
+}
+
// TestReapAccountClearsAndMarks: materialization's verb for a manifest
// tombstoned on a LATER pass — memberships, invites and apps rows are
// deleted outright, last_account references are cleared, and the accounts
diff --git a/internal/host/haplacement.go b/internal/host/haplacement.go
index 6c6b74425..522c25604 100644
--- a/internal/host/haplacement.go
+++ b/internal/host/haplacement.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"fmt"
+ "log"
"time"
"github.com/carlosframework/platform/internal/activator"
@@ -14,6 +15,10 @@ func armHAPlacement(svc *activator.Service, page func(context.Context, string, s
svc.OnHAOverCapacity = func(region, host, ref string) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- _ = page(ctx, alerting.LevelWarning, fmt.Sprintf("Region %s needs more capacity", region), fmt.Sprintf("Region %s is short on spare capacity. Instance %s is waking on %s. Add capacity to the region.", region, host, ref))
+ if err := page(ctx, alerting.LevelWarning, fmt.Sprintf("Region %s needs more capacity", region), fmt.Sprintf("Region %s is short on spare capacity. Instance %s is waking on %s. Add capacity to the region.", region, host, ref)); err != nil {
+ // As wireRawSecretPages does: a page that fails is logged, or
+ // nobody learns the region ran short.
+ log.Printf("agent: %s: the region %s capacity page failed: %v", host, region, err)
+ }
}
}
diff --git a/internal/host/haplacement_wiring_test.go b/internal/host/haplacement_wiring_test.go
index 043e62b7f..7fc96a197 100644
--- a/internal/host/haplacement_wiring_test.go
+++ b/internal/host/haplacement_wiring_test.go
@@ -1,10 +1,13 @@
package host
import (
+ "bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "log"
"net/http/httputil"
"net/url"
"os/exec"
@@ -111,6 +114,25 @@ func TestHAPlacementPageWiring(t *testing.T) {
}
}
+// TestHAPlacementLogsAFailedPage: a capacity page the sink refuses is
+// logged, as the raw-secret page is (wireRawSecretPages). It used to be
+// dropped with _ =, so a region could run short with no trace anywhere.
+func TestHAPlacementLogsAFailedPage(t *testing.T) {
+ var buf bytes.Buffer
+ prev := log.Writer()
+ log.SetOutput(&buf)
+ t.Cleanup(func() { log.SetOutput(prev) })
+ t.Cleanup(func() { setHAAwakeApps(nil) })
+ svc := &activator.Service{}
+ armHAPlacement(svc, func(context.Context, string, string, string) error {
+ return errors.New("sink unreachable")
+ })
+ svc.OnHAOverCapacity("ie", "shop.example.com", "b")
+ if got := buf.String(); !strings.Contains(got, "shop.example.com") || !strings.Contains(got, "region ie capacity page failed: sink unreachable") {
+ t.Fatalf("log = %q, want the failed capacity page", got)
+ }
+}
+
func armHAPlacementWitness(svc *activator.Service, sink func(context.Context, string, string, string) error) {
if os.Getenv("RHASIM_MUTATE") == "placement-skips-arm" {
return
diff --git a/internal/ledger/verify.go b/internal/ledger/verify.go
index 97cd9debb..a99628905 100644
--- a/internal/ledger/verify.go
+++ b/internal/ledger/verify.go
@@ -38,6 +38,37 @@ func HTTPGetter(client *http.Client, base string) Getter {
}
}
+// checkHead refuses a HEAD that cannot name a chain. There is no empty
+// ledger HEAD: Append writes HEAD.json only after the entry it points at, so
+// a ledger with no entries has no HEAD object and the GET for it fails.
+// Every HEAD therefore names at least one entry: a non-empty head_key, that
+// entry's sha256 as 64 lowercase hex digits, and a count of one or more.
+// Without this a HEAD of {} or null decodes to the zero value, the walk never
+// starts, and the empty chain "verifies" with no head digest at all.
+func checkHead(h Head) error {
+ switch {
+ case h.Count < 1:
+ return fmt.Errorf("ledger: HEAD malformed: count %d, a HEAD names at least one entry", h.Count)
+ case h.HeadKey == "":
+ return fmt.Errorf("ledger: HEAD malformed: no head_key")
+ case !isSHA256Hex(h.HeadSHA256):
+ return fmt.Errorf("ledger: HEAD malformed: head_sha256 %q is not a sha256 digest", h.HeadSHA256)
+ }
+ return nil
+}
+
+func isSHA256Hex(s string) bool {
+ if len(s) != 64 {
+ return false
+ }
+ for _, c := range s {
+ if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
+ return false
+ }
+ }
+ return true
+}
+
type VerifyResult struct {
Count int
HeadSHA256 string
@@ -56,6 +87,9 @@ func Verify(ctx context.Context, get Getter, sqid, app, name string) (VerifyResu
if err := json.Unmarshal(hb, &head); err != nil {
return VerifyResult{}, fmt.Errorf("ledger: HEAD corrupt: %w", err)
}
+ if err := checkHead(head); err != nil {
+ return VerifyResult{}, err
+ }
// The walk follows keys the CHAIN supplies (HEAD.json's head_key, then
// each entry's prev_key), so those keys are exactly as trustworthy as the
diff --git a/internal/ledger/verify_test.go b/internal/ledger/verify_test.go
index 4139c2fab..c16eb1289 100644
--- a/internal/ledger/verify_test.go
+++ b/internal/ledger/verify_test.go
@@ -134,3 +134,41 @@ func TestVerifyOverHTTP(t *testing.T) {
t.Fatalf("res=%+v err=%v", res, err)
}
}
+
+// TestVerifyRefusesMalformedHead: a HEAD that decodes but names no chain
+// ({}, null, a zero count, a missing key, a digest that is not a sha256) is
+// refused, never reported as a clean empty ledger. Before checkHead, {} and
+// null decoded to the zero Head, the walk never started, and Verify returned
+// success with an empty HeadSHA256, which the CLI then sliced and panicked on.
+func TestVerifyRefusesMalformedHead(t *testing.T) {
+ ctx := context.Background()
+ key := Prefix("bab", "platform", "carbon") + "entries/x.json"
+ sha := strings.Repeat("a", 64)
+ for name, head := range map[string]string{
+ "empty object": `{}`,
+ "null": `null`,
+ "zero count": `{"head_key":"` + key + `","head_sha256":"` + sha + `","count":0}`,
+ "negative count": `{"count":-1}`,
+ "no key": `{"head_sha256":"` + sha + `","count":1}`,
+ "no digest": `{"head_key":"` + key + `","count":1}`,
+ "short digest": `{"head_key":"` + key + `","head_sha256":"abc","count":1}`,
+ "upper digest": `{"head_key":"` + key + `","head_sha256":"` + strings.Repeat("A", 64) + `","count":1}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ get := func(_ context.Context, k string) ([]byte, error) {
+ if k == HeadKey("bab", "platform", "carbon") {
+ return []byte(head), nil
+ }
+ t.Fatalf("walked to %s from a malformed HEAD", k)
+ return nil, nil
+ }
+ res, err := Verify(ctx, get, "bab", "platform", "carbon")
+ if err == nil {
+ t.Fatalf("HEAD %s verified: %+v", head, res)
+ }
+ if !strings.Contains(err.Error(), "HEAD malformed") {
+ t.Fatalf("error = %v, want it to say the HEAD is malformed", err)
+ }
+ })
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv b/internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv
new file mode 100644
index 000000000..683200eee
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv
@@ -0,0 +1,14 @@
+# Census overlay audit-bugs-2, written by census-propose (#369). census-ruling-audit-bugs-2, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-audit-bugs-2.md.
+# 4 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 51a7ec904ec6d600eaa102b5d87f46c9c3d9417745dc91b9106420b3a7a00051 internal/activator/escrow.go ExecBackend.EscrowSweep legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the agent as carlos (carlos-edge.service), no root caller, from escrowLoop: classifies each row against the rows handed in (Classify), keeps eligible rows known not HA from memory (haKnown, no read), and in host order from a round-robin cursor stats each escrowed file (stampAt) and publishes the changed ones, 8 at a time, at most 256 a sweep (sweepPublish); a box without a files store or key does nothing; opens nothing outside the rows' own data directories; writes only the hibernate bucket's files/0 prefix and the ledger Fix round 1: a host whose instance lease this box does not hold (holdsLease) is skipped, and one with a conflict marker counts as failing and is not published; the report is tallied through one lock (P1-4). Durability 3a Task 5: for each lease-held candidate, the host's held publisher (st.pub under the escrow lock) is handed to noteRawBaseline. Reads only manifests this process already holds (no request, no file opened); calls the detector, which logs and calls ExecBackend.OnRawSecret; nothing else changes. The +registry:Host sites are rt.Host as the state key and the detector's argument.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: use coordinator authority for stateless projections and the unchanged serving lease for stateful rows; followers are skipped without I/O; no new poll loop or file path.;rev3=census-ruling-audit-bugs-2;basis=a failed publish is logged as an alert when isEscrowAlert (errors.As on the new escrowAlert type) says so, instead of strings.HasPrefix(err.Error(), "ALERT: "), so a joined or wrapped alert is logged plainly rather than once an hour as a routine failure; logging only, no new read registry:Host@1009,registry:Host@1046,registry:Host@1136,registry:Host@1292,registry:Host@1311,registry:Host@1462,registry:Host@1995,registry:Host@2341,registry:Host@2575,registry:Host@2649,registry:Host@536,registry:Host@800,registry:Host@938,whole:Route@1193,whole:Route@1197,whole:Route@1214,whole:Route@1301,whole:Route@1320,whole:Route@1471,whole:Route@1789,whole:Route@1997,whole:Route@2227,whole:Route@2343,whole:Route@2577,whole:Route@2651,whole:Route@356,whole:Route@519,whole:Route@587,whole:Route@653,whole:Route@706,whole:Route@771 1e14fab5e73211227bc9e3149d0b2ebd8275776b9e29b186bb66df72f12bb626
+@legacy 4e7267d7dedb59073fb53828c363fd955744195215cf62f75cb88999946943b6 internal/activator/escrow.go ExecBackend.escrowConflict legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 1: new: os.Lstat of <data>/.escrow/<host>.conflict, the agent's own directory; present, every launch, mint and publish of the host is refused with an alert naming the file for an operator to remove; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 2: the alert text names the divergence generally (local secrets differ from the escrow); the same Lstat.;rev3=census-ruling-audit-bugs-2;basis=the refusal is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same Lstat, no new read file:Lstat@117 2813507167377d322febb10abcb556a42d56f1a4b0715bbf190da36dd8e63c40
+@legacy 5de0a4472b24b196937fe2ea4749207e45a3cd2f1caad5e14669d5bd5124ad60 internal/activator/escrow.go ExecBackend.escrowConflictFound legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 2: new: the refusal for a divergent trio item: tries to write the host's conflict marker (writeEscrowMarker: EnsureDirBeneath <data>/.escrow 0700, a 0600 temp, rename, fsync), logs if it cannot, and returns the alert; the refusal holds either way, since every later publish finds the same divergence; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 3: the alert names the env file too, since a platform-minted env variable can diverge; the same marker write.;rev3=census-ruling-audit-bugs-2;basis=the alert is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same marker write, no new read registry:Host@144,registry:Host@186,registry:Host@355,registry:Host@819 0d17cb55ff4c39a7d079fcf81d6900467347159b3c35d01bd2358dc457a99a82
+@legacy a01e384e755d13eccb2be5fddb1cef0f68946fb6a8c9062309b5a0dfe6ce91ea internal/activator/escrow.go ExecBackend.escrowedLaunchEnv legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the launch path for an eligible host: captureLaunchEnv once, publishEscrowAt over those bytes, SealedAcknowledged on the commit, and the env parsed from the captured bytes; on a supersession escrowReread and the launch preparation again (ensureAdminTokenFor, ensureInstanceKeyFor) once; a not-ready box launches only a host its ledger shows escrowed; the agent as carlos (carlos-edge.service), no root caller Fix round 0 (controller readiness ruling): before the capture, the box's mode: no files store, instanceEnvLayer exactly as before 3a (logged once); no sealing key, a host whose ledger shows it escrowed launches on instanceEnvLayer (logged), otherwise keylessEscrowed (the answer this launch's restore read, within haSecretsBudget, else one GET) refuses when the bucket holds an escrow and launches on instanceEnvLayer when it holds none; nothing is published in either. Fix round 1: ends the launch's preparation; refuses while the conflict marker exists, and with a key while this box does not hold the host's lease; an ALERT from the publish fails the launch; the keyless decision uses the preparation's read. Fix round 3: a publish that answers errEscrowNoLease (the lease lost before the commit) refuses the launch with an error saying so, never the later-launch fallback. Fix round 4: a publish that answers errEscrowUnreadable or ErrEscrowNotReady (the manifest or sealed env could not be read, or does not open here) refuses the launch, never the later-launch fallback; only refuses.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: followers take read-only escrow verification/restore and never open the publisher; stateless coordinator requires ready escrow. Existing stateful publish, first-launch and conflict branches preserved.;rev3=census-ruling-audit-bugs-2;basis=the publish's alert branch matches isEscrowAlert(err) (errors.As) instead of the "ALERT: " prefix, so a joined or wrapped alert also refuses the launch as an alert; a joined alert was already refused via errEscrowUnreadable; only refuses, no new read registry:Host@1012,registry:Host@1115,registry:Host@1242,registry:Host@1390,registry:Host@145,registry:Host@1545,registry:Host@1630,registry:Host@1798,registry:Host@2000,registry:Host@2262,registry:Host@2423,registry:Host@2842,registry:Host@3245,registry:Host@3413,registry:Host@3534,registry:Host@3708,registry:Host@3924,registry:Host@441,registry:Host@838,registry:Host@967,registry:Stateless@158,registry:Stateless@249,whole:Route@1162,whole:Route@1313,whole:Route@1452,whole:Route@1678,whole:Route@1907,whole:Route@198,whole:Route@2165,whole:Route@2325,whole:Route@238,whole:Route@290,whole:Route@408,whole:Route@534,whole:Route@577,whole:Route@622,whole:Route@672,whole:Route@719,whole:Route@894,whole:Route@938 3b98f460b501e2b650cf5502c2407dcdaf281d8aabd0930e9fd09e1fb9e0249e
+internal/activator/escrow.go ExecBackend.EscrowSweep legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the agent as carlos (carlos-edge.service), no root caller, from escrowLoop: classifies each row against the rows handed in (Classify), keeps eligible rows known not HA from memory (haKnown, no read), and in host order from a round-robin cursor stats each escrowed file (stampAt) and publishes the changed ones, 8 at a time, at most 256 a sweep (sweepPublish); a box without a files store or key does nothing; opens nothing outside the rows' own data directories; writes only the hibernate bucket's files/0 prefix and the ledger Fix round 1: a host whose instance lease this box does not hold (holdsLease) is skipped, and one with a conflict marker counts as failing and is not published; the report is tallied through one lock (P1-4). Durability 3a Task 5: for each lease-held candidate, the host's held publisher (st.pub under the escrow lock) is handed to noteRawBaseline. Reads only manifests this process already holds (no request, no file opened); calls the detector, which logs and calls ExecBackend.OnRawSecret; nothing else changes. The +registry:Host sites are rt.Host as the state key and the detector's argument.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: use coordinator authority for stateless projections and the unchanged serving lease for stateful rows; followers are skipped without I/O; no new poll loop or file path.;rev3=census-ruling-audit-bugs-2;basis=a failed publish is logged as an alert when isEscrowAlert (errors.As on the new escrowAlert type) says so, instead of strings.HasPrefix(err.Error(), "ALERT: "), so a joined or wrapped alert is logged plainly rather than once an hour as a routine failure; logging only, no new read registry:Host@1009,registry:Host@1046,registry:Host@1136,registry:Host@1292,registry:Host@1311,registry:Host@1462,registry:Host@1995,registry:Host@2341,registry:Host@2575,registry:Host@2649,registry:Host@536,registry:Host@800,registry:Host@938,whole:Route@1193,whole:Route@1197,whole:Route@1214,whole:Route@1301,whole:Route@1320,whole:Route@1471,whole:Route@1789,whole:Route@1997,whole:Route@2227,whole:Route@2343,whole:Route@2577,whole:Route@2651,whole:Route@356,whole:Route@519,whole:Route@587,whole:Route@653,whole:Route@706,whole:Route@771 1e14fab5e73211227bc9e3149d0b2ebd8275776b9e29b186bb66df72f12bb626
+internal/activator/escrow.go ExecBackend.escrowConflict legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 1: new: os.Lstat of <data>/.escrow/<host>.conflict, the agent's own directory; present, every launch, mint and publish of the host is refused with an alert naming the file for an operator to remove; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 2: the alert text names the divergence generally (local secrets differ from the escrow); the same Lstat.;rev3=census-ruling-audit-bugs-2;basis=the refusal is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same Lstat, no new read file:Lstat@117 2813507167377d322febb10abcb556a42d56f1a4b0715bbf190da36dd8e63c40
+internal/activator/escrow.go ExecBackend.escrowConflictFound legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 2: new: the refusal for a divergent trio item: tries to write the host's conflict marker (writeEscrowMarker: EnsureDirBeneath <data>/.escrow 0700, a 0600 temp, rename, fsync), logs if it cannot, and returns the alert; the refusal holds either way, since every later publish finds the same divergence; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 3: the alert names the env file too, since a platform-minted env variable can diverge; the same marker write.;rev3=census-ruling-audit-bugs-2;basis=the alert is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same marker write, no new read registry:Host@144,registry:Host@186,registry:Host@355,registry:Host@819 0d17cb55ff4c39a7d079fcf81d6900467347159b3c35d01bd2358dc457a99a82
+internal/activator/escrow.go ExecBackend.escrowedLaunchEnv legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the launch path for an eligible host: captureLaunchEnv once, publishEscrowAt over those bytes, SealedAcknowledged on the commit, and the env parsed from the captured bytes; on a supersession escrowReread and the launch preparation again (ensureAdminTokenFor, ensureInstanceKeyFor) once; a not-ready box launches only a host its ledger shows escrowed; the agent as carlos (carlos-edge.service), no root caller Fix round 0 (controller readiness ruling): before the capture, the box's mode: no files store, instanceEnvLayer exactly as before 3a (logged once); no sealing key, a host whose ledger shows it escrowed launches on instanceEnvLayer (logged), otherwise keylessEscrowed (the answer this launch's restore read, within haSecretsBudget, else one GET) refuses when the bucket holds an escrow and launches on instanceEnvLayer when it holds none; nothing is published in either. Fix round 1: ends the launch's preparation; refuses while the conflict marker exists, and with a key while this box does not hold the host's lease; an ALERT from the publish fails the launch; the keyless decision uses the preparation's read. Fix round 3: a publish that answers errEscrowNoLease (the lease lost before the commit) refuses the launch with an error saying so, never the later-launch fallback. Fix round 4: a publish that answers errEscrowUnreadable or ErrEscrowNotReady (the manifest or sealed env could not be read, or does not open here) refuses the launch, never the later-launch fallback; only refuses.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: followers take read-only escrow verification/restore and never open the publisher; stateless coordinator requires ready escrow. Existing stateful publish, first-launch and conflict branches preserved.;rev3=census-ruling-audit-bugs-2;basis=the publish's alert branch matches isEscrowAlert(err) (errors.As) instead of the "ALERT: " prefix, so a joined or wrapped alert also refuses the launch as an alert; a joined alert was already refused via errEscrowUnreadable; only refuses, no new read registry:Host@1012,registry:Host@1115,registry:Host@1242,registry:Host@1390,registry:Host@145,registry:Host@1545,registry:Host@1630,registry:Host@1798,registry:Host@2000,registry:Host@2262,registry:Host@2423,registry:Host@2842,registry:Host@3245,registry:Host@3413,registry:Host@3534,registry:Host@3708,registry:Host@3924,registry:Host@441,registry:Host@838,registry:Host@967,registry:Stateless@158,registry:Stateless@249,whole:Route@1162,whole:Route@1313,whole:Route@1452,whole:Route@1678,whole:Route@1907,whole:Route@198,whole:Route@2165,whole:Route@2325,whole:Route@238,whole:Route@290,whole:Route@408,whole:Route@534,whole:Route@577,whole:Route@622,whole:Route@672,whole:Route@719,whole:Route@894,whole:Route@938 3b98f460b501e2b650cf5502c2407dcdaf281d8aabd0930e9fd09e1fb9e0249e
+@coverage . e0e1c2cf1540c9e2c196b7ed48b23c2a666d296157de709ca06b45236e770f83
+@coverage internal/activator 09d8de3860da15a033b9b5230383bec93eb95cff029659f7dd001ac64e958eab
+@coverage internal/host ed966179bf9c3c818a815ca284d4fd59c0bf6602bf84a9f6a1d1e91d03e4a73f
+@coverage internal/ledger 01aa8d104e7820e67739da46c184cc3c27d252e8584fe7d25e28909d14311024
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 62225b972..cb0019cd5 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -242,3 +242,4 @@ plan14-root-reads-audit-edge-test-sleeps.tsv 4abde13ec40d53a479684b7f1e2079fbedb
plan14-root-reads-ha-generations-floor.tsv 7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54
plan14-root-reads-fix-1193-wal-close-test.tsv 7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54
plan14-root-reads-ha-1192.tsv 8df52839a0c961d3721f3a5c3247d06202dae4e00d011844b7117f8e918803d4
+plan14-root-reads-audit-bugs-2.tsv 1610abfc476fe45d259494242243756dac9cfec49cdd7f7f7b238329392241a1
diff --git a/system.go b/system.go
index 3dc87b9c9..4702c331f 100644
--- a/system.go
+++ b/system.go
@@ -385,7 +385,11 @@ func runSystemUpdate(args []string) {
log.Fatalf("carlos system update: %s", apiErrorFromBody(st, body))
}
var cur systemStatusResponse
- _ = json.Unmarshal(body, &cur)
+ if err := json.Unmarshal(body, &cur); err != nil {
+ // Read on, and the preview below would say "0 box(es) will roll"
+ // about a promote that may reach every box.
+ log.Fatalf("carlos system update: could not read the console's system status, so there is no telling which boxes this would reach; nothing was promoted (%v)", err)
+ }
var reach []string
for _, b := range cur.Boxes {
if b.Channel == *channel {
@@ -455,11 +459,11 @@ func runSystemUpdate(args []string) {
}
log.Fatalf("carlos system update: %s", apiErrorFromBody(st, body))
}
- var started struct {
- Job string `json:"job"`
+ job, err := systemUpdateJob(body, *channel)
+ if err != nil {
+ log.Fatal(err)
}
- _ = json.Unmarshal(body, &started)
- if err := sess.watchSystemJob(ctx, started.Job, stdout); err != nil {
+ if err := sess.watchSystemJob(ctx, job, stdout); err != nil {
log.Fatal(err)
}
fmt.Fprintf(stdout, "%s boxes on %s roll themselves; watch with: carlos system status --channel %s\n",
@@ -486,11 +490,31 @@ func systemLadderWarning(pointers map[string]*systemPointerRow, channel, version
return fmt.Sprintf("warning: %s has not been on canary; promoting straight to stable", version)
}
+// systemUpdateJob reads the job id out of the console's 200 answer to a
+// promote. The promote is already under way by then, so neither refusal
+// says it failed: each says the job cannot be watched from here and where
+// to look instead. An empty id used to be polled as /jobs/ for 15 minutes.
+func systemUpdateJob(body []byte, channel string) (string, error) {
+ var started struct {
+ Job string `json:"job"`
+ }
+ if err := json.Unmarshal(body, &started); err != nil {
+ return "", fmt.Errorf("carlos system update: the console accepted the promote but its answer could not be read (%v); follow it with: carlos system status --channel %s", err, channel)
+ }
+ if started.Job == "" {
+ return "", fmt.Errorf("carlos system update: the console accepted the promote but named no job to watch; follow it with: carlos system status --channel %s", channel)
+ }
+ return started.Job, nil
+}
+
// watchSystemJob polls the job and prints each step once, as deploy's
// watchVersion does for a route. The console runs the promote off the
// request precisely so a dropped connection cannot abandon it, so this is a
// view of work already under way, not the work itself.
func (s *apiSession) watchSystemJob(ctx context.Context, id string, w io.Writer) error {
+ if id == "" {
+ return errors.New("carlos system update: no job to watch")
+ }
printed := 0
deadline := time.Now().Add(15 * time.Minute)
for {
@@ -506,7 +530,11 @@ func (s *apiSession) watchSystemJob(ctx context.Context, id string, w io.Writer)
Done bool `json:"done"`
Error string `json:"error"`
}
- _ = json.Unmarshal(body, &j)
+ if err := json.Unmarshal(body, &j); err != nil {
+ // An unreadable answer never says done, so polling on would
+ // spin for the whole 15 minutes on a reply that will not change.
+ return fmt.Errorf("carlos system update: job %s: could not read the console's progress report (%v); the promote may still be running", id, err)
+ }
for ; printed < len(j.Steps); printed++ {
fmt.Fprintf(w, " %s\n", j.Steps[printed])
}
@@ -688,11 +716,24 @@ func runSystemRollback(args []string) {
if st != http.StatusOK {
log.Fatalf("carlos system rollback: %s", apiErrorFromBody(st, body))
}
+ printSystemRolledBack(stdout, *channel, body)
+}
+
+// printSystemRolledBack reports a rollback the console has already done
+// (it answered 200). An answer that cannot be read or names no version
+// still means the rollback happened, so this never fails the command: a
+// non-zero exit would invite a second rollback, one release further back.
+// It says the version is unknown and where to read it instead.
+func printSystemRolledBack(w io.Writer, channel string, body []byte) {
var out struct {
Version string `json:"version"`
}
- _ = json.Unmarshal(body, &out)
- fmt.Fprintf(stdout, "%s %s → %s\n", colorFor(stdout).ok("rolled back"), *channel, out.Version)
+ if err := json.Unmarshal(body, &out); err != nil || out.Version == "" {
+ fmt.Fprintf(w, "%s %s; the console did not say which release it is on now. check with: carlos system status --channel %s\n",
+ colorFor(w).ok("rolled back"), channel, channel)
+ return
+ }
+ fmt.Fprintf(w, "%s %s → %s\n", colorFor(w).ok("rolled back"), channel, out.Version)
}
// systemPDFCommand is `carlos system pdf status`. Bare is the usage and
diff --git a/system_test.go b/system_test.go
index bafb4f22e..cda1616c5 100644
--- a/system_test.go
+++ b/system_test.go
@@ -11,6 +11,7 @@ import (
"os/exec"
"path/filepath"
"strings"
+ "sync/atomic"
"testing"
"time"
)
@@ -432,3 +433,86 @@ func TestSystemGroupMaintenanceVerb(t *testing.T) {
}
}
}
+
+// TestSystemUpdateJobRefusesNoJob: the console's 200 answer to a promote
+// must name a job. An unreadable answer or one with no id is refused with
+// where to follow the promote instead; before, both came out as "" and the
+// CLI polled /api/cli/system/jobs/ for 15 minutes.
+func TestSystemUpdateJobRefusesNoJob(t *testing.T) {
+ for _, body := range []string{`{}`, `{"job":""}`, `not json`, ``} {
+ job, err := systemUpdateJob([]byte(body), "canary")
+ if err == nil {
+ t.Fatalf("answer %q gave job %q, want a refusal", body, job)
+ }
+ if !strings.Contains(err.Error(), "carlos system status --channel canary") {
+ t.Fatalf("answer %q: %v, want it to say where to follow the promote", body, err)
+ }
+ }
+ if job, err := systemUpdateJob([]byte(`{"job":"j1"}`), "canary"); err != nil || job != "j1" {
+ t.Fatalf("job = %q, %v; want j1", job, err)
+ }
+}
+
+// TestWatchSystemJobStopsOnNoJobOrUnreadableReport: watchSystemJob never polls
+// an empty id, and a progress report it cannot read ends the watch at once
+// instead of polling an answer that will never say done for 15 minutes.
+func TestWatchSystemJobStopsOnNoJobOrUnreadableReport(t *testing.T) {
+ var emptyPolls, jobPolls atomic.Int32
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/cli/system/jobs/":
+ emptyPolls.Add(1)
+ w.Write([]byte(`{}`))
+ case "/api/cli/system/jobs/j1":
+ jobPolls.Add(1)
+ w.Write([]byte(`<html>not a job</html>`))
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(ts.Close)
+ sess := &apiSession{c: newConsoleClient(ts.URL, "tok"), console: ts.URL}
+
+ watch := func(id string) error {
+ done := make(chan error, 1)
+ go func() { done <- sess.watchSystemJob(context.Background(), id, io.Discard) }()
+ select {
+ case err := <-done:
+ return err
+ case <-time.After(5 * time.Second):
+ t.Fatalf("watchSystemJob(%q) still polling after 5s", id)
+ return nil
+ }
+ }
+ if err := watch(""); err == nil {
+ t.Fatal("watched a job with no id")
+ }
+ if n := emptyPolls.Load(); n != 0 {
+ t.Fatalf("polled /api/cli/system/jobs/ %d times for an empty id", n)
+ }
+ err := watch("j1")
+ if err == nil || !strings.Contains(err.Error(), "could not read") {
+ t.Fatalf("unreadable report: %v, want a could-not-read error", err)
+ }
+ if n := jobPolls.Load(); n != 1 {
+ t.Fatalf("polled j1 %d times, want 1", n)
+ }
+}
+
+// TestSystemRollbackReportsAnUnreadableAnswer: a rollback the console has
+// done is reported as done even when its answer names no version, and the
+// line says where to read the version rather than ending in a blank arrow.
+func TestSystemRollbackReportsAnUnreadableAnswer(t *testing.T) {
+ for _, body := range []string{`{}`, `not json`} {
+ var out bytes.Buffer
+ printSystemRolledBack(&out, "canary", []byte(body))
+ if !strings.Contains(out.String(), "rolled back canary;") || !strings.Contains(out.String(), "carlos system status --channel canary") {
+ t.Fatalf("answer %q printed %q", body, out.String())
+ }
+ }
+ var out bytes.Buffer
+ printSystemRolledBack(&out, "canary", []byte(`{"version":"v0.31.0"}`))
+ if !strings.Contains(out.String(), "canary → v0.31.0") {
+ t.Fatalf("printed %q", out.String())
+ }
+}