hostedctl: operator routes for certification and reload
Operator-only routes: POST /v1/cert/launch, GET /v1/certs, POST /v1/admin/reload, POST /v1/admin/restart (signed 202, then exit 0 once requests in flight finish), POST /v1/admin/alert-test (one "test" alert) and GET /v1/status (audit, provider binding, proxy feed ages, enabled, last clean reaper pass). A certification launch needs its image in certification-images.json, bound to the provider's version at the size asked for; it shares Launch's path, is gated again at dispatch, and holds no certificate. Reload re-reads the key, certificate and certification images files from local disk; a bad file keeps both old sets. Logic in the new ctlops package; hostedctl gains wiring only (budget record raised).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
20 files changed,
+1,367
−56
.rastrillo/budgets.txt+1 −1cmd/equipo-hosted-controller/config.go+15 −23cmd/equipo-hosted-controller/config_test.go+40 −13cmd/equipo-hosted-controller/main.go+23 −3cmd/equipo-hosted-controller/main_test.go+105 −0docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+29 −0internal/hostedclient/client.go+6 −0internal/hostedctl/controller.go+8 −0internal/hostedctl/ctlcert/certs.go+17 −0internal/hostedctl/ctlops/ops.go+216 −0internal/hostedctl/ctlops/ops_test.go+120 −0internal/hostedctl/http.go+20 −1internal/hostedctl/http_test.go+6 −1internal/hostedctl/launch.go+28 −10internal/hostedctl/operator_test.go+389 −0internal/hostedctl/ops.go+202 −0internal/hostedctl/reaper.go+5 −0internal/hostedwire/hosted.go+19 −3internal/hostedwire/hosted_test.go+24 −1internal/hostedwire/ops.go+94 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 7f946e58..bdf3e083 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 5689 9355 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. |
| +size internal/hostedctl 5939 9749 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. |
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go| index 556001e9..8c856c1f 100644 |
| --- a/cmd/equipo-hosted-controller/config.go |
| +++ b/cmd/equipo-hosted-controller/config.go |
| @@ -14,6 +14,7 @@ import ( |
| "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/hostedctl/ctlops" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| @@ -70,6 +71,13 @@ type fileConfig struct { |
| // starting. |
| CertKeysFile string `json:"cert_keys_file"` |
| CertificatesFile string `json:"certificates_file"` |
| + // CertificationImagesFile lists the images an operator may launch for |
| + // certification (ctlops.Candidates): one JSON array of {"digest", |
| + // "image_arn", "version_arn"}, each version one images launches its |
| + // digest with at some size. POST /v1/admin/reload re-reads it with the |
| + // two certificate files; a file that does not check stops the |
| + // controller starting, or fails the reload and keeps the old sets. |
| + CertificationImagesFile string `json:"certification_images_file"` |
| // ProxyCACertFile and ProxyCAKeyFile are the egress proxies' client CA |
| // (ctlproxy.NewCA), which signs each VM's proxy certificate: one PEM |
| // certificate, and its ECDSA P-256 key in PEM, which group and others |
| @@ -151,7 +159,8 @@ 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, "cert_keys_file": fc.CertKeysFile, "certificates_file": fc.CertificatesFile, |
| - "proxy_ca_cert_file": fc.ProxyCACertFile, "proxy_ca_key_file": fc.ProxyCAKeyFile, "proxy_code_key_file": fc.ProxyCodeKeyFile} { |
| + "certification_images_file": fc.CertificationImagesFile, |
| + "proxy_ca_cert_file": fc.ProxyCACertFile, "proxy_ca_key_file": fc.ProxyCAKeyFile, "proxy_code_key_file": fc.ProxyCodeKeyFile} { |
| if v == "" { |
| return config{}, fmt.Errorf("%s is required", name) |
| } |
| @@ -170,8 +179,11 @@ func (fc fileConfig) check() (config, error) { |
| if c.ctl.Manifest, err = readManifest(fc.EgressManifestFile); err != nil { |
| return config{}, err |
| } |
| - if c.ctl.Certs, err = readCerts(fc.CertKeysFile, fc.CertificatesFile, c.aws.ImageVersion); err != nil { |
| - return config{}, err |
| + c.ctl.Certs, c.ctl.Candidates = ctlcert.NewSet(c.aws.ImageVersion), ctlops.NewCandidates(c.aws.ImageVersion) |
| + c.ctl.Files = ctlops.Files{CertKeys: fc.CertKeysFile, Certificates: fc.CertificatesFile, CertificationImages: fc.CertificationImagesFile} |
| + if _, err := ctlops.Reload(c.ctl.Files, c.ctl.Certs, c.ctl.Candidates); err != nil { |
| + return config{}, fmt.Errorf("certificates %s (keys %s, certification images %s): %w", |
| + fc.CertificatesFile, fc.CertKeysFile, fc.CertificationImagesFile, err) |
| } |
| if c.ctl.ProxyCA, err = readProxyCA(fc.ProxyCACertFile, fc.ProxyCAKeyFile); err != nil { |
| return config{}, err |
| @@ -230,26 +242,6 @@ func readPrivate(path, what string) ([]byte, error) { |
| return raw, nil |
| } |
| -// readCerts reads the certificate key file and certificate file into a new |
| -// set bound to the adapter's image versions: a certificate whose signed |
| -// image version is not what images launches its digest with, at some size, |
| -// stops the controller starting. |
| -func readCerts(keysPath, certsPath string, versions ctlcert.ImageVersions) (*ctlcert.Set, error) { |
| - keys, err := os.ReadFile(keysPath) |
| - if err != nil { |
| - return nil, fmt.Errorf("certificate keys: %w", err) |
| - } |
| - certs, err := os.ReadFile(certsPath) |
| - if err != nil { |
| - return nil, fmt.Errorf("certificates: %w", err) |
| - } |
| - s := ctlcert.NewSet(versions) |
| - 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 0e6e46a9..09ee0083 100644 |
| --- a/cmd/equipo-hosted-controller/config_test.go |
| +++ b/cmd/equipo-hosted-controller/config_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlegress" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| @@ -50,6 +51,10 @@ func validConfig(t *testing.T, dir string) fileConfig { |
| if err := os.WriteFile(certsPath, ctlcerttest.CertsJSON(testCert), 0o600); err != nil { |
| t.Fatal(err) |
| } |
| + candidatesPath := filepath.Join(dir, "certification-images.json") |
| + if err := os.WriteFile(candidatesPath, []byte(`[{"digest":"`+testDigest+`","image_arn":"`+testImageARN+`","version_arn":"`+testImageARN+`:2"}]`), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| caCert, caKey := ctlproxytest.PEM() |
| caCertPath, caKeyPath := filepath.Join(dir, "proxy-ca.crt"), filepath.Join(dir, "proxy-ca.key") |
| if err := os.WriteFile(caCertPath, caCert, 0o644); err != nil { |
| @@ -73,15 +78,16 @@ func validConfig(t *testing.T, dir string) fileConfig { |
| Images: []imageEntry{{Digest: testDigest, ARN: testImageARN, |
| Versions: map[string]string{"small": "1", "large": "2"}}}, |
| Region: "eu-west-1", VPCID: "vpc-1", VMSubnetID: "subnet-1", VMSecurityGroupID: "sg-1", |
| - ConnectorARN: "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress:3", |
| - Egress: []string{}, |
| - SNSTopicARN: "arn:aws:sns:eu-west-1:123456789012:equipo-hosted", |
| - EgressManifestFile: manifestPath, |
| - CertKeysFile: certKeysPath, |
| - CertificatesFile: certsPath, |
| - ProxyCACertFile: caCertPath, |
| - ProxyCAKeyFile: caKeyPath, |
| - ProxyCodeKeyFile: codeKeyPath, |
| + ConnectorARN: "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress:3", |
| + Egress: []string{}, |
| + SNSTopicARN: "arn:aws:sns:eu-west-1:123456789012:equipo-hosted", |
| + EgressManifestFile: manifestPath, |
| + CertKeysFile: certKeysPath, |
| + CertificatesFile: certsPath, |
| + CertificationImagesFile: candidatesPath, |
| + ProxyCACertFile: caCertPath, |
| + ProxyCAKeyFile: caKeyPath, |
| + ProxyCodeKeyFile: codeKeyPath, |
| } |
| } |
| @@ -118,6 +124,25 @@ func TestCertificatesFromConfig(t *testing.T) { |
| t.Fatalf("For(testDigest, large) with only the small version certified = %v, want ErrNotCertified", err) |
| } |
| + // The certification images file names testDigest at its large version. |
| + if err := c.ctl.Candidates.Allows(testDigest, isolatedjob.SizeLarge); err != nil { |
| + t.Fatalf("candidate testDigest large = %v, want allowed", err) |
| + } |
| + if err := c.ctl.Candidates.Allows(testDigest, isolatedjob.SizeSmall); !errors.Is(err, ctlops.ErrNotCandidate) { |
| + t.Fatalf("candidate testDigest small (version 1, file names 2) = %v, want ErrNotCandidate", err) |
| + } |
| + if c.ctl.Files.CertificationImages == "" || c.ctl.Files.Certificates == "" || c.ctl.Files.CertKeys == "" { |
| + t.Fatalf("reload files = %+v, want all three", c.ctl.Files) |
| + } |
| + unbound := validConfig(t, dir) |
| + unbound.CertificationImagesFile = filepath.Join(dir, "unbound-images.json") |
| + if err := os.WriteFile(unbound.CertificationImagesFile, []byte(`[{"digest":"`+testDigest+`","image_arn":"`+testImageARN+`","version_arn":"`+testImageARN+`:9"}]`), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := loadFC(t, dir, unbound); !errors.Is(err, ctlops.ErrCandidates) { |
| + t.Fatalf("a certification image version images does not launch: config load = %v, want ErrCandidates", err) |
| + } |
| + |
| // Each certificate's signed image version must be what images launches |
| // its digest with, "<arn>:<version>", at some size. |
| writeCerts := func(name string, certs ...hostedcert.Certificate) string { |
| @@ -168,10 +193,12 @@ func TestCertificatesFromConfig(t *testing.T) { |
| 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") }, |
| + "bad signature": func(f *fileConfig) { f.CertificatesFile = badPath }, |
| + "no key file": func(f *fileConfig) { f.CertKeysFile = "" }, |
| + "no certificates file": func(f *fileConfig) { f.CertificatesFile = "" }, |
| + "no certification images file": func(f *fileConfig) { f.CertificationImagesFile = "" }, |
| + "missing certification images file": func(f *fileConfig) { f.CertificationImagesFile = filepath.Join(dir, "absent.json") }, |
| + "missing key file": func(f *fileConfig) { f.CertKeysFile = filepath.Join(dir, "absent.json") }, |
| } { |
| fc := validConfig(t, dir) |
| edit(&fc) |
diff --git a/cmd/equipo-hosted-controller/main.go b/cmd/equipo-hosted-controller/main.go| index cb58dc31..62d63f64 100644 |
| --- a/cmd/equipo-hosted-controller/main.go |
| +++ b/cmd/equipo-hosted-controller/main.go |
| @@ -44,10 +44,23 @@ const shutdownTimeout = 30 * time.Second |
| func main() { |
| path := flag.String("config", "", "path of the controller's JSON config file") |
| flag.Parse() |
| - if err := run(*path); err != nil { |
| + exitWith(run(*path)) |
| +} |
| + |
| +// exit ends the process; tests replace it. |
| +var exit = os.Exit |
| + |
| +// exitWith exits 1 after logging err, or 0 when err is nil: a signal or |
| +// POST /v1/admin/restart ended serve once its requests had finished, so |
| +// the service manager starts the controller again (its ExecStartPre |
| +// fetching the config first). |
| +func exitWith(err error) { |
| + if err != nil { |
| log.Printf("equipo-hosted-controller: %v", err) |
| - os.Exit(1) |
| + exit(1) |
| + return |
| } |
| + exit(0) |
| } |
| func run(path string) error { |
| @@ -57,6 +70,9 @@ func run(path string) error { |
| } |
| ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| defer stop() |
| + // The restart route ends ctx as a signal does: serve drains and returns. |
| + ctx, restart := context.WithCancel(ctx) |
| + defer restart() |
| // Bad TLS files or a busy address fail here, before the store is |
| // opened or any startup alert is sent. |
| @@ -113,7 +129,11 @@ func run(path string) error { |
| if err != nil { |
| return err |
| } |
| - api, err := c.Handler(hostedctl.HandlerConfig{Keys: cfg.keys, Signing: cfg.signing, Wall: clock.Wall, Metrics: metrics}) |
| + api, err := c.Handler(hostedctl.HandlerConfig{Keys: cfg.keys, Signing: cfg.signing, Wall: clock.Wall, Metrics: metrics, |
| + Restart: func() { |
| + log.Printf("equipo-hosted-controller: restart asked for; exiting once the requests in flight finish") |
| + restart() |
| + }}) |
| if err != nil { |
| return err |
| } |
diff --git a/cmd/equipo-hosted-controller/main_test.go b/cmd/equipo-hosted-controller/main_test.go| index 4efe524a..3cb07c05 100644 |
| --- a/cmd/equipo-hosted-controller/main_test.go |
| +++ b/cmd/equipo-hosted-controller/main_test.go |
| @@ -359,3 +359,108 @@ func TestShutdownDrainsRequests(t *testing.T) { |
| t.Fatalf("store Close after shutdown = %v", err) |
| } |
| } |
| + |
| +// heldRunner holds every Launch until release is closed, then launches |
| +// on the Fake. |
| +type heldRunner struct { |
| + *isolatedjob.Fake |
| + once sync.Once |
| + entered chan struct{} |
| + released chan struct{} |
| +} |
| + |
| +func (h *heldRunner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { |
| + h.once.Do(func() { close(h.entered) }) |
| + <-h.released |
| + return h.Fake.Launch(ctx, s) |
| +} |
| + |
| +// TestRestartAnswers202ThenExits: POST /v1/admin/restart by the operator |
| +// is answered 202 at once; serve then returns only after the request in |
| +// flight has finished, with no error, and the process exits 0 so the |
| +// service manager starts it again. Not parallel: it replaces exit. |
| +func TestRestartAnswers202ThenExits(t *testing.T) { |
| + hr := &heldRunner{entered: make(chan struct{}), released: make(chan struct{})} |
| + tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { hr.Fake = f; return hr }) |
| + opKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)) |
| + ctx, restart := context.WithCancel(context.Background()) |
| + defer restart() |
| + api, err := tc.c.Handler(hostedctl.HandlerConfig{Signing: ctlKey, Wall: tc.clk.Wall, Restart: restart, |
| + Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{ |
| + instID: {Public: instKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}, |
| + "op-1": {Public: opKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleOperator}}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cert, client := testTLS(t) |
| + apiLn, metricsLn := listen(t), listen(t) |
| + served := make(chan error, 1) |
| + go func() { |
| + served <- serve(ctx, tc.c, newAPIServer(api, cert), apiLn, newMetricsServer(hostedctl.NewMetrics().Handler(tc.c)), metricsLn, 10*time.Second) |
| + }() |
| + |
| + body, _ := json.Marshal(hostedwire.LaunchRequest{AttemptID: "a1", TaskID: "t1", Account: "acct", Image: testDigest, |
| + Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "aW5zdGFuY2UtY29kZS0xLTAwMDAwMDAwMDAwMC0wMDQ", |
| + Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000}) |
| + req, err := http.NewRequest(http.MethodPost, "https://"+apiLn.Addr().String()+"/v1/jobs", bytes.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tc.sign(t, req, body) |
| + launched := make(chan int, 1) |
| + go func() { |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + launched <- 0 |
| + return |
| + } |
| + _ = resp.Body.Close() |
| + launched <- resp.StatusCode |
| + }() |
| + select { |
| + case <-hr.entered: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the launch never reached the provider") |
| + } |
| + |
| + rb := []byte(`{}`) |
| + rreq, err := http.NewRequest(http.MethodPost, "https://"+apiLn.Addr().String()+"/v1/admin/restart", bytes.NewReader(rb)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + nonce := "restart-nonce-00000000000000001" |
| + if err := hostedwire.SignRequest(rreq, rb, "op-1", opKey, tc.clk.Wall(), nonce); err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := client.Do(rreq) |
| + if err != nil { |
| + t.Fatalf("restart: %v", err) |
| + } |
| + got := readAll(t, resp) |
| + if resp.StatusCode != http.StatusAccepted || string(got) != `{"restarting":true}` || |
| + hostedwire.VerifyResponse(resp, got, nonce, ctlKey.Public().(ed25519.PublicKey)) != nil { |
| + t.Fatalf("restart = %d %s, want a signed 202 {\"restarting\":true}", resp.StatusCode, got) |
| + } |
| + select { |
| + case err := <-served: |
| + t.Fatalf("serve returned (%v) with a request still in flight", err) |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + close(hr.released) |
| + if code := <-launched; code != http.StatusOK { |
| + t.Fatalf("the launch in flight was answered %d, want 200", code) |
| + } |
| + var serveErr error |
| + select { |
| + case serveErr = <-served: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("serve did not return after the restart") |
| + } |
| + var codes []int |
| + defer func(old func(int)) { exit = old }(exit) |
| + exit = func(code int) { codes = append(codes, code) } |
| + exitWith(serveErr) |
| + if len(codes) != 1 || codes[0] != 0 { |
| + t.Fatalf("exit codes after a restart = %v (serve: %v), want [0]", codes, serveErr) |
| + } |
| +} |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 7e4596e1..7f4bd78c 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -162,3 +162,32 @@ A key that has never asked for the feed is now due at `OpenedAt + SilentAfter`, |
| 23. The first deadline counts from the first check (`opened+SilentAfter` became `now+SilentAfter` in `MarkSilent`'s insert, `ctlproxy/feed.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedctl/ctlproxy -run 'TestProxySilentNeverPolled' -count=1`. Observed: FAIL, `feed_test.go:371: proxy_silent alerts = [], want one each for [proxy-1 proxy-2]`. Restored (byte for byte). |
| Also run: the covering command (`-run 'TestRedeem|TestCertCapped|TestRenew|TestStopRevokes|TestFeed|TestProxyRole|TestProxySilent|TestVMList|TestProxyCodeKey|TestReplaySends'`) ok; `go test ./internal/hostedctl/... -count=1` ok (hostedctl 9.6 s); `make budget build vet` ok. |
| + |
| +## Task 5 |
| + |
| +Operator routes. New package `internal/hostedctl/ctlops` (`ops.go`, `ops_test.go`): `Candidates` (the certification images file, one strict JSON array of `{"digest","image_arn","version_arn"}`; each version must be under its image ARN and be what the provider config launches the digest with at some size, as certificates are bound; `Allows(image, size)` also needs the version at the size asked for, else `ErrNotCandidate`), `Files` and `Reload` (re-reads the key, certificate and certification images files from local disk; the images file is checked first and swapped in last, after `ctlcert.Set.Load`, so a failure of either keeps both old sets; Task 3's split is unchanged: a removed key drops its certificates, a bad certificate under a listed key fails the reload; `ErrCandidates`, `ErrCertificates`; one reload at a time), `CertAttemptID` (`cert-` + 32 hex of a hash of key, image, size and launch-by, so the same request is the same attempt), `CertTask` `certification`, `CertLifetime` 30 min. `ctlcert.Set.Active` lists the active certificates. `hostedwire/ops.go`: `CertsResponse`/`CertView`, `ReloadRequest`/`Response`, `RestartRequest`/`Response`, `AlertTestRequest`/`Response`, `AlertTestKind` `test`, `StatusResponse` (`now_ns`, `enabled`, `network_audit` {ran, passed, passing, age_ms}, `provider_bound` (the `provider_binding` namespaces), `proxies` (one per configured proxy key: fed, last_feed_age_ms), `last_clean_reap` {ran, at_ns, age_ms}); `CertLaunchRequest` gains `launch_by_unix_ms` and `Validate`. |
| + |
| +hostedctl wiring only (`ops.go`; budget record raised to 5939/9749 with the reason): operator-only routes `POST /v1/cert/launch`, `GET /v1/certs`, `POST /v1/admin/reload`, `POST /v1/admin/restart`, `POST /v1/admin/alert-test`, `GET /v1/status`. `CertLaunch` (operator key, checked by the route and by the method) shares `launch` with `Launch` (refactored: the role checks, then one path with an `admit` callback); purpose certification, `Person` "", no instance code, services from `Manifest.For("certification")`, no certificate digest (never certified); the candidate check runs before saving and again in `creatable` before each provider call. New typed codes: `image_not_candidate` 400, `certificates_invalid` 422, `certification_images_invalid` 422, `alert_failed` 502 (hostedclient maps them to existing kinds, operator routes only). Reload, restart and alert test write audit rows (`reload`/`reload_failed`, `restart_asked`, `alert_test`/`alert_test_failed`). `HandlerConfig.Restart`: the restart route answers a signed 202 `{"restarting":true}` and calls it once the answer is written; without it the route is `no_route`. The reaper keeps the time of its last pass with no error. Controller config gains `certification_images_file` (required); startup loads all three files through `ctlops.Reload`. `main`: the restart hook cancels serve's context (as a signal does), serve drains, and `exitWith` exits 0 through the injectable `exit`. |
| + |
| +RED: `CGO_ENABLED=0 go test ./internal/hostedctl -run 'TestCertLaunch|TestReload|TestAlertTest|TestStatusOperatorOnly' -count=1` failed to build: `operator_test.go:54:8: e.cfg.Files undefined (type Config has no field or method Files)`, `e.cfg.Candidates undefined (type Config has no field or method Candidates)`. `... ./cmd/equipo-hosted-controller -run 'TestRestart'` failed to build: `undefined: exit`, `undefined: exitWith`. |
| + |
| +GREEN: `go test ./internal/hostedctl -run 'TestCertLaunch|TestReload|TestAlertTest' -count=1`: ok (TestCertLaunchOperatorOnly, TestCertLaunchNeedsCandidateImage, TestReloadKeepsOldSetOnBadFile, TestAlertTestPublishesOnce; TestStatusOperatorOnly also passes). Also new: TestRestartAnswers202ThenExits (cmd), TestCandidatesFileRules, TestReloadMissingFileKeepsSets, TestCertAttemptID (ctlops), TestCertLaunchRequestValidate (hostedwire); TestCertificatesFromConfig gains the certification images file and an unbound entry; TestConfigRefusesMissingListenOrKeys gains a missing and an absent images file. |
| + |
| +Mutation checks (each applied by script, the named test run, then restored and checked byte for byte with `cmp`): |
| + |
| +1. Accept an instance key on `/v1/cert/launch` (the route's role became `RoleInstance` and `CertLaunch`'s role check `if false && (...)`, `ops.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedctl -run 'TestCertLaunchOperatorOnly' -count=1`. Observed: FAIL, `operator_test.go:93: certification launch by an instance key = 200 {"attempt_id":"cert-4aa47b06...","state":"starting",...}, want 403 forbidden`. Restored (by hand: this first run's save path was wrong, so the two lines were put back and checked with grep; every later run used the script). |
| +2. (extra) The route's role alone (`RoleInstance`). Same command. Observed: FAIL, `operator_test.go:98: last audit row = {Actor:inst-a ... Action:launch_refused Reason:hostedctl: this key may not do that: a certification launch needs an operator key ...}, want api_refused by inst-a`. Restored. |
| +3. (extra) `CertLaunch`'s own role check alone (`key.Role == "nobody"`). Same command. First observed ok (the route stopped it first); TestCertLaunchOperatorOnly then gained a direct `CertLaunch` call with an instance key. Observed: FAIL, `operator_test.go:102: CertLaunch by an instance key = ({AttemptID:cert-4aa47b06... State:starting VMRef:vm-0001 ...}, <nil>), 1 jobs; want ErrForbidden and none`. Restored. |
| +4. No candidate check before saving (`admit` returned `"", nil`). Command: `... -run 'TestCertLaunchNeedsCandidateImage' -count=1`. Observed: FAIL, `operator_test.go:157: an image not in the file = 200 {"attempt_id":"cert-4c7b30bd...","state":"waiting",...}, want 400 image_not_candidate`. Restored. |
| +5. Dispatch does not re-check the candidate (the `Candidates.Allows` call removed from `creatable`, `launch.go`). Same command. Observed: FAIL, `operator_test.go:186: after imgB left the file: job starting, provider launches 2; want waiting and 1`. Restored. |
| +6. Candidates swapped in before the certificates load (`ctlops/ops.go`). Command: `... -run 'TestReloadKeepsOldSetOnBadFile' -count=1`. Observed: FAIL, `operator_test.go:252: imgB after a failed reload = ctlops: the image is not a certification candidate at this size: image sha256:bbbb... is not in the certification images file, want still a candidate`. Restored. |
| +7. The alert test sends a second alert. Command: `... -run 'TestAlertTestPublishesOnce' -count=1`. Observed: FAIL, `operator_test.go:323: test alerts = [{Kind:test Detail:test alert asked for by operator key op-1 At:0} {Kind:test Detail: At:0}], want exactly one naming op-1`. Restored. |
| +8. `/v1/status` takes the instance role. Command: `... -run 'TestStatusOperatorOnly' -count=1`. Observed: FAIL, `operator_test.go:355: status by an instance key = 200 {"now_ns":0,"enabled":true,...}, want 403 forbidden`. Restored. |
| +9. Every reaper pass counts as clean (`if err == nil` became `if true`, `reaper.go`). Same command. Observed: FAIL, `operator_test.go:384: last clean reap after a failed pass = {Ran:true AtNS:90000000000 AgeMS:0}, want the earlier one, a minute old`. Restored. |
| +10. `Allows` ignores the version at the size asked for (`v != e.VersionARN` became `v == ""`). Command: `... -run 'TestCertLaunchNeedsCandidateImage' -count=1`. Observed: FAIL, `operator_test.go:161: a size launching another version = 200 {...,"state":"starting",...}, want 400 image_not_candidate`. Restored. |
| +11. Restart answered 200 (`http.go`). Command: `CGO_ENABLED=0 go test ./cmd/equipo-hosted-controller -run 'TestRestartAnswers202ThenExits' -count=1`. Observed: FAIL, `main_test.go:442: restart = 200 {"restarting":true}, want a signed 202 {"restarting":true}`. Restored. |
| +12. A clean end exits 1 (`exitWith`'s `exit(0)` became `exit(1)`). Same command. Observed: FAIL, `main_test.go:464: exit codes after a restart = [1] (serve: <nil>), want [0]`. Restored. |
| +13. The restart hook is never called (`defer a.then()` became `_ = a.then`). Same command. Observed: FAIL, `main_test.go:457: serve did not return after the restart`. Restored. |
| +14. An unbound certification image version loads (`case false && !c.bound(e)`). Command: `... ./internal/hostedctl -run 'TestReloadKeepsOldSetOnBadFile' -count=1`. Observed: FAIL, `operator_test.go:262: reload with an unbound version = 200 {"certificates":2,"certification_images":1}, want 422 certification_images_invalid`. Restored. |
| + |
| +Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./internal/hostedwire ./cmd/equipo-hosted-controller -count=1` ok (hostedctl 13.9 s at load average 32 to 37; a first run at load average 88 to 99 took 66.5 s; the five operator tests take about 0.5 s together); `go test -race` of the new tests ok; `go vet -tags hostedlive` and staticcheck v0.7.0 (plain and `-tags hostedlive`) ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5939/9749. |
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go| index 5c37aff5..90dde21e 100644 |
| --- a/internal/hostedclient/client.go |
| +++ b/internal/hostedclient/client.go |
| @@ -116,6 +116,12 @@ var refusals = map[string]struct { |
| "store_lost": {http.StatusServiceUnavailable, ErrStoreLost}, |
| "unavailable": {http.StatusServiceUnavailable, ErrUnavailable}, |
| "internal": {http.StatusInternalServerError, ErrInternal}, |
| + |
| + // Operator routes only; an instance key never gets these. |
| + "image_not_candidate": {http.StatusBadRequest, ErrInvalid}, |
| + "certificates_invalid": {http.StatusUnprocessableEntity, ErrInternal}, |
| + "certification_images_invalid": {http.StatusUnprocessableEntity, ErrInternal}, |
| + "alert_failed": {http.StatusBadGateway, ErrProvider}, |
| } |
| // APIError is a signed refusal from the controller. Kind is one of the |
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go| index e972da6f..c1a825fe 100644 |
| --- a/internal/hostedctl/controller.go |
| +++ b/internal/hostedctl/controller.go |
| @@ -11,6 +11,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlegress" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| @@ -54,6 +55,11 @@ type Config struct { |
| // ProxyCodeKey (ctlproxy.CodeKeySize bytes) derives each launch's proxy |
| // code, so no table holds the code (ctlproxy.DeriveCode). |
| ProxyCodeKey []byte |
| + // Candidates are the images an operator may launch for certification; |
| + // nil allows none. Files are what POST /v1/admin/reload re-reads into |
| + // Certs and Candidates (ctlops.Reload). |
| + Candidates *ctlops.Candidates |
| + Files ctlops.Files |
| } |
| // ErrProviderMismatch: the database belongs to another provider namespace |
| @@ -89,6 +95,8 @@ type Controller struct { |
| // proxies are the proxy keys Handler was given, which the reaper |
| // watches for silence (proxy.go). |
| proxies atomic.Pointer[[]hostedwire.KeyID] |
| + // restart is the Handler's restart hook (ops.go), or nil. |
| + restart atomic.Pointer[func()] |
| // beforeMark, when set, runs in dispatch after its gates pass and just |
| // before the dispatch marker is recorded. Tests use it to hold the store |
| // there; production leaves it nil. |
diff --git a/internal/hostedctl/ctlcert/certs.go b/internal/hostedctl/ctlcert/certs.go| index 3f5672a6..5a8d8a28 100644 |
| --- a/internal/hostedctl/ctlcert/certs.go |
| +++ b/internal/hostedctl/ctlcert/certs.go |
| @@ -12,6 +12,7 @@ import ( |
| "encoding/base64" |
| "errors" |
| "fmt" |
| + "maps" |
| "slices" |
| "sync" |
| @@ -197,6 +198,22 @@ func (s *Set) Valid(digest string) bool { |
| return err == nil && s.bound(snap) |
| } |
| +// Active returns every certificate Valid would accept now, by digest, |
| +// with the snapshot it signs. |
| +func (s *Set) Active() []hostedwire.CertView { |
| + s.mu.RLock() |
| + defer s.mu.RUnlock() |
| + out := []hostedwire.CertView{} |
| + for _, d := range slices.Sorted(maps.Keys(s.certs)) { |
| + snap, err := hostedcert.Verify(s.certs[d], s.keys) |
| + if err == nil && s.bound(snap) { |
| + snap.Deployment = slices.Clone(snap.Deployment) |
| + out = append(out, hostedwire.CertView{Digest: d, Snapshot: snap}) |
| + } |
| + } |
| + return out |
| +} |
| + |
| // 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 { |
diff --git a/internal/hostedctl/ctlops/ops.go b/internal/hostedctl/ctlops/ops.go| new file mode 100644 |
| index 00000000..a7307b04 |
| --- /dev/null |
| +++ b/internal/hostedctl/ctlops/ops.go |
| @@ -0,0 +1,216 @@ |
| +// Package ctlops holds the logic of the controller's operator routes: the |
| +// certification images an operator may launch for certification, the |
| +// reload of the controller's certificate, key and certification image |
| +// files from local disk, and the attempt a certification launch runs as. |
| +// hostedctl wires it to the API (ops.go there). |
| +package ctlops |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/binary" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlcert" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +var ( |
| + // ErrNotCandidate: the image is not in the certification images file, |
| + // or the provider does not launch it at the size asked for with the |
| + // version the file names. |
| + ErrNotCandidate = errors.New("ctlops: the image is not a certification candidate at this size") |
| + // ErrCandidates: the certification images file does not read or check. |
| + // The old candidates are kept. |
| + ErrCandidates = errors.New("ctlops: the certification images file is not valid") |
| + // ErrCertificates: the certificate key file or certificate file does |
| + // not read or verify (ctlcert.Set.Load). The old set is kept. |
| + ErrCertificates = errors.New("ctlops: the certificate files are not valid") |
| +) |
| + |
| +// Candidate is one entry of the certification images file: an image |
| +// digest and the provider image and image version (for AWS, the version |
| +// ARN, "<image ARN>:<version>") a certification VM of it runs. |
| +type Candidate struct { |
| + Digest isolatedjob.ImageDigest `json:"digest"` |
| + ImageARN string `json:"image_arn"` |
| + VersionARN string `json:"version_arn"` |
| +} |
| + |
| +// Candidates is the controller's current certification images. Its zero |
| +// value and a nil pointer allow nothing. It is safe for concurrent use. |
| +type Candidates struct { |
| + versions ctlcert.ImageVersions // fixed; the provider config does not reload |
| + reload sync.Mutex // held by Reload throughout, so two reloads never interleave |
| + mu sync.RWMutex |
| + byDigest map[isolatedjob.ImageDigest]Candidate |
| +} |
| + |
| +// NewCandidates returns an empty set whose entries are bound to the |
| +// provider image versions versions gives, as certificates are |
| +// (ctlcert.NewSet). A nil versions binds nothing, so no entry loads. |
| +func NewCandidates(versions ctlcert.ImageVersions) *Candidates { |
| + if versions == nil { |
| + versions = func(isolatedjob.ImageDigest, isolatedjob.Size) (string, bool) { return "", false } |
| + } |
| + return &Candidates{versions: versions} |
| +} |
| + |
| +// sizes are the sizes an entry's version may be bound at. |
| +var sizes = []isolatedjob.Size{isolatedjob.SizeSmall, isolatedjob.SizeLarge} |
| + |
| +// parse reads the certification images file: one JSON array of entries, |
| +// each read as strictly as hostedwire.DecodeStrict reads a body. An entry |
| +// needs a sha256 digest, listed once, an image ARN, and a version ARN |
| +// under that image that the provider launches the digest with at some |
| +// size; anything else is ErrCandidates. |
| +func (c *Candidates) parse(raw []byte) (map[isolatedjob.ImageDigest]Candidate, error) { |
| + trimmed := bytes.TrimSpace(raw) |
| + if !json.Valid(trimmed) || len(trimmed) == 0 || trimmed[0] != '[' { |
| + return nil, fmt.Errorf("%w: it must be one JSON array", ErrCandidates) |
| + } |
| + // trimmed is exactly one JSON array, so wrapping it gives one object |
| + // with one key, which DecodeStrict reads with its own key rules. |
| + var f struct { |
| + Images []Candidate `json:"images"` |
| + } |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(append(append([]byte(`{"images":`), trimmed...), '}')), &f); err != nil { |
| + return nil, fmt.Errorf("%w: %v", ErrCandidates, err) |
| + } |
| + out := make(map[isolatedjob.ImageDigest]Candidate, len(f.Images)) |
| + for i, e := range f.Images { |
| + version, ok := strings.CutPrefix(e.VersionARN, e.ImageARN+":") |
| + switch { |
| + case !validDigest(string(e.Digest)): |
| + return nil, fmt.Errorf("%w: entry %d: digest %q is not sha256: and 64 lower-case hex digits", ErrCandidates, i, e.Digest) |
| + case out[e.Digest] != Candidate{}: |
| + return nil, fmt.Errorf("%w: entry %d: image %s is listed twice", ErrCandidates, i, e.Digest) |
| + case e.ImageARN == "" || !ok || version == "": |
| + return nil, fmt.Errorf("%w: entry %d: version ARN %q is not a version of image ARN %q", ErrCandidates, i, e.VersionARN, e.ImageARN) |
| + case !c.bound(e): |
| + return nil, fmt.Errorf("%w: entry %d: the provider does not launch image %s with version %q at any size", ErrCandidates, i, e.Digest, e.VersionARN) |
| + } |
| + out[e.Digest] = e |
| + } |
| + return out, nil |
| +} |
| + |
| +// bound reports whether the provider launches e's digest with e's version |
| +// at some size. |
| +func (c *Candidates) bound(e Candidate) bool { |
| + for _, s := range sizes { |
| + if v, ok := c.versions(e.Digest, s); ok && v == e.VersionARN { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// Allows returns nil when image is a candidate and the provider launches |
| +// it at size with the version its entry names; otherwise ErrNotCandidate. |
| +func (c *Candidates) Allows(image isolatedjob.ImageDigest, size isolatedjob.Size) error { |
| + if c == nil { |
| + return fmt.Errorf("%w: no certification images are configured", ErrNotCandidate) |
| + } |
| + c.mu.RLock() |
| + e, ok := c.byDigest[image] |
| + c.mu.RUnlock() |
| + if !ok { |
| + return fmt.Errorf("%w: image %s is not in the certification images file", ErrNotCandidate, image) |
| + } |
| + if v, ok := c.versions(image, size); !ok || v != e.VersionARN { |
| + return fmt.Errorf("%w: image %s at size %s does not launch version %q", ErrNotCandidate, image, size, e.VersionARN) |
| + } |
| + return nil |
| +} |
| + |
| +// Files are the controller's local files a reload re-reads: the |
| +// certificate key file, the certificate file and the certification images |
| +// file. |
| +type Files struct { |
| + CertKeys, Certificates, CertificationImages string |
| +} |
| + |
| +// Reload reads files from local disk and, if every one checks, makes them |
| +// certs's and cands's contents. The certification images file is checked |
| +// first and swapped in last, after certs.Load has replaced the |
| +// certificates, so a failure of either leaves both as they were. |
| +// certs.Load keeps ctlcert's rules: a certificate under a key the key file |
| +// no longer names is withdrawn, while one that fails to verify under a key |
| +// it names fails the reload. The error wraps ErrCandidates or |
| +// ErrCertificates. |
| +func Reload(files Files, certs *ctlcert.Set, cands *Candidates) (hostedwire.ReloadResponse, error) { |
| + if certs == nil || cands == nil { |
| + return hostedwire.ReloadResponse{}, errors.New("ctlops: reload needs a certificate set and a candidate set") |
| + } |
| + cands.reload.Lock() |
| + defer cands.reload.Unlock() |
| + raw, err := os.ReadFile(files.CertificationImages) |
| + if err != nil { |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: %v", ErrCandidates, err) |
| + } |
| + next, err := cands.parse(raw) |
| + if err != nil { |
| + return hostedwire.ReloadResponse{}, err |
| + } |
| + keys, err := os.ReadFile(files.CertKeys) |
| + if err != nil { |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: key file: %v", ErrCertificates, err) |
| + } |
| + certsJSON, err := os.ReadFile(files.Certificates) |
| + if err != nil { |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: certificate file: %v", ErrCertificates, err) |
| + } |
| + n, err := certs.Load(keys, certsJSON) |
| + if err != nil { |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: %w", ErrCertificates, err) |
| + } |
| + cands.mu.Lock() |
| + cands.byDigest = next |
| + cands.mu.Unlock() |
| + return hostedwire.ReloadResponse{Certificates: n, CertificationImages: len(next)}, nil |
| +} |
| + |
| +// Certification launches. A certification VM runs as its own attempt, |
| +// under task CertTask and the operator key's ID as its account, for |
| +// CertLifetime: the reaper stops it at CertLifetime less the controller's |
| +// stop margin (10 minutes), 20 minutes after launch. |
| +const ( |
| + CertTask = "certification" |
| + CertLifetime = 30 * time.Minute |
| +) |
| + |
| +// CertAttemptID is the attempt a certification launch of q by key runs |
| +// as: "cert-" and 32 hex digits of a hash of the key, image, size and |
| +// launch-by time. The same request again names the same attempt, so the |
| +// controller answers it with the job it already saved instead of a second |
| +// VM; the launch-by time is the operator's client token. |
| +func CertAttemptID(by hostedwire.KeyID, q hostedwire.CertLaunchRequest) string { |
| + h := sha256.New() |
| + for _, f := range []string{"equipo-cert-launch-v1", string(by), string(q.Image), string(q.Size), fmt.Sprint(q.LaunchByUnixMS)} { |
| + _, _ = h.Write(binary.AppendUvarint(nil, uint64(len(f)))) |
| + _, _ = h.Write([]byte(f)) |
| + } |
| + return "cert-" + hex.EncodeToString(h.Sum(nil)[:16]) |
| +} |
| + |
| +func validDigest(s string) bool { |
| + hexPart, ok := strings.CutPrefix(s, "sha256:") |
| + if !ok || len(hexPart) != 64 { |
| + return false |
| + } |
| + for i := 0; i < len(hexPart); i++ { |
| + if !(hexPart[i] >= '0' && hexPart[i] <= '9' || hexPart[i] >= 'a' && hexPart[i] <= 'f') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/hostedctl/ctlops/ops_test.go b/internal/hostedctl/ctlops/ops_test.go| new file mode 100644 |
| index 00000000..ddb44ba3 |
| --- /dev/null |
| +++ b/internal/hostedctl/ctlops/ops_test.go |
| @@ -0,0 +1,120 @@ |
| +package ctlops |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "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 ( |
| + img = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") |
| + arn = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:test" // ctlcerttest.ImageVersion is arn + ":1" |
| +) |
| + |
| +func entry(digest, imageARN, version string) string { |
| + return `{"digest":"` + digest + `","image_arn":"` + imageARN + `","version_arn":"` + version + `"}` |
| +} |
| + |
| +// TestCandidatesFileRules: the certification images file is one strict |
| +// JSON array of entries, each a sha256 digest listed once with a version |
| +// ARN under its image ARN that the provider launches it with. |
| +func TestCandidatesFileRules(t *testing.T) { |
| + t.Parallel() |
| + good := entry(string(img), arn, ctlcerttest.ImageVersion) |
| + c := NewCandidates(ctlcerttest.Versions) |
| + if got, err := c.parse([]byte(" [" + good + "]\n")); err != nil || len(got) != 1 { |
| + t.Fatalf("a good file = (%v, %v), want one entry", got, err) |
| + } |
| + for name, body := range map[string]string{ |
| + "an object": `{"images":[` + good + `]}`, |
| + "two arrays": `[` + good + `][]`, |
| + "a repeated key": strings.Replace(good, `"digest"`, `"digest":"x","digest"`, 1), |
| + "an upper-case key": strings.Replace(good, `"digest"`, `"Digest"`, 1), |
| + "a short digest": `[` + entry("sha256:ab", arn, ctlcerttest.ImageVersion) + `]`, |
| + "a digest listed twice": `[` + good + `,` + good + `]`, |
| + "no image ARN": `[` + entry(string(img), "", ctlcerttest.ImageVersion) + `]`, |
| + "another image's ARN": `[` + entry(string(img), arn+"-other", ctlcerttest.ImageVersion) + `]`, |
| + "the image ARN only": `[` + entry(string(img), arn, arn) + `]`, |
| + "an unbound version": `[` + entry(string(img), arn, arn+":2") + `]`, |
| + } { |
| + if _, err := c.parse([]byte(body)); !errors.Is(err, ErrCandidates) { |
| + t.Errorf("%s: parse = %v, want ErrCandidates", name, err) |
| + } |
| + } |
| + if err := NewCandidates(nil).Allows(img, isolatedjob.SizeSmall); !errors.Is(err, ErrNotCandidate) { |
| + t.Fatalf("an empty set allows %s: %v", img, err) |
| + } |
| + var none *Candidates |
| + if err := none.Allows(img, isolatedjob.SizeSmall); !errors.Is(err, ErrNotCandidate) { |
| + t.Fatalf("a nil set allows %s: %v", img, err) |
| + } |
| +} |
| + |
| +// TestReloadMissingFileKeepsSets: an unreadable file fails the reload with |
| +// its kind and changes nothing. |
| +func TestReloadMissingFileKeepsSets(t *testing.T) { |
| + t.Parallel() |
| + dir := t.TempDir() |
| + f := Files{CertKeys: filepath.Join(dir, "k"), Certificates: filepath.Join(dir, "c"), CertificationImages: filepath.Join(dir, "i")} |
| + for path, body := range map[string]string{f.CertKeys: string(ctlcerttest.KeysJSON()), |
| + f.Certificates: string(ctlcerttest.CertsJSON(ctlcerttest.Cert(img, "equipo.example.com"))), |
| + f.CertificationImages: `[` + entry(string(img), arn, ctlcerttest.ImageVersion) + `]`} { |
| + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + certs, cands := ctlcerttest.Set(), NewCandidates(ctlcerttest.Versions) |
| + if r, err := Reload(f, certs, cands); err != nil || r != (hostedwire.ReloadResponse{Certificates: 1, CertificationImages: 1}) { |
| + t.Fatalf("Reload = (%+v, %v)", r, err) |
| + } |
| + for _, c := range []struct { |
| + path string |
| + want error |
| + }{{f.CertificationImages, ErrCandidates}, {f.CertKeys, ErrCertificates}, {f.Certificates, ErrCertificates}} { |
| + g := f |
| + switch c.path { |
| + case f.CertificationImages: |
| + g.CertificationImages = filepath.Join(dir, "absent") |
| + case f.CertKeys: |
| + g.CertKeys = filepath.Join(dir, "absent") |
| + default: |
| + g.Certificates = filepath.Join(dir, "absent") |
| + } |
| + if _, err := Reload(g, certs, cands); !errors.Is(err, c.want) { |
| + t.Fatalf("Reload without %s = %v, want %v", c.path, err, c.want) |
| + } |
| + if len(certs.Active()) != 1 || cands.Allows(img, isolatedjob.SizeSmall) != nil { |
| + t.Fatalf("after a failed reload: %d certificates, candidate %v; want both kept", len(certs.Active()), cands.Allows(img, isolatedjob.SizeSmall)) |
| + } |
| + } |
| +} |
| + |
| +// TestCertAttemptID: the same request names the same attempt; another key, |
| +// image, size or launch-by time another one; each fits a bootstrap. |
| +func TestCertAttemptID(t *testing.T) { |
| + t.Parallel() |
| + q := hostedwire.CertLaunchRequest{Image: img, Size: isolatedjob.SizeLarge, LaunchByUnixMS: 1} |
| + a := CertAttemptID("op-1", q) |
| + if a != CertAttemptID("op-1", q) || !strings.HasPrefix(a, "cert-") || len(a) > hostedwire.MaxLaunchIDLen { |
| + t.Fatalf("CertAttemptID = %q", a) |
| + } |
| + seen := map[string]bool{a: true} |
| + for _, b := range []string{CertAttemptID("op-2", q), |
| + CertAttemptID("op-1", hostedwire.CertLaunchRequest{Image: img + "b", Size: q.Size, LaunchByUnixMS: 1}), |
| + CertAttemptID("op-1", hostedwire.CertLaunchRequest{Image: img, Size: isolatedjob.SizeSmall, LaunchByUnixMS: 1}), |
| + CertAttemptID("op-1", hostedwire.CertLaunchRequest{Image: img, Size: q.Size, LaunchByUnixMS: 2})} { |
| + if seen[b] { |
| + t.Fatalf("two requests share attempt %s", b) |
| + } |
| + seen[b] = true |
| + } |
| +} |
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go| index 4da24f3c..6e4c210c 100644 |
| --- a/internal/hostedctl/http.go |
| +++ b/internal/hostedctl/http.go |
| @@ -15,6 +15,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlegress" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| @@ -34,6 +35,10 @@ type HandlerConfig struct { |
| Wall func() time.Time |
| // Metrics, when set, counts launches and refusals. |
| Metrics *Metrics |
| + // Restart, when set, is called once POST /v1/admin/restart has been |
| + // answered 202; the caller then exits when its requests in flight |
| + // finish. Without it that route is not found. |
| + Restart func() |
| } |
| // Audit action the handler writes when a key's role may not use a route. The |
| @@ -80,6 +85,10 @@ var apiErrors = []apiError{ |
| {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."}, |
| {ErrNotCertified, http.StatusBadRequest, "not_certified", "No valid certificate covers the image for this deployment."}, |
| + {ctlops.ErrNotCandidate, http.StatusBadRequest, "image_not_candidate", "The image is not in the certification images file at this size."}, |
| + {ctlops.ErrCertificates, http.StatusUnprocessableEntity, "certificates_invalid", "The certificate or key file is not valid. The old set is kept."}, |
| + {ctlops.ErrCandidates, http.StatusUnprocessableEntity, "certification_images_invalid", "The certification images file is not valid. The old set is kept."}, |
| + {ErrAlertFailed, http.StatusBadGateway, "alert_failed", "The test alert was not delivered."}, |
| {ctlproxy.ErrRefused, http.StatusForbidden, "proxy_refused", "The proxy request was refused."}, |
| {ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."}, |
| {errNoRoute, http.StatusNotFound, "no_route", "No such route."}, |
| @@ -171,6 +180,8 @@ func matchRoute(r *http.Request) (route, string, error) { |
| var rt route |
| var attempt string |
| switch { |
| + case operatorRoutes[r.URL.EscapedPath()].serve != nil: |
| + rt = operatorRoutes[r.URL.EscapedPath()] |
| case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs": |
| rt = routeLaunch |
| case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "vms": |
| @@ -248,6 +259,9 @@ func (c *Controller) Handler(hc HandlerConfig) (http.Handler, error) { |
| keys[id] = hostedwire.VerifyKey{Public: bytes.Clone(k.Public), Role: k.Role} |
| } |
| c.watchProxies(keys) |
| + if hc.Restart != nil { |
| + c.restart.Store(&hc.Restart) |
| + } |
| return &apiHandler{ |
| c: c, |
| v: &hostedwire.Verifier{Keys: keys, Nonces: c.store, Now: hc.Wall}, |
| @@ -351,6 +365,11 @@ func (h *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| h.write(w, r, a.status, errorBody(a), nonce) |
| return |
| } |
| + status := http.StatusOK |
| + if a, ok := out.(accepted); ok { |
| + status, out = http.StatusAccepted, a.v |
| + defer a.then() |
| + } |
| resp, err := json.Marshal(out) |
| if err != nil { |
| h.m.apiError(name, errInternal.code) |
| @@ -360,7 +379,7 @@ func (h *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| if v, ok := out.(hostedwire.JobView); ok && rt.name == routeLaunch.name { |
| h.m.launch(v.State) |
| } |
| - h.write(w, r, http.StatusOK, resp, nonce) |
| + h.write(w, r, status, resp, nonce) |
| } |
| // signedNonce returns the nonce to sign a verification failure for, or "" |
diff --git a/internal/hostedctl/http_test.go b/internal/hostedctl/http_test.go| index 365d661d..6275a473 100644 |
| --- a/internal/hostedctl/http_test.go |
| +++ b/internal/hostedctl/http_test.go |
| @@ -48,6 +48,7 @@ type apiEnv struct { |
| *launchEnv |
| srv *httptest.Server |
| metrics *Metrics |
| + keys map[hostedwire.KeyID]hostedwire.VerifyKey // the handler's; testKeys() when nil |
| nonces int |
| } |
| @@ -70,7 +71,11 @@ func (e *apiEnv) serve() { |
| e.srv.Close() |
| } |
| e.metrics = NewMetrics() |
| - h, err := e.c.Handler(HandlerConfig{Keys: testKeys(), Signing: keyCtl, Wall: e.clk.Wall, Metrics: e.metrics}) |
| + keys := e.keys |
| + if keys == nil { |
| + keys = testKeys() |
| + } |
| + h, err := e.c.Handler(HandlerConfig{Keys: keys, Signing: keyCtl, Wall: e.clk.Wall, Metrics: e.metrics}) |
| if err != nil { |
| e.t.Fatalf("Handler = %v", err) |
| } |
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go| index 5633f470..fa04fce3 100644 |
| --- a/internal/hostedctl/launch.go |
| +++ b/internal/hostedctl/launch.go |
| @@ -173,6 +173,17 @@ func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hosted |
| if q.Purpose == hostedwire.PurposeCertification { |
| return c.refuse(ctx, by, q, fmt.Errorf("%w: certification launches are the operator's", ErrForbidden)) |
| } |
| + return c.launch(ctx, by, q, func(services []hostedwire.Service) (string, error) { |
| + cert, err := c.cfg.Certs.For(q.Image, q.Size, ctlcert.InstanceHosts(services)) |
| + return hostedcert.Digest(cert), err |
| + }) |
| +} |
| + |
| +// launch is Launch, and CertLaunch (ops.go), after the role checks: admit |
| +// names the certificate digest the intent is saved with ("" for none), or |
| +// refuses. |
| +func (c *Controller) launch(ctx context.Context, by hostedwire.KeyID, q LaunchRequest, |
| + admit func([]hostedwire.Service) (string, error)) (JobView, error) { |
| if err := c.checkRequest(q); err != nil { |
| return c.refuse(ctx, by, q, err) |
| } |
| @@ -186,7 +197,7 @@ func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hosted |
| if err := c.checkSpec(q, services); err != nil { |
| return c.refuse(ctx, by, q, err) |
| } |
| - cert, err := c.cfg.Certs.For(q.Image, q.Size, ctlcert.InstanceHosts(services)) |
| + cert, err := admit(services) |
| if err != nil { |
| return c.refuse(ctx, by, q, err) |
| } |
| @@ -194,7 +205,7 @@ func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hosted |
| return c.refuse(ctx, by, q, err) |
| } |
| - view, created, err := c.saveIntent(ctx, by, q, services, hostedcert.Digest(cert)) |
| + view, created, err := c.saveIntent(ctx, by, q, services, cert) |
| if err != nil || !created { |
| return view, err |
| } |
| @@ -554,7 +565,7 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem |
| if !ready { |
| return view, nil, nil |
| } |
| - if gate := c.creatable(j, c.store.Clock().Now()); gate != nil { |
| + if gate := c.creatable(j, spec, c.store.Clock().Now()); gate != nil { |
| return view, gate, nil |
| } |
| if c.beforeMark != nil { |
| @@ -570,7 +581,7 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem |
| 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(j, now); gate != nil { |
| + } else if gate := c.creatable(j, spec, now); gate != nil { |
| return view, gate, nil |
| } |
| // R21: c.runner bounds the call by ProviderLaunchTimeout, so no launch |
| @@ -852,15 +863,22 @@ func launchExpired(launchByMS int64, wall time.Time) string { |
| return "" |
| } |
| -// 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 { |
| +// creatable checks the transient creation gates for intent j, whose saved |
| +// spec is spec: launches on, a checks intent's certificate still valid or |
| +// a certification intent's image still a candidate at its size |
| +// (ctlops.Candidates.Allows), and a passing audit begun within |
| +// AuditMaxAge. A legacy slice 1a intent (purpose "task") or any other |
| +// purpose is never creatable here. |
| +func (c *Controller) creatable(j jobRow, spec isolatedjob.LaunchSpec, now T) error { |
| if !c.cfg.Enabled { |
| return ErrDisabled |
| } |
| - if j.purpose != hostedwire.PurposeChecks || !c.cfg.Certs.Valid(j.certDigest) { |
| + switch { |
| + case j.purpose == hostedwire.PurposeCertification: |
| + if err := c.cfg.Candidates.Allows(spec.Image, spec.Size); err != nil { |
| + return err |
| + } |
| + case 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) |
diff --git a/internal/hostedctl/operator_test.go b/internal/hostedctl/operator_test.go| new file mode 100644 |
| index 00000000..c489ec0a |
| --- /dev/null |
| +++ b/internal/hostedctl/operator_test.go |
| @@ -0,0 +1,389 @@ |
| +package hostedctl |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedcert" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// candImageARN is the provider image of the certification candidate imgB: |
| +// ctlcerttest.ImageVersion is its version 1. candVersions launches imgB |
| +// at version 1 when small and version 2 when large. |
| +const candImageARN = "arn:aws:lambda:eu-west-1:123456789012:microvm-image:test" |
| + |
| +func candVersions(d isolatedjob.ImageDigest, s isolatedjob.Size) (string, bool) { |
| + if d == imgB && s == isolatedjob.SizeLarge { |
| + return candImageARN + ":2", true |
| + } |
| + return ctlcerttest.Versions(d, s) |
| +} |
| + |
| +// candidatesJSON is a certification images file listing imgB at version 1. |
| +var candidatesJSON = `[{"digest":"` + string(imgB) + `","image_arn":"` + candImageARN + `","version_arn":"` + candImageARN + `:1"}]` |
| + |
| +// opEnv is an apiEnv whose controller reloads its certificates and |
| +// certification images from files in a temporary directory: at first the |
| +// test key, imgA's certificate (only: testCerts also certifies imgB) |
| +// and imgB as the one candidate. |
| +type opEnv struct { |
| + *apiEnv |
| + files ctlops.Files |
| +} |
| + |
| +func newOpEnv(t *testing.T) *opEnv { |
| + t.Helper() |
| + dir := t.TempDir() |
| + e := &opEnv{apiEnv: &apiEnv{launchEnv: newLaunchEnv(t)}, files: ctlops.Files{CertKeys: filepath.Join(dir, "keys.json"), |
| + Certificates: filepath.Join(dir, "certificates.json"), CertificationImages: filepath.Join(dir, "certification-images.json")}} |
| + e.write(e.files.CertKeys, string(ctlcerttest.KeysJSON())) |
| + e.write(e.files.Certificates, string(ctlcerttest.CertsJSON(certA2()))) |
| + e.write(e.files.CertificationImages, candidatesJSON) |
| + e.cfg.Files = e.files |
| + e.cfg.Candidates = ctlops.NewCandidates(candVersions) |
| + if _, err := ctlops.Reload(e.files, e.cfg.Certs, e.cfg.Candidates); err != nil { |
| + t.Fatalf("first reload = %v", err) |
| + } |
| + e.newController() |
| + e.audit() |
| + e.serve() |
| + return e |
| +} |
| + |
| +func (e *opEnv) write(path, body string) { |
| + e.t.Helper() |
| + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| + e.t.Fatal(err) |
| + } |
| +} |
| + |
| +func certLaunch(image isolatedjob.ImageDigest, size isolatedjob.Size) hostedwire.CertLaunchRequest { |
| + return hostedwire.CertLaunchRequest{Image: image, Size: size, LaunchByUnixMS: testLaunchBy} |
| +} |
| + |
| +// wantCode wants r to be the signed refusal with status and code. |
| +func wantCode(t *testing.T, what string, r reply, status int, code string) { |
| + t.Helper() |
| + if r.status != status || r.errBody(t).Code != code { |
| + t.Fatalf("%s = %d %s, want %d %s", what, r.status, r.body, status, code) |
| + } |
| +} |
| + |
| +// TestCertLaunchOperatorOnly: only an operator key may launch a |
| +// certification VM, on its own route; the VM gets purpose certification, |
| +// no person, no instance code, the manifest's certification services and |
| +// no certificate. The same request again is the same attempt. |
| +func TestCertLaunchOperatorOnly(t *testing.T) { |
| + t.Parallel() |
| + e := newOpEnv(t) |
| + q := certLaunch(imgB, isolatedjob.SizeSmall) |
| + wantCode(t, "certification launch by an instance key", e.call("POST", "/v1/cert/launch", q, idInstA, keyInstA), http.StatusForbidden, "forbidden") |
| + if e.jobCount() != 0 || e.fake.Calls(isolatedjob.OpLaunch) != 0 { |
| + t.Fatalf("an instance key's certification launch made %d jobs and %d provider calls", e.jobCount(), e.fake.Calls(isolatedjob.OpLaunch)) |
| + } |
| + if a := e.lastAudit(); a.Action != actionAPIRefused || a.Actor != idInstA { |
| + t.Fatalf("last audit row = %+v, want api_refused by %s", a, idInstA) |
| + } |
| + // CertLaunch checks the role itself too. |
| + if v, err := e.c.CertLaunch(e.ctx, idInstA, instKey, q); !errors.Is(err, ErrForbidden) || e.jobCount() != 0 { |
| + t.Fatalf("CertLaunch by an instance key = (%+v, %v), %d jobs; want ErrForbidden and none", v, err, e.jobCount()) |
| + } |
| + // The instance launch route refuses certification to every key. |
| + wl := wireLaunch("att-cert") |
| + wl.Purpose, wl.Person, wl.InstanceCode = hostedwire.PurposeCertification, "", "" |
| + wantCode(t, "certification purpose on /v1/jobs by an instance key", e.call("POST", "/v1/jobs", wl, idInstA, keyInstA), http.StatusForbidden, "forbidden") |
| + wantCode(t, "/v1/jobs by an operator key", e.call("POST", "/v1/jobs", wl, idOp, keyOp), http.StatusForbidden, "forbidden") |
| + |
| + r := e.call("POST", "/v1/cert/launch", q, idOp, keyOp) |
| + if r.status != http.StatusOK { |
| + t.Fatalf("certification launch by the operator = %d %s, want 200", r.status, r.body) |
| + } |
| + var v hostedwire.JobView |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &v); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v.AttemptID != ctlops.CertAttemptID(idOp, q) || v.State != JobStarting || v.VMRef == "" { |
| + t.Fatalf("certification launch = %+v, want attempt %s starting on a VM", v, ctlops.CertAttemptID(idOp, q)) |
| + } |
| + j, _ := e.job(v.AttemptID) |
| + if j.purpose != hostedwire.PurposeCertification || j.certDigest != "" || j.actor != string(idOp) || j.launchBy != testLaunchBy { |
| + t.Fatalf("saved job = purpose %q, cert %q, actor %q, launch-by %d; want certification, none, %s, %d", |
| + j.purpose, j.certDigest, j.actor, j.launchBy, idOp, int64(testLaunchBy)) |
| + } |
| + spec, err := decodeSpec(j.specJSON, v.AttemptID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var boot hostedwire.BootstrapV2 |
| + if err := json.Unmarshal(spec.Bootstrap, &boot); err != nil { |
| + t.Fatal(err) |
| + } |
| + want, _ := e.cfg.Manifest.For(hostedwire.PurposeCertification) |
| + if boot.Purpose != hostedwire.PurposeCertification || boot.InstanceCode != "" || !reflect.DeepEqual(boot.Services, want) || |
| + spec.Image != imgB || spec.Size != isolatedjob.SizeSmall || spec.MaxLifetime != ctlops.CertLifetime { |
| + t.Fatalf("saved spec = %+v, bootstrap %+v; want imgB small for %v, certification, no instance code, services %v", |
| + spec, boot, ctlops.CertLifetime, want) |
| + } |
| + if again := e.call("POST", "/v1/cert/launch", q, idOp, keyOp); again.status != http.StatusOK || e.fake.Calls(isolatedjob.OpLaunch) != 1 { |
| + t.Fatalf("same request again = %d %s with %d provider launches, want 200 and still 1", again.status, again.body, e.fake.Calls(isolatedjob.OpLaunch)) |
| + } |
| + // It never counts as certified: no certificate covers imgB. |
| + if e.cfg.Certs.Valid(j.certDigest) { |
| + t.Fatal("the certification job's empty certificate digest is valid") |
| + } |
| +} |
| + |
| +// TestCertLaunchNeedsCandidateImage: a certification launch needs the |
| +// image in the certification images file at a size the provider launches |
| +// with the file's version; a waiting intent whose image a reload removed |
| +// is not launched. A candidate is not certified. |
| +func TestCertLaunchNeedsCandidateImage(t *testing.T) { |
| + t.Parallel() |
| + e := newOpEnv(t) |
| + for name, q := range map[string]hostedwire.CertLaunchRequest{ |
| + "an image not in the file": certLaunch(imgOther, isolatedjob.SizeSmall), |
| + "a size launching another version": certLaunch(imgB, isolatedjob.SizeLarge), |
| + "a certified image not in the file": certLaunch(imgA, isolatedjob.SizeSmall), |
| + } { |
| + wantCode(t, name, e.call("POST", "/v1/cert/launch", q, idOp, keyOp), http.StatusBadRequest, "image_not_candidate") |
| + if a := e.lastAudit(); a.Action != actionLaunchRefused || !strings.Contains(a.Reason, "candidate") { |
| + t.Fatalf("%s: last audit row = %+v, want launch_refused naming the candidate", name, a) |
| + } |
| + } |
| + if e.jobCount() != 0 || e.fake.Calls(isolatedjob.OpLaunch) != 0 { |
| + t.Fatalf("refused launches made %d jobs and %d provider calls", e.jobCount(), e.fake.Calls(isolatedjob.OpLaunch)) |
| + } |
| + // A checks launch of the candidate has no certificate. |
| + wl := wireLaunch("att-1") |
| + wl.Image = imgB |
| + wantCode(t, "checks launch of a candidate", e.call("POST", "/v1/jobs", wl, idInstA, keyInstA), http.StatusBadRequest, "not_certified") |
| + |
| + // Throttled, the intent waits; a reload that drops imgB keeps it waiting. |
| + e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) |
| + q := certLaunch(imgB, isolatedjob.SizeSmall) |
| + r := e.call("POST", "/v1/cert/launch", q, idOp, keyOp) |
| + if r.status != http.StatusOK || !strings.Contains(string(r.body), `"state":"waiting"`) { |
| + t.Fatalf("throttled certification launch = %d %s, want 200 waiting", r.status, r.body) |
| + } |
| + e.write(e.files.CertificationImages, `[]`) |
| + if r := e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idOp, keyOp); r.status != http.StatusOK { |
| + t.Fatalf("reload dropping imgB = %d %s", r.status, r.body) |
| + } |
| + calls := e.fake.Calls(isolatedjob.OpLaunch) |
| + if err := e.c.Replay(e.ctx); err != nil { |
| + t.Fatalf("Replay = %v", err) |
| + } |
| + if j, _ := e.job(q2attempt(q)); j.state != JobWaiting || e.fake.Calls(isolatedjob.OpLaunch) != calls { |
| + t.Fatalf("after imgB left the file: job %s, provider launches %d; want waiting and %d", j.state, e.fake.Calls(isolatedjob.OpLaunch), calls) |
| + } |
| + e.write(e.files.CertificationImages, candidatesJSON) |
| + if r := e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idOp, keyOp); r.status != http.StatusOK { |
| + t.Fatalf("reload adding imgB = %d %s", r.status, r.body) |
| + } |
| + if err := e.c.Replay(e.ctx); err != nil { |
| + t.Fatalf("Replay = %v", err) |
| + } |
| + if j, _ := e.job(q2attempt(q)); j.state != JobStarting { |
| + t.Fatalf("after imgB came back: job %s, want starting", j.state) |
| + } |
| +} |
| + |
| +func q2attempt(q hostedwire.CertLaunchRequest) string { return ctlops.CertAttemptID(idOp, q) } |
| + |
| +// TestReloadKeepsOldSetOnBadFile: a reload re-reads the key, certificate |
| +// and certification images files; a file that fails leaves both old sets |
| +// in place and answers its code; removing a key withdraws its |
| +// certificates. GET /v1/certs lists the active set. |
| +func TestReloadKeepsOldSetOnBadFile(t *testing.T) { |
| + t.Parallel() |
| + e := newOpEnv(t) |
| + reload := func() reply { return e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idOp, keyOp) } |
| + certs := func() []string { |
| + r := e.call("GET", "/v1/certs", nil, idOp, keyOp) |
| + var cr hostedwire.CertsResponse |
| + if r.status != http.StatusOK { |
| + t.Fatalf("GET /v1/certs = %d %s", r.status, r.body) |
| + } |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &cr); err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []string |
| + for _, c := range cr.Certs { |
| + if c.Snapshot.Image == "" { |
| + t.Fatalf("certificate %s listed without its snapshot", c.Digest) |
| + } |
| + out = append(out, c.Digest) |
| + } |
| + return out |
| + } |
| + certB := ctlcerttest.Cert(imgB, testHosts...) |
| + wantA := []string{certA()} |
| + if got := certs(); !reflect.DeepEqual(got, wantA) { |
| + t.Fatalf("certs at start = %v, want %v", got, wantA) |
| + } |
| + wantCode(t, "reload by an instance key", e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idInstA, keyInstA), http.StatusForbidden, "forbidden") |
| + wantCode(t, "certs by an instance key", e.call("GET", "/v1/certs", nil, idInstA, keyInstA), http.StatusForbidden, "forbidden") |
| + |
| + // A certificate that fails to verify under a listed key: nothing |
| + // changes, not even the candidates file read in the same reload. |
| + bad := certB |
| + bad.Sig = bytes.Clone(bad.Sig) |
| + bad.Sig[0] ^= 1 |
| + e.write(e.files.Certificates, string(ctlcerttest.CertsJSON(certA2(), bad))) |
| + e.write(e.files.CertificationImages, `[]`) |
| + wantCode(t, "reload with a bad certificate", reload(), http.StatusUnprocessableEntity, "certificates_invalid") |
| + if got := certs(); !reflect.DeepEqual(got, wantA) { |
| + t.Fatalf("certs after a failed reload = %v, want %v", got, wantA) |
| + } |
| + if err := e.cfg.Candidates.Allows(imgB, isolatedjob.SizeSmall); err != nil { |
| + t.Fatalf("imgB after a failed reload = %v, want still a candidate", err) |
| + } |
| + // A bad certification images file: nothing changes either. |
| + e.write(e.files.Certificates, string(ctlcerttest.CertsJSON(certA2(), certB))) |
| + for name, body := range map[string]string{ |
| + "an object": `{"images":[]}`, |
| + "an unbound version": strings.Replace(candidatesJSON, candImageARN+`:1"`, candImageARN+`:7"`, 1), |
| + "an unknown field": strings.Replace(candidatesJSON, `"digest"`, `"size":"small","digest"`, 1), |
| + } { |
| + e.write(e.files.CertificationImages, body) |
| + wantCode(t, "reload with "+name, reload(), http.StatusUnprocessableEntity, "certification_images_invalid") |
| + if got := certs(); !reflect.DeepEqual(got, wantA) { |
| + t.Fatalf("certs after a reload with %s = %v, want %v", name, got, wantA) |
| + } |
| + } |
| + // Good files take effect together. |
| + e.write(e.files.CertificationImages, `[]`) |
| + r := reload() |
| + var rr hostedwire.ReloadResponse |
| + if r.status != http.StatusOK || hostedwire.DecodeStrict(bytes.NewReader(r.body), &rr) != nil || rr != (hostedwire.ReloadResponse{Certificates: 2}) { |
| + t.Fatalf("good reload = %d %s, want 2 certificates and no candidates", r.status, r.body) |
| + } |
| + if got, want := certs(), sortedDigests(certA2(), certB); !reflect.DeepEqual(got, want) { |
| + t.Fatalf("certs after a good reload = %v, want %v", got, want) |
| + } |
| + if err := e.cfg.Candidates.Allows(imgB, isolatedjob.SizeSmall); !errors.Is(err, ctlops.ErrNotCandidate) { |
| + t.Fatalf("imgB after a reload dropping it = %v, want ErrNotCandidate", err) |
| + } |
| + // Removing the key withdraws its certificates; that is not an error. |
| + e.write(e.files.CertKeys, `{"keys":[]}`) |
| + if r := reload(); r.status != http.StatusOK || len(certs()) != 0 { |
| + t.Fatalf("reload without the key = %d %s, certs %v; want 200 and none", r.status, r.body, certs()) |
| + } |
| +} |
| + |
| +// certA2 is imgA's test certificate (the one testCertList holds). |
| +func certA2() hostedcert.Certificate { return ctlcerttest.Cert(imgA, testHosts...) } |
| + |
| +func sortedDigests(certs ...hostedcert.Certificate) []string { |
| + var out []string |
| + for _, c := range certs { |
| + out = append(out, hostedcert.Digest(c)) |
| + } |
| + if len(out) == 2 && out[0] > out[1] { |
| + out[0], out[1] = out[1], out[0] |
| + } |
| + return out |
| +} |
| + |
| +// TestAlertTestPublishesOnce: an operator's alert test sends exactly one |
| +// "test" alert; a replay of it, or an instance key's, sends none; a failed |
| +// delivery is reported. |
| +func TestAlertTestPublishesOnce(t *testing.T) { |
| + t.Parallel() |
| + e := newOpEnv(t) |
| + body := []byte(`{}`) |
| + req, nonce := e.newRequest("POST", "/v1/admin/alert-test", body, idOp, keyOp) |
| + replay, err := http.NewRequest("POST", req.URL.String(), bytes.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + replay.Header = req.Header.Clone() |
| + r := e.send(req, nonce) |
| + var ar hostedwire.AlertTestResponse |
| + if r.status != http.StatusOK || !r.signed() || hostedwire.DecodeStrict(bytes.NewReader(r.body), &ar) != nil || ar.Kind != hostedwire.AlertTestKind { |
| + t.Fatalf("alert test = %d %s, want a signed 200 of kind test", r.status, r.body) |
| + } |
| + wantCode(t, "the alert test replayed", e.send(replay, nonce), http.StatusUnauthorized, "replay") |
| + wantCode(t, "alert test by an instance key", e.call("POST", "/v1/admin/alert-test", hostedwire.AlertTestRequest{}, idInstA, keyInstA), http.StatusForbidden, "forbidden") |
| + got := e.alerts(hostedwire.AlertTestKind) |
| + if len(got) != 1 || !strings.Contains(got[0].Detail, string(idOp)) { |
| + t.Fatalf("test alerts = %+v, want exactly one naming %s", got, idOp) |
| + } |
| + if a := e.lastAudit(); a.Action != actionAPIRefused { |
| + t.Fatalf("last audit row = %+v, want the instance key's refusal", a) |
| + } |
| + e.c.alerter.(*recordingAlerter).fail = errors.New("topic down") |
| + wantCode(t, "alert test with the alerter down", e.call("POST", "/v1/admin/alert-test", hostedwire.AlertTestRequest{}, idOp, keyOp), http.StatusBadGateway, "alert_failed") |
| +} |
| + |
| +// TestStatusOperatorOnly: GET /v1/status is the operator's, and shows the |
| +// audit, the provider binding, each configured proxy's feed age, the |
| +// launch switch and the last clean reaper pass. |
| +func TestStatusOperatorOnly(t *testing.T) { |
| + t.Parallel() |
| + e := newOpEnv(t) |
| + keyProxy := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize)) |
| + e.keys = testKeys() |
| + e.keys["proxy-1"] = hostedwire.VerifyKey{Public: keyProxy.Public().(ed25519.PublicKey), Role: hostedwire.RoleProxy} |
| + e.keys["proxy-2"] = hostedwire.VerifyKey{Public: ed25519.NewKeyFromSeed(bytes.Repeat([]byte{8}, ed25519.SeedSize)).Public().(ed25519.PublicKey), Role: hostedwire.RoleProxy} |
| + e.serve() |
| + status := func() hostedwire.StatusResponse { |
| + t.Helper() |
| + r := e.call("GET", "/v1/status", nil, idOp, keyOp) |
| + var s hostedwire.StatusResponse |
| + if r.status != http.StatusOK { |
| + t.Fatalf("GET /v1/status = %d %s", r.status, r.body) |
| + } |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &s); err != nil { |
| + t.Fatalf("status %s: %v", r.body, err) |
| + } |
| + return s |
| + } |
| + wantCode(t, "status by an instance key", e.call("GET", "/v1/status", nil, idInstA, keyInstA), http.StatusForbidden, "forbidden") |
| + wantCode(t, "status by a proxy key", e.call("GET", "/v1/status", nil, "proxy-1", keyProxy), http.StatusForbidden, "forbidden") |
| + |
| + if r := e.call("GET", "/v1/proxy/feed", nil, "proxy-1", keyProxy); r.status != http.StatusOK { |
| + t.Fatalf("feed = %d %s", r.status, r.body) |
| + } |
| + e.clk.AdvanceMono(30 * time.Second) |
| + s := status() |
| + want := hostedwire.StatusResponse{NowNS: s.NowNS, Enabled: true, |
| + NetworkAudit: hostedwire.AuditStatus{Ran: true, Passed: true, Passing: true, AgeMS: 30000}, |
| + ProviderBound: []string{testNamespace}, |
| + Proxies: []hostedwire.ProxyStatus{{Proxy: "proxy-1", Fed: true, LastFeedAgeMS: 30000}, {Proxy: "proxy-2"}}, |
| + } |
| + if !reflect.DeepEqual(s, want) { |
| + t.Fatalf("status = %+v, want %+v", s, want) |
| + } |
| + |
| + e.reap() |
| + clean := status().LastCleanReap |
| + if !clean.Ran || clean.AgeMS != 0 { |
| + t.Fatalf("last clean reap after a pass = %+v, want one just now", clean) |
| + } |
| + e.clk.AdvanceMono(time.Minute) |
| + e.fake.SetAudit(isolatedjob.NetworkAudit{}, errors.New("audit down")) |
| + if _, err := e.c.Reap(e.ctx); err == nil { |
| + t.Fatal("Reap with the audit down = nil, want its error") |
| + } |
| + s = status() |
| + if s.LastCleanReap != (hostedwire.ReapStatus{Ran: true, AtNS: clean.AtNS, AgeMS: 60000}) { |
| + t.Fatalf("last clean reap after a failed pass = %+v, want the earlier one, a minute old", s.LastCleanReap) |
| + } |
| + if s.NetworkAudit.Passed || s.NetworkAudit.Passing || !s.NetworkAudit.Ran { |
| + t.Fatalf("audit after a failure = %+v, want ran and failing", s.NetworkAudit) |
| + } |
| +} |
diff --git a/internal/hostedctl/ops.go b/internal/hostedctl/ops.go| new file mode 100644 |
| index 00000000..7f5155b7 |
| --- /dev/null |
| +++ b/internal/hostedctl/ops.go |
| @@ -0,0 +1,202 @@ |
| +package hostedctl |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// Wiring for the operator's routes (hostedwire/ops.go lists them; the |
| +// logic is ctlops's). Only an operator key may use them. |
| +var operatorRoutes = map[string]route{ |
| + "/v1/cert/launch": {"cert_launch", http.MethodPost, hostedwire.RoleOperator, serveCertLaunch}, |
| + "/v1/certs": {"certs", http.MethodGet, hostedwire.RoleOperator, serveCerts}, |
| + "/v1/admin/reload": {"reload", http.MethodPost, hostedwire.RoleOperator, serveReload}, |
| + "/v1/admin/restart": {"restart", http.MethodPost, hostedwire.RoleOperator, serveRestart}, |
| + "/v1/admin/alert-test": {"alert_test", http.MethodPost, hostedwire.RoleOperator, serveAlertTest}, |
| + "/v1/status": {"status", http.MethodGet, hostedwire.RoleOperator, serveStatus}, |
| +} |
| + |
| +// ErrAlertFailed: the alerter did not take the test alert. |
| +var ErrAlertFailed = errors.New("hostedctl: the test alert was not delivered") |
| + |
| +// Audit actions of the operator routes; a certification launch writes the |
| +// launch actions. |
| +const ( |
| + actionReload = "reload" |
| + actionReloadFailed = "reload_failed" |
| + actionRestartAsked = "restart_asked" |
| + actionAlertTest = "alert_test" |
| + actionAlertTestFail = "alert_test_failed" |
| +) |
| + |
| +// accepted is a success answered 202 instead of 200; then runs once the |
| +// answer is written. |
| +type accepted struct { |
| + v any |
| + then func() |
| +} |
| + |
| +// CertLaunch launches a certification VM for q.Image at q.Size, as Launch |
| +// does a checks VM, with these differences: only an operator key may ask |
| +// (ErrForbidden); the attempt is ctlops.CertAttemptID, so the same |
| +// request again is answered from the saved job; the task is |
| +// ctlops.CertTask, the account the operator key's ID, the lifetime |
| +// ctlops.CertLifetime; purpose certification, no person and no instance |
| +// code; and in place of a certificate the image must be a candidate at |
| +// q.Size (ctlops.ErrNotCandidate), before the intent is saved and again |
| +// before each provider call. Its intent holds no certificate digest, so |
| +// it never counts as certified. |
| +func (c *Controller) CertLaunch(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, q hostedwire.CertLaunchRequest) (JobView, error) { |
| + lq := LaunchRequest{AttemptID: ctlops.CertAttemptID(by, q), TaskID: ctlops.CertTask, Account: string(by), Image: q.Image, Size: q.Size, |
| + MaxLifetime: ctlops.CertLifetime, Purpose: hostedwire.PurposeCertification, LaunchByUnixMS: q.LaunchByUnixMS} |
| + if !c.cfg.Enabled { |
| + return c.refuse(ctx, by, lq, ErrDisabled) |
| + } |
| + if by == "" || key.Role != hostedwire.RoleOperator { |
| + return c.refuse(ctx, by, lq, fmt.Errorf("%w: a certification launch needs an operator key", ErrForbidden)) |
| + } |
| + if err := q.Validate(); err != nil { |
| + return c.refuse(ctx, by, lq, fmt.Errorf("%w: %w", isolatedjob.ErrInvalid, err)) |
| + } |
| + return c.launch(ctx, by, lq, func([]hostedwire.Service) (string, error) { return "", c.cfg.Candidates.Allows(q.Image, q.Size) }) |
| +} |
| + |
| +func serveCertLaunch(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, _ string, body []byte) (any, error) { |
| + var q hostedwire.CertLaunchRequest |
| + if err := decode(body, &q); err != nil { |
| + return nil, err |
| + } |
| + v, err := c.CertLaunch(ctx, by, key, q) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return wireView(v), nil |
| +} |
| + |
| +func serveCerts(_ context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, _ []byte) (any, error) { |
| + return hostedwire.CertsResponse{Certs: c.cfg.Certs.Active()}, nil |
| +} |
| + |
| +// serveReload re-reads Config.Files (ctlops.Reload) and audits the |
| +// result; a failure leaves both sets as they were. |
| +func serveReload(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, body []byte) (any, error) { |
| + if err := decode(body, &hostedwire.ReloadRequest{}); err != nil { |
| + return nil, err |
| + } |
| + res, err := ctlops.Reload(c.cfg.Files, c.cfg.Certs, c.cfg.Candidates) |
| + action, reason := actionReload, fmt.Sprintf("%d certificates, %d certification images", res.Certificates, res.CertificationImages) |
| + if err != nil { |
| + action, reason = actionReloadFailed, "old sets kept: "+err.Error() |
| + } |
| + if aerr := c.opAudit(ctx, by, action, reason); err != nil || aerr != nil { |
| + return nil, errors.Join(err, aerr) |
| + } |
| + return res, nil |
| +} |
| + |
| +// serveRestart answers 202 and then calls the Handler's restart hook. With |
| +// no hook there is no such route. |
| +func serveRestart(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, body []byte) (any, error) { |
| + if err := decode(body, &hostedwire.RestartRequest{}); err != nil { |
| + return nil, err |
| + } |
| + hook := c.restart.Load() |
| + if hook == nil { |
| + return nil, errNoRoute |
| + } |
| + if err := c.opAudit(ctx, by, actionRestartAsked, "exit after the requests in flight"); err != nil { |
| + return nil, err |
| + } |
| + return accepted{v: hostedwire.RestartResponse{Restarting: true}, then: *hook}, nil |
| +} |
| + |
| +// serveAlertTest sends one AlertTestKind alert. The request's nonce makes |
| +// each signed request send at most one. |
| +func serveAlertTest(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, body []byte) (any, error) { |
| + if err := decode(body, &hostedwire.AlertTestRequest{}); err != nil { |
| + return nil, err |
| + } |
| + err := c.alerter.Alert(ctx, Alert{Kind: hostedwire.AlertTestKind, At: c.store.Clock().Now(), |
| + Detail: fmt.Sprintf("test alert asked for by operator key %s", by)}) |
| + if err != nil { |
| + return nil, errors.Join(fmt.Errorf("%w: %w", ErrAlertFailed, err), c.opAudit(ctx, by, actionAlertTestFail, "the alerter did not take it")) |
| + } |
| + if err := c.opAudit(ctx, by, actionAlertTest, "sent"); err != nil { |
| + return nil, err |
| + } |
| + return hostedwire.AlertTestResponse{Kind: hostedwire.AlertTestKind}, nil |
| +} |
| + |
| +func serveStatus(ctx context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, _ []byte) (any, error) { |
| + return c.Status(ctx) |
| +} |
| + |
| +// Status is what the metrics listener shows: the last network audit, the |
| +// provider binding rows, each configured proxy's last feed age, whether |
| +// launches are on, and the last reaper pass that finished with no error, |
| +// all at one controller time read in one transaction. |
| +func (c *Controller) Status(ctx context.Context) (hostedwire.StatusResponse, error) { |
| + var ids []hostedwire.KeyID |
| + if p := c.proxies.Load(); p != nil { |
| + ids = *p |
| + } |
| + s := hostedwire.StatusResponse{Enabled: c.cfg.Enabled, Proxies: []hostedwire.ProxyStatus{}} |
| + var now T |
| + err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| + now = c.store.Clock().Now() |
| + var err error |
| + if s.ProviderBound, err = textColumn(ctx, tx, `SELECT namespace FROM provider_binding ORDER BY id`); err != nil { |
| + return err |
| + } |
| + ages, err := ctlproxy.FeedAges(ctx, tx, ids, time.Duration(now)) |
| + s.Proxies = s.Proxies[:0] |
| + for _, id := range ids { |
| + age, fed := ages[id] |
| + s.Proxies = append(s.Proxies, hostedwire.ProxyStatus{Proxy: id, Fed: fed, LastFeedAgeMS: age.Milliseconds()}) |
| + } |
| + return err |
| + }) |
| + if err != nil { |
| + return hostedwire.StatusResponse{}, err |
| + } |
| + if s.ProviderBound == nil { |
| + s.ProviderBound = []string{} |
| + } |
| + s.NowNS, s.NetworkAudit = int64(now), c.audit.view(now) |
| + c.reap.mu.Lock() |
| + if c.reap.cleanRan { |
| + s.LastCleanReap = hostedwire.ReapStatus{Ran: true, AtNS: int64(c.reap.clean), AgeMS: time.Duration(now - c.reap.clean).Milliseconds()} |
| + } |
| + c.reap.mu.Unlock() |
| + return s, nil |
| +} |
| + |
| +// view is the last audit's result at now; the age counts from when it |
| +// began. |
| +func (s *auditState) view(now T) hostedwire.AuditStatus { |
| + passing := s.check(now) == nil |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + v := hostedwire.AuditStatus{Ran: s.ran, Passed: s.passed, Passing: passing} |
| + if s.ran { |
| + v.AgeMS = time.Duration(now - s.at).Milliseconds() |
| + } |
| + return v |
| +} |
| + |
| +// opAudit writes one operator route's audit row in a transaction of its |
| +// own. |
| +func (c *Controller) opAudit(ctx context.Context, by hostedwire.KeyID, action, reason string) error { |
| + return c.store.Tx(ctx, func(tx *sql.Tx) error { |
| + return appendAudit(tx, Audit{Actor: by, Action: action, Reason: reason, At: c.store.Clock().Now()}) |
| + }) |
| +} |
diff --git a/internal/hostedctl/reaper.go b/internal/hostedctl/reaper.go| index b7872f07..ead68115 100644 |
| --- a/internal/hostedctl/reaper.go |
| +++ b/internal/hostedctl/reaper.go |
| @@ -98,6 +98,8 @@ type reapState struct { |
| observed map[string]bool // attempt -> Refresh's latest Get read unknown; absent: no answer since the last pass |
| last ReapResult |
| ran bool |
| + clean T // when the last pass with no error finished |
| + cleanRan bool // a pass has finished with no error |
| // Used only under pass. |
| unknownRuns map[string]int // attempt -> passes in a row its VM read unknown |
| @@ -235,6 +237,9 @@ func (c *Controller) Reap(ctx context.Context) (ReapReport, error) { |
| err := c.reapPass(ctx, &rep) |
| c.reap.mu.Lock() |
| c.reap.last, c.reap.ran = ReapResult{Report: rep, Err: err, At: c.store.Clock().Now()}, true |
| + if err == nil { |
| + c.reap.clean, c.reap.cleanRan = c.reap.last.At, true |
| + } |
| c.reap.mu.Unlock() |
| return rep, err |
| } |
diff --git a/internal/hostedwire/hosted.go b/internal/hostedwire/hosted.go| index 2084c6d9..eec088fd 100644 |
| --- a/internal/hostedwire/hosted.go |
| +++ b/internal/hostedwire/hosted.go |
| @@ -240,8 +240,24 @@ func CertReportMessage(serial string, report []byte) []byte { |
| return []byte("equipo-hosted-cert-report-v1\n" + serial + "\n" + hex.EncodeToString(sum[:])) |
| } |
| -// CertLaunchRequest asks for a certification VM for one image. |
| +// CertLaunchRequest asks for a certification VM for one image at one |
| +// size. LaunchByUnixMS is the wall clock (Unix milliseconds) after which |
| +// the controller must not launch it, as in LaunchRequest. |
| type CertLaunchRequest struct { |
| - Image isolatedjob.ImageDigest `json:"image"` |
| - Size isolatedjob.Size `json:"size"` |
| + Image isolatedjob.ImageDigest `json:"image"` |
| + Size isolatedjob.Size `json:"size"` |
| + LaunchByUnixMS int64 `json:"launch_by_unix_ms"` |
| +} |
| + |
| +// Validate checks an image, a known size and a launch-by time above zero. |
| +func (q CertLaunchRequest) Validate() error { |
| + switch { |
| + case q.Image == "": |
| + return fmt.Errorf("%w: image is required", ErrLaunchRequest) |
| + case q.Size.MemoryMiB() == 0: |
| + return fmt.Errorf("%w: size must be %q or %q", ErrLaunchRequest, isolatedjob.SizeSmall, isolatedjob.SizeLarge) |
| + case q.LaunchByUnixMS <= 0: |
| + return fmt.Errorf("%w: launch_by_unix_ms must be above zero", ErrLaunchRequest) |
| + } |
| + return nil |
| } |
diff --git a/internal/hostedwire/hosted_test.go b/internal/hostedwire/hosted_test.go| index 8e5855e0..a2640691 100644 |
| --- a/internal/hostedwire/hosted_test.go |
| +++ b/internal/hostedwire/hosted_test.go |
| @@ -181,7 +181,7 @@ func TestHostedWireNames(t *testing.T) { |
| {RedeemResponse{Cert: []byte{3}, NotAfterNS: 9}, func() any { return &RedeemResponse{} }, `{"cert":"Aw==","not_after_ns":9}`}, |
| {RenewCertRequest{Serial: "s1", CSR: []byte{1}}, func() any { return &RenewCertRequest{} }, `{"serial":"s1","csr":"AQ=="}`}, |
| {CertReport{Serial: "s1", Report: []byte{1}, Sig: []byte{2}}, func() any { return &CertReport{} }, `{"serial":"s1","report":"AQ==","sig":"Ag=="}`}, |
| - {CertLaunchRequest{Image: img, Size: isolatedjob.SizeLarge}, func() any { return &CertLaunchRequest{} }, `{"image":"sha256:ab","size":"large"}`}, |
| + {CertLaunchRequest{Image: img, Size: isolatedjob.SizeLarge, LaunchByUnixMS: 8}, func() any { return &CertLaunchRequest{} }, `{"image":"sha256:ab","size":"large","launch_by_unix_ms":8}`}, |
| } |
| for _, c := range cases { |
| b, err := json.Marshal(c.v) |
| @@ -211,3 +211,26 @@ func TestCertReportMessage(t *testing.T) { |
| t.Fatalf("CertReportMessage = %q, want %q", got, want) |
| } |
| } |
| + |
| +// TestCertLaunchRequestValidate: a certification launch needs an image, a |
| +// known size and a launch-by time above zero. |
| +func TestCertLaunchRequestValidate(t *testing.T) { |
| + t.Parallel() |
| + ok := CertLaunchRequest{Image: "sha256:ab", Size: isolatedjob.SizeLarge, LaunchByUnixMS: 1} |
| + if err := ok.Validate(); err != nil { |
| + t.Fatalf("Validate(%+v) = %v", ok, err) |
| + } |
| + for name, edit := range map[string]func(*CertLaunchRequest){ |
| + "no image": func(q *CertLaunchRequest) { q.Image = "" }, |
| + "no size": func(q *CertLaunchRequest) { q.Size = "" }, |
| + "unknown size": func(q *CertLaunchRequest) { q.Size = "huge" }, |
| + "no launch-by": func(q *CertLaunchRequest) { q.LaunchByUnixMS = 0 }, |
| + "past epoch": func(q *CertLaunchRequest) { q.LaunchByUnixMS = -1 }, |
| + } { |
| + q := ok |
| + edit(&q) |
| + if err := q.Validate(); !errors.Is(err, ErrLaunchRequest) { |
| + t.Errorf("%s: Validate = %v, want ErrLaunchRequest", name, err) |
| + } |
| + } |
| +} |
diff --git a/internal/hostedwire/ops.go b/internal/hostedwire/ops.go| new file mode 100644 |
| index 00000000..1d1b909e |
| --- /dev/null |
| +++ b/internal/hostedwire/ops.go |
| @@ -0,0 +1,94 @@ |
| +package hostedwire |
| + |
| +import "amadan.net/oficina/equipo/internal/hostedcert" |
| + |
| +// Operator routes (slice 2 Task 5). Only an operator key may use them: |
| +// |
| +// POST /v1/cert/launch CertLaunchRequest -> JobView |
| +// GET /v1/certs (empty body) -> CertsResponse |
| +// POST /v1/admin/reload ReloadRequest -> ReloadResponse |
| +// POST /v1/admin/restart RestartRequest -> RestartResponse (202) |
| +// POST /v1/admin/alert-test AlertTestRequest -> AlertTestResponse |
| +// GET /v1/status (empty body) -> StatusResponse |
| + |
| +// CertView is one active certificate: its digest (hostedcert.Digest) and |
| +// the snapshot it signs. |
| +type CertView struct { |
| + Digest string `json:"digest"` |
| + Snapshot hostedcert.Snapshot `json:"snapshot"` |
| +} |
| + |
| +// CertsResponse lists the controller's active certificates by digest. |
| +type CertsResponse struct { |
| + Certs []CertView `json:"certs"` |
| +} |
| + |
| +// ReloadRequest re-reads the controller's certificate, key and |
| +// certification image files. It has no fields; its body is {}. |
| +type ReloadRequest struct{} |
| + |
| +// ReloadResponse counts what the controller holds after a reload. |
| +type ReloadResponse struct { |
| + Certificates int `json:"certificates"` |
| + CertificationImages int `json:"certification_images"` |
| +} |
| + |
| +// RestartRequest asks the controller to exit once its requests in flight |
| +// finish, so its service manager starts it again. Its body is {}. |
| +type RestartRequest struct{} |
| + |
| +type RestartResponse struct { |
| + Restarting bool `json:"restarting"` |
| +} |
| + |
| +// AlertTestRequest sends one alert of kind AlertTestKind. Its body is {}. |
| +type AlertTestRequest struct{} |
| + |
| +type AlertTestResponse struct { |
| + Kind string `json:"kind"` |
| +} |
| + |
| +// AlertTestKind is the kind of the alert POST /v1/admin/alert-test sends. |
| +const AlertTestKind = "test" |
| + |
| +// StatusResponse is what the controller's private metrics listener shows, |
| +// for an operator outside its network. NowNS and every *_ns field are |
| +// controller time; ages are controller time too. |
| +type StatusResponse struct { |
| + NowNS int64 `json:"now_ns"` |
| + Enabled bool `json:"enabled"` |
| + NetworkAudit AuditStatus `json:"network_audit"` |
| + // ProviderBound is the provider namespace each provider_binding row |
| + // binds the database to. |
| + ProviderBound []string `json:"provider_bound"` |
| + // Proxies has one entry for each configured proxy key, in key order. |
| + Proxies []ProxyStatus `json:"proxies"` |
| + LastCleanReap ReapStatus `json:"last_clean_reap"` |
| +} |
| + |
| +// AuditStatus is the last network audit: whether one has run, whether it |
| +// passed, whether it is passing now (passed and fresh enough for a |
| +// launch), and its age from when it began. Age is 0 when none has run. |
| +type AuditStatus struct { |
| + Ran bool `json:"ran"` |
| + Passed bool `json:"passed"` |
| + Passing bool `json:"passing"` |
| + AgeMS int64 `json:"age_ms"` |
| +} |
| + |
| +// ProxyStatus is one configured proxy: whether it has asked for the launch |
| +// feed, and how long ago it last did (0 when it never has). |
| +type ProxyStatus struct { |
| + Proxy KeyID `json:"proxy"` |
| + Fed bool `json:"fed"` |
| + LastFeedAgeMS int64 `json:"last_feed_age_ms"` |
| +} |
| + |
| +// ReapStatus is the last reaper pass that finished with no error: whether |
| +// there was one since the controller started, when it finished and its |
| +// age. AtNS and AgeMS are 0 when there was none. |
| +type ReapStatus struct { |
| + Ran bool `json:"ran"` |
| + AtNS int64 `json:"at_ns"` |
| + AgeMS int64 `json:"age_ms"` |
| +} |