oficina / equipo Public

hostedctl: certified images and the admission record

Image certificates (internal/hostedcert: canonical snapshot, Sign,
Verify, Digest) and the controller's certificate set
(internal/hostedctl/ctlcert) replace Config.Images. A checks launch
needs a certificate naming its image and covering every instance host
of its services snapshot; its digest and the launch-by time are kept on
the intent (schema 0003, immutable). Launch refuses a wall clock past
LaunchByUnixMS (409 launch_expired), dispatch and Replay abandon such an
intent without a provider call, and an instance key's certification
launch is refused until Task 5's operator route. GET
/v1/jobs/{attempt}/admission answers CertValid from the set at the call;
hostedclient.Admission reads it. The controller config gains
cert_keys_file and certificates_file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 3a0b3cdfe14ab0091d71c04181912244432594ec parent 4ff9161
28 files changed, +1,660 −97
  • .rastrillo/budgets.txt +1 −1
  • cmd/equipo-hosted-controller/config.go +34 −7
  • cmd/equipo-hosted-controller/config_test.go +69 −1
  • cmd/equipo-hosted-controller/crashpoint_test.go +1 −1
  • cmd/equipo-hosted-controller/main_test.go +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +23 −0
  • internal/hostedcert/cert.go +202 −0
  • internal/hostedcert/cert_test.go +199 −0
  • internal/hostedclient/client.go +24 −3
  • internal/hostedclient/client_test.go +75 −3
  • internal/hostedctl/admission.go +41 −0
  • internal/hostedctl/admission_test.go +362 −0
  • internal/hostedctl/controller.go +8 −5
  • internal/hostedctl/ctlcert/certs.go +185 −0
  • internal/hostedctl/ctlcert/certs_test.go +178 −0
  • internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go +74 −0
  • internal/hostedctl/egress_test.go +5 −1
  • internal/hostedctl/http.go +11 −2
  • internal/hostedctl/http_test.go +2 −1
  • internal/hostedctl/launch.go +89 −52
  • internal/hostedctl/launch_test.go +15 −4
  • internal/hostedctl/reaper_test.go +2 −1
  • internal/hostedctl/schema/0003_cert.sql +20 −0
  • internal/hostedctl/sim_test.go +8 −2
  • internal/hostedctl/stop.go +18 −9
  • internal/hostedctl/store.go +5 −1
  • internal/hostedctl/store_test.go +7 −2
  • internal/hostedwire/api.go +1 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 5eb47e5a..96eff419 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 5341 8729 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.
+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.
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go
index 6aea26fd..b88a27f5 100644
--- a/cmd/equipo-hosted-controller/config.go
+++ b/cmd/equipo-hosted-controller/config.go
@@ -12,6 +12,7 @@ import (
"strings"
"amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
@@ -59,6 +60,13 @@ type fileConfig struct {
// service hosts VMs may reach through the proxies, and the proxies. A
// service named but unset loads, and blocks launches until it is set.
EgressManifestFile string `json:"egress_manifest_file"`
+ // CertKeysFile names the offline keys image certificates are signed
+ // 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.
+ CertKeysFile string `json:"cert_keys_file"`
+ CertificatesFile string `json:"certificates_file"`
}
// keyEntry is one verify key: its ID, role (instance or operator) and
@@ -69,8 +77,10 @@ type keyEntry struct {
PublicKey string `json:"public_key"`
}
-// imageEntry is one certified image: its digest, MicroVM image ARN and the
-// image version for each size ("small", "large").
+// imageEntry is one image the adapter can launch: its digest, MicroVM
+// image ARN and the image version for each size ("small", "large"). A
+// checks launch of it also needs a certificate (cert_keys_file,
+// certificates_file).
type imageEntry struct {
Digest string `json:"digest"`
ARN string `json:"arn"`
@@ -126,7 +136,7 @@ func (fc fileConfig) check() (config, error) {
}
for name, v := range map[string]string{"tls_cert_file": fc.TLSCertFile, "tls_key_file": fc.TLSKeyFile,
"database": fc.Database, "signing_key_file": fc.SigningKeyFile, "sns_topic_arn": fc.SNSTopicARN,
- "egress_manifest_file": fc.EgressManifestFile} {
+ "egress_manifest_file": fc.EgressManifestFile, "cert_keys_file": fc.CertKeysFile, "certificates_file": fc.CertificatesFile} {
if v == "" {
return config{}, fmt.Errorf("%s is required", name)
}
@@ -140,18 +150,35 @@ func (fc fileConfig) check() (config, error) {
if c.aws, err = fc.awsConfig(); err != nil {
return config{}, err
}
- c.ctl.Images = map[isolatedjob.ImageDigest]bool{}
- for d := range c.aws.Images {
- c.ctl.Images[d] = true
- }
c.ctl.Egress = c.aws.Egress
c.ctl.ProviderFingerprint = c.aws.Fingerprint
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 {
+ 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) {
+ keys, err := os.ReadFile(keysPath)
+ if err != nil {
+ return nil, fmt.Errorf("certificate keys: %w", err)
+ }
+ certs, err := os.ReadFile(certsPath)
+ if err != nil {
+ return nil, fmt.Errorf("certificates: %w", err)
+ }
+ s := ctlcert.NewSet()
+ if _, err := s.Load(keys, certs); err != nil {
+ return nil, fmt.Errorf("certificates %s (keys %s): %w", certsPath, keysPath, err)
+ }
+ return s, nil
+}
+
// readManifest reads and checks the egress manifest at path.
func readManifest(path string) (ctlegress.Manifest, error) {
raw, err := os.ReadFile(path)
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go
index 39218386..eece9216 100644
--- a/cmd/equipo-hosted-controller/config_test.go
+++ b/cmd/equipo-hosted-controller/config_test.go
@@ -12,6 +12,9 @@ import (
"strings"
"testing"
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "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/hostedwire"
"amadan.net/rastrillo/rastrillo/budget"
@@ -38,6 +41,13 @@ func validConfig(t *testing.T, dir string) fileConfig {
if err := os.WriteFile(manifestPath, manifestBody("equipo.example.com"), 0o600); err != nil {
t.Fatal(err)
}
+ certKeysPath, certsPath := filepath.Join(dir, "cert-keys.json"), filepath.Join(dir, "certificates.json")
+ if err := os.WriteFile(certKeysPath, ctlcerttest.KeysJSON(), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(certsPath, ctlcerttest.CertsJSON(testCert), 0o600); err != nil {
+ t.Fatal(err)
+ }
return fileConfig{
Listen: "127.0.0.1:8443", MetricsListen: "100.119.180.57:9090",
TLSCertFile: "/etc/equipo/tls.crt", TLSKeyFile: "/etc/equipo/tls.key", Database: "/var/lib/equipo/hosted.db",
@@ -53,6 +63,64 @@ func validConfig(t *testing.T, dir string) fileConfig {
Egress: []string{},
SNSTopicARN: "arn:aws:sns:eu-west-1:123456789012:equipo-hosted",
EgressManifestFile: manifestPath,
+ CertKeysFile: certKeysPath,
+ CertificatesFile: certsPath,
+ }
+}
+
+// testCert is the certificate validConfig's certificate file holds, for
+// testDigest at equipo.example.com.
+var testCert = ctlcerttest.Cert(testDigest, "equipo.example.com")
+
+// testCerts is a certificate set holding testCert, for tests that build a
+// controller directly.
+func testCerts() *ctlcert.Set { return ctlcerttest.Set(testCert) }
+
+// TestCertificatesFromConfig: the controller reads its certificate keys and
+// certificates from the files the config names; a certificate that does not
+// verify under a key it names stops the controller from starting, and one
+// under a key it does not name is left out.
+func TestCertificatesFromConfig(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ c, err := loadFC(t, dir, validConfig(t, dir))
+ if err != nil {
+ t.Fatalf("valid config: %v", err)
+ }
+ if got, err := c.ctl.Certs.For(testDigest, []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)
+ }
+
+ bad := testCert
+ bad.Sig = bytes.Clone(bad.Sig)
+ bad.Sig[0] ^= 1
+ badPath := filepath.Join(dir, "bad-certificates.json")
+ if err := os.WriteFile(badPath, ctlcerttest.CertsJSON(bad), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ noKeys := filepath.Join(dir, "no-keys.json")
+ if err := os.WriteFile(noKeys, []byte(`{"keys":[]}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ 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) {
+ t.Fatalf("no certificate keys: For = %v, want ErrNotCertified", err)
+ }
+ for name, edit := range map[string]func(*fileConfig){
+ "bad signature": func(f *fileConfig) { f.CertificatesFile = badPath },
+ "no key file": func(f *fileConfig) { f.CertKeysFile = "" },
+ "no certificates file": func(f *fileConfig) { f.CertificatesFile = "" },
+ "missing key file": func(f *fileConfig) { f.CertKeysFile = filepath.Join(dir, "absent.json") },
+ } {
+ fc := validConfig(t, dir)
+ edit(&fc)
+ if _, err := loadFC(t, dir, fc); err == nil {
+ t.Errorf("%s: config loaded, want a refusal", name)
+ }
}
}
@@ -160,7 +228,7 @@ func TestConfigRefusesMissingListenOrKeys(t *testing.T) {
t.Fatalf("valid config: %v", err)
}
if c.listen != "127.0.0.1:8443" || len(c.keys) != 2 || c.keys["op-1"].Role != hostedwire.RoleOperator ||
- !c.ctl.Images[testDigest] || len(c.ctl.Egress) != 0 || len(c.signing) != ed25519.PrivateKeySize {
+ c.ctl.Certs == nil || len(c.ctl.Egress) != 0 || len(c.signing) != ed25519.PrivateKeySize {
t.Fatalf("valid config loaded as %+v", c)
}
if c.ctl.ProviderFingerprint == nil || c.ctl.ProviderFingerprint(testDigest, "small") != c.aws.Fingerprint(testDigest, "small") {
diff --git a/cmd/equipo-hosted-controller/crashpoint_test.go b/cmd/equipo-hosted-controller/crashpoint_test.go
index 7c7a2bba..791d902a 100644
--- a/cmd/equipo-hosted-controller/crashpoint_test.go
+++ b/cmd/equipo-hosted-controller/crashpoint_test.go
@@ -28,7 +28,7 @@ func crashCtl(t *testing.T, path string, clk *isolatedjobtest.FakeClock, run iso
t.Fatal(err)
}
t.Cleanup(func() { _ = store.Close() }) // a second Close does nothing
- c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true},
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: testCerts(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
diff --git a/cmd/equipo-hosted-controller/main_test.go b/cmd/equipo-hosted-controller/main_test.go
index 164762a4..b4cb3433 100644
--- a/cmd/equipo-hosted-controller/main_test.go
+++ b/cmd/equipo-hosted-controller/main_test.go
@@ -62,7 +62,7 @@ func newTestCtl(t *testing.T, wrap func(*isolatedjob.Fake) isolatedjob.Runner) *
t.Fatal(err)
}
t.Cleanup(func() { _ = store.Close() })
- c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true},
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: testCerts(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index f7622989..2fa14da7 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -40,3 +40,26 @@ Mutation checks after review round 1 (each run on the final code; every mutation
Review round 1 also: ErrServiceUnset answers a signed 503 `service_unset` (hostedctl `apiErrors`), and hostedclient maps it to `ErrServiceUnset`. New tests: TestServiceUnsetOverHTTP (hostedctl) and TestClientServiceUnset (hostedclient). TestManifestFromConfig loads `team.amadan.net`. Finding 1 (Replay sending services) moved to Task 4 by ruling (plan commit 17de8d2e).
Also run: `go test ./internal/hostedctl/... ./internal/hostedclient ./cmd/equipo-hosted-controller -count=1` ok (TestLifecycleSimulation and the 1a launch, HTTP and main tests, with fixtures given a manifest and the slice 2 request fields); `go vet -tags hostedlive` on the three packages ok; `make budget` ok after raising the `internal/hostedctl` record to 5341/8729; `make build vet` ok.
+
+## Task 3
+
+Image certificates and the admission record. `internal/hostedcert`: `Snapshot`, `Certificate`, `Canonical` (length-prefixed, every field in order, the deployment as a count then each host), `Sign`/`Verify` (the signature covers the canonical snapshot, the key ID and the issue time; `Verify` then holds the snapshot to the version 1 rules: purpose, version, deps, profile, digests, a non-empty deployment), `Digest`. `internal/hostedctl/ctlcert`: `Set` (`NewSet`, `Replace`, `Load` from the key and certificate files, `For`, `Valid`, `InstanceHosts`); a reload is all or nothing, except that a certificate under a key the key file no longer names is withdrawn rather than refused. `ctlcerttest` signs test certificates with a fixed key; the 1a fixtures and the simulation use it. `hostedctl`: `Config.Images` is gone, `Config.Certs` is required; `Launch` refuses a certification purpose from an instance key (ErrForbidden, until Task 5's operator route), a wall clock past `LaunchByUnixMS` (ErrLaunchExpired, 409 `launch_expired`), and a checks launch with no certificate naming the image and covering every instance host of its services snapshot (ErrNotCertified, 400 `not_certified`, replacing `image_not_allowed`). Migration `0003_cert.sql` keeps `cert_digest` and `launch_by_unix_ms` on each intent, immutable; legacy rows keep `''` and `0`, so they never launch. `dispatch` abandons an intent whose launch-by has passed, in its transaction and again after the dispatch marker, and gates on the intent's own certificate being valid now (purpose `checks` only; legacy `task` and anything else are never creatable). `Admission` and `GET /v1/jobs/{attempt}/admission` (creator only; Get's refusals, audited `admission_refused`) answer `CertValid` from `Set.Valid` at the call and `CheckedNS` in controller time. `hostedclient.Admission`, `ErrNotCertified`, `ErrLaunchExpired`. The controller config gains `cert_keys_file` and `certificates_file` (required).
+
+RED: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient -run 'TestCertificate|TestLaunchNeedsCertificate|TestAdmission|TestLaunchBy|TestClientAdmission' -count=1` failed to build: `no required module provides package .../internal/hostedctl/ctlcert/ctlcerttest` (hostedctl, ctlcert, hostedclient) and `internal/hostedcert/cert_test.go:28:17: undefined: Snapshot`.
+
+GREEN: the same command: `ok internal/hostedcert`, `ok internal/hostedctl`, `ok internal/hostedclient` (TestCertificateCanonical, TestCertificateVerifyRefusals, TestCertificateDigest, TestCertificateJSON, TestLaunchNeedsCertificate, TestAdmissionRecordsCertDigest, TestAdmissionKeyRemoved, TestAdmissionCreatorOnly, TestAdmissionOverHTTP, TestLaunchByEnforced, TestClientAdmissionVerified). Also new: TestSetFor, TestSetReplace, TestSetValid, TestSetLoad, TestInstanceHosts (ctlcert), TestLegacyIntentNeverLaunches (hostedctl), TestCertificatesFromConfig (cmd). `go test ./internal/hostedctl -run TestLifecycleSimulation -count=1`: ok.
+
+Mutation checks (each restored with the edit reversed, then the covering tests passed again):
+
+1. Leave `Deployment` out of `Canonical` (the count and the host loop removed, `internal/hostedcert/cert.go`). Command: `go test ./internal/hostedcert -run TestCertificateCanonical -count=1`. Observed: FAIL, `cert_test.go:84: Canonical ignores Deployment`, `cert_test.go:89: Verify with Deployment changed after signing = nil, want an error`, and `cert_test.go:101: Canonical with the deployment reordered equals the original` (also joined, one fewer). Restored.
+2. Cache `CertValid` from launch time: `CertValid: c.cfg.Certs.Valid(j.certDigest)` became `CertValid: j.certDigest != ""` in `internal/hostedctl/admission.go`. Command: `go test ./internal/hostedctl -run 'TestAdmissionKeyRemoved|TestAdmissionRecordsCertDigest' -count=1`. Observed: FAIL, `admission_test.go:184: Admission after the key was removed = {... CertValid:true ...}, want its digest, not valid` and `admission_test.go:164: Admission with the launch's certificate removed = {... CertValid:true ...}, want its digest, not valid`. Restored.
+3. (extra) Host coverage ignored in `Set.For` (`false && !covers(...)`, `internal/hostedctl/ctlcert/certs.go`). Command: `go test ./internal/hostedctl/ctlcert ./internal/hostedctl -run 'TestSetFor|TestLaunchNeedsCertificate' -count=1`. Observed: FAIL, `certs_test.go:55: host not covered: For = <nil>, want ErrNotCertified` (and `suffix not enough`), `admission_test.go:102: TestLaunchNeedsCertificate/host_not_covered: Launch = ({... State:starting ...}, <nil>), want (zero view, ctlcert: no valid certificate covers this image and deployment)`. Restored.
+4. (extra) Launch's launch-by check before saving the intent skipped (`false && why != ""`, `launch.go`). Command: `go test ./internal/hostedctl -run TestLaunchByEnforced -count=1`. Observed: FAIL, `admission_test.go:260: Launch past launch-by = ({... State:abandoned ...}, <nil>), want (zero view, ErrLaunchExpired)`. Restored.
+5. (extra) `abandonReason` ignores launch-by (`return ""` for `launchExpired(j.launchBy, wall)`), so Replay and dispatch's transaction do not abandon. Command: `go test ./internal/hostedctl -run 'TestLaunchByEnforced|TestLegacyIntentNeverLaunches' -count=1`. Observed: FAIL, `admission_test.go:303: att-1 after Replay: waiting ref { false}; want abandoned with no ref` (throttled), `admission_test.go:322` (lost reply, same), `admission_test.go:281: Launch = ({... State:waiting ...}, <nil>), want abandoned`, `admission_test.go:354: legacy-1 after Replay: waiting ref { false}; want abandoned`. Restored.
+6. (extra) The launch-by re-check after the dispatch marker, immediately before the provider call, dropped (`false && launchExpired(...)`). Command: `go test ./internal/hostedctl -run TestLaunchByEnforced -count=1`. Observed: FAIL, `admission_test.go:281: Launch = ({... State:starting VMRef:vm-0001 ...}, <nil>), want abandoned`. Restored.
+7. (extra) `creatable` ignores the intent's certificate (`false && (...)`). Command: `go test ./internal/hostedctl -run 'TestThrottleThenRefusal|TestReapDefersOrphansWhileIntentWaits' -count=1`. Observed: FAIL, `launch_test.go:946: TestThrottleThenRefusal/certificate_withdrawn: provider launches = 2, want 1: a failed gate calls nothing` and `reaper_test.go:765: ... OrphansStopped:1 OrphansDeferred:0 ..., want both orphans deferred` (both certificate-withdrawn cases). Restored.
+8. (extra) The purpose-aware role check skipped (`false && q.Purpose == hostedwire.PurposeCertification`). Command: `go test ./internal/hostedctl -run TestLaunchNeedsCertificate -count=1`. Observed: FAIL, `admission_test.go:102: TestLaunchNeedsCertificate/certification_launch_by_an_instance_key: Launch = ({... State:waiting ...}, <nil>), want (zero view, hostedctl: this key may not do that)`. Restored. (The saved certification intent stayed waiting: `creatable` admits only checks intents.)
+9. (extra) `hostedclient.Admission` takes a record for another attempt (`false && a.AttemptID != attempt`). Command: `go test ./internal/hostedclient -run TestClientAdmissionVerified -count=1`. Observed: FAIL, `client_test.go:321: Admission answered for another attempt = ({AttemptID:a9 ... CertValid:true ...}, <nil>), want ErrBadResponse and nothing`. Restored.
+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.
diff --git a/internal/hostedcert/cert.go b/internal/hostedcert/cert.go
new file mode 100644
index 00000000..e929ba27
--- /dev/null
+++ b/internal/hostedcert/cert.go
@@ -0,0 +1,202 @@
+// Package hostedcert is the hosted image certificate: a snapshot of what a
+// certification run proved about one image in one deployment, signed
+// offline with an ed25519 key. The controller admits a checks launch only
+// under a certificate that verifies, and the instance counts a hosted
+// result only while the controller says that certificate is still valid.
+//
+// The signature covers the whole snapshot in its canonical form
+// (Canonical), with the key ID and the issue time, never a digest alone:
+// a verifier reads every field it relies on from the signed bytes.
+package hostedcert
+
+import (
+ "crypto/ed25519"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// The fixed values of a version 1 snapshot.
+const (
+ // Purpose names the document, so a signature made for another
+ // document by the same key never passes for a certificate.
+ Purpose = "equipo-hosted-image-cert"
+ Version = 1
+ // DepsPrimaryBundleV1: dependencies come from the person's primary as
+ // a bundle checked against the base commit's pins (decision S2-1).
+ DepsPrimaryBundleV1 = "primary-bundle-v1"
+ // ProfileVMBoundaryChecks: the image runs checks steps inside the VM
+ // boundary, with no network but the egress proxies.
+ ProfileVMBoundaryChecks = "vm-boundary-checks"
+)
+
+// maxText bounds each free-text field (an image version ARN, an evidence
+// ID, a host).
+const maxText = 1024
+
+// Snapshot is what a certificate certifies.
+type Snapshot struct {
+ Purpose string `json:"purpose"` // Purpose
+ Version int `json:"version"` // Version
+ Image isolatedjob.ImageDigest `json:"image"` // the image digest launches name
+ ImageVersion string `json:"image_version"` // the provider's image version ARN the evidence ran on
+ Runner string `json:"runner"` // hex SHA-256 of the runner binary, measured in the VM by vm-init
+ VMInit string `json:"vm_init"` // hex SHA-256 of equipo-vm-init, measured
+ SandboxPolicy string `json:"sandbox_policy"` // hex SHA-256 of the check policy set, measured
+ ProxyPolicy int `json:"proxy_policy"` // the proxy policy version the matrix ran against
+ Deps string `json:"deps"` // DepsPrimaryBundleV1
+ Deployment []string `json:"deployment"` // the exact instance hosts this certificate covers
+ Profile string `json:"profile"` // ProfileVMBoundaryChecks
+ EvidenceID string `json:"evidence_id"` // the controller-signed evidence this was judged from
+}
+
+// Certificate is a Snapshot signed by the key named KeyID at IssuedAt.
+type Certificate struct {
+ Snapshot Snapshot `json:"snapshot"`
+ KeyID string `json:"key_id"`
+ IssuedAt time.Time `json:"issued_at"`
+ Sig []byte `json:"sig"`
+}
+
+var (
+ // ErrUnknownKey: the certificate names a key the verifier does not hold.
+ ErrUnknownKey = errors.New("hostedcert: certificate is signed by an unknown key")
+ // ErrBadSignature: the signature does not verify over the snapshot, key
+ // ID and issue time.
+ ErrBadSignature = errors.New("hostedcert: certificate signature does not verify")
+ // ErrSnapshot: a well-signed snapshot that breaks the version 1 rules.
+ ErrSnapshot = errors.New("hostedcert: certificate snapshot is not valid")
+)
+
+// appendField appends v as its length (uvarint) and then its bytes, so no
+// two different field lists encode alike.
+func appendField(b []byte, v string) []byte {
+ return append(binary.AppendUvarint(b, uint64(len(v))), v...)
+}
+
+// Canonical is the snapshot's canonical encoding: a label, then every
+// field in declaration order, each length-prefixed; the deployment as its
+// count and then each host in order.
+func Canonical(s Snapshot) []byte {
+ b := appendField(nil, "equipo-hosted-image-cert canonical v1")
+ for _, f := range []string{s.Purpose, strconv.Itoa(s.Version), string(s.Image), s.ImageVersion, s.Runner, s.VMInit,
+ s.SandboxPolicy, strconv.Itoa(s.ProxyPolicy), s.Deps, strconv.Itoa(len(s.Deployment))} {
+ b = appendField(b, f)
+ }
+ for _, h := range s.Deployment {
+ b = appendField(b, h)
+ }
+ b = appendField(b, s.Profile)
+ return appendField(b, s.EvidenceID)
+}
+
+// message is what Sig signs: Canonical(s) bound to the key ID and the
+// issue time (RFC 3339 in UTC, to the nanosecond).
+func message(s Snapshot, id string, at time.Time) []byte {
+ b := appendField(nil, "equipo-hosted-image-cert signature v1")
+ b = appendField(b, id)
+ b = appendField(b, at.UTC().Format(time.RFC3339Nano))
+ return appendField(b, string(Canonical(s)))
+}
+
+// Sign signs s with k under the key ID id at time at.
+func Sign(s Snapshot, id string, k ed25519.PrivateKey, at time.Time) Certificate {
+ s.Deployment = slices.Clone(s.Deployment)
+ at = at.Round(0).UTC()
+ return Certificate{Snapshot: s, KeyID: id, IssuedAt: at, Sig: ed25519.Sign(k, message(s, id, at))}
+}
+
+// Verify checks c's signature under keys[c.KeyID] and then the snapshot's
+// rules, and returns a copy of the snapshot.
+func Verify(c Certificate, keys map[string]ed25519.PublicKey) (Snapshot, error) {
+ k, ok := keys[c.KeyID]
+ if !ok || len(k) != ed25519.PublicKeySize {
+ return Snapshot{}, fmt.Errorf("%w: %q", ErrUnknownKey, c.KeyID)
+ }
+ if !ed25519.Verify(k, message(c.Snapshot, c.KeyID, c.IssuedAt), c.Sig) {
+ return Snapshot{}, ErrBadSignature
+ }
+ if err := check(c.Snapshot); err != nil {
+ return Snapshot{}, fmt.Errorf("%w: %s", ErrSnapshot, err)
+ }
+ s := c.Snapshot
+ s.Deployment = slices.Clone(s.Deployment)
+ return s, nil
+}
+
+// Digest identifies c: "sha256:" and the hex SHA-256 of its signed message
+// and signature. Two certificates with the same digest are the same
+// certificate.
+func Digest(c Certificate) string {
+ sum := sha256.Sum256(appendField(message(c.Snapshot, c.KeyID, c.IssuedAt), string(c.Sig)))
+ return "sha256:" + hex.EncodeToString(sum[:])
+}
+
+// check holds a snapshot to the version 1 rules.
+func check(s Snapshot) error {
+ img, isSHA := strings.CutPrefix(string(s.Image), "sha256:")
+ switch {
+ case s.Purpose != Purpose:
+ return fmt.Errorf("purpose %q is not %q", s.Purpose, Purpose)
+ case s.Version != Version:
+ return fmt.Errorf("version %d is not %d", s.Version, Version)
+ case !isSHA || !sha256Hex(img):
+ return errors.New("image is not sha256: and 64 lower-case hex digits")
+ case !text(s.ImageVersion):
+ return errors.New("image version must be 1 to 1024 printable ASCII characters")
+ case !sha256Hex(s.Runner) || !sha256Hex(s.VMInit) || !sha256Hex(s.SandboxPolicy):
+ return errors.New("runner, vm-init and sandbox policy must each be 64 lower-case hex digits")
+ case s.ProxyPolicy < 1:
+ return fmt.Errorf("proxy policy %d is below 1", s.ProxyPolicy)
+ case s.Deps != DepsPrimaryBundleV1:
+ return fmt.Errorf("deps %q is not %q", s.Deps, DepsPrimaryBundleV1)
+ case len(s.Deployment) == 0:
+ return errors.New("deployment names no host")
+ case s.Profile != ProfileVMBoundaryChecks:
+ return fmt.Errorf("profile %q is not %q", s.Profile, ProfileVMBoundaryChecks)
+ case !text(s.EvidenceID):
+ return errors.New("evidence ID must be 1 to 1024 printable ASCII characters")
+ }
+ seen := map[string]bool{}
+ for _, h := range s.Deployment {
+ if !text(h) || seen[h] {
+ return fmt.Errorf("deployment host %q is empty, not printable ASCII, or listed twice", h)
+ }
+ seen[h] = true
+ }
+ return nil
+}
+
+// text is 1 to maxText bytes of printable ASCII.
+func text(s string) bool {
+ if s == "" || len(s) > maxText {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if s[i] < 0x20 || s[i] > 0x7e {
+ return false
+ }
+ }
+ return true
+}
+
+// sha256Hex is 64 lower-case hex digits.
+func sha256Hex(s string) bool {
+ if len(s) != 64 {
+ 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/hostedcert/cert_test.go b/internal/hostedcert/cert_test.go
new file mode 100644
index 00000000..4ec7c936
--- /dev/null
+++ b/internal/hostedcert/cert_test.go
@@ -0,0 +1,199 @@
+package hostedcert
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+var (
+ keyA = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
+ keyB = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{8}, ed25519.SeedSize))
+ at = time.Date(2026, 11, 30, 9, 0, 0, 0, time.UTC)
+)
+
+func pub(k ed25519.PrivateKey) ed25519.PublicKey { return k.Public().(ed25519.PublicKey) }
+
+func snapshot() Snapshot {
+ return Snapshot{
+ Purpose: Purpose, Version: Version,
+ Image: isolatedjob.ImageDigest("sha256:" + strings.Repeat("a", 64)),
+ ImageVersion: "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img:3",
+ Runner: strings.Repeat("1", 64),
+ VMInit: strings.Repeat("2", 64),
+ SandboxPolicy: strings.Repeat("3", 64),
+ ProxyPolicy: 1,
+ Deps: DepsPrimaryBundleV1,
+ Deployment: []string{"equipo.example.com", "team.example.org"},
+ Profile: ProfileVMBoundaryChecks,
+ EvidenceID: "ev-1",
+ }
+}
+
+// changes gives, for each Snapshot field by name, another value that still
+// passes the snapshot rules where the field allows one.
+var changes = map[string]func(*Snapshot){
+ "Purpose": func(s *Snapshot) { s.Purpose = "equipo-hosted-other" },
+ "Version": func(s *Snapshot) { s.Version = 2 },
+ "Image": func(s *Snapshot) { s.Image = isolatedjob.ImageDigest("sha256:" + strings.Repeat("b", 64)) },
+ "ImageVersion": func(s *Snapshot) { s.ImageVersion += "x" },
+ "Runner": func(s *Snapshot) { s.Runner = strings.Repeat("4", 64) },
+ "VMInit": func(s *Snapshot) { s.VMInit = strings.Repeat("5", 64) },
+ "SandboxPolicy": func(s *Snapshot) { s.SandboxPolicy = strings.Repeat("6", 64) },
+ "ProxyPolicy": func(s *Snapshot) { s.ProxyPolicy = 2 },
+ "Deps": func(s *Snapshot) { s.Deps = "mirror-v1" },
+ "Deployment": func(s *Snapshot) { s.Deployment = []string{"equipo.example.com", "other.example.org"} },
+ "Profile": func(s *Snapshot) { s.Profile = "other-profile" },
+ "EvidenceID": func(s *Snapshot) { s.EvidenceID = "ev-2" },
+}
+
+// TestCertificateCanonical: every Snapshot field is in Canonical, so a
+// certificate whose snapshot differs from the signed one in any one field
+// fails Verify. The field list is read from the type, so a field added
+// later without a change here fails the test.
+func TestCertificateCanonical(t *testing.T) {
+ keys := map[string]ed25519.PublicKey{"k1": pub(keyA)}
+ c := Sign(snapshot(), "k1", keyA, at)
+ got, err := Verify(c, keys)
+ if err != nil || !reflect.DeepEqual(got, snapshot()) {
+ t.Fatalf("Verify of a signed certificate = (%+v, %v), want its snapshot", got, err)
+ }
+ base := Canonical(snapshot())
+ typ := reflect.TypeFor[Snapshot]()
+ for i := range typ.NumField() {
+ name := typ.Field(i).Name
+ change, ok := changes[name]
+ if !ok {
+ t.Errorf("Snapshot field %s has no change in this test", name)
+ continue
+ }
+ s := snapshot()
+ change(&s)
+ if bytes.Equal(Canonical(s), base) {
+ t.Errorf("Canonical ignores %s", name)
+ }
+ forged := c
+ forged.Snapshot = s
+ if _, err := Verify(forged, keys); err == nil {
+ t.Errorf("Verify with %s changed after signing = nil, want an error", name)
+ }
+ }
+ // The deployment's order and its split into hosts are both signed.
+ for name, d := range map[string][]string{
+ "reordered": {"team.example.org", "equipo.example.com"},
+ "joined": {"equipo.example.comteam.example.org"},
+ "one fewer": {"equipo.example.com"},
+ } {
+ s := snapshot()
+ s.Deployment = d
+ if bytes.Equal(Canonical(s), base) {
+ t.Errorf("Canonical with the deployment %s equals the original", name)
+ }
+ }
+ // The key ID and issue time are signed too.
+ moved := c
+ moved.IssuedAt = at.Add(time.Second)
+ if _, err := Verify(moved, keys); !errors.Is(err, ErrBadSignature) {
+ t.Errorf("Verify with IssuedAt changed = %v, want ErrBadSignature", err)
+ }
+ keys["k2"] = pub(keyA)
+ renamed := c
+ renamed.KeyID = "k2"
+ if _, err := Verify(renamed, keys); !errors.Is(err, ErrBadSignature) {
+ t.Errorf("Verify with KeyID moved to the same key = %v, want ErrBadSignature", err)
+ }
+}
+
+func TestCertificateVerifyRefusals(t *testing.T) {
+ keys := map[string]ed25519.PublicKey{"k1": pub(keyA)}
+ c := Sign(snapshot(), "k1", keyA, at)
+ if _, err := Verify(c, map[string]ed25519.PublicKey{"k2": pub(keyA)}); !errors.Is(err, ErrUnknownKey) {
+ t.Errorf("Verify with the key absent = %v, want ErrUnknownKey", err)
+ }
+ if _, err := Verify(c, map[string]ed25519.PublicKey{"k1": pub(keyB)}); !errors.Is(err, ErrBadSignature) {
+ t.Errorf("Verify under another key = %v, want ErrBadSignature", err)
+ }
+ bad := c
+ bad.Sig = bytes.Clone(c.Sig)
+ bad.Sig[0] ^= 1
+ if _, err := Verify(bad, keys); !errors.Is(err, ErrBadSignature) {
+ t.Errorf("Verify with a flipped signature bit = %v, want ErrBadSignature", err)
+ }
+ // A well-signed snapshot that breaks the rules is still refused.
+ for name, edit := range map[string]func(*Snapshot){
+ "other purpose": func(s *Snapshot) { s.Purpose = "equipo-hosted-other" },
+ "version 2": func(s *Snapshot) { s.Version = 2 },
+ "bad image": func(s *Snapshot) { s.Image = "sha256:AA" },
+ "no image version": func(s *Snapshot) { s.ImageVersion = "" },
+ "short runner": func(s *Snapshot) { s.Runner = "abc" },
+ "upper vm-init": func(s *Snapshot) { s.VMInit = strings.Repeat("A", 64) },
+ "no sandbox policy": func(s *Snapshot) { s.SandboxPolicy = "" },
+ "proxy policy 0": func(s *Snapshot) { s.ProxyPolicy = 0 },
+ "other deps": func(s *Snapshot) { s.Deps = "mirror-v1" },
+ "no deployment": func(s *Snapshot) { s.Deployment = nil },
+ "empty host": func(s *Snapshot) { s.Deployment = []string{""} },
+ "host twice": func(s *Snapshot) { s.Deployment = []string{"a.example.com", "a.example.com"} },
+ "other profile": func(s *Snapshot) { s.Profile = "other-profile" },
+ "no evidence": func(s *Snapshot) { s.EvidenceID = "" },
+ } {
+ s := snapshot()
+ edit(&s)
+ if _, err := Verify(Sign(s, "k1", keyA, at), keys); !errors.Is(err, ErrSnapshot) {
+ t.Errorf("%s: Verify = %v, want ErrSnapshot", name, err)
+ }
+ }
+}
+
+func TestCertificateDigest(t *testing.T) {
+ c := Sign(snapshot(), "k1", keyA, at)
+ d := Digest(c)
+ if !strings.HasPrefix(d, "sha256:") || len(d) != len("sha256:")+64 || Digest(Sign(snapshot(), "k1", keyA, at)) != d {
+ t.Fatalf("Digest = %q, want a stable sha256: and 64 hex digits", d)
+ }
+ other := snapshot()
+ other.EvidenceID = "ev-2"
+ for name, o := range map[string]Certificate{
+ "other snapshot": Sign(other, "k1", keyA, at),
+ "other key ID": Sign(snapshot(), "k2", keyA, at),
+ "other time": Sign(snapshot(), "k1", keyA, at.Add(time.Nanosecond)),
+ "other key": Sign(snapshot(), "k1", keyB, at),
+ } {
+ if Digest(o) == d {
+ t.Errorf("Digest with %s = the original's", name)
+ }
+ }
+}
+
+// TestCertificateJSON: a certificate survives the JSON round trip the
+// certificate file makes, and still verifies with the same digest.
+func TestCertificateJSON(t *testing.T) {
+ c := Sign(snapshot(), "k1", keyA, at.Add(123*time.Nanosecond))
+ raw, err := json.Marshal(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range []string{`"snapshot"`, `"key_id"`, `"issued_at"`, `"sig"`, `"image_version"`, `"vm_init"`, `"sandbox_policy"`,
+ `"proxy_policy"`, `"deployment"`, `"evidence_id"`} {
+ if !bytes.Contains(raw, []byte(key)) {
+ t.Errorf("JSON %s has no key %s", raw, key)
+ }
+ }
+ var back Certificate
+ if err := json.Unmarshal(raw, &back); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Verify(back, map[string]ed25519.PublicKey{"k1": pub(keyA)}); err != nil || Digest(back) != Digest(c) {
+ t.Fatalf("after JSON: Verify = %v, digest %s want %s", err, Digest(back), Digest(c))
+ }
+}
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go
index 53227ee2..4c49cd95 100644
--- a/internal/hostedclient/client.go
+++ b/internal/hostedclient/client.go
@@ -57,7 +57,8 @@ var (
ErrReplay = errors.New("hostedclient: the controller has already seen this request's nonce")
ErrBadRequest = errors.New("hostedclient: the controller could not take the request as sent")
ErrInvalid = errors.New("hostedclient: a request field is out of range")
- ErrImageNotAllowed = errors.New("hostedclient: the image is not in the controller's allowlist")
+ ErrNotCertified = errors.New("hostedclient: no valid certificate covers the image for this deployment")
+ ErrLaunchExpired = errors.New("hostedclient: the launch-by time has passed")
ErrForbidden = errors.New("hostedclient: this key may not do that")
ErrNotFound = errors.New("hostedclient: not found")
ErrTooLarge = errors.New("hostedclient: the request body is too large")
@@ -93,7 +94,8 @@ var refusals = map[string]struct {
"no_route": {http.StatusNotFound, ErrBadRequest},
"method": {http.StatusMethodNotAllowed, ErrBadRequest},
"invalid": {http.StatusBadRequest, ErrInvalid},
- "image_not_allowed": {http.StatusBadRequest, ErrImageNotAllowed},
+ "not_certified": {http.StatusBadRequest, ErrNotCertified},
+ "launch_expired": {http.StatusConflict, ErrLaunchExpired},
"forbidden": {http.StatusForbidden, ErrForbidden},
"not_found": {http.StatusNotFound, ErrNotFound},
"too_large": {http.StatusRequestEntityTooLarge, ErrTooLarge},
@@ -118,7 +120,7 @@ var refusals = map[string]struct {
// APIError is a signed refusal from the controller. Kind is one of the
// kinds above, or ErrUnexpected; errors.Is matches it.
type APIError struct {
- Op string // the route: launch, get, stop, drain, quiescent, suspend, reopen, resume
+ Op string // the route: launch, get, admission, stop, drain, quiescent, suspend, reopen, resume
Status int
Code string // the controller's code, or "" when the body was not a strict ErrorResponse
Kind error
@@ -234,6 +236,25 @@ func (c *Client) Get(ctx context.Context, attempt string) (hostedwire.JobView, e
return v, nil
}
+// Admission reads attempt's admission record:
+// GET /v1/jobs/{attempt}/admission. Like every answer, it is taken only
+// when signed by the controller for this request's nonce, and only when it
+// names attempt.
+func (c *Client) Admission(ctx context.Context, attempt string) (hostedwire.AdmissionView, error) {
+ p, err := jobPath(attempt, "admission")
+ if err != nil {
+ return hostedwire.AdmissionView{}, err
+ }
+ var a hostedwire.AdmissionView
+ if err := c.call(ctx, "admission", http.MethodGet, p, nil, &a); err != nil {
+ return hostedwire.AdmissionView{}, err
+ }
+ if a.AttemptID != attempt {
+ return hostedwire.AdmissionView{}, fmt.Errorf("%w: admission: the record is for another attempt", ErrBadResponse)
+ }
+ return a, nil
+}
+
// Stop stops attempt's VM: POST /v1/jobs/{attempt}/stop. Until the provider
// proves the VM stopped it returns ErrStopPending; ask again.
func (c *Client) Stop(ctx context.Context, attempt, reason string) (hostedwire.StopProof, error) {
diff --git a/internal/hostedclient/client_test.go b/internal/hostedclient/client_test.go
index 166e588e..76e34db4 100644
--- a/internal/hostedclient/client_test.go
+++ b/internal/hostedclient/client_test.go
@@ -19,7 +19,9 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/hostedcert"
"amadan.net/oficina/equipo/internal/hostedctl"
+ "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"
@@ -75,7 +77,7 @@ func newCtlEnvManifest(t *testing.T, m ctlegress.Manifest) *ctlEnv {
}
t.Cleanup(func() { _ = store.Close() })
fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
- c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true},
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: ctlcerttest.Set(ctlcerttest.Cert(imgA, "equipo.example.com")),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: m},
hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}})
@@ -245,8 +247,78 @@ func TestClientAgainstController(t *testing.T) {
}
bad := launchReq("a2")
bad.Image = "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
- if _, err := cl.Launch(ctx, bad); !errors.Is(err, ErrImageNotAllowed) {
- t.Fatalf("launch with an image off the allowlist = %v, want ErrImageNotAllowed", err)
+ if _, err := cl.Launch(ctx, bad); !errors.Is(err, ErrNotCertified) {
+ t.Fatalf("launch with an image no certificate covers = %v, want ErrNotCertified", err)
+ }
+ late := launchReq("a3")
+ late.LaunchByUnixMS = time.Date(2026, 11, 19, 11, 0, 0, 0, time.UTC).UnixMilli() // before the controller's wall clock
+ if _, err := cl.Launch(ctx, late); !errors.Is(err, ErrLaunchExpired) {
+ t.Fatalf("launch past its launch-by time = %v, want ErrLaunchExpired", err)
+ }
+}
+
+// TestClientAdmissionVerified: Admission reads the attempt's admission
+// record, and takes it only when the controller signed it for this
+// request's own nonce and it names the attempt asked about.
+func TestClientAdmissionVerified(t *testing.T) {
+ e := newCtlEnv(t)
+ ctx := e.ctx
+ cl := newClient(t, e.srv, keyInst, ctlPublic())
+ v, err := cl.Launch(ctx, launchReq("a1"))
+ if err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ a, err := cl.Admission(ctx, "a1")
+ want := hostedcert.Digest(ctlcerttest.Cert(imgA, "equipo.example.com"))
+ if err != nil || a.AttemptID != "a1" || a.LaunchID != v.LaunchID || a.VMRef != v.VMRef || a.Image != imgA ||
+ a.CertDigest != want || !a.CertValid {
+ t.Fatalf("Admission = (%+v, %v), want a1's VM under %s, valid", a, err, want)
+ }
+ if _, err := cl.Admission(ctx, "nope"); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("Admission of an unknown attempt = %v, want ErrForbidden", err)
+ }
+
+ // A genuine admission answer, captured and replayed to a later request,
+ // is signed for the captured request's nonce, not the new one.
+ var captured struct {
+ hdr http.Header
+ body []byte
+ }
+ var replay atomic.Bool
+ real := e.srv.Config.Handler
+ relay := serveTLS(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if replay.Load() {
+ for k, vs := range captured.hdr {
+ w.Header()[k] = vs
+ }
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(captured.body)
+ return
+ }
+ rec := httptest.NewRecorder()
+ real.ServeHTTP(rec, r)
+ captured.hdr, captured.body = rec.Header().Clone(), rec.Body.Bytes()
+ for k, vs := range rec.Header() {
+ w.Header()[k] = vs
+ }
+ w.WriteHeader(rec.Code)
+ _, _ = w.Write(rec.Body.Bytes())
+ }))
+ relayed := newClient(t, relay, keyInst, ctlPublic())
+ if a, err := relayed.Admission(ctx, "a1"); err != nil || !a.CertValid {
+ t.Fatalf("Admission through the relay = (%+v, %v), want valid", a, err)
+ }
+ replay.Store(true)
+ if a, err := relayed.Admission(ctx, "a1"); !errors.Is(err, ErrUnverified) || a != (hostedwire.AdmissionView{}) {
+ t.Fatalf("Admission answered with a replayed response = (%+v, %v), want ErrUnverified and nothing", a, err)
+ }
+
+ // A signed answer for another attempt does not answer this one.
+ other := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
+ signedAnswer(w, http.StatusOK, []byte(`{"attempt_id":"a9","state":"running","cert_valid":true}`), nonce, keyCtl)
+ }), keyInst, ctlPublic())
+ if a, err := other.Admission(ctx, "a1"); !errors.Is(err, ErrBadResponse) || a != (hostedwire.AdmissionView{}) {
+ t.Fatalf("Admission answered for another attempt = (%+v, %v), want ErrBadResponse and nothing", a, err)
}
}
diff --git a/internal/hostedctl/admission.go b/internal/hostedctl/admission.go
new file mode 100644
index 00000000..44b7500d
--- /dev/null
+++ b/internal/hostedctl/admission.go
@@ -0,0 +1,41 @@
+package hostedctl
+
+import (
+ "context"
+
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// ErrNotCertified: no valid certificate names the image and covers the
+// launch's instance hosts, or an intent's certificate is no longer valid.
+var ErrNotCertified = ctlcert.ErrNotCertified
+
+// actionAdmissionRefused is the audit action of a refused Admission.
+const actionAdmissionRefused = "admission_refused"
+
+// Admission returns attempt's admission record: its VM, epoch and image,
+// the digest of the certificate its launch was admitted under, and whether
+// that certificate is valid at this moment (Config.Certs, re-verified on
+// every call, never remembered from launch time). CheckedNS is the
+// controller time of the answer. Only the instance key that launched the
+// attempt may read it; the refusals are Get's, audited as
+// admission_refused. Admission makes no provider call.
+func (c *Controller) Admission(ctx context.Context, by hostedwire.KeyID, attemptID string) (hostedwire.AdmissionView, error) {
+ var a hostedwire.AdmissionView
+ err := c.readOwn(ctx, by, attemptID, actionAdmissionRefused, func(j jobRow, now T) error {
+ spec, err := decodeSpec(j.specJSON, j.attempt)
+ if err != nil {
+ return err
+ }
+ a = hostedwire.AdmissionView{AttemptID: j.attempt, LaunchID: j.launchID, State: j.state, VMRef: isolatedjob.Ref(j.ref.String),
+ Epoch: j.epoch, Image: spec.Image, CertDigest: j.certDigest, CertValid: c.cfg.Certs.Valid(j.certDigest),
+ CheckedNS: int64(now)}
+ return nil
+ })
+ if err != nil {
+ return hostedwire.AdmissionView{}, err
+ }
+ return a, nil
+}
diff --git a/internal/hostedctl/admission_test.go b/internal/hostedctl/admission_test.go
new file mode 100644
index 00000000..326d30a2
--- /dev/null
+++ b/internal/hostedctl/admission_test.go
@@ -0,0 +1,362 @@
+package hostedctl
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "errors"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// testHosts are the instance hosts the tests' manifests name; the test
+// certificates cover all of them.
+var testHosts = []string{"equipo.example.com", "one.example.com", "two.example.com"}
+
+// testCerts is a certificate set with one certificate each for imgA and
+// imgB, covering testHosts.
+func testCerts() *ctlcert.Set { return ctlcerttest.Set(testCertList()...) }
+
+func testCertList() []hostedcert.Certificate {
+ return []hostedcert.Certificate{ctlcerttest.Cert(imgA, testHosts...), ctlcerttest.Cert(imgB, testHosts...)}
+}
+
+// certA is the digest of testCerts' certificate for imgA.
+func certA() string { return hostedcert.Digest(ctlcerttest.Cert(imgA, testHosts...)) }
+
+var otherCertKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x66}, ed25519.SeedSize))
+
+// TestLaunchNeedsCertificate: a checks launch needs a certificate that
+// verifies under a key the controller holds, names the image, and covers
+// every instance host the launch's services snapshot names. Each refusal
+// is audited and creates nothing.
+func TestLaunchNeedsCertificate(t *testing.T) {
+ t.Parallel()
+ badSig := ctlcerttest.Cert(imgA, testHosts...)
+ badSig.Sig = bytes.Clone(badSig.Sig)
+ badSig.Sig[0] ^= 1
+ otherDoc := ctlcerttest.Snapshot(imgA, testHosts...)
+ otherDoc.Purpose = "equipo-hosted-evidence"
+ cases := []struct {
+ name string
+ setup func(e *launchEnv)
+ edit func(q *LaunchRequest)
+ want error
+ }{
+ {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) {
+ e.replaceCerts(ctlcerttest.Keys(), []hostedcert.Certificate{ctlcerttest.Cert(imgA, "one.example.com")})
+ }, want: ErrNotCertified},
+ {name: "unknown key", setup: func(e *launchEnv) {
+ other := map[string]ed25519.PublicKey{"other": otherCertKey.Public().(ed25519.PublicKey)}
+ e.replaceCerts(other, []hostedcert.Certificate{ctlcerttest.Cert(imgA, testHosts...)})
+ }, want: ErrNotCertified},
+ {name: "bad signature", setup: func(e *launchEnv) {
+ e.replaceCerts(ctlcerttest.Keys(), []hostedcert.Certificate{ctlcerttest.Cert(imgB, testHosts...)})
+ if _, err := e.cfg.Certs.Replace(ctlcerttest.Keys(), []hostedcert.Certificate{badSig}); err == nil {
+ e.t.Fatal("Replace with a bad signature = nil, want an error")
+ }
+ }, want: ErrNotCertified},
+ {name: "purpose mismatch in the snapshot", setup: func(e *launchEnv) {
+ e.replaceCerts(ctlcerttest.Keys(), nil)
+ c := hostedcert.Sign(otherDoc, ctlcerttest.KeyID, ctlcerttest.Key, ctlcerttest.IssuedAt)
+ if _, err := e.cfg.Certs.Replace(ctlcerttest.Keys(), []hostedcert.Certificate{c}); err == nil {
+ e.t.Fatal("Replace with another document's purpose = nil, want an error")
+ }
+ }, want: ErrNotCertified},
+ {name: "certification launch by an instance key", edit: func(q *LaunchRequest) {
+ q.Purpose, q.Person = hostedwire.PurposeCertification, ""
+ }, want: ErrForbidden},
+ {name: "certified", want: nil},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ if tc.setup != nil {
+ tc.setup(e)
+ }
+ q := request("att-1")
+ if tc.edit != nil {
+ tc.edit(&q)
+ }
+ v, err := e.c.Launch(e.ctx, "inst-1", instKey, q)
+ if tc.want == nil {
+ 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())
+ }
+ return
+ }
+ if !errors.Is(err, tc.want) || v != (JobView{}) {
+ t.Fatalf("Launch = (%+v, %v), want (zero view, %v)", v, err, tc.want)
+ }
+ if n, calls := e.jobCount(), e.fake.Calls(isolatedjob.OpLaunch); n != 0 || calls != 0 {
+ t.Fatalf("after the refusal: %d jobs, %d provider launches; want none", n, calls)
+ }
+ if a := e.lastAudit(); a.Action != actionLaunchRefused || a.Attempt != "att-1" {
+ t.Fatalf("last audit = %+v, want %s for att-1", a, actionLaunchRefused)
+ }
+ })
+ }
+}
+
+// replaceCerts replaces the env's certificate set and wants it to load.
+func (e *launchEnv) replaceCerts(keys map[string]ed25519.PublicKey, certs []hostedcert.Certificate) {
+ e.t.Helper()
+ if _, err := e.cfg.Certs.Replace(keys, certs); err != nil {
+ e.t.Fatalf("Replace = %v", err)
+ }
+}
+
+// admission reads attempt's admission as inst-1 and wants no error.
+func (e *launchEnv) admission(attempt string) hostedwire.AdmissionView {
+ e.t.Helper()
+ a, err := e.c.Admission(e.ctx, "inst-1", attempt)
+ if err != nil {
+ e.t.Fatalf("Admission(%s) = %v", attempt, err)
+ }
+ return a
+}
+
+// TestAdmissionRecordsCertDigest: the admission record names the VM, its
+// epoch and image, and the digest of the certificate the launch was
+// admitted under; a newer certificate does not move it, and removing that
+// one certificate makes it invalid.
+func TestAdmissionRecordsCertDigest(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
+ if err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ if j, _ := e.job("att-1"); j.certDigest != certA() {
+ t.Fatalf("intent's certificate digest = %q, want %q", j.certDigest, certA())
+ }
+ a := e.admission("att-1")
+ want := hostedwire.AdmissionView{AttemptID: "att-1", LaunchID: v.LaunchID, State: v.State, VMRef: v.VMRef, Epoch: v.Epoch,
+ Image: imgA, CertDigest: certA(), CertValid: true, CheckedNS: int64(e.store.Clock().Now())}
+ if a != want {
+ t.Fatalf("Admission = %+v, want %+v", a, want)
+ }
+ e.clk.AdvanceMono(time.Minute)
+ if a := e.admission("att-1"); a.CheckedNS != want.CheckedNS+int64(time.Minute) {
+ t.Fatalf("CheckedNS a minute later = %d, want %d", a.CheckedNS, want.CheckedNS+int64(time.Minute))
+ }
+
+ newer := hostedcert.Sign(ctlcerttest.Snapshot(imgA, testHosts...), ctlcerttest.KeyID, ctlcerttest.Key, ctlcerttest.IssuedAt.Add(time.Hour))
+ e.replaceCerts(ctlcerttest.Keys(), []hostedcert.Certificate{ctlcerttest.Cert(imgA, testHosts...), newer})
+ if a := e.admission("att-1"); a.CertDigest != certA() || !a.CertValid {
+ t.Fatalf("Admission with a newer certificate loaded = %+v, want the launch's certificate, valid", a)
+ }
+ e.replaceCerts(ctlcerttest.Keys(), []hostedcert.Certificate{newer})
+ if a := e.admission("att-1"); a.CertDigest != certA() || a.CertValid {
+ t.Fatalf("Admission with the launch's certificate removed = %+v, want its digest, not valid", a)
+ }
+}
+
+// TestAdmissionKeyRemoved: a reload without the signing key withdraws the
+// certificate, and the next admission call says so.
+func TestAdmissionKeyRemoved(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)
+ }
+ if a := e.admission("att-1"); !a.CertValid {
+ t.Fatalf("Admission = %+v, want valid", a)
+ }
+ certs := ctlcerttest.CertsJSON(ctlcerttest.Cert(imgA, testHosts...), ctlcerttest.Cert(imgB, testHosts...))
+ if n, err := e.cfg.Certs.Load([]byte(`{"keys":[]}`), certs); err != nil || n != 0 {
+ t.Fatalf("reload without the key = (%d, %v), want 0 certificates", n, err)
+ }
+ if a := e.admission("att-1"); a.CertValid || a.CertDigest != certA() {
+ t.Fatalf("Admission after the key was removed = %+v, want its digest, not valid", a)
+ }
+ if n, err := e.cfg.Certs.Load(ctlcerttest.KeysJSON(), certs); err != nil || n != 2 {
+ t.Fatalf("reload with the key = (%d, %v), want 2 certificates", n, err)
+ }
+ if a := e.admission("att-1"); !a.CertValid {
+ t.Fatalf("Admission with the key back = %+v, want valid", a)
+ }
+}
+
+// TestAdmissionCreatorOnly: only the key that launched an attempt reads its
+// admission; another key, no key and an unknown attempt get the same
+// refusal, audited.
+func TestAdmissionCreatorOnly(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)
+ }
+ for _, c := range []struct {
+ by hostedwire.KeyID
+ attempt string
+ want error
+ }{
+ {"inst-2", "att-1", ErrForbidden},
+ {"", "att-1", ErrForbidden},
+ {"inst-1", "att-9", ErrForbidden},
+ {"inst-1", "", isolatedjob.ErrInvalid},
+ {"inst-1", "att-\n", isolatedjob.ErrInvalid},
+ } {
+ a, err := e.c.Admission(e.ctx, c.by, c.attempt)
+ if !errors.Is(err, c.want) || a != (hostedwire.AdmissionView{}) {
+ t.Fatalf("Admission(%q, %q) = (%+v, %v), want (zero, %v)", c.by, c.attempt, a, err, c.want)
+ }
+ if got := e.lastAudit(); got.Action != actionAdmissionRefused || got.Actor != c.by {
+ t.Fatalf("last audit = %+v, want %s by %q", got, actionAdmissionRefused, c.by)
+ }
+ }
+}
+
+// TestAdmissionOverHTTP: GET /v1/jobs/{attempt}/admission answers the
+// creator with a signed AdmissionView.
+func TestAdmissionOverHTTP(t *testing.T) {
+ t.Parallel()
+ e := newAPIEnv(t, true)
+ v := e.launch("a1")
+ r := e.call("GET", "/v1/jobs/a1/admission", nil, idInstA, keyInstA)
+ if r.status != http.StatusOK {
+ t.Fatalf("GET admission = %d %s", r.status, r.body)
+ }
+ var a hostedwire.AdmissionView
+ if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &a); err != nil {
+ t.Fatal(err)
+ }
+ if a.AttemptID != "a1" || a.LaunchID != v.LaunchID || a.VMRef != v.VMRef || a.Image != imgA || a.CertDigest != certA() || !a.CertValid {
+ t.Fatalf("GET admission = %+v, want a1's VM under %s, valid", a, certA())
+ }
+ if r := e.call("POST", "/v1/jobs/a1/admission", "{}", idInstA, keyInstA); r.status != http.StatusMethodNotAllowed {
+ t.Fatalf("POST admission = %d %s, want 405", r.status, r.body)
+ }
+}
+
+// TestLaunchByEnforced: the controller never asks the provider for a VM
+// once its wall clock is past the request's launch-by time: not before
+// the intent is saved, not before a dispatch, and not on Replay.
+func TestLaunchByEnforced(t *testing.T) {
+ t.Parallel()
+ launchBy := time.UnixMilli(testLaunchBy)
+ past := func(e *launchEnv) { e.clk.SetWall(launchBy.Add(time.Millisecond)) }
+
+ t.Run("refused before the intent is saved", func(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ past(e)
+ v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
+ if !errors.Is(err, ErrLaunchExpired) || v != (JobView{}) {
+ t.Fatalf("Launch past launch-by = (%+v, %v), want (zero view, ErrLaunchExpired)", v, err)
+ }
+ if n, calls := e.jobCount(), e.fake.Calls(isolatedjob.OpLaunch); n != 0 || calls != 0 {
+ t.Fatalf("%d jobs, %d provider launches; want none", n, calls)
+ }
+ if a := e.lastAudit(); a.Action != actionLaunchRefused {
+ t.Fatalf("last audit = %+v, want %s", a, actionLaunchRefused)
+ }
+ // At exactly the launch-by time it may still launch.
+ e.clk.SetWall(launchBy)
+ if v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil || v.State != JobStarting {
+ t.Fatalf("Launch at launch-by = (%+v, %v), want starting", v, err)
+ }
+ })
+
+ t.Run("passes while the dispatch is recorded", func(t *testing.T) {
+ t.Parallel()
+ 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 calls := e.fake.Calls(isolatedjob.OpLaunch); calls != 0 {
+ t.Fatalf("provider launches = %d, want 0", calls)
+ }
+ })
+
+ t.Run("throttled past it, abandoned on Replay", func(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ if v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil || v.State != JobWaiting {
+ t.Fatalf("throttled Launch = (%+v, %v), want waiting", v, err)
+ }
+ past(e)
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("Replay = %v", err)
+ }
+ if calls := e.fake.Calls(isolatedjob.OpLaunch); calls != 1 {
+ t.Fatalf("provider launches = %d, want only the throttled one", calls)
+ }
+ if j, _ := e.job("att-1"); j.state != JobAbandoned || j.ref.Valid {
+ t.Fatalf("att-1 after Replay: %s ref %v; want abandoned with no ref", j.state, j.ref)
+ }
+ if a := e.lastAudit(); a.Action != actionReplayAbandoned || !strings.Contains(a.Reason, "launch-by") {
+ t.Fatalf("last audit = %+v, want %s naming the launch-by time", a, actionReplayAbandoned)
+ }
+ })
+
+ t.Run("lost reply reconciled, not replayed", func(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ ref := e.lostLaunch("att-1")
+ past(e)
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("Replay = %v", err)
+ }
+ if calls := e.fake.Calls(isolatedjob.OpLaunch); calls != 1 {
+ t.Fatalf("provider launches = %d, want only the lost one", calls)
+ }
+ if j, _ := e.job("att-1"); j.state != JobAbandoned || j.ref.Valid {
+ t.Fatalf("att-1 after Replay: %s ref %v; want abandoned with no ref", j.state, j.ref)
+ }
+ e.reap()
+ e.clk.AdvanceMono(OrphanGrace)
+ if r := e.reap(); r.OrphansStopped != 1 {
+ t.Fatalf("pass after the grace = %+v, want the lost reply's VM stopped as an orphan", r)
+ }
+ e.wantStops(ref)
+ })
+}
+
+// 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.
+func TestLegacyIntentNeverLaunches(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ e.exec(`INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key, purpose, spec_json, spec_sha256,
+ provider_fingerprint, state, launched_t, deadline_t, drain_t, stop_t)
+ SELECT 'legacy-1', 'legacy-launch-1', task_id, account_id, actor_key, 'task', replace(spec_json, '"att-1"', '"legacy-1"'),
+ spec_sha256, provider_fingerprint, state, launched_t, deadline_t, drain_t, stop_t FROM jobs WHERE attempt_id = 'att-1'`)
+ if a := e.admission("legacy-1"); a.CertValid || a.CertDigest != "" {
+ t.Fatalf("legacy admission = %+v, want no certificate, not valid", a)
+ }
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("Replay = %v", err)
+ }
+ if j, _ := e.job("legacy-1"); j.state != JobAbandoned || j.ref.Valid {
+ t.Fatalf("legacy-1 after Replay: %s ref %v; want abandoned", j.state, j.ref)
+ }
+ if j, _ := e.job("att-1"); j.state != JobStarting {
+ t.Fatalf("att-1 after Replay: %s, want starting", j.state)
+ }
+ if calls := e.fake.Calls(isolatedjob.OpLaunch); calls != 2 {
+ t.Fatalf("provider launches = %d, want 2 (att-1 throttled, then launched)", calls)
+ }
+}
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go
index 6427696b..8364c684 100644
--- a/internal/hostedctl/controller.go
+++ b/internal/hostedctl/controller.go
@@ -4,11 +4,11 @@ import (
"context"
"errors"
"log/slog"
- "maps"
"net/netip"
"reflect"
"slices"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -26,9 +26,11 @@ type Alerter interface {
// Config is the controller's settings. Later tasks add fields.
type Config struct {
- Enabled bool // launches allowed; only EQUIPO_HOSTED_ENABLED=1 sets it
- Images map[isolatedjob.ImageDigest]bool // image digests launches may use
- Egress []netip.AddrPort // the exact egress set the network audit expects
+ Enabled bool // launches allowed; only EQUIPO_HOSTED_ENABLED=1 sets it
+ Egress []netip.AddrPort // the exact egress set the network audit expects
+ // Certs are the image certificates a checks launch needs one of. The
+ // controller keeps the pointer, so a reload of the set reaches it.
+ Certs *ctlcert.Set
// ProviderNamespace names where the runner's VM references live (for
// AWS, the account and region). New binds the database to it on first
// use and refuses any other (ruling R28): a reference read in another
@@ -102,6 +104,8 @@ func New(cfg Config, d Deps) (*Controller, error) {
return nil, errors.New("hostedctl: controller needs an alerter")
case cfg.ProviderNamespace == "" || cfg.ProviderFingerprint == nil:
return nil, errors.New("hostedctl: controller needs a provider namespace and fingerprint")
+ case cfg.Certs == nil:
+ return nil, errors.New("hostedctl: controller needs a certificate set")
}
if err := d.Store.bindProvider(context.Background(), cfg.ProviderNamespace); err != nil {
return nil, err
@@ -109,7 +113,6 @@ func New(cfg Config, d Deps) (*Controller, error) {
if err := d.Store.deliverStartupAlerts(context.Background(), d.Alerter); err != nil {
return nil, err
}
- cfg.Images = maps.Clone(cfg.Images)
cfg.Egress = slices.Clone(cfg.Egress)
cfg.Manifest = cfg.Manifest.Clone()
log := d.Log
diff --git a/internal/hostedctl/ctlcert/certs.go b/internal/hostedctl/ctlcert/certs.go
new file mode 100644
index 00000000..17dece13
--- /dev/null
+++ b/internal/hostedctl/ctlcert/certs.go
@@ -0,0 +1,185 @@
+// Package ctlcert holds the controller's image certificates: the offline
+// signing keys it trusts and the certificates signed with them. A checks
+// launch is admitted only under a certificate from the set (Set.For), and
+// the admission record says whether that certificate is still in the set
+// (Set.Valid). A reload replaces the keys and certificates together, at
+// once; removing a key withdraws every certificate it signed.
+package ctlcert
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "slices"
+ "sync"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+var (
+ // ErrNotCertified: no certificate in the set names the image and
+ // covers every host asked for.
+ 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")
+)
+
+// maxKeyID bounds a signing key's ID.
+const maxKeyID = 64
+
+// 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
+}
+
+// NewSet returns an empty set.
+func NewSet() *Set {
+ return &Set{keys: map[string]ed25519.PublicKey{}, certs: map[string]hostedcert.Certificate{}}
+}
+
+// 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.
+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 {
+ if id == "" || len(id) > maxKeyID || len(k) != ed25519.PublicKeySize {
+ return 0, fmt.Errorf("ctlcert: key %q must have a 1 to %d character ID and a %d-byte public key", id, maxKeyID, ed25519.PublicKeySize)
+ }
+ nk[id] = bytes.Clone(k)
+ }
+ nc := make(map[string]hostedcert.Certificate, len(certs))
+ for i, c := range certs {
+ if _, err := hostedcert.Verify(c, nk); errors.Is(err, hostedcert.ErrUnknownKey) {
+ continue
+ } else if err != nil {
+ return 0, fmt.Errorf("ctlcert: certificate %d (%s): %w", i, hostedcert.Digest(c), err)
+ }
+ nc[hostedcert.Digest(c)] = clone(c)
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.keys, s.certs = nk, nc
+ return len(nc), nil
+}
+
+// keysFile is the key file: the offline signing keys certificates are
+// checked against, each public key in standard base64.
+type keysFile struct {
+ Keys []struct {
+ ID string `json:"id"`
+ PublicKey string `json:"public_key"`
+ } `json:"keys"`
+}
+
+// certsFile is the certificate file.
+type certsFile struct {
+ Certificates []hostedcert.Certificate `json:"certificates"`
+}
+
+// Load reads the key file and the certificate file (each one JSON object,
+// read with hostedwire.DecodeStrict) and Replaces the set with them. A file
+// that does not read, or a key ID listed twice, is ErrFile; either way, as
+// for any Replace error, the set is left as it was.
+func (s *Set) Load(keysJSON, certsJSON []byte) (int, error) {
+ var kf keysFile
+ if err := hostedwire.DecodeStrict(bytes.NewReader(keysJSON), &kf); err != nil {
+ return 0, fmt.Errorf("%w: key file: %v", ErrFile, err)
+ }
+ keys := map[string]ed25519.PublicKey{}
+ for _, k := range kf.Keys {
+ pub, err := base64.StdEncoding.Strict().DecodeString(k.PublicKey)
+ if err != nil {
+ return 0, fmt.Errorf("%w: key %q is not base64", ErrFile, k.ID)
+ }
+ if _, dup := keys[k.ID]; dup {
+ return 0, fmt.Errorf("%w: key %q is listed twice", ErrFile, k.ID)
+ }
+ keys[k.ID] = pub
+ }
+ var cf certsFile
+ if err := hostedwire.DecodeStrict(bytes.NewReader(certsJSON), &cf); err != nil {
+ return 0, fmt.Errorf("%w: certificate file: %v", ErrFile, err)
+ }
+ n, err := s.Replace(keys, cf.Certificates)
+ if err != nil {
+ return 0, fmt.Errorf("%w: %w", ErrFile, err)
+ }
+ return n, nil
+}
+
+// For returns the certificate that names image 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) {
+ 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) {
+ continue
+ }
+ if bestDigest == "" || c.IssuedAt.After(best.IssuedAt) || c.IssuedAt.Equal(best.IssuedAt) && d < bestDigest {
+ best, bestDigest = c, d
+ }
+ }
+ if bestDigest == "" {
+ return hostedcert.Certificate{}, fmt.Errorf("%w: image %s at %v", ErrNotCertified, image, 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 "".
+func (s *Set) Valid(digest string) bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ c, ok := s.certs[digest]
+ if !ok {
+ return false
+ }
+ _, err := hostedcert.Verify(c, s.keys)
+ return err == nil
+}
+
+// InstanceHosts returns the hosts of the instance-class services, in order:
+// the hosts a checks launch's certificate must cover.
+func InstanceHosts(services []hostedwire.Service) []string {
+ var out []string
+ for _, sv := range services {
+ if sv.Class == hostedwire.ServiceInstance {
+ out = append(out, sv.Host)
+ }
+ }
+ return out
+}
+
+// covers reports whether every host is in deployment, exactly.
+func covers(deployment, hosts []string) bool {
+ for _, h := range hosts {
+ if !slices.Contains(deployment, h) {
+ return false
+ }
+ }
+ return true
+}
+
+func clone(c hostedcert.Certificate) hostedcert.Certificate {
+ c.Snapshot.Deployment = slices.Clone(c.Snapshot.Deployment)
+ c.Sig = bytes.Clone(c.Sig)
+ return c
+}
diff --git a/internal/hostedctl/ctlcert/certs_test.go b/internal/hostedctl/ctlcert/certs_test.go
new file mode 100644
index 00000000..cff25f85
--- /dev/null
+++ b/internal/hostedctl/ctlcert/certs_test.go
@@ -0,0 +1,178 @@
+package ctlcert_test
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/base64"
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "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)) }
+
+const (
+ imgA = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
+ imgB = isolatedjob.ImageDigest("sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
+)
+
+var otherKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x77}, ed25519.SeedSize))
+
+func b64(k ed25519.PrivateKey) string {
+ return base64.StdEncoding.EncodeToString(k.Public().(ed25519.PublicKey))
+}
+
+func TestSetFor(t *testing.T) {
+ a := ctlcerttest.Cert(imgA, "equipo.example.com", "team.example.org")
+ s := ctlcerttest.Set(a)
+ for name, hosts := range map[string][]string{
+ "every host": {"equipo.example.com", "team.example.org"},
+ "one host": {"team.example.org"},
+ } {
+ got, err := s.For(imgA, 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)
+ }
+ }
+ for name, q := range map[string]struct {
+ img isolatedjob.ImageDigest
+ hosts []string
+ }{
+ "wrong image": {imgB, []string{"equipo.example.com"}},
+ "host not covered": {imgA, []string{"equipo.example.com", "other.example.com"}},
+ "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) {
+ t.Errorf("%s: For = %v, want ErrNotCertified", name, err)
+ }
+ }
+ if _, err := ctlcert.NewSet().For(imgA, []string{"equipo.example.com"}); !errors.Is(err, ctlcert.ErrNotCertified) {
+ t.Errorf("For on an empty set = %v, want ErrNotCertified", err)
+ }
+
+ // Of two that cover, the newer is chosen.
+ 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) {
+ t.Errorf("For with two covering = (%s, %v), want the newer %s", hostedcert.Digest(got), err, hostedcert.Digest(newer))
+ }
+}
+
+// TestSetReplace: a certificate under a key the set has must verify, or
+// Replace changes nothing; one under a key the set lacks is withdrawn.
+func TestSetReplace(t *testing.T) {
+ a := ctlcerttest.Cert(imgA, "equipo.example.com")
+ s := ctlcerttest.Set(a)
+ digest := hostedcert.Digest(a)
+
+ badSig := ctlcerttest.Cert(imgB, "equipo.example.com")
+ badSig.Sig = bytes.Clone(badSig.Sig)
+ badSig.Sig[3] ^= 1
+ badSnap := ctlcerttest.Snapshot(imgB, "equipo.example.com")
+ badSnap.Purpose = "equipo-hosted-other"
+ for name, certs := range map[string][]hostedcert.Certificate{
+ "bad signature": {badSig},
+ "purpose mismatch": {hostedcert.Sign(badSnap, ctlcerttest.KeyID, ctlcerttest.Key, ctlcerttest.IssuedAt)},
+ "other key's sig": {hostedcert.Sign(ctlcerttest.Snapshot(imgB, "equipo.example.com"), ctlcerttest.KeyID, otherKey, ctlcerttest.IssuedAt)},
+ } {
+ if _, err := s.Replace(ctlcerttest.Keys(), certs); err == nil {
+ t.Errorf("%s: Replace = nil, want an error", name)
+ }
+ 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) {
+ t.Errorf("%s: For(imgB) = %v, want ErrNotCertified", name, err)
+ }
+ }
+ for name, keys := range map[string]map[string]ed25519.PublicKey{
+ "short key": {ctlcerttest.KeyID: ed25519.PublicKey{1, 2}},
+ "empty key ID": {"": ctlcerttest.Key.Public().(ed25519.PublicKey)},
+ } {
+ if _, err := s.Replace(keys, nil); err == nil || !s.Valid(digest) {
+ t.Errorf("%s: Replace = %v and old set kept %v, want an error and the old set", name, err, s.Valid(digest))
+ }
+ }
+
+ // A key removed withdraws its certificates; it is not an error.
+ other := hostedcert.Sign(ctlcerttest.Snapshot(imgB, "equipo.example.com"), "other", otherKey, ctlcerttest.IssuedAt)
+ n, err := s.Replace(map[string]ed25519.PublicKey{"other": otherKey.Public().(ed25519.PublicKey)}, []hostedcert.Certificate{a, other})
+ if err != nil || n != 1 {
+ t.Fatalf("Replace without the test key = (%d, %v), want 1 kept", n, err)
+ }
+ 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) {
+ t.Errorf("For after its key was removed = %v, want ErrNotCertified", err)
+ }
+ if !s.Valid(hostedcert.Digest(other)) {
+ t.Error("Valid of the other key's certificate = false, want true")
+ }
+}
+
+func TestSetValid(t *testing.T) {
+ a := ctlcerttest.Cert(imgA, "equipo.example.com")
+ s := ctlcerttest.Set(a)
+ if !s.Valid(hostedcert.Digest(a)) {
+ t.Fatal("Valid of a loaded certificate = false")
+ }
+ for _, d := range []string{"", "sha256:" + string(bytes.Repeat([]byte("0"), 64)), hostedcert.Digest(ctlcerttest.Cert(imgB, "equipo.example.com"))} {
+ if s.Valid(d) {
+ t.Errorf("Valid(%q) = true, want false", d)
+ }
+ }
+ if _, err := s.Replace(ctlcerttest.Keys(), nil); err != nil {
+ t.Fatal(err)
+ }
+ if s.Valid(hostedcert.Digest(a)) {
+ t.Error("Valid after the certificate was removed = true, want false")
+ }
+}
+
+// TestSetLoad: the key and certificate files, read strictly; a file that
+// fails leaves the set as it was.
+func TestSetLoad(t *testing.T) {
+ a := ctlcerttest.Cert(imgA, "equipo.example.com")
+ s := ctlcert.NewSet()
+ 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)))
+ }
+ for name, files := range map[string][2][]byte{
+ "keys not JSON": {[]byte("{"), ctlcerttest.CertsJSON(a)},
+ "unknown keys field": {[]byte(`{"keys":[],"extra":1}`), ctlcerttest.CertsJSON(a)},
+ "key not base64": {[]byte(`{"keys":[{"id":"k","public_key":"%%"}]}`), ctlcerttest.CertsJSON()},
+ "certs not JSON": {ctlcerttest.KeysJSON(), []byte("[]")},
+ "unknown cert field": {ctlcerttest.KeysJSON(), []byte(`{"certificates":[],"x":1}`)},
+ "key ID listed twice": {[]byte(`{"keys":[{"id":"k","public_key":"` + b64(otherKey) + `"},{"id":"k","public_key":"` + b64(otherKey) + `"}]}`), ctlcerttest.CertsJSON()},
+ } {
+ if _, err := s.Load(files[0], files[1]); !errors.Is(err, ctlcert.ErrFile) {
+ t.Errorf("%s: Load = %v, want ErrFile", name, err)
+ }
+ if !s.Valid(hostedcert.Digest(a)) {
+ t.Errorf("%s: the old set was not kept", name)
+ }
+ }
+}
+
+func TestInstanceHosts(t *testing.T) {
+ got := ctlcert.InstanceHosts([]hostedwire.Service{
+ {Host: "b.example.com", Port: 443, Class: hostedwire.ServiceInstance},
+ {Host: "g.example.com", Port: 443, Class: "gateway"},
+ {Host: "a.example.com", Port: 443, Class: hostedwire.ServiceInstance},
+ })
+ if len(got) != 2 || got[0] != "b.example.com" || got[1] != "a.example.com" {
+ t.Fatalf("InstanceHosts = %v, want the two instance hosts in order", got)
+ }
+}
diff --git a/internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go b/internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go
new file mode 100644
index 00000000..ebb9899e
--- /dev/null
+++ b/internal/hostedctl/ctlcert/ctlcerttest/ctlcerttest.go
@@ -0,0 +1,74 @@
+// Package ctlcerttest signs image certificates with a fixed test key, for
+// tests that need a controller to admit checks launches. Nothing outside
+// tests may import it.
+package ctlcerttest
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// KeyID and Key are the test signing key.
+const KeyID = "test-cert-key"
+
+var Key = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x3c}, ed25519.SeedSize))
+
+// IssuedAt is when Cert signs.
+var IssuedAt = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
+
+// Keys is the key table holding Key under KeyID.
+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.
+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",
+ 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",
+ }
+}
+
+// Cert is Snapshot(image, hosts...) signed with Key at IssuedAt.
+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.
+func Set(certs ...hostedcert.Certificate) *ctlcert.Set {
+ s := ctlcert.NewSet()
+ if _, err := s.Replace(Keys(), certs); err != nil {
+ panic(err)
+ }
+ return s
+}
+
+// KeysJSON is a key file holding Key under KeyID.
+func KeysJSON() []byte {
+ return []byte(`{"keys":[{"id":"` + KeyID + `","public_key":"` +
+ base64.StdEncoding.EncodeToString(Key.Public().(ed25519.PublicKey)) + `"}]}`)
+}
+
+// CertsJSON is a certificate file holding certs.
+func CertsJSON(certs ...hostedcert.Certificate) []byte {
+ if certs == nil {
+ certs = []hostedcert.Certificate{}
+ }
+ b, err := json.Marshal(map[string]any{"certificates": certs})
+ if err != nil {
+ panic(err)
+ }
+ return b
+}
diff --git a/internal/hostedctl/egress_test.go b/internal/hostedctl/egress_test.go
index 6cedc6f5..9c82d68f 100644
--- a/internal/hostedctl/egress_test.go
+++ b/internal/hostedctl/egress_test.go
@@ -47,9 +47,13 @@ func svc(host string) []hostedwire.Service {
return []hostedwire.Service{{Host: host, Port: 443, Class: hostedwire.ServiceInstance}}
}
+// A certification launch is the operator's (Task 5's route), so an
+// instance key's is refused before the manifest is read; only checks are
+// tried here until then. ctlegress's TestManifestForBothPurposes covers
+// both purposes.
func TestUnsetServiceBlocksLaunch(t *testing.T) {
t.Parallel()
- for _, purpose := range []string{hostedwire.PurposeChecks, hostedwire.PurposeCertification} {
+ for _, purpose := range []string{hostedwire.PurposeChecks} {
for name, m := range map[string]ctlegress.Manifest{"unset host": testManifest(""), "no manifest": {}} {
e := newLaunchEnv(t)
e.cfg.Manifest = m
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go
index c68c030f..95e7666e 100644
--- a/internal/hostedctl/http.go
+++ b/internal/hostedctl/http.go
@@ -78,7 +78,7 @@ var apiErrors = []apiError{
{hostedwire.ErrDuration, http.StatusBadRequest, "invalid", "The request has a field out of range."},
{isolatedjob.ErrBootstrapTooLarge, http.StatusBadRequest, "invalid", "The request has a field out of range."},
{isolatedjob.ErrInvalid, http.StatusBadRequest, "invalid", "The request has a field out of range."},
- {ErrImageNotAllowed, http.StatusBadRequest, "image_not_allowed", "The image is not in the allowlist."},
+ {ErrNotCertified, http.StatusBadRequest, "not_certified", "No valid certificate covers the image for this deployment."},
{ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."},
{errNoRoute, http.StatusNotFound, "no_route", "No such route."},
{isolatedjob.ErrNotFound, http.StatusNotFound, "not_found", "Not found."},
@@ -88,6 +88,7 @@ var apiErrors = []apiError{
{ErrNotQuiescent, http.StatusConflict, "not_quiescent", "No quiescent acknowledgement for this pause generation."},
{ErrResumePending, http.StatusConflict, "resume_pending", "A resume is pending. Retry with its operation ID."},
{ErrReplacementLive, http.StatusConflict, "replacement_live", "The replaced attempt is not proven stopped."},
+ {ErrLaunchExpired, http.StatusConflict, "launch_expired", "The launch-by time has passed."},
{ErrStateUnknown, http.StatusConflict, "state_unknown", "The provider reports an unknown VM state."},
{isolatedjob.ErrConflict, http.StatusConflict, "conflict", "The job's state does not allow that."},
{ErrPastDeadline, http.StatusGone, "past_deadline", "The job's stop time has passed."},
@@ -143,8 +144,10 @@ type route struct {
serve func(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error)
}
-// jobActions are the POST routes under /v1/jobs/{attempt}/.
+// jobActions are the routes under /v1/jobs/{attempt}/: admission is a GET,
+// the rest POSTs.
var jobActions = map[string]route{
+ "admission": {"admission", http.MethodGet, hostedwire.RoleInstance, serveAdmission},
"stop": {"stop", http.MethodPost, hostedwire.RoleInstance, serveStop},
"drain": {"drain", http.MethodPost, hostedwire.RoleInstance, serveDrain},
"quiescent": {"quiescent", http.MethodPost, hostedwire.RoleInstance, serveQuiescent},
@@ -444,6 +447,12 @@ func serveGet(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedw
return wireView(v), nil
}
+// serveAdmission: like serveGet, Admission checks that by created the
+// attempt.
+func serveAdmission(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, attempt string, _ []byte) (any, error) {
+ return c.Admission(ctx, by, attempt)
+}
+
func wireView(v JobView) hostedwire.JobView {
return hostedwire.JobView{AttemptID: v.AttemptID, LaunchID: v.LaunchID, State: v.State, VMRef: v.VMRef, Epoch: v.Epoch,
DeadlineInMS: v.DeadlineIn.Milliseconds(), DrainInMS: v.DrainIn.Milliseconds(), StopInMS: v.StopIn.Milliseconds()}
diff --git a/internal/hostedctl/http_test.go b/internal/hostedctl/http_test.go
index afec3218..365d661d 100644
--- a/internal/hostedctl/http_test.go
+++ b/internal/hostedctl/http_test.go
@@ -194,6 +194,7 @@ func jobRoutes(attempt string) []struct {
body any
}{
{"GET", p, nil},
+ {"GET", p + "/admission", nil},
{"POST", p + "/stop", hostedwire.StopRequest{Reason: "done"}},
{"POST", p + "/drain", hostedwire.DrainRequest{}},
{"POST", p + "/quiescent", hostedwire.QuiescentRequest{Generation: 1}},
@@ -570,7 +571,7 @@ func TestRoutesMapErrorsToStatus(t *testing.T) {
err error
want int
}{
- {isolatedjob.ErrInvalid, 400}, {hostedwire.ErrBadJSON, 400}, {ErrImageNotAllowed, 400},
+ {isolatedjob.ErrInvalid, 400}, {hostedwire.ErrBadJSON, 400}, {ErrNotCertified, 400}, {ErrLaunchExpired, 409},
{hostedwire.ErrBadSignature, 401}, {hostedwire.ErrSkew, 401}, {hostedwire.ErrReplay, 401}, {hostedwire.ErrUnknownKey, 401},
{ErrForbidden, 403}, {isolatedjob.ErrNotFound, 404},
{isolatedjob.ErrConflict, 409}, {ErrGenerationCancelled, 409}, {ErrNotQuiescent, 409}, {ErrResumePending, 409},
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go
index 8d750928..62bd5ed7 100644
--- a/internal/hostedctl/launch.go
+++ b/internal/hostedctl/launch.go
@@ -14,6 +14,8 @@ import (
"strings"
"time"
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -23,8 +25,9 @@ var (
ErrDisabled = errors.New("hostedctl: hosted launches are disabled")
// ErrForbidden: the verified key's role may not make this call.
ErrForbidden = errors.New("hostedctl: this key may not do that")
- // ErrImageNotAllowed: the image digest is not in Config.Images.
- ErrImageNotAllowed = errors.New("hostedctl: image is not in the allowlist")
+ // ErrLaunchExpired: the controller's wall clock is past the request's
+ // launch-by time.
+ ErrLaunchExpired = errors.New("hostedctl: the launch-by time has passed")
// ErrReplacementLive: the attempt named in Replaces is unknown, belongs
// to another key, or has no stop proof yet.
ErrReplacementLive = errors.New("hostedctl: replaced attempt is not proven stopped")
@@ -115,16 +118,19 @@ func Deadlines(launched T, lifetime time.Duration) (deadline, drain, stop T) {
// Launch saves a launch intent for q and then asks the provider for the VM.
//
// In order it refuses: launches switched off (ErrDisabled); a key without
-// RoleInstance (ErrForbidden); a malformed request (isolatedjob.ErrInvalid,
+// RoleInstance, or a certification launch, which is the operator's
+// (ErrForbidden); a malformed request (isolatedjob.ErrInvalid,
// or ErrBootstrapTooLarge; see checkRequest for the controller's own
-// limits); an image outside Config.Images (ErrImageNotAllowed); a purpose
+// limits); a wall clock past q.LaunchByUnixMS (ErrLaunchExpired); a purpose
// whose egress services are not all set (ctlegress.ErrServiceUnset); no
-// passing network audit begun within AuditMaxAge (ErrNetworkAudit). Each
-// refusal is audited and creates nothing.
+// certificate in Config.Certs for the image covering every instance host of
+// those services (ErrNotCertified); no passing network audit begun within
+// AuditMaxAge (ErrNetworkAudit). Each refusal is audited and creates
+// nothing.
//
-// The services of Config.Manifest for q.Purpose are copied into the new
-// intent (jobs.services_json) and never change; a later manifest never
-// reaches a saved intent, and Replay never reads it.
+// The services of Config.Manifest for q.Purpose, the certificate's digest
+// and the launch-by time are copied into the new intent and never change;
+// a later manifest never reaches a saved intent, and Replay never reads it.
//
// Transaction 1 then looks up q.AttemptID. A job saved for the same request
// by the same key is returned as it stands, with no provider call; a
@@ -136,8 +142,9 @@ 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 or the stop time reached abandons the intent
-// (JobAbandoned); launches off, the image dropped or no fresh passing audit
+// call: a stop asked for, the stop time reached or the launch-by time
+// passed abandons the intent (JobAbandoned); 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
// before it is not enough.
@@ -156,21 +163,28 @@ func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hosted
if by == "" || key.Role != hostedwire.RoleInstance {
return c.refuse(ctx, by, q, fmt.Errorf("%w: launch needs an instance key", ErrForbidden))
}
+ if q.Purpose == hostedwire.PurposeCertification {
+ return c.refuse(ctx, by, q, fmt.Errorf("%w: certification launches are the operator's", ErrForbidden))
+ }
if err := c.checkRequest(q); err != nil {
return c.refuse(ctx, by, q, err)
}
- if !c.cfg.Images[q.Image] {
- return c.refuse(ctx, by, q, fmt.Errorf("%w: %s", ErrImageNotAllowed, q.Image))
+ if why := launchExpired(q.LaunchByUnixMS, c.store.wall()); why != "" {
+ return c.refuse(ctx, by, q, fmt.Errorf("%w: %s", ErrLaunchExpired, why))
}
services, err := c.cfg.Manifest.For(q.Purpose)
if err != nil {
return c.refuse(ctx, by, q, err)
}
+ cert, err := c.cfg.Certs.For(q.Image, ctlcert.InstanceHosts(services))
+ if err != nil {
+ return c.refuse(ctx, by, q, err)
+ }
if err := c.audit.check(c.store.Clock().Now()); err != nil {
return c.refuse(ctx, by, q, err)
}
- view, created, err := c.saveIntent(ctx, by, q, services)
+ view, created, err := c.saveIntent(ctx, by, q, services, hostedcert.Digest(cert))
if err != nil || !created {
return view, err
}
@@ -327,10 +341,11 @@ func decodeSpec(text, attempt string) (isolatedjob.LaunchSpec, error) {
// saveIntent is transaction 1. It returns the existing job's view when the
// same request was saved before (created false), or draws a launch ID,
-// builds the spec, saves the new intent with its services snapshot and
-// returns its view (created true). A conflict or a live replaced attempt is audited, committed, and
+// builds the spec, saves the new intent with its services snapshot,
+// certificate digest and launch-by time, and returns its view (created
+// true). A conflict or a live replaced attempt is audited, committed, and
// returned as the error.
-func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q LaunchRequest, services []hostedwire.Service) (JobView, bool, error) {
+func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q LaunchRequest, services []hostedwire.Service, cert string) (JobView, bool, error) {
hash := requestHash(by, q)
servicesJSON, err := json.Marshal(services)
if err != nil {
@@ -382,10 +397,12 @@ func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q Laun
deadline, drain, stop := Deadlines(now, spec.MaxLifetime)
replaces := sql.NullString{String: q.Replaces, Valid: q.Replaces != ""}
if _, err := tx.ExecContext(ctx, `INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key,
- purpose, replaces_attempt, spec_json, spec_sha256, provider_fingerprint, services_json, state, launched_t, deadline_t, drain_t, stop_t)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ purpose, replaces_attempt, spec_json, spec_sha256, provider_fingerprint, services_json, cert_digest, launch_by_unix_ms,
+ state, launched_t, deadline_t, drain_t, stop_t)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
q.AttemptID, launchID, q.TaskID, q.Account, string(by), q.Purpose, replaces, specJSON, hash,
- c.cfg.ProviderFingerprint(spec.Image, spec.Size), string(servicesJSON), JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
+ c.cfg.ProviderFingerprint(spec.Image, spec.Size), string(servicesJSON), cert, q.LaunchByUnixMS,
+ JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
return fmt.Errorf("hostedctl: save launch intent: %w", err)
}
a.Action = actionLaunchIntent
@@ -431,15 +448,17 @@ func checkReplaces(ctx context.Context, tx *sql.Tx, by hostedwire.KeyID, attempt
// true) both create VMs only through it.
//
// In its own transaction it re-reads the row. An intent no longer waiting,
-// or holding a Ref, is returned as it stands. A stop asked for, or the stop
-// time reached, marks it JobAbandoned with an audit row; so does a provider
+// or holding a Ref, is returned as it stands. A stop asked for, the stop
+// time reached, or the launch-by time passed (wall clock) marks it
+// JobAbandoned with an audit row; so does a provider
// fingerprint other than the one saved with the intent (R29), which also
// raises an AlertConfigChanged alert. Then, outside the
// transaction and just before the call, it checks the transient gates
// (creatable); a failure is returned as gate with the waiting view and no
// provider call. Otherwise it records the dispatch marker (markDispatch,
-// R19), checks the stop time and the transient gates again once the marker
-// has committed, and only then calls the provider and settles the answer.
+// R19), checks the stop and launch-by times and the transient gates again
+// once the marker has committed, and only then calls the provider and
+// settles the answer.
func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attempt string, replay bool) (view JobView, gate, err error) {
// The attempt's lock (R18) is held from the gate check to the settled
// answer, so a Stop cannot land between them.
@@ -450,12 +469,13 @@ 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 stopAt T // the intent's stop time; the attempt lock keeps it still
+ var j jobRow // the intent as read; the attempt lock keeps its times still
ready, changed := false, false
err = c.store.Tx(ctx, func(tx *sql.Tx) error {
ready, changed = false, false
- j, found, err := loadJob(ctx, tx, attempt)
- if err != nil {
+ var found bool
+ var err error
+ if j, found, err = loadJob(ctx, tx, attempt); err != nil {
return err
}
if !found {
@@ -469,7 +489,7 @@ 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)
+ reason := 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
@@ -478,8 +498,7 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
view, err = abandonIntent(ctx, tx, actor, j, replay, reason, now)
return err
}
- view, stopAt = j.view(now), T(j.stopT)
- ready = true
+ view, ready = j.view(now), true
return nil
})
if err != nil {
@@ -491,7 +510,7 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
if !ready {
return view, nil, nil
}
- if gate := c.creatable(spec.Image, c.store.Clock().Now()); gate != nil {
+ if gate := c.creatable(j, c.store.Clock().Now()); gate != nil {
return view, gate, nil
}
if c.beforeMark != nil {
@@ -501,12 +520,13 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
return JobView{}, nil, err
}
// The marker's transaction may have queued for the store while the stop
- // time passed or the audit failed or went stale, so both are checked
- // again once it commits, in memory, immediately before the call.
- if now := c.store.Clock().Now(); now >= stopAt {
+ // or launch-by time passed or the audit failed or went stale, so they
+ // are checked again once it commits, in memory, immediately before the
+ // call.
+ if now := c.store.Clock().Now(); now >= T(j.stopT) || launchExpired(j.launchBy, c.store.wall()) != "" {
view, err = c.abandonDue(ctx, actor, attempt, replay)
return view, nil, err
- } else if gate := c.creatable(spec.Image, now); gate != nil {
+ } else if gate := c.creatable(j, now); gate != nil {
return view, gate, nil
}
// R21: c.runner bounds the call by ProviderLaunchTimeout, so no launch
@@ -640,10 +660,12 @@ func (c *Controller) saveRef(ctx context.Context, actor hostedwire.KeyID, attemp
// egress manifest is never read. Before each provider call the gates are
// re-checked:
//
-// - a stop asked for, the intent's stop time reached, or provider
-// settings changed since it was saved (config_changed, alerted): the
-// intent is marked JobAbandoned and audited, and never replayed again;
-// - launches switched off, the image no longer allowed, or no passing
+// - a stop asked for, the intent's stop time reached, its launch-by time
+// passed (wall clock), or provider settings changed since it was saved
+// (config_changed, alerted): the intent is marked JobAbandoned and
+// audited, and never replayed again; a VM a lost reply made for it is
+// an orphan, which the reaper stops;
+// - launches switched off, its certificate no longer valid, or no passing
// audit begun within AuditMaxAge: the intent stays JobWaiting for a later
// pass, with no audit row, as nothing changed.
//
@@ -720,7 +742,7 @@ 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)
+ reason := abandonReason(j, now, c.store.wall())
if j.state != JobWaiting || j.ref.Valid || reason == "" {
view = j.view(now)
return nil
@@ -748,25 +770,39 @@ 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, or its stop time has come.
-func abandonReason(j jobRow, now T) string {
+// 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 {
if j.stopRequested.Valid {
return "stop asked for before the VM was launched"
}
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 launchExpired(j.launchBy, wall)
+}
+
+// launchExpired returns why the launch-by time launchByMS (Unix
+// milliseconds) has passed at wall, or "" when it has not. Zero, an intent
+// saved before launch-by times were kept, has passed.
+func launchExpired(launchByMS int64, wall time.Time) string {
+ if by := time.UnixMilli(launchByMS); wall.After(by) {
+ return fmt.Sprintf("launch-by time %s passed before the VM was launched (%v after it)",
+ by.UTC().Format(time.RFC3339Nano), wall.Sub(by))
+ }
return ""
}
-// creatable checks the transient creation gates: launches on, the image
-// still allowed, and a passing audit begun within AuditMaxAge.
-func (c *Controller) creatable(img isolatedjob.ImageDigest, now T) error {
+// creatable checks the transient creation gates for intent j: launches on,
+// its certificate still valid, and a passing audit begun within
+// AuditMaxAge. Only a checks intent has a certificate; a legacy slice 1a
+// intent (purpose "task") or any other purpose is never creatable here.
+func (c *Controller) creatable(j jobRow, now T) error {
if !c.cfg.Enabled {
return ErrDisabled
}
- if !c.cfg.Images[img] {
- return fmt.Errorf("%w: %s", ErrImageNotAllowed, img)
+ if j.purpose != hostedwire.PurposeChecks || !c.cfg.Certs.Valid(j.certDigest) {
+ return fmt.Errorf("%w: %s intent's certificate %q is not valid now", ErrNotCertified, j.purpose, j.certDigest)
}
return c.audit.check(now)
}
@@ -775,8 +811,9 @@ func (c *Controller) creatable(img isolatedjob.ImageDigest, now T) error {
type jobRow struct {
attempt, launchID, task, account, actor, state, specJSON, specSHA string
fingerprint string // provider_fingerprint
+ purpose, certDigest string
ref sql.NullString
- launchedT, deadlineT, drainT, stopT, epoch int64
+ launchedT, deadlineT, drainT, stopT, epoch, launchBy int64 // launchBy: Unix ms, wall clock
stopRequested sql.NullInt64
stopProof sql.NullString
}
@@ -785,10 +822,10 @@ type jobRow struct {
func loadJob(ctx context.Context, tx *sql.Tx, attempt string) (jobRow, bool, error) {
var j jobRow
err := tx.QueryRowContext(ctx, `SELECT attempt_id, launch_id, task_id, account_id, actor_key, state,
- spec_json, spec_sha256, provider_fingerprint, vm_ref, launched_t, deadline_t, drain_t, stop_t, epoch, stop_requested_t,
- stop_proof_json FROM jobs WHERE attempt_id = ?`, attempt).Scan(&j.attempt, &j.launchID, &j.task, &j.account, &j.actor,
- &j.state, &j.specJSON, &j.specSHA, &j.fingerprint, &j.ref, &j.launchedT, &j.deadlineT, &j.drainT, &j.stopT, &j.epoch,
- &j.stopRequested, &j.stopProof)
+ spec_json, spec_sha256, provider_fingerprint, purpose, cert_digest, vm_ref, launched_t, deadline_t, drain_t, stop_t, epoch,
+ launch_by_unix_ms, stop_requested_t, stop_proof_json FROM jobs WHERE attempt_id = ?`, attempt).Scan(&j.attempt, &j.launchID,
+ &j.task, &j.account, &j.actor, &j.state, &j.specJSON, &j.specSHA, &j.fingerprint, &j.purpose, &j.certDigest, &j.ref,
+ &j.launchedT, &j.deadlineT, &j.drainT, &j.stopT, &j.epoch, &j.launchBy, &j.stopRequested, &j.stopProof)
switch {
case errors.Is(err, sql.ErrNoRows):
return jobRow{}, false, nil
diff --git a/internal/hostedctl/launch_test.go b/internal/hostedctl/launch_test.go
index b169e440..c07f9661 100644
--- a/internal/hostedctl/launch_test.go
+++ b/internal/hostedctl/launch_test.go
@@ -14,6 +14,7 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -57,7 +58,7 @@ func newLaunchEnv(t *testing.T) *launchEnv {
e := &launchEnv{
t: t, ctx: context.Background(), path: filepath.Join(t.TempDir(), "hosted.db"),
clk: clk, gc: &gateClock{FakeClock: clk}, fake: fake, run: fake,
- cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true, imgB: true},
+ cfg: Config{Enabled: true, Certs: testCerts(),
ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Manifest: testManifest("equipo.example.com")},
}
e.store = openStore(t, e.path, e.gc)
@@ -360,6 +361,14 @@ func TestLaunchIdempotentOnAttempt(t *testing.T) {
}
func TestLaunchConflictOnChangedRequest(t *testing.T) {
+ // An instance key's certification request is refused before the hash is
+ // compared (it is the operator's), so the purpose's place in the hash is
+ // checked directly.
+ cert := request("att-1")
+ cert.Purpose = hostedwire.PurposeCertification
+ if requestHash("inst-1", cert) == requestHash("inst-1", request("att-1")) {
+ t.Fatal("requestHash ignores the purpose")
+ }
cases := []struct {
name string
by hostedwire.KeyID
@@ -371,7 +380,6 @@ func TestLaunchConflictOnChangedRequest(t *testing.T) {
{"size", "inst-1", func(q *LaunchRequest) { q.Size = isolatedjob.SizeLarge }},
{"lifetime", "inst-1", func(q *LaunchRequest) { q.MaxLifetime = 3 * time.Hour }},
{"instance code", "inst-1", func(q *LaunchRequest) { q.InstanceCode = "code-other" }},
- {"purpose", "inst-1", func(q *LaunchRequest) { q.Purpose, q.Person = hostedwire.PurposeCertification, "" }},
{"person", "inst-1", func(q *LaunchRequest) { q.Person = "person-2" }},
{"launch-by", "inst-1", func(q *LaunchRequest) { q.LaunchByUnixMS++ }},
{"another key", "inst-2", func(*LaunchRequest) {}},
@@ -785,7 +793,8 @@ func TestLaunchRefusals(t *testing.T) {
{name: "flag off", setup: func(e *launchEnv) { e.cfg.Enabled = false; e.newController(); e.audit() }, want: ErrDisabled},
{name: "operator role", key: opKey, want: ErrForbidden},
{name: "no key ID", by: "-", want: ErrForbidden},
- {name: "image not allowed", edit: func(q *LaunchRequest) { q.Image = imgOther }, want: ErrImageNotAllowed},
+ {name: "image not certified", edit: func(q *LaunchRequest) { q.Image = imgOther }, want: ErrNotCertified},
+ {name: "past launch-by", setup: func(e *launchEnv) { e.clk.SetWall(time.UnixMilli(testLaunchBy + 1)) }, want: ErrLaunchExpired},
{name: "no audit yet", setup: func(e *launchEnv) { e.newController() }, want: ErrNetworkAudit},
{name: "stale audit", setup: func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, want: ErrNetworkAudit},
{name: "audit exactly 5 min old", setup: func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge) }},
@@ -901,7 +910,9 @@ func TestThrottleThenRefusal(t *testing.T) {
want string
}{
{"flag off", func(e *launchEnv) { e.c.cfg.Enabled = false }, func(e *launchEnv) { e.c.cfg.Enabled = true }, JobWaiting},
- {"image removed", func(e *launchEnv) { delete(e.c.cfg.Images, imgA) }, func(e *launchEnv) { e.c.cfg.Images[imgA] = true }, JobWaiting},
+ {"certificate withdrawn", func(e *launchEnv) { e.replaceCerts(ctlcerttest.Keys(), nil) },
+ func(e *launchEnv) { e.replaceCerts(ctlcerttest.Keys(), testCertList()) }, JobWaiting},
+ {"launch-by passed", func(e *launchEnv) { e.clk.SetWall(time.UnixMilli(testLaunchBy + 1)) }, nil, JobAbandoned},
{"stale audit", func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, func(e *launchEnv) { e.audit() }, JobWaiting},
{"failing audit", func(e *launchEnv) {
e.fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, RouteOutAbsent: true}, nil)
diff --git a/internal/hostedctl/reaper_test.go b/internal/hostedctl/reaper_test.go
index 6c4df76f..2345b4bc 100644
--- a/internal/hostedctl/reaper_test.go
+++ b/internal/hostedctl/reaper_test.go
@@ -11,6 +11,7 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -723,7 +724,7 @@ func TestReapDefersOrphansWhileIntentWaits(t *testing.T) {
}
}},
{"launches off", func(e *launchEnv) { e.c.cfg.Enabled = false }},
- {"image removed", func(e *launchEnv) { delete(e.c.cfg.Images, imgA) }},
+ {"certificate withdrawn", func(e *launchEnv) { e.replaceCerts(ctlcerttest.Keys(), nil) }},
{"audit failing", func(e *launchEnv) {
e.fake.SetAudit(bad, nil)
_ = e.c.RunAudit(e.ctx) // recorded now, so the first pass's replay is gated too
diff --git a/internal/hostedctl/schema/0003_cert.sql b/internal/hostedctl/schema/0003_cert.sql
new file mode 100644
index 00000000..aa29db7f
--- /dev/null
+++ b/internal/hostedctl/schema/0003_cert.sql
@@ -0,0 +1,20 @@
+-- Schema version 3: each launch intent keeps what it was admitted under.
+--
+-- cert_digest is the hostedcert.Digest of the image certificate a checks
+-- launch was admitted under; the admission record reports whether that
+-- certificate is still valid. Intents saved before this version keep '',
+-- which no certificate has.
+--
+-- launch_by_unix_ms is the request's launch-by time, wall clock, Unix
+-- milliseconds: no provider call for the intent is made after it. Intents
+-- saved before this version keep 0, which has passed, so they never launch.
+ALTER TABLE jobs ADD COLUMN cert_digest TEXT NOT NULL DEFAULT '';
+ALTER TABLE jobs ADD COLUMN launch_by_unix_ms INTEGER NOT NULL DEFAULT 0;
+
+-- Like the spec and the services snapshot, neither ever changes.
+CREATE TRIGGER jobs_admission_immutable
+BEFORE UPDATE OF cert_digest, launch_by_unix_ms ON jobs
+WHEN NEW.cert_digest IS NOT OLD.cert_digest OR NEW.launch_by_unix_ms IS NOT OLD.launch_by_unix_ms
+BEGIN
+ SELECT RAISE(ABORT, 'admission record is immutable');
+END;
diff --git a/internal/hostedctl/sim_test.go b/internal/hostedctl/sim_test.go
index c6087145..67159323 100644
--- a/internal/hostedctl/sim_test.go
+++ b/internal/hostedctl/sim_test.go
@@ -17,11 +17,17 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
)
+// simLaunchBy is every simulated request's launch-by time: far beyond any
+// wall clock the simulation reaches, as its model does not cover launch-by
+// (TestLaunchByEnforced does).
+var simLaunchBy = testWall.AddDate(10, 0, 0).UnixMilli()
+
// TestLifecycleSimulation drives the real controller, over the real store
// and the fake provider, through random launches, crashes, provider faults,
// pauses, resumes, orphans, stops, wall-clock jumps and time advances, and
@@ -222,7 +228,7 @@ func newSimWorld(dir string, seed int64) *simWorld {
w := &simWorld{
seed: seed, rng: rand.New(rand.NewSource(seed)), ctx: context.Background(),
path: filepath.Join(dir, fmt.Sprintf("sim-%d.db", seed)), clk: clk, fake: fake,
- cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true},
+ cfg: Config{Enabled: true, Certs: ctlcerttest.Set(ctlcerttest.Cert(imgA, "equipo.example.com")),
ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Manifest: testManifest("equipo.example.com")},
m: simModel{req: map[string]LaunchRequest{}, stopAt: map[string]T{}, pause: map[string]*simPause{},
ops: map[string][]string{}, done: map[[2]string]int64{}, deferral: map[isolatedjob.Ref]*simDeferral{}},
@@ -543,7 +549,7 @@ func (w *simWorld) newRequest(replaces string) LaunchRequest {
}
q := LaunchRequest{AttemptID: id, TaskID: "task-" + id, Account: "acct-1", Replaces: replaces,
Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: life, InstanceCode: testCode,
- Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: testLaunchBy}
+ Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: simLaunchBy}
w.m.req[id] = q
return q
}
diff --git a/internal/hostedctl/stop.go b/internal/hostedctl/stop.go
index 4e6908e8..57e20f0b 100644
--- a/internal/hostedctl/stop.go
+++ b/internal/hostedctl/stop.go
@@ -93,11 +93,24 @@ func notCreator(attempt string) error {
// ErrForbidden and an audit row. Get makes no provider call.
func (c *Controller) Get(ctx context.Context, by hostedwire.KeyID, attemptID string) (JobView, error) {
var view JobView
+ err := c.readOwn(ctx, by, attemptID, actionGetRefused, func(j jobRow, now T) error { view = j.view(now); return nil })
+ if err != nil {
+ return JobView{}, err
+ }
+ return view, nil
+}
+
+// readOwn calls read with attemptID's row and the controller time, in one
+// transaction, if by is the key that launched it, and returns read's error.
+// Otherwise it audits a row with action refused and returns
+// isolatedjob.ErrInvalid for a malformed attempt ID, or the same
+// ErrForbidden for another key's attempt and for an unknown one.
+func (c *Controller) readOwn(ctx context.Context, by hostedwire.KeyID, attemptID, refused string, read func(jobRow, T) error) error {
var refusal error
err := c.store.Tx(ctx, func(tx *sql.Tx) error {
- view, refusal = JobView{}, nil
+ refusal = nil
now := c.store.Clock().Now()
- a := Audit{Actor: by, Action: actionGetRefused, At: now}
+ a := Audit{Actor: by, Action: refused, At: now}
if !printableASCII(attemptID, maxNameLen) {
refusal = fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)
a.Reason = refusal.Error()
@@ -116,16 +129,12 @@ func (c *Controller) Get(ctx context.Context, by hostedwire.KeyID, attemptID str
a.Reason = refusal.Error()
return appendAudit(tx, a)
}
- view = j.view(now)
- return nil
+ return read(j, now)
})
if err != nil {
- return JobView{}, err
- }
- if refusal != nil {
- return JobView{}, refusal
+ return err
}
- return view, nil
+ return refusal
}
// Stop asks for attempt's VM to stop and returns proof once it has.
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go
index f4c4c163..08295493 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"}
+var migrations = []string{"schema/0001_jobs.sql", "schema/0002_egress.sql", "schema/0003_cert.sql"}
// schemaVersion is the newest schema this code knows.
func schemaVersion() int { return len(migrations) }
@@ -309,6 +309,10 @@ func (s *Store) release() error {
// Clock returns the store's controller clock.
func (s *Store) Clock() *CtlClock { return s.clock }
+// wall reads the host's wall clock: only for launch-by times, which the
+// instance sets in wall time.
+func (s *Store) wall() time.Time { return s.host.Wall() }
+
// Restarted reports whether Open found state from an earlier run. When it
// is true, the time that passed while the controller was down is unknown.
// The wall delta Open added to T is untrusted in either direction: the
diff --git a/internal/hostedctl/store_test.go b/internal/hostedctl/store_test.go
index d7debb1a..7f31de36 100644
--- a/internal/hostedctl/store_test.go
+++ b/internal/hostedctl/store_test.go
@@ -554,9 +554,9 @@ func testFingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string {
return "fp/" + string(d) + "/" + string(s)
}
-// testConfig is a Config with only the required provider fields set.
+// testConfig is a Config with only the required fields set.
func testConfig() Config {
- return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint}
+ return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Certs: testCerts()}
}
func TestNewRefusesNilDependency(t *testing.T) {
@@ -584,6 +584,11 @@ func TestNewRefusesNilDependency(t *testing.T) {
t.Errorf("New with %s = %v, want the error to name the %s", c.name, err, c.want)
}
}
+ noCerts := testConfig()
+ noCerts.Certs = nil
+ if got, err := New(noCerts, full); err == nil || got != nil || !strings.Contains(err.Error(), "certificate") {
+ t.Errorf("New with no certificate set = (%v, %v), want (nil, an error naming the certificates)", got, err)
+ }
}
// TestProviderNamespaceBound: the first controller binds the database to its
diff --git a/internal/hostedwire/api.go b/internal/hostedwire/api.go
index 04f5af08..11d881d9 100644
--- a/internal/hostedwire/api.go
+++ b/internal/hostedwire/api.go
@@ -20,6 +20,7 @@ import (
//
// POST /v1/jobs LaunchRequest -> JobView
// GET /v1/jobs/{attempt} (empty body) -> JobView
+// GET /v1/jobs/{attempt}/admission (empty body) -> AdmissionView
// POST /v1/jobs/{attempt}/stop StopRequest -> StopProof
// POST /v1/jobs/{attempt}/drain DrainRequest -> DrainResponse
// POST /v1/jobs/{attempt}/quiescent QuiescentRequest -> QuiescentResponse