hostedcert: read the suite verdict past budget's record; stop rule in v6
Task 13 review round 2. The containment suite's verdict is the PASS or FAIL m.Run prints, followed by nothing or exactly one budget.Main record, so a real run with its footer certifies and anything else does not. The evidence stop rule moves from version 5 (back to its bec02feb bytes) to migration 6, with a test upgrading a version 5 database. Mutations 126 to 130.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+218
−17
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+19 −0internal/hostedcert/probe_linux.go+31 −4internal/hostedcert/probe_linux_test.go+31 −0internal/hostedctl/ctlcert/report.go+1 −1internal/hostedctl/schema/0005_cert_report.sql+0 −10internal/hostedctl/schema/0006_cert_evidence_stop.sql+10 −0internal/hostedctl/store.go+2 −1internal/hostedctl/testdata/schema-0005-bec02feb.sql+40 −0internal/hostedctl/upgrade_test.go+83 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index db7d9cd4..49c0a8a6 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -84,4 +84,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin, |
| # branch uses an indexed primary-key lookup, one current-member/device check, |
| # and the same bounded cardView as the snapshot; no list scan or new route. |
| perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen. |
| -size internal/hostedctl 6037 9907 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. |
| +size internal/hostedctl 6038 9990 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 6f78d812..9278f291 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1026,3 +1026,22 @@ Mutation checks, applied and restored as for mutations 97 to 108 (exact unique s |
| 123. The module caches not checked. Same test: FAIL `probe_linux_test.go:344: an unwritable module cache: "blocked", want inconclusive`. Restored. |
| 124. Every lookup error blocked. Same test: FAIL `probe_linux_test.go:360: lookup something else: "blocked", want "inconclusive"`. Restored. |
| 125. Local errnos not excluded from tool text. Same test: FAIL `probe_linux_test.go:333: go mod download one attempt local: "blocked", want "inconclusive"`. Restored. |
| + |
| +### Task 13 review round 2 (t13-r2.md: round 1 all addressed; two new Important findings, both fixed) |
| + |
| +1. **The suite's verdict, read explicitly.** The containment suite's `TestMain` runs `budget.Main`, which prints `rastrillo-budget/v1 ran <duration>` after `m.Run`'s `PASS`, so taking the last line as the summary failed every real run. `readSuite` now keeps the last two lines that are not blank, as printed, and `suiteVerdict` takes `PASS` or `FAIL` at the start of a line, followed by nothing or by exactly one budget record whose duration parses. Anything else after the verdict, a second record, or a record with no verdict gives no verdict, and Judge fails it. The completeness checks are unchanged. The representative fixture now ends with the real footer; `TestRunContainmentVerdict` holds `budget.Prefix` to the reader's prefix. |
| +2. **The stop rule is migration 6.** `0005_cert_report.sql` is back to its bec02feb bytes; `cert_evidence_needs_stop` is `0006_cert_evidence_stop.sql`. `TestUpgradeFromVersion5` builds a database from versions 1 to 4 and bec02feb's version 5 (`testdata/schema-0005-bec02feb.sql`, from `git show bec02feb:...`) at `user_version` 5 with a job in it, opens it, and finds version 6, evidence for a launch with no stop refused, and evidence for one with its stop recorded kept. hostedctl budget raised to 6038/9990 (the migration list wraps one line; the upgrade test). |
| + |
| +Red: |
| +- 1: the footer added to the fixture and `TestRunContainmentVerdict` written first: `go test ./internal/hostedcert -run TestRunContainment -count=1` FAIL `TestRunContainmentRepresentativeVM` (`probe_linux_test.go:484`) and `TestRunContainmentVerdict` (`probe_linux_test.go:524: verdict and the record: summary "rastrillo-budget/v1 ran 1.5s", want "PASS"`, `FAIL and the record: ... want "FAIL"`, `another line after: summary "ok all fine", want ""`). |
| +- 2: `go test ./internal/hostedctl -run TestUpgradeFromVersion5 -count=1` with the trigger still in 0005: FAIL `upgrade_test.go:69: the upgraded database kept evidence for a launch with no stop recorded`. |
| + |
| +Green: the covering packages (`./internal/hostedcert ./internal/hostedctl/... ./internal/hostedproxy/... ./internal/runner/hosted ./cmd/equipo-hosted-certify ./cmd/equipo-runner ./internal/vminit ./internal/hostedclient ./cmd/equipo-hosted-controller`): ok. `make budget build vet`: ok. staticcheck v0.7.0, gofmt, `git diff --check`: clean. |
| + |
| +Mutation checks, as before (exact unique string replaced, `go test -count=1`, restored and checked byte-equal); each compiled and failed on an assertion. |
| + |
| +126. The summary is the last line again. `go test ./internal/hostedcert -run TestRunContainment`: FAIL `probe_linux_test.go:484: result = {...}` (the representative VM) and `probe_linux_test.go:524: the record twice: summary "rastrillo-budget/v1 ran 2s", want ""`. Restored. |
| +127. Any one line after the verdict is skipped (the prefix check replaced). `-run TestRunContainmentVerdict`: FAIL `probe_linux_test.go:524: another line after: summary "PASS", want ""`, `verdict alone: summary "", want "PASS"`. Restored. |
| +128. The record's duration not checked. Same test: FAIL `probe_linux_test.go:524: a record of no duration: summary "PASS", want ""`. Restored. |
| +129. A budget record alone counts as PASS. Same test: FAIL `probe_linux_test.go:524: FAIL and the record: summary "PASS", want "FAIL"`, `a record and no verdict: summary "PASS", want ""`. Restored. |
| +130. Migration 6 left out of the list. `go test ./internal/hostedctl -run TestUpgradeFromVersion5`: FAIL `upgrade_test.go:69: the upgraded database kept evidence for a launch with no stop recorded`. Restored. |
diff --git a/internal/hostedcert/probe_linux.go b/internal/hostedcert/probe_linux.go| index d265e810..84aafa5d 100644 |
| --- a/internal/hostedcert/probe_linux.go |
| +++ b/internal/hostedcert/probe_linux.go |
| @@ -738,20 +738,22 @@ func RunContainment(ctx context.Context, path string, run func(ctx context.Conte |
| // SKIP: name" record is a test with its result; a skip's reason is the |
| // last message that test logged (" file.go:N: message" lines, which |
| // belong to the test the last "=== RUN/CONT/NAME" line named). The |
| -// summary is the last line. Problems are what makes the read incomplete: |
| +// summary is the suite's verdict (suiteVerdict). Problems are what makes |
| +// the read incomplete: |
| // a line too long to scan, a scanner error, or a test that started with |
| // no result. |
| func readSuite(out []byte) (tests []ContainmentTest, summary string, problems []string) { |
| results := map[string]string{"--- PASS: ": TestPassed, "--- FAIL: ": TestFailed, "--- SKIP: ": TestSkipped} |
| started, logged := map[string]bool{}, map[string]string{} |
| - current, last := "", "" |
| + current := "" |
| + var tail []string // the last two lines that are not blank, as printed |
| sc := bufio.NewScanner(bytes.NewReader(out)) |
| sc.Buffer(make([]byte, 4096), maxSuiteLine) |
| for sc.Scan() { |
| raw := sc.Text() |
| line := strings.TrimSpace(raw) |
| if line != "" { |
| - last = line |
| + tail = append(tail[max(0, len(tail)-1):], strings.TrimRight(raw, "\r")) |
| } |
| if name, ok := marker(line); ok { |
| current = name |
| @@ -788,7 +790,32 @@ func readSuite(out []byte) (tests []ContainmentTest, summary string, problems [] |
| problems = append(problems, "test "+name+" started with no result") |
| } |
| slices.Sort(problems) |
| - return tests, last, problems |
| + return tests, suiteVerdict(tail), problems |
| +} |
| + |
| +// budgetRecordPrefix starts the one line budget.Main (rastrillo) prints |
| +// after m.Run's verdict, in the containment suite's TestMain; a test |
| +// holds it equal to budget.Prefix. |
| +const budgetRecordPrefix = "rastrillo-budget/v1 ran " |
| + |
| +// suiteVerdict is the suite's own verdict from the last two lines that |
| +// are not blank: "PASS" or "FAIL", as m.Run prints it at the start of a |
| +// line, followed by nothing or by exactly one budget record |
| +// ("rastrillo-budget/v1 ran <duration>"). Anything else is no verdict: |
| +// "". |
| +func suiteVerdict(tail []string) string { |
| + if n := len(tail); n > 0 { |
| + if d, ok := strings.CutPrefix(tail[n-1], budgetRecordPrefix); ok { |
| + if _, err := time.ParseDuration(d); err != nil { |
| + return "" |
| + } |
| + tail = tail[:n-1] |
| + } |
| + } |
| + if n := len(tail); n > 0 && (tail[n-1] == "PASS" || tail[n-1] == "FAIL") { |
| + return tail[n-1] |
| + } |
| + return "" |
| } |
| // marker reads a "=== RUN/CONT/NAME/PAUSE name" line. |
diff --git a/internal/hostedcert/probe_linux_test.go b/internal/hostedcert/probe_linux_test.go| index 30beff30..a19d5394 100644 |
| --- a/internal/hostedcert/probe_linux_test.go |
| +++ b/internal/hostedcert/probe_linux_test.go |
| @@ -20,6 +20,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedcert" |
| "amadan.net/oficina/equipo/internal/vminit" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| ) |
| // TestRootProbesAreVMInits: the root probes, outcomes and file names the |
| @@ -421,6 +422,7 @@ const vmContainmentOutput = `=== RUN TestCgroupSessionRule |
| --- PASS: TestMountsReadOnly (0.12s) |
| --- PASS: TestEgressDenied (0.20s) |
| PASS |
| +rastrillo-budget/v1 ran 4.217s |
| ` |
| func suite(t *testing.T) string { |
| @@ -495,6 +497,35 @@ func TestRunContainmentRepresentativeVM(t *testing.T) { |
| } |
| } |
| +// TestRunContainmentVerdict: the summary is the suite's own verdict, the |
| +// PASS or FAIL m.Run prints, followed by nothing but the one record |
| +// budget.Main prints; anything else after it, or no verdict, leaves no |
| +// PASS to certify. |
| +func TestRunContainmentVerdict(t *testing.T) { |
| + if budget.Prefix != "rastrillo-budget/v1 ran " { |
| + t.Fatalf("budget.Main's record now starts %q; the verdict reader must follow it", budget.Prefix) |
| + } |
| + tests := "=== RUN TestA\n--- PASS: TestA (0.00s)\n" |
| + for what, c := range map[string]struct { |
| + out, summary string |
| + }{ |
| + "verdict alone": {tests + "PASS\n", "PASS"}, |
| + "verdict and the record": {tests + "PASS\nrastrillo-budget/v1 ran 1.5s\n", "PASS"}, |
| + "FAIL and the record": {tests + "FAIL\nrastrillo-budget/v1 ran 1.5s\n", "FAIL"}, |
| + "the record twice": {tests + "PASS\nrastrillo-budget/v1 ran 1.5s\nrastrillo-budget/v1 ran 2s\n", ""}, |
| + "a record of no duration": {tests + "PASS\nrastrillo-budget/v1 ran soon\n", ""}, |
| + "another line after": {tests + "PASS\nok all fine\n", ""}, |
| + "a record and no verdict": {tests + "rastrillo-budget/v1 ran 1.5s\n", ""}, |
| + "no verdict at all": {tests, ""}, |
| + "a verdict-like log line": {tests + " a_test.go:1: PASS\n", ""}, |
| + } { |
| + c2 := hostedcert.RunContainment(context.Background(), suite(t), runs(0, c.out, nil)) |
| + if c2.Summary != c.summary { |
| + t.Errorf("%s: summary %q, want %q", what, c2.Summary, c.summary) |
| + } |
| + } |
| +} |
| + |
| // TestRunContainmentIncomplete: output cut at the capture limit, a line |
| // too long to scan, a test that started with no result, or a missing |
| // summary leaves the result incomplete or unsummarised, and Judge fails |
diff --git a/internal/hostedctl/ctlcert/report.go b/internal/hostedctl/ctlcert/report.go| index a32ed9c2..75cee20a 100644 |
| --- a/internal/hostedctl/ctlcert/report.go |
| +++ b/internal/hostedctl/ctlcert/report.go |
| @@ -131,7 +131,7 @@ type jobRow struct { |
| // Before the evidence is kept, stop records the launch's stop in tx (the |
| // controller's own stop, which revokes its serials): the VM's one report |
| // is in. The store refuses evidence for a launch with no stop recorded |
| -// (schema version 5), so the evidence and the stop obligation commit |
| +// (schema version 6), so the evidence and the stop obligation commit |
| // together or not at all, and the controller's refresh drives every |
| // recorded stop to proof, across restarts. |
| func AcceptReport(ctx context.Context, tx *sql.Tx, q hostedwire.CertReport, now ctlproxy.Now, cfg ReportConfig, |
diff --git a/internal/hostedctl/schema/0005_cert_report.sql b/internal/hostedctl/schema/0005_cert_report.sql| index eedd857d..1e0c0581 100644 |
| --- a/internal/hostedctl/schema/0005_cert_report.sql |
| +++ b/internal/hostedctl/schema/0005_cert_report.sql |
| @@ -27,16 +27,6 @@ CREATE TABLE cert_evidence ( |
| received_t INTEGER NOT NULL |
| ); |
| --- Evidence only for a launch whose stop is recorded: acceptance records |
| --- the controller's stop of the reporting VM first, in the same |
| --- transaction, so no report is ever in while its VM is left to run. |
| -CREATE TRIGGER cert_evidence_needs_stop |
| -BEFORE INSERT ON cert_evidence |
| -WHEN (SELECT stop_requested_t FROM jobs WHERE launch_id = NEW.launch_id) IS NULL |
| -BEGIN |
| - SELECT RAISE(ABORT, 'evidence needs the launch''s stop recorded'); |
| -END; |
| - |
| CREATE TRIGGER cert_evidence_immutable |
| BEFORE UPDATE ON cert_evidence |
| BEGIN |
diff --git a/internal/hostedctl/schema/0006_cert_evidence_stop.sql b/internal/hostedctl/schema/0006_cert_evidence_stop.sql| new file mode 100644 |
| index 00000000..1d3a470d |
| --- /dev/null |
| +++ b/internal/hostedctl/schema/0006_cert_evidence_stop.sql |
| @@ -0,0 +1,10 @@ |
| +-- Schema version 6: evidence only for a launch whose stop is recorded. |
| +-- Acceptance (ctlcert.AcceptReport) records the controller's stop of the |
| +-- reporting VM first, in the same transaction, so no report is ever in |
| +-- while its VM is left to run; this rule holds it for every writer. |
| +CREATE TRIGGER cert_evidence_needs_stop |
| +BEFORE INSERT ON cert_evidence |
| +WHEN (SELECT stop_requested_t FROM jobs WHERE launch_id = NEW.launch_id) IS NULL |
| +BEGIN |
| + SELECT RAISE(ABORT, 'evidence needs the launch''s stop recorded'); |
| +END; |
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go| index 48a00870..185b7fe7 100644 |
| --- a/internal/hostedctl/store.go |
| +++ b/internal/hostedctl/store.go |
| @@ -51,7 +51,8 @@ var schemaFS embed.FS |
| // migrations are applied in order; version n is migrations[n-1]. Add a file, |
| // never edit one. |
| -var migrations = []string{"schema/0001_jobs.sql", "schema/0002_egress.sql", "schema/0003_cert.sql", "schema/0004_proxy.sql", "schema/0005_cert_report.sql"} |
| +var migrations = []string{"schema/0001_jobs.sql", "schema/0002_egress.sql", "schema/0003_cert.sql", "schema/0004_proxy.sql", "schema/0005_cert_report.sql", |
| + "schema/0006_cert_evidence_stop.sql"} |
| // schemaVersion is the newest schema this code knows. |
| func schemaVersion() int { return len(migrations) } |
diff --git a/internal/hostedctl/testdata/schema-0005-bec02feb.sql b/internal/hostedctl/testdata/schema-0005-bec02feb.sql| new file mode 100644 |
| index 00000000..1e0c0581 |
| --- /dev/null |
| +++ b/internal/hostedctl/testdata/schema-0005-bec02feb.sql |
| @@ -0,0 +1,40 @@ |
| +-- Schema version 5: certification reports (package ctlcert, report.go). |
| + |
| +-- Each client certificate's public key (PKIX DER), so a certification |
| +-- report signed with the VM's certificate key can be checked against the |
| +-- key the controller certified. Serials issued before this version keep |
| +-- none, and no report verifies against them. |
| +ALTER TABLE proxy_certs ADD COLUMN public_key BLOB; |
| + |
| +CREATE TRIGGER proxy_certs_key_immutable |
| +BEFORE UPDATE OF public_key ON proxy_certs |
| +WHEN NEW.public_key IS NOT OLD.public_key |
| +BEGIN |
| + SELECT RAISE(ABORT, 'certificate key is immutable'); |
| +END; |
| + |
| +-- One certification report per launch, kept as the evidence the |
| +-- controller signed: the exact evidence bytes (hostedcert.Evidence as |
| +-- JSON) and the controller's signature over them. Rows never change and |
| +-- are never deleted. |
| +CREATE TABLE cert_evidence ( |
| + launch_id TEXT PRIMARY KEY REFERENCES jobs(launch_id), |
| + attempt_id TEXT NOT NULL UNIQUE REFERENCES jobs(attempt_id), |
| + evidence_id TEXT NOT NULL UNIQUE, |
| + serial TEXT NOT NULL REFERENCES proxy_certs(serial), |
| + evidence_json BLOB NOT NULL, |
| + sig BLOB NOT NULL, |
| + received_t INTEGER NOT NULL |
| +); |
| + |
| +CREATE TRIGGER cert_evidence_immutable |
| +BEFORE UPDATE ON cert_evidence |
| +BEGIN |
| + SELECT RAISE(ABORT, 'evidence is immutable'); |
| +END; |
| + |
| +CREATE TRIGGER cert_evidence_never_deleted |
| +BEFORE DELETE ON cert_evidence |
| +BEGIN |
| + SELECT RAISE(ABORT, 'evidence is never deleted'); |
| +END; |
diff --git a/internal/hostedctl/upgrade_test.go b/internal/hostedctl/upgrade_test.go| new file mode 100644 |
| index 00000000..b21cb805 |
| --- /dev/null |
| +++ b/internal/hostedctl/upgrade_test.go |
| @@ -0,0 +1,83 @@ |
| +package hostedctl |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" |
| +) |
| + |
| +// TestUpgradeFromVersion5: a database made by bec02feb (schema version 5 |
| +// as it shipped there, testdata/schema-0005-bec02feb.sql, with a |
| +// certification report's evidence table but no stop rule) is upgraded on |
| +// Open, keeps its rows, and from then on refuses evidence for a launch |
| +// whose stop is not recorded, as a fresh database does. |
| +func TestUpgradeFromVersion5(t *testing.T) { |
| + ctx := context.Background() |
| + path := filepath.Join(t.TempDir(), "hosted.db") |
| + db := rawDB(t, path) |
| + v5, err := os.ReadFile(filepath.Join("testdata", "schema-0005-bec02feb.sql")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tx, err := db.Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, m := range migrations[:4] { |
| + body, err := schemaFS.ReadFile(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := tx.Exec(string(body)); err != nil { |
| + t.Fatalf("%s: %v", m, err) |
| + } |
| + } |
| + if _, err := tx.Exec(string(v5)); err != nil { |
| + t.Fatalf("bec02feb's version 5: %v", err) |
| + } |
| + if err := insertJob(ctx, tx, "att-old"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := tx.Exec(`PRAGMA user_version = 5`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = db.Close() |
| + |
| + s := openStore(t, path, isolatedjobtest.NewFakeClock(testWall)) |
| + var version int |
| + err = s.Tx(ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&version) }) |
| + if err != nil || version != schemaVersion() { |
| + t.Fatalf("user_version after Open = %d (%v), want %d", version, err, schemaVersion()) |
| + } |
| + evidence := func(tx *sql.Tx, attempt string) error { |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_certs (serial, launch_id, attempt_id, vm_ref, epoch, issued_t, not_after_t) |
| + VALUES (?, ?, ?, 'vm-1', 1, 0, 100)`, "ab"+attempt[len(attempt)-1:], "launch-"+attempt, attempt); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, `INSERT INTO cert_evidence (launch_id, attempt_id, evidence_id, serial, evidence_json, sig, received_t) |
| + VALUES (?, ?, ?, ?, x'7b7d', x'00', 1)`, "launch-"+attempt, attempt, "evidence-"+attempt, "ab"+attempt[len(attempt)-1:]) |
| + return err |
| + } |
| + if err := s.Tx(ctx, func(tx *sql.Tx) error { return evidence(tx, "att-old") }); err == nil { |
| + t.Fatal("the upgraded database kept evidence for a launch with no stop recorded") |
| + } |
| + err = s.Tx(ctx, func(tx *sql.Tx) error { |
| + if err := insertJob(ctx, tx, "att-2"); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE jobs SET stop_requested_t = 1, stop_reason = 'certification_reported' WHERE attempt_id = 'att-2'`); err != nil { |
| + return err |
| + } |
| + return evidence(tx, "att-2") |
| + }) |
| + if err != nil { |
| + t.Fatalf("evidence for a launch whose stop is recorded: %v", err) |
| + } |
| +} |