oficina / equipo Public

hostedcert: containment test by test, stop with evidence, local failures

Task 13 review round 1. The containment suite is judged test by test:
only TestNamespaceCgroupMoveKeepsMembership may skip, with its one
message; truncated, unscannable or unsummarised output fails. A report's
stop is recorded in the transaction that keeps its evidence (the store
refuses evidence without it) and Refresh drives it to proof. Probe
failures that are local (EMFILE, a socket or cache not permitted) are
inconclusive, from structured errno results. Mutations 109 to 125.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a116d330304462dc94f9cadab8d3144fef1682f6 parent bec02fe
17 files changed, +999 −165
  • .rastrillo/budgets.txt +1 −1
  • cmd/equipo-hosted-certify/main_test.go +3 −2
  • cmd/equipo-runner/hosted_certify_linux.go +25 −10
  • cmd/equipo-runner/hosted_certify_linux_test.go +19 −0
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +34 −0
  • internal/hostedcert/buildscript_linux_test.go +50 −0
  • internal/hostedcert/evidence.go +35 −10
  • internal/hostedcert/judge.go +41 −10
  • internal/hostedcert/judge_test.go +47 −7
  • internal/hostedcert/matrix.go +16 −1
  • internal/hostedcert/probe_linux.go +271 −63
  • internal/hostedcert/probe_linux_test.go +236 −13
  • internal/hostedctl/ctlcert/report.go +12 −2
  • internal/hostedctl/ctlcert/report_test.go +160 −22
  • internal/hostedctl/proxy.go +17 −15
  • internal/hostedctl/schema/0005_cert_report.sql +10 −0
  • internal/hostedctl/stop.go +22 −9
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 867a0b9c..db7d9cd4 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 6022 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.
+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.
diff --git a/cmd/equipo-hosted-certify/main_test.go b/cmd/equipo-hosted-certify/main_test.go
index 80fa1d7f..5b6610d3 100644
--- a/cmd/equipo-hosted-certify/main_test.go
+++ b/cmd/equipo-hosted-certify/main_test.go
@@ -52,8 +52,9 @@ func manifest() hostedimage.Manifest {
// as m pins.
func passingReport(m hostedimage.Manifest, launch string) hostedcert.Report {
r := hostedcert.Report{LaunchID: launch, Root: []hostedcert.ProbeResult{}, User: []hostedcert.ProbeResult{}, Sandbox: []hostedcert.ProbeResult{},
- Measured: m.Measured(),
- Containment: hostedcert.ContainmentResult{Binary: m.ContainmentTestSHA256, Args: hostedcert.ContainmentArgs(), Passed: 30}}
+ Measured: m.Measured(),
+ Containment: hostedcert.ContainmentResult{Binary: m.ContainmentTestSHA256, Args: hostedcert.ContainmentArgs(),
+ Tests: []hostedcert.ContainmentTest{{Name: "TestA", Result: hostedcert.TestPassed}}, Summary: "PASS", Complete: true}}
for _, e := range hostedcert.Matrix() {
p := hostedcert.ProbeResult{Name: e.Name, Stage: e.Stage, Outcome: e.Want, OK: true}
switch e.Stage {
diff --git a/cmd/equipo-runner/hosted_certify_linux.go b/cmd/equipo-runner/hosted_certify_linux.go
index 323373d5..f76669af 100644
--- a/cmd/equipo-runner/hosted_certify_linux.go
+++ b/cmd/equipo-runner/hosted_certify_linux.go
@@ -71,37 +71,49 @@ func certify(ctx context.Context, s *hosted.Session, state, results string) erro
return s.SendReport(ctx, raw)
}
+// plainLimit is how much of the suite's output runPlain keeps.
+var plainLimit = 4 << 20
+
// runPlain runs argv as this process's user, with its environment, and
// returns the exit code and combined output (at most 4 MiB).
func runPlain(ctx context.Context, argv []string) (int, []byte, error) {
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
var out limited
- out.max = 4 << 20
+ out.max = plainLimit
cmd.Stdout, cmd.Stderr = &out, &out
err := cmd.Run()
var exit *exec.ExitError
+ code := -1
switch {
case err == nil:
- return 0, out.b.Bytes(), nil
+ code = 0
case errors.As(err, &exit):
- return exit.ExitCode(), out.b.Bytes(), nil
+ code = exit.ExitCode()
+ default:
+ return -1, out.b.Bytes(), err
+ }
+ if out.over {
+ return code, out.b.Bytes(), hostedcert.ErrTruncated
}
- return -1, out.b.Bytes(), err
+ return code, out.b.Bytes(), nil
}
-// limited keeps the first max bytes written to it.
+// limited keeps the first max bytes written to it, and whether more came.
type limited struct {
- mu sync.Mutex
- b bytes.Buffer
- max int
+ mu sync.Mutex
+ b bytes.Buffer
+ max int
+ over bool
}
func (l *limited) Write(p []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
- if room := l.max - l.b.Len(); room > 0 {
- l.b.Write(p[:min(len(p), room)])
+ room := l.max - l.b.Len()
+ if len(p) > room {
+ l.over = true
}
+ l.b.Write(p[:max(0, min(len(p), room))])
return len(p), nil
}
@@ -146,6 +158,9 @@ func checksSandbox(state string) hostedcert.SandboxRunner {
go func() { defer copied.Done(); _, _ = io.Copy(io.Discard, proc.Stderr()) }()
exit, err := proc.Wait(ctx)
copied.Wait()
+ if err == nil && stdout.over {
+ err = hostedcert.ErrTruncated
+ }
return stdout.b.Bytes(), exit.Code, err
}
}
diff --git a/cmd/equipo-runner/hosted_certify_linux_test.go b/cmd/equipo-runner/hosted_certify_linux_test.go
index c95bc06a..232b4f68 100644
--- a/cmd/equipo-runner/hosted_certify_linux_test.go
+++ b/cmd/equipo-runner/hosted_certify_linux_test.go
@@ -3,8 +3,11 @@
package main
import (
+ "context"
+ "errors"
"testing"
+ "amadan.net/oficina/equipo/internal/hostedcert"
"amadan.net/oficina/equipo/internal/hostedimage"
)
@@ -16,3 +19,19 @@ func TestCertifyPathsAreTheImages(t *testing.T) {
hostedimage.PathBwrap, hostedimage.PathContainmentTest)
}
}
+
+// TestRunPlainReportsTruncation: output past the capture limit is cut and
+// reported as hostedcert.ErrTruncated, never returned as if whole; output
+// within it is whole.
+func TestRunPlainReportsTruncation(t *testing.T) {
+ defer func(n int) { plainLimit = n }(plainLimit)
+ plainLimit = 16
+ exit, out, err := runPlain(context.Background(), []string{"/bin/sh", "-c", "printf 'PASS line one\\nPASS line two\\n'"})
+ if !errors.Is(err, hostedcert.ErrTruncated) || len(out) != 16 || exit != 0 {
+ t.Errorf("over the limit: exit %d, %q, %v; want 16 bytes and ErrTruncated", exit, out, err)
+ }
+ exit, out, err = runPlain(context.Background(), []string{"/bin/sh", "-c", "printf short; exit 3"})
+ if err != nil || string(out) != "short" || exit != 3 {
+ t.Errorf("within the limit: exit %d, %q, %v", exit, out, err)
+ }
+}
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index eb75ecf8..6f78d812 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -992,3 +992,37 @@ Mutation checks. Each was applied by a script that replaced one exact, unique st
108. vm-init reports an answered probe as blocked (`res.Outcome = OutcomeBlocked` for `failed`).
- `go test ./internal/vminit -run TestRootProbeOutcomes`
- FAIL: `init_test.go:1167: answered: root_vpc_dns_silent outcome "blocked", want "reached"`. Restored.
+
+### Task 13 review round 1 (t13-r1.md: findings 1 to 4 fixed; 5 ruled out; 6 kept as a recorded deviation)
+
+1. **The containment suite, test by test.** `ContainmentResult` now keeps every test and subtest with its result (`Tests []ContainmentTest{Name, Result, Reason}`), the output's last line (`Summary`) and `Complete`; the counts are gone. `readSuite` attributes each logged message to the test the last `=== RUN/CONT/NAME` line named, and a skip's reason is that test's last message. `Judge` (`judgeContainment`) needs exit 0, summary `PASS`, a whole read, at least one test, each name once, and every test passed except `TestNamespaceCgroupMoveKeepsMembership` skipped with exactly "no systemd user session; production containment does not use cgroups" (`AuthorisedSkips()`, in the trusted matrix). Any other skip, a failure, a repeated name, a missing or FAIL summary fails. `TestRunContainmentRepresentativeVM` reads a VM's output (subtests, interleaved parallel logs, the authorised skip) and certifies it.
+2. **Incomplete output fails.** The scanner reads lines of at most 64 KiB; a scanner error (an over-long line), a test that started with no result, or output past the capture limit makes the result incomplete. `runPlain` (the suite) and the sandbox runner report `hostedcert.ErrTruncated` when output went past their limits, and `RunContainment` keeps what came but marks it incomplete.
+3. **The stop commits with the evidence.** `AcceptReport` takes a `stop` callback and calls it in its transaction before keeping the evidence; the controller passes `recordStop` (requestStop's work, split out to run in the caller's transaction), which records the stop request, revokes the serials and audits. Schema version 5 gains `cert_evidence_needs_stop`: the store refuses evidence for a launch with no stop recorded, so evidence and the stop obligation commit together or not at all. The provider stop is then driven on a context the request's end does not cancel; any stop not proven (a refusing provider, a crash, a cancelled request) is driven to proof by `Refresh`, which drives every recorded stop. Version 5 is unreleased (nothing outside this branch has opened it), so the trigger went into `0005_cert_report.sql` rather than a version 6.
+4. **Local failures are inconclusive.** `denied` counts only timeouts, `ECONNREFUSED`, `EHOSTUNREACH`, `ENETUNREACH`, `EAFNOSUPPORT`, and `EPERM`/`EACCES` from `connect` (a firewall); `EMFILE`, `ENFILE`, `ENOMEM`, `ENOBUFS`, `EADDRNOTAVAIL`, `ENOSPC`, `EROFS`, a permission refusal from any other call, and a cancellation are inconclusive, also when joined to a network refusal. The build-script program now prints one structured line (`dial ok`, or `dial failed syscall=S errno=N timeout=B`), which the probe classifies with `denied`; anything else is inconclusive (`TestBuildScriptProgramReportsStructuredFailure` compiles and runs the program against a closed loopback port). `go mod download` runs with `-json`, after a check that its caches are writable; only the module's own `Error` is classified, by the same errno texts (`textOutcome`), local and filesystem failures first. A name lookup is blocked only when not found, timed out or refused.
+
+Red (tests written before each fix, after a field-only type change so they failed on assertions):
+- 1 and 2: `go test ./internal/hostedcert -count=1` FAIL `TestJudgeContainmentInFull` (`judge_test.go:177: a VM's run with the authorised skip: Judge = hostedcert: the evidence does not certify the image`), `TestRunContainment`, `TestRunContainmentRepresentativeVM` (`probe_linux_test.go:357`: skip reason empty, summary empty), `TestRunContainmentIncomplete` (`probe_linux_test.go:392: an over-long line ... certified`, `a test with no result ... certified`, `no summary ... certified`); `go test ./cmd/equipo-runner -run TestRunPlainReportsTruncation` FAIL `hosted_certify_linux_test.go:31: over the limit: exit 0, "PASS line one\nPA", <nil>; want 16 bytes and ErrTruncated`.
+- 3: `go test ./internal/hostedctl/ctlcert -run TestEvidenceNeedsStopRecorded` FAIL `report_test.go:519: evidence was kept for a launch with no stop recorded`. `TestReportStopSurvivesRestart` and `TestReportStopSurvivesCancellation` (both assert the stored stop proof) passed before the fix: regression guards, shown failing by mutations 116 and 118.
+- 4: `go test ./internal/hostedcert -count=1` FAIL `TestSandboxProbeFailuresClassified` (`probe_linux_test.go:281: dial socket not permitted: sandbox_direct_ipv4 = "blocked", want "inconclusive"`; `:304: build script the old text: "blocked"`; `:331: go mod download out of descriptors: "blocked"`, `cache not writable: "blocked"`; `:344: an unwritable module cache: "blocked"`; `:360: lookup out of descriptors: "blocked"`).
+
+Green: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedproxy/... ./internal/runner/hosted ./cmd/equipo-hosted-certify ./cmd/equipo-runner ./internal/vminit ./internal/hostedclient -count=1`: ok. `make budget build vet`: ok (hostedctl record raised to 6037/9907 with the reason). staticcheck v0.7.0 on the changed packages, gofmt and `git diff --check`: clean.
+
+Mutation checks, applied and restored as for mutations 97 to 108 (exact unique string replaced, `go test -count=1`, file restored and checked byte-equal). Each compiled and failed on an assertion.
+
+109. Any skip passes (`case t.Result == TestSkipped && (authorised && t.Reason == reason || true):`). `go test ./internal/hostedcert -run TestJudgeContainmentInFull`: FAIL `judge_test.go:199: containment: a subtest skipped: Judge = <nil> ...`, `... another test skipped with the authorised reason ...`. Restored.
+110. The authorised skip's reason not checked (`authorised && (t.Reason == reason || true)`). Same test: FAIL `judge_test.go:199: containment: the authorised test skipped for another reason: Judge = <nil>`. Restored.
+111. Completeness not judged (the `!c.Complete` case removed). `-run 'TestJudgeContainmentInFull|TestRunContainmentIncomplete'`: FAIL `judge_test.go:199: containment: output not whole: Judge = <nil>` and `probe_linux_test.go:519: past the capture limit: {... Complete:false ...} certified`. Restored.
+112. A scanner error ignored (`_ = err` for the problem). `-run TestRunContainmentIncomplete`: FAIL `probe_linux_test.go:519: an over-long last line: {... Summary:PASS Complete:true ...} certified`. Restored.
+113. `RunContainment` ignores `ErrTruncated`. Same test: FAIL `probe_linux_test.go:519: past the capture limit: {... Complete:true ...} certified`. Restored.
+114. `runPlain` hides truncation (the `out.over` return removed). `go test ./cmd/equipo-runner -run TestRunPlainReportsTruncation`: FAIL `hosted_certify_linux_test.go:31: over the limit: exit 0, "PASS line one\nPA", <nil>`. Restored.
+115. A skip's reason not read from its log. `-run TestRunContainmentRepresentativeVM`: FAIL `probe_linux_test.go:480: result = {...}`. Restored.
+116. `AcceptReport` records no stop (`stop(j.AttemptID)` not called). `go test ./internal/hostedctl/ctlcert -run 'TestReportOncePerLaunch|TestReportStopSurvives'`: FAIL `report_test.go:420: first report = 500 internal` (the store refused the evidence), `report_test.go:560: report = 500`. Restored.
+117. The store keeps evidence with no stop (the trigger's condition `WHEN 0`). `-run 'TestEvidenceNeedsStopRecorded|TestReportOncePerLaunch'`: FAIL `report_test.go:530: evidence was kept for a launch with no stop recorded`, `report_test.go:462: AcceptReport with a stop that records nothing = <nil>`. Restored.
+118. Neither (116 and 117 together: acceptance with no stop obligation, as before the fix). `-run TestReportStopSurvives`: FAIL `report_test.go:594: after the report with the provider refusing: stop asked false, 1 serials unrevoked, proof { false}` and `report_test.go:563: the provider stop was never sent`. Both files restored.
+119. Any permission refusal blocks a dial (`se.Syscall == "connect"` dropped). `go test ./internal/hostedcert -run TestSandboxProbeFailuresClassified`: FAIL `probe_linux_test.go:281: dial socket not permitted: ... "blocked", want "inconclusive"`, `:304: build script socket refused: "blocked"`. Restored.
+120. Local errnos not excluded from dials (the `localErrnos` loop in `denied` removed). Same test: FAIL `probe_linux_test.go:282: dial one attempt local: sandbox_direct_ipv4 = "blocked", want "inconclusive"`. Restored. (Run first without the joined-error case, this mutation survived; the case was added and it then failed.)
+121. A tool's permission refusal counts as blocked. Same test: FAIL `probe_linux_test.go:331: go mod download cache not writable: "blocked", want "inconclusive"`. Restored.
+122. Every build-script failure blocked (`dialLine`'s last return). Same test: FAIL `probe_linux_test.go:304: build script out of descriptors: "blocked"`, `socket refused: "blocked"`. Restored.
+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.
diff --git a/internal/hostedcert/buildscript_linux_test.go b/internal/hostedcert/buildscript_linux_test.go
new file mode 100644
index 00000000..d33e1d0a
--- /dev/null
+++ b/internal/hostedcert/buildscript_linux_test.go
@@ -0,0 +1,50 @@
+//go:build linux
+
+package hostedcert
+
+import (
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// TestBuildScriptProgramReportsStructuredFailure: the build-script
+// program compiles with the Go toolchain alone and, dialled at a closed
+// loopback port, prints the one line dialLine reads: connect, ECONNREFUSED,
+// no timeout, which is blocked.
+func TestBuildScriptProgramReportsStructuredFailure(t *testing.T) {
+ if testing.Short() {
+ t.Skip("builds a program")
+ }
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ addr := ln.Addr().String()
+ ln.Close()
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(buildScript), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ goBin, err := exec.LookPath("go")
+ if err != nil {
+ t.Skip("no go command on PATH")
+ }
+ cmd := exec.Command(goBin, "run", "main.go", addr)
+ cmd.Dir = dir
+ cmd.Env = append(os.Environ(), "GOFLAGS=", "GOWORK=off", "CGO_ENABLED=0")
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("go run: %v: %s", err, out)
+ }
+ line := strings.TrimSpace(string(out))
+ if line != probeMark+"dial failed syscall=connect errno=111 timeout=false" {
+ t.Fatalf("the program printed %q", line)
+ }
+ if o, ok := dialLine(line); !ok || o != OutcomeBlocked {
+ t.Errorf("dialLine(%q) = %q, %v; want blocked", line, o, ok)
+ }
+}
diff --git a/internal/hostedcert/evidence.go b/internal/hostedcert/evidence.go
index 53e88a87..a27db277 100644
--- a/internal/hostedcert/evidence.go
+++ b/internal/hostedcert/evidence.go
@@ -57,18 +57,35 @@ type ProbeResult struct {
// ContainmentResult is one run of the image's containment suite
// (ContainmentArgs): the SHA-256 of the binary that ran, its arguments,
-// its exit code, and its verbose output's counts of passed, failed and
-// skipped tests.
+// its exit code, every test and subtest its verbose output reported with
+// its result (a skip with the message it logged), the output's last line
+// (the suite's own summary, PASS or FAIL), and whether the output was
+// read whole: within the capture limit, every line scanned, every test
+// that started given a result.
type ContainmentResult struct {
- Binary string `json:"binary"`
- Args []string `json:"args"`
- ExitCode int `json:"exit_code"`
- Passed int `json:"passed"`
- Failed int `json:"failed"`
- Skipped int `json:"skipped"`
- Detail string `json:"detail"`
+ Binary string `json:"binary"`
+ Args []string `json:"args"`
+ ExitCode int `json:"exit_code"`
+ Tests []ContainmentTest `json:"tests"`
+ Summary string `json:"summary"`
+ Complete bool `json:"complete"`
+ Detail string `json:"detail"`
}
+// ContainmentTest is one test's result in the suite's output.
+type ContainmentTest struct {
+ Name string `json:"name"`
+ Result string `json:"result"` // TestPassed, TestFailed or TestSkipped
+ Reason string `json:"reason"` // a skip's last logged message
+}
+
+// A containment test's results.
+const (
+ TestPassed = "pass"
+ TestFailed = "fail"
+ TestSkipped = "skip"
+)
+
// Report is what a certification VM reports.
type Report struct {
LaunchID string `json:"launch_id"`
@@ -84,6 +101,8 @@ const (
maxProbes = 64
maxProbeDetail = 2048
maxMeasured = 128
+ maxTests = 1024 // containment tests and subtests
+ maxTestText = 256 // a test's name or skip message
)
// ErrReport is a report that breaks a bound or a form rule.
@@ -125,9 +144,15 @@ func (r Report) Check() error {
}
}
c := r.Containment
- if len(c.Args) > 16 || len(c.Detail) > maxProbeDetail || len(c.Binary) > maxText {
+ if len(c.Args) > 16 || len(c.Detail) > maxProbeDetail || len(c.Binary) > maxText || len(c.Summary) > maxText || len(c.Tests) > maxTests {
return bad("the containment result is over its bounds")
}
+ for _, t := range c.Tests {
+ if !text(t.Name) || len(t.Name) > maxTestText || len(t.Reason) > maxTestText ||
+ (t.Result != TestPassed && t.Result != TestFailed && t.Result != TestSkipped) {
+ return bad("containment test %q is not a named pass, fail or skip within bounds", t.Name)
+ }
+ }
return nil
}
diff --git a/internal/hostedcert/judge.go b/internal/hostedcert/judge.go
index 927c397d..4b81cddc 100644
--- a/internal/hostedcert/judge.go
+++ b/internal/hostedcert/judge.go
@@ -4,6 +4,7 @@ import (
"crypto/ed25519"
"errors"
"fmt"
+ "maps"
"slices"
)
@@ -52,16 +53,8 @@ func Judge(r Report, m []Expectation) error {
}
}
}
- c := r.Containment
- switch {
- case !slices.Equal(c.Args, containmentArgs):
- fail("positive control: the containment suite ran with %q, not %q", c.Args, containmentArgs)
- case c.ExitCode != 0 || c.Failed != 0:
- fail("positive control: the containment suite exited %d with %d failed", c.ExitCode, c.Failed)
- case c.Skipped != 0:
- fail("positive control: the containment suite skipped %d tests; it must run in full", c.Skipped)
- case c.Passed < 1:
- fail("positive control: the containment suite passed no test")
+ for _, err := range judgeContainment(r.Containment) {
+ fail("positive control: %v", err)
}
if len(errs) == 0 {
return nil
@@ -69,6 +62,44 @@ func Judge(r Report, m []Expectation) error {
return errors.Join(append([]error{ErrNotCertified}, errs...)...)
}
+// judgeContainment holds the containment suite to passing in full, test
+// by test: its arguments are ContainmentArgs, it exited 0, its summary is
+// PASS, its output was read whole, it reported at least one test, each
+// name once, and every test passed but an authorised skip with exactly
+// its message.
+func judgeContainment(c ContainmentResult) []error {
+ var errs []error
+ fail := func(format string, a ...any) { errs = append(errs, fmt.Errorf(format, a...)) }
+ switch {
+ case !slices.Equal(c.Args, containmentArgs):
+ fail("the containment suite ran with %q, not %q", c.Args, containmentArgs)
+ case c.ExitCode != 0:
+ fail("the containment suite exited %d", c.ExitCode)
+ case c.Summary != "PASS":
+ fail("the containment suite's summary is %q, not PASS", c.Summary)
+ case !c.Complete:
+ fail("the containment suite's output was not read whole")
+ case len(c.Tests) == 0:
+ fail("the containment suite reported no test")
+ }
+ seen := map[string]bool{}
+ for _, t := range c.Tests {
+ if seen[t.Name] {
+ fail("containment test %s is reported twice", t.Name)
+ }
+ seen[t.Name] = true
+ switch reason, authorised := authorisedSkips[t.Name]; {
+ case t.Result == TestPassed:
+ case t.Result == TestSkipped && authorised && t.Reason == reason:
+ case t.Result == TestSkipped:
+ fail("containment test %s skipped (%q); only %v may skip, each with its one message", t.Name, t.Reason, slices.Sorted(maps.Keys(authorisedSkips)))
+ default:
+ fail("containment test %s did not pass (%s)", t.Name, t.Result)
+ }
+ }
+ return errs
+}
+
// Release is what the release manifest pins that the evidence must match:
// the digests vm-init measures (hostedimage.Manifest.Measured) and the
// containment suite's SHA-256.
diff --git a/internal/hostedcert/judge_test.go b/internal/hostedcert/judge_test.go
index 9e26970b..b85afd65 100644
--- a/internal/hostedcert/judge_test.go
+++ b/internal/hostedcert/judge_test.go
@@ -32,7 +32,9 @@ var (
func passing(launch string) hostedcert.Report {
r := hostedcert.Report{LaunchID: launch, Root: []hostedcert.ProbeResult{}, User: []hostedcert.ProbeResult{},
Sandbox: []hostedcert.ProbeResult{}, Measured: map[string]string{"policy:/etc/equipo/checks.json": strings.Repeat("5", 64)},
- Containment: hostedcert.ContainmentResult{Binary: release.ContainmentTest, Args: hostedcert.ContainmentArgs(), Passed: 40}}
+ Containment: hostedcert.ContainmentResult{Binary: release.ContainmentTest, Args: hostedcert.ContainmentArgs(),
+ Tests: []hostedcert.ContainmentTest{{Name: "TestA", Result: hostedcert.TestPassed}, {Name: "TestB/sub", Result: hostedcert.TestPassed}},
+ Summary: "PASS", Complete: true}}
for k, v := range release.Measured {
r.Measured[k] = v
}
@@ -147,12 +149,10 @@ func TestJudgeNeedsPositiveControls(t *testing.T) {
wantNotCertified(t, "control "+e.Name+" blocked", hostedcert.Judge(r, hostedcert.Matrix()), e.Name)
}
for what, fn := range map[string]func(*hostedcert.ContainmentResult){
- "other arguments": func(c *hostedcert.ContainmentResult) { c.Args = []string{"-test.run", "^TestOne$"} },
- "no arguments": func(c *hostedcert.ContainmentResult) { c.Args = nil },
- "exit 1": func(c *hostedcert.ContainmentResult) { c.ExitCode = 1 },
- "a failed test": func(c *hostedcert.ContainmentResult) { c.Failed = 1 },
- "a skipped test": func(c *hostedcert.ContainmentResult) { c.Skipped = 1 },
- "no passing tests": func(c *hostedcert.ContainmentResult) { c.Passed = 0 },
+ "other arguments": func(c *hostedcert.ContainmentResult) { c.Args = []string{"-test.run", "^TestOne$"} },
+ "no arguments": func(c *hostedcert.ContainmentResult) { c.Args = nil },
+ "exit 1": func(c *hostedcert.ContainmentResult) { c.ExitCode = 1 },
+ "no tests": func(c *hostedcert.ContainmentResult) { c.Tests = nil },
} {
r := passing("l-1")
fn(&r.Containment)
@@ -160,6 +160,46 @@ func TestJudgeNeedsPositiveControls(t *testing.T) {
}
}
+// TestJudgeContainmentInFull: the containment suite passes in full, test
+// by test: every test it reported passed, but for the one authorised skip
+// with its one message; its summary says PASS; and its output was read
+// whole. Any other skip, a failure, a repeated name, a missing summary or
+// an incomplete read fails.
+func TestJudgeContainmentInFull(t *testing.T) {
+ const cgroup = "TestNamespaceCgroupMoveKeepsMembership"
+ reason := hostedcert.AuthorisedSkips()[cgroup]
+ if reason != "no systemd user session; production containment does not use cgroups" {
+ t.Fatalf("authorised skip reason = %q", reason)
+ }
+ vm := passing("l-1")
+ vm.Containment.Tests = append(vm.Containment.Tests, hostedcert.ContainmentTest{Name: cgroup, Result: hostedcert.TestSkipped, Reason: reason})
+ if err := hostedcert.Judge(vm, hostedcert.Matrix()); err != nil {
+ t.Fatalf("a VM's run with the authorised skip: Judge = %v", err)
+ }
+ for what, c := range map[string]struct {
+ fn func(*hostedcert.ContainmentResult)
+ naming string
+ }{
+ "the authorised test skipped for another reason": {func(c *hostedcert.ContainmentResult) { c.Tests[2].Reason = "no bubblewrap" }, cgroup},
+ "the authorised test skipped with no reason": {func(c *hostedcert.ContainmentResult) { c.Tests[2].Reason = "" }, cgroup},
+ "another test skipped with the authorised reason": {func(c *hostedcert.ContainmentResult) {
+ c.Tests[0] = hostedcert.ContainmentTest{Name: "TestA", Result: hostedcert.TestSkipped, Reason: reason}
+ }, "TestA"},
+ "a subtest skipped": {func(c *hostedcert.ContainmentResult) { c.Tests[1].Result = hostedcert.TestSkipped }, "TestB/sub"},
+ "a failed test": {func(c *hostedcert.ContainmentResult) { c.Tests[0].Result = hostedcert.TestFailed }, "TestA"},
+ "a name twice": {func(c *hostedcert.ContainmentResult) { c.Tests = append(c.Tests, c.Tests[0]) }, "TestA"},
+ "no summary": {func(c *hostedcert.ContainmentResult) { c.Summary = "" }, "summary"},
+ "a FAIL summary": {func(c *hostedcert.ContainmentResult) { c.Summary = "FAIL" }, "summary"},
+ "output not whole": {func(c *hostedcert.ContainmentResult) { c.Complete = false }, "not read whole"},
+ "an unknown result": {func(c *hostedcert.ContainmentResult) { c.Tests[0].Result = "bench" }, "TestA"},
+ } {
+ r := passing("l-1")
+ r.Containment.Tests = append(r.Containment.Tests, hostedcert.ContainmentTest{Name: cgroup, Result: hostedcert.TestSkipped, Reason: reason})
+ c.fn(&r.Containment)
+ wantNotCertified(t, "containment: "+what, hostedcert.Judge(r, hostedcert.Matrix()), c.naming)
+ }
+}
+
// TestEvidenceSignatureChecked: evidence opens only with its signature
// intact over the exact bytes signed, and only when those bytes are
// strict evidence.
diff --git a/internal/hostedcert/matrix.go b/internal/hostedcert/matrix.go
index 72b9669b..f63d5423 100644
--- a/internal/hostedcert/matrix.go
+++ b/internal/hostedcert/matrix.go
@@ -1,6 +1,9 @@
package hostedcert
-import "slices"
+import (
+ "maps"
+ "slices"
+)
// The probes, by stage. The root probes are vm-init's (vminit.Probe*; a
// test holds the names equal).
@@ -81,6 +84,18 @@ const SandboxSubcommand = "hosted-sandbox-probes"
// full, but for the source checks, which need the repository.
var containmentArgs = []string{"-test.v", "-test.count=1", "-test.skip", "^TestSource"}
+// authorisedSkips are the only containment tests that may skip, each with
+// the one message it must skip with. TestNamespaceCgroupMoveKeepsMembership
+// needs a systemd user session, which a hosted VM has none of (spec §7);
+// production containment does not use cgroups.
+var authorisedSkips = map[string]string{
+ "TestNamespaceCgroupMoveKeepsMembership": "no systemd user session; production containment does not use cgroups",
+}
+
+// AuthorisedSkips returns the containment tests that may skip, each with
+// the message it must skip with.
+func AuthorisedSkips() map[string]string { return maps.Clone(authorisedSkips) }
+
// ContainmentArgs returns the containment suite's arguments. Its passing
// run, every test passing and none skipped, is the third positive
// control.
diff --git a/internal/hostedcert/probe_linux.go b/internal/hostedcert/probe_linux.go
index efdb4bac..d265e810 100644
--- a/internal/hostedcert/probe_linux.go
+++ b/internal/hostedcert/probe_linux.go
@@ -19,6 +19,8 @@ import (
"os"
"os/exec"
"path/filepath"
+ "slices"
+ "strconv"
"strings"
"syscall"
"time"
@@ -69,18 +71,72 @@ func result(stage, name, outcome, detail string) ProbeResult {
return ProbeResult{Name: name, Stage: stage, Outcome: outcome, OK: outcome == OutcomeBlocked, Detail: detail}
}
-// denied reports whether err shows the attempt was refused or never
-// answered: a permission refusal, a timeout, a refused connection, no
-// route or no network. A cancellation shows nothing.
+// localErrnos are local failures: out of descriptors, memory, buffers,
+// local ports or disk, or a read-only file system. They show nothing
+// about the network, so a probe that meets one is inconclusive.
+var localErrnos = []syscall.Errno{syscall.EMFILE, syscall.ENFILE, syscall.ENOMEM, syscall.ENOBUFS, syscall.EADDRNOTAVAIL,
+ syscall.ENOSPC, syscall.EROFS}
+
+// networkErrnos show the network refusing the attempt or having no route
+// for it.
+var networkErrnos = []syscall.Errno{syscall.ECONNREFUSED, syscall.EHOSTUNREACH, syscall.ENETUNREACH, syscall.EAFNOSUPPORT}
+
+// denied reports whether err shows the network refused the attempt or
+// never answered it: a timeout, a refused connection, no route or no
+// network, or a connect(2) a firewall forbade (EPERM, EACCES). A local
+// failure (localErrnos), a permission refusal by any other call (a socket
+// the sandbox would not make, a file it could not write) and a
+// cancellation show nothing.
func denied(err error) bool {
if err == nil || errors.Is(err, context.Canceled) {
return false
}
+ for _, e := range localErrnos {
+ if errors.Is(err, e) {
+ return false
+ }
+ }
var ne net.Error
- return errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) ||
- (errors.As(err, &ne) && ne.Timeout()) || errors.Is(err, fs.ErrPermission) ||
- errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EHOSTUNREACH) ||
- errors.Is(err, syscall.ENETUNREACH) || errors.Is(err, syscall.EADDRNOTAVAIL) || errors.Is(err, syscall.EAFNOSUPPORT)
+ if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &ne) && ne.Timeout()) {
+ return true
+ }
+ for _, e := range networkErrnos {
+ if errors.Is(err, e) {
+ return true
+ }
+ }
+ var se *os.SyscallError
+ return errors.As(err, &se) && se.Syscall == "connect" && (errors.Is(err, syscall.EPERM) || errors.Is(err, syscall.EACCES))
+}
+
+// textOutcome classifies an error a tool reported only as text (the Go
+// command's module fetch, the resolver's message), by the errno texts
+// denied uses: a local failure, or a permission refusal anywhere but a
+// connect, is inconclusive; a network refusal, a timeout or a name with
+// no answer is blocked; anything else is inconclusive.
+func textOutcome(s string) string {
+ for _, e := range localErrnos {
+ if strings.Contains(s, e.Error()) {
+ return OutcomeInconclusive
+ }
+ }
+ for _, e := range []syscall.Errno{syscall.EPERM, syscall.EACCES} {
+ if strings.Contains(s, "connect: "+e.Error()) {
+ return OutcomeBlocked
+ }
+ if strings.Contains(s, e.Error()) {
+ return OutcomeInconclusive
+ }
+ }
+ for _, e := range networkErrnos {
+ if strings.Contains(s, e.Error()) {
+ return OutcomeBlocked
+ }
+ }
+ if strings.Contains(s, "i/o timeout") || strings.Contains(s, "no such host") {
+ return OutcomeBlocked
+ }
+ return OutcomeInconclusive
}
// ---- the user stage ----
@@ -270,34 +326,75 @@ func runCommand(ctx context.Context, dir string, env []string, argv ...string) (
return -1, out, err
}
-// The marks the build-script probe's program prints.
-const (
- markReached = "equipo-probe: reached"
- markBlocked = "equipo-probe: blocked"
-)
+// probeMark starts the one line the build-script program prints: "dial
+// ok", or "dial failed syscall=S errno=N timeout=B", the failure's own
+// system call, errno and timeout flag, which the probe classifies with
+// denied.
+const probeMark = "equipo-probe: "
// buildScript is the build-script probe's program: a dial, as a build
// step that fetches something would make.
const buildScript = `package main
import (
+ "errors"
"fmt"
"net"
"os"
+ "syscall"
"time"
)
func main() {
c, err := net.DialTimeout("tcp", os.Args[1], 5*time.Second)
- if err != nil {
- fmt.Println("` + markBlocked + `:", err)
+ if err == nil {
+ c.Close()
+ fmt.Println("` + probeMark + `dial ok")
return
}
- c.Close()
- fmt.Println("` + markReached + `")
+ call, errno := "", 0
+ var se *os.SyscallError
+ if errors.As(err, &se) {
+ call = se.Syscall
+ }
+ var en syscall.Errno
+ if errors.As(err, &en) {
+ errno = int(en)
+ }
+ var ne net.Error
+ fmt.Printf("` + probeMark + `dial failed syscall=%s errno=%d timeout=%t\n", call, errno, errors.As(err, &ne) && ne.Timeout())
}
`
+// dialLine classifies the build-script program's one result line.
+func dialLine(line string) (string, bool) {
+ if line == probeMark+"dial ok" {
+ return OutcomeReached, true
+ }
+ var call string
+ var errno int
+ var timeout bool
+ rest, ok := strings.CutPrefix(line, probeMark+"dial failed ")
+ f := strings.Fields(rest)
+ if !ok || len(f) != 3 || !strings.HasPrefix(f[0], "syscall=") {
+ return "", false
+ }
+ call = strings.TrimPrefix(f[0], "syscall=")
+ n, err1 := strconv.Atoi(strings.TrimPrefix(f[1], "errno="))
+ t, err2 := strconv.ParseBool(strings.TrimPrefix(f[2], "timeout="))
+ if err1 != nil || err2 != nil || !strings.HasPrefix(f[1], "errno=") || !strings.HasPrefix(f[2], "timeout=") || n < 0 {
+ return "", false
+ }
+ errno, timeout = n, t
+ switch {
+ case timeout:
+ return OutcomeBlocked, true
+ case errno != 0 && denied(&os.SyscallError{Syscall: call, Err: syscall.Errno(errno)}):
+ return OutcomeBlocked, true
+ }
+ return OutcomeInconclusive, true
+}
+
// RunSandboxProbes runs the sandbox probes in a fixed order. Each probe
// with no target to aim at is inconclusive: nothing was shown.
func RunSandboxProbes(ctx context.Context, t SandboxTargets, s SandboxSeams) []ProbeResult {
@@ -339,15 +436,7 @@ func RunSandboxProbes(ctx context.Context, t SandboxTargets, s SandboxSeams) []P
lctx, cancel := context.WithTimeout(ctx, probeTimeout)
addrs, err := s.Lookup(lctx, "example.com")
cancel()
- var dnsErr *net.DNSError
- switch {
- case err == nil && len(addrs) > 0:
- r(ProbeSandboxDNS, OutcomeReached, fmt.Sprintf("example.com resolved to %d addresses", len(addrs)))
- case errors.As(err, &dnsErr) || denied(err):
- r(ProbeSandboxDNS, OutcomeBlocked, fmt.Sprint(err))
- default:
- r(ProbeSandboxDNS, OutcomeInconclusive, fmt.Sprintf("%v (%d addresses)", err, len(addrs)))
- }
+ r(ProbeSandboxDNS, lookupOutcome(addrs, err), fmt.Sprintf("%v (%d addresses)", err, len(addrs)))
env := goEnv(t)
o, detail := buildScriptProbe(ctx, t, s, env)
@@ -366,6 +455,30 @@ func RunSandboxProbes(ctx context.Context, t SandboxTargets, s SandboxSeams) []P
return out
}
+// lookupOutcome classifies a name lookup: addresses reached; a name with
+// no answer, a timeout or a refusal blocked; a local failure, or anything
+// the resolver says it cannot tell, inconclusive.
+func lookupOutcome(addrs []string, err error) string {
+ var dnsErr *net.DNSError
+ switch {
+ case err == nil && len(addrs) > 0:
+ return OutcomeReached
+ case errors.As(err, &dnsErr):
+ for _, e := range localErrnos {
+ if strings.Contains(dnsErr.Err, e.Error()) {
+ return OutcomeInconclusive
+ }
+ }
+ if dnsErr.IsNotFound || dnsErr.IsTimeout || denied(err) {
+ return OutcomeBlocked
+ }
+ return textOutcome(dnsErr.Err)
+ case denied(err):
+ return OutcomeBlocked
+ }
+ return OutcomeInconclusive
+}
+
// worse is the probe's outcome over several attempts: reached if any got
// through, else inconclusive if any could not tell, else blocked.
func worse(a, b string) string {
@@ -455,31 +568,41 @@ func buildScriptProbe(ctx context.Context, t SandboxTargets, s SandboxSeams, env
defer cancel()
exit, out, err := s.Run(ctx, dir, env, filepath.Join(t.GoRoot, "bin/go"), "run", "main.go", t.PublicIPv4.String())
text := lastLines(out)
- switch {
- case err != nil:
+ if err != nil {
return OutcomeInconclusive, "go run did not start: " + err.Error()
- case bytes.Contains(out, []byte(markReached)):
- return OutcomeReached, text
- case bytes.Contains(out, []byte(markBlocked)):
- return OutcomeBlocked, text
}
- return OutcomeInconclusive, fmt.Sprintf("go run exited %d without a result: %s", exit, text)
+ var lines []string
+ for _, l := range strings.Split(string(out), "\n") {
+ if strings.HasPrefix(l, probeMark) {
+ lines = append(lines, l)
+ }
+ }
+ if len(lines) != 1 {
+ return OutcomeInconclusive, fmt.Sprintf("go run exited %d with %d results: %s", exit, len(lines), text)
+ }
+ o, ok := dialLine(lines[0])
+ if !ok {
+ return OutcomeInconclusive, "a malformed result: " + text
+ }
+ return o, text
}
-// networkFailures are what go mod download prints when its fetch cannot
-// reach the network.
-var networkFailures = []string{"dial tcp", "lookup ", "no such host", "network is unreachable", "connection refused",
- "i/o timeout", "server misbehaving", "permission denied"}
-
func modDownloadProbe(ctx context.Context, t SandboxTargets, s SandboxSeams, env []string) (string, string) {
dir := filepath.Join(t.Work, "modprobe")
if err := s.WriteFile(filepath.Join(dir, "go.mod"), []byte("module equipo.invalid/probe\n\ngo 1.26\n")); err != nil {
return OutcomeInconclusive, "writing go.mod: " + err.Error()
}
+ // The caches the download fills must be writable, or its failure
+ // shows nothing about the network.
+ for _, c := range []string{"modcache", "gocache"} {
+ if err := s.WriteFile(filepath.Join(t.Work, c, ".equipo-probe"), nil); err != nil {
+ return OutcomeInconclusive, "the " + c + " is not writable: " + err.Error()
+ }
+ }
env = append(env, "GOPROXY=https://proxy.golang.org", "GOSUMDB=off")
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
- exit, out, err := s.Run(ctx, dir, env, filepath.Join(t.GoRoot, "bin/go"), "mod", "download", "golang.org/x/text@v0.3.0")
+ exit, out, err := s.Run(ctx, dir, env, filepath.Join(t.GoRoot, "bin/go"), "mod", "download", "-json", "golang.org/x/text@v0.3.0")
text := lastLines(out)
switch {
case err != nil:
@@ -487,12 +610,17 @@ func modDownloadProbe(ctx context.Context, t SandboxTargets, s SandboxSeams, env
case exit == 0:
return OutcomeReached, "go mod download fetched a module"
}
- for _, f := range networkFailures {
- if strings.Contains(string(out), f) {
- return OutcomeBlocked, fmt.Sprintf("exited %d: %s", exit, text)
- }
+ // The module's own Error, from the one JSON object -json prints.
+ var m struct{ Error string }
+ i := strings.Index(string(out), "\n{")
+ body := string(out)
+ if !strings.HasPrefix(body, "{") && i >= 0 {
+ body = body[i+1:]
+ }
+ if !strings.HasPrefix(body, "{") || json.Unmarshal([]byte(body), &m) != nil || m.Error == "" {
+ return OutcomeInconclusive, fmt.Sprintf("exited %d with no module error: %s", exit, text)
}
- return OutcomeInconclusive, fmt.Sprintf("exited %d for another reason: %s", exit, text)
+ return textOutcome(m.Error), fmt.Sprintf("exited %d: %s", exit, m.Error)
}
// lastLines is at most the last 1 KiB of out, as one line.
@@ -561,9 +689,20 @@ func sandboxFailed(err error) []ProbeResult {
// ---- the containment suite ----
+// ErrTruncated is what a containment run function returns, with the exit
+// code and the output it kept, when the output went past its capture
+// limit: the result is then incomplete.
+var ErrTruncated = errors.New("hostedcert: the output went past its capture limit")
+
+// maxSuiteLine is the longest line of the suite's output read; a longer
+// one leaves the result incomplete.
+const maxSuiteLine = 64 << 10
+
// RunContainment runs the containment suite at path with ContainmentArgs
-// through run (argv, then exit code and combined output; err only when it
-// could not run) and counts its verbose output's results.
+// through run (argv, then the exit code and combined output; ErrTruncated
+// with what it kept when the output went past its capture limit; any
+// other error when it could not run) and reads its verbose output test by
+// test (readSuite).
func RunContainment(ctx context.Context, path string, run func(ctx context.Context, argv []string) (int, []byte, error)) ContainmentResult {
c := ContainmentResult{Args: ContainmentArgs(), ExitCode: -1}
sum, err := fileSHA256(path)
@@ -573,29 +712,21 @@ func RunContainment(ctx context.Context, path string, run func(ctx context.Conte
}
c.Binary = sum
exit, out, err := run(ctx, append([]string{path}, c.Args...))
- if err != nil {
+ truncated := errors.Is(err, ErrTruncated)
+ if err != nil && !truncated {
c.Detail = "the suite did not run: " + err.Error()
return c
}
c.ExitCode = exit
- sc := bufio.NewScanner(bytes.NewReader(out))
- sc.Buffer(make([]byte, 64<<10), 1<<20)
- var failed []string
- for sc.Scan() {
- line := strings.TrimSpace(sc.Text())
- switch {
- case strings.HasPrefix(line, "--- PASS:"):
- c.Passed++
- case strings.HasPrefix(line, "--- FAIL:"):
- c.Failed++
- failed = append(failed, strings.Fields(line)[2])
- case strings.HasPrefix(line, "--- SKIP:"):
- c.Skipped++
- }
+ var problems []string
+ c.Tests, c.Summary, problems = readSuite(out)
+ if truncated {
+ problems = append(problems, "the output went past its capture limit")
}
- c.Detail = fmt.Sprintf("exit %d; %d passed, %d failed, %d skipped", exit, c.Passed, c.Failed, c.Skipped)
- if len(failed) > 0 {
- c.Detail += "; failed: " + strings.Join(failed, " ")
+ c.Complete = len(problems) == 0
+ c.Detail = fmt.Sprintf("exit %d; %d tests; summary %q", exit, len(c.Tests), c.Summary)
+ if len(problems) > 0 {
+ c.Detail += "; incomplete: " + strings.Join(problems, "; ")
}
if len(c.Detail) > maxProbeDetail {
c.Detail = c.Detail[:maxProbeDetail]
@@ -603,6 +734,83 @@ func RunContainment(ctx context.Context, path string, run func(ctx context.Conte
return c
}
+// readSuite reads a test binary's -test.v output: each "--- PASS/FAIL/
+// 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:
+// 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 := "", ""
+ 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
+ }
+ if name, ok := marker(line); ok {
+ current = name
+ if strings.HasPrefix(line, "=== RUN ") {
+ started[name] = true
+ }
+ continue
+ }
+ matched := false
+ for prefix, result := range results {
+ rest, ok := strings.CutPrefix(line, prefix)
+ if !ok {
+ continue
+ }
+ matched = true
+ name, _, _ := strings.Cut(rest, " ")
+ t := ContainmentTest{Name: name, Result: result}
+ if result == TestSkipped {
+ t.Reason = logged[name]
+ }
+ tests = append(tests, t)
+ delete(started, name)
+ }
+ if !matched && current != "" && raw != line && strings.HasPrefix(raw, " ") {
+ if msg, ok := logMessage(line); ok {
+ logged[current] = msg
+ }
+ }
+ }
+ if err := sc.Err(); err != nil {
+ problems = append(problems, "reading the output: "+err.Error())
+ }
+ for name := range started {
+ problems = append(problems, "test "+name+" started with no result")
+ }
+ slices.Sort(problems)
+ return tests, last, problems
+}
+
+// marker reads a "=== RUN/CONT/NAME/PAUSE name" line.
+func marker(line string) (string, bool) {
+ for _, p := range []string{"=== RUN ", "=== CONT ", "=== NAME ", "=== PAUSE "} {
+ if rest, ok := strings.CutPrefix(line, p); ok {
+ return strings.TrimSpace(rest), true
+ }
+ }
+ return "", false
+}
+
+// logMessage reads "file.go:N: message".
+func logMessage(line string) (string, bool) {
+ loc, msg, ok := strings.Cut(line, ": ")
+ file, n, ok2 := strings.Cut(loc, ".go:")
+ if !ok || !ok2 || file == "" || n == "" || strings.Trim(n, "0123456789") != "" {
+ return "", false
+ }
+ return msg, true
+}
+
func fileSHA256(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
diff --git a/internal/hostedcert/probe_linux_test.go b/internal/hostedcert/probe_linux_test.go
index 0f4db0e9..30beff30 100644
--- a/internal/hostedcert/probe_linux_test.go
+++ b/internal/hostedcert/probe_linux_test.go
@@ -175,8 +175,8 @@ var offline = map[string]struct {
exit int
out string
}{
- "run": {1, "equipo-probe: blocked: dial tcp 1.1.1.1:443: connect: network is unreachable\nexit status 0"},
- "mod": {1, "go: golang.org/x/text@v0.3.0: Get \"https://proxy.golang.org/...\": dial tcp: lookup proxy.golang.org: no such host"},
+ "run": {0, "equipo-probe: dial failed syscall=connect errno=101 timeout=false\n"},
+ "mod": {1, `{"Path":"golang.org/x/text","Version":"v0.3.0","Error":"golang.org/x/text@v0.3.0: Get \"https://proxy.golang.org/golang.org/x/text/@v/v0.3.0.info\": dial tcp: lookup proxy.golang.org on 127.0.0.1:53: read udp 127.0.0.1:41000->127.0.0.1:53: read: connection refused"}`},
}
// TestSandboxProbes: with no network every negative probe is blocked and
@@ -213,7 +213,7 @@ func TestSandboxProbes(t *testing.T) {
online := map[string]struct {
exit int
out string
- }{"run": {0, "equipo-probe: reached"}, "mod": {0, ""}}
+ }{"run": {0, "equipo-probe: dial ok\n"}, "mod": {0, `{"Path":"golang.org/x/text","Version":"v0.3.0","Dir":"/tmp/x"}`}}
got = outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), seams(&sandboxNet{}, online)))
if got[hostedcert.ProbeSandboxBuildScript] != hostedcert.OutcomeReached || got[hostedcert.ProbeSandboxGoModDownload] != hostedcert.OutcomeReached {
t.Errorf("a networked toolchain: %v", got)
@@ -239,6 +239,131 @@ func TestSandboxProbes(t *testing.T) {
}
}
+func dialErr(call string, errno syscall.Errno) error {
+ return &net.OpError{Op: "dial", Net: "tcp", Err: os.NewSyscallError(call, errno)}
+}
+
+type timeoutErr struct{}
+
+func (timeoutErr) Error() string { return "i/o timeout" }
+func (timeoutErr) Timeout() bool { return true }
+func (timeoutErr) Temporary() bool { return true }
+
+// TestSandboxProbeFailuresClassified: only a failure that shows the
+// network refusing (no route, refused, unreachable, timed out, or a
+// connect a firewall forbade) counts as blocked. A local failure (out of
+// descriptors, memory or buffers, a socket the sandbox would not make, a
+// cache it could not write, a cancelled probe) shows nothing and is
+// inconclusive, from the direct dials, the build script, go mod download
+// and the name lookup alike.
+func TestSandboxProbeFailuresClassified(t *testing.T) {
+ dials := map[string]struct {
+ err error
+ want string
+ }{
+ "no route": {dialErr("connect", syscall.ENETUNREACH), hostedcert.OutcomeBlocked},
+ "refused": {dialErr("connect", syscall.ECONNREFUSED), hostedcert.OutcomeBlocked},
+ "host unreachable": {dialErr("connect", syscall.EHOSTUNREACH), hostedcert.OutcomeBlocked},
+ "firewall on connect": {dialErr("connect", syscall.EPERM), hostedcert.OutcomeBlocked},
+ "timed out": {&net.OpError{Op: "dial", Net: "tcp", Err: timeoutErr{}}, hostedcert.OutcomeBlocked},
+ "out of descriptors": {dialErr("socket", syscall.EMFILE), hostedcert.OutcomeInconclusive},
+ "system out of files": {dialErr("socket", syscall.ENFILE), hostedcert.OutcomeInconclusive},
+ "out of buffers": {dialErr("connect", syscall.ENOBUFS), hostedcert.OutcomeInconclusive},
+ "out of memory": {dialErr("socket", syscall.ENOMEM), hostedcert.OutcomeInconclusive},
+ "no local port": {dialErr("connect", syscall.EADDRNOTAVAIL), hostedcert.OutcomeInconclusive},
+ "socket not permitted": {dialErr("socket", syscall.EACCES), hostedcert.OutcomeInconclusive},
+ "cancelled": {context.Canceled, hostedcert.OutcomeInconclusive},
+ "one attempt local": {errors.Join(dialErr("connect", syscall.ENETUNREACH), dialErr("socket", syscall.EMFILE)), hostedcert.OutcomeInconclusive},
+ }
+ for what, c := range dials {
+ s := seams(&sandboxNet{}, offline)
+ s.Dial = func(context.Context, string, string) (net.Conn, error) { return nil, c.err }
+ if got := outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), s))[hostedcert.ProbeSandboxIPv4]; got != c.want {
+ t.Errorf("dial %s: %s = %q, want %q", what, hostedcert.ProbeSandboxIPv4, got, c.want)
+ }
+ }
+
+ for what, c := range map[string]struct {
+ out string
+ want string
+ }{
+ "no route": {"equipo-probe: dial failed syscall=connect errno=101 timeout=false\n", hostedcert.OutcomeBlocked},
+ "timed out": {"equipo-probe: dial failed syscall= errno=0 timeout=true\n", hostedcert.OutcomeBlocked},
+ "reached": {"equipo-probe: dial ok\n", hostedcert.OutcomeReached},
+ "out of descriptors": {"equipo-probe: dial failed syscall=socket errno=24 timeout=false\n", hostedcert.OutcomeInconclusive},
+ "socket refused": {"equipo-probe: dial failed syscall=socket errno=13 timeout=false\n", hostedcert.OutcomeInconclusive},
+ "two results": {"equipo-probe: dial ok\nequipo-probe: dial failed syscall=connect errno=101 timeout=false\n", hostedcert.OutcomeInconclusive},
+ "a malformed result": {"equipo-probe: dial failed syscall=connect errno=x timeout=false\n", hostedcert.OutcomeInconclusive},
+ "the old text": {"equipo-probe: blocked: dial tcp: too many open files\n", hostedcert.OutcomeInconclusive},
+ "build failed": {"go: creating work dir: mkdir /tmp/x: permission denied\n", hostedcert.OutcomeInconclusive},
+ } {
+ run := map[string]struct {
+ exit int
+ out string
+ }{"run": {0, c.out}, "mod": offline["mod"]}
+ if got := outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), seams(&sandboxNet{}, run)))[hostedcert.ProbeSandboxBuildScript]; got != c.want {
+ t.Errorf("build script %s: %q, want %q", what, got, c.want)
+ }
+ }
+
+ modErr := func(e string) string {
+ raw, _ := json.Marshal(map[string]string{"Path": "golang.org/x/text", "Version": "v0.3.0", "Error": e})
+ return string(raw)
+ }
+ for what, c := range map[string]struct {
+ exit int
+ out string
+ want string
+ }{
+ "no route": {1, modErr(`Get "https://proxy.golang.org/x": dial tcp 142.250.0.1:443: connect: network is unreachable`), hostedcert.OutcomeBlocked},
+ "no DNS": {1, modErr(`Get "https://proxy.golang.org/x": dial tcp: lookup proxy.golang.org on 127.0.0.1:53: read udp 127.0.0.1:1->127.0.0.1:53: read: connection refused`), hostedcert.OutcomeBlocked},
+ "cache not writable": {1, modErr(`mkdir /tmp/equipo-probes/modcache/cache: permission denied`), hostedcert.OutcomeInconclusive},
+ "read-only cache": {1, modErr(`open /tmp/equipo-probes/modcache/x.lock: read-only file system`), hostedcert.OutcomeInconclusive},
+ "out of descriptors": {1, modErr(`Get "https://proxy.golang.org/x": dial tcp: lookup proxy.golang.org: socket: too many open files`), hostedcert.OutcomeInconclusive},
+ "out of disk": {1, modErr(`write /tmp/equipo-probes/modcache/x.zip: no space left on device`), hostedcert.OutcomeInconclusive},
+ "one attempt local": {1, modErr(`dial tcp 142.250.0.1:443: connect: network is unreachable; dial tcp [2001:db8::1]:443: socket: too many open files`), hostedcert.OutcomeInconclusive},
+ "not JSON": {1, "go: golang.org/x/text@v0.3.0: dial tcp: connect: network is unreachable", hostedcert.OutcomeInconclusive},
+ "fetched": {0, `{"Path":"golang.org/x/text","Version":"v0.3.0","Dir":"/tmp/x"}`, hostedcert.OutcomeReached},
+ } {
+ run := map[string]struct {
+ exit int
+ out string
+ }{"run": offline["run"], "mod": {c.exit, c.out}}
+ if got := outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), seams(&sandboxNet{}, run)))[hostedcert.ProbeSandboxGoModDownload]; got != c.want {
+ t.Errorf("go mod download %s: %q, want %q", what, got, c.want)
+ }
+ }
+ // The module cache the download would fill cannot be made: nothing
+ // shown.
+ s := seams(&sandboxNet{}, offline)
+ s.WriteFile = func(p string, b []byte) error {
+ if strings.Contains(p, "modcache") {
+ return &os.PathError{Op: "open", Path: p, Err: syscall.EACCES}
+ }
+ return nil
+ }
+ if got := outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), s))[hostedcert.ProbeSandboxGoModDownload]; got != hostedcert.OutcomeInconclusive {
+ t.Errorf("an unwritable module cache: %q, want inconclusive", got)
+ }
+
+ for what, c := range map[string]struct {
+ err error
+ want string
+ }{
+ "not found": {&net.DNSError{Err: "no such host", Name: "example.com", IsNotFound: true}, hostedcert.OutcomeBlocked},
+ "timed out": {&net.DNSError{Err: "i/o timeout", Name: "example.com", IsTimeout: true}, hostedcert.OutcomeBlocked},
+ "refused": {&net.DNSError{Err: "read udp 127.0.0.1:1->127.0.0.1:53: read: connection refused", Name: "example.com", IsTemporary: true}, hostedcert.OutcomeBlocked},
+ "out of descriptors": {&net.DNSError{Err: "socket: too many open files", Name: "example.com", IsTemporary: true}, hostedcert.OutcomeInconclusive},
+ "something else": {&net.DNSError{Err: "server misbehaving", Name: "example.com", IsTemporary: true}, hostedcert.OutcomeInconclusive},
+ } {
+ s := seams(&sandboxNet{}, offline)
+ s.Lookup = func(context.Context, string) ([]string, error) { return nil, c.err }
+ if got := outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), s))[hostedcert.ProbeSandboxDNS]; got != c.want {
+ t.Errorf("lookup %s: %q, want %q", what, got, c.want)
+ }
+ }
+}
+
// TestRunInSandbox: the probes run as the runner's sandbox subcommand with
// the targets; a sandbox that fails, or answers anything but sandbox
// results, leaves every sandbox probe inconclusive.
@@ -272,16 +397,52 @@ func TestRunInSandbox(t *testing.T) {
}
}
-// TestRunContainment: the suite runs with ContainmentArgs, its binary is
-// measured, and its verbose output is counted.
-func TestRunContainment(t *testing.T) {
+// vmContainmentOutput is the containment suite's verbose output as a
+// hosted VM gives it: subtests, parallel tests whose logs interleave, and
+// the one authorised skip, logged before its result line.
+const vmContainmentOutput = `=== RUN TestCgroupSessionRule
+=== RUN TestCgroupSessionRule/session
+=== RUN TestCgroupSessionRule/no_session
+--- PASS: TestCgroupSessionRule (0.00s)
+ --- PASS: TestCgroupSessionRule/session (0.00s)
+ --- PASS: TestCgroupSessionRule/no_session (0.00s)
+=== RUN TestNamespaceCgroupMoveKeepsMembership
+ linux_test.go:279: no systemd user session; production containment does not use cgroups
+--- SKIP: TestNamespaceCgroupMoveKeepsMembership (0.00s)
+=== RUN TestEgressDenied
+=== PAUSE TestEgressDenied
+=== RUN TestMountsReadOnly
+=== PAUSE TestMountsReadOnly
+=== CONT TestEgressDenied
+=== CONT TestMountsReadOnly
+ mounts_test.go:88: checked 14 mounts
+=== NAME TestEgressDenied
+ egress_test.go:51: no systemd user session; production containment does not use cgroups
+--- PASS: TestMountsReadOnly (0.12s)
+--- PASS: TestEgressDenied (0.20s)
+PASS
+`
+
+func suite(t *testing.T) string {
+ t.Helper()
path := filepath.Join(t.TempDir(), "containment.test")
if err := os.WriteFile(path, []byte("suite"), 0o755); err != nil {
t.Fatal(err)
}
+ return path
+}
+
+func runs(exit int, out string, err error) func(context.Context, []string) (int, []byte, error) {
+ return func(context.Context, []string) (int, []byte, error) { return exit, []byte(out), err }
+}
+
+// TestRunContainment: the suite runs with ContainmentArgs, its binary is
+// measured, and every test keeps its own name and result.
+func TestRunContainment(t *testing.T) {
+ path := suite(t)
sum := sha256.Sum256([]byte("suite"))
var argv []string
- out := "=== RUN TestA\n--- PASS: TestA (0.01s)\n=== RUN TestB\n --- PASS: TestB/one (0.00s)\n--- FAIL: TestB (0.00s)\n--- SKIP: TestC (0.00s)\nFAIL\n"
+ out := "=== RUN TestA\n--- PASS: TestA (0.01s)\n=== RUN TestB\n=== RUN TestB/one\n --- PASS: TestB/one (0.00s)\n--- FAIL: TestB (0.00s)\nFAIL\n"
c := hostedcert.RunContainment(context.Background(), path, func(_ context.Context, a []string) (int, []byte, error) {
argv = a
return 1, []byte(out), nil
@@ -290,17 +451,78 @@ func TestRunContainment(t *testing.T) {
!slices.Equal(argv, append([]string{path}, hostedcert.ContainmentArgs()...)) {
t.Errorf("binary %s args %q argv %q", c.Binary, c.Args, argv)
}
- if c.ExitCode != 1 || c.Passed != 2 || c.Failed != 1 || c.Skipped != 1 || !strings.Contains(c.Detail, "TestB") {
+ want := []hostedcert.ContainmentTest{{Name: "TestA", Result: hostedcert.TestPassed}, {Name: "TestB/one", Result: hostedcert.TestPassed},
+ {Name: "TestB", Result: hostedcert.TestFailed}}
+ if c.ExitCode != 1 || !slices.Equal(c.Tests, want) || c.Summary != "FAIL" || !c.Complete {
t.Errorf("result = %+v", c)
}
- c = hostedcert.RunContainment(context.Background(), path, func(context.Context, []string) (int, []byte, error) {
- return -1, nil, errors.New("exec format error")
- })
- if c.ExitCode != -1 || c.Passed != 0 {
+ c = hostedcert.RunContainment(context.Background(), path, runs(-1, "", errors.New("exec format error")))
+ if c.ExitCode != -1 || len(c.Tests) != 0 || c.Complete {
t.Errorf("a suite that did not run: %+v", c)
}
}
+// TestRunContainmentRepresentativeVM: a hosted VM's real output, with the
+// authorised skip, reads test by test and certifies.
+func TestRunContainmentRepresentativeVM(t *testing.T) {
+ c := hostedcert.RunContainment(context.Background(), suite(t), runs(0, vmContainmentOutput, nil))
+ reason := "no systemd user session; production containment does not use cgroups"
+ want := []hostedcert.ContainmentTest{
+ {Name: "TestCgroupSessionRule/session", Result: hostedcert.TestPassed}, {Name: "TestCgroupSessionRule/no_session", Result: hostedcert.TestPassed},
+ {Name: "TestCgroupSessionRule", Result: hostedcert.TestPassed},
+ {Name: "TestNamespaceCgroupMoveKeepsMembership", Result: hostedcert.TestSkipped, Reason: reason},
+ {Name: "TestMountsReadOnly", Result: hostedcert.TestPassed}, {Name: "TestEgressDenied", Result: hostedcert.TestPassed},
+ }
+ sortTests := func(ts []hostedcert.ContainmentTest) []hostedcert.ContainmentTest {
+ ts = slices.Clone(ts)
+ slices.SortFunc(ts, func(a, b hostedcert.ContainmentTest) int { return strings.Compare(a.Name, b.Name) })
+ return ts
+ }
+ if !slices.Equal(sortTests(c.Tests), sortTests(want)) || c.Summary != "PASS" || !c.Complete || c.ExitCode != 0 {
+ t.Fatalf("result = %+v", c)
+ }
+ r := passing("l-1")
+ c.Binary = release.ContainmentTest
+ r.Containment = c
+ if err := hostedcert.Judge(r, hostedcert.Matrix()); err != nil {
+ t.Errorf("a contained VM's suite: Judge = %v", err)
+ }
+ // The same message logged by a test that then passes is not a skip.
+ for _, ts := range c.Tests {
+ if ts.Name == "TestEgressDenied" && ts.Reason != "" {
+ t.Errorf("TestEgressDenied passed but carries reason %q", ts.Reason)
+ }
+ }
+}
+
+// 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
+// it, even where every result kept passed.
+func TestRunContainmentIncomplete(t *testing.T) {
+ cut := "=== RUN TestA\n--- PASS: TestA (0.00s)\n=== RUN TestB\n"
+ long := "=== RUN TestA\n a_test.go:1: " + strings.Repeat("x", 70<<10) + "\n--- PASS: TestA (0.00s)\nPASS\n"
+ // An over-long line after the summary: only the scanner's error shows
+ // the output was not read whole.
+ longAtEnd := "=== RUN TestA\n--- PASS: TestA (0.00s)\nPASS\n" + strings.Repeat("x", 70<<10) + "\n"
+ for what, run := range map[string]func(context.Context, []string) (int, []byte, error){
+ "past the capture limit": runs(0, "=== RUN TestA\n--- PASS: TestA (0.00s)\nPASS\n", hostedcert.ErrTruncated),
+ "cut mid-test": runs(0, cut, hostedcert.ErrTruncated),
+ "an over-long line": runs(0, long, nil),
+ "an over-long last line": runs(0, longAtEnd, nil),
+ "a test with no result": runs(0, cut+"PASS\n", nil),
+ "no summary": runs(0, "=== RUN TestA\n--- PASS: TestA (0.00s)\n", nil),
+ } {
+ c := hostedcert.RunContainment(context.Background(), suite(t), run)
+ r := passing("l-1")
+ c.Binary = release.ContainmentTest
+ r.Containment = c
+ if err := hostedcert.Judge(r, hostedcert.Matrix()); err == nil {
+ t.Errorf("%s: %+v certified", what, c)
+ }
+ }
+}
+
// TestCollect: a VM whose vm-init results, user probes, sandbox and
// containment suite are all as they should be makes a report that
// passes the matrix; vm-init's results are read strictly.
@@ -332,7 +554,8 @@ func TestCollect(t *testing.T) {
return hostedcert.RunSandboxProbes(ctx, tg, seams(&sandboxNet{}, offline))
},
Containment: func(context.Context) hostedcert.ContainmentResult {
- return hostedcert.ContainmentResult{Binary: release.ContainmentTest, Args: hostedcert.ContainmentArgs(), Passed: 12}
+ return hostedcert.ContainmentResult{Binary: release.ContainmentTest, Args: hostedcert.ContainmentArgs(),
+ Tests: []hostedcert.ContainmentTest{{Name: "TestA", Result: hostedcert.TestPassed}}, Summary: "PASS", Complete: true}
}}
r, err := c.Collect(context.Background())
if err != nil {
diff --git a/internal/hostedctl/ctlcert/report.go b/internal/hostedctl/ctlcert/report.go
index 6e3d64ea..a32ed9c2 100644
--- a/internal/hostedctl/ctlcert/report.go
+++ b/internal/hostedctl/ctlcert/report.go
@@ -127,14 +127,21 @@ type jobRow struct {
// not read is ErrReportRequest. An accepted report is kept as Evidence
// whose every field but the report comes from the launch record and cfg,
// signed with cfg.Key.
+//
+// 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
+// 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,
- audit ctlproxy.Audit) (string, error) {
+ audit ctlproxy.Audit, stop func(attempt string) error) (string, error) {
switch {
case !serialText(q.Serial):
return "", fmt.Errorf("%w: serial must be 1 to 40 lower-case hex digits", ErrReportRequest)
case len(q.Report) == 0 || len(q.Sig) == 0 || len(q.Sig) > 128:
return "", fmt.Errorf("%w: a report and a signature are required", ErrReportRequest)
- case len(cfg.Key) != ed25519.PrivateKeySize || cfg.ImageVersion == nil || cfg.Fingerprint == nil:
+ case len(cfg.Key) != ed25519.PrivateKeySize || cfg.ImageVersion == nil || cfg.Fingerprint == nil || stop == nil:
return "", errors.New("ctlcert: the controller has no report config")
}
var c certRow
@@ -212,6 +219,9 @@ func AcceptReport(ctx context.Context, tx *sql.Tx, q hostedwire.CertReport, now
if err != nil {
return "", err
}
+ if err := stop(j.AttemptID); err != nil {
+ return "", fmt.Errorf("ctlcert: record the stop of %s: %w", j.AttemptID, err)
+ }
if _, err := tx.ExecContext(ctx, `INSERT INTO cert_evidence (launch_id, attempt_id, evidence_id, serial, evidence_json, sig, received_t)
VALUES (?, ?, ?, ?, ?, ?, ?)`, j.LaunchID, j.AttemptID, id, q.Serial, se.Evidence, se.Sig, int64(now.T)); err != nil {
return "", fmt.Errorf("ctlcert: keep evidence: %w", err)
diff --git a/internal/hostedctl/ctlcert/report_test.go b/internal/hostedctl/ctlcert/report_test.go
index 0c96b6e6..216c1611 100644
--- a/internal/hostedctl/ctlcert/report_test.go
+++ b/internal/hostedctl/ctlcert/report_test.go
@@ -8,6 +8,7 @@ import (
"crypto/x509"
"database/sql"
"encoding/json"
+ "errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -59,8 +60,23 @@ const (
type recorder struct {
isolatedjob.Runner
- mu sync.Mutex
- specs []isolatedjob.LaunchSpec
+ mu sync.Mutex
+ specs []isolatedjob.LaunchSpec
+ stopFail bool // every provider stop fails, as a throttled provider's
+ onStop func() // runs at each provider stop, before it is sent
+}
+
+func (r *recorder) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error {
+ r.mu.Lock()
+ fail, on := r.stopFail, r.onStop
+ r.mu.Unlock()
+ if on != nil {
+ on()
+ }
+ if fail {
+ return isolatedjob.ErrThrottled
+ }
+ return r.Runner.Stop(ctx, ref, reason)
}
func (r *recorder) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
@@ -76,6 +92,7 @@ func (alerts) Alert(context.Context, hostedctl.Alert) error { return nil }
type env struct {
t *testing.T
+ path string
ctx context.Context
clk *isolatedjobtest.FakeClock
fake *isolatedjob.Fake
@@ -115,14 +132,33 @@ func newEnv(t *testing.T) *env {
if _, err := ctlops.Reload(files, e.cfg.Certs, e.cfg.Candidates); err != nil {
t.Fatalf("Reload = %v", err)
}
- s, err := hostedctl.Open(e.ctx, filepath.Join(dir, "hosted.db"), clk)
+ e.path = filepath.Join(dir, "hosted.db")
+ e.open()
+ e.build()
+ return e
+}
+
+func (e *env) open() {
+ e.t.Helper()
+ s, err := hostedctl.Open(e.ctx, e.path, e.clk)
if err != nil {
- t.Fatalf("Open = %v", err)
+ e.t.Fatalf("Open = %v", err)
}
- t.Cleanup(func() { _ = s.Close() })
+ e.t.Cleanup(func() { _ = s.Close() })
e.store = s
+}
+
+// restart closes the store, as a controller that dies, and opens it again
+// under a new controller.
+func (e *env) restart() {
+ e.t.Helper()
+ if err := e.store.Close(); err != nil {
+ e.t.Fatalf("Close = %v", err)
+ }
+ e.clk.AdvanceMono(time.Second)
+ e.clk.SetWall(e.clk.Wall().Add(time.Second))
+ e.open()
e.build()
- return e
}
func (e *env) build() {
@@ -150,7 +186,12 @@ func (e *env) build() {
// answer signed by the controller for it.
func (e *env) do(method, path string, raw []byte, id hostedwire.KeyID, key ed25519.PrivateKey, extra http.Header) (int, []byte) {
e.t.Helper()
- req := httptest.NewRequest(method, "https://controller.example"+path, bytes.NewReader(raw))
+ return e.doCtx(e.ctx, method, path, raw, id, key, extra)
+}
+
+func (e *env) doCtx(ctx context.Context, method, path string, raw []byte, id hostedwire.KeyID, key ed25519.PrivateKey, extra http.Header) (int, []byte) {
+ e.t.Helper()
+ req := httptest.NewRequestWithContext(ctx, method, "https://controller.example"+path, bytes.NewReader(raw))
for k, v := range extra {
req.Header[k] = v
}
@@ -400,27 +441,28 @@ func TestReportOncePerLaunch(t *testing.T) {
t.Errorf("after the report: stop reason %v, %d serials unrevoked; want a stop and none", stopReason, unrevoked)
}
- // Two reports in one moment: the evidence row admits one. (Through
- // the API the stop revokes the serial first; here AcceptReport runs
- // twice on a second launch's live serial.)
+ // Acceptance and the stop are one: a stop that cannot be recorded
+ // keeps no evidence, and a stop callback that records nothing is
+ // refused by the store.
w := e.certVM(isolatedjob.SizeLarge, time.Hour)
cfg := ctlcert.ReportConfig{Key: keyCtl, ImageVersion: e.cfg.Certs.ImageVersion, Fingerprint: e.cfg.ProviderFingerprint, ProxyPolicy: 1}
- accept := func(note string) error {
+ accept := func(stop func(string) error) error {
var q hostedwire.CertReport
- _ = json.Unmarshal(proxytest.ReportBody(t, w.serial, proxytest.CertReport(w.launch, note), w.key), &q)
- var err error
- _ = e.store.Tx(e.ctx, func(tx *sql.Tx) error {
- _, err = ctlcert.AcceptReport(e.ctx, tx, q, ctlproxy.Now{T: time.Minute, Wall: e.clk.Wall()}, cfg,
- func(string, string, string) error { return nil })
- return nil
+ _ = json.Unmarshal(proxytest.ReportBody(t, w.serial, proxytest.CertReport(w.launch, "w"), w.key), &q)
+ return e.store.Tx(e.ctx, func(tx *sql.Tx) error {
+ _, err := ctlcert.AcceptReport(e.ctx, tx, q, ctlproxy.Now{T: time.Minute, Wall: e.clk.Wall()}, cfg,
+ func(string, string, string) error { return nil }, stop)
+ return err
})
- return err
}
- if err := accept("one"); err != nil {
- t.Fatalf("first AcceptReport = %v", err)
+ if err := accept(func(string) error { return errors.New("store lost") }); err == nil {
+ t.Error("AcceptReport succeeded with its stop not recorded")
}
- if err := accept("two"); err == nil || !strings.Contains(err.Error(), "already reported") {
- t.Errorf("second AcceptReport = %v, want ErrAlreadyReported", err)
+ if err := accept(func(string) error { return nil }); err == nil || !strings.Contains(err.Error(), "stop recorded") {
+ t.Errorf("AcceptReport with a stop that records nothing = %v, want the store's refusal", err)
+ }
+ if status, _ := e.evidence(w.launch); status != http.StatusNotFound {
+ t.Errorf("evidence of %s after failed acceptances = %d, want 404", w.launch, status)
}
}
@@ -472,3 +514,99 @@ func TestEvidenceFromLaunchRecord(t *testing.T) {
status, code := e.report(proxytest.ReportBody(t, w.serial, proxytest.CertReport(w.launch, "x"), w.key), nil)
e.wantRefused("a launch whose provider settings changed", status, code, "proxy_refused", "no longer launches")
}
+
+// TestEvidenceNeedsStopRecorded: the store keeps no evidence for a launch
+// whose stop is not recorded, so acceptance and the stop are one
+// transaction or neither happens.
+func TestEvidenceNeedsStopRecorded(t *testing.T) {
+ e := newEnv(t)
+ v := e.certVM(isolatedjob.SizeSmall, time.Hour)
+ err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
+ _, err := tx.ExecContext(e.ctx, `INSERT INTO cert_evidence (launch_id, attempt_id, evidence_id, serial, evidence_json, sig, received_t)
+ VALUES (?, ?, 'evidence-x', ?, x'7b7d', x'00', 1)`, v.launch, v.attempt, v.serial)
+ return err
+ })
+ if err == nil {
+ t.Fatal("evidence was kept for a launch with no stop recorded")
+ }
+}
+
+// stopState reads attempt's stop request, unrevoked serials and proof.
+func (e *env) stopState(attempt string) (stopRequested bool, unrevoked int, proof sql.NullString) {
+ e.t.Helper()
+ e.tx(func(tx *sql.Tx) error {
+ if err := tx.QueryRowContext(e.ctx, `SELECT stop_requested_t IS NOT NULL, stop_proof_json FROM jobs WHERE attempt_id = ?`,
+ attempt).Scan(&stopRequested, &proof); err != nil {
+ return err
+ }
+ return tx.QueryRowContext(e.ctx, `SELECT count(*) FROM proxy_certs WHERE attempt_id = ? AND revoked_t IS NULL`, attempt).Scan(&unrevoked)
+ })
+ return
+}
+
+// TestReportStopSurvivesCancellation: the proxy gives up on the request
+// as the controller starts stopping the VM. The stop goes on regardless,
+// and the stop proof is stored.
+func TestReportStopSurvivesCancellation(t *testing.T) {
+ e := newEnv(t)
+ v := e.certVM(isolatedjob.SizeSmall, time.Hour)
+ ctx, cancel := context.WithCancel(e.ctx)
+ defer cancel()
+ e.rec.mu.Lock()
+ e.rec.onStop = cancel
+ e.rec.mu.Unlock()
+ body := proxytest.ReportBody(t, v.serial, proxytest.CertReport(v.launch, "x"), v.key)
+ if status, out := e.doCtx(ctx, http.MethodPost, "/v1/proxy/cert-report", body, idProxy, keyProxy, nil); status != http.StatusOK {
+ t.Fatalf("report = %d %s", status, out)
+ }
+ if ctx.Err() == nil {
+ t.Fatal("the provider stop was never sent")
+ }
+ var proof sql.NullString
+ for i := 0; i < 6 && !proof.Valid; i++ {
+ _, _, proof = e.stopState(v.attempt)
+ e.fake.Tick()
+ e.clk.AdvanceMono(time.Minute)
+ e.clk.SetWall(e.clk.Wall().Add(time.Minute))
+ _ = e.c.Refresh(e.ctx)
+ }
+ var p hostedwire.StopProof
+ if !proof.Valid || json.Unmarshal([]byte(proof.String), &p) != nil || p.AttemptID != v.attempt || !p.State.Terminal() {
+ t.Fatalf("stop proof after a cancelled report = %v", proof)
+ }
+}
+
+// TestReportStopSurvivesRestart: the stop is recorded with the evidence,
+// serials revoked, even when the provider will not stop the VM yet and
+// the controller then dies; the controller that comes back drives it to
+// stop proof, which the store keeps.
+func TestReportStopSurvivesRestart(t *testing.T) {
+ e := newEnv(t)
+ v := e.certVM(isolatedjob.SizeSmall, time.Hour)
+ e.rec.mu.Lock()
+ e.rec.stopFail = true
+ e.rec.mu.Unlock()
+ if status, code := e.report(proxytest.ReportBody(t, v.serial, proxytest.CertReport(v.launch, "x"), v.key), nil); status != http.StatusOK {
+ t.Fatalf("report = %d %s", status, code)
+ }
+ state := func() (bool, int, sql.NullString) { return e.stopState(v.attempt) }
+ if requested, unrevoked, proof := state(); !requested || unrevoked != 0 || proof.Valid {
+ t.Fatalf("after the report with the provider refusing: stop asked %v, %d serials unrevoked, proof %v", requested, unrevoked, proof)
+ }
+ e.rec.mu.Lock()
+ e.rec.stopFail = false
+ e.rec.mu.Unlock()
+ e.restart()
+ var proof sql.NullString
+ for i := 0; i < 6 && !proof.Valid; i++ {
+ e.fake.Tick()
+ _ = e.c.Refresh(e.ctx)
+ _, _, proof = state()
+ e.clk.AdvanceMono(time.Minute)
+ e.clk.SetWall(e.clk.Wall().Add(time.Minute))
+ }
+ var p hostedwire.StopProof
+ if !proof.Valid || json.Unmarshal([]byte(proof.String), &p) != nil || p.AttemptID != v.attempt || !p.State.Terminal() {
+ t.Fatalf("stop proof after the restart = %v", proof)
+ }
+}
diff --git a/internal/hostedctl/proxy.go b/internal/hostedctl/proxy.go
index cfcdf212..d501b4ca 100644
--- a/internal/hostedctl/proxy.go
+++ b/internal/hostedctl/proxy.go
@@ -57,9 +57,11 @@ func serveRenew(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hoste
}
// serveCertReport keeps a certification report as signed evidence
-// (ctlcert.AcceptReport), then stops the VM: its one report is in. The
-// stop is the controller's own; one not yet proven is finished by the
-// reaper.
+// (ctlcert.AcceptReport) and, in the same transaction, records the
+// controller's own stop of the VM, which revokes its serials: its one
+// report is in. It then drives the stop, on a context the request's end
+// does not cancel; a stop not yet proven, or one a crash interrupted, is
+// driven to proof by Refresh like every recorded stop.
func serveCertReport(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, body []byte) (any, error) {
var q hostedwire.CertReport
if err := decode(body, &q); err != nil {
@@ -71,24 +73,24 @@ func serveCertReport(ctx context.Context, c *Controller, by hostedwire.KeyID, _
}
cfg := ctlcert.ReportConfig{Key: *key, ImageVersion: c.cfg.Certs.ImageVersion, Fingerprint: c.cfg.ProviderFingerprint,
ProxyPolicy: hostedwire.ProxyPolicyVersion}
- var attempt string
+ var stop stopReq
if _, err := c.proxyTx(ctx, by, func(tx *sql.Tx, now ctlproxy.Now, audit ctlproxy.Audit) (any, error) {
- var err error
- attempt, err = ctlcert.AcceptReport(ctx, tx, q, now, cfg, audit)
+ _, err := ctlcert.AcceptReport(ctx, tx, q, now, cfg, audit, func(attempt string) error {
+ r, refusal, err := c.recordStop(ctx, tx, "", attempt, reasonCertReported, false)
+ stop = r
+ return errors.Join(refusal, err)
+ })
return nil, err
}); err != nil {
return nil, err
}
- func() {
- defer c.lockAttempt(attempt)()
- r, err := c.requestStop(ctx, "", attempt, reasonCertReported, false)
- if err == nil && r.proof == nil && r.ref != "" {
- _, err = c.driveStop(ctx, "", r)
+ if stop.proof == nil && stop.ref != "" {
+ drive := context.WithoutCancel(ctx)
+ defer c.lockAttempt(stop.attempt)()
+ if _, err := c.driveStop(drive, "", stop); err != nil {
+ c.log.Info("certification VM not yet proven stopped", "attempt", stop.attempt, "err", err)
}
- if err != nil {
- c.log.Info("certification VM not yet proven stopped", "attempt", attempt, "err", err)
- }
- }()
+ }
return struct{}{}, nil
}
diff --git a/internal/hostedctl/schema/0005_cert_report.sql b/internal/hostedctl/schema/0005_cert_report.sql
index 1e0c0581..eedd857d 100644
--- a/internal/hostedctl/schema/0005_cert_report.sql
+++ b/internal/hostedctl/schema/0005_cert_report.sql
@@ -27,6 +27,16 @@ 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/stop.go b/internal/hostedctl/stop.go
index 3f6bfc12..289c4ba7 100644
--- a/internal/hostedctl/stop.go
+++ b/internal/hostedctl/stop.go
@@ -220,7 +220,26 @@ func (c *Controller) requestStop(ctx context.Context, actor hostedwire.KeyID, at
var r stopReq
var refusal error
err := c.store.Tx(ctx, func(tx *sql.Tx) error {
- r, refusal = stopReq{}, nil
+ var err error
+ r, refusal, err = c.recordStop(ctx, tx, actor, attempt, reason, creatorOnly)
+ return err
+ })
+ if err != nil {
+ return stopReq{}, err
+ }
+ if refusal != nil {
+ return stopReq{}, refusal
+ }
+ return r, nil
+}
+
+// recordStop is requestStop's work in the caller's transaction tx, so a
+// caller can record a stop together with what it requires (a
+// certification report's evidence, proxy.go). It returns the request, a
+// refusal (audited, to be committed) or an error.
+func (c *Controller) recordStop(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, attempt, reason string,
+ creatorOnly bool) (r stopReq, refusal error, _ error) {
+ err := func() error {
now := c.store.Clock().Now()
j, found, err := loadJob(ctx, tx, attempt)
if err != nil {
@@ -277,14 +296,8 @@ func (c *Controller) requestStop(ctx context.Context, actor hostedwire.KeyID, at
a.Reason += "; intent abandoned before any VM ref was saved"
}
return appendAudit(tx, a)
- })
- if err != nil {
- return stopReq{}, err
- }
- if refusal != nil {
- return stopReq{}, refusal
- }
- return r, nil
+ }()
+ return r, refusal, err
}
// driveStop sends the provider stop for a recorded request and then reads