hostedctl: bind certificates to image versions; late expiry refused
Review round 1 of Task 3. A certificate's signed ImageVersion must be the
provider image version ("<ARN>:<version>") its digest launches with:
ctlcert refuses unbound certificates at config load and every reload
(ErrUnbound), and For admits only the certificate for the requested
size's version, before any intent is saved. A launch whose launch-by
time passes after its intent is saved is still abandoned with no
provider call, and Launch now returns ErrLaunchExpired (signed 409
launch_expired); Replay's abandonment stays a success. The admission
record's immutability trigger is tested.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+450
−69
.rastrillo/budgets.txt+1 −1cmd/equipo-hosted-controller/config.go+9 −5cmd/equipo-hosted-controller/config_test.go+51 −10docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+19 −0internal/hostedctl/admission_test.go+168 −8internal/hostedctl/ctlcert/certs.go+61 −20internal/hostedctl/ctlcert/certs_test.go+76 −7internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go+19 −5internal/hostedctl/launch.go+31 −13internal/isolatedjob/awsjob/runner.go+15 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 96eff419..86de2c1e 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 5444 9119 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. |
| +size internal/hostedctl 5462 9279 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. |
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go| index b88a27f5..96d2a942 100644 |
| --- a/cmd/equipo-hosted-controller/config.go |
| +++ b/cmd/equipo-hosted-controller/config.go |
| @@ -64,7 +64,9 @@ type fileConfig struct { |
| // with, and CertificatesFile the certificates (ctlcert.Set.Load). A |
| // checks launch needs a certificate for its image; a certificate under a |
| // key the key file does not name is withdrawn, and one that fails to |
| - // verify under a key it names stops the controller starting. |
| + // verify under a key it names, or signs an image version images does |
| + // not launch its digest with ("<arn>:<version>"), stops the controller |
| + // starting. |
| CertKeysFile string `json:"cert_keys_file"` |
| CertificatesFile string `json:"certificates_file"` |
| } |
| @@ -155,15 +157,17 @@ func (fc fileConfig) check() (config, error) { |
| if c.ctl.Manifest, err = readManifest(fc.EgressManifestFile); err != nil { |
| return config{}, err |
| } |
| - if c.ctl.Certs, err = readCerts(fc.CertKeysFile, fc.CertificatesFile); err != nil { |
| + if c.ctl.Certs, err = readCerts(fc.CertKeysFile, fc.CertificatesFile, c.aws.ImageVersion); err != nil { |
| return config{}, err |
| } |
| return c, nil |
| } |
| // readCerts reads the certificate key file and certificate file into a new |
| -// set. |
| -func readCerts(keysPath, certsPath string) (*ctlcert.Set, error) { |
| +// set bound to the adapter's image versions: a certificate whose signed |
| +// image version is not what images launches its digest with, at some size, |
| +// stops the controller starting. |
| +func readCerts(keysPath, certsPath string, versions ctlcert.ImageVersions) (*ctlcert.Set, error) { |
| keys, err := os.ReadFile(keysPath) |
| if err != nil { |
| return nil, fmt.Errorf("certificate keys: %w", err) |
| @@ -172,7 +176,7 @@ func readCerts(keysPath, certsPath string) (*ctlcert.Set, error) { |
| if err != nil { |
| return nil, fmt.Errorf("certificates: %w", err) |
| } |
| - s := ctlcert.NewSet() |
| + s := ctlcert.NewSet(versions) |
| if _, err := s.Load(keys, certs); err != nil { |
| return nil, fmt.Errorf("certificates %s (keys %s): %w", certsPath, keysPath, err) |
| } |
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go| index eece9216..b8f63e44 100644 |
| --- a/cmd/equipo-hosted-controller/config_test.go |
| +++ b/cmd/equipo-hosted-controller/config_test.go |
| @@ -17,6 +17,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlegress" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| "amadan.net/rastrillo/rastrillo/budget" |
| ) |
| @@ -56,7 +57,7 @@ func validConfig(t *testing.T, dir string) fileConfig { |
| {ID: "inst-1", Role: "instance", PublicKey: pubB64(1)}, |
| {ID: "op-1", Role: "operator", PublicKey: pubB64(2)}, |
| }, |
| - Images: []imageEntry{{Digest: testDigest, ARN: "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img", |
| + Images: []imageEntry{{Digest: testDigest, ARN: testImageARN, |
| Versions: map[string]string{"small": "1", "large": "2"}}}, |
| Region: "eu-west-1", VPCID: "vpc-1", VMSubnetID: "subnet-1", VMSecurityGroupID: "sg-1", |
| ConnectorARN: "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress:3", |
| @@ -68,13 +69,19 @@ func validConfig(t *testing.T, dir string) fileConfig { |
| } |
| } |
| -// testCert is the certificate validConfig's certificate file holds, for |
| -// testDigest at equipo.example.com. |
| -var testCert = ctlcerttest.Cert(testDigest, "equipo.example.com") |
| +// testImageARN is validConfig's image ARN; its small version is 1 and its |
| +// large version 2. |
| +const testImageARN = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img" |
| -// testCerts is a certificate set holding testCert, for tests that build a |
| -// controller directly. |
| -func testCerts() *ctlcert.Set { return ctlcerttest.Set(testCert) } |
| +// testCert is the certificate validConfig's certificate file holds: for |
| +// testDigest at its small version, at equipo.example.com. |
| +var testCert = ctlcerttest.CertAt(testDigest, testImageARN+":1", "equipo.example.com") |
| + |
| +// testCerts is a certificate set for testDigest at equipo.example.com, for |
| +// tests that build a controller directly. |
| +func testCerts() *ctlcert.Set { |
| + return ctlcerttest.Set(ctlcerttest.Cert(testDigest, "equipo.example.com")) |
| +} |
| // TestCertificatesFromConfig: the controller reads its certificate keys and |
| // certificates from the files the config names; a certificate that does not |
| @@ -87,10 +94,44 @@ func TestCertificatesFromConfig(t *testing.T) { |
| if err != nil { |
| t.Fatalf("valid config: %v", err) |
| } |
| - if got, err := c.ctl.Certs.For(testDigest, []string{"equipo.example.com"}); err != nil || |
| + if got, err := c.ctl.Certs.For(testDigest, isolatedjob.SizeSmall, []string{"equipo.example.com"}); err != nil || |
| hostedcert.Digest(got) != hostedcert.Digest(testCert) { |
| t.Fatalf("For(testDigest) = (%s, %v), want the file's certificate", hostedcert.Digest(got), err) |
| } |
| + if _, err := c.ctl.Certs.For(testDigest, isolatedjob.SizeLarge, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + t.Fatalf("For(testDigest, large) with only the small version certified = %v, want ErrNotCertified", err) |
| + } |
| + |
| + // Each certificate's signed image version must be what images launches |
| + // its digest with, "<arn>:<version>", at some size. |
| + writeCerts := func(name string, certs ...hostedcert.Certificate) string { |
| + p := filepath.Join(dir, name) |
| + if err := os.WriteFile(p, ctlcerttest.CertsJSON(certs...), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return p |
| + } |
| + large := ctlcerttest.CertAt(testDigest, testImageARN+":2", "equipo.example.com") |
| + fc := validConfig(t, dir) |
| + fc.CertificatesFile = writeCerts("both-sizes.json", testCert, large) |
| + if c, err := loadFC(t, dir, fc); err != nil { |
| + t.Fatalf("certificates for both sizes: %v, want them to load", err) |
| + } else if got, err := c.ctl.Certs.For(testDigest, isolatedjob.SizeLarge, []string{"equipo.example.com"}); err != nil || |
| + hostedcert.Digest(got) != hostedcert.Digest(large) { |
| + t.Fatalf("For(testDigest, large) = (%s, %v), want the large certificate", hostedcert.Digest(got), err) |
| + } |
| + other := isolatedjob.ImageDigest("sha256:" + strings.Repeat("b", 64)) |
| + for name, cert := range map[string]hostedcert.Certificate{ |
| + "another version": ctlcerttest.CertAt(testDigest, testImageARN+":3", "equipo.example.com"), |
| + "another ARN": ctlcerttest.CertAt(testDigest, "arn:aws:lambda:eu-west-1:123456789012:microvm-image:other:1", "equipo.example.com"), |
| + "digest not in images": ctlcerttest.CertAt(other, testImageARN+":1", "equipo.example.com"), |
| + } { |
| + fc := validConfig(t, dir) |
| + fc.CertificatesFile = writeCerts("unbound.json", testCert, cert) |
| + if _, err := loadFC(t, dir, fc); !errors.Is(err, ctlcert.ErrUnbound) { |
| + t.Errorf("%s: config load = %v, want ErrUnbound", name, err) |
| + } |
| + } |
| bad := testCert |
| bad.Sig = bytes.Clone(bad.Sig) |
| @@ -103,11 +144,11 @@ func TestCertificatesFromConfig(t *testing.T) { |
| if err := os.WriteFile(noKeys, []byte(`{"keys":[]}`), 0o600); err != nil { |
| t.Fatal(err) |
| } |
| - fc := validConfig(t, dir) |
| + fc = validConfig(t, dir) |
| fc.CertKeysFile = noKeys |
| if c, err := loadFC(t, dir, fc); err != nil { |
| t.Fatalf("no certificate keys: %v, want it to load", err) |
| - } else if _, err := c.ctl.Certs.For(testDigest, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + } else if _, err := c.ctl.Certs.For(testDigest, isolatedjob.SizeSmall, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| t.Fatalf("no certificate keys: For = %v, want ErrNotCertified", err) |
| } |
| for name, edit := range map[string]func(*fileConfig){ |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 2fa14da7..ac2722d7 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -63,3 +63,22 @@ Mutation checks (each restored with the edit reversed, then the covering tests p |
| 10. (extra) The handler's `launch_expired` entry matched `ErrDisabled` instead of `ErrLaunchExpired` (`http.go`). Command: `go test ./internal/hostedctl ./internal/hostedclient -run 'TestRoutesMapErrorsToStatus|TestClientAgainstController' -count=1`. Observed: FAIL, `http_test.go:588: lookupError(hostedctl: the launch-by time has passed) = {... status:500 code:internal ...}, want status 409 with a fixed message` and `client_test.go:256: launch past its launch-by time = hostedclient: the controller failed (launch: controller answered 500 "internal"), want ErrLaunchExpired`. Restored. |
| Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./cmd/equipo-hosted-controller -count=1` ok (TestLifecycleSimulation included; the 1a fixtures use a ctlcerttest certificate, and the simulation's requests carry a launch-by ten years past its start, since its model does not cover launch-by); `go vet -tags hostedlive` on the hostedclient, cmd and hostedctl packages ok; staticcheck v0.7.0 on the changed packages ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5444/9119. |
| + |
| +### Task 3 review round 1 (t3-r1.md: findings 1 to 3; finding 4 not acted on by ruling) |
| + |
| +1. Certificates are bound to the provider image version. `ctlcert.NewSet(versions ImageVersions)` takes the adapter's resolver (`awsjob.Config.ImageVersion(d, size)`, `"<image ARN>:<version>"`). `Replace` and `Load` refuse a certificate whose signed `ImageVersion` the provider does not launch its digest with at any size (`ErrUnbound`: no mapping, another ARN, another version), so the config load and every reload fail closed and keep the old set. `For(image, size, hosts)` resolves the version for the requested size and admits only a certificate signing exactly that version; no mapping at that size is `ErrNotCertified` before any intent is saved, so there are no futile retries. `Valid` also requires the binding. |
| +2. When the launch-by time passes after the intent is saved (in dispatch's transaction, or after the dispatch marker), the intent is still abandoned with no provider call, and `Launch` now returns `ErrLaunchExpired` with a zero view (signed 409 `launch_expired`; `hostedclient.ErrLaunchExpired`). Replay's abandonment stays a success. |
| +3. TestAdmissionRecordImmutable covers the `jobs_admission_immutable` trigger. |
| + |
| +New or changed tests: TestSetBindsImageVersion (ctlcert); TestLaunchNeedsCertificate gains "certified only at the other size", "no provider version at the size" and "certified at large"; TestLaunchByEnforced's "passes while the dispatch is recorded" now wants ErrLaunchExpired, and a new "passes while the intent is saved" subtest; TestLaunchExpiredDuringDispatchOverHTTP (raw signed 409 and the hostedclient sentinel); TestAdmissionRecordImmutable; TestCertificatesFromConfig gains both sizes, another version, another ARN and a digest not in `images`. |
| + |
| +Mutation checks (each restored, then the covering tests passed again): |
| + |
| +11. `For` ignores the image version (`false && snap.ImageVersion != version`, `ctlcert/certs.go`). Command: `go test ./internal/hostedctl/ctlcert ./internal/hostedctl ./cmd/equipo-hosted-controller -run 'TestSetBindsImageVersion|TestLaunchNeedsCertificate|TestCertificatesFromConfig' -count=1`. Observed: FAIL, `certs_test.go:61: For(imgA, large) with only the small version certified = <nil>, want ErrNotCertified`, `admission_test.go:138: TestLaunchNeedsCertificate/certified_only_at_the_other_size: Launch = ({... State:starting ...}, <nil>), want (zero view, ctlcert: no valid certificate covers this image and deployment)`, `config_test.go:102: For(testDigest, large) with only the small version certified = <nil>, want ErrNotCertified`. Restored. |
| +12. `Replace` skips the binding (`case false && !s.bound(snap)`), which config load and reload both go through. Same command. Observed: FAIL, `certs_test.go:84: another version: Replace = <nil>, want ErrUnbound` (also `:87` Load, `:90` old set not kept, for another ARN, no mapping and a bare ARN; `:94` a set with no versions), `admission_test.go:68: Replace with a version the provider does not launch = <nil>, want ErrUnbound`, `config_test.go:132: digest not in images: config load = <nil>, want ErrUnbound` (also another version, another ARN). Restored. |
| +13. The post-marker path does not report the expiry (`if false && late && !replay` in `abandonDue`). Command: `go test ./internal/hostedctl -run 'TestLaunchByEnforced|TestLaunchExpiredDuringDispatchOverHTTP' -count=1`. Observed: FAIL, `admission_test.go:424: launch expiring at dispatch = 200 {"attempt_id":"a1",...,"state":"abandoned",...}, want a signed 409 {"code":"launch_expired","message":"The launch-by time has passed."}` and `admission_test.go:317: Launch = ({... State:abandoned ...}, <nil>), want (zero view, ErrLaunchExpired)`. Restored. |
| +14. Dispatch's own transaction does not report the expiry (`if false && late && !replay` in `dispatch`). Command: `go test ./internal/hostedctl -run TestLaunchByEnforced -count=1`. Observed: FAIL, `admission_test.go:361: TestLaunchByEnforced/passes_while_the_intent_is_saved: Launch = ({... State:abandoned ...}, <nil>), want (zero view, ErrLaunchExpired)`. Restored. |
| +15. (extra) Replay reports it too (`if late` without `!replay`, in `dispatch`). Same command. Observed: FAIL, `admission_test.go:377: Replay = hostedctl: the launch-by time has passed: launch-by time 2026-12-01T00:00:00Z passed before the VM was launched (1ms after it)` (throttled) and `admission_test.go:396` (lost reply). Restored. |
| +16. The `jobs_admission_immutable` trigger removed from `schema/0003_cert.sql`. Command: `go test ./internal/hostedctl -run TestAdmissionRecordImmutable -count=1`. Observed: FAIL, `admission_test.go:482: UPDATE jobs SET cert_digest = ? = <nil>, want the immutability trigger to refuse it` (also `launch_by_unix_ms`), and `admission_test.go:489: after the updates: digest "sha256:be22...", launch-by 1796083260000; want "sha256:2ac2..." and 1796083200000`. Restored (`git diff` of the file empty). |
| + |
| +Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./cmd/equipo-hosted-controller ./internal/isolatedjob/awsjob -count=1` ok; `go vet -tags hostedlive` ok; staticcheck v0.7.0 on the changed packages ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5462/9279. |
diff --git a/internal/hostedctl/admission_test.go b/internal/hostedctl/admission_test.go| index 326d30a2..a522700a 100644 |
| --- a/internal/hostedctl/admission_test.go |
| +++ b/internal/hostedctl/admission_test.go |
| @@ -3,13 +3,17 @@ package hostedctl |
| import ( |
| "bytes" |
| "crypto/ed25519" |
| + "database/sql" |
| "errors" |
| + "net" |
| "net/http" |
| + "net/http/httptest" |
| "strings" |
| "testing" |
| "time" |
| "amadan.net/oficina/equipo/internal/hostedcert" |
| + "amadan.net/oficina/equipo/internal/hostedclient" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| @@ -44,12 +48,40 @@ func TestLaunchNeedsCertificate(t *testing.T) { |
| badSig.Sig[0] ^= 1 |
| otherDoc := ctlcerttest.Snapshot(imgA, testHosts...) |
| otherDoc.Purpose = "equipo-hosted-evidence" |
| + // The provider launches imgA at small with vSmall and at large with |
| + // vLarge; certLarge certifies only the large one. |
| + const vSmall, vLarge = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img:1", "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img:2" |
| + certLarge := ctlcerttest.CertAt(imgA, vLarge, testHosts...) |
| + bySize := func(small bool) func(e *launchEnv) { |
| + return func(e *launchEnv) { |
| + e.cfg.Certs = ctlcert.NewSet(func(d isolatedjob.ImageDigest, s isolatedjob.Size) (string, bool) { |
| + switch { |
| + case d == imgA && s == isolatedjob.SizeSmall && small: |
| + return vSmall, true |
| + case d == imgA && s == isolatedjob.SizeLarge: |
| + return vLarge, true |
| + } |
| + return "", false |
| + }) |
| + e.replaceCerts(ctlcerttest.Keys(), []hostedcert.Certificate{certLarge}) |
| + if _, err := e.cfg.Certs.Replace(ctlcerttest.Keys(), []hostedcert.Certificate{ctlcerttest.CertAt(imgA, vSmall+"9", testHosts...)}); !errors.Is(err, ctlcert.ErrUnbound) { |
| + e.t.Fatalf("Replace with a version the provider does not launch = %v, want ErrUnbound", err) |
| + } |
| + e.newController() |
| + e.audit() |
| + } |
| + } |
| cases := []struct { |
| - name string |
| - setup func(e *launchEnv) |
| - edit func(q *LaunchRequest) |
| - want error |
| + name string |
| + setup func(e *launchEnv) |
| + edit func(q *LaunchRequest) |
| + want error |
| + digest string // the certificate a launch that goes ahead is admitted under; certA() when empty |
| }{ |
| + {name: "certified only at the other size", setup: bySize(true), want: ErrNotCertified}, |
| + {name: "no provider version at the size", setup: bySize(false), want: ErrNotCertified}, |
| + {name: "certified at large", setup: bySize(true), edit: func(q *LaunchRequest) { q.Size = isolatedjob.SizeLarge }, |
| + digest: hostedcert.Digest(certLarge)}, |
| {name: "no certificate", setup: func(e *launchEnv) { e.replaceCerts(ctlcerttest.Keys(), nil) }, want: ErrNotCertified}, |
| {name: "wrong image", edit: func(q *LaunchRequest) { q.Image = imgOther }, want: ErrNotCertified}, |
| {name: "host not covered", setup: func(e *launchEnv) { |
| @@ -93,8 +125,12 @@ func TestLaunchNeedsCertificate(t *testing.T) { |
| if err != nil || v.State != JobStarting { |
| t.Fatalf("Launch = (%+v, %v), want starting", v, err) |
| } |
| - if j, _ := e.job("att-1"); j.certDigest != certA() { |
| - t.Fatalf("intent's certificate digest = %q, want %q", j.certDigest, certA()) |
| + want := tc.digest |
| + if want == "" { |
| + want = certA() |
| + } |
| + if j, _ := e.job("att-1"); j.certDigest != want { |
| + t.Fatalf("intent's certificate digest = %q, want %q", j.certDigest, want) |
| } |
| return |
| } |
| @@ -277,14 +313,58 @@ func TestLaunchByEnforced(t *testing.T) { |
| e := newLaunchEnv(t) |
| e.c.beforeMark = func() { past(e) } |
| v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) |
| - if err != nil || v.State != JobAbandoned { |
| - t.Fatalf("Launch = (%+v, %v), want abandoned", v, err) |
| + if !errors.Is(err, ErrLaunchExpired) || v != (JobView{}) { |
| + t.Fatalf("Launch = (%+v, %v), want (zero view, ErrLaunchExpired)", v, err) |
| + } |
| + if j, _ := e.job("att-1"); j.state != JobAbandoned || j.ref.Valid { |
| + t.Fatalf("att-1: %s ref %v; want abandoned with no ref", j.state, j.ref) |
| } |
| if calls := e.fake.Calls(isolatedjob.OpLaunch); calls != 0 { |
| t.Fatalf("provider launches = %d, want 0", calls) |
| } |
| }) |
| + t.Run("passes while the intent is saved", func(t *testing.T) { |
| + t.Parallel() |
| + e := newLaunchEnv(t) |
| + // Hold the store, so the launch passes its checks and then queues |
| + // for transaction 1; the launch-by time passes while it waits. |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + blocker := make(chan error, 1) |
| + go func() { |
| + blocker <- e.store.Tx(e.ctx, func(*sql.Tx) error { close(entered); <-release; return nil }) |
| + }() |
| + <-entered |
| + read := e.gc.arm() // the audit check is the launch's first clock read, after the launch-by check |
| + type result struct { |
| + v JobView |
| + err error |
| + } |
| + done := make(chan result, 1) |
| + go func() { |
| + v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) |
| + done <- result{v, err} |
| + }() |
| + select { |
| + case <-read: |
| + case <-time.After(5 * time.Second): |
| + close(release) |
| + t.Fatal("the launch did not read the clock within 5 s") |
| + } |
| + past(e) |
| + close(release) |
| + if err := <-blocker; err != nil { |
| + t.Fatalf("holding transaction = %v", err) |
| + } |
| + r := <-done |
| + if !errors.Is(r.err, ErrLaunchExpired) || r.v != (JobView{}) { |
| + t.Fatalf("Launch = (%+v, %v), want (zero view, ErrLaunchExpired)", r.v, r.err) |
| + } |
| + if j, _ := e.job("att-1"); j.state != JobAbandoned || e.fake.Calls(isolatedjob.OpLaunch) != 0 { |
| + t.Fatalf("att-1: %s, %d provider launches; want abandoned and none", j.state, e.fake.Calls(isolatedjob.OpLaunch)) |
| + } |
| + }) |
| + |
| t.Run("throttled past it, abandoned on Replay", func(t *testing.T) { |
| t.Parallel() |
| e := newLaunchEnv(t) |
| @@ -330,6 +410,86 @@ func TestLaunchByEnforced(t *testing.T) { |
| }) |
| } |
| +// TestLaunchExpiredDuringDispatchOverHTTP: a launch-by time that passes |
| +// while the dispatch is recorded is a signed 409 launch_expired over HTTP, |
| +// and hostedclient.ErrLaunchExpired to the client. Not parallel: the |
| +// client needs its flag in the environment. |
| +func TestLaunchExpiredDuringDispatchOverHTTP(t *testing.T) { |
| + past := func(e *launchEnv) { e.clk.SetWall(time.UnixMilli(testLaunchBy + 1)) } |
| + |
| + e := newAPIEnv(t, true) |
| + e.c.beforeMark = func() { past(e.launchEnv) } |
| + r := e.call("POST", "/v1/jobs", wireLaunch("a1"), idInstA, keyInstA) |
| + if r.status != http.StatusConflict || string(r.body) != fixedBody(t, "launch_expired") { |
| + t.Fatalf("launch expiring at dispatch = %d %s, want a signed 409 %s", r.status, r.body, fixedBody(t, "launch_expired")) |
| + } |
| + if j, _ := e.job("a1"); j.state != JobAbandoned || e.fake.Calls(isolatedjob.OpLaunch) != 0 { |
| + t.Fatalf("a1: %s, %d provider launches; want abandoned and none", j.state, e.fake.Calls(isolatedjob.OpLaunch)) |
| + } |
| + |
| + // The client signs with the real clock, so this handler checks request |
| + // times against it; the controller's own wall clock stays the fake one. |
| + c := newLaunchEnv(t) |
| + c.c.beforeMark = func() { past(c) } |
| + h, err := c.c.Handler(HandlerConfig{Keys: testKeys(), Signing: keyCtl, Wall: time.Now}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := httptest.NewUnstartedServer(h) |
| + srv.Listener = ln |
| + srv.StartTLS() |
| + t.Cleanup(srv.Close) |
| + t.Setenv(hostedclient.FlagEnv, "1") |
| + cl, err := hostedclient.New(hostedclient.Config{BaseURL: srv.URL, KeyID: idInstA, Key: keyInstA, |
| + ControllerKey: keyCtl.Public().(ed25519.PublicKey), HTTP: srv.Client()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var api *hostedclient.APIError |
| + if _, err := cl.Launch(c.ctx, wireLaunch("a1")); !errors.Is(err, hostedclient.ErrLaunchExpired) || !errors.As(err, &api) || |
| + api.Status != http.StatusConflict || api.Code != "launch_expired" { |
| + t.Fatalf("client launch expiring at dispatch = %v, want ErrLaunchExpired (409 launch_expired)", err) |
| + } |
| + if j, _ := c.job("a1"); j.state != JobAbandoned || c.fake.Calls(isolatedjob.OpLaunch) != 0 { |
| + t.Fatalf("a1: %s, %d provider launches; want abandoned and none", j.state, c.fake.Calls(isolatedjob.OpLaunch)) |
| + } |
| +} |
| + |
| +// TestAdmissionRecordImmutable: an intent's certificate digest and |
| +// launch-by time never change once saved (schema 0003's trigger); an |
| +// update that leaves them as they are is allowed. |
| +func TestAdmissionRecordImmutable(t *testing.T) { |
| + t.Parallel() |
| + e := newLaunchEnv(t) |
| + if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil { |
| + t.Fatalf("Launch = %v", err) |
| + } |
| + update := func(set string, args ...any) error { |
| + return e.store.Tx(e.ctx, func(tx *sql.Tx) error { |
| + _, err := tx.ExecContext(e.ctx, `UPDATE jobs SET `+set+` WHERE attempt_id = 'att-1'`, args...) |
| + return err |
| + }) |
| + } |
| + for set, args := range map[string][]any{ |
| + "cert_digest = ?": {hostedcert.Digest(ctlcerttest.Cert(imgB, testHosts...))}, |
| + "launch_by_unix_ms = ?": {testLaunchBy + 60_000}, |
| + } { |
| + if err := update(set, args...); err == nil || !strings.Contains(err.Error(), "admission record is immutable") { |
| + t.Errorf("UPDATE jobs SET %s = %v, want the immutability trigger to refuse it", set, err) |
| + } |
| + } |
| + if err := update("cert_digest = cert_digest, launch_by_unix_ms = launch_by_unix_ms, revision = revision + 1"); err != nil { |
| + t.Errorf("an update leaving both unchanged = %v, want it allowed", err) |
| + } |
| + if j, _ := e.job("att-1"); j.certDigest != certA() || j.launchBy != testLaunchBy { |
| + t.Errorf("after the updates: digest %q, launch-by %d; want %q and %d", j.certDigest, j.launchBy, certA(), int64(testLaunchBy)) |
| + } |
| +} |
| + |
| // TestLegacyIntentNeverLaunches: an intent saved before certificates (its |
| // purpose is slice 1a's "task", with no certificate and no launch-by time) |
| // is abandoned on Replay and never admitted. |
diff --git a/internal/hostedctl/ctlcert/certs.go b/internal/hostedctl/ctlcert/certs.go| index 17dece13..3f5672a6 100644 |
| --- a/internal/hostedctl/ctlcert/certs.go |
| +++ b/internal/hostedctl/ctlcert/certs.go |
| @@ -26,30 +26,61 @@ var ( |
| ErrNotCertified = errors.New("ctlcert: no valid certificate covers this image and deployment") |
| // ErrFile: a key or certificate file Load refuses. The set is unchanged. |
| ErrFile = errors.New("ctlcert: certificate files are not valid") |
| + // ErrUnbound: a certificate's signed image version is not one the |
| + // provider config launches its image with, at any size. |
| + ErrUnbound = errors.New("ctlcert: certificate's image version is not the one the provider launches") |
| ) |
| // maxKeyID bounds a signing key's ID. |
| const maxKeyID = 64 |
| +// sizes are the sizes a certificate's image version may be bound at. |
| +var sizes = []isolatedjob.Size{isolatedjob.SizeSmall, isolatedjob.SizeLarge} |
| + |
| +// ImageVersions resolves an image digest at a size to the provider image |
| +// version a launch of it runs (for AWS, the image ARN and version), the |
| +// same string a certificate's Snapshot.ImageVersion signs. ok is false |
| +// when the provider config has no version for that image and size. |
| +type ImageVersions func(isolatedjob.ImageDigest, isolatedjob.Size) (version string, ok bool) |
| + |
| // Set is the controller's current keys and certificates. Its zero value |
| // is not usable; NewSet returns an empty set, which certifies nothing. It |
| // is safe for concurrent use. |
| type Set struct { |
| - mu sync.RWMutex |
| - keys map[string]ed25519.PublicKey |
| - certs map[string]hostedcert.Certificate // by hostedcert.Digest |
| + versions ImageVersions // fixed for the set's life; the provider config does not reload |
| + mu sync.RWMutex |
| + keys map[string]ed25519.PublicKey |
| + certs map[string]hostedcert.Certificate // by hostedcert.Digest |
| } |
| -// NewSet returns an empty set. |
| -func NewSet() *Set { |
| - return &Set{keys: map[string]ed25519.PublicKey{}, certs: map[string]hostedcert.Certificate{}} |
| +// NewSet returns an empty set whose certificates are bound to the provider |
| +// image versions versions gives. A nil versions resolves nothing, so no |
| +// certificate loads. |
| +func NewSet(versions ImageVersions) *Set { |
| + if versions == nil { |
| + versions = func(isolatedjob.ImageDigest, isolatedjob.Size) (string, bool) { return "", false } |
| + } |
| + return &Set{versions: versions, keys: map[string]ed25519.PublicKey{}, certs: map[string]hostedcert.Certificate{}} |
| +} |
| + |
| +// bound reports whether snap's image version is what the provider launches |
| +// snap's image with at some size. |
| +func (s *Set) bound(snap hostedcert.Snapshot) bool { |
| + for _, size := range sizes { |
| + if v, ok := s.versions(snap.Image, size); ok && v == snap.ImageVersion { |
| + return true |
| + } |
| + } |
| + return false |
| } |
| // Replace makes keys and certs the set, all at once, and returns how many |
| // certificates it holds now. A certificate signed under a key ID keys does |
| // not hold is withdrawn: left out, not an error. Any other certificate |
| -// that fails hostedcert.Verify, or a key that is malformed, is an error, |
| -// and the set is left as it was. |
| +// that fails hostedcert.Verify, or whose image version the provider does |
| +// not launch its image with at any size (ErrUnbound: no mapping, or |
| +// another ARN or version), or a key that is malformed, is an error, and |
| +// the set is left as it was. |
| func (s *Set) Replace(keys map[string]ed25519.PublicKey, certs []hostedcert.Certificate) (int, error) { |
| nk := make(map[string]ed25519.PublicKey, len(keys)) |
| for id, k := range keys { |
| @@ -60,10 +91,14 @@ func (s *Set) Replace(keys map[string]ed25519.PublicKey, certs []hostedcert.Cert |
| } |
| nc := make(map[string]hostedcert.Certificate, len(certs)) |
| for i, c := range certs { |
| - if _, err := hostedcert.Verify(c, nk); errors.Is(err, hostedcert.ErrUnknownKey) { |
| + snap, err := hostedcert.Verify(c, nk) |
| + switch { |
| + case errors.Is(err, hostedcert.ErrUnknownKey): |
| continue |
| - } else if err != nil { |
| + case err != nil: |
| return 0, fmt.Errorf("ctlcert: certificate %d (%s): %w", i, hostedcert.Digest(c), err) |
| + case !s.bound(snap): |
| + return 0, fmt.Errorf("%w: certificate %d (%s) signs %q for image %s", ErrUnbound, i, hostedcert.Digest(c), snap.ImageVersion, snap.Image) |
| } |
| nc[hostedcert.Digest(c)] = clone(c) |
| } |
| @@ -118,18 +153,23 @@ func (s *Set) Load(keysJSON, certsJSON []byte) (int, error) { |
| return n, nil |
| } |
| -// For returns the certificate that names image and covers every host in |
| +// For returns the certificate that names image, signs the image version |
| +// the provider launches image with at size, and covers every host in |
| // hosts, verified again now under the set's keys; of several, the one |
| -// issued last (ties by digest). No hosts, or no such certificate, is |
| -// ErrNotCertified. |
| -func (s *Set) For(image isolatedjob.ImageDigest, hosts []string) (hostedcert.Certificate, error) { |
| +// issued last (ties by digest). No provider version for image at size, no |
| +// hosts, or no such certificate, is ErrNotCertified. |
| +func (s *Set) For(image isolatedjob.ImageDigest, size isolatedjob.Size, hosts []string) (hostedcert.Certificate, error) { |
| + version, ok := s.versions(image, size) |
| + if !ok { |
| + return hostedcert.Certificate{}, fmt.Errorf("%w: the provider has no version of image %s at size %s", ErrNotCertified, image, size) |
| + } |
| s.mu.RLock() |
| defer s.mu.RUnlock() |
| var best hostedcert.Certificate |
| var bestDigest string |
| for d, c := range s.certs { |
| snap, err := hostedcert.Verify(c, s.keys) |
| - if err != nil || snap.Image != image || len(hosts) == 0 || !covers(snap.Deployment, hosts) { |
| + if err != nil || snap.Image != image || snap.ImageVersion != version || len(hosts) == 0 || !covers(snap.Deployment, hosts) { |
| continue |
| } |
| if bestDigest == "" || c.IssuedAt.After(best.IssuedAt) || c.IssuedAt.Equal(best.IssuedAt) && d < bestDigest { |
| @@ -137,14 +177,15 @@ func (s *Set) For(image isolatedjob.ImageDigest, hosts []string) (hostedcert.Cer |
| } |
| } |
| if bestDigest == "" { |
| - return hostedcert.Certificate{}, fmt.Errorf("%w: image %s at %v", ErrNotCertified, image, hosts) |
| + return hostedcert.Certificate{}, fmt.Errorf("%w: image %s at size %s (%s) for %v", ErrNotCertified, image, size, version, hosts) |
| } |
| return clone(best), nil |
| } |
| // Valid reports whether the certificate with this digest is in the set |
| -// now and still verifies under the set's keys. It is false once the |
| -// certificate or its key has been removed, and for "". |
| +// now, still verifies under the set's keys and is still bound to a |
| +// provider image version. It is false once the certificate or its key has |
| +// been removed, and for "". |
| func (s *Set) Valid(digest string) bool { |
| s.mu.RLock() |
| defer s.mu.RUnlock() |
| @@ -152,8 +193,8 @@ func (s *Set) Valid(digest string) bool { |
| if !ok { |
| return false |
| } |
| - _, err := hostedcert.Verify(c, s.keys) |
| - return err == nil |
| + snap, err := hostedcert.Verify(c, s.keys) |
| + return err == nil && s.bound(snap) |
| } |
| // InstanceHosts returns the hosts of the instance-class services, in order: |
diff --git a/internal/hostedctl/ctlcert/certs_test.go b/internal/hostedctl/ctlcert/certs_test.go| index cff25f85..ed40b84c 100644 |
| --- a/internal/hostedctl/ctlcert/certs_test.go |
| +++ b/internal/hostedctl/ctlcert/certs_test.go |
| @@ -24,8 +24,77 @@ const ( |
| imgB = isolatedjob.ImageDigest("sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") |
| ) |
| +const small = isolatedjob.SizeSmall |
| + |
| var otherKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x77}, ed25519.SeedSize)) |
| +// TestSetBindsImageVersion: a certificate counts only for the provider |
| +// image version its image launches with at the size asked for. A |
| +// certificate whose signed version the provider does not launch its image |
| +// with at any size (no mapping, another ARN, another version) does not |
| +// load, and the old set stays. |
| +func TestSetBindsImageVersion(t *testing.T) { |
| + const ( |
| + arn = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img" |
| + vSmall = arn + ":1" |
| + vLarge = arn + ":2" |
| + ) |
| + versions := func(d isolatedjob.ImageDigest, s isolatedjob.Size) (string, bool) { |
| + switch { |
| + case d == imgA && s == isolatedjob.SizeSmall: |
| + return vSmall, true |
| + case d == imgA && s == isolatedjob.SizeLarge: |
| + return vLarge, true |
| + } |
| + return "", false // imgB has no mapping at any size |
| + } |
| + hosts := []string{"equipo.example.com"} |
| + certSmall := ctlcerttest.CertAt(imgA, vSmall, hosts...) |
| + s := ctlcert.NewSet(versions) |
| + if n, err := s.Replace(ctlcerttest.Keys(), []hostedcert.Certificate{certSmall}); err != nil || n != 1 { |
| + t.Fatalf("Replace with a bound certificate = (%d, %v), want 1", n, err) |
| + } |
| + if got, err := s.For(imgA, isolatedjob.SizeSmall, hosts); err != nil || hostedcert.Digest(got) != hostedcert.Digest(certSmall) { |
| + t.Fatalf("For(imgA, small) = (%s, %v), want the small certificate", hostedcert.Digest(got), err) |
| + } |
| + if _, err := s.For(imgA, isolatedjob.SizeLarge, hosts); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + t.Fatalf("For(imgA, large) with only the small version certified = %v, want ErrNotCertified", err) |
| + } |
| + if _, err := s.For(imgB, isolatedjob.SizeSmall, hosts); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + t.Fatalf("For(imgB) with no provider mapping = %v, want ErrNotCertified", err) |
| + } |
| + |
| + certLarge := ctlcerttest.CertAt(imgA, vLarge, hosts...) |
| + if _, err := s.Replace(ctlcerttest.Keys(), []hostedcert.Certificate{certSmall, certLarge}); err != nil { |
| + t.Fatalf("Replace with both sizes = %v", err) |
| + } |
| + for size, want := range map[isolatedjob.Size]hostedcert.Certificate{isolatedjob.SizeSmall: certSmall, isolatedjob.SizeLarge: certLarge} { |
| + if got, err := s.For(imgA, size, hosts); err != nil || hostedcert.Digest(got) != hostedcert.Digest(want) { |
| + t.Errorf("For(imgA, %s) = (%s, %v), want that size's certificate", size, hostedcert.Digest(got), err) |
| + } |
| + } |
| + |
| + for name, c := range map[string]hostedcert.Certificate{ |
| + "another version": ctlcerttest.CertAt(imgA, arn+":3", hosts...), |
| + "another ARN": ctlcerttest.CertAt(imgA, "arn:aws:lambda:eu-west-1:123456789012:microvm-image:other:1", hosts...), |
| + "no mapping": ctlcerttest.CertAt(imgB, vSmall, hosts...), |
| + "version as bare ARN": ctlcerttest.CertAt(imgA, arn, hosts...), |
| + } { |
| + if _, err := s.Replace(ctlcerttest.Keys(), []hostedcert.Certificate{certSmall, c}); !errors.Is(err, ctlcert.ErrUnbound) { |
| + t.Errorf("%s: Replace = %v, want ErrUnbound", name, err) |
| + } |
| + if _, err := s.Load(ctlcerttest.KeysJSON(), ctlcerttest.CertsJSON(c)); !errors.Is(err, ctlcert.ErrUnbound) { |
| + t.Errorf("%s: Load = %v, want ErrUnbound", name, err) |
| + } |
| + if !s.Valid(hostedcert.Digest(certLarge)) || s.Valid(hostedcert.Digest(c)) { |
| + t.Errorf("%s: the old set was not kept, or the unbound certificate is valid", name) |
| + } |
| + } |
| + if _, err := ctlcert.NewSet(nil).Replace(ctlcerttest.Keys(), []hostedcert.Certificate{certSmall}); !errors.Is(err, ctlcert.ErrUnbound) { |
| + t.Errorf("Replace on a set with no versions = %v, want ErrUnbound", err) |
| + } |
| +} |
| + |
| func b64(k ed25519.PrivateKey) string { |
| return base64.StdEncoding.EncodeToString(k.Public().(ed25519.PublicKey)) |
| } |
| @@ -37,7 +106,7 @@ func TestSetFor(t *testing.T) { |
| "every host": {"equipo.example.com", "team.example.org"}, |
| "one host": {"team.example.org"}, |
| } { |
| - got, err := s.For(imgA, hosts) |
| + got, err := s.For(imgA, small, hosts) |
| if err != nil || hostedcert.Digest(got) != hostedcert.Digest(a) { |
| t.Errorf("For(imgA, %s) = (%s, %v), want the certificate", name, hostedcert.Digest(got), err) |
| } |
| @@ -51,11 +120,11 @@ func TestSetFor(t *testing.T) { |
| "suffix not enough": {imgA, []string{"x.equipo.example.com"}}, |
| "no hosts": {imgA, nil}, |
| } { |
| - if _, err := s.For(q.img, q.hosts); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + if _, err := s.For(q.img, small, q.hosts); !errors.Is(err, ctlcert.ErrNotCertified) { |
| t.Errorf("%s: For = %v, want ErrNotCertified", name, err) |
| } |
| } |
| - if _, err := ctlcert.NewSet().For(imgA, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + if _, err := ctlcert.NewSet(ctlcerttest.Versions).For(imgA, small, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| t.Errorf("For on an empty set = %v, want ErrNotCertified", err) |
| } |
| @@ -63,7 +132,7 @@ func TestSetFor(t *testing.T) { |
| newer := hostedcert.Sign(ctlcerttest.Snapshot(imgA, "equipo.example.com"), ctlcerttest.KeyID, ctlcerttest.Key, |
| ctlcerttest.IssuedAt.Add(time.Hour)) |
| s = ctlcerttest.Set(a, newer) |
| - if got, err := s.For(imgA, []string{"equipo.example.com"}); err != nil || hostedcert.Digest(got) != hostedcert.Digest(newer) { |
| + if got, err := s.For(imgA, small, []string{"equipo.example.com"}); err != nil || hostedcert.Digest(got) != hostedcert.Digest(newer) { |
| t.Errorf("For with two covering = (%s, %v), want the newer %s", hostedcert.Digest(got), err, hostedcert.Digest(newer)) |
| } |
| } |
| @@ -91,7 +160,7 @@ func TestSetReplace(t *testing.T) { |
| if !s.Valid(digest) { |
| t.Errorf("%s: the old set was not kept after a failed Replace", name) |
| } |
| - if _, err := s.For(imgB, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + if _, err := s.For(imgB, small, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| t.Errorf("%s: For(imgB) = %v, want ErrNotCertified", name, err) |
| } |
| } |
| @@ -113,7 +182,7 @@ func TestSetReplace(t *testing.T) { |
| if s.Valid(digest) { |
| t.Error("Valid after its key was removed = true, want false") |
| } |
| - if _, err := s.For(imgA, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| + if _, err := s.For(imgA, small, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) { |
| t.Errorf("For after its key was removed = %v, want ErrNotCertified", err) |
| } |
| if !s.Valid(hostedcert.Digest(other)) { |
| @@ -144,7 +213,7 @@ func TestSetValid(t *testing.T) { |
| // fails leaves the set as it was. |
| func TestSetLoad(t *testing.T) { |
| a := ctlcerttest.Cert(imgA, "equipo.example.com") |
| - s := ctlcert.NewSet() |
| + s := ctlcert.NewSet(ctlcerttest.Versions) |
| n, err := s.Load(ctlcerttest.KeysJSON(), ctlcerttest.CertsJSON(a)) |
| if err != nil || n != 1 || !s.Valid(hostedcert.Digest(a)) { |
| t.Fatalf("Load = (%d, %v), valid %v; want 1 certificate, valid", n, err, s.Valid(hostedcert.Digest(a))) |
diff --git a/internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go b/internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go| index ebb9899e..726e92e1 100644 |
| --- a/internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go |
| +++ b/internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go |
| @@ -29,11 +29,18 @@ func Keys() map[string]ed25519.PublicKey { |
| return map[string]ed25519.PublicKey{KeyID: Key.Public().(ed25519.PublicKey)} |
| } |
| -// Snapshot is a valid snapshot for image covering hosts. |
| +// ImageVersion is the provider image version Versions gives every image at |
| +// every size, and the one Snapshot signs. |
| +const ImageVersion = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:test:1" |
| + |
| +// Versions resolves every image at every size to ImageVersion. |
| +func Versions(isolatedjob.ImageDigest, isolatedjob.Size) (string, bool) { return ImageVersion, true } |
| + |
| +// Snapshot is a valid snapshot for image covering hosts, at ImageVersion. |
| func Snapshot(image isolatedjob.ImageDigest, hosts ...string) hostedcert.Snapshot { |
| return hostedcert.Snapshot{ |
| Purpose: hostedcert.Purpose, Version: hostedcert.Version, Image: image, |
| - ImageVersion: "arn:aws:lambda:eu-west-1:123456789012:microvm-image:test:1", |
| + ImageVersion: ImageVersion, |
| Runner: strings.Repeat("1", 64), VMInit: strings.Repeat("2", 64), SandboxPolicy: strings.Repeat("3", 64), |
| ProxyPolicy: 1, Deps: hostedcert.DepsPrimaryBundleV1, Deployment: hosts, |
| Profile: hostedcert.ProfileVMBoundaryChecks, EvidenceID: "test-evidence", |
| @@ -45,10 +52,17 @@ func Cert(image isolatedjob.ImageDigest, hosts ...string) hostedcert.Certificate |
| return hostedcert.Sign(Snapshot(image, hosts...), KeyID, Key, IssuedAt) |
| } |
| -// Set is a certificate set with Keys and certs. It panics if they do not |
| -// load. |
| +// CertAt is Cert with the snapshot's image version set to version. |
| +func CertAt(image isolatedjob.ImageDigest, version string, hosts ...string) hostedcert.Certificate { |
| + s := Snapshot(image, hosts...) |
| + s.ImageVersion = version |
| + return hostedcert.Sign(s, KeyID, Key, IssuedAt) |
| +} |
| + |
| +// Set is a certificate set over Versions with Keys and certs. It panics if |
| +// they do not load. |
| func Set(certs ...hostedcert.Certificate) *ctlcert.Set { |
| - s := ctlcert.NewSet() |
| + s := ctlcert.NewSet(Versions) |
| if _, err := s.Replace(Keys(), certs); err != nil { |
| panic(err) |
| } |
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go| index 62bd5ed7..e5fa81fb 100644 |
| --- a/internal/hostedctl/launch.go |
| +++ b/internal/hostedctl/launch.go |
| @@ -123,8 +123,9 @@ func Deadlines(launched T, lifetime time.Duration) (deadline, drain, stop T) { |
| // or ErrBootstrapTooLarge; see checkRequest for the controller's own |
| // limits); a wall clock past q.LaunchByUnixMS (ErrLaunchExpired); a purpose |
| // whose egress services are not all set (ctlegress.ErrServiceUnset); no |
| -// certificate in Config.Certs for the image covering every instance host of |
| -// those services (ErrNotCertified); no passing network audit begun within |
| +// certificate in Config.Certs for the image, signing the provider image |
| +// version the image launches with at q.Size and covering every instance |
| +// host of those services (ErrNotCertified); no passing network audit begun within |
| // AuditMaxAge (ErrNetworkAudit). Each refusal is audited and creates |
| // nothing. |
| // |
| @@ -143,7 +144,8 @@ func Deadlines(launched T, lifetime time.Duration) (deadline, drain, stop T) { |
| // After that commit, dispatch re-reads the intent and re-checks every gate |
| // that guards VM creation, as Replay does, immediately before the provider |
| // call: a stop asked for, the stop time reached or the launch-by time |
| -// passed abandons the intent (JobAbandoned); launches off, the certificate |
| +// passed abandons the intent (JobAbandoned), and for the launch-by time |
| +// Launch returns ErrLaunchExpired and a zero view; launches off, the certificate |
| // withdrawn or no fresh passing audit |
| // leaves it JobWaiting, and Launch returns that view with a nil error. Time |
| // spent queueing for transaction 1 can let the audit go stale, so the check |
| @@ -176,7 +178,7 @@ func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hosted |
| if err != nil { |
| return c.refuse(ctx, by, q, err) |
| } |
| - cert, err := c.cfg.Certs.For(q.Image, ctlcert.InstanceHosts(services)) |
| + cert, err := c.cfg.Certs.For(q.Image, q.Size, ctlcert.InstanceHosts(services)) |
| if err != nil { |
| return c.refuse(ctx, by, q, err) |
| } |
| @@ -469,10 +471,11 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem |
| // wait for it never lets a gate that passed go stale before the call. |
| defer c.ownership.rlock()() |
| var spec isolatedjob.LaunchSpec |
| - var j jobRow // the intent as read; the attempt lock keeps its times still |
| + var j jobRow // the intent as read; the attempt lock keeps its times still |
| + var expired string // a launch-by abandonment Launch reports as ErrLaunchExpired |
| ready, changed := false, false |
| err = c.store.Tx(ctx, func(tx *sql.Tx) error { |
| - ready, changed = false, false |
| + ready, changed, expired = false, false, "" |
| var found bool |
| var err error |
| if j, found, err = loadJob(ctx, tx, attempt); err != nil { |
| @@ -489,12 +492,15 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem |
| if spec, err = decodeSpec(j.specJSON, attempt); err != nil { |
| return err |
| } |
| - reason := abandonReason(j, now, c.store.wall()) |
| + reason, late := abandonReason(j, now, c.store.wall()) |
| if fp := c.cfg.ProviderFingerprint(spec.Image, spec.Size); reason == "" && fp != j.fingerprint { |
| reason, changed = fmt.Sprintf("%s: the provider settings for image %s at size %s changed since the intent was saved (%q, now %q)", |
| reasonConfigChanged, spec.Image, spec.Size, j.fingerprint, fp), true |
| } |
| if reason != "" { |
| + if late && !replay { |
| + expired = reason |
| + } |
| view, err = abandonIntent(ctx, tx, actor, j, replay, reason, now) |
| return err |
| } |
| @@ -504,6 +510,9 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem |
| if err != nil { |
| return JobView{}, nil, err |
| } |
| + if expired != "" { |
| + return JobView{}, nil, fmt.Errorf("%w: %s", ErrLaunchExpired, expired) |
| + } |
| if changed { |
| return view, nil, c.alertConfigChanged(ctx, attempt, view) |
| } |
| @@ -733,7 +742,9 @@ func abandonIntent(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jo |
| // intent no longer waiting is returned as it stands. |
| func (c *Controller) abandonDue(ctx context.Context, actor hostedwire.KeyID, attempt string, replay bool) (JobView, error) { |
| var view JobView |
| + var expired string |
| err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| + expired = "" |
| j, found, err := loadJob(ctx, tx, attempt) |
| if err != nil { |
| return err |
| @@ -742,17 +753,23 @@ func (c *Controller) abandonDue(ctx context.Context, actor hostedwire.KeyID, att |
| return fmt.Errorf("hostedctl: launch intent %s is missing", attempt) |
| } |
| now := c.store.Clock().Now() |
| - reason := abandonReason(j, now, c.store.wall()) |
| + reason, late := abandonReason(j, now, c.store.wall()) |
| if j.state != JobWaiting || j.ref.Valid || reason == "" { |
| view = j.view(now) |
| return nil |
| } |
| + if late && !replay { |
| + expired = reason |
| + } |
| view, err = abandonIntent(ctx, tx, actor, j, replay, reason+"; found after the dispatch was recorded", now) |
| return err |
| }) |
| if err != nil { |
| return JobView{}, err |
| } |
| + if expired != "" { |
| + return JobView{}, fmt.Errorf("%w: %s", ErrLaunchExpired, expired) |
| + } |
| return view, nil |
| } |
| @@ -771,15 +788,16 @@ func (c *Controller) alertConfigChanged(ctx context.Context, attempt string, v J |
| // abandonReason returns why a waiting intent must never be launched, or "" |
| // when nothing stops it: a stop was asked for, its stop time has come, or |
| -// the wall clock is past its launch-by time. |
| -func abandonReason(j jobRow, now T, wall time.Time) string { |
| +// the wall clock is past its launch-by time (expired true). |
| +func abandonReason(j jobRow, now T, wall time.Time) (reason string, expired bool) { |
| if j.stopRequested.Valid { |
| - return "stop asked for before the VM was launched" |
| + return "stop asked for before the VM was launched", false |
| } |
| if now >= T(j.stopT) { |
| - return fmt.Sprintf("stop time passed before the VM was launched (%v after it)", time.Duration(now-T(j.stopT))) |
| + return fmt.Sprintf("stop time passed before the VM was launched (%v after it)", time.Duration(now-T(j.stopT))), false |
| } |
| - return launchExpired(j.launchBy, wall) |
| + reason = launchExpired(j.launchBy, wall) |
| + return reason, reason != "" |
| } |
| // launchExpired returns why the launch-by time launchByMS (Unix |
diff --git a/internal/isolatedjob/awsjob/runner.go b/internal/isolatedjob/awsjob/runner.go| index a8c638dd..723239da 100644 |
| --- a/internal/isolatedjob/awsjob/runner.go |
| +++ b/internal/isolatedjob/awsjob/runner.go |
| @@ -188,6 +188,21 @@ func (c Config) Fingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) strin |
| return fmt.Sprintf("region=%q connector=%q image=%q version=%q", c.Region, c.ConnectorID, img.ARN, img.Versions[s]) |
| } |
| +// ImageVersion is the provider image version a launch of d at size s runs, |
| +// as an image certificate signs it: the image ARN, ":", and the version. |
| +// ok is false when d or its size has none configured. |
| +func (c Config) ImageVersion(d isolatedjob.ImageDigest, s isolatedjob.Size) (string, bool) { |
| + img, ok := c.Images[d] |
| + if !ok { |
| + return "", false |
| + } |
| + v, ok := img.Versions[s] |
| + if !ok || img.ARN == "" || v == "" { |
| + return "", false |
| + } |
| + return img.ARN + ":" + v, true |
| +} |
| + |
| // NoIngressConnectorARN is the Lambda-provided NO_INGRESS connector in |
| // region, in the form the developer guide prints for the managed ingress |
| // connectors (doc.go, Connectors). The guide does not print this one; the |