oficina / equipo Public

hostedcert: certification evidence, trusted matrix and offline signer

A certification VM's report (root, user and sandbox probes, measured
digests, the containment suite) is signed with its proxy certificate
key and sent through the proxy. The controller accepts it only for an
issued, unrevoked serial of a live certification launch, signed by that
serial's own key, once per launch, with no identity header, and keeps it
as evidence signed with the controller key, every field but the report
from its own launch record. equipo-hosted-certify judges that evidence
offline against a separately supplied controller key, the release
manifest's digests and the trusted matrix, and signs the snapshot
derived from the evidence alone. Mutations 97 to 108 recorded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev bec02feb70498498d57b1fb0bb3bd140541af701 parent 2f94d13
36 files changed, +4,424 −45
  • .rastrillo/budgets.txt +1 −1
  • cmd/equipo-hosted-certify/main.go +561 −0
  • cmd/equipo-hosted-certify/main_test.go +367 −0
  • cmd/equipo-runner/hosted.go +19 −6
  • cmd/equipo-runner/hosted_certify_linux.go +174 −0
  • cmd/equipo-runner/hosted_certify_linux_test.go +18 −0
  • cmd/equipo-runner/hosted_certify_other.go +18 −0
  • cmd/equipo-runner/hosted_test.go +45 −16
  • cmd/equipo-runner/main.go +6 −0
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +68 −0
  • internal/hostedcert/evidence.go +240 −0
  • internal/hostedcert/judge.go +139 −0
  • internal/hostedcert/judge_test.go +281 −0
  • internal/hostedcert/matrix.go +87 −0
  • internal/hostedcert/matrix_test.go +79 −0
  • internal/hostedcert/probe_linux.go +675 −0
  • internal/hostedcert/probe_linux_test.go +358 −0
  • internal/hostedclient/client.go +14 −0
  • internal/hostedclient/operator.go +62 −0
  • internal/hostedctl/controller.go +4 −0
  • internal/hostedctl/ctlcert/report.go +304 −0
  • internal/hostedctl/ctlcert/report_test.go +474 −0
  • internal/hostedctl/ctlproxy/ca.go +9 −3
  • internal/hostedctl/http.go +11 −0
  • internal/hostedctl/proxy.go +55 −4
  • internal/hostedctl/schema/0005_cert_report.sql +40 −0
  • internal/hostedctl/stop.go +2 −0
  • internal/hostedctl/store.go +1 −1
  • internal/hostedproxy/proxytest/harness.go +8 −2
  • internal/hostedwire/hosted.go +12 −0
  • internal/runner/hosted/certify.go +121 −0
  • internal/runner/hosted/certify_test.go +67 −0
  • internal/vminit/hooks.go +5 −0
  • internal/vminit/init_test.go +56 −1
  • internal/vminit/measure.go +11 −0
  • internal/vminit/rootprobe_linux.go +32 −11
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 76ba2580..867a0b9c 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 5954 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.
+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.
diff --git a/cmd/equipo-hosted-certify/main.go b/cmd/equipo-hosted-certify/main.go
new file mode 100644
index 00000000..bde19e14
--- /dev/null
+++ b/cmd/equipo-hosted-certify/main.go
@@ -0,0 +1,561 @@
+// Command equipo-hosted-certify certifies a hosted runner image (plan
+// Task 13): it launches a certification VM, collects the evidence the
+// controller signed for its report, judges that evidence offline against
+// the trusted matrix and the release manifest, and signs the certificate.
+//
+// equipo-hosted-certify COMMAND [flags]
+//
+// launch -controller URL -controller-tls-pin HEX -controller-pub FILE
+// -operator-id ID -operator-key FILE -image sha256:... -size small|large
+// -ledger DIR -out FILE [-window 10m] [-timeout 45m] [-interval 15s]
+// journals the attempt ID in DIR/journal.tsv before the launch call
+// (a rerun with the same ledger asks for the same attempt), launches
+// the certification VM (POST /v1/cert/launch), waits for its evidence
+// (GET /v1/cert/evidence/{launch}) and writes it to FILE.
+// judge -evidence FILE -release FILE -controller-pub FILE [-out snapshot.json]
+// verifies the evidence's signature against the controller key FILE
+// (supplied here, never read from the evidence), checks its measured
+// digests against the release manifest, judges its report against
+// the trusted matrix (hostedcert.Matrix), and writes the snapshot
+// derived from the evidence alone.
+// sign -evidence FILE -release FILE -controller-pub FILE -key FILE -key-id ID
+// [-out certificate.json]
+// judges as judge does, then signs the derived snapshot with the
+// offline key FILE. There is no snapshot input to substitute.
+// verify -cert FILE -cert-keys FILE
+// verifies a certificate against the certificate key file
+// (controller/cert-keys.json) and prints its digest and snapshot.
+// reload (controller flags) POST /v1/admin/reload
+// alert-test (controller flags) POST /v1/admin/alert-test
+//
+// The controller flags are -controller, -controller-tls-pin (hex SHA-256
+// of the controller certificate's public key), -controller-pub (a file
+// holding the controller's ed25519 public key in standard base64),
+// -operator-id and -operator-key (a file holding the operator's ed25519
+// seed in standard base64, readable by its owner alone). The offline key
+// is a seed file the same way.
+//
+// Each success prints one JSON object on stdout. A failure prints one JSON
+// line on stderr and exits 2 (usage), 3 (the evidence does not certify,
+// or a signature does not verify) or 1 (anything else).
+package main
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/sha256"
+ "crypto/subtle"
+ "crypto/tls"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedclient"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlops"
+ "amadan.net/oficina/equipo/internal/hostedimage"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// Exit codes.
+const (
+ exitOther = 1
+ exitUsage = 2
+ exitRefused = 3
+)
+
+// JournalFile is the launch ledger's journal in the -ledger directory, as
+// equipo-hosted-image publish keeps its own.
+const JournalFile = "journal.tsv"
+
+func main() {
+ os.Exit(run(context.Background(), os.Args[1:], os.Stdout, os.Stderr, time.Now))
+}
+
+// failure is an error with its exit code.
+type failure struct {
+ exit int
+ kind string
+ err error
+}
+
+func (f *failure) Error() string { return f.err.Error() }
+func (f *failure) Unwrap() error { return f.err }
+
+func usage(format string, a ...any) error {
+ return &failure{exitUsage, "usage", fmt.Errorf(format, a...)}
+}
+
+func refused(err error) error { return &failure{exitRefused, "refused", err} }
+
+// report writes err as one JSON line and returns its exit code.
+func report(w io.Writer, err error) int {
+ f := &failure{exitOther, "other", err}
+ errors.As(err, &f)
+ b, _ := json.Marshal(map[string]string{"error": f.kind, "message": err.Error()})
+ fmt.Fprintf(w, "%s\n", b)
+ return f.exit
+}
+
+func run(ctx context.Context, args []string, stdout, stderr io.Writer, now func() time.Time) int {
+ if len(args) == 0 {
+ return report(stderr, usage("a command is required: launch, judge, sign, verify, reload or alert-test"))
+ }
+ fs := flag.NewFlagSet(args[0], flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ var res any
+ var err error
+ switch args[0] {
+ case "launch":
+ l := launchFlags(fs)
+ if err = parse(fs, args[1:]); err == nil {
+ res, err = l.run(ctx, now)
+ }
+ case "judge":
+ j := judgeFlags(fs)
+ out := fs.String("out", "snapshot.json", "where to write the derived snapshot")
+ if err = parse(fs, args[1:]); err == nil {
+ res, err = judge(j, *out)
+ }
+ case "sign":
+ j := judgeFlags(fs)
+ key := fs.String("key", "", "the offline signing key: an ed25519 seed in standard base64, readable by its owner alone")
+ keyID := fs.String("key-id", "", "the signing key's ID in controller/cert-keys.json")
+ out := fs.String("out", "certificate.json", "where to write the certificate")
+ if err = parse(fs, args[1:]); err == nil {
+ res, err = sign(j, *key, *keyID, *out, now)
+ }
+ case "verify":
+ cert := fs.String("cert", "", "the certificate to verify")
+ keys := fs.String("cert-keys", "", "the certificate key file (controller/cert-keys.json)")
+ if err = parse(fs, args[1:]); err == nil {
+ res, err = verify(*cert, *keys)
+ }
+ case "reload", "alert-test":
+ c := controllerFlags(fs)
+ if err = parse(fs, args[1:]); err == nil {
+ res, err = admin(ctx, args[0], c)
+ }
+ default:
+ err = usage("unknown command %q", args[0])
+ }
+ if err != nil {
+ return report(stderr, err)
+ }
+ b, _ := json.Marshal(res)
+ fmt.Fprintf(stdout, "%s\n", b)
+ return 0
+}
+
+func parse(fs *flag.FlagSet, args []string) error {
+ if err := fs.Parse(args); err != nil {
+ return usage("%v", err)
+ }
+ if fs.NArg() != 0 {
+ return usage("unexpected arguments %q", fs.Args())
+ }
+ return nil
+}
+
+// ---- judge and sign ----
+
+type judgeArgs struct{ evidence, release, controllerPub *string }
+
+func judgeFlags(fs *flag.FlagSet) judgeArgs {
+ return judgeArgs{
+ evidence: fs.String("evidence", "", "the signed evidence (GET /v1/cert/evidence/{launch})"),
+ release: fs.String("release", "", "the release's image manifest (infra/hosted/image/manifest.json)"),
+ controllerPub: fs.String("controller-pub", "", "the controller's ed25519 public key in standard base64, supplied separately"),
+ }
+}
+
+// certified is the whole judgement: the snapshot the evidence certifies,
+// derived from the evidence alone.
+func (j judgeArgs) certified() (hostedcert.Snapshot, error) {
+ if *j.evidence == "" || *j.release == "" || *j.controllerPub == "" {
+ return hostedcert.Snapshot{}, usage("-evidence, -release and -controller-pub are required")
+ }
+ pub, err := readPublic(*j.controllerPub)
+ if err != nil {
+ return hostedcert.Snapshot{}, err
+ }
+ raw, err := os.ReadFile(*j.evidence)
+ if err != nil {
+ return hostedcert.Snapshot{}, err
+ }
+ se, err := hostedcert.ReadSignedEvidence(raw)
+ if err != nil {
+ return hostedcert.Snapshot{}, refused(err)
+ }
+ m, err := hostedimage.LoadManifest(*j.release)
+ if err != nil {
+ return hostedcert.Snapshot{}, usage("%v", err)
+ }
+ s, err := hostedcert.Certify(se, pub, hostedcert.Release{Measured: m.Measured(), ContainmentTest: m.ContainmentTestSHA256})
+ if err != nil {
+ return hostedcert.Snapshot{}, refused(err)
+ }
+ return s, nil
+}
+
+type judgeResult struct {
+ Snapshot string `json:"snapshot"`
+ Derived hostedcert.Snapshot `json:"derived"`
+}
+
+func judge(j judgeArgs, out string) (judgeResult, error) {
+ s, err := j.certified()
+ if err != nil {
+ return judgeResult{}, err
+ }
+ if err := writeJSON(out, s); err != nil {
+ return judgeResult{}, err
+ }
+ return judgeResult{Snapshot: out, Derived: s}, nil
+}
+
+type signResult struct {
+ Certificate string `json:"certificate"`
+ Digest string `json:"digest"`
+}
+
+func sign(j judgeArgs, keyFile, keyID, out string, now func() time.Time) (signResult, error) {
+ if keyFile == "" || keyID == "" {
+ return signResult{}, usage("-key and -key-id are required")
+ }
+ key, err := readSeed(keyFile)
+ if err != nil {
+ return signResult{}, err
+ }
+ s, err := j.certified()
+ if err != nil {
+ return signResult{}, err
+ }
+ c := hostedcert.Sign(s, keyID, key, now())
+ if _, err := hostedcert.Verify(c, map[string]ed25519.PublicKey{keyID: key.Public().(ed25519.PublicKey)}); err != nil {
+ return signResult{}, err
+ }
+ if err := writeJSON(out, c); err != nil {
+ return signResult{}, err
+ }
+ return signResult{Certificate: out, Digest: hostedcert.Digest(c)}, nil
+}
+
+// ---- verify ----
+
+type verifyResult struct {
+ Digest string `json:"digest"`
+ Snapshot hostedcert.Snapshot `json:"snapshot"`
+}
+
+func verify(certFile, keysFile string) (verifyResult, error) {
+ if certFile == "" || keysFile == "" {
+ return verifyResult{}, usage("-cert and -cert-keys are required")
+ }
+ raw, err := os.ReadFile(certFile)
+ if err != nil {
+ return verifyResult{}, err
+ }
+ var c hostedcert.Certificate
+ if err := hostedwire.DecodeStrict(bytes.NewReader(raw), &c); err != nil {
+ return verifyResult{}, refused(err)
+ }
+ kraw, err := os.ReadFile(keysFile)
+ if err != nil {
+ return verifyResult{}, err
+ }
+ var kf struct {
+ Keys []struct {
+ ID string `json:"id"`
+ PublicKey string `json:"public_key"`
+ } `json:"keys"`
+ }
+ if err := hostedwire.DecodeStrict(bytes.NewReader(kraw), &kf); err != nil {
+ return verifyResult{}, usage("certificate key file: %v", err)
+ }
+ keys := map[string]ed25519.PublicKey{}
+ for _, k := range kf.Keys {
+ pub, err := base64.StdEncoding.Strict().DecodeString(k.PublicKey)
+ if err != nil || len(pub) != ed25519.PublicKeySize {
+ return verifyResult{}, usage("certificate key %q is not an ed25519 public key in base64", k.ID)
+ }
+ keys[k.ID] = pub
+ }
+ s, err := hostedcert.Verify(c, keys)
+ if err != nil {
+ return verifyResult{}, refused(err)
+ }
+ return verifyResult{Digest: hostedcert.Digest(c), Snapshot: s}, nil
+}
+
+// ---- the controller ----
+
+type controllerArgs struct{ url, pin, pub, id, key *string }
+
+func controllerFlags(fs *flag.FlagSet) controllerArgs {
+ return controllerArgs{
+ url: fs.String("controller", "", "the controller's https origin"),
+ pin: fs.String("controller-tls-pin", "", "hex SHA-256 of the controller certificate's public key"),
+ pub: fs.String("controller-pub", "", "the controller's ed25519 public key in standard base64"),
+ id: fs.String("operator-id", "", "the operator key's ID"),
+ key: fs.String("operator-key", "", "the operator's ed25519 seed in standard base64, readable by its owner alone"),
+ }
+}
+
+func (c controllerArgs) client() (*hostedclient.Client, hostedwire.KeyID, error) {
+ if *c.url == "" || *c.pin == "" || *c.pub == "" || *c.id == "" || *c.key == "" {
+ return nil, "", usage("-controller, -controller-tls-pin, -controller-pub, -operator-id and -operator-key are required")
+ }
+ want, err := hex.DecodeString(*c.pin)
+ if err != nil || len(want) != sha256.Size {
+ return nil, "", usage("-controller-tls-pin must be 64 hex digits")
+ }
+ pub, err := readPublic(*c.pub)
+ if err != nil {
+ return nil, "", err
+ }
+ key, err := readSeed(*c.key)
+ if err != nil {
+ return nil, "", err
+ }
+ tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12,
+ // The pin is the controller's identity: the leaf's key must be the
+ // pinned one. VerifyConnection runs either way.
+ InsecureSkipVerify: true,
+ VerifyConnection: func(cs tls.ConnectionState) error {
+ if len(cs.PeerCertificates) == 0 {
+ return errors.New("the controller sent no certificate")
+ }
+ got := sha256.Sum256(cs.PeerCertificates[0].RawSubjectPublicKeyInfo)
+ if subtle.ConstantTimeCompare(got[:], want) != 1 {
+ return errors.New("the controller's certificate is not the pinned one")
+ }
+ return nil
+ }}
+ cl, err := hostedclient.NewOperator(hostedclient.Config{BaseURL: *c.url, KeyID: hostedwire.KeyID(*c.id), Key: key, ControllerKey: pub,
+ HTTP: &http.Client{Transport: &http.Transport{TLSClientConfig: tlsCfg, Proxy: nil}, Timeout: time.Minute}})
+ if err != nil {
+ return nil, "", usage("%v", err)
+ }
+ return cl, hostedwire.KeyID(*c.id), nil
+}
+
+func admin(ctx context.Context, cmd string, c controllerArgs) (any, error) {
+ cl, _, err := c.client()
+ if err != nil {
+ return nil, err
+ }
+ if cmd == "reload" {
+ return cl.Reload(ctx)
+ }
+ return cl.AlertTest(ctx)
+}
+
+// ---- launch ----
+
+type launchArgs struct {
+ controllerArgs
+ image, size, ledger, out *string
+ window, timeout, interval *time.Duration
+}
+
+func launchFlags(fs *flag.FlagSet) launchArgs {
+ return launchArgs{controllerArgs: controllerFlags(fs),
+ image: fs.String("image", "", "the image digest to certify (sha256:...)"),
+ size: fs.String("size", "", "small or large: one certificate per size"),
+ ledger: fs.String("ledger", "", "the run's ledger directory; the attempt goes to journal.tsv there before the launch call"),
+ out: fs.String("out", "", "where to write the evidence"),
+ window: fs.Duration("window", 10*time.Minute, "how long the controller may take to launch"),
+ timeout: fs.Duration("timeout", 45*time.Minute, "how long to wait for the evidence"),
+ interval: fs.Duration("interval", 15*time.Second, "how often to ask for the evidence"),
+ }
+}
+
+type launchResult struct {
+ AttemptID string `json:"attempt_id"`
+ LaunchID string `json:"launch_id"`
+ Evidence string `json:"evidence"`
+}
+
+func (l launchArgs) run(ctx context.Context, now func() time.Time) (launchResult, error) {
+ switch {
+ case *l.image == "" || *l.size == "" || *l.ledger == "" || *l.out == "":
+ return launchResult{}, usage("-image, -size, -ledger and -out are required")
+ case *l.window <= 0 || *l.timeout <= 0 || *l.timeout > 2*time.Hour || *l.interval <= 0:
+ return launchResult{}, usage("-window, -timeout (at most 2h) and -interval must be positive")
+ }
+ if st, err := os.Stat(*l.ledger); err != nil || !st.IsDir() {
+ return launchResult{}, usage("-ledger %s is not a directory", *l.ledger)
+ }
+ cl, by, err := l.client()
+ if err != nil {
+ return launchResult{}, err
+ }
+ q := hostedwire.CertLaunchRequest{Image: isolatedjob.ImageDigest(*l.image), Size: isolatedjob.Size(*l.size)}
+ // A rerun with this ledger asks again for the attempt it journaled, so
+ // a lost answer never makes a second VM.
+ if q.LaunchByUnixMS, err = journaledLaunchBy(*l.ledger, q); err != nil {
+ return launchResult{}, err
+ }
+ if q.LaunchByUnixMS == 0 {
+ q.LaunchByUnixMS = now().Add(*l.window).UnixMilli()
+ }
+ if err := q.Validate(); err != nil {
+ return launchResult{}, usage("%v", err)
+ }
+ attempt := ctlops.CertAttemptID(by, q)
+ if err := journal(*l.ledger, now(), fmt.Sprintf("INTENT cert-launch %s %s %d %s", q.Image, q.Size, q.LaunchByUnixMS, attempt)); err != nil {
+ return launchResult{}, err
+ }
+ v, err := cl.CertLaunch(ctx, q)
+ if err != nil {
+ return launchResult{}, err
+ }
+ if v.AttemptID != attempt {
+ return launchResult{}, fmt.Errorf("the controller answered for attempt %s, not %s", v.AttemptID, attempt)
+ }
+ if err := journal(*l.ledger, now(), "LAUNCHED "+attempt+" "+v.LaunchID); err != nil {
+ return launchResult{}, err
+ }
+ giveUp := now().Add(*l.timeout)
+ for {
+ se, err := cl.Evidence(ctx, v.LaunchID)
+ if err == nil {
+ if err := writeJSON(*l.out, se); err != nil {
+ return launchResult{}, err
+ }
+ if err := journal(*l.ledger, now(), "EVIDENCE "+v.LaunchID+" "+*l.out); err != nil {
+ return launchResult{}, err
+ }
+ return launchResult{AttemptID: attempt, LaunchID: v.LaunchID, Evidence: *l.out}, nil
+ }
+ if !errors.Is(err, hostedclient.ErrNotFound) {
+ return launchResult{}, err
+ }
+ if !now().Before(giveUp) {
+ return launchResult{}, fmt.Errorf("no evidence for launch %s after %v", v.LaunchID, *l.timeout)
+ }
+ select {
+ case <-ctx.Done():
+ return launchResult{}, ctx.Err()
+ case <-time.After(*l.interval):
+ }
+ }
+}
+
+// journaledLaunchBy returns the launch-by time an earlier run journaled
+// for q's image and size in ledger, or 0.
+func journaledLaunchBy(ledger string, q hostedwire.CertLaunchRequest) (int64, error) {
+ f, err := os.Open(filepath.Join(ledger, JournalFile))
+ if errors.Is(err, os.ErrNotExist) {
+ return 0, nil
+ }
+ if err != nil {
+ return 0, err
+ }
+ defer f.Close()
+ var at int64
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ _, entry, _ := strings.Cut(sc.Text(), "\t")
+ fields := strings.Fields(entry)
+ if len(fields) == 6 && fields[0] == "INTENT" && fields[1] == "cert-launch" && fields[2] == string(q.Image) && fields[3] == string(q.Size) {
+ if at, err = strconv.ParseInt(fields[4], 10, 64); err != nil {
+ return 0, fmt.Errorf("the journal's launch-by %q does not read", fields[4])
+ }
+ }
+ }
+ return at, sc.Err()
+}
+
+// journal appends one timestamped entry to the ledger's journal and syncs
+// it before anything else happens.
+func journal(dir string, now time.Time, entry string) error {
+ f, err := os.OpenFile(filepath.Join(dir, JournalFile), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600)
+ if err != nil {
+ return err
+ }
+ _, err = fmt.Fprintf(f, "%s\t%s\n", now.UTC().Format("2006-01-02T15:04:05.000Z"), entry)
+ if err == nil {
+ err = f.Sync()
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ return err
+}
+
+// ---- files ----
+
+// readPublic reads an ed25519 public key in standard base64.
+func readPublic(path string) (ed25519.PublicKey, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ pub, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw)))
+ if err != nil || len(pub) != ed25519.PublicKeySize {
+ return nil, usage("%s must hold an ed25519 public key in standard base64", path)
+ }
+ return pub, nil
+}
+
+// readSeed reads an ed25519 seed in standard base64 from a file that
+// group and others cannot read.
+func readSeed(path string) (ed25519.PrivateKey, error) {
+ st, err := os.Stat(path)
+ if err != nil {
+ return nil, err
+ }
+ if st.Mode().Perm()&0o077 != 0 {
+ return nil, usage("%s is readable by group or others", path)
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ seed, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw)))
+ if err != nil || len(seed) != ed25519.SeedSize {
+ return nil, usage("%s must hold a %d-byte ed25519 seed in standard base64", path, ed25519.SeedSize)
+ }
+ return ed25519.NewKeyFromSeed(seed), nil
+}
+
+// writeJSON writes v to path atomically: a temporary file beside it,
+// synced, then renamed.
+func writeJSON(path string, v any) error {
+ b, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(path), ".equipo-certify-*")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(tmp.Name())
+ if _, err := tmp.Write(append(b, '\n')); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Sync(); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ return os.Rename(tmp.Name(), path)
+}
diff --git a/cmd/equipo-hosted-certify/main_test.go b/cmd/equipo-hosted-certify/main_test.go
new file mode 100644
index 00000000..80fa1d7f
--- /dev/null
+++ b/cmd/equipo-hosted-certify/main_test.go
@@ -0,0 +1,367 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "flag"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlops"
+ "amadan.net/oficina/equipo/internal/hostedimage"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+var (
+ ctlKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x51}, ed25519.SeedSize))
+ otherKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x52}, ed25519.SeedSize))
+ paulKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x53}, ed25519.SeedSize))
+ opKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x54}, ed25519.SeedSize))
+ image = isolatedjob.ImageDigest("sha256:" + strings.Repeat("e", 64))
+ wall = time.Date(2026, 12, 1, 9, 0, 0, 0, time.UTC)
+)
+
+// manifest is a release manifest; its Measured and containment pin are
+// what passing evidence must hold.
+func manifest() hostedimage.Manifest {
+ return hostedimage.Manifest{RunnerRelease: "v0.50.0", RunnerSHA256: strings.Repeat("1", 64), VMInitSHA256: strings.Repeat("2", 64),
+ BubblewrapSHA256: strings.Repeat("3", 64), GoToolchain: "go1.26.11", GoToolchainSHA256: strings.Repeat("4", 64),
+ GitSHA256: strings.Repeat("5", 64), CodexSHA256: strings.Repeat("6", 64), ContainmentTestSHA256: strings.Repeat("7", 64),
+ Resolvers: []string{"10.0.0.2"}, Metadata: []string{"169.254.169.254:80"}}
+}
+
+// passingReport is a report every probe of the matrix passes, measured
+// 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}}
+ for _, e := range hostedcert.Matrix() {
+ p := hostedcert.ProbeResult{Name: e.Name, Stage: e.Stage, Outcome: e.Want, OK: true}
+ switch e.Stage {
+ case hostedcert.StageRoot:
+ r.Root = append(r.Root, p)
+ case hostedcert.StageUser:
+ r.User = append(r.User, p)
+ default:
+ r.Sandbox = append(r.Sandbox, p)
+ }
+ }
+ return r
+}
+
+func evidence(r hostedcert.Report) hostedcert.Evidence {
+ return hostedcert.Evidence{EvidenceID: "evidence-1", LaunchID: r.LaunchID, Image: image,
+ ImageVersion: "arn:aws:lambda:eu-west-1:123456789012:microvm-image:equipo-hosted:4", ProxyPolicy: 1,
+ Deployment: []string{"equipo.example.com"}, Report: r, ReceivedNS: 99}
+}
+
+// files writes the evidence (signed with key), the release manifest m,
+// the controller's public key and the offline key into dir.
+type files struct{ evidence, release, controllerPub, key string }
+
+func write(t *testing.T, e hostedcert.Evidence, key ed25519.PrivateKey, m hostedimage.Manifest) files {
+ t.Helper()
+ dir := t.TempDir()
+ f := files{filepath.Join(dir, "evidence.json"), filepath.Join(dir, "manifest.json"), filepath.Join(dir, "controller.pub"),
+ filepath.Join(dir, "paul.key")}
+ se, err := hostedcert.SignEvidence(e, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ put := func(path string, b []byte, mode os.FileMode) {
+ if err := os.WriteFile(path, b, mode); err != nil {
+ t.Fatal(err)
+ }
+ }
+ raw, _ := json.Marshal(se)
+ put(f.evidence, raw, 0o644)
+ raw, _ = json.Marshal(m)
+ put(f.release, raw, 0o644)
+ put(f.controllerPub, []byte(base64.StdEncoding.EncodeToString(ctlKey.Public().(ed25519.PublicKey))+"\n"), 0o644)
+ put(f.key, []byte(base64.StdEncoding.EncodeToString(paulKey.Seed())), 0o600)
+ return f
+}
+
+func runCmd(t *testing.T, args ...string) (int, string, string) {
+ t.Helper()
+ var out, errOut bytes.Buffer
+ code := run(context.Background(), args, &out, &errOut, func() time.Time { return wall })
+ return code, out.String(), errOut.String()
+}
+
+// TestJudgeWritesSnapshotFromEvidence: judge writes the snapshot the
+// evidence certifies, every field from the evidence.
+func TestJudgeWritesSnapshotFromEvidence(t *testing.T) {
+ m := manifest()
+ e := evidence(passingReport(m, "l-1"))
+ f := write(t, e, ctlKey, m)
+ out := filepath.Join(t.TempDir(), "snapshot.json")
+ code, stdout, stderr := runCmd(t, "judge", "-evidence", f.evidence, "-release", f.release, "-controller-pub", f.controllerPub, "-out", out)
+ if code != 0 {
+ t.Fatalf("judge = %d %s %s", code, stdout, stderr)
+ }
+ raw, _ := os.ReadFile(out)
+ var s hostedcert.Snapshot
+ if err := json.Unmarshal(raw, &s); err != nil {
+ t.Fatal(err)
+ }
+ if string(hostedcert.Canonical(s)) != string(hostedcert.Canonical(hostedcert.Derive(e))) {
+ t.Errorf("snapshot = %+v, want %+v", s, hostedcert.Derive(e))
+ }
+}
+
+// TestJudgeRefusesFailingReport: evidence whose report fails the trusted
+// matrix is refused, however the VM labelled its results.
+func TestJudgeRefusesFailingReport(t *testing.T) {
+ m := manifest()
+ r := passingReport(m, "l-1")
+ r.Sandbox[0].Outcome, r.Sandbox[0].OK = hostedcert.OutcomeReached, true
+ f := write(t, evidence(r), ctlKey, m)
+ out := filepath.Join(t.TempDir(), "snapshot.json")
+ code, _, stderr := runCmd(t, "judge", "-evidence", f.evidence, "-release", f.release, "-controller-pub", f.controllerPub, "-out", out)
+ if code != exitRefused || !strings.Contains(stderr, r.Sandbox[0].Name) {
+ t.Errorf("judge = %d %s, want %d naming %s", code, stderr, exitRefused, r.Sandbox[0].Name)
+ }
+ if _, err := os.Stat(out); err == nil {
+ t.Error("judge wrote a snapshot for a failing report")
+ }
+}
+
+// TestEvidenceSignatureChecked: an evidence file edited after the
+// controller signed it is refused by judge and sign.
+func TestEvidenceSignatureChecked(t *testing.T) {
+ m := manifest()
+ f := write(t, evidence(passingReport(m, "l-1")), ctlKey, m)
+ raw, _ := os.ReadFile(f.evidence)
+ var se hostedcert.SignedEvidence
+ _ = json.Unmarshal(raw, &se)
+ se.Evidence = bytes.Replace(se.Evidence, []byte(`"proxy_policy":1`), []byte(`"proxy_policy":7`), 1)
+ raw, _ = json.Marshal(se)
+ if err := os.WriteFile(f.evidence, raw, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ for _, cmd := range [][]string{{"judge", "-out", filepath.Join(t.TempDir(), "s.json")},
+ {"sign", "-key", f.key, "-key-id", "paul-1", "-out", filepath.Join(t.TempDir(), "c.json")}} {
+ code, _, stderr := runCmd(t, append(cmd, "-evidence", f.evidence, "-release", f.release, "-controller-pub", f.controllerPub)...)
+ if code != exitRefused || !strings.Contains(stderr, "not signed by the given controller key") {
+ t.Errorf("%s of edited evidence = %d %s, want refused", cmd[0], code, stderr)
+ }
+ }
+}
+
+// TestEvidenceFromSubstitutedControllerKeyRefused: evidence signed by any
+// key but the controller's (the one supplied on the command line) is
+// refused; a key or field carried in the evidence file is not read, the
+// file refused for carrying it.
+func TestEvidenceFromSubstitutedControllerKeyRefused(t *testing.T) {
+ m := manifest()
+ f := write(t, evidence(passingReport(m, "l-1")), otherKey, m)
+ code, _, stderr := runCmd(t, "judge", "-evidence", f.evidence, "-release", f.release, "-controller-pub", f.controllerPub,
+ "-out", filepath.Join(t.TempDir(), "s.json"))
+ if code != exitRefused || !strings.Contains(stderr, "not signed by the given controller key") {
+ t.Errorf("judge of evidence signed by another key = %d %s, want refused", code, stderr)
+ }
+ // The forger's own key carried beside the evidence.
+ raw, _ := os.ReadFile(f.evidence)
+ var withKey map[string]any
+ _ = json.Unmarshal(raw, &withKey)
+ withKey["controller_pub"] = base64.StdEncoding.EncodeToString(otherKey.Public().(ed25519.PublicKey))
+ raw, _ = json.Marshal(withKey)
+ if err := os.WriteFile(f.evidence, raw, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ code, _, stderr = runCmd(t, "sign", "-evidence", f.evidence, "-release", f.release, "-controller-pub", f.controllerPub,
+ "-key", f.key, "-key-id", "paul-1", "-out", filepath.Join(t.TempDir(), "c.json"))
+ if code != exitRefused {
+ t.Errorf("sign of evidence carrying a key = %d %s, want refused", code, stderr)
+ }
+ // Without the controller key the commands do not run at all.
+ code, _, _ = runCmd(t, "judge", "-evidence", f.evidence, "-release", f.release)
+ if code != exitUsage {
+ t.Errorf("judge without -controller-pub = %d, want usage", code)
+ }
+}
+
+// TestSignRefusesMeasuredMismatch: evidence whose measured runner digest
+// differs from the release manifest's is refused, and no certificate is
+// written.
+func TestSignRefusesMeasuredMismatch(t *testing.T) {
+ m := manifest()
+ e := evidence(passingReport(m, "l-1"))
+ other := m
+ other.RunnerSHA256 = strings.Repeat("9", 64)
+ f := write(t, e, ctlKey, other)
+ out := filepath.Join(t.TempDir(), "certificate.json")
+ code, _, stderr := runCmd(t, "sign", "-evidence", f.evidence, "-release", f.release, "-controller-pub", f.controllerPub,
+ "-key", f.key, "-key-id", "paul-1", "-out", out)
+ if code != exitRefused || !strings.Contains(stderr, hostedcert.MeasuredRunner) {
+ t.Errorf("sign = %d %s, want refused naming the runner", code, stderr)
+ }
+ if _, err := os.Stat(out); err == nil {
+ t.Error("sign wrote a certificate for a mismatched runner")
+ }
+}
+
+// TestSignHasNoSnapshotInput: sign takes the evidence, the release, the
+// controller key and the offline key, and nothing that could stand in for
+// the snapshot; the certificate it writes signs the snapshot derived from
+// the evidence and verifies under the offline key.
+func TestSignHasNoSnapshotInput(t *testing.T) {
+ fs := flag.NewFlagSet("sign", flag.ContinueOnError)
+ judgeFlags(fs)
+ _ = fs.String("key", "", "")
+ _ = fs.String("key-id", "", "")
+ _ = fs.String("out", "", "")
+ var names []string
+ fs.VisitAll(func(f *flag.Flag) { names = append(names, f.Name) })
+ if want := []string{"controller-pub", "evidence", "key", "key-id", "out", "release"}; !slices.Equal(names, want) {
+ t.Errorf("sign's flags = %q, want %q", names, want)
+ }
+
+ m := manifest()
+ e := evidence(passingReport(m, "l-1"))
+ f := write(t, e, ctlKey, m)
+ snapshot := filepath.Join(t.TempDir(), "snapshot.json")
+ forged := hostedcert.Derive(e)
+ forged.Image = isolatedjob.ImageDigest("sha256:" + strings.Repeat("f", 64))
+ raw, _ := json.Marshal(forged)
+ if err := os.WriteFile(snapshot, raw, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ base := []string{"sign", "-evidence", f.evidence, "-release", f.release, "-controller-pub", f.controllerPub, "-key", f.key, "-key-id", "paul-1"}
+ if code, _, stderr := runCmd(t, append(base, "-snapshot", snapshot)...); code != exitUsage {
+ t.Errorf("sign -snapshot = %d %s, want usage", code, stderr)
+ }
+ out := filepath.Join(t.TempDir(), "certificate.json")
+ code, stdout, stderr := runCmd(t, append(base, "-out", out)...)
+ if code != 0 {
+ t.Fatalf("sign = %d %s %s", code, stdout, stderr)
+ }
+ raw, _ = os.ReadFile(out)
+ var c hostedcert.Certificate
+ if err := json.Unmarshal(raw, &c); err != nil {
+ t.Fatal(err)
+ }
+ s, err := hostedcert.Verify(c, map[string]ed25519.PublicKey{"paul-1": paulKey.Public().(ed25519.PublicKey)})
+ if err != nil || string(hostedcert.Canonical(s)) != string(hostedcert.Canonical(hostedcert.Derive(e))) || !c.IssuedAt.Equal(wall) {
+ t.Errorf("certificate %+v (%v), want the evidence's snapshot", s, err)
+ }
+ // verify reads it back under the certificate key file.
+ keys := filepath.Join(t.TempDir(), "cert-keys.json")
+ _ = os.WriteFile(keys, []byte(`{"keys":[{"id":"paul-1","public_key":"`+
+ base64.StdEncoding.EncodeToString(paulKey.Public().(ed25519.PublicKey))+`"}]}`), 0o644)
+ if code, stdout, _ := runCmd(t, "verify", "-cert", out, "-cert-keys", keys); code != 0 || !strings.Contains(stdout, hostedcert.Digest(c)) {
+ t.Errorf("verify = %d %s", code, stdout)
+ }
+ // An offline key others can read is refused.
+ if err := os.Chmod(f.key, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if code, _, _ := runCmd(t, append(base, "-out", out)...); code != exitUsage {
+ t.Errorf("sign with a world-readable key = %d, want usage", code)
+ }
+}
+
+// fakeController answers the operator's certification launch and, after
+// one not-found, the evidence, each answer signed for its request. It
+// records the ledger's journal as it stood when each launch arrived.
+type fakeController struct {
+ t *testing.T
+ ledger string
+ evidence hostedcert.SignedEvidence
+ mu sync.Mutex
+ journals []string
+ asked int
+}
+
+func (f *fakeController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ status, out := http.StatusOK, []byte(nil)
+ f.mu.Lock()
+ switch {
+ case r.Method == http.MethodPost && r.URL.Path == "/v1/cert/launch":
+ j, _ := os.ReadFile(filepath.Join(f.ledger, JournalFile))
+ f.journals = append(f.journals, string(j))
+ var q hostedwire.CertLaunchRequest
+ _ = json.Unmarshal(body, &q)
+ out, _ = json.Marshal(hostedwire.JobView{AttemptID: ctlops.CertAttemptID(hostedwire.KeyID(r.Header.Get(hostedwire.HeaderKeyID)), q),
+ LaunchID: "launch-1", State: "starting"})
+ case r.Method == http.MethodGet && r.URL.Path == "/v1/cert/evidence/launch-1":
+ f.asked++
+ if f.asked == 1 {
+ status, out = http.StatusNotFound, []byte(`{"code":"not_found","message":"Not found."}`)
+ } else {
+ out, _ = json.Marshal(f.evidence)
+ }
+ default:
+ status, out = http.StatusNotFound, []byte(`{"code":"no_route","message":"No such route."}`)
+ }
+ f.mu.Unlock()
+ hostedwire.SignResponse(w.Header(), status, r.Header.Get(hostedwire.HeaderNonce), out, ctlKey)
+ w.WriteHeader(status)
+ _, _ = w.Write(out)
+}
+
+// TestLaunchJournalsBeforeCreate: launch writes its attempt to the
+// ledger before the launch call, waits through a not-found for the
+// evidence and writes it; a rerun with the same ledger asks for the same
+// attempt.
+func TestLaunchJournalsBeforeCreate(t *testing.T) {
+ m := manifest()
+ se, _ := hostedcert.SignEvidence(evidence(passingReport(m, "launch-1")), ctlKey)
+ ledger := t.TempDir()
+ fc := &fakeController{t: t, ledger: ledger, evidence: se}
+ srv := httptest.NewTLSServer(fc)
+ defer srv.Close()
+ sum := sha256.Sum256(srv.Certificate().RawSubjectPublicKeyInfo)
+ dir := t.TempDir()
+ pub, key := filepath.Join(dir, "controller.pub"), filepath.Join(dir, "op.key")
+ _ = os.WriteFile(pub, []byte(base64.StdEncoding.EncodeToString(ctlKey.Public().(ed25519.PublicKey))), 0o644)
+ _ = os.WriteFile(key, []byte(base64.StdEncoding.EncodeToString(opKey.Seed())), 0o600)
+ out := filepath.Join(dir, "evidence.json")
+ args := []string{"launch", "-controller", srv.URL, "-controller-tls-pin", hex.EncodeToString(sum[:]), "-controller-pub", pub,
+ "-operator-id", "op-1", "-operator-key", key, "-image", string(image), "-size", "large", "-ledger", ledger, "-out", out,
+ "-interval", "10ms"}
+ code, stdout, stderr := runCmd(t, args...)
+ if code != 0 {
+ t.Fatalf("launch = %d %s %s", code, stdout, stderr)
+ }
+ attempt := ctlops.CertAttemptID("op-1", hostedwire.CertLaunchRequest{Image: image, Size: isolatedjob.SizeLarge,
+ LaunchByUnixMS: wall.Add(10 * time.Minute).UnixMilli()})
+ if len(fc.journals) != 1 || !strings.Contains(fc.journals[0], "INTENT cert-launch "+string(image)+" large") ||
+ !strings.Contains(fc.journals[0], attempt) {
+ t.Fatalf("the journal when the launch arrived = %q, want the intent naming %s", fc.journals, attempt)
+ }
+ raw, _ := os.ReadFile(out)
+ got, err := hostedcert.ReadSignedEvidence(raw)
+ if err != nil || !bytes.Equal(got.Evidence, se.Evidence) || fc.asked != 2 {
+ t.Errorf("evidence written %v after %d asks", err, fc.asked)
+ }
+ // Again with the same ledger, later: the same attempt.
+ var later bytes.Buffer
+ if code := run(context.Background(), args, &later, io.Discard, func() time.Time { return wall.Add(3 * time.Minute) }); code != 0 {
+ t.Fatalf("second launch = %d", code)
+ }
+ if !strings.Contains(later.String(), attempt) {
+ t.Errorf("rerun = %s, want attempt %s again", later.String(), attempt)
+ }
+}
diff --git a/cmd/equipo-runner/hosted.go b/cmd/equipo-runner/hosted.go
index 9259c02c..907f22d9 100644
--- a/cmd/equipo-runner/hosted.go
+++ b/cmd/equipo-runner/hosted.go
@@ -13,18 +13,23 @@ import (
"amadan.net/oficina/equipo/internal/runner/hosted"
)
-// startHosted is hosted.Start; tests replace it.
-var startHosted = hosted.Start
+// startHosted is hosted.Start, and certifyHosted certify; tests replace
+// them.
+var (
+ startHosted = hosted.Start
+ certifyHosted = certify
+)
// errNotWired is a hosted subcommand whose work has not arrived yet: the
-// checks worker loop (Task 17) and the certification probes (Task 13).
+// checks worker loop (Task 17).
var errNotWired = errors.New("equipo-runner: started, but this hosted subcommand is not yet wired")
// hostedMain runs hosted-run or hosted-certify as vm-init starts it: the
// environment names the bootstrap file (in the state directory) and the
// results directory. It reads and deletes the bootstrap, checks that its
-// purpose is the subcommand's, and runs hosted.Start. What follows Start
-// is not built yet, so it then refuses.
+// purpose is the subcommand's, and runs hosted.Start. hosted-certify then
+// runs the certification probes and sends the report (certify); what
+// follows Start for hosted-run is not built yet, so it then refuses.
func hostedMain(ctx context.Context, sub string, errorOutput io.Writer, getenv func(string) string) int {
logger := slog.New(slog.NewTextHandler(errorOutput, nil))
fail := func(code, variable string, err error) int {
@@ -50,9 +55,17 @@ func hostedMain(ctx context.Context, sub string, errorOutput io.Writer, getenv f
if b.Purpose != want {
return fail("runner.hosted.purpose", hostedwire.EnvBootstrap, fmt.Errorf("a %s bootstrap for %s", b.Purpose, sub))
}
- if _, err := startHosted(ctx, b, vm, filepath.Dir(path)); err != nil {
+ s, err := startHosted(ctx, b, vm, filepath.Dir(path))
+ if err != nil {
return fail("runner.hosted.start", hostedwire.EnvBootstrap, err)
}
logger.Info("hosted runner started", "subcommand", sub, "launch", b.LaunchID, "vm", string(vm))
+ if sub == hostedwire.SubcommandCertify {
+ if err := certifyHosted(ctx, s, filepath.Dir(path), results); err != nil {
+ return fail("runner.hosted.certify", hostedwire.EnvResults, err)
+ }
+ logger.Info("certification report sent", "launch", b.LaunchID)
+ return 0
+ }
return fail("runner.hosted.not_wired", "-", errNotWired)
}
diff --git a/cmd/equipo-runner/hosted_certify_linux.go b/cmd/equipo-runner/hosted_certify_linux.go
new file mode 100644
index 00000000..323373d5
--- /dev/null
+++ b/cmd/equipo-runner/hosted_certify_linux.go
@@ -0,0 +1,174 @@
+//go:build linux
+
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/hosted"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain"
+)
+
+// Where the hosted image installs what certification runs (hostedimage's
+// PathBwrap and PathContainmentTest; a test holds them equal) and the Go
+// tree (the Dockerfile unpacks the toolchain into /usr/local).
+const (
+ hostedBwrap = "/usr/bin/bwrap"
+ hostedContainmentTest = "/usr/local/libexec/equipo/containment.test"
+ hostedGoRoot = "/usr/local/go"
+)
+
+// Inside the checks sandbox: the probe binary (a copy of this runner in
+// the workspace), the Go tree, and the probes' scratch.
+const (
+ sandboxProbe = "/workspace/equipo-probes"
+ sandboxGoRoot = "/opt/go"
+ sandboxWork = "/tmp/equipo-probes"
+ // certifyTimeout bounds the whole certification run.
+ certifyTimeout = 15 * time.Minute
+)
+
+// certify makes a certification VM's report and sends it: the user
+// probes here, the sandbox probes in the checks sandbox, the containment
+// suite, with vm-init's results from results, and the state directory
+// state for the sandbox's workspace.
+func certify(ctx context.Context, s *hosted.Session, state, results string) error {
+ ctx, cancel := context.WithTimeout(ctx, certifyTimeout)
+ defer cancel()
+ egress, boot := s.Proxies()
+ c := hostedcert.Collector{LaunchID: s.LaunchID(), Results: results,
+ User: hostedcert.DefaultUserProbes(s.ReuseProxyCode, s.InstanceProtocol),
+ Sandbox: func(ctx context.Context, pt hostedcert.ProbeTargets) []hostedcert.ProbeResult {
+ t := hostedcert.SandboxTargets{PublicIPv4: hostedcert.PublicIPv4, PublicIPv6: hostedcert.PublicIPv6, Resolvers: pt.Resolvers,
+ Metadata: pt.Metadata, ProxyEgress: egress, ProxyBoot: boot, GoRoot: sandboxGoRoot, Work: sandboxWork}
+ return hostedcert.RunInSandbox(ctx, checksSandbox(state), sandboxProbe, t)
+ },
+ Containment: func(ctx context.Context) hostedcert.ContainmentResult {
+ return hostedcert.RunContainment(ctx, hostedContainmentTest, runPlain)
+ }}
+ r, err := c.Collect(ctx)
+ if err != nil {
+ return err
+ }
+ raw, err := json.Marshal(r)
+ if err != nil {
+ return err
+ }
+ return s.SendReport(ctx, raw)
+}
+
+// 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
+ cmd.Stdout, cmd.Stderr = &out, &out
+ err := cmd.Run()
+ var exit *exec.ExitError
+ switch {
+ case err == nil:
+ return 0, out.b.Bytes(), nil
+ case errors.As(err, &exit):
+ return exit.ExitCode(), out.b.Bytes(), nil
+ }
+ return -1, out.b.Bytes(), err
+}
+
+// limited keeps the first max bytes written to it.
+type limited struct {
+ mu sync.Mutex
+ b bytes.Buffer
+ max int
+}
+
+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)])
+ }
+ return len(p), nil
+}
+
+// checksSandbox runs argv in the checks sandbox: the containment
+// manager's namespace under the check policy (no network, no provider
+// home), as the runner's checks run, with a copy of this runner in the
+// workspace as the probe binary.
+func checksSandbox(state string) hostedcert.SandboxRunner {
+ return func(ctx context.Context, argv []string) ([]byte, int, error) {
+ self, err := os.Executable()
+ if err != nil {
+ return nil, -1, err
+ }
+ scratch, work := filepath.Join(state, "certify-scratch"), filepath.Join(state, "certify-work")
+ for _, d := range []string{scratch, work} {
+ if err := os.Mkdir(d, 0o700); err != nil {
+ return nil, -1, err
+ }
+ }
+ if err := copyExecutable(self, filepath.Join(work, filepath.Base(sandboxProbe))); err != nil {
+ return nil, -1, err
+ }
+ m, err := containment.New(containment.Config{Binary: hostedBwrap, RunnerBinary: self, ScratchRoot: scratch})
+ if err != nil {
+ return nil, -1, fmt.Errorf("the containment manager: %w", err)
+ }
+ policy, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: work, Bwrap: hostedBwrap, RunnerBinary: self,
+ GoRoot: hostedGoRoot, Argv: argv, Env: gotoolchain.Environment()})
+ if err != nil {
+ return nil, -1, fmt.Errorf("the check policy: %w", err)
+ }
+ proc, err := m.Start(ctx, provider.Launch{AttemptKey: "certify/" + rand.Text(), Workspace: work, Policy: policy}, argv)
+ if err != nil {
+ return nil, -1, err
+ }
+ _ = proc.Stdin().Close()
+ var stdout limited
+ stdout.max = 1 << 20
+ var copied sync.WaitGroup
+ copied.Add(2)
+ go func() { defer copied.Done(); _, _ = io.Copy(&stdout, proc.Stdout()) }()
+ go func() { defer copied.Done(); _, _ = io.Copy(io.Discard, proc.Stderr()) }()
+ exit, err := proc.Wait(ctx)
+ copied.Wait()
+ return stdout.b.Bytes(), exit.Code, err
+ }
+}
+
+// copyExecutable copies src to a new file dst, mode 0755.
+func copyExecutable(src, dst string) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o755)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, in); err != nil {
+ out.Close()
+ return err
+ }
+ return out.Close()
+}
+
+// sandboxProbes is the sandbox's side: hostedcert.SandboxMain.
+func sandboxProbes(ctx context.Context, args []string, output io.Writer) int {
+ return hostedcert.SandboxMain(ctx, args, output)
+}
diff --git a/cmd/equipo-runner/hosted_certify_linux_test.go b/cmd/equipo-runner/hosted_certify_linux_test.go
new file mode 100644
index 00000000..c95bc06a
--- /dev/null
+++ b/cmd/equipo-runner/hosted_certify_linux_test.go
@@ -0,0 +1,18 @@
+//go:build linux
+
+package main
+
+import (
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedimage"
+)
+
+// TestCertifyPathsAreTheImages: certification runs bubblewrap and the
+// containment suite where the image installs them.
+func TestCertifyPathsAreTheImages(t *testing.T) {
+ if hostedBwrap != hostedimage.PathBwrap || hostedContainmentTest != hostedimage.PathContainmentTest {
+ t.Errorf("bwrap %s, containment suite %s; the image installs %s and %s", hostedBwrap, hostedContainmentTest,
+ hostedimage.PathBwrap, hostedimage.PathContainmentTest)
+ }
+}
diff --git a/cmd/equipo-runner/hosted_certify_other.go b/cmd/equipo-runner/hosted_certify_other.go
new file mode 100644
index 00000000..fb76e0b6
--- /dev/null
+++ b/cmd/equipo-runner/hosted_certify_other.go
@@ -0,0 +1,18 @@
+//go:build !linux
+
+package main
+
+import (
+ "context"
+ "errors"
+ "io"
+
+ "amadan.net/oficina/equipo/internal/runner/hosted"
+)
+
+// A hosted VM is Linux: certification runs nowhere else.
+func certify(context.Context, *hosted.Session, string, string) error {
+ return errors.New("equipo-runner: hosted certification runs only on Linux")
+}
+
+func sandboxProbes(context.Context, []string, io.Writer) int { return 2 }
diff --git a/cmd/equipo-runner/hosted_test.go b/cmd/equipo-runner/hosted_test.go
index 646106b9..c74026aa 100644
--- a/cmd/equipo-runner/hosted_test.go
+++ b/cmd/equipo-runner/hosted_test.go
@@ -37,31 +37,60 @@ func hostedBootstrap(t *testing.T, purpose string) string {
}
// The hosted subcommands read vm-init's environment and bootstrap and
-// run Start; until their work arrives (Tasks 13 and 17) they then refuse
-// with "not yet wired", never a silent success.
+// run Start. hosted-certify then certifies (Task 13), with the session,
+// the state directory and the results directory, and exits 0 only once
+// its report is sent; hosted-run, until its work arrives (Task 17),
+// refuses with "not yet wired", never a silent success.
func TestHostedSubcommandsNotYetWired(t *testing.T) {
- defer func(f func(context.Context, hostedwire.BootstrapV2, isolatedjob.Ref, string) (*hosted.Session, error)) {
- startHosted = f
- }(startHosted)
- for sub, purpose := range map[string]string{hostedwire.SubcommandChecks: hostedwire.PurposeChecks,
- hostedwire.SubcommandCertify: hostedwire.PurposeCertification} {
- path := hostedBootstrap(t, purpose)
- env := map[string]string{hostedwire.EnvBootstrap: path, hostedwire.EnvResults: filepath.Join(t.TempDir(), "results")}
- var started []string
+ defer func(f func(context.Context, hostedwire.BootstrapV2, isolatedjob.Ref, string) (*hosted.Session, error),
+ c func(context.Context, *hosted.Session, string, string) error) {
+ startHosted, certifyHosted = f, c
+ }(startHosted, certifyHosted)
+ for _, tc := range []struct {
+ sub, purpose string
+ certifyErr error
+ code int
+ want string
+ }{
+ {hostedwire.SubcommandChecks, hostedwire.PurposeChecks, nil, 1, "runner.hosted.not_wired"},
+ {hostedwire.SubcommandCertify, hostedwire.PurposeCertification, nil, 0, ""},
+ {hostedwire.SubcommandCertify, hostedwire.PurposeCertification, errors.New("report refused"), 1, "runner.hosted.certify"},
+ } {
+ path := hostedBootstrap(t, tc.purpose)
+ results := filepath.Join(t.TempDir(), "results")
+ env := map[string]string{hostedwire.EnvBootstrap: path, hostedwire.EnvResults: results}
+ var started, certified []string
+ session := &hosted.Session{}
startHosted = func(_ context.Context, b hostedwire.BootstrapV2, vm isolatedjob.Ref, state string) (*hosted.Session, error) {
started = append(started, b.Purpose+" "+string(vm)+" "+state)
- return &hosted.Session{}, nil
+ return session, nil
+ }
+ certifyHosted = func(_ context.Context, s *hosted.Session, state, res string) error {
+ if s == session {
+ certified = append(certified, state+" "+res)
+ }
+ return tc.certifyErr
}
var out, errOut bytes.Buffer
- code := run(context.Background(), []string{sub}, strings.NewReader(""), &out, &errOut, func(k string) string { return env[k] })
- want := purpose + " vm-1 " + filepath.Dir(path)
- if code != 1 || len(started) != 1 || started[0] != want || !strings.Contains(errOut.String(), "runner.hosted.not_wired") {
- t.Errorf("%s: exit %d, started %q (want %q), stderr %q", sub, code, started, want, errOut.String())
+ code := run(context.Background(), []string{tc.sub}, strings.NewReader(""), &out, &errOut, func(k string) string { return env[k] })
+ want := tc.purpose + " vm-1 " + filepath.Dir(path)
+ if code != tc.code || len(started) != 1 || started[0] != want || !strings.Contains(errOut.String(), tc.want) {
+ t.Errorf("%s: exit %d, started %q (want %q), stderr %q; want exit %d naming %q", tc.sub, code, started, want, errOut.String(), tc.code, tc.want)
+ }
+ if wantCertified := tc.sub == hostedwire.SubcommandCertify; wantCertified != (len(certified) == 1) ||
+ wantCertified && certified[0] != filepath.Dir(path)+" "+results {
+ t.Errorf("%s: certified %q", tc.sub, certified)
}
if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
- t.Errorf("%s: the bootstrap file was left behind", sub)
+ t.Errorf("%s: the bootstrap file was left behind", tc.sub)
}
}
+ // The sandbox probes' subcommand takes exactly its targets.
+ var out, errOut bytes.Buffer
+ if code := run(context.Background(), []string{"hosted-sandbox-probes", "{}"}, strings.NewReader(""), &out, &errOut,
+ func(string) string { return "" }); code != 2 {
+ t.Errorf("sandbox probes with no targets: exit %d, want 2", code)
+ }
// The other purpose's bootstrap, a failed Start and a missing
// environment are refused for what they are, and Start runs only for
// the right purpose.
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go
index 3818d2ed..96fd67d1 100644
--- a/cmd/equipo-runner/main.go
+++ b/cmd/equipo-runner/main.go
@@ -13,6 +13,7 @@ import (
"syscall"
"amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/hostedcert"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/runner"
@@ -64,6 +65,11 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu
}
return installRunner(ctx, args[1:], input, output, errorOutput, getenv)
}
+ // A certification VM's sandbox probes, started by its runner inside
+ // the checks sandbox with their targets as the one argument.
+ if len(args) == 2 && args[0] == hostedcert.SandboxSubcommand {
+ return sandboxProbes(ctx, args[1:], output)
+ }
// A hosted VM's runner, started by vm-init with its own environment.
if len(args) == 1 && (args[0] == hostedwire.SubcommandChecks || args[0] == hostedwire.SubcommandCertify) {
return hostedMain(ctx, args[0], errorOutput, getenv)
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index a9c86b5f..eb75ecf8 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -924,3 +924,71 @@ No code change. Four more mutation checks, run as before (sed, `go test ... -cou
- `sed -i 's/if len(leaf.URIs) != 1 {/if len(leaf.URIs) == 0 {/' internal/runner/hosted/redeem.go`
- `go test $H -run '^TestProxyCertGuards$'`
- FAIL: `guards_test.go:113: two launch URIs: accepted`. Restored.
+
+## Task 13
+
+Certification run, evidence and offline signing (Fable M8, certification half).
+
+- `internal/hostedcert` (new files). `evidence.go`: `Report{LaunchID; Root, User, Sandbox []ProbeResult; Measured map[string]string; Containment ContainmentResult}` with `Check` (bounds and form); `ProbeResult{Name, Stage, OK, Outcome, Detail}`, where `Outcome` is what the probe's attempt did (`blocked`, `reached`, `inconclusive`) and `OK` is the VM's own verdict, which nothing reads; `Evidence{EvidenceID, LaunchID, Image, ImageVersion, ProxyPolicy, Deployment, Report, ReceivedNS}`; `SignedEvidence{Evidence []byte (the exact JSON signed); Sig}`; `SignEvidence` (ed25519 over a length-prefixed label and the bytes) and `OpenEvidence(se, controllerPub)`, which verifies against the key the caller holds and then decodes strictly. `matrix.go`: `Matrix()`, the one trusted table (3 root, 4 user, 10 sandbox rows; positive controls `user_instance_protocol` and `sandbox_go_tree_read`), `ContainmentArgs()` (`-test.v -test.count=1 -test.skip ^TestSource`, the third control). `judge.go`: `Judge(report, matrix)` compares only `Outcome` with the matrix, needs every row exactly once in its stage's list, refuses probes the matrix does not know, and needs the containment suite with those arguments, exit 0, nothing failed or skipped; `CheckMeasured` (runner, vm-init, sandbox policy equal the release's); `Derive(evidence)`; `Certify(se, controllerPub, release)` does all of it and checks the derived snapshot. `probe_linux.go`: the user probes, the sandbox probes (`RunSandboxProbes`, `SandboxMain` as `equipo-runner hosted-sandbox-probes <targets>`), `RunInSandbox` (a failed sandbox leaves every sandbox row inconclusive), `RunContainment` (counts `--- PASS/FAIL/SKIP`, measures the suite), and `Collector` (reads `root.json`, `measured.json`, `probe-targets.json` strictly). Every network, privilege and sandbox step is a seam.
+- `internal/vminit`: `ProbeResult` gains `Outcome` (a probe that saw an answer, a credential or a named resolver is `reached`; one that could not tell is `inconclusive`). A certification `/run` also writes `probe-targets.json` (the resolvers and metadata endpoints only root init knows), root-owned 0444 like the other two.
+- `internal/hostedctl/ctlcert/report.go`: `AcceptReport` in the proxy route's transaction, in order: unknown serial; signature by the serial's own key (`proxy_certs.public_key`, ECDSA P-256 ASN.1 over SHA-256 of `CertReportMessage`); a report already in (`already_reported`, so a VM retrying after a lost answer learns it); revoked or expired serial; launch not live for that VM and epoch; not a certification launch; strict `Report` and `Check` (400); report naming another launch; provider settings changed since the launch (the stored fingerprint must equal the current one, so the image version is the one the VM ran). Evidence fields other than the report come from the jobs row (image and size from `spec_json`, deployment from `services_json`), the provider version, `hostedwire.ProxyPolicyVersion` and controller time; signed with the controller's key; kept in `cert_evidence` (schema version 5, `0005_cert_report.sql`; rows immutable; launch and attempt unique). `CheckProxyHeaders`: a proxy request with any header but the signature and transport headers is 400 `identity_header`. `LoadEvidence`; `Set.ImageVersion`.
+- `internal/hostedctl` (wiring, budget raised to 6022/9907 with the reason): `POST /v1/proxy/cert-report` (accept, then the controller's own stop, `certification_reported`, which revokes the serials; an unproven stop is the reaper's), `GET /v1/cert/evidence/{launch}` (operator), the header check on every proxy route, codes `identity_header` (400) and `already_reported` (403), the Handler's signing key kept for evidence. `ctlproxy.issue` records each certificate's public key.
+- `internal/hostedclient`: `NewOperator` (no `EQUIPO_HOSTED_RUNNERS`), `CertLaunch`, `Evidence`, `Certs`, `Reload`, `AlertTest`; the two new codes in `refusals`.
+- `internal/runner/hosted/certify.go`: `ReuseProxyCode`, `InstanceProtocol`, `SendReport` (signs with the current certificate's key; 200 or `already_reported` count as taken), `Proxies`, `LaunchID`. `cmd/equipo-runner`: `hosted-certify` now runs `certify` after Start (Linux: the user probes, the sandbox probes in the containment manager's namespace under `BuildCheckPolicy` with a copy of the runner in the workspace, the containment suite at `/usr/local/libexec/equipo/containment.test`) and exits 0 once the report is taken; `hosted-run` still refuses `not_wired`.
+- `proxytest.CertReport` now builds a real `hostedcert.Report`, so the fake and the real controller read the same body; `ctlcert`'s tests use `proxytest.ReportBody` and `proxytest.CSR`.
+- `cmd/equipo-hosted-certify` (new): `launch` (journals `INTENT cert-launch <image> <size> <launch-by> <attempt>` in `-ledger/journal.tsv` before the call; a rerun reuses the journaled launch-by, so the attempt ID is the same; waits for the evidence), `judge -evidence -release -controller-pub [-out snapshot.json]`, `sign ... -key -key-id [-out]` (no snapshot flag exists), `verify -cert -cert-keys`, `reload`, `alert-test`. `img publish -ledger -base-version` already existed (Task 10).
+- Decisions to confirm:
+ - The probe outcome vocabulary and `OK` being ignored; vm-init's `Outcome` and `probe-targets.json` are additions to Task 8's output.
+ - `hostedwire.ProxyPolicyVersion = 1` is a constant (no proxy policy version existed); raise it when `hostedproxy.Decide`'s rules change.
+ - The evidence is signed with the controller's response signing key (domain-separated), so `-controller-pub` is the key operators already pin.
+ - The real sandbox runner is the containment namespace with the check policy (as thin Linux checks run), without the Codex inner layer; Task 17's gate may differ. It and the containment suite run only in a real VM (Task 34).
+ - Report refusals other than `already_reported` answer `proxy_refused` alike (as ctlproxy does), with the reason in the audit row; the fake controller keeps its own finer codes.
+
+Red:
+- hostedcert: tests written against stubs (`Judge`, `CheckMeasured`, `Certify` returning nil; `OpenEvidence` not verifying): `go test ./internal/hostedcert -count=1` FAIL `TestJudgeUsesTrustedMatrix`, `TestJudgeNeedsEveryProbe`, `TestJudgeNeedsPositiveControls`, `TestEvidenceSignatureChecked`, `TestEvidenceFromSubstitutedControllerKeyRefused`, `TestSignRefusesMeasuredMismatch`; e.g. `judge_test.go:102: root_vpc_dns_silent reached claiming OK: Judge = <nil>, want ErrNotCertified naming "root_vpc_dns_silent"`.
+- ctlcert: `report_test.go` with the route not wired: `go test ./internal/hostedctl/ctlcert -run 'TestReport|TestEvidence' -count=1` FAIL all three; e.g. `report_test.go:319: right serial, another VM's key = 404 no_route, want 403 proxy_refused`.
+- The command's tests were written with `main.go`; mutations 99, 105 and 107 show them failing on their assertions.
+
+Green:
+- `go test ./internal/hostedcert ./internal/hostedctl/... ./cmd/equipo-hosted-certify -run 'TestJudge|TestEvidence|TestReportOnce|TestReportNeedsVMKeySignature|TestSign' -count=1`: ok.
+- `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedproxy/... ./internal/runner/hosted ./cmd/equipo-hosted-certify ./cmd/equipo-runner -count=1`: ok; also `./internal/vminit ./internal/hostedclient ./internal/hostedwire ./internal/hostedimage ./cmd/equipo-hosted-controller ./internal/isolatedjob`: ok.
+- `make budget build vet`: ok (138 directories within budget). staticcheck v0.7.0 on the changed packages and gofmt: clean.
+
+Mutation checks. Each was applied by a script that replaced one exact, unique string, ran the `go test` shown with `-count=1`, and restored the file from a copy (checked byte-equal after every one). Every run compiled and failed on an assertion. Output is cut.
+
+97. The evidence takes the image from the report (the brief's mutation): `Image: image` in `AcceptReport`'s `Evidence` became the report's `Measured["image"]` when present.
+ - `go test ./internal/hostedctl/ctlcert -run TestEvidenceFromLaunchRecord`
+ - FAIL: `report_test.go:462: evidence = {... "image":"sha256:bbbb..." ...} want {... "image":"sha256:aaaa..." ...}`. Restored.
+98. `Certify` skips the measured-digest comparison (the brief's mutation): the `CheckMeasured` call removed.
+ - `go test ./internal/hostedcert -run TestSignRefusesMeasuredMismatch`
+ - FAIL: `judge_test.go:250: measured runner differs: Judge = <nil>, want ErrNotCertified naming "runner"` (and vm_init, sandbox_policy). Restored.
+99. The same, through the command.
+ - `go test ./cmd/equipo-hosted-certify -run TestSignRefusesMeasuredMismatch`
+ - FAIL: `main_test.go:217: sign = 0 , want refused naming the runner` and `main_test.go:220: sign wrote a certificate for a mismatched runner`. Restored.
+100. `Judge` skips one positive control (the brief's mutation): `continue` for `sandbox_go_tree_read`.
+ - `go test ./internal/hostedcert -run TestJudgeNeedsPositiveControls`
+ - FAIL: `judge_test.go:147: control sandbox_go_tree_read blocked: Judge = <nil>, want ErrNotCertified naming "sandbox_go_tree_read"`. Restored.
+101. The report's signature is not checked (`!signedBy(c.key, q) && false`).
+ - `go test ./internal/hostedctl/ctlcert -run TestReportNeedsVMKeySignature`
+ - FAIL: `report_test.go:319: right serial, another VM's key = 200 , want 403 proxy_refused`, `report_test.go:349: refused reports left 1 evidence rows`. Restored.
+102. Proxy headers are not checked (`... && false` in `CheckProxyHeaders`).
+ - `go test ./internal/hostedctl/ctlcert -run TestReportNeedsVMKeySignature`
+ - FAIL: `report_test.go:330: a report with header map[X-Equipo-Launch:[...]] = 200 , want 400 identity_header`. Restored.
+103. A second report is not refused (the `ErrAlreadyReported` check removed).
+ - `go test ./internal/hostedctl/ctlcert -run TestReportOncePerLaunch`
+ - FAIL: `report_test.go:386: a second report = 403 proxy_refused, want 403 already_reported` and `report_test.go:423: second AcceptReport = ctlcert: keep evidence: ... UNIQUE constraint failed: cert_evidence.attempt_id ..., want ErrAlreadyReported` (the table's key still held). Restored.
+104. A revoked serial is accepted (`revoked.Valid && false`).
+ - `go test ./internal/hostedctl/ctlcert -run TestReportNeedsVMKeySignature`
+ - FAIL: `report_test.go:340: a revoked serial = 200 , want 403 proxy_refused`. Restored.
+105. `OpenEvidence` does not verify the signature (the `ed25519.Verify` term removed).
+ - `go test ./cmd/equipo-hosted-certify -run TestEvidenceFromSubstitutedControllerKeyRefused`
+ - FAIL: `main_test.go:181: judge of evidence signed by another key = 0 , want refused`. Restored.
+106. `Judge` trusts the VM's `OK` (`case !found[0].OK:` for `case found[0].Outcome != e.Want:`).
+ - `go test ./internal/hostedcert -run TestJudgeUsesTrustedMatrix`
+ - FAIL: `judge_test.go:102: root_vpc_dns_silent reached claiming OK: Judge = <nil>, want ErrNotCertified naming "root_vpc_dns_silent"`. Restored.
+107. `launch` journals after the launch call (the journal write moved below `CertLaunch`).
+ - `go test ./cmd/equipo-hosted-certify -run TestLaunchJournalsBeforeCreate`
+ - FAIL: `main_test.go:352: the journal when the launch arrived = [""], want the intent naming cert-82bb...`. Restored.
+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.
diff --git a/internal/hostedcert/evidence.go b/internal/hostedcert/evidence.go
new file mode 100644
index 00000000..53e88a87
--- /dev/null
+++ b/internal/hostedcert/evidence.go
@@ -0,0 +1,240 @@
+package hostedcert
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// A certification run (plan Task 13) produces a Report inside the VM,
+// signed with the VM's proxy certificate key and sent through a proxy to
+// the controller. The controller wraps it in Evidence, every field but the
+// report from its own launch record and config, and signs that with its
+// own key. The offline signer judges only controller-signed evidence
+// (judge.go), checked against a controller key supplied separately.
+
+// The stages a probe runs at.
+const (
+ StageRoot = "root" // vm-init as root, before the runner starts (root.json)
+ StageUser = "user" // the runner, as the runner user
+ StageSandbox = "sandbox" // inside the checks sandbox
+)
+
+// What a probe's attempt did. Each probe makes one attempt (a connection,
+// a write, a request, a read) and reports what happened to it; whether
+// that was the expected outcome is for Matrix to say, never the VM.
+const (
+ OutcomeBlocked = "blocked" // refused, unanswered, or found nothing
+ OutcomeReached = "reached" // it got through or worked
+ OutcomeInconclusive = "inconclusive" // the probe could not tell
+)
+
+// The names in measured.json (vminit's MeasuredRunner, MeasuredVMInit and
+// MeasuredSandboxPolicy; a test holds them equal) that a certificate
+// records.
+const (
+ MeasuredRunner = "runner"
+ MeasuredVMInit = "vm_init"
+ MeasuredSandboxPolicy = "sandbox_policy"
+)
+
+// ProbeResult is one probe's result, as vm-init writes root.json and the
+// runner writes the rest. OK is the VM's own verdict, kept for people
+// reading the report; Judge never reads it.
+type ProbeResult struct {
+ Name string `json:"name"`
+ Stage string `json:"stage"`
+ OK bool `json:"ok"`
+ Outcome string `json:"outcome"`
+ Detail string `json:"detail"`
+}
+
+// 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.
+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"`
+}
+
+// Report is what a certification VM reports.
+type Report struct {
+ LaunchID string `json:"launch_id"`
+ Root []ProbeResult `json:"root"`
+ User []ProbeResult `json:"user"`
+ Sandbox []ProbeResult `json:"sandbox"`
+ Measured map[string]string `json:"measured"`
+ Containment ContainmentResult `json:"containment"`
+}
+
+// Bounds of a report: it travels inside one controller request body.
+const (
+ maxProbes = 64
+ maxProbeDetail = 2048
+ maxMeasured = 128
+)
+
+// ErrReport is a report that breaks a bound or a form rule.
+var ErrReport = errors.New("hostedcert: the certification report is not valid")
+
+// Check holds r to its form: a launch ID, at most 64 results per stage,
+// each with a name, a known stage and outcome and a bounded detail, and
+// at most 128 measured names, each with a value.
+func (r Report) Check() error {
+ bad := func(format string, a ...any) error {
+ return fmt.Errorf("%w: "+format, append([]any{ErrReport}, a...)...)
+ }
+ if !text(r.LaunchID) {
+ return bad("launch ID must be 1 to %d printable ASCII characters", maxText)
+ }
+ for _, list := range [][]ProbeResult{r.Root, r.User, r.Sandbox} {
+ if len(list) > maxProbes {
+ return bad("more than %d results in one stage", maxProbes)
+ }
+ for _, p := range list {
+ switch {
+ case !text(p.Name):
+ return bad("a probe has no printable name")
+ case p.Stage != StageRoot && p.Stage != StageUser && p.Stage != StageSandbox:
+ return bad("probe %q has stage %q", p.Name, p.Stage)
+ case p.Outcome != OutcomeBlocked && p.Outcome != OutcomeReached && p.Outcome != OutcomeInconclusive:
+ return bad("probe %q has outcome %q", p.Name, p.Outcome)
+ case len(p.Detail) > maxProbeDetail:
+ return bad("probe %q has a detail over %d bytes", p.Name, maxProbeDetail)
+ }
+ }
+ }
+ if len(r.Measured) > maxMeasured {
+ return bad("more than %d measured names", maxMeasured)
+ }
+ for k, v := range r.Measured {
+ if !text(k) || !text(v) {
+ return bad("measured name %q or its value is not printable", k)
+ }
+ }
+ c := r.Containment
+ if len(c.Args) > 16 || len(c.Detail) > maxProbeDetail || len(c.Binary) > maxText {
+ return bad("the containment result is over its bounds")
+ }
+ return nil
+}
+
+// Evidence is the controller's record of one certification report. Every
+// field but Report comes from the controller's own launch record and
+// config; nothing the VM sent can change them.
+type Evidence struct {
+ EvidenceID string `json:"evidence_id"`
+ LaunchID string `json:"launch_id"`
+ Image isolatedjob.ImageDigest `json:"image"`
+ ImageVersion string `json:"image_version"`
+ ProxyPolicy int `json:"proxy_policy"`
+ Deployment []string `json:"deployment"`
+ Report Report `json:"report"`
+ ReceivedNS int64 `json:"received_ns"` // controller time
+}
+
+// SignedEvidence is evidence as the controller signed it: Evidence holds
+// the exact JSON bytes signed, so a verifier reads every field from the
+// signed bytes and nothing re-encoded.
+type SignedEvidence struct {
+ Evidence []byte `json:"evidence"`
+ Sig []byte `json:"sig"`
+}
+
+var (
+ // ErrEvidenceSignature: the evidence is not signed by the controller
+ // key the verifier was given.
+ ErrEvidenceSignature = errors.New("hostedcert: the evidence is not signed by the given controller key")
+ // ErrEvidence: signed evidence that does not decode or check.
+ ErrEvidence = errors.New("hostedcert: the evidence is not valid")
+)
+
+// evidenceMessage is what SignedEvidence.Sig signs: a label, then the
+// evidence bytes, each length-prefixed, so it can never pass for a
+// response signature (hostedwire) or a certificate's.
+func evidenceMessage(raw []byte) []byte {
+ return appendField(appendField(nil, "equipo-hosted-cert-evidence v1"), string(raw))
+}
+
+// SignEvidence signs e with the controller's key k.
+func SignEvidence(e Evidence, k ed25519.PrivateKey) (SignedEvidence, error) {
+ if len(k) != ed25519.PrivateKeySize {
+ return SignedEvidence{}, errors.New("hostedcert: the controller key has the wrong length")
+ }
+ e.Deployment = slices.Clone(e.Deployment)
+ raw, err := json.Marshal(e)
+ if err != nil {
+ return SignedEvidence{}, fmt.Errorf("hostedcert: encode evidence: %w", err)
+ }
+ return SignedEvidence{Evidence: raw, Sig: ed25519.Sign(k, evidenceMessage(raw))}, nil
+}
+
+// OpenEvidence verifies se under controller, the controller's public key
+// as the caller holds it (never a key read from the evidence), then
+// decodes the signed bytes strictly and checks the evidence's form.
+func OpenEvidence(se SignedEvidence, controller ed25519.PublicKey) (Evidence, error) {
+ if len(controller) != ed25519.PublicKeySize || !ed25519.Verify(controller, evidenceMessage(se.Evidence), se.Sig) {
+ return Evidence{}, ErrEvidenceSignature
+ }
+ var e Evidence
+ if err := decodeStrict(se.Evidence, &e); err != nil {
+ return Evidence{}, fmt.Errorf("%w: %v", ErrEvidence, err)
+ }
+ img, isSHA := cutSHA(string(e.Image))
+ switch {
+ case !text(e.EvidenceID) || !text(e.LaunchID) || !text(e.ImageVersion):
+ return Evidence{}, fmt.Errorf("%w: evidence, launch and image version must be printable", ErrEvidence)
+ case !isSHA || !sha256Hex(img):
+ return Evidence{}, fmt.Errorf("%w: image is not sha256: and 64 lower-case hex digits", ErrEvidence)
+ case e.Report.LaunchID != e.LaunchID:
+ return Evidence{}, fmt.Errorf("%w: the report names launch %q, the evidence %q", ErrEvidence, e.Report.LaunchID, e.LaunchID)
+ }
+ if err := e.Report.Check(); err != nil {
+ return Evidence{}, fmt.Errorf("%w: %v", ErrEvidence, err)
+ }
+ return e, nil
+}
+
+// ReadSignedEvidence reads a signed evidence file: one JSON object with
+// exactly the fields of SignedEvidence.
+func ReadSignedEvidence(raw []byte) (SignedEvidence, error) {
+ var se SignedEvidence
+ if err := decodeStrict(raw, &se); err != nil {
+ return SignedEvidence{}, fmt.Errorf("%w: %v", ErrEvidence, err)
+ }
+ return se, nil
+}
+
+// decodeStrict decodes exactly one JSON value into v, refusing fields v
+// does not have and anything after the value.
+func decodeStrict(raw []byte, v any) error {
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(v); err != nil {
+ return err
+ }
+ if _, err := dec.Token(); err != io.EOF {
+ return errors.New("more than one JSON value")
+ }
+ return nil
+}
+
+func cutSHA(s string) (string, bool) {
+ const p = "sha256:"
+ if len(s) < len(p) || s[:len(p)] != p {
+ return "", false
+ }
+ return s[len(p):], true
+}
diff --git a/internal/hostedcert/judge.go b/internal/hostedcert/judge.go
new file mode 100644
index 00000000..927c397d
--- /dev/null
+++ b/internal/hostedcert/judge.go
@@ -0,0 +1,139 @@
+package hostedcert
+
+import (
+ "crypto/ed25519"
+ "errors"
+ "fmt"
+ "slices"
+)
+
+// ErrNotCertified: the evidence does not certify the image. Every reason
+// found is joined to it.
+var ErrNotCertified = errors.New("hostedcert: the evidence does not certify the image")
+
+// Judge holds r to the matrix m: every expectation's probe appears once,
+// in its stage's list, with its stage and the outcome m wants; no probe m
+// does not know appears; and the containment suite ran with
+// ContainmentArgs and passed in full. A result's own OK is never read: a
+// report that calls a probe a success decides nothing. It returns nil or
+// ErrNotCertified joined to every failure.
+func Judge(r Report, m []Expectation) error {
+ var errs []error
+ fail := func(format string, a ...any) { errs = append(errs, fmt.Errorf(format, a...)) }
+ lists := map[string][]ProbeResult{StageRoot: r.Root, StageUser: r.User, StageSandbox: r.Sandbox}
+ known := map[string]bool{}
+ for _, e := range m {
+ known[e.Stage+"/"+e.Name] = true
+ var found []ProbeResult
+ for _, p := range lists[e.Stage] {
+ if p.Name == e.Name {
+ found = append(found, p)
+ }
+ }
+ kind := "probe"
+ if e.Control {
+ kind = "positive control"
+ }
+ switch {
+ case len(found) == 0:
+ fail("%s %s (%s) is missing", kind, e.Name, e.Stage)
+ case len(found) > 1:
+ fail("%s %s (%s) appears %d times", kind, e.Name, e.Stage, len(found))
+ case found[0].Stage != e.Stage:
+ fail("%s %s is in the %s list but says stage %q", kind, e.Name, e.Stage, found[0].Stage)
+ case found[0].Outcome != e.Want:
+ fail("%s %s (%s) was %s, the matrix wants %s", kind, e.Name, e.Stage, found[0].Outcome, e.Want)
+ }
+ }
+ for _, stage := range []string{StageRoot, StageUser, StageSandbox} {
+ for _, p := range lists[stage] {
+ if !known[stage+"/"+p.Name] {
+ fail("probe %s (%s) is not in the matrix", p.Name, stage)
+ }
+ }
+ }
+ 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")
+ }
+ if len(errs) == 0 {
+ return nil
+ }
+ return errors.Join(append([]error{ErrNotCertified}, 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.
+type Release struct {
+ Measured map[string]string
+ ContainmentTest string
+}
+
+// CheckMeasured holds measured to the release: the runner, vm-init and
+// sandbox policy digests must each be 64 lower-case hex digits and equal
+// the release's.
+func CheckMeasured(measured map[string]string, rel Release) error {
+ var errs []error
+ for _, k := range []string{MeasuredRunner, MeasuredVMInit, MeasuredSandboxPolicy} {
+ got, want := measured[k], rel.Measured[k]
+ switch {
+ case !sha256Hex(want):
+ errs = append(errs, fmt.Errorf("the release has no digest for %s", k))
+ case got != want:
+ errs = append(errs, fmt.Errorf("measured %s is %q, the release pins %q", k, got, want))
+ }
+ }
+ if len(errs) == 0 {
+ return nil
+ }
+ return errors.Join(append([]error{ErrNotCertified}, errs...)...)
+}
+
+// Derive is the snapshot the evidence certifies, from the evidence alone:
+// the image, version, proxy policy and deployment the controller recorded,
+// and the digests vm-init measured.
+func Derive(e Evidence) Snapshot {
+ return Snapshot{
+ Purpose: Purpose, Version: Version, Image: e.Image, ImageVersion: e.ImageVersion,
+ Runner: e.Report.Measured[MeasuredRunner], VMInit: e.Report.Measured[MeasuredVMInit],
+ SandboxPolicy: e.Report.Measured[MeasuredSandboxPolicy], ProxyPolicy: e.ProxyPolicy,
+ Deps: DepsPrimaryBundleV1, Deployment: slices.Clone(e.Deployment), Profile: ProfileVMBoundaryChecks,
+ EvidenceID: e.EvidenceID,
+ }
+}
+
+// Certify is the whole judgement: se must verify under controller (the
+// controller's public key as the caller holds it); the measured digests
+// must be the release's; the containment suite that ran must be the
+// release's; the report must pass Judge against Matrix; and the snapshot
+// derived from the evidence must keep the version 1 rules. It returns
+// that snapshot.
+func Certify(se SignedEvidence, controller ed25519.PublicKey, rel Release) (Snapshot, error) {
+ e, err := OpenEvidence(se, controller)
+ if err != nil {
+ return Snapshot{}, err
+ }
+ if err := CheckMeasured(e.Report.Measured, rel); err != nil {
+ return Snapshot{}, err
+ }
+ if !sha256Hex(rel.ContainmentTest) || e.Report.Containment.Binary != rel.ContainmentTest {
+ return Snapshot{}, fmt.Errorf("%w: the containment suite that ran (%q) is not the release's (%q)",
+ ErrNotCertified, e.Report.Containment.Binary, rel.ContainmentTest)
+ }
+ if err := Judge(e.Report, Matrix()); err != nil {
+ return Snapshot{}, err
+ }
+ s := Derive(e)
+ if err := check(s); err != nil {
+ return Snapshot{}, fmt.Errorf("%w: %v", ErrNotCertified, err)
+ }
+ return s, nil
+}
diff --git a/internal/hostedcert/judge_test.go b/internal/hostedcert/judge_test.go
new file mode 100644
index 00000000..9e26970b
--- /dev/null
+++ b/internal/hostedcert/judge_test.go
@@ -0,0 +1,281 @@
+package hostedcert_test
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+var (
+ ctlKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x41}, ed25519.SeedSize))
+ otherKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x42}, ed25519.SeedSize))
+ ctlPub = ctlKey.Public().(ed25519.PublicKey)
+ image = isolatedjob.ImageDigest("sha256:" + strings.Repeat("e", 64))
+ release = hostedcert.Release{
+ Measured: map[string]string{hostedcert.MeasuredRunner: strings.Repeat("1", 64), hostedcert.MeasuredVMInit: strings.Repeat("2", 64),
+ hostedcert.MeasuredSandboxPolicy: strings.Repeat("3", 64)},
+ ContainmentTest: strings.Repeat("4", 64),
+ }
+)
+
+// passing is a report that passes the matrix for launch: every probe at
+// its matrix outcome, the measured digests the release's, the containment
+// suite the release's and passing in full.
+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}}
+ for k, v := range release.Measured {
+ r.Measured[k] = v
+ }
+ for _, e := range hostedcert.Matrix() {
+ p := hostedcert.ProbeResult{Name: e.Name, Stage: e.Stage, OK: true, Outcome: e.Want, Detail: "as wanted"}
+ switch e.Stage {
+ case hostedcert.StageRoot:
+ r.Root = append(r.Root, p)
+ case hostedcert.StageUser:
+ r.User = append(r.User, p)
+ default:
+ r.Sandbox = append(r.Sandbox, p)
+ }
+ }
+ return r
+}
+
+func evidence(r hostedcert.Report) hostedcert.Evidence {
+ return hostedcert.Evidence{EvidenceID: "ev-1", LaunchID: r.LaunchID, Image: image,
+ ImageVersion: "arn:aws:lambda:eu-west-1:123456789012:microvm-image:equipo-hosted:3", ProxyPolicy: 1,
+ Deployment: []string{"equipo.example.com"}, Report: r, ReceivedNS: 42}
+}
+
+func signed(t *testing.T, e hostedcert.Evidence, k ed25519.PrivateKey) hostedcert.SignedEvidence {
+ t.Helper()
+ se, err := hostedcert.SignEvidence(e, k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return se
+}
+
+// edit returns the probe list of stage in r with fn applied to probe name.
+func edit(r hostedcert.Report, name string, fn func(*hostedcert.ProbeResult)) hostedcert.Report {
+ for _, list := range [][]hostedcert.ProbeResult{r.Root, r.User, r.Sandbox} {
+ for i := range list {
+ if list[i].Name == name {
+ fn(&list[i])
+ }
+ }
+ }
+ return r
+}
+
+func wantNotCertified(t *testing.T, what string, err error, naming string) {
+ t.Helper()
+ if !errors.Is(err, hostedcert.ErrNotCertified) || !strings.Contains(err.Error(), naming) {
+ t.Errorf("%s: Judge = %v, want ErrNotCertified naming %q", what, err, naming)
+ }
+}
+
+// TestJudgeUsesTrustedMatrix: the outcome each probe must have is the
+// matrix's. A report that calls a probe a success (OK) when its attempt
+// got through still fails, as does one whose attempt could not tell; a
+// probe moved to another stage's list fails too.
+func TestJudgeUsesTrustedMatrix(t *testing.T) {
+ if err := hostedcert.Judge(passing("l-1"), hostedcert.Matrix()); err != nil {
+ t.Fatalf("a passing report: Judge = %v", err)
+ }
+ for _, e := range hostedcert.Matrix() {
+ other := hostedcert.OutcomeReached
+ if e.Want == hostedcert.OutcomeReached {
+ other = hostedcert.OutcomeBlocked
+ }
+ for _, outcome := range []string{other, hostedcert.OutcomeInconclusive} {
+ r := edit(passing("l-1"), e.Name, func(p *hostedcert.ProbeResult) { p.Outcome, p.OK = outcome, true })
+ wantNotCertified(t, e.Name+" "+outcome+" claiming OK", hostedcert.Judge(r, hostedcert.Matrix()), e.Name)
+ }
+ }
+ // The report's own stage field decides nothing either.
+ r := edit(passing("l-1"), hostedcert.ProbeSandboxIPv4, func(p *hostedcert.ProbeResult) { p.Stage = hostedcert.StageRoot })
+ wantNotCertified(t, "a sandbox probe saying stage root", hostedcert.Judge(r, hostedcert.Matrix()), hostedcert.ProbeSandboxIPv4)
+ r = passing("l-1")
+ i := slices.IndexFunc(r.Sandbox, func(p hostedcert.ProbeResult) bool { return p.Name == hostedcert.ProbeSandboxIPv4 })
+ r.User = append(r.User, r.Sandbox[i])
+ r.Sandbox = slices.Delete(r.Sandbox, i, i+1)
+ wantNotCertified(t, "a sandbox probe in the user list", hostedcert.Judge(r, hostedcert.Matrix()), hostedcert.ProbeSandboxIPv4)
+}
+
+// TestJudgeNeedsEveryProbe: a report missing any probe of the matrix, or
+// holding one twice, or one the matrix does not know, fails.
+func TestJudgeNeedsEveryProbe(t *testing.T) {
+ for _, e := range hostedcert.Matrix() {
+ r := passing("l-1")
+ r.Root = slices.DeleteFunc(r.Root, func(p hostedcert.ProbeResult) bool { return p.Name == e.Name })
+ r.User = slices.DeleteFunc(r.User, func(p hostedcert.ProbeResult) bool { return p.Name == e.Name })
+ r.Sandbox = slices.DeleteFunc(r.Sandbox, func(p hostedcert.ProbeResult) bool { return p.Name == e.Name })
+ wantNotCertified(t, "without "+e.Name, hostedcert.Judge(r, hostedcert.Matrix()), e.Name)
+ }
+ r := passing("l-1")
+ r.Sandbox = append(r.Sandbox, r.Sandbox[0])
+ wantNotCertified(t, "a probe twice", hostedcert.Judge(r, hostedcert.Matrix()), r.Sandbox[0].Name)
+ r = passing("l-1")
+ r.User = append(r.User, hostedcert.ProbeResult{Name: "user_extra", Stage: hostedcert.StageUser, Outcome: hostedcert.OutcomeBlocked})
+ wantNotCertified(t, "an unknown probe", hostedcert.Judge(r, hostedcert.Matrix()), "user_extra")
+ empty := hostedcert.Report{LaunchID: "l-1", Containment: passing("l-1").Containment}
+ if err := hostedcert.Judge(empty, hostedcert.Matrix()); err == nil {
+ t.Error("a report with no probes passed")
+ }
+}
+
+// TestJudgeNeedsPositiveControls: a VM whose network is simply dead
+// blocks every negative probe; the positive controls fail it. Each
+// control blocked fails, and so does every way the containment suite can
+// fall short of passing in full.
+func TestJudgeNeedsPositiveControls(t *testing.T) {
+ for _, e := range hostedcert.Matrix() {
+ if !e.Control {
+ continue
+ }
+ r := edit(passing("l-1"), e.Name, func(p *hostedcert.ProbeResult) { p.Outcome = hostedcert.OutcomeBlocked })
+ 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 },
+ } {
+ r := passing("l-1")
+ fn(&r.Containment)
+ wantNotCertified(t, "containment "+what, hostedcert.Judge(r, hostedcert.Matrix()), "containment suite")
+ }
+}
+
+// TestEvidenceSignatureChecked: evidence opens only with its signature
+// intact over the exact bytes signed, and only when those bytes are
+// strict evidence.
+func TestEvidenceSignatureChecked(t *testing.T) {
+ se := signed(t, evidence(passing("l-1")), ctlKey)
+ e, err := hostedcert.OpenEvidence(se, ctlPub)
+ if err != nil || e.LaunchID != "l-1" || e.Image != image {
+ t.Fatalf("OpenEvidence = %+v, %v", e, err)
+ }
+ tampered := se
+ tampered.Evidence = bytes.Replace(bytes.Clone(se.Evidence), []byte(`"proxy_policy":1`), []byte(`"proxy_policy":2`), 1)
+ if bytes.Equal(tampered.Evidence, se.Evidence) {
+ t.Fatal("the test did not change the evidence")
+ }
+ if _, err := hostedcert.OpenEvidence(tampered, ctlPub); !errors.Is(err, hostedcert.ErrEvidenceSignature) {
+ t.Errorf("edited evidence: OpenEvidence = %v, want ErrEvidenceSignature", err)
+ }
+ badSig := se
+ badSig.Sig = bytes.Clone(se.Sig)
+ badSig.Sig[0] ^= 1
+ if _, err := hostedcert.OpenEvidence(badSig, ctlPub); !errors.Is(err, hostedcert.ErrEvidenceSignature) {
+ t.Errorf("edited signature: OpenEvidence = %v, want ErrEvidenceSignature", err)
+ }
+ // Well signed, but not strict evidence: an unknown field, or a report
+ // naming another launch.
+ var raw map[string]any
+ _ = json.Unmarshal(se.Evidence, &raw)
+ raw["controller_key"] = "attacker"
+ extra, _ := json.Marshal(raw)
+ if _, err := hostedcert.OpenEvidence(hostedcert.SignedEvidence{Evidence: extra, Sig: ed25519.Sign(ctlKey, message(extra))}, ctlPub); !errors.Is(err, hostedcert.ErrEvidence) {
+ t.Errorf("an unknown field: OpenEvidence = %v, want ErrEvidence", err)
+ }
+ mixed := evidence(passing("l-2"))
+ mixed.LaunchID = "l-1"
+ if _, err := hostedcert.OpenEvidence(signed(t, mixed, ctlKey), ctlPub); !errors.Is(err, hostedcert.ErrEvidence) {
+ t.Errorf("a report for another launch: OpenEvidence = %v, want ErrEvidence", err)
+ }
+ // The file form reads strictly too.
+ file, _ := json.Marshal(se)
+ if back, err := hostedcert.ReadSignedEvidence(file); err != nil || !bytes.Equal(back.Evidence, se.Evidence) {
+ t.Errorf("ReadSignedEvidence = %v", err)
+ }
+ if _, err := hostedcert.ReadSignedEvidence(append(bytes.Clone(file), []byte(` {}`)...)); err == nil {
+ t.Error("ReadSignedEvidence took two values")
+ }
+}
+
+// message is the evidence signature's message, written out here so the
+// test signs exactly what a controller would.
+func message(raw []byte) []byte {
+ label := "equipo-hosted-cert-evidence v1"
+ b := append([]byte{byte(len(label))}, label...)
+ return append(appendUvarint(b, len(raw)), raw...)
+}
+
+func appendUvarint(b []byte, n int) []byte {
+ for n >= 0x80 {
+ b = append(b, byte(n)|0x80)
+ n >>= 7
+ }
+ return append(b, byte(n))
+}
+
+// TestEvidenceFromSubstitutedControllerKeyRefused: evidence signed by any
+// key but the controller's, which the verifier holds on its own, is
+// refused, however well formed; so is a verifier given no key.
+func TestEvidenceFromSubstitutedControllerKeyRefused(t *testing.T) {
+ forged := signed(t, evidence(passing("l-1")), otherKey)
+ if _, err := hostedcert.OpenEvidence(forged, ctlPub); !errors.Is(err, hostedcert.ErrEvidenceSignature) {
+ t.Errorf("evidence signed by another key: OpenEvidence = %v, want ErrEvidenceSignature", err)
+ }
+ if _, err := hostedcert.Certify(forged, ctlPub, release); !errors.Is(err, hostedcert.ErrEvidenceSignature) {
+ t.Errorf("evidence signed by another key: Certify = %v, want ErrEvidenceSignature", err)
+ }
+ if _, err := hostedcert.OpenEvidence(signed(t, evidence(passing("l-1")), ctlKey), nil); !errors.Is(err, hostedcert.ErrEvidenceSignature) {
+ t.Errorf("no controller key: OpenEvidence = %v, want ErrEvidenceSignature", err)
+ }
+}
+
+// TestSignRefusesMeasuredMismatch: evidence whose measured runner, vm-init
+// or policy digest differs from the release's, or whose containment suite
+// is not the release's, does not certify.
+func TestSignRefusesMeasuredMismatch(t *testing.T) {
+ for _, k := range []string{hostedcert.MeasuredRunner, hostedcert.MeasuredVMInit, hostedcert.MeasuredSandboxPolicy} {
+ r := passing("l-1")
+ r.Measured[k] = strings.Repeat("9", 64)
+ _, err := hostedcert.Certify(signed(t, evidence(r), ctlKey), ctlPub, release)
+ wantNotCertified(t, "measured "+k+" differs", err, k)
+ r = passing("l-1")
+ delete(r.Measured, k)
+ _, err = hostedcert.Certify(signed(t, evidence(r), ctlKey), ctlPub, release)
+ wantNotCertified(t, "measured "+k+" missing", err, k)
+ }
+ r := passing("l-1")
+ r.Containment.Binary = strings.Repeat("8", 64)
+ _, err := hostedcert.Certify(signed(t, evidence(r), ctlKey), ctlPub, release)
+ wantNotCertified(t, "another containment suite", err, "containment suite")
+}
+
+// TestCertifyDerivesFromEvidence: the snapshot is the evidence's, field
+// by field, and keeps the version 1 rules.
+func TestCertifyDerivesFromEvidence(t *testing.T) {
+ e := evidence(passing("l-1"))
+ s, err := hostedcert.Certify(signed(t, e, ctlKey), ctlPub, release)
+ if err != nil {
+ t.Fatalf("Certify = %v", err)
+ }
+ want := hostedcert.Snapshot{Purpose: hostedcert.Purpose, Version: hostedcert.Version, Image: e.Image, ImageVersion: e.ImageVersion,
+ Runner: release.Measured[hostedcert.MeasuredRunner], VMInit: release.Measured[hostedcert.MeasuredVMInit],
+ SandboxPolicy: release.Measured[hostedcert.MeasuredSandboxPolicy], ProxyPolicy: e.ProxyPolicy,
+ Deps: hostedcert.DepsPrimaryBundleV1, Deployment: e.Deployment, Profile: hostedcert.ProfileVMBoundaryChecks, EvidenceID: e.EvidenceID}
+ if string(hostedcert.Canonical(s)) != string(hostedcert.Canonical(want)) {
+ t.Errorf("Certify = %+v, want %+v", s, want)
+ }
+ cert := hostedcert.Sign(s, "paul-1", otherKey, time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC))
+ if _, err := hostedcert.Verify(cert, map[string]ed25519.PublicKey{"paul-1": otherKey.Public().(ed25519.PublicKey)}); err != nil {
+ t.Errorf("the derived snapshot does not verify once signed: %v", err)
+ }
+}
diff --git a/internal/hostedcert/matrix.go b/internal/hostedcert/matrix.go
new file mode 100644
index 00000000..72b9669b
--- /dev/null
+++ b/internal/hostedcert/matrix.go
@@ -0,0 +1,87 @@
+package hostedcert
+
+import "slices"
+
+// The probes, by stage. The root probes are vm-init's (vminit.Probe*; a
+// test holds the names equal).
+const (
+ // Root, before the drop.
+ ProbeRootVPCDNS = "root_vpc_dns_silent" // a DNS query to each managed resolver
+ ProbeRootMetadata = "root_metadata_no_credential" // a credential from each metadata endpoint
+ ProbeRootResolvConfEmpty = "root_resolv_conf_empty" // a resolver named in /etc/resolv.conf
+
+ // User: the runner, as the runner user.
+ ProbeUserResolvConfWrite = "user_resolv_conf_write" // open /etc/resolv.conf for writing
+ ProbeUserCapability = "user_capability_gain" // hold or raise a capability
+ ProbeUserProxyCodeReuse = "user_proxy_code_reuse" // redeem the used proxy code again at a bootstrap listener
+ ProbeUserInstance = "user_instance_protocol" // GET /api/runner/protocol from the instance through the proxy (control)
+
+ // Sandbox: inside the checks sandbox.
+ ProbeSandboxIPv4 = "sandbox_direct_ipv4" // TCP to a public IPv4 address
+ ProbeSandboxIPv6 = "sandbox_direct_ipv6" // TCP to a public IPv6 address
+ ProbeSandboxResolvers = "sandbox_managed_resolvers" // a DNS query to each managed resolver
+ ProbeSandboxMetadata = "sandbox_metadata" // TCP to each metadata endpoint
+ ProbeSandboxProxyEgress = "sandbox_proxy_egress" // TCP to each proxy's egress port, with no certificate
+ ProbeSandboxProxyBoot = "sandbox_proxy_bootstrap" // TCP to each proxy's bootstrap port
+ ProbeSandboxDNS = "sandbox_dns_query" // a name lookup through the system resolver
+ ProbeSandboxBuildScript = "sandbox_build_script" // a program built and run by go run dials a public address
+ ProbeSandboxGoModDownload = "sandbox_go_mod_download" // go mod download with an empty cache and a public proxy
+ ProbeSandboxGoTree = "sandbox_go_tree_read" // read the Go tree (control)
+)
+
+// Expectation is one row of the trusted matrix: the probe, the stage
+// whose list must hold it, the outcome it must have, and whether it is a
+// positive control (it shows the run could reach what it should, so a
+// dead network cannot pass for a contained one).
+type Expectation struct {
+ Name string
+ Stage string
+ Want string // OutcomeBlocked or OutcomeReached
+ Control bool
+}
+
+// Matrix is the trusted certification matrix: every probe a report must
+// hold, at its stage, with the outcome it must have. It lives only here,
+// in the signer; nothing in a report changes it.
+func Matrix() []Expectation {
+ blocked := func(stage, name string) Expectation {
+ return Expectation{Name: name, Stage: stage, Want: OutcomeBlocked}
+ }
+ reached := func(stage, name string) Expectation {
+ return Expectation{Name: name, Stage: stage, Want: OutcomeReached, Control: true}
+ }
+ return []Expectation{
+ blocked(StageRoot, ProbeRootVPCDNS),
+ blocked(StageRoot, ProbeRootMetadata),
+ blocked(StageRoot, ProbeRootResolvConfEmpty),
+
+ blocked(StageUser, ProbeUserResolvConfWrite),
+ blocked(StageUser, ProbeUserCapability),
+ blocked(StageUser, ProbeUserProxyCodeReuse),
+ reached(StageUser, ProbeUserInstance),
+
+ blocked(StageSandbox, ProbeSandboxIPv4),
+ blocked(StageSandbox, ProbeSandboxIPv6),
+ blocked(StageSandbox, ProbeSandboxResolvers),
+ blocked(StageSandbox, ProbeSandboxMetadata),
+ blocked(StageSandbox, ProbeSandboxProxyEgress),
+ blocked(StageSandbox, ProbeSandboxProxyBoot),
+ blocked(StageSandbox, ProbeSandboxDNS),
+ blocked(StageSandbox, ProbeSandboxBuildScript),
+ blocked(StageSandbox, ProbeSandboxGoModDownload),
+ reached(StageSandbox, ProbeSandboxGoTree),
+ }
+}
+
+// SandboxSubcommand is the runner's subcommand that runs the sandbox
+// probes inside the checks sandbox (SandboxMain, on Linux).
+const SandboxSubcommand = "hosted-sandbox-probes"
+
+// containmentArgs are the arguments the containment suite runs with: in
+// full, but for the source checks, which need the repository.
+var containmentArgs = []string{"-test.v", "-test.count=1", "-test.skip", "^TestSource"}
+
+// ContainmentArgs returns the containment suite's arguments. Its passing
+// run, every test passing and none skipped, is the third positive
+// control.
+func ContainmentArgs() []string { return slices.Clone(containmentArgs) }
diff --git a/internal/hostedcert/matrix_test.go b/internal/hostedcert/matrix_test.go
new file mode 100644
index 00000000..cbeaf956
--- /dev/null
+++ b/internal/hostedcert/matrix_test.go
@@ -0,0 +1,79 @@
+package hostedcert_test
+
+import (
+ "slices"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/vminit"
+)
+
+// TestMatrixShape: the trusted matrix names every probe of the brief once,
+// at a known stage, wanting blocked for each negative probe and reached
+// for each positive control, with a control at the user and the sandbox
+// stage.
+func TestMatrixShape(t *testing.T) {
+ m := hostedcert.Matrix()
+ seen := map[string]bool{}
+ controls := map[string]int{}
+ for _, e := range m {
+ if seen[e.Name] {
+ t.Errorf("%s is in the matrix twice", e.Name)
+ }
+ seen[e.Name] = true
+ switch {
+ case e.Stage != hostedcert.StageRoot && e.Stage != hostedcert.StageUser && e.Stage != hostedcert.StageSandbox:
+ t.Errorf("%s has stage %q", e.Name, e.Stage)
+ case e.Control && e.Want != hostedcert.OutcomeReached, !e.Control && e.Want != hostedcert.OutcomeBlocked:
+ t.Errorf("%s: control %v wants %q", e.Name, e.Control, e.Want)
+ }
+ if e.Control {
+ controls[e.Stage]++
+ }
+ }
+ for _, name := range []string{
+ hostedcert.ProbeRootVPCDNS, hostedcert.ProbeRootMetadata, hostedcert.ProbeRootResolvConfEmpty,
+ hostedcert.ProbeUserResolvConfWrite, hostedcert.ProbeUserCapability, hostedcert.ProbeUserProxyCodeReuse, hostedcert.ProbeUserInstance,
+ hostedcert.ProbeSandboxIPv4, hostedcert.ProbeSandboxIPv6, hostedcert.ProbeSandboxResolvers, hostedcert.ProbeSandboxMetadata,
+ hostedcert.ProbeSandboxProxyEgress, hostedcert.ProbeSandboxProxyBoot, hostedcert.ProbeSandboxDNS,
+ hostedcert.ProbeSandboxBuildScript, hostedcert.ProbeSandboxGoModDownload, hostedcert.ProbeSandboxGoTree,
+ } {
+ if !seen[name] {
+ t.Errorf("the matrix lacks %s", name)
+ }
+ }
+ if controls[hostedcert.StageUser] == 0 || controls[hostedcert.StageSandbox] == 0 {
+ t.Errorf("controls by stage = %v, want one at the user and the sandbox stage", controls)
+ }
+ if got := hostedcert.ContainmentArgs(); !slices.Contains(got, "-test.skip") || !slices.Contains(got, "^TestSource") {
+ t.Errorf("ContainmentArgs = %q, want the source tests skipped", got)
+ }
+}
+
+// TestMatrixIsACopy: a caller that edits what Matrix or ContainmentArgs
+// returned changes nothing the next caller gets.
+func TestMatrixIsACopy(t *testing.T) {
+ m := hostedcert.Matrix()
+ m[0].Want = hostedcert.OutcomeReached
+ if hostedcert.Matrix()[0].Want != hostedcert.OutcomeBlocked {
+ t.Fatal("editing Matrix's result changed the matrix")
+ }
+ a := hostedcert.ContainmentArgs()
+ a[0] = "-test.run=Nothing"
+ if hostedcert.ContainmentArgs()[0] == a[0] {
+ t.Fatal("editing ContainmentArgs's result changed the arguments")
+ }
+}
+
+// TestMeasuredNamesMatchVMInit: the names certification reads are the
+// names vm-init writes.
+func TestMeasuredNamesMatchVMInit(t *testing.T) {
+ for got, want := range map[string]string{
+ hostedcert.MeasuredRunner: vminit.MeasuredRunner, hostedcert.MeasuredVMInit: vminit.MeasuredVMInit,
+ hostedcert.MeasuredSandboxPolicy: vminit.MeasuredSandboxPolicy,
+ } {
+ if got != want {
+ t.Errorf("measured name %q, vm-init writes %q", got, want)
+ }
+ }
+}
diff --git a/internal/hostedcert/probe_linux.go b/internal/hostedcert/probe_linux.go
new file mode 100644
index 00000000..efdb4bac
--- /dev/null
+++ b/internal/hostedcert/probe_linux.go
@@ -0,0 +1,675 @@
+//go:build linux
+
+package hostedcert
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "net"
+ "net/netip"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+// The certification VM's side: the user and sandbox probes, the
+// containment suite, and the report they make with vm-init's root.json and
+// measured.json. Every attempt that needs the network, privileges or a
+// sandbox goes through a seam, so tests need none of them.
+
+// The files vm-init leaves in the results directory (vminit's
+// MeasuredFile, RootProbeFile and ProbeTargetsFile; a test holds them
+// equal).
+const (
+ MeasuredFile = "measured.json"
+ RootProbeFile = "root.json"
+ ProbeTargetsFile = "probe-targets.json"
+)
+
+// The public addresses the sandbox's direct probes dial: well-known
+// anycast DNS services on port 443.
+var (
+ PublicIPv4 = netip.MustParseAddrPort("1.1.1.1:443")
+ PublicIPv6 = netip.MustParseAddrPort("[2606:4700:4700::1111]:443")
+)
+
+const (
+ probeTimeout = 5 * time.Second
+ // maxResultFile bounds each results file the collector reads.
+ maxResultFile = 1 << 20
+)
+
+// ProbeTargets are the managed resolvers and metadata endpoints vm-init
+// knows (its -resolver and -metadata flags, and the nameservers the
+// managed resolv.conf named at boot), written for the runner's probes.
+type ProbeTargets struct {
+ Resolvers []netip.Addr `json:"resolvers"`
+ Metadata []netip.AddrPort `json:"metadata"`
+}
+
+// result makes a probe result whose OK says whether the attempt was
+// blocked, the VM's own verdict for readers; Judge reads only Outcome.
+func result(stage, name, outcome, detail string) ProbeResult {
+ if len(detail) > maxProbeDetail {
+ detail = detail[:maxProbeDetail]
+ }
+ 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.
+func denied(err error) bool {
+ if err == nil || errors.Is(err, context.Canceled) {
+ 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)
+}
+
+// ---- the user stage ----
+
+// UserProbes are the user stage's seams. DefaultUserProbes fills the OS
+// ones; ReuseCode and Instance come from the runner's session.
+type UserProbes struct {
+ ResolvConf string
+ // OpenForWrite opens path for writing, writes nothing, and closes it.
+ OpenForWrite func(path string) error
+ // Capabilities returns the process's permitted, effective and
+ // ambient capability sets, ORed.
+ Capabilities func() (uint64, error)
+ // Raise asks the kernel to add a capability to the permitted and
+ // effective sets.
+ Raise func() error
+ // ReuseCode redeems the launch's used proxy code again at a bootstrap
+ // listener and returns the status and error code answered.
+ ReuseCode func(ctx context.Context) (int, string, error)
+ // Instance asks the instance for GET /api/runner/protocol through the
+ // proxy and returns the status.
+ Instance func(ctx context.Context) (int, error)
+}
+
+// DefaultUserProbes is the OS's side of the user probes.
+func DefaultUserProbes(reuse func(context.Context) (int, string, error), instance func(context.Context) (int, error)) UserProbes {
+ return UserProbes{ResolvConf: "/etc/resolv.conf", OpenForWrite: openForWrite, Capabilities: capabilities, Raise: raiseCapability,
+ ReuseCode: reuse, Instance: instance}
+}
+
+// RunUserProbes runs the user probes in a fixed order.
+func RunUserProbes(ctx context.Context, u UserProbes) []ProbeResult {
+ out := []ProbeResult{}
+ r := func(name, outcome, detail string) { out = append(out, result(StageUser, name, outcome, detail)) }
+
+ switch err := u.OpenForWrite(u.ResolvConf); {
+ case err == nil:
+ r(ProbeUserResolvConfWrite, OutcomeReached, u.ResolvConf+" opened for writing")
+ case errors.Is(err, fs.ErrPermission) || errors.Is(err, syscall.EROFS):
+ r(ProbeUserResolvConfWrite, OutcomeBlocked, err.Error())
+ default:
+ r(ProbeUserResolvConfWrite, OutcomeInconclusive, err.Error())
+ }
+
+ held, err := u.Capabilities()
+ switch {
+ case err != nil:
+ r(ProbeUserCapability, OutcomeInconclusive, "reading the capability sets: "+err.Error())
+ case held != 0:
+ r(ProbeUserCapability, OutcomeReached, fmt.Sprintf("the process holds capabilities %#x", held))
+ default:
+ switch err := u.Raise(); {
+ case err == nil:
+ r(ProbeUserCapability, OutcomeReached, "a capability was raised")
+ case errors.Is(err, syscall.EPERM):
+ r(ProbeUserCapability, OutcomeBlocked, "no capability held; raising one: "+err.Error())
+ default:
+ r(ProbeUserCapability, OutcomeInconclusive, "raising a capability: "+err.Error())
+ }
+ }
+
+ status, code, err := u.ReuseCode(ctx)
+ switch {
+ case err != nil:
+ r(ProbeUserProxyCodeReuse, OutcomeInconclusive, "no bootstrap listener answered: "+err.Error())
+ case status == 200:
+ r(ProbeUserProxyCodeReuse, OutcomeReached, "the used proxy code was redeemed again")
+ case status == 403:
+ // A bootstrap listener forwards every redemption; a 403 is the
+ // controller's refusal.
+ r(ProbeUserProxyCodeReuse, OutcomeBlocked, fmt.Sprintf("the controller refused the used proxy code (%s)", code))
+ default:
+ r(ProbeUserProxyCodeReuse, OutcomeInconclusive, fmt.Sprintf("answered %d %q", status, code))
+ }
+
+ switch status, err := u.Instance(ctx); {
+ case err != nil:
+ r(ProbeUserInstance, OutcomeBlocked, err.Error())
+ case status == 200:
+ r(ProbeUserInstance, OutcomeReached, "the instance answered 200 through the proxy")
+ default:
+ r(ProbeUserInstance, OutcomeBlocked, fmt.Sprintf("the instance answered %d", status))
+ }
+ return out
+}
+
+func openForWrite(path string) error {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|syscall.O_NOFOLLOW, 0)
+ if err != nil {
+ return err
+ }
+ return f.Close()
+}
+
+// capabilities reads CapPrm, CapEff and CapAmb from /proc/self/status.
+func capabilities() (uint64, error) {
+ raw, err := os.ReadFile("/proc/self/status")
+ if err != nil {
+ return 0, err
+ }
+ var held uint64
+ seen := 0
+ for _, line := range strings.Split(string(raw), "\n") {
+ k, v, ok := strings.Cut(line, ":")
+ if !ok || (k != "CapPrm" && k != "CapEff" && k != "CapAmb") {
+ continue
+ }
+ var n uint64
+ if _, err := fmt.Sscanf(strings.TrimSpace(v), "%x", &n); err != nil {
+ return 0, fmt.Errorf("%s: %w", k, err)
+ }
+ held |= n
+ seen++
+ }
+ if seen != 3 {
+ return 0, errors.New("/proc/self/status lacks a capability set")
+ }
+ return held, nil
+}
+
+// raiseCapability asks capset(2) for CAP_SYS_ADMIN and CAP_NET_ADMIN in
+// the permitted and effective sets.
+func raiseCapability() error {
+ const linuxCapabilityVersion3 = 0x20080522
+ const want = 1<<21 | 1<<12 // CAP_SYS_ADMIN, CAP_NET_ADMIN
+ hdr := struct {
+ version uint32
+ pid int32
+ }{linuxCapabilityVersion3, 0}
+ data := [2]struct{ effective, permitted, inheritable uint32 }{{want, want, 0}, {}}
+ _, _, errno := syscall.RawSyscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(&hdr)), uintptr(unsafe.Pointer(&data[0])), 0)
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
+
+// ---- the sandbox stage ----
+
+// SandboxTargets are what the sandbox probes aim at. Work is a writable
+// directory inside the sandbox for the build-script and module probes.
+type SandboxTargets struct {
+ PublicIPv4 netip.AddrPort `json:"public_ipv4"`
+ PublicIPv6 netip.AddrPort `json:"public_ipv6"`
+ Resolvers []netip.Addr `json:"resolvers"`
+ Metadata []netip.AddrPort `json:"metadata"`
+ ProxyEgress []netip.AddrPort `json:"proxy_egress"`
+ ProxyBoot []netip.AddrPort `json:"proxy_boot"`
+ GoRoot string `json:"go_root"`
+ Work string `json:"work"`
+}
+
+// SandboxSeams are the sandbox probes' ways out.
+type SandboxSeams struct {
+ Dial func(ctx context.Context, network, addr string) (net.Conn, error)
+ Lookup func(ctx context.Context, host string) ([]string, error)
+ // Run runs argv in dir with exactly env and returns its exit code and
+ // combined output; err only when it could not run.
+ Run func(ctx context.Context, dir string, env []string, argv ...string) (int, []byte, error)
+ ReadFile func(path string) ([]byte, error)
+ WriteFile func(path string, data []byte) error
+}
+
+// DefaultSandboxSeams are the OS's own.
+func DefaultSandboxSeams() SandboxSeams {
+ var d net.Dialer
+ return SandboxSeams{Dial: d.DialContext, Lookup: net.DefaultResolver.LookupHost, Run: runCommand, ReadFile: os.ReadFile,
+ WriteFile: func(p string, b []byte) error {
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ return err
+ }
+ return os.WriteFile(p, b, 0o600)
+ }}
+}
+
+func runCommand(ctx context.Context, dir string, env []string, argv ...string) (int, []byte, error) {
+ cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
+ cmd.Dir, cmd.Env = dir, env
+ out, err := cmd.CombinedOutput()
+ var exit *exec.ExitError
+ switch {
+ case err == nil:
+ return 0, out, nil
+ case errors.As(err, &exit):
+ return exit.ExitCode(), out, nil
+ }
+ return -1, out, err
+}
+
+// The marks the build-script probe's program prints.
+const (
+ markReached = "equipo-probe: reached"
+ markBlocked = "equipo-probe: blocked"
+)
+
+// buildScript is the build-script probe's program: a dial, as a build
+// step that fetches something would make.
+const buildScript = `package main
+
+import (
+ "fmt"
+ "net"
+ "os"
+ "time"
+)
+
+func main() {
+ c, err := net.DialTimeout("tcp", os.Args[1], 5*time.Second)
+ if err != nil {
+ fmt.Println("` + markBlocked + `:", err)
+ return
+ }
+ c.Close()
+ fmt.Println("` + markReached + `")
+}
+`
+
+// 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 {
+ out := []ProbeResult{}
+ r := func(name, outcome, detail string) { out = append(out, result(StageSandbox, name, outcome, detail)) }
+ dialAll := func(name string, addrs []netip.AddrPort) {
+ if len(addrs) == 0 {
+ r(name, OutcomeInconclusive, "no address to try")
+ return
+ }
+ outcome, notes := OutcomeBlocked, []string{}
+ for _, a := range addrs {
+ o, note := dialOnce(ctx, s, a)
+ notes = append(notes, note)
+ outcome = worse(outcome, o)
+ }
+ r(name, outcome, strings.Join(notes, "; "))
+ }
+ dialAll(ProbeSandboxIPv4, []netip.AddrPort{t.PublicIPv4})
+ dialAll(ProbeSandboxIPv6, []netip.AddrPort{t.PublicIPv6})
+
+ if len(t.Resolvers) == 0 {
+ r(ProbeSandboxResolvers, OutcomeInconclusive, "no managed resolver known")
+ } else {
+ outcome, notes := OutcomeBlocked, []string{}
+ for _, a := range t.Resolvers {
+ for _, network := range []string{"udp", "tcp"} {
+ o, note := dnsOnce(ctx, s, network, netip.AddrPortFrom(a, 53))
+ notes = append(notes, note)
+ outcome = worse(outcome, o)
+ }
+ }
+ r(ProbeSandboxResolvers, outcome, strings.Join(notes, "; "))
+ }
+ dialAll(ProbeSandboxMetadata, t.Metadata)
+ dialAll(ProbeSandboxProxyEgress, t.ProxyEgress)
+ dialAll(ProbeSandboxProxyBoot, t.ProxyBoot)
+
+ 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)))
+ }
+
+ env := goEnv(t)
+ o, detail := buildScriptProbe(ctx, t, s, env)
+ r(ProbeSandboxBuildScript, o, detail)
+ o, detail = modDownloadProbe(ctx, t, s, env)
+ r(ProbeSandboxGoModDownload, o, detail)
+
+ o, detail = OutcomeReached, "read the Go tree"
+ for _, p := range []string{"VERSION", "src/fmt/print.go"} {
+ if b, err := s.ReadFile(filepath.Join(t.GoRoot, p)); err != nil || len(b) == 0 {
+ o, detail = OutcomeBlocked, fmt.Sprintf("%s: %v (%d bytes)", p, err, len(b))
+ break
+ }
+ }
+ r(ProbeSandboxGoTree, o, detail)
+ return out
+}
+
+// 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 {
+ switch {
+ case a == OutcomeReached || b == OutcomeReached:
+ return OutcomeReached
+ case a == OutcomeInconclusive || b == OutcomeInconclusive:
+ return OutcomeInconclusive
+ }
+ return OutcomeBlocked
+}
+
+func dialOnce(ctx context.Context, s SandboxSeams, a netip.AddrPort) (string, string) {
+ ctx, cancel := context.WithTimeout(ctx, probeTimeout)
+ defer cancel()
+ c, err := s.Dial(ctx, "tcp", a.String())
+ switch {
+ case err == nil:
+ c.Close()
+ return OutcomeReached, a.String() + " connected"
+ case denied(err):
+ return OutcomeBlocked, fmt.Sprintf("%s: %v", a, err)
+ }
+ return OutcomeInconclusive, fmt.Sprintf("%s: %s (%v)", a, OutcomeInconclusive, err)
+}
+
+func dnsOnce(ctx context.Context, s SandboxSeams, network string, server netip.AddrPort) (string, string) {
+ ctx, cancel := context.WithTimeout(ctx, probeTimeout)
+ defer cancel()
+ c, err := s.Dial(ctx, network, server.String())
+ if err != nil {
+ if denied(err) {
+ return OutcomeBlocked, fmt.Sprintf("%s %s: %v", network, server, err)
+ }
+ return OutcomeInconclusive, fmt.Sprintf("%s %s: %s (%v)", network, server, OutcomeInconclusive, err)
+ }
+ defer c.Close()
+ if dl, ok := ctx.Deadline(); ok {
+ _ = c.SetDeadline(dl)
+ }
+ q := dnsQuery("example.com")
+ if network == "tcp" {
+ q = append(binary.BigEndian.AppendUint16(nil, uint16(len(q))), q...)
+ }
+ if _, err := c.Write(q); err != nil {
+ if denied(err) {
+ return OutcomeBlocked, fmt.Sprintf("%s %s: %v", network, server, err)
+ }
+ return OutcomeInconclusive, fmt.Sprintf("%s %s: %s (%v)", network, server, OutcomeInconclusive, err)
+ }
+ buf := make([]byte, 512)
+ n, err := c.Read(buf)
+ switch {
+ case n > 0:
+ return OutcomeReached, fmt.Sprintf("%s %s answered %d bytes", network, server, n)
+ case denied(err) || errors.Is(err, io.EOF):
+ return OutcomeBlocked, fmt.Sprintf("%s %s silent", network, server)
+ }
+ return OutcomeInconclusive, fmt.Sprintf("%s %s: %s (%v)", network, server, OutcomeInconclusive, err)
+}
+
+// dnsQuery is a one-question A query for name, recursion desired.
+func dnsQuery(name string) []byte {
+ q := []byte{0x45, 0x52, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0}
+ for _, label := range strings.Split(name, ".") {
+ q = append(q, byte(len(label)))
+ q = append(q, label...)
+ }
+ return append(q, 0, 0, 1, 0, 1)
+}
+
+// goEnv is the Go toolchain's environment for the two build probes: the
+// sandbox's Go tree, fresh caches under Work, and nothing inherited.
+func goEnv(t SandboxTargets) []string {
+ return []string{"PATH=" + filepath.Join(t.GoRoot, "bin") + ":/usr/bin:/bin", "HOME=" + t.Work, "GOROOT=" + t.GoRoot,
+ "GOCACHE=" + filepath.Join(t.Work, "gocache"), "GOMODCACHE=" + filepath.Join(t.Work, "modcache"),
+ "GOTMPDIR=", "TMPDIR=" + t.Work, "GOTOOLCHAIN=local", "GOTELEMETRY=off", "GOENV=off", "GOFLAGS=", "CGO_ENABLED=0",
+ "GOWORK=off", "LANG=C"}
+}
+
+func buildScriptProbe(ctx context.Context, t SandboxTargets, s SandboxSeams, env []string) (string, string) {
+ dir := filepath.Join(t.Work, "buildscript")
+ if err := s.WriteFile(filepath.Join(dir, "main.go"), []byte(buildScript)); err != nil {
+ return OutcomeInconclusive, "writing the build script: " + err.Error()
+ }
+ ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
+ 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:
+ 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)
+}
+
+// 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()
+ }
+ 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")
+ text := lastLines(out)
+ switch {
+ case err != nil:
+ return OutcomeInconclusive, "go mod download did not start: " + err.Error()
+ 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)
+ }
+ }
+ return OutcomeInconclusive, fmt.Sprintf("exited %d for another reason: %s", exit, text)
+}
+
+// lastLines is at most the last 1 KiB of out, as one line.
+func lastLines(out []byte) string {
+ if len(out) > 1024 {
+ out = out[len(out)-1024:]
+ }
+ return strings.Join(strings.Fields(string(out)), " ")
+}
+
+// SandboxMain is the sandbox's side: it runs the probes against the
+// targets in args[0] (SandboxTargets as JSON) and prints the results as
+// one JSON array on stdout.
+func SandboxMain(ctx context.Context, args []string, stdout io.Writer) int {
+ var t SandboxTargets
+ if len(args) != 1 || decodeStrict([]byte(args[0]), &t) != nil || !filepath.IsAbs(t.GoRoot) || !filepath.IsAbs(t.Work) {
+ return 2
+ }
+ if err := json.NewEncoder(stdout).Encode(RunSandboxProbes(ctx, t, DefaultSandboxSeams())); err != nil {
+ return 1
+ }
+ return 0
+}
+
+// SandboxRunner runs argv inside the checks sandbox and returns what it
+// printed on stdout and its exit code.
+type SandboxRunner func(ctx context.Context, argv []string) (stdout []byte, exit int, err error)
+
+// RunInSandbox runs the probes through run as [self, SandboxSubcommand,
+// targets] and reads their results. Any failure, or a result that is not
+// a sandbox probe, gives every sandbox probe of the matrix inconclusive,
+// with the reason: the report still goes, and Judge fails it.
+func RunInSandbox(ctx context.Context, run SandboxRunner, self string, t SandboxTargets) []ProbeResult {
+ raw, err := json.Marshal(t)
+ if err != nil {
+ return sandboxFailed(err)
+ }
+ stdout, exit, err := run(ctx, []string{self, SandboxSubcommand, string(raw)})
+ switch {
+ case err != nil:
+ return sandboxFailed(fmt.Errorf("the sandbox did not run: %w", err))
+ case exit != 0:
+ return sandboxFailed(fmt.Errorf("the probes exited %d", exit))
+ }
+ var res []ProbeResult
+ if err := decodeStrict(stdout, &res); err != nil {
+ return sandboxFailed(fmt.Errorf("the probes' output does not decode: %w", err))
+ }
+ for _, p := range res {
+ if p.Stage != StageSandbox {
+ return sandboxFailed(fmt.Errorf("the probes returned %s at stage %q", p.Name, p.Stage))
+ }
+ }
+ return res
+}
+
+func sandboxFailed(err error) []ProbeResult {
+ var out []ProbeResult
+ for _, e := range Matrix() {
+ if e.Stage == StageSandbox {
+ out = append(out, result(StageSandbox, e.Name, OutcomeInconclusive, err.Error()))
+ }
+ }
+ return out
+}
+
+// ---- the containment suite ----
+
+// 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.
+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)
+ if err != nil {
+ c.Detail = "measuring the suite: " + err.Error()
+ return c
+ }
+ c.Binary = sum
+ exit, out, err := run(ctx, append([]string{path}, c.Args...))
+ if err != nil {
+ 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++
+ }
+ }
+ 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, " ")
+ }
+ if len(c.Detail) > maxProbeDetail {
+ c.Detail = c.Detail[:maxProbeDetail]
+ }
+ return c
+}
+
+func fileSHA256(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+// ---- the report ----
+
+// Collector makes a certification VM's report.
+type Collector struct {
+ LaunchID string
+ // Results is the results directory vm-init wrote (EQUIPO_HOSTED_RESULTS).
+ Results string
+ User UserProbes
+ Sandbox func(ctx context.Context, targets ProbeTargets) []ProbeResult
+ Containment func(ctx context.Context) ContainmentResult
+}
+
+// ReadTargets reads the probe targets vm-init wrote in results.
+func ReadTargets(results string) (ProbeTargets, error) {
+ var t ProbeTargets
+ return t, readResult(results, ProbeTargetsFile, &t)
+}
+
+// Collect reads root.json, measured.json and the probe targets, runs the
+// user probes, the sandbox probes and the containment suite, and returns
+// the report, checked.
+func (c Collector) Collect(ctx context.Context) (Report, error) {
+ r := Report{LaunchID: c.LaunchID}
+ if err := readResult(c.Results, RootProbeFile, &r.Root); err != nil {
+ return Report{}, err
+ }
+ if err := readResult(c.Results, MeasuredFile, &r.Measured); err != nil {
+ return Report{}, err
+ }
+ targets, err := ReadTargets(c.Results)
+ if err != nil {
+ return Report{}, err
+ }
+ r.User = RunUserProbes(ctx, c.User)
+ r.Sandbox = c.Sandbox(ctx, targets)
+ r.Containment = c.Containment(ctx)
+ if r.Root == nil {
+ r.Root = []ProbeResult{}
+ }
+ return r, r.Check()
+}
+
+func readResult(dir, name string, v any) error {
+ f, err := os.Open(filepath.Join(dir, name))
+ if err != nil {
+ return fmt.Errorf("hostedcert: results: %w", err)
+ }
+ defer f.Close()
+ raw, err := io.ReadAll(io.LimitReader(f, maxResultFile+1))
+ if err != nil || len(raw) > maxResultFile {
+ return fmt.Errorf("hostedcert: results: %s is unreadable or over %d bytes", name, maxResultFile)
+ }
+ if err := decodeStrict(raw, v); err != nil {
+ return fmt.Errorf("hostedcert: results: %s: %w", name, err)
+ }
+ return nil
+}
diff --git a/internal/hostedcert/probe_linux_test.go b/internal/hostedcert/probe_linux_test.go
new file mode 100644
index 00000000..0f4db0e9
--- /dev/null
+++ b/internal/hostedcert/probe_linux_test.go
@@ -0,0 +1,358 @@
+//go:build linux
+
+package hostedcert_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "net"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "syscall"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/vminit"
+)
+
+// TestRootProbesAreVMInits: the root probes, outcomes and file names the
+// matrix and the collector use are vm-init's, and a result vm-init writes
+// reads strictly as a hostedcert.ProbeResult.
+func TestRootProbesAreVMInits(t *testing.T) {
+ pairs := map[string]string{
+ hostedcert.ProbeRootVPCDNS: vminit.ProbeVPCDNSSilent, hostedcert.ProbeRootMetadata: vminit.ProbeMetadataNoCredential,
+ hostedcert.ProbeRootResolvConfEmpty: vminit.ProbeResolvConfEmpty, hostedcert.StageRoot: vminit.StageRoot,
+ hostedcert.OutcomeBlocked: vminit.OutcomeBlocked, hostedcert.OutcomeReached: vminit.OutcomeReached,
+ hostedcert.OutcomeInconclusive: vminit.OutcomeInconclusive, hostedcert.MeasuredFile: vminit.MeasuredFile,
+ hostedcert.RootProbeFile: vminit.RootProbeFile, hostedcert.ProbeTargetsFile: vminit.ProbeTargetsFile,
+ }
+ for ours, theirs := range pairs {
+ if ours != theirs {
+ t.Errorf("%q here, %q in vm-init", ours, theirs)
+ }
+ }
+ raw, _ := json.Marshal(vminit.ProbeResult{Name: vminit.ProbeVPCDNSSilent, Stage: vminit.StageRoot, OK: true,
+ Outcome: vminit.OutcomeBlocked, Detail: "silent"})
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.DisallowUnknownFields()
+ var p hostedcert.ProbeResult
+ if err := dec.Decode(&p); err != nil || p.Outcome != hostedcert.OutcomeBlocked {
+ t.Errorf("vm-init's result %s reads as %+v, %v", raw, p, err)
+ }
+}
+
+func outcomes(res []hostedcert.ProbeResult) map[string]string {
+ m := map[string]string{}
+ for _, p := range res {
+ m[p.Name] = p.Outcome
+ }
+ return m
+}
+
+// TestUserProbes: each user probe's outcome follows from its attempt.
+func TestUserProbes(t *testing.T) {
+ contained := hostedcert.UserProbes{ResolvConf: "/etc/resolv.conf",
+ OpenForWrite: func(string) error { return &os.PathError{Op: "open", Path: "/etc/resolv.conf", Err: syscall.EROFS} },
+ Capabilities: func() (uint64, error) { return 0, nil },
+ Raise: func() error { return syscall.EPERM },
+ ReuseCode: func(context.Context) (int, string, error) { return 403, "proxy_refused", nil },
+ Instance: func(context.Context) (int, error) { return 200, nil }}
+ want := map[string]string{hostedcert.ProbeUserResolvConfWrite: hostedcert.OutcomeBlocked, hostedcert.ProbeUserCapability: hostedcert.OutcomeBlocked,
+ hostedcert.ProbeUserProxyCodeReuse: hostedcert.OutcomeBlocked, hostedcert.ProbeUserInstance: hostedcert.OutcomeReached}
+ res := hostedcert.RunUserProbes(context.Background(), contained)
+ if got := outcomes(res); len(res) != 4 || !mapsEqual(got, want) {
+ t.Fatalf("contained: %v, want %v", got, want)
+ }
+ for _, p := range res {
+ if p.Stage != hostedcert.StageUser || p.Detail == "" {
+ t.Errorf("result %+v: want stage user and a detail", p)
+ }
+ }
+ for name, c := range map[string]struct {
+ edit func(*hostedcert.UserProbes)
+ probe string
+ want string
+ }{
+ "resolv.conf writable": {func(u *hostedcert.UserProbes) { u.OpenForWrite = func(string) error { return nil } }, hostedcert.ProbeUserResolvConfWrite, hostedcert.OutcomeReached},
+ "resolv.conf missing": {func(u *hostedcert.UserProbes) { u.OpenForWrite = func(string) error { return os.ErrNotExist } }, hostedcert.ProbeUserResolvConfWrite, hostedcert.OutcomeInconclusive},
+ "a capability held": {func(u *hostedcert.UserProbes) { u.Capabilities = func() (uint64, error) { return 1 << 21, nil } }, hostedcert.ProbeUserCapability, hostedcert.OutcomeReached},
+ "a capability raised": {func(u *hostedcert.UserProbes) { u.Raise = func() error { return nil } }, hostedcert.ProbeUserCapability, hostedcert.OutcomeReached},
+ "capabilities unread": {func(u *hostedcert.UserProbes) {
+ u.Capabilities = func() (uint64, error) { return 0, errors.New("no proc") }
+ }, hostedcert.ProbeUserCapability, hostedcert.OutcomeInconclusive},
+ "code redeemed again": {func(u *hostedcert.UserProbes) {
+ u.ReuseCode = func(context.Context) (int, string, error) { return 200, "", nil }
+ }, hostedcert.ProbeUserProxyCodeReuse, hostedcert.OutcomeReached},
+ "no listener": {func(u *hostedcert.UserProbes) {
+ u.ReuseCode = func(context.Context) (int, string, error) { return 0, "", errors.New("down") }
+ }, hostedcert.ProbeUserProxyCodeReuse, hostedcert.OutcomeInconclusive},
+ "controller unreachable": {func(u *hostedcert.UserProbes) {
+ u.ReuseCode = func(context.Context) (int, string, error) { return 502, "controller_unavailable", nil }
+ }, hostedcert.ProbeUserProxyCodeReuse, hostedcert.OutcomeInconclusive},
+ "instance unreachable": {func(u *hostedcert.UserProbes) {
+ u.Instance = func(context.Context) (int, error) { return 0, errors.New("down") }
+ }, hostedcert.ProbeUserInstance, hostedcert.OutcomeBlocked},
+ "instance answers a 502": {func(u *hostedcert.UserProbes) { u.Instance = func(context.Context) (int, error) { return 502, nil } }, hostedcert.ProbeUserInstance, hostedcert.OutcomeBlocked},
+ } {
+ u := contained
+ c.edit(&u)
+ if got := outcomes(hostedcert.RunUserProbes(context.Background(), u))[c.probe]; got != c.want {
+ t.Errorf("%s: %s = %q, want %q", name, c.probe, got, c.want)
+ }
+ }
+}
+
+func mapsEqual(a, b map[string]string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for k, v := range a {
+ if b[k] != v {
+ return false
+ }
+ }
+ return true
+}
+
+// sandboxNet is a sandbox with no network: every dial fails with
+// ENETUNREACH, except to the addresses in open.
+type sandboxNet struct {
+ open map[string]bool
+ dialed []string
+}
+
+func (n *sandboxNet) dial(_ context.Context, network, addr string) (net.Conn, error) {
+ n.dialed = append(n.dialed, network+" "+addr)
+ if n.open[addr] {
+ a, b := net.Pipe()
+ go func() {
+ buf := make([]byte, 512)
+ k, _ := b.Read(buf)
+ if k > 0 {
+ _, _ = b.Write([]byte{1, 2, 3})
+ }
+ b.Close()
+ }()
+ return a, nil
+ }
+ return nil, &net.OpError{Op: "dial", Net: network, Err: os.NewSyscallError("connect", syscall.ENETUNREACH)}
+}
+
+func targets() hostedcert.SandboxTargets {
+ return hostedcert.SandboxTargets{PublicIPv4: hostedcert.PublicIPv4, PublicIPv6: hostedcert.PublicIPv6,
+ Resolvers: []netip.Addr{netip.MustParseAddr("10.0.0.2")}, Metadata: []netip.AddrPort{netip.MustParseAddrPort("169.254.169.254:80")},
+ ProxyEgress: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8443")}, ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8444")},
+ GoRoot: "/opt/go", Work: "/tmp/probes"}
+}
+
+func seams(n *sandboxNet, runs map[string]struct {
+ exit int
+ out string
+}) hostedcert.SandboxSeams {
+ return hostedcert.SandboxSeams{Dial: n.dial,
+ Lookup: func(context.Context, string) ([]string, error) {
+ return nil, &net.DNSError{Err: "no such host", Name: "example.com", IsNotFound: true}
+ },
+ Run: func(_ context.Context, _ string, env []string, argv ...string) (int, []byte, error) {
+ if !slices.Contains(env, "GOTOOLCHAIN=local") {
+ return -1, nil, errors.New("the Go environment is not the probe's")
+ }
+ r := runs[argv[1]]
+ return r.exit, []byte(r.out), nil
+ },
+ ReadFile: func(p string) ([]byte, error) { return []byte("content of " + p), nil },
+ WriteFile: func(string, []byte) error { return nil }}
+}
+
+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"},
+}
+
+// TestSandboxProbes: with no network every negative probe is blocked and
+// the Go tree is read; one way out, or an attempt that cannot tell, shows.
+func TestSandboxProbes(t *testing.T) {
+ n := &sandboxNet{}
+ res := hostedcert.RunSandboxProbes(context.Background(), targets(), seams(n, offline))
+ got := outcomes(res)
+ for _, e := range hostedcert.Matrix() {
+ if e.Stage == hostedcert.StageSandbox && got[e.Name] != e.Want {
+ t.Errorf("offline: %s = %q, want %q", e.Name, got[e.Name], e.Want)
+ }
+ }
+ for _, want := range []string{"tcp 1.1.1.1:443", "tcp [2606:4700:4700::1111]:443", "udp 10.0.0.2:53", "tcp 10.0.0.2:53",
+ "tcp 169.254.169.254:80", "tcp 10.42.1.10:8443", "tcp 10.42.1.10:8444"} {
+ if !slices.Contains(n.dialed, want) {
+ t.Errorf("the probes never tried %s: %q", want, n.dialed)
+ }
+ }
+
+ for name, c := range map[string]struct {
+ open string
+ probe string
+ }{
+ "public IPv4": {"1.1.1.1:443", hostedcert.ProbeSandboxIPv4}, "resolver": {"10.0.0.2:53", hostedcert.ProbeSandboxResolvers},
+ "metadata": {"169.254.169.254:80", hostedcert.ProbeSandboxMetadata}, "proxy egress": {"10.42.1.10:8443", hostedcert.ProbeSandboxProxyEgress},
+ "proxy bootstrap": {"10.42.1.10:8444", hostedcert.ProbeSandboxProxyBoot},
+ } {
+ got := outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), seams(&sandboxNet{open: map[string]bool{c.open: true}}, offline)))
+ if got[c.probe] != hostedcert.OutcomeReached {
+ t.Errorf("%s open: %s = %q, want reached", name, c.probe, got[c.probe])
+ }
+ }
+ online := map[string]struct {
+ exit int
+ out string
+ }{"run": {0, "equipo-probe: reached"}, "mod": {0, ""}}
+ 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)
+ }
+ broken := map[string]struct {
+ exit int
+ out string
+ }{"run": {1, "main.go:1: syntax error"}, "mod": {1, "go: module cache not writable"}}
+ got = outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), seams(&sandboxNet{}, broken)))
+ if got[hostedcert.ProbeSandboxBuildScript] != hostedcert.OutcomeInconclusive || got[hostedcert.ProbeSandboxGoModDownload] != hostedcert.OutcomeInconclusive {
+ t.Errorf("a broken toolchain shows nothing: %v", got)
+ }
+ empty := targets()
+ empty.Resolvers, empty.Metadata = nil, nil
+ got = outcomes(hostedcert.RunSandboxProbes(context.Background(), empty, seams(&sandboxNet{}, offline)))
+ if got[hostedcert.ProbeSandboxResolvers] != hostedcert.OutcomeInconclusive || got[hostedcert.ProbeSandboxMetadata] != hostedcert.OutcomeInconclusive {
+ t.Errorf("nothing to try shows nothing: %v", got)
+ }
+ s := seams(&sandboxNet{}, offline)
+ s.ReadFile = func(string) ([]byte, error) { return nil, os.ErrPermission }
+ if got := outcomes(hostedcert.RunSandboxProbes(context.Background(), targets(), s)); got[hostedcert.ProbeSandboxGoTree] != hostedcert.OutcomeBlocked {
+ t.Errorf("an unreadable Go tree: %s = %q, want blocked", hostedcert.ProbeSandboxGoTree, got[hostedcert.ProbeSandboxGoTree])
+ }
+}
+
+// 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.
+func TestRunInSandbox(t *testing.T) {
+ ok, _ := json.Marshal(hostedcert.RunSandboxProbes(context.Background(), targets(), seams(&sandboxNet{}, offline)))
+ var argv []string
+ run := func(out []byte, exit int, err error) hostedcert.SandboxRunner {
+ return func(_ context.Context, a []string) ([]byte, int, error) { argv = a; return out, exit, err }
+ }
+ res := hostedcert.RunInSandbox(context.Background(), run(ok, 0, nil), "/usr/local/bin/equipo-runner", targets())
+ if len(argv) != 3 || argv[0] != "/usr/local/bin/equipo-runner" || argv[1] != hostedcert.SandboxSubcommand || !strings.Contains(argv[2], "10.42.1.10:8443") {
+ t.Errorf("argv = %q", argv)
+ }
+ if outcomes(res)[hostedcert.ProbeSandboxIPv4] != hostedcert.OutcomeBlocked {
+ t.Errorf("results = %+v", res)
+ }
+ user, _ := json.Marshal([]hostedcert.ProbeResult{{Name: hostedcert.ProbeSandboxIPv4, Stage: hostedcert.StageUser, Outcome: hostedcert.OutcomeBlocked}})
+ for name, r := range map[string]hostedcert.SandboxRunner{
+ "no sandbox": run(nil, -1, errors.New("bwrap missing")),
+ "exit 1": run(ok, 1, nil),
+ "not JSON": run([]byte("hello"), 0, nil),
+ "another stage": run(user, 0, nil),
+ "trailing output": run(append(bytes.Clone(ok), []byte("[]")...), 0, nil),
+ } {
+ res := hostedcert.RunInSandbox(context.Background(), r, "/usr/local/bin/equipo-runner", targets())
+ for _, e := range hostedcert.Matrix() {
+ if e.Stage == hostedcert.StageSandbox && outcomes(res)[e.Name] != hostedcert.OutcomeInconclusive {
+ t.Errorf("%s: %s = %q, want inconclusive", name, e.Name, outcomes(res)[e.Name])
+ }
+ }
+ }
+}
+
+// TestRunContainment: the suite runs with ContainmentArgs, its binary is
+// measured, and its verbose output is counted.
+func TestRunContainment(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "containment.test")
+ if err := os.WriteFile(path, []byte("suite"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ 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"
+ c := hostedcert.RunContainment(context.Background(), path, func(_ context.Context, a []string) (int, []byte, error) {
+ argv = a
+ return 1, []byte(out), nil
+ })
+ if c.Binary != hex.EncodeToString(sum[:]) || !slices.Equal(c.Args, hostedcert.ContainmentArgs()) ||
+ !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") {
+ 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 {
+ t.Errorf("a suite that did not run: %+v", 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.
+func TestCollect(t *testing.T) {
+ dir := t.TempDir()
+ write := func(name string, v any) {
+ raw, _ := json.Marshal(v)
+ if err := os.WriteFile(filepath.Join(dir, name), raw, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ root := []vminit.ProbeResult{}
+ for _, name := range []string{vminit.ProbeVPCDNSSilent, vminit.ProbeMetadataNoCredential, vminit.ProbeResolvConfEmpty} {
+ root = append(root, vminit.ProbeResult{Name: name, Stage: vminit.StageRoot, OK: true, Outcome: vminit.OutcomeBlocked, Detail: "x"})
+ }
+ write(hostedcert.RootProbeFile, root)
+ write(hostedcert.MeasuredFile, release.Measured)
+ write(hostedcert.ProbeTargetsFile, map[string]any{"resolvers": []string{"10.0.0.2"}, "metadata": []string{"169.254.169.254:80"}})
+ var gotTargets hostedcert.ProbeTargets
+ c := hostedcert.Collector{LaunchID: "l-1", Results: dir,
+ User: hostedcert.UserProbes{ResolvConf: "/etc/resolv.conf", OpenForWrite: func(string) error { return os.ErrPermission },
+ Capabilities: func() (uint64, error) { return 0, nil }, Raise: func() error { return syscall.EPERM },
+ ReuseCode: func(context.Context) (int, string, error) { return 403, "proxy_refused", nil },
+ Instance: func(context.Context) (int, error) { return 200, nil }},
+ Sandbox: func(ctx context.Context, pt hostedcert.ProbeTargets) []hostedcert.ProbeResult {
+ gotTargets = pt
+ tg := targets()
+ tg.Resolvers, tg.Metadata = pt.Resolvers, pt.Metadata
+ 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}
+ }}
+ r, err := c.Collect(context.Background())
+ if err != nil {
+ t.Fatalf("Collect = %v", err)
+ }
+ if len(gotTargets.Resolvers) != 1 || len(gotTargets.Metadata) != 1 {
+ t.Errorf("targets = %+v", gotTargets)
+ }
+ if err := hostedcert.Judge(r, hostedcert.Matrix()); err != nil {
+ t.Errorf("a contained VM's report: Judge = %v", err)
+ }
+ write(hostedcert.MeasuredFile, map[string]any{"runner": 1})
+ if _, err := c.Collect(context.Background()); err == nil {
+ t.Error("Collect took a measured.json that is not a map of strings")
+ }
+ if err := os.Remove(filepath.Join(dir, hostedcert.RootProbeFile)); err != nil {
+ t.Fatal(err)
+ }
+ write(hostedcert.MeasuredFile, release.Measured)
+ if _, err := c.Collect(context.Background()); err == nil {
+ t.Error("Collect ran with no root.json")
+ }
+}
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go
index f6434c00..53cc58f7 100644
--- a/internal/hostedclient/client.go
+++ b/internal/hostedclient/client.go
@@ -123,6 +123,11 @@ var refusals = map[string]struct {
"certification_images_invalid": {http.StatusUnprocessableEntity, ErrInternal},
"alert_failed": {http.StatusBadGateway, ErrProvider},
"fetch_failed": {http.StatusBadGateway, ErrProvider},
+
+ // Proxy routes only (certification reports); an instance key never
+ // gets these.
+ "identity_header": {http.StatusBadRequest, ErrBadRequest},
+ "already_reported": {http.StatusForbidden, ErrForbidden},
}
// APIError is a signed refusal from the controller. Kind is one of the
@@ -184,6 +189,15 @@ func New(cfg Config) (*Client, error) {
if os.Getenv(FlagEnv) != "1" {
return nil, ErrRunnersOff
}
+ return build(cfg)
+}
+
+// NewOperator builds a client for an operator key's routes (operator.go),
+// as New does but without EQUIPO_HOSTED_RUNNERS: it is the operator's
+// tool, not the instance.
+func NewOperator(cfg Config) (*Client, error) { return build(cfg) }
+
+func build(cfg Config) (*Client, error) {
u, err := url.Parse(cfg.BaseURL)
if err != nil {
return nil, errors.New("hostedclient: BaseURL does not parse")
diff --git a/internal/hostedclient/operator.go b/internal/hostedclient/operator.go
new file mode 100644
index 00000000..5944f6f8
--- /dev/null
+++ b/internal/hostedclient/operator.go
@@ -0,0 +1,62 @@
+package hostedclient
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+// An operator key's routes (hostedwire/ops.go), for equipo-hosted-certify.
+// Each answer is taken only when signed by the controller for its request.
+
+// CertLaunch asks for a certification VM: POST /v1/cert/launch.
+func (c *Client) CertLaunch(ctx context.Context, q hostedwire.CertLaunchRequest) (hostedwire.JobView, error) {
+ var v hostedwire.JobView
+ if err := c.call(ctx, "cert_launch", http.MethodPost, "/v1/cert/launch", q, &v); err != nil {
+ return hostedwire.JobView{}, err
+ }
+ if v.LaunchID == "" {
+ return hostedwire.JobView{}, fmt.Errorf("%w: cert_launch: the view names no launch", ErrBadResponse)
+ }
+ return v, nil
+}
+
+// Evidence reads a certification launch's signed evidence:
+// GET /v1/cert/evidence/{launch}. Before the report is in it is an
+// *APIError of kind ErrNotFound. The evidence itself is not verified here:
+// the offline judge verifies it against a controller key it is given.
+func (c *Client) Evidence(ctx context.Context, launch string) (hostedcert.SignedEvidence, error) {
+ if launch == "" || launch == "." || launch == ".." {
+ return hostedcert.SignedEvidence{}, errors.New("hostedclient: launch ID must not be empty, \".\" or \"..\"")
+ }
+ var se hostedcert.SignedEvidence
+ if err := c.call(ctx, "cert_evidence", http.MethodGet, "/v1/cert/evidence/"+url.PathEscape(launch), nil, &se); err != nil {
+ return hostedcert.SignedEvidence{}, err
+ }
+ return se, nil
+}
+
+// Certs lists the controller's active certificates: GET /v1/certs.
+func (c *Client) Certs(ctx context.Context) (hostedwire.CertsResponse, error) {
+ var r hostedwire.CertsResponse
+ return r, c.call(ctx, "certs", http.MethodGet, "/v1/certs", nil, &r)
+}
+
+// Reload has the controller fetch and re-read its certificate files:
+// POST /v1/admin/reload.
+func (c *Client) Reload(ctx context.Context) (hostedwire.ReloadResponse, error) {
+ var r hostedwire.ReloadResponse
+ return r, c.call(ctx, "reload", http.MethodPost, "/v1/admin/reload", hostedwire.ReloadRequest{}, &r)
+}
+
+// AlertTest has the controller send one test alert:
+// POST /v1/admin/alert-test.
+func (c *Client) AlertTest(ctx context.Context) (hostedwire.AlertTestResponse, error) {
+ var r hostedwire.AlertTestResponse
+ return r, c.call(ctx, "alert_test", http.MethodPost, "/v1/admin/alert-test", hostedwire.AlertTestRequest{}, &r)
+}
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go
index 41972c55..6d9bd9bb 100644
--- a/internal/hostedctl/controller.go
+++ b/internal/hostedctl/controller.go
@@ -2,6 +2,7 @@ package hostedctl
import (
"context"
+ "crypto/ed25519"
"errors"
"log/slog"
"net/netip"
@@ -102,6 +103,9 @@ type Controller struct {
proxies atomic.Pointer[[]hostedwire.KeyID]
// restart is the Handler's restart hook (ops.go), or nil.
restart atomic.Pointer[func()]
+ // signing is the Handler's signing key, which also signs
+ // certification evidence (proxy.go), or nil before Handler.
+ signing atomic.Pointer[ed25519.PrivateKey]
// beforeMark, when set, runs in dispatch after its gates pass and just
// before the dispatch marker is recorded. Tests use it to hold the store
// there; production leaves it nil.
diff --git a/internal/hostedctl/ctlcert/report.go b/internal/hostedctl/ctlcert/report.go
new file mode 100644
index 00000000..6e3d64ea
--- /dev/null
+++ b/internal/hostedctl/ctlcert/report.go
@@ -0,0 +1,304 @@
+package ctlcert
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/x509"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// Certification reports (plan Task 13). A certification VM signs its
+// report with its proxy certificate's key and sends it through a proxy's
+// bootstrap listener to POST /v1/proxy/cert-report. The proxy only
+// forwards it: the identity is the serial the controller issued and the
+// signature by that serial's own key, never a header and never the proxy.
+// AcceptReport wraps the report in evidence whose every other field is
+// the controller's own, signs it with the controller's key, and keeps it,
+// once per launch, in cert_evidence (schema version 5).
+
+var (
+ // Refusals of a report. Each wraps ctlproxy.ErrRefused, so the API
+ // answers them as it answers a refused redemption, and the refusal's
+ // audit row is committed. ErrAlreadyReported has its own code: a VM
+ // whose first answer was lost learns its report is in, which only its
+ // own key could have signed.
+ ErrNotCertification = fmt.Errorf("%w: the launch is not a certification launch", ctlproxy.ErrRefused)
+ ErrLaunchMismatch = fmt.Errorf("%w: the report names another launch than its certificate's", ctlproxy.ErrRefused)
+ ErrReportSignature = fmt.Errorf("%w: the report is not signed by its certificate's key", ctlproxy.ErrRefused)
+ ErrAlreadyReported = fmt.Errorf("%w: the launch has already reported", ctlproxy.ErrRefused)
+ ErrProviderChanged = fmt.Errorf("%w: the provider no longer launches the image as the launch did", ctlproxy.ErrRefused)
+
+ // ErrReportRequest is a report that does not read: it wraps
+ // isolatedjob.ErrInvalid, so the API answers 400.
+ ErrReportRequest = fmt.Errorf("%w: certification report", isolatedjob.ErrInvalid)
+ // ErrIdentityHeader is a request to a proxy route that carries a
+ // header other than the signature and transport headers: no header may
+ // name a VM, a launch or a serial.
+ ErrIdentityHeader = errors.New("ctlcert: a proxy request carries a header that is not a signature or transport header")
+ // ErrNoEvidence: no evidence is kept for that launch. It wraps
+ // isolatedjob.ErrNotFound.
+ ErrNoEvidence = fmt.Errorf("%w: no certification evidence for that launch", isolatedjob.ErrNotFound)
+)
+
+// ActionReported is the audit action of an accepted report.
+const ActionReported = "cert_reported"
+
+// proxyHeaders are the header names a proxy's request may carry: its
+// signature, and what Go's HTTP client sends on its own.
+var proxyHeaders = map[string]bool{
+ hostedwire.HeaderKeyID: true, hostedwire.HeaderTimestamp: true, hostedwire.HeaderNonce: true, hostedwire.HeaderSignature: true,
+ "Content-Type": true, "Content-Length": true, "Accept-Encoding": true, "User-Agent": true,
+}
+
+// CheckProxyHeaders refuses (ErrIdentityHeader) a proxy request with any
+// other header, so none can carry an identity.
+func CheckProxyHeaders(h http.Header) error {
+ for name := range h {
+ if !proxyHeaders[http.CanonicalHeaderKey(name)] {
+ return ErrIdentityHeader
+ }
+ }
+ return nil
+}
+
+// ReportConfig is what AcceptReport takes from the controller's config.
+type ReportConfig struct {
+ // Key is the controller's signing key.
+ Key ed25519.PrivateKey
+ // ImageVersion is the provider image version a launch of an image at
+ // a size runs (Set.ImageVersion).
+ ImageVersion ImageVersions
+ // Fingerprint is the provider settings a launch of an image at a size
+ // uses now; it must equal the launch's, or the version above may not
+ // be the one the VM ran.
+ Fingerprint func(isolatedjob.ImageDigest, isolatedjob.Size) string
+ // ProxyPolicy is the proxy policy version the proxies apply.
+ ProxyPolicy int
+}
+
+// ImageVersion is the provider image version the set's certificates are
+// bound to for image at size.
+func (s *Set) ImageVersion(image isolatedjob.ImageDigest, size isolatedjob.Size) (string, bool) {
+ return s.versions(image, size)
+}
+
+// certRow is a proxy_certs row as a report reads it.
+type certRow struct {
+ ctlproxy.LaunchIdentity
+ notAfter time.Duration
+ key []byte
+}
+
+// jobRow is a jobs row as a report reads it.
+type jobRow struct {
+ ctlproxy.LaunchIdentity
+ hasRef bool
+ deadline time.Duration
+ ended bool
+ purpose, spec, services, fp string
+}
+
+// AcceptReport takes a certification report q, in tx, at now, and
+// returns the attempt it came from. It refuses (each wrapping
+// ctlproxy.ErrRefused, audited through audit), in order: a serial the
+// controller never issued; a signature that does not verify against the
+// serial's own key (ECDSA P-256, ASN.1, over SHA-256 of
+// hostedwire.CertReportMessage); a second report for the launch; a
+// revoked or expired serial; a launch that is not live for that serial's
+// VM and epoch; a launch that is not a certification launch; a report
+// naming another launch; and a launch whose provider settings have
+// changed since. A report that does
+// 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.
+func AcceptReport(ctx context.Context, tx *sql.Tx, q hostedwire.CertReport, now ctlproxy.Now, cfg ReportConfig,
+ audit ctlproxy.Audit) (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:
+ return "", errors.New("ctlcert: the controller has no report config")
+ }
+ var c certRow
+ var revoked sql.NullInt64
+ err := tx.QueryRowContext(ctx, `SELECT launch_id, attempt_id, vm_ref, epoch, not_after_t, revoked_t, public_key
+ FROM proxy_certs WHERE serial = ?`, q.Serial).Scan(&c.LaunchID, &c.AttemptID, &c.VMRef, &c.Epoch, &c.notAfter, &revoked, &c.key)
+ refuse := func(why error) (string, error) {
+ if err := audit(c.AttemptID, ctlproxy.ActionRefused, "cert-report for serial "+q.Serial+": "+why.Error()); err != nil {
+ return "", err
+ }
+ return "", fmt.Errorf("cert-report for serial %s: %w", q.Serial, why)
+ }
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return refuse(ctlproxy.ErrUnknownSerial)
+ case err != nil:
+ return "", fmt.Errorf("ctlcert: read serial: %w", err)
+ case !signedBy(c.key, q):
+ return refuse(ErrReportSignature)
+ }
+ // Signed by the serial's own key: from here the refusals tell its
+ // holder exactly why. A report already in comes first, so a VM that
+ // asks again after a lost answer (its serial now revoked by the stop)
+ // learns that.
+ var n int
+ if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM cert_evidence WHERE launch_id = ?`, c.LaunchID).Scan(&n); err != nil {
+ return "", fmt.Errorf("ctlcert: read evidence: %w", err)
+ }
+ if n != 0 {
+ return refuse(ErrAlreadyReported)
+ }
+ switch {
+ case revoked.Valid:
+ return refuse(ctlproxy.ErrRevoked)
+ case now.T >= c.notAfter:
+ return refuse(ctlproxy.ErrCertExpired)
+ }
+ j, found, err := loadJob(ctx, tx, c.LaunchID)
+ switch {
+ case err != nil:
+ return "", err
+ case !found || !j.hasRef || j.ended || now.T >= j.deadline || j.AttemptID != c.AttemptID || j.VMRef != c.VMRef || j.Epoch != c.Epoch:
+ return refuse(ctlproxy.ErrNotLive)
+ case j.purpose != hostedwire.PurposeCertification:
+ return refuse(ErrNotCertification)
+ }
+ var r hostedcert.Report
+ if err := hostedwire.DecodeStrict(bytes.NewReader(q.Report), &r); err != nil {
+ return "", fmt.Errorf("%w: %v", ErrReportRequest, err)
+ }
+ if err := r.Check(); err != nil {
+ return "", fmt.Errorf("%w: %v", ErrReportRequest, err)
+ }
+ if r.LaunchID != j.LaunchID {
+ return refuse(ErrLaunchMismatch)
+ }
+ image, size, err := specImage(j.spec, j.AttemptID)
+ if err != nil {
+ return "", err
+ }
+ version, ok := cfg.ImageVersion(image, size)
+ if !ok || cfg.Fingerprint(image, size) != j.fp {
+ return refuse(ErrProviderChanged)
+ }
+ var services []hostedwire.Service
+ if err := json.Unmarshal([]byte(j.services), &services); err != nil {
+ return "", fmt.Errorf("ctlcert: saved services of %s are unreadable: %w", j.AttemptID, err)
+ }
+ id, err := newEvidenceID()
+ if err != nil {
+ return "", err
+ }
+ se, err := hostedcert.SignEvidence(hostedcert.Evidence{EvidenceID: id, LaunchID: j.LaunchID, Image: image, ImageVersion: version,
+ ProxyPolicy: cfg.ProxyPolicy, Deployment: InstanceHosts(services), Report: r, ReceivedNS: int64(now.T)}, cfg.Key)
+ if err != nil {
+ return "", 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)
+ }
+ return j.AttemptID, audit(j.AttemptID, ActionReported, fmt.Sprintf("evidence %s from serial %s", id, q.Serial))
+}
+
+// LoadEvidence returns the signed evidence kept for launchID, or
+// ErrNoEvidence.
+func LoadEvidence(ctx context.Context, tx *sql.Tx, launchID string) (hostedcert.SignedEvidence, error) {
+ var se hostedcert.SignedEvidence
+ err := tx.QueryRowContext(ctx, `SELECT evidence_json, sig FROM cert_evidence WHERE launch_id = ?`, launchID).Scan(&se.Evidence, &se.Sig)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return hostedcert.SignedEvidence{}, ErrNoEvidence
+ case err != nil:
+ return hostedcert.SignedEvidence{}, fmt.Errorf("ctlcert: read evidence: %w", err)
+ }
+ return se, nil
+}
+
+// signedBy reports whether q.Sig verifies over q's message under the
+// ECDSA P-256 key key holds (PKIX DER).
+func signedBy(key []byte, q hostedwire.CertReport) bool {
+ if len(key) == 0 {
+ return false
+ }
+ parsed, err := x509.ParsePKIXPublicKey(key)
+ pub, ok := parsed.(*ecdsa.PublicKey)
+ if err != nil || !ok || pub.Curve != elliptic.P256() {
+ return false
+ }
+ sum := sha256.Sum256(hostedwire.CertReportMessage(q.Serial, q.Report))
+ return ecdsa.VerifyASN1(pub, sum[:], q.Sig)
+}
+
+// loadJob reads the job of launchID as a report needs it. The launch has
+// ended once a stop is asked for or proven, or the VM is stopping.
+func loadJob(ctx context.Context, tx *sql.Tx, launchID string) (jobRow, bool, error) {
+ var j jobRow
+ var ref sql.NullString
+ err := tx.QueryRowContext(ctx, `SELECT launch_id, attempt_id, vm_ref, epoch, deadline_t,
+ stop_requested_t IS NOT NULL OR stop_proof_json IS NOT NULL OR state = 'stopping',
+ purpose, spec_json, services_json, provider_fingerprint FROM jobs WHERE launch_id = ?`, launchID).Scan(
+ &j.LaunchID, &j.AttemptID, &ref, &j.Epoch, &j.deadline, &j.ended, &j.purpose, &j.spec, &j.services, &j.fp)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return jobRow{}, false, nil
+ case err != nil:
+ return jobRow{}, false, fmt.Errorf("ctlcert: read launch: %w", err)
+ }
+ j.VMRef, j.hasRef = isolatedjob.Ref(ref.String), ref.Valid
+ return j, true, nil
+}
+
+// specImage reads the image and size from a saved launch spec (hostedctl's
+// storedSpec), checking it is attempt's.
+func specImage(spec, attempt string) (isolatedjob.ImageDigest, isolatedjob.Size, error) {
+ var s struct {
+ AttemptID string `json:"attempt_id"`
+ Image isolatedjob.ImageDigest `json:"image"`
+ Size isolatedjob.Size `json:"size"`
+ }
+ if err := json.Unmarshal([]byte(spec), &s); err != nil || s.AttemptID != attempt || s.Image == "" {
+ return "", "", fmt.Errorf("ctlcert: the saved spec of %s is unreadable or not its own", attempt)
+ }
+ return s.Image, s.Size, nil
+}
+
+func newEvidenceID() (string, error) {
+ b := make([]byte, 16)
+ if _, err := rand.Read(b); err != nil {
+ return "", fmt.Errorf("ctlcert: evidence ID: %w", err)
+ }
+ return "evidence-" + hex.EncodeToString(b), nil
+}
+
+// serialText is a serial as ctlproxy writes it: 1 to 40 lower-case hex
+// digits.
+func serialText(s string) bool {
+ if s == "" || len(s) > 40 {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if c := s[i]; !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/hostedctl/ctlcert/report_test.go b/internal/hostedctl/ctlcert/report_test.go
new file mode 100644
index 00000000..0c96b6e6
--- /dev/null
+++ b/internal/hostedctl/ctlcert/report_test.go
@@ -0,0 +1,474 @@
+package ctlcert_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/x509"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlops"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
+ "amadan.net/oficina/equipo/internal/hostedproxy/proxytest"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
+)
+
+// The tests drive a real controller over a fresh store and the fake
+// provider through its signed HTTP API: an operator launches a
+// certification VM, the VM redeems its proxy code, and its report comes
+// in under the proxy's key as the proxy forwards it, built with the proxy
+// harness's own fixtures (proxytest.ReportBody, proxytest.CertReport).
+
+var (
+ keyInst = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
+ keyOp = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{3}, ed25519.SeedSize))
+ keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize))
+ keyProxy = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{5}, ed25519.SeedSize))
+ ctlPub = keyCtl.Public().(ed25519.PublicKey)
+ img = isolatedjob.ImageDigest("sha256:" + strings.Repeat("a", 64))
+ wall0 = time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
+)
+
+const (
+ idInst hostedwire.KeyID = "inst-1"
+ idOp hostedwire.KeyID = "op-1"
+ idProxy hostedwire.KeyID = "proxy-1"
+ host = "equipo.example.com"
+ instCode = "aW5zdGFuY2UtY29kZS1TRUNSRVQtNGYyYTljLTAwMDE"
+)
+
+type recorder struct {
+ isolatedjob.Runner
+ mu sync.Mutex
+ specs []isolatedjob.LaunchSpec
+}
+
+func (r *recorder) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
+ r.mu.Lock()
+ r.specs = append(r.specs, s)
+ r.mu.Unlock()
+ return r.Runner.Launch(ctx, s)
+}
+
+type alerts struct{}
+
+func (alerts) Alert(context.Context, hostedctl.Alert) error { return nil }
+
+type env struct {
+ t *testing.T
+ ctx context.Context
+ clk *isolatedjobtest.FakeClock
+ fake *isolatedjob.Fake
+ rec *recorder
+ cfg hostedctl.Config
+ store *hostedctl.Store
+ c *hostedctl.Controller
+ h http.Handler
+ nonce int
+}
+
+func newEnv(t *testing.T) *env {
+ t.Helper()
+ clk := isolatedjobtest.NewFakeClock(wall0)
+ fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
+ dir := t.TempDir()
+ files := ctlops.Files{CertKeys: filepath.Join(dir, "keys.json"), Certificates: filepath.Join(dir, "certificates.json"),
+ CertificationImages: filepath.Join(dir, "images.json"), Operators: filepath.Join(dir, "operators.json")}
+ imageARN := strings.TrimSuffix(ctlcerttest.ImageVersion, ":1")
+ for path, body := range map[string]string{files.CertKeys: string(ctlcerttest.KeysJSON()),
+ files.Certificates: string(ctlcerttest.CertsJSON(ctlcerttest.Cert(img, host))),
+ files.CertificationImages: `[{"digest":"` + string(img) + `","image_arn":"` + imageARN + `","version_arn":"` + ctlcerttest.ImageVersion + `"}]`,
+ files.Operators: `{"operators":["op-1"]}`} {
+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ e := &env{t: t, ctx: context.Background(), clk: clk, fake: fake, rec: &recorder{Runner: fake},
+ cfg: hostedctl.Config{Enabled: true, Certs: ctlcert.NewSet(ctlcerttest.Versions), Candidates: ctlops.NewCandidates(ctlcerttest.Versions),
+ Files: files, ProviderNamespace: "test:account-1:region-1",
+ ProviderFingerprint: func(d isolatedjob.ImageDigest, s isolatedjob.Size) string { return "fp/" + string(d) + "/" + string(s) },
+ Manifest: ctlegress.Manifest{Services: map[string]hostedwire.Service{"instance": {Host: host, Port: 443, Class: hostedwire.ServiceInstance}},
+ Proxies: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8443")},
+ ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8444")},
+ ProxyCAPin: strings.Repeat("ab", 32)},
+ ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey()}}
+ 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)
+ if err != nil {
+ t.Fatalf("Open = %v", err)
+ }
+ t.Cleanup(func() { _ = s.Close() })
+ e.store = s
+ e.build()
+ return e
+}
+
+func (e *env) build() {
+ e.t.Helper()
+ c, err := hostedctl.New(e.cfg, hostedctl.Deps{Store: e.store, Runner: e.rec, Auditor: e.fake, Alerter: alerts{}})
+ if err != nil {
+ e.t.Fatalf("New = %v", err)
+ }
+ keys := map[hostedwire.KeyID]hostedwire.VerifyKey{
+ idInst: {Public: keyInst.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance},
+ idOp: {Public: keyOp.Public().(ed25519.PublicKey), Role: hostedwire.RoleOperator},
+ idProxy: {Public: keyProxy.Public().(ed25519.PublicKey), Role: hostedwire.RoleProxy},
+ }
+ h, err := c.Handler(hostedctl.HandlerConfig{Keys: keys, Signing: keyCtl, Wall: e.clk.Wall})
+ if err != nil {
+ e.t.Fatalf("Handler = %v", err)
+ }
+ e.c, e.h = c, h
+ if err := c.RunAudit(e.ctx); err != nil {
+ e.t.Fatalf("RunAudit = %v", err)
+ }
+}
+
+// do sends a request signed by id, with extra headers, and wants an
+// 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))
+ for k, v := range extra {
+ req.Header[k] = v
+ }
+ e.nonce++
+ nonce := fmt.Sprintf("ctlcert-test-nonce-%08d", e.nonce)
+ if err := hostedwire.SignRequest(req, raw, id, key, e.clk.Wall(), nonce); err != nil {
+ e.t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ e.h.ServeHTTP(w, req)
+ if err := hostedwire.VerifyResponse(w.Result(), w.Body.Bytes(), nonce, ctlPub); err != nil {
+ e.t.Fatalf("%s %s: answer %d %s is not signed for its request: %v", method, path, w.Code, w.Body.Bytes(), err)
+ }
+ return w.Code, w.Body.Bytes()
+}
+
+// vm is one launched VM with its proxy certificate.
+type vm struct {
+ launch, attempt string
+ ref isolatedjob.Ref
+ key *ecdsa.PrivateKey
+ serial string
+}
+
+// certVM launches a certification VM for img at size as the operator,
+// lets it run and redeems its proxy code with a fresh key.
+func (e *env) certVM(size isolatedjob.Size, at time.Duration) vm {
+ e.t.Helper()
+ body, _ := json.Marshal(hostedwire.CertLaunchRequest{Image: img, Size: size, LaunchByUnixMS: wall0.Add(at).UnixMilli()})
+ status, out := e.do(http.MethodPost, "/v1/cert/launch", body, idOp, keyOp, nil)
+ var v hostedwire.JobView
+ if status != http.StatusOK || json.Unmarshal(out, &v) != nil || v.LaunchID == "" {
+ e.t.Fatalf("cert launch = %d %s", status, out)
+ }
+ return e.redeem(v.AttemptID)
+}
+
+// checksVM launches a checks VM for img as the instance and redeems its
+// proxy code.
+func (e *env) checksVM(attempt string) vm {
+ e.t.Helper()
+ _, err := e.c.Launch(e.ctx, idInst, hostedwire.VerifyKey{Role: hostedwire.RoleInstance}, hostedctl.LaunchRequest{
+ AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: img, Size: isolatedjob.SizeSmall, MaxLifetime: time.Hour,
+ InstanceCode: instCode, Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: wall0.Add(time.Hour).UnixMilli()})
+ if err != nil {
+ e.t.Fatalf("Launch = %v", err)
+ }
+ return e.redeem(attempt)
+}
+
+func (e *env) redeem(attempt string) vm {
+ e.t.Helper()
+ e.fake.Tick()
+ if err := e.c.Refresh(e.ctx); err != nil {
+ e.t.Fatalf("Refresh = %v", err)
+ }
+ var b hostedwire.BootstrapV2
+ e.rec.mu.Lock()
+ for _, s := range e.rec.specs {
+ if s.AttemptID == attempt {
+ _ = json.Unmarshal(s.Bootstrap, &b)
+ }
+ }
+ e.rec.mu.Unlock()
+ ref := e.ref(attempt)
+ key, csr := proxytest.CSR(e.t)
+ body, _ := json.Marshal(hostedwire.RedeemRequest{LaunchID: b.LaunchID, VMRef: ref, ProxyCode: b.ProxyCode, CSR: csr})
+ status, out := e.do(http.MethodPost, "/v1/proxy/redeem", body, idProxy, keyProxy, nil)
+ var r hostedwire.RedeemResponse
+ if status != http.StatusOK || json.Unmarshal(out, &r) != nil {
+ e.t.Fatalf("redeem for %s = %d %s", attempt, status, out)
+ }
+ cert, err := x509.ParseCertificate(r.Cert)
+ if err != nil {
+ e.t.Fatal(err)
+ }
+ return vm{launch: b.LaunchID, attempt: attempt, ref: ref, key: key, serial: cert.SerialNumber.Text(16)}
+}
+
+// ref reads attempt's VM reference from the store.
+func (e *env) ref(attempt string) isolatedjob.Ref {
+ e.t.Helper()
+ var ref string
+ e.tx(func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT vm_ref FROM jobs WHERE attempt_id = ?`, attempt).Scan(&ref)
+ })
+ return isolatedjob.Ref(ref)
+}
+
+func (e *env) tx(fn func(*sql.Tx) error) {
+ e.t.Helper()
+ if err := e.store.Tx(e.ctx, fn); err != nil {
+ e.t.Fatalf("store: %v", err)
+ }
+}
+
+// report sends body as the proxy forwards a report, with extra headers.
+func (e *env) report(body []byte, extra http.Header) (int, string) {
+ e.t.Helper()
+ status, out := e.do(http.MethodPost, "/v1/proxy/cert-report", body, idProxy, keyProxy, extra)
+ var er hostedwire.ErrorResponse
+ _ = json.Unmarshal(out, &er)
+ return status, er.Code
+}
+
+// evidence reads launch's evidence as the operator: the status and, on
+// 200, the evidence opened under the controller's key.
+func (e *env) evidence(launch string) (int, hostedcert.Evidence) {
+ e.t.Helper()
+ status, out := e.do(http.MethodGet, "/v1/cert/evidence/"+launch, nil, idOp, keyOp, nil)
+ if status != http.StatusOK {
+ return status, hostedcert.Evidence{}
+ }
+ var se hostedcert.SignedEvidence
+ if err := hostedwire.DecodeStrict(bytes.NewReader(out), &se); err != nil {
+ e.t.Fatalf("evidence %s: %v", out, err)
+ }
+ ev, err := hostedcert.OpenEvidence(se, ctlPub)
+ if err != nil {
+ e.t.Fatalf("evidence does not open under the controller's key: %v", err)
+ }
+ return status, ev
+}
+
+func (e *env) lastAudit() (action, reason string) {
+ e.t.Helper()
+ e.tx(func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT action, reason FROM audit ORDER BY id DESC LIMIT 1`).Scan(&action, &reason)
+ })
+ return action, reason
+}
+
+func (e *env) evidenceRows() int {
+ e.t.Helper()
+ var n int
+ e.tx(func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT count(*) FROM cert_evidence`).Scan(&n)
+ })
+ return n
+}
+
+// wantRefused wants 403 with code and the last audit row a refusal whose
+// reason holds why.
+func (e *env) wantRefused(what string, status int, code, wantCode, why string) {
+ e.t.Helper()
+ if status != http.StatusForbidden || code != wantCode {
+ e.t.Errorf("%s = %d %s, want 403 %s", what, status, code, wantCode)
+ return
+ }
+ if action, reason := e.lastAudit(); action != ctlproxy.ActionRefused || !strings.Contains(reason, why) {
+ e.t.Errorf("%s: last audit %s %q, want a refusal naming %q", what, action, reason, why)
+ }
+}
+
+// TestReportNeedsVMKeySignature: a report counts only under its serial's
+// own key, for an issued, unrevoked serial, with no header naming
+// anything. Each refusal leaves no evidence; the good report then lands.
+func TestReportNeedsVMKeySignature(t *testing.T) {
+ e := newEnv(t)
+ v := e.certVM(isolatedjob.SizeSmall, time.Hour)
+ other := e.certVM(isolatedjob.SizeLarge, time.Hour)
+ report := proxytest.CertReport(v.launch, "first")
+
+ // Right serial, wrong key: another VM's, and a stranger's.
+ status, code := e.report(proxytest.ReportBody(t, v.serial, report, other.key), nil)
+ e.wantRefused("right serial, another VM's key", status, code, "proxy_refused", "not signed by its certificate's key")
+ stranger, _ := proxytest.CSR(t)
+ status, code = e.report(proxytest.ReportBody(t, v.serial, report, stranger), nil)
+ e.wantRefused("right serial, a stranger's key", status, code, "proxy_refused", "not signed by its certificate's key")
+ // A serial the controller never issued.
+ status, code = e.report(proxytest.ReportBody(t, "abc123", report, v.key), nil)
+ e.wantRefused("an unknown serial", status, code, "proxy_refused", "unknown serial")
+ // A proxy-supplied identity header, on a report that is otherwise good.
+ good := proxytest.ReportBody(t, v.serial, report, v.key)
+ for _, h := range []http.Header{{"X-Equipo-Launch": {v.launch}}, {"X-Forwarded-For": {"10.0.0.9"}}, {"Equipo-Serial": {v.serial}}} {
+ if status, code := e.report(good, h); status != http.StatusBadRequest || code != "identity_header" {
+ t.Errorf("a report with header %v = %d %s, want 400 identity_header", h, status, code)
+ }
+ }
+ // A revoked serial: renewal revokes the old one.
+ _, csr := proxytest.CSR(t)
+ body, _ := json.Marshal(hostedwire.RenewCertRequest{Serial: other.serial, CSR: csr})
+ if status, out := e.do(http.MethodPost, "/v1/proxy/renew", body, idProxy, keyProxy, nil); status != http.StatusOK {
+ t.Fatalf("renew = %d %s", status, out)
+ }
+ status, code = e.report(proxytest.ReportBody(t, other.serial, proxytest.CertReport(other.launch, "x"), other.key), nil)
+ e.wantRefused("a revoked serial", status, code, "proxy_refused", "revoked")
+ // A checks launch's VM may not report, and a report naming another
+ // launch is refused.
+ checks := e.checksVM("checks-1")
+ status, code = e.report(proxytest.ReportBody(t, checks.serial, proxytest.CertReport(checks.launch, "x"), checks.key), nil)
+ e.wantRefused("a checks launch", status, code, "proxy_refused", "not a certification launch")
+ status, code = e.report(proxytest.ReportBody(t, v.serial, proxytest.CertReport(other.launch, "x"), v.key), nil)
+ e.wantRefused("a report naming another launch", status, code, "proxy_refused", "names another launch")
+ if n := e.evidenceRows(); n != 0 {
+ t.Fatalf("refused reports left %d evidence rows", n)
+ }
+
+ if status, code := e.report(good, nil); status != http.StatusOK {
+ t.Fatalf("the good report = %d %s", status, code)
+ }
+ var reported int
+ e.tx(func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT count(*) FROM audit WHERE action = ? AND reason LIKE ?`,
+ ctlcert.ActionReported, "%"+v.serial+"%").Scan(&reported)
+ })
+ if reported != 1 {
+ t.Errorf("%d %s audit rows naming the serial, want 1", reported, ctlcert.ActionReported)
+ }
+ // Only an operator reads evidence.
+ if status, _ := e.do(http.MethodGet, "/v1/cert/evidence/"+v.launch, nil, idInst, keyInst, nil); status != http.StatusForbidden {
+ t.Errorf("evidence read by the instance key = %d, want 403", status)
+ }
+ if status, _ := e.evidence("no-such-launch"); status != http.StatusNotFound {
+ t.Errorf("evidence of an unknown launch = %d, want 404", status)
+ }
+}
+
+// TestReportOncePerLaunch: a launch's first report is its evidence; a
+// second, however signed, changes nothing. The accepted report stops the
+// VM, which revokes its serials.
+func TestReportOncePerLaunch(t *testing.T) {
+ e := newEnv(t)
+ v := e.certVM(isolatedjob.SizeSmall, time.Hour)
+ if status, code := e.report(proxytest.ReportBody(t, v.serial, proxytest.CertReport(v.launch, "first"), v.key), nil); status != http.StatusOK {
+ t.Fatalf("first report = %d %s", status, code)
+ }
+ _, first := e.evidence(v.launch)
+ if first.Report.Containment.Detail != "first" {
+ t.Fatalf("evidence = %+v", first)
+ }
+ status, code := e.report(proxytest.ReportBody(t, v.serial, proxytest.CertReport(v.launch, "second"), v.key), nil)
+ e.wantRefused("a second report", status, code, "already_reported", "already reported")
+ if _, again := e.evidence(v.launch); again.EvidenceID != first.EvidenceID || again.Report.Containment.Detail != "first" {
+ t.Errorf("evidence after a second report = %+v, want the first", again)
+ }
+ // The VM is stopped: its stop asked for, its serials revoked.
+ var stopReason sql.NullString
+ var unrevoked int
+ e.tx(func(tx *sql.Tx) error {
+ if err := tx.QueryRowContext(e.ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, v.attempt).Scan(&stopReason); err != nil {
+ return err
+ }
+ return tx.QueryRowContext(e.ctx, `SELECT count(*) FROM proxy_certs WHERE attempt_id = ? AND revoked_t IS NULL`, v.attempt).Scan(&unrevoked)
+ })
+ if !stopReason.Valid || unrevoked != 0 {
+ 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.)
+ 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 {
+ 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
+ })
+ return err
+ }
+ if err := accept("one"); err != nil {
+ t.Fatalf("first AcceptReport = %v", err)
+ }
+ if err := accept("two"); err == nil || !strings.Contains(err.Error(), "already reported") {
+ t.Errorf("second AcceptReport = %v, want ErrAlreadyReported", err)
+ }
+}
+
+// TestEvidenceFromLaunchRecord: every field of the evidence but the
+// report is the controller's own: the launch's image at its size's
+// version, the launch's services, the proxy policy, controller time. A
+// report cannot name an image (it has no such field, and a strict body
+// refuses one), and nothing in its measured digests changes the
+// evidence's image.
+func TestEvidenceFromLaunchRecord(t *testing.T) {
+ e := newEnv(t)
+ v := e.certVM(isolatedjob.SizeLarge, time.Hour)
+ other := isolatedjob.ImageDigest("sha256:" + strings.Repeat("b", 64))
+
+ // A report body with an image field of its own: refused as malformed.
+ var withImage map[string]any
+ _ = json.Unmarshal(proxytest.CertReport(v.launch, "x"), &withImage)
+ withImage["image"], withImage["image_version"] = string(other), "arn:aws:lambda:eu-west-1:123456789012:microvm-image:other:9"
+ raw, _ := json.Marshal(withImage)
+ if status, code := e.report(proxytest.ReportBody(t, v.serial, raw, v.key), nil); status != http.StatusBadRequest {
+ t.Errorf("a report naming an image = %d %s, want 400", status, code)
+ }
+
+ r := hostedcert.Report{LaunchID: v.launch, Root: []hostedcert.ProbeResult{}, User: []hostedcert.ProbeResult{},
+ Sandbox: []hostedcert.ProbeResult{{Name: hostedcert.ProbeSandboxIPv4, Stage: hostedcert.StageSandbox, Outcome: hostedcert.OutcomeBlocked}},
+ Measured: map[string]string{"image": string(other), hostedcert.MeasuredRunner: strings.Repeat("1", 64)}}
+ raw, _ = json.Marshal(r)
+ e.clk.AdvanceMono(time.Second)
+ e.clk.SetWall(e.clk.Wall().Add(time.Second))
+ if status, code := e.report(proxytest.ReportBody(t, v.serial, raw, v.key), nil); status != http.StatusOK {
+ t.Fatalf("report = %d %s", status, code)
+ }
+ _, ev := e.evidence(v.launch)
+ want := hostedcert.Evidence{EvidenceID: ev.EvidenceID, LaunchID: v.launch, Image: img, ImageVersion: ctlcerttest.ImageVersion,
+ ProxyPolicy: hostedwire.ProxyPolicyVersion, Deployment: []string{host}, Report: r, ReceivedNS: ev.ReceivedNS}
+ gotJSON, _ := json.Marshal(ev)
+ wantJSON, _ := json.Marshal(want)
+ if string(gotJSON) != string(wantJSON) || !strings.HasPrefix(ev.EvidenceID, "evidence-") || ev.ReceivedNS <= 0 {
+ t.Errorf("evidence = %s\nwant %s", gotJSON, wantJSON)
+ }
+
+ // A launch whose provider settings changed since it was launched may
+ // not report: the version would not be the one it ran.
+ w := e.certVM(isolatedjob.SizeSmall, 2*time.Hour)
+ e.cfg.ProviderFingerprint = func(d isolatedjob.ImageDigest, s isolatedjob.Size) string {
+ return "fp2/" + string(d) + "/" + string(s)
+ }
+ e.build()
+ 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")
+}
diff --git a/internal/hostedctl/ctlproxy/ca.go b/internal/hostedctl/ctlproxy/ca.go
index f3926276..1f3b0abb 100644
--- a/internal/hostedctl/ctlproxy/ca.go
+++ b/internal/hostedctl/ctlproxy/ca.go
@@ -440,7 +440,7 @@ func (ca *CA) Renew(ctx context.Context, tx *sql.Tx, q hostedwire.RenewCertReque
}
// issue signs a client certificate for l's identity and pub, and records
-// its serial. NotAfter is the earlier of CertLifetime and l's deadline,
+// its serial and pub. NotAfter is the earlier of CertLifetime and l's deadline,
// rounded down to the second the certificate can hold.
func (ca *CA) issue(ctx context.Context, tx *sql.Tx, l launch, pub *ecdsa.PublicKey, now Now) (hostedwire.RedeemResponse, string, error) {
notAfter := now.Wall.Add(min(CertLifetime, l.deadline-now.T)).Truncate(time.Second)
@@ -463,9 +463,15 @@ func (ca *CA) issue(ctx context.Context, tx *sql.Tx, l launch, pub *ecdsa.Public
if err != nil {
return hostedwire.RedeemResponse{}, "", fmt.Errorf("ctlproxy: sign client certificate: %w", err)
}
+ // The key is kept so a certification report signed with it can be
+ // checked against the key certified (ctlcert.AcceptReport).
+ pkix, err := x509.MarshalPKIXPublicKey(pub)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, "", fmt.Errorf("ctlproxy: encode the certificate key: %w", err)
+ }
serial, until := n.Text(16), now.T+life
- if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_certs (serial, launch_id, attempt_id, vm_ref, epoch, issued_t, not_after_t)
- VALUES (?, ?, ?, ?, ?, ?, ?)`, serial, l.LaunchID, l.AttemptID, string(l.VMRef), l.Epoch, int64(now.T), int64(until)); err != nil {
+ if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_certs (serial, launch_id, attempt_id, vm_ref, epoch, issued_t, not_after_t, public_key)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, serial, l.LaunchID, l.AttemptID, string(l.VMRef), l.Epoch, int64(now.T), int64(until), pkix); err != nil {
return hostedwire.RedeemResponse{}, "", fmt.Errorf("ctlproxy: record serial: %w", err)
}
return hostedwire.RedeemResponse{Cert: der, NotAfterNS: int64(until)}, serial, nil
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go
index 69dec0fd..69284083 100644
--- a/internal/hostedctl/http.go
+++ b/internal/hostedctl/http.go
@@ -14,6 +14,7 @@ import (
"strings"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
"amadan.net/oficina/equipo/internal/hostedctl/ctlops"
"amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
@@ -90,6 +91,8 @@ var apiErrors = []apiError{
{ctlops.ErrCandidates, http.StatusUnprocessableEntity, "certification_images_invalid", "The certification images file is not valid. The old set is kept."},
{ErrAlertFailed, http.StatusBadGateway, "alert_failed", "The test alert was not delivered."},
{ctlops.ErrFetch, http.StatusBadGateway, "fetch_failed", "The config bucket could not be read. The old sets are kept."},
+ {ctlcert.ErrIdentityHeader, http.StatusBadRequest, "identity_header", "A proxy request carries a header that is not allowed."},
+ {ctlcert.ErrAlreadyReported, http.StatusForbidden, "already_reported", "This launch has already reported."},
{ctlproxy.ErrRefused, http.StatusForbidden, "proxy_refused", "The proxy request was refused."},
{ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."},
{errNoRoute, http.StatusNotFound, "no_route", "No such route."},
@@ -172,6 +175,8 @@ var (
routeLaunch = route{"launch", http.MethodPost, hostedwire.RoleInstance, serveLaunch}
routeGet = route{"get", http.MethodGet, hostedwire.RoleInstance, serveGet}
routeVMs = route{"vms", http.MethodGet, hostedwire.RoleOperator, serveVMs}
+ // GET /v1/cert/evidence/{launch}: the launch rides in attempt.
+ routeEvidence = route{"cert_evidence", http.MethodGet, hostedwire.RoleOperator, serveEvidence}
)
// matchRoute finds r's route and the attempt its path names. Path segments
@@ -195,6 +200,8 @@ func matchRoute(r *http.Request) (route, string, error) {
rt = p
case len(seg) == 4 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "":
rt, attempt = routeGet, seg[3]
+ case len(seg) == 5 && seg[0] == "" && seg[1] == "v1" && seg[2] == "cert" && seg[3] == "evidence" && seg[4] != "":
+ rt, attempt = routeEvidence, seg[4]
case len(seg) == 5 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "":
a, ok := jobActions[seg[4]]
if !ok {
@@ -263,6 +270,8 @@ func (c *Controller) Handler(hc HandlerConfig) (http.Handler, error) {
if hc.Restart != nil {
c.restart.Store(&hc.Restart)
}
+ signing := bytes.Clone(hc.Signing)
+ c.signing.Store((*ed25519.PrivateKey)(&signing))
return &apiHandler{
c: c,
v: &hostedwire.Verifier{Keys: keys, Nonces: c.store, Now: hc.Wall},
@@ -348,6 +357,8 @@ func (h *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err = h.refuseRole(ctx, by, key.Role, rt, attempt)
case rt.method == http.MethodGet && len(body) != 0:
err = fmt.Errorf("%w: a GET takes no body", hostedwire.ErrBadJSON)
+ case rt.role == hostedwire.RoleProxy:
+ err = ctlcert.CheckProxyHeaders(r.Header) // no header names a VM, a launch or a serial
}
var out any
if err == nil {
diff --git a/internal/hostedctl/proxy.go b/internal/hostedctl/proxy.go
index d7546f95..cfcdf212 100644
--- a/internal/hostedctl/proxy.go
+++ b/internal/hostedctl/proxy.go
@@ -8,6 +8,7 @@ import (
"net/http"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
"amadan.net/oficina/equipo/internal/hostedwire"
)
@@ -18,12 +19,15 @@ import (
// GET /v1/proxy/feed (empty body) -> hostedwire.ProxyFeed
// POST /v1/proxy/redeem hostedwire.RedeemRequest -> hostedwire.RedeemResponse
// POST /v1/proxy/renew hostedwire.RenewCertRequest -> hostedwire.RedeemResponse
+// POST /v1/proxy/cert-report hostedwire.CertReport -> {} (ctlcert's)
//
-// POST /v1/proxy/cert-report is Task 13's.
+// A proxy request carrying any header but its signature and transport
+// headers is refused (ctlcert.CheckProxyHeaders, in the handler).
var proxyRoutes = map[string]route{
- "feed": {"proxy_feed", http.MethodGet, hostedwire.RoleProxy, serveFeed},
- "redeem": {"proxy_redeem", http.MethodPost, hostedwire.RoleProxy, serveRedeem},
- "renew": {"proxy_renew", http.MethodPost, hostedwire.RoleProxy, serveRenew},
+ "feed": {"proxy_feed", http.MethodGet, hostedwire.RoleProxy, serveFeed},
+ "redeem": {"proxy_redeem", http.MethodPost, hostedwire.RoleProxy, serveRedeem},
+ "renew": {"proxy_renew", http.MethodPost, hostedwire.RoleProxy, serveRenew},
+ "cert-report": {"proxy_cert_report", http.MethodPost, hostedwire.RoleProxy, serveCertReport},
}
func serveFeed(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, _ []byte) (any, error) {
@@ -52,6 +56,53 @@ 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.
+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 {
+ return nil, err
+ }
+ key := c.signing.Load()
+ if key == nil {
+ return nil, errors.New("hostedctl: no signing key for evidence")
+ }
+ cfg := ctlcert.ReportConfig{Key: *key, ImageVersion: c.cfg.Certs.ImageVersion, Fingerprint: c.cfg.ProviderFingerprint,
+ ProxyPolicy: hostedwire.ProxyPolicyVersion}
+ var attempt string
+ 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)
+ 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 err != nil {
+ c.log.Info("certification VM not yet proven stopped", "attempt", attempt, "err", err)
+ }
+ }()
+ return struct{}{}, nil
+}
+
+// serveEvidence returns the signed evidence of the launch the path names.
+func serveEvidence(ctx context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwire.VerifyKey, launch string, _ []byte) (any, error) {
+ var out any
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ se, err := ctlcert.LoadEvidence(ctx, tx, launch)
+ out = se
+ return err
+ })
+ return out, err
+}
+
// proxyTx runs fn in one transaction, at the controller time and wall clock
// read inside it, with audit rows by by. A refusal (ctlproxy.ErrRefused),
// which fn has audited, is committed and then returned.
diff --git a/internal/hostedctl/schema/0005_cert_report.sql b/internal/hostedctl/schema/0005_cert_report.sql
new file mode 100644
index 00000000..1e0c0581
--- /dev/null
+++ b/internal/hostedctl/schema/0005_cert_report.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/stop.go b/internal/hostedctl/stop.go
index 458ff310..3f6bfc12 100644
--- a/internal/hostedctl/stop.go
+++ b/internal/hostedctl/stop.go
@@ -38,6 +38,8 @@ const (
// reasonEnded: the VM ended, or the provider forgot it, with no stop
// asked for.
reasonEnded = "ended"
+ // reasonCertReported: a certification VM's one report is in.
+ reasonCertReported = "certification_reported"
)
// Audit actions written by Get, Stop and Refresh.
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go
index e621d7bd..48a00870 100644
--- a/internal/hostedctl/store.go
+++ b/internal/hostedctl/store.go
@@ -51,7 +51,7 @@ 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"}
+var migrations = []string{"schema/0001_jobs.sql", "schema/0002_egress.sql", "schema/0003_cert.sql", "schema/0004_proxy.sql", "schema/0005_cert_report.sql"}
// schemaVersion is the newest schema this code knows.
func schemaVersion() int { return len(migrations) }
diff --git a/internal/hostedproxy/proxytest/harness.go b/internal/hostedproxy/proxytest/harness.go
index e8abbaa8..f15d15f7 100644
--- a/internal/hostedproxy/proxytest/harness.go
+++ b/internal/hostedproxy/proxytest/harness.go
@@ -37,6 +37,7 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/hostedcert"
"amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
"amadan.net/oficina/equipo/internal/hostedproxy"
"amadan.net/oficina/equipo/internal/hostedwire"
@@ -985,9 +986,14 @@ func (h *Harness) CertVM(t testing.TB, launchID string) *VM {
return h.Issue(t, launchID)
}
-// CertReport is a report body naming launchID, as Task 13's Report does.
+// CertReport is a certification report (hostedcert.Report) naming
+// launchID, with note as its containment detail so two reports differ:
+// the body the real controller (ctlcert.AcceptReport) and this fake both
+// read.
func CertReport(launchID, note string) []byte {
- raw, _ := json.Marshal(map[string]string{"launch_id": launchID, "note": note})
+ raw, _ := json.Marshal(hostedcert.Report{LaunchID: launchID, Root: []hostedcert.ProbeResult{}, User: []hostedcert.ProbeResult{},
+ Sandbox: []hostedcert.ProbeResult{}, Measured: map[string]string{},
+ Containment: hostedcert.ContainmentResult{Args: hostedcert.ContainmentArgs(), Detail: note}})
return raw
}
diff --git a/internal/hostedwire/hosted.go b/internal/hostedwire/hosted.go
index 5a514ca7..8b3542f7 100644
--- a/internal/hostedwire/hosted.go
+++ b/internal/hostedwire/hosted.go
@@ -240,6 +240,18 @@ func CertReportMessage(serial string, report []byte) []byte {
return []byte("equipo-hosted-cert-report-v1\n" + serial + "\n" + hex.EncodeToString(sum[:]))
}
+// ProxyPolicyVersion is the version of the egress rules the proxies apply
+// (hostedproxy's Decide), which a certificate records as ProxyPolicy. The
+// proxies and the controller ship from one release; raise it whenever
+// those rules change, so certificates judged under the old rules no
+// longer match.
+const ProxyPolicyVersion = 1
+
+// The certification routes beside the operator routes (ops.go):
+//
+// POST /v1/proxy/cert-report CertReport -> {} (role proxy)
+// GET /v1/cert/evidence/{launch} (empty) -> hostedcert.SignedEvidence (role operator)
+
// CertLaunchRequest asks for a certification VM for one image at one
// size. LaunchByUnixMS is the wall clock (Unix milliseconds) after which
// the controller must not launch it, as in LaunchRequest.
diff --git a/internal/runner/hosted/certify.go b/internal/runner/hosted/certify.go
new file mode 100644
index 00000000..c6df0715
--- /dev/null
+++ b/internal/runner/hosted/certify.go
@@ -0,0 +1,121 @@
+package hosted
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/netip"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+// A certification launch's session (plan Task 13): the two user probes
+// that need the proxy, and the report.
+
+// ErrReport is a certification report no bootstrap listener took.
+var ErrReport = errors.New("hosted: the certification report was not taken")
+
+// Proxies returns the launch's proxy egress and bootstrap listeners, for
+// the sandbox probes to try.
+func (s *Session) Proxies() (egress, boot []netip.AddrPort) {
+ return slices.Clone(s.launch.Proxies), slices.Clone(s.launch.ProxyBoot)
+}
+
+// LaunchID is the launch the session belongs to.
+func (s *Session) LaunchID() string { return s.launch.LaunchID }
+
+// ReuseProxyCode redeems the launch's proxy code again, with a fresh key,
+// at the first bootstrap listener that answers, and returns its status
+// and error code: a used code must be refused.
+func (s *Session) ReuseProxyCode(ctx context.Context) (int, string, error) {
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return 0, "", err
+ }
+ csr, err := csrFor(key)
+ if err != nil {
+ return 0, "", err
+ }
+ body, err := json.Marshal(hostedwire.RedeemRequest{LaunchID: s.launch.LaunchID, VMRef: s.vm, ProxyCode: s.launch.ProxyCode, CSR: csr})
+ if err != nil {
+ return 0, "", err
+ }
+ last := errors.New("no bootstrap listener")
+ for _, boot := range s.launch.ProxyBoot {
+ status, out, err := postBoot(ctx, s.boot, boot, "/redeem", body)
+ if err != nil {
+ last = fmt.Errorf("bootstrap listener %s: %w", boot, err)
+ continue
+ }
+ var e hostedwire.ErrorResponse
+ _ = json.Unmarshal(out, &e)
+ return status, e.Code, nil
+ }
+ return 0, "", last
+}
+
+// InstanceProtocol asks the instance for GET /api/runner/protocol through
+// the proxy and returns the status.
+func (s *Session) InstanceProtocol(ctx context.Context) (int, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.origin+"/api/runner/protocol", nil)
+ if err != nil {
+ return 0, err
+ }
+ resp, err := s.client.Do(req)
+ if err != nil {
+ return 0, err
+ }
+ defer resp.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
+ return resp.StatusCode, nil
+}
+
+// SendReport signs report with the current proxy certificate's key (ECDSA
+// over SHA-256 of hostedwire.CertReportMessage, ASN.1) and posts it to
+// each bootstrap listener in turn until one takes it. The controller's
+// already_reported counts as taken: only this VM's key signs for its
+// serial, so the report in is this one, its first answer lost.
+func (s *Session) SendReport(ctx context.Context, report []byte) error {
+ cert := s.currentCert()
+ key, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
+ if cert.Leaf == nil || !ok {
+ return fmt.Errorf("%w: no proxy certificate", ErrReport)
+ }
+ serial := cert.Leaf.SerialNumber.Text(16)
+ sum := sha256.Sum256(hostedwire.CertReportMessage(serial, report))
+ sig, err := ecdsa.SignASN1(rand.Reader, key, sum[:])
+ if err != nil {
+ return err
+ }
+ body, err := json.Marshal(hostedwire.CertReport{Serial: serial, Report: report, Sig: sig})
+ if err != nil {
+ return err
+ }
+ last := errors.New("no bootstrap listener")
+ for _, boot := range s.launch.ProxyBoot {
+ status, out, err := postBoot(ctx, s.boot, boot, "/cert-report", body)
+ if err != nil {
+ last = fmt.Errorf("bootstrap listener %s: %w", boot, err)
+ continue
+ }
+ var e hostedwire.ErrorResponse
+ _ = json.Unmarshal(out, &e)
+ switch {
+ case status == http.StatusOK, status == http.StatusForbidden && e.Code == "already_reported":
+ return nil
+ case status >= 500:
+ last = fmt.Errorf("bootstrap listener %s answered %d %q", boot, status, e.Code)
+ continue // this proxy cannot reach the controller; the next may
+ }
+ return fmt.Errorf("%w: bootstrap listener %s answered %d %q", ErrReport, boot, status, e.Code)
+ }
+ return fmt.Errorf("%w: %w", ErrReport, last)
+}
diff --git a/internal/runner/hosted/certify_test.go b/internal/runner/hosted/certify_test.go
new file mode 100644
index 00000000..4d281fb8
--- /dev/null
+++ b/internal/runner/hosted/certify_test.go
@@ -0,0 +1,67 @@
+package hosted_test
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedproxy/proxytest"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+// TestCertifySessionThroughProxy: a certification launch's session, over
+// the real proxy, does not enrol; its used proxy code is refused when
+// tried again; the instance answers through the proxy; and its report,
+// signed with its certificate key, reaches the controller once, a second
+// send counting the first as taken.
+func TestCertifySessionThroughProxy(t *testing.T) {
+ h := proxytest.New(t)
+ f := enrolOn(h)
+ h.Controller.SetLaunch(proxytest.Launch{LaunchID: proxytest.LaunchID, AttemptID: proxytest.AttemptID, VMRef: proxytest.VMRef,
+ Epoch: proxytest.Epoch, Code: proxytest.ProxyCode, Certification: true,
+ Services: []hostedwire.Service{{Host: proxytest.Host, Port: 443, Class: hostedwire.ServiceInstance}}})
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := h.Proxy.Poll(ctx); err != nil {
+ t.Fatal(err)
+ }
+ b := bootstrap(h)
+ b.Purpose, b.InstanceCode = hostedwire.PurposeCertification, ""
+ s, err := start(t, b, t.TempDir())
+ if err != nil {
+ t.Fatalf("Start = %v", err)
+ }
+ if len(f.requests()) != 0 || s.Token() != "" {
+ t.Error("a certification session enrolled")
+ }
+ if egress, boot := s.Proxies(); !slices.Equal(egress, b.Proxies) || !slices.Equal(boot, b.ProxyBoot) || s.LaunchID() != proxytest.LaunchID {
+ t.Errorf("Proxies = %v %v, launch %s", egress, boot, s.LaunchID())
+ }
+
+ status, code, err := s.ReuseProxyCode(ctx)
+ if err != nil || status != http.StatusForbidden || code != "code_used" {
+ t.Errorf("ReuseProxyCode = %d %q %v, want the controller's 403", status, code, err)
+ }
+ if status, err := s.InstanceProtocol(ctx); err != nil || status != http.StatusOK {
+ t.Errorf("InstanceProtocol = %d %v, want 200", status, err)
+ }
+
+ report := proxytest.CertReport(proxytest.LaunchID, "probes")
+ if err := s.SendReport(ctx, report); err != nil {
+ t.Fatalf("SendReport = %v", err)
+ }
+ if r := h.Controller.Reports(); len(r) != 1 || string(r[0].Body) != string(report) || r[0].Launch.LaunchID != proxytest.LaunchID {
+ t.Fatalf("reports = %+v", r)
+ }
+ if err := s.SendReport(ctx, report); err != nil {
+ t.Errorf("a second SendReport = %v, want the first counted as taken", err)
+ }
+ if err := s.SendReport(ctx, proxytest.CertReport("another-launch", "x")); err == nil {
+ t.Error("a report naming another launch was taken")
+ }
+ if n := len(h.Controller.Reports()); n != 1 {
+ t.Errorf("the controller holds %d reports, want 1", n)
+ }
+}
diff --git a/internal/vminit/hooks.go b/internal/vminit/hooks.go
index cf71d5af..b1a62f13 100644
--- a/internal/vminit/hooks.go
+++ b/internal/vminit/hooks.go
@@ -236,6 +236,11 @@ func (h *hooks) launch(ctx context.Context, vm isolatedjob.Ref, boot hostedwire.
if err := h.writeRootJSON(RootProbeFile, probes); err != nil {
return 0, "", err
}
+ // What the runner's sandbox probes aim at: the same resolvers
+ // and endpoints, which only root init knows.
+ if err := h.writeRootJSON(ProbeTargetsFile, probeTargets{Resolvers: h.sys.resolvers, Metadata: h.cfg.Metadata}); err != nil {
+ return 0, "", err
+ }
}
// The runner's: its state directory, TMPDIR and the bootstrap.
diff --git a/internal/vminit/init_test.go b/internal/vminit/init_test.go
index a1a038d2..4ea3ad4c 100644
--- a/internal/vminit/init_test.go
+++ b/internal/vminit/init_test.go
@@ -385,7 +385,15 @@ func TestMeasurementsRootOwned(t *testing.T) {
if len(r.atStart) != 1 || fmt.Sprint(r.atStart[0]) != fmt.Sprint(want) {
t.Errorf("measured.json at the runner's launch = %v, want %v", r.atStart, want)
}
- for _, name := range []string{MeasuredFile, RootProbeFile} {
+ targets, err := os.ReadFile(filepath.Join(r.cfg.ResultsDir, ProbeTargetsFile))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var pt probeTargets
+ if err := json.Unmarshal(targets, &pt); err != nil || !slices.Equal(pt.Metadata, r.cfg.Metadata) {
+ t.Errorf("%s = %s (%v), want the metadata endpoints %v", ProbeTargetsFile, targets, err, r.cfg.Metadata)
+ }
+ for _, name := range []string{MeasuredFile, RootProbeFile, ProbeTargetsFile} {
p := filepath.Join(r.cfg.ResultsDir, name)
st, err := os.Lstat(p)
if err != nil {
@@ -1017,6 +1025,9 @@ func TestRootProbesInconclusive(t *testing.T) {
if p.OK == unsure || unsure != strings.Contains(p.Detail, "inconclusive") {
t.Errorf("%s: %+v; want ok %v and inconclusive %v", name, p, !unsure, unsure)
}
+ if want := map[bool]string{true: OutcomeInconclusive, false: OutcomeBlocked}[unsure]; p.Outcome != want {
+ t.Errorf("%s: %s outcome %q, want %q", name, p.Name, p.Outcome, want)
+ }
}
}
}
@@ -1098,6 +1109,9 @@ func TestRootProbes(t *testing.T) {
t.Errorf("%s: probe %+v, want stage root and a detail", name, p)
}
got[p.Name] = p.OK
+ if p.OK != (p.Outcome == OutcomeBlocked) || p.Outcome == "" {
+ t.Errorf("%s: probe %+v: only a passing probe is blocked", name, p)
+ }
}
w := map[string]bool{ProbeVPCDNSSilent: c.want.dns, ProbeMetadataNoCredential: c.want.meta, ProbeResolvConfEmpty: c.want.resolv}
if len(res) != 3 || fmt.Sprint(got) != fmt.Sprint(w) {
@@ -1115,6 +1129,47 @@ func TestRootProbes(t *testing.T) {
}
}
+// TestRootProbeOutcomes: each root probe's outcome says what its attempt
+// did, for the certification matrix to judge: an answer, a credential or
+// a named resolver reached; nothing to ask, or a file that cannot be
+// read, is inconclusive.
+func TestRootProbeOutcomes(t *testing.T) {
+ dir := t.TempDir()
+ empty, full := filepath.Join(dir, "resolv.conf"), filepath.Join(dir, "resolv.full")
+ if err := os.WriteFile(empty, nil, 0o444); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(full, []byte("nameserver 10.0.0.2\n"), 0o444); err != nil {
+ t.Fatal(err)
+ }
+ resolvers := []netip.Addr{netip.MustParseAddr("10.0.0.2")}
+ meta := []netip.AddrPort{netip.MustParseAddrPort("169.254.169.254:80")}
+ role := func(req *http.Request) (int, string) {
+ if req.Method == http.MethodGet {
+ return 200, "equipo-role"
+ }
+ return 404, ""
+ }
+ for name, c := range map[string]struct {
+ net *fakeNet
+ resolvers []netip.Addr
+ meta []netip.AddrPort
+ resolv string
+ want [3]string
+ }{
+ "silent": {silentNet(), resolvers, meta, empty, [3]string{OutcomeBlocked, OutcomeBlocked, OutcomeBlocked}},
+ "answered": {&fakeNet{replies: map[string][]byte{"udp 10.0.0.2:53": {1}}, web: role}, resolvers, meta, full, [3]string{OutcomeReached, OutcomeReached, OutcomeReached}},
+ "none known": {silentNet(), nil, nil, filepath.Join(dir, "none"), [3]string{OutcomeInconclusive, OutcomeInconclusive, OutcomeInconclusive}},
+ } {
+ res := rootProbes(context.Background(), c.net, c.resolvers, c.meta, c.resolv)
+ for i, p := range res {
+ if p.Outcome != c.want[i] {
+ t.Errorf("%s: %s outcome %q, want %q", name, p.Name, p.Outcome, c.want[i])
+ }
+ }
+ }
+}
+
// TestRootProbesInterrupted: a probe cut short cannot tell silence from
// the cut, so with its context ended the network probes fail.
func TestRootProbesInterrupted(t *testing.T) {
diff --git a/internal/vminit/measure.go b/internal/vminit/measure.go
index f6b1a6c2..3f390088 100644
--- a/internal/vminit/measure.go
+++ b/internal/vminit/measure.go
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"fmt"
"io"
+ "net/netip"
"os"
"syscall"
)
@@ -18,8 +19,18 @@ const (
MeasuredFile = "measured.json"
// RootProbeFile holds the root-before-drop probes ([]ProbeResult).
RootProbeFile = "root.json"
+ // ProbeTargetsFile holds, for a certification launch, the managed
+ // resolvers and metadata endpoints the runner's sandbox probes try
+ // (hostedcert.ProbeTargets).
+ ProbeTargetsFile = "probe-targets.json"
)
+// probeTargets is ProbeTargetsFile's layout.
+type probeTargets struct {
+ Resolvers []netip.Addr `json:"resolvers"`
+ Metadata []netip.AddrPort `json:"metadata"`
+}
+
// measure hashes the runner, vm-init itself and each policy file.
func measure(runner, self string, policies []string) (map[string]string, error) {
m := map[string]string{}
diff --git a/internal/vminit/rootprobe_linux.go b/internal/vminit/rootprobe_linux.go
index f059df08..7acb4a6e 100644
--- a/internal/vminit/rootprobe_linux.go
+++ b/internal/vminit/rootprobe_linux.go
@@ -19,15 +19,26 @@ import (
// ProbeResult is one certification probe's outcome. OK means the probe
// demonstrated the property it checks; a probe that could not tell (an
// error that is not a denial, an answer it did not expect) is not OK and
-// says "inconclusive". What each probe must show is for the certification
-// matrix (Task 13) to judge, not the VM.
+// says "inconclusive". Outcome is what the probe's attempt did (a query
+// answered, a credential found, a resolver named): OutcomeBlocked,
+// OutcomeReached or OutcomeInconclusive, hostedcert's values. What each
+// probe must show is for the certification matrix (hostedcert.Matrix) to
+// judge, from Outcome alone, not the VM.
type ProbeResult struct {
- Name string `json:"name"`
- Stage string `json:"stage"`
- OK bool `json:"ok"`
- Detail string `json:"detail"`
+ Name string `json:"name"`
+ Stage string `json:"stage"`
+ OK bool `json:"ok"`
+ Outcome string `json:"outcome"`
+ Detail string `json:"detail"`
}
+// A probe's outcomes (hostedcert.Outcome*; a test there holds them equal).
+const (
+ OutcomeBlocked = "blocked"
+ OutcomeReached = "reached"
+ OutcomeInconclusive = "inconclusive"
+)
+
// StageRoot marks the probes vm-init runs as root, before the runner
// starts, for a certification launch.
const StageRoot = "root"
@@ -110,6 +121,14 @@ func verdict(ctx context.Context, res ProbeResult, failed, unsure bool, notes []
notes = append([]string{inconclusive}, notes...)
}
res.OK = !failed && !unsure
+ switch {
+ case failed:
+ res.Outcome = OutcomeReached
+ case unsure:
+ res.Outcome = OutcomeInconclusive
+ default:
+ res.Outcome = OutcomeBlocked
+ }
s := strings.Join(notes, "; ")
if len(s) > maxProbeDetail {
s = s[:maxProbeDetail]
@@ -119,7 +138,7 @@ func verdict(ctx context.Context, res ProbeResult, failed, unsure bool, notes []
}
func probeDNS(ctx context.Context, n RootNet, resolvers []netip.Addr) ProbeResult {
- res := ProbeResult{Name: ProbeVPCDNSSilent, Stage: StageRoot}
+ res := ProbeResult{Name: ProbeVPCDNSSilent, Stage: StageRoot, Outcome: OutcomeInconclusive}
if len(resolvers) == 0 {
res.Detail = "no managed resolver address known"
return res
@@ -165,7 +184,7 @@ func dnsQuery(name string) []byte {
// counts when a token was issued, as IMDSv2 requires one). A 200 with a
// body names a role: a credential. Anything else is inconclusive.
func probeMetadata(ctx context.Context, n RootNet, endpoints []netip.AddrPort) ProbeResult {
- res := ProbeResult{Name: ProbeMetadataNoCredential, Stage: StageRoot}
+ res := ProbeResult{Name: ProbeMetadataNoCredential, Stage: StageRoot, Outcome: OutcomeInconclusive}
if len(endpoints) == 0 {
res.Detail = "no metadata endpoint configured"
return res
@@ -251,17 +270,19 @@ func fetch(ctx context.Context, n RootNet, method, url string, header map[string
}
func probeResolvConf(path string) ProbeResult {
- res := ProbeResult{Name: ProbeResolvConfEmpty, Stage: StageRoot}
+ // The attempt: find a resolver named in path. An empty regular file
+ // names none; anything else might.
+ res := ProbeResult{Name: ProbeResolvConfEmpty, Stage: StageRoot, Outcome: OutcomeReached}
st, err := os.Lstat(path)
switch {
case err != nil:
- res.Detail = fmt.Sprintf("%s: %s (%v)", path, inconclusive, err)
+ res.Outcome, res.Detail = OutcomeInconclusive, fmt.Sprintf("%s: %s (%v)", path, inconclusive, err)
case !st.Mode().IsRegular():
res.Detail = fmt.Sprintf("%s is not a regular file (%v)", path, st.Mode().Type())
case st.Size() != 0:
res.Detail = fmt.Sprintf("%s holds %d bytes", path, st.Size())
default:
- res.OK, res.Detail = true, path+" is empty"
+ res.OK, res.Outcome, res.Detail = true, OutcomeBlocked, path+" is empty"
}
return res
}