hostedctl: reload fetches config objects first; status audit snapshot
Task 5 review round 1. POST /v1/admin/reload fetches cert-keys.json, certificates.json, certification-images.json and operators.json through an injected Fetcher (S3 GetObject in the controller command, bucket and prefix from config, owner-checked and bounded), writes each atomically over its local file, then verifies and swaps; any fetch or verification failure keeps the old sets. /v1/status reads the audit under one lock. The parser key-rule fixtures now reach the key checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+516
−38
.rastrillo/budgets.txt+1 −1cmd/equipo-hosted-controller/config.go+20 −3cmd/equipo-hosted-controller/config_test.go+11 −2cmd/equipo-hosted-controller/fetcher.go+67 −0cmd/equipo-hosted-controller/fetcher_test.go+67 −0cmd/equipo-hosted-controller/main.go+7 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+23 −0go.mod+4 −0go.sum+8 −0internal/hostedclient/client.go+1 −0internal/hostedctl/audit.go+5 −0internal/hostedctl/controller.go+10 −1internal/hostedctl/ctlops/ops.go+106 −3internal/hostedctl/ctlops/ops_test.go+2 −2internal/hostedctl/http.go+1 −0internal/hostedctl/launch_test.go+4 −1internal/hostedctl/operator_test.go+172 −17internal/hostedctl/ops.go+7 −7
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index bdf3e083..7958b799 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 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. |
| +size internal/hostedctl 5954 9907 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. |
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go| index 8c856c1f..f9bc53fc 100644 |
| --- a/cmd/equipo-hosted-controller/config.go |
| +++ b/cmd/equipo-hosted-controller/config.go |
| @@ -78,6 +78,16 @@ type fileConfig struct { |
| // 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"` |
| + // OperatorsFile is the local copy of the operator keys object, which a |
| + // reload fetches and writes for the next start. |
| + OperatorsFile string `json:"operators_file"` |
| + // ConfigBucket and ConfigPrefix (ending in "/", for example |
| + // "controller/") name where POST /v1/admin/reload fetches |
| + // cert-keys.json, certificates.json, certification-images.json and |
| + // operators.json before writing them over the four local files above |
| + // and verifying them (ctlops.FetchAndReload). |
| + ConfigBucket string `json:"config_bucket"` |
| + ConfigPrefix string `json:"config_prefix"` |
| // 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 |
| @@ -112,6 +122,7 @@ type imageEntry struct { |
| // config is a checked fileConfig, ready to wire. |
| type config struct { |
| listen, metricsListen, tlsCert, tlsKey, database, topicARN string |
| + bucket, prefix string // the config bucket and the controller's prefix in it |
| signing ed25519.PrivateKey |
| keys map[hostedwire.KeyID]hostedwire.VerifyKey |
| ctl hostedctl.Config |
| @@ -159,8 +170,9 @@ 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, |
| - "certification_images_file": fc.CertificationImagesFile, |
| - "proxy_ca_cert_file": fc.ProxyCACertFile, "proxy_ca_key_file": fc.ProxyCAKeyFile, "proxy_code_key_file": fc.ProxyCodeKeyFile} { |
| + "certification_images_file": fc.CertificationImagesFile, "operators_file": fc.OperatorsFile, |
| + "config_bucket": fc.ConfigBucket, "config_prefix": fc.ConfigPrefix, |
| + "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) |
| } |
| @@ -180,7 +192,12 @@ func (fc fileConfig) check() (config, error) { |
| 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} |
| + c.ctl.Files = ctlops.Files{CertKeys: fc.CertKeysFile, Certificates: fc.CertificatesFile, |
| + CertificationImages: fc.CertificationImagesFile, Operators: fc.OperatorsFile} |
| + if !strings.HasSuffix(fc.ConfigPrefix, "/") || strings.HasPrefix(fc.ConfigPrefix, "/") { |
| + return config{}, fmt.Errorf("config_prefix %q must end in / and not start with one", fc.ConfigPrefix) |
| + } |
| + c.bucket, c.prefix = fc.ConfigBucket, fc.ConfigPrefix |
| 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) |
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go| index 09ee0083..e971a7bc 100644 |
| --- a/cmd/equipo-hosted-controller/config_test.go |
| +++ b/cmd/equipo-hosted-controller/config_test.go |
| @@ -85,6 +85,9 @@ func validConfig(t *testing.T, dir string) fileConfig { |
| CertKeysFile: certKeysPath, |
| CertificatesFile: certsPath, |
| CertificationImagesFile: candidatesPath, |
| + OperatorsFile: filepath.Join(dir, "operators.json"), |
| + ConfigBucket: "equipo-hosted-config", |
| + ConfigPrefix: "controller/", |
| ProxyCACertFile: caCertPath, |
| ProxyCAKeyFile: caKeyPath, |
| ProxyCodeKeyFile: codeKeyPath, |
| @@ -131,8 +134,9 @@ func TestCertificatesFromConfig(t *testing.T) { |
| 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) |
| + if c.ctl.Files.CertificationImages == "" || c.ctl.Files.Certificates == "" || c.ctl.Files.CertKeys == "" || c.ctl.Files.Operators == "" || |
| + c.bucket != "equipo-hosted-config" || c.prefix != "controller/" { |
| + t.Fatalf("reload files = %+v, bucket %q, prefix %q; want all four and the config's bucket and prefix", c.ctl.Files, c.bucket, c.prefix) |
| } |
| unbound := validConfig(t, dir) |
| unbound.CertificationImagesFile = filepath.Join(dir, "unbound-images.json") |
| @@ -198,6 +202,11 @@ func TestCertificatesFromConfig(t *testing.T) { |
| "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") }, |
| + "no operators file": func(f *fileConfig) { f.OperatorsFile = "" }, |
| + "no config bucket": func(f *fileConfig) { f.ConfigBucket = "" }, |
| + "no config prefix": func(f *fileConfig) { f.ConfigPrefix = "" }, |
| + "a prefix not ending in /": func(f *fileConfig) { f.ConfigPrefix = "controller" }, |
| + "a prefix starting with /": func(f *fileConfig) { f.ConfigPrefix = "/controller/" }, |
| "missing key file": func(f *fileConfig) { f.CertKeysFile = filepath.Join(dir, "absent.json") }, |
| } { |
| fc := validConfig(t, dir) |
diff --git a/cmd/equipo-hosted-controller/fetcher.go b/cmd/equipo-hosted-controller/fetcher.go| new file mode 100644 |
| index 00000000..09d2a8cb |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-controller/fetcher.go |
| @@ -0,0 +1,67 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| +) |
| + |
| +// fetchTimeout bounds one config bucket object's read, the call and its |
| +// body together. |
| +const fetchTimeout = 20 * time.Second |
| + |
| +// getObject is the S3 call s3Fetcher makes. *s3.Client satisfies it. |
| +type getObject interface { |
| + GetObject(context.Context, *s3.GetObjectInput, ...func(*s3.Options)) (*s3.GetObjectOutput, error) |
| +} |
| + |
| +// s3Fetcher is the controller's ctlops.Fetcher: it reads prefix+name from |
| +// the config bucket, which must belong to owner (the account the |
| +// controller's credentials are in), within fetchTimeout, and refuses an |
| +// object over ctlops.MaxObject bytes. |
| +type s3Fetcher struct { |
| + client getObject |
| + bucket, prefix, owner string |
| + timeout time.Duration |
| +} |
| + |
| +var _ ctlops.Fetcher = s3Fetcher{} |
| + |
| +func (f s3Fetcher) Fetch(ctx context.Context, name string) ([]byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, f.timeout) |
| + defer cancel() |
| + key := f.prefix + name |
| + out, err := f.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(f.bucket), Key: aws.String(key), |
| + ExpectedBucketOwner: aws.String(f.owner)}) |
| + if err != nil { |
| + return nil, fmt.Errorf("get s3://%s/%s: %w", f.bucket, key, err) |
| + } |
| + if out.Body == nil { |
| + return nil, fmt.Errorf("get s3://%s/%s: no body", f.bucket, key) |
| + } |
| + defer out.Body.Close() |
| + b, err := io.ReadAll(io.LimitReader(out.Body, ctlops.MaxObject+1)) |
| + switch { |
| + case err != nil: |
| + return nil, fmt.Errorf("read s3://%s/%s: %w", f.bucket, key, err) |
| + case len(b) > ctlops.MaxObject: |
| + return nil, fmt.Errorf("s3://%s/%s is over %d bytes", f.bucket, key, ctlops.MaxObject) |
| + } |
| + return b, nil |
| +} |
| + |
| +// accountOf returns ACCOUNT from a provider namespace "aws:ACCOUNT:REGION". |
| +func accountOf(namespace string) (string, error) { |
| + f := strings.Split(namespace, ":") |
| + if len(f) != 3 || f[0] != "aws" || f[1] == "" { |
| + return "", errors.New("provider namespace names no account") |
| + } |
| + return f[1], nil |
| +} |
diff --git a/cmd/equipo-hosted-controller/fetcher_test.go b/cmd/equipo-hosted-controller/fetcher_test.go| new file mode 100644 |
| index 00000000..d2eb1062 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-controller/fetcher_test.go |
| @@ -0,0 +1,67 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| +) |
| + |
| +// fakeS3 answers GetObject with body or err, and keeps the last input and |
| +// whether its context had a deadline. |
| +type fakeS3 struct { |
| + body string |
| + err error |
| + in *s3.GetObjectInput |
| + hadDeadline bool |
| +} |
| + |
| +func (f *fakeS3) GetObject(ctx context.Context, in *s3.GetObjectInput, _ ...func(*s3.Options)) (*s3.GetObjectOutput, error) { |
| + f.in = in |
| + _, f.hadDeadline = ctx.Deadline() |
| + if f.err != nil { |
| + return nil, f.err |
| + } |
| + return &s3.GetObjectOutput{Body: io.NopCloser(strings.NewReader(f.body))}, nil |
| +} |
| + |
| +// TestS3FetcherReadsPrefixedObject: the fetcher reads prefix+name from the |
| +// configured bucket, expects the controller's account to own it, bounds |
| +// the call in time, refuses an object over ctlops.MaxObject and passes a |
| +// failure on. No AWS call. |
| +func TestS3FetcherReadsPrefixedObject(t *testing.T) { |
| + t.Parallel() |
| + fake := &fakeS3{body: `{"keys":[]}`} |
| + f := s3Fetcher{client: fake, bucket: "cfg", prefix: "controller/", owner: "123456789012", timeout: time.Second} |
| + b, err := f.Fetch(context.Background(), ctlops.ObjectCertKeys) |
| + if err != nil || string(b) != fake.body { |
| + t.Fatalf("Fetch = (%q, %v), want the body", b, err) |
| + } |
| + if aws.ToString(fake.in.Bucket) != "cfg" || aws.ToString(fake.in.Key) != "controller/cert-keys.json" || |
| + aws.ToString(fake.in.ExpectedBucketOwner) != "123456789012" || !fake.hadDeadline { |
| + t.Fatalf("GetObject input = bucket %q key %q owner %q, deadline %v; want cfg, controller/cert-keys.json, 123456789012, a deadline", |
| + aws.ToString(fake.in.Bucket), aws.ToString(fake.in.Key), aws.ToString(fake.in.ExpectedBucketOwner), fake.hadDeadline) |
| + } |
| + fake.body = strings.Repeat("x", ctlops.MaxObject+1) |
| + if _, err := f.Fetch(context.Background(), ctlops.ObjectCertKeys); err == nil { |
| + t.Fatal("Fetch of an oversized object = nil, want an error") |
| + } |
| + fake.err = errors.New("AccessDenied") |
| + if _, err := f.Fetch(context.Background(), ctlops.ObjectCertKeys); !errors.Is(err, fake.err) { |
| + t.Fatalf("Fetch with GetObject failing = %v, want its error", err) |
| + } |
| + if a, err := accountOf("aws:123456789012:eu-west-1"); err != nil || a != "123456789012" { |
| + t.Fatalf("accountOf = (%q, %v)", a, err) |
| + } |
| + for _, ns := range []string{"test", "aws::eu-west-1", "gcp:1:r"} { |
| + if _, err := accountOf(ns); err == nil { |
| + t.Fatalf("accountOf(%q) = nil error", ns) |
| + } |
| + } |
| +} |
diff --git a/cmd/equipo-hosted-controller/main.go b/cmd/equipo-hosted-controller/main.go| index 62d63f64..961fa031 100644 |
| --- a/cmd/equipo-hosted-controller/main.go |
| +++ b/cmd/equipo-hosted-controller/main.go |
| @@ -33,6 +33,7 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/service/ec2" |
| "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| "github.com/aws/aws-sdk-go-v2/service/sns" |
| "github.com/aws/aws-sdk-go-v2/service/sts" |
| ) |
| @@ -125,7 +126,12 @@ func run(path string) error { |
| // Operator records (orphans, audits, restart settling) go to stderr |
| // at info, beside the log package's lines. |
| opLog := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})) |
| - c, err := hostedctl.New(cfg.ctl, hostedctl.Deps{Store: store, Runner: jobs, Auditor: runner, Alerter: alerter, Log: opLog}) |
| + owner, err := accountOf(cfg.ctl.ProviderNamespace) |
| + if err != nil { |
| + return err |
| + } |
| + fetcher := s3Fetcher{client: s3.NewFromConfig(awsCfg), bucket: cfg.bucket, prefix: cfg.prefix, owner: owner, timeout: fetchTimeout} |
| + c, err := hostedctl.New(cfg.ctl, hostedctl.Deps{Store: store, Runner: jobs, Auditor: runner, Alerter: alerter, Fetcher: fetcher, Log: opLog}) |
| if err != nil { |
| return err |
| } |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 7f4bd78c..33afbccc 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -191,3 +191,26 @@ Mutation checks (each applied by script, the named test run, then restored and c |
| 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. |
| + |
| +### Task 5 review round 1 (t5-r1.md: findings 1 to 3; coordinator's corrected ruling: reload fetches first) |
| + |
| +1. `POST /v1/admin/reload` now fetches before it verifies: `ctlops.Fetcher` (`Fetch(ctx, name)`) is injected as `Deps.Fetcher`; `ctlops.FetchAndReload` fetches `cert-keys.json`, `certificates.json`, `certification-images.json` and `operators.json` (each at most `MaxObject`, 1 MiB) all before writing any, writes each over its local path atomically (temporary file in the same directory, mode 0600, synced, renamed), then verifies and swaps as `Reload` does. A failed or oversized fetch, a failed write or no fetcher is `ErrFetch` (signed 502 `fetch_failed`; hostedclient maps it to `ErrProvider`, operator routes only); verification failures keep their codes; every failure keeps both old sets. `operators.json` is fetched and written for the next start; a reload does not change the API's keys. The S3 fetcher lives only in `cmd/equipo-hosted-controller/fetcher.go` (`s3.GetObject`, `prefix+name` from the new required config fields `config_bucket` and `config_prefix` (ends in `/`), `ExpectedBucketOwner` the controller's account, 20 s per object, body bounded); new required `operators_file`. `go.mod` gains `aws-sdk-go-v2/service/s3 v1.105.0` from the local module cache (`GOPROXY=off`; no other module moved). Startup still reads the local files (`ExecStartPre` fetches them). |
| +2. `auditState.view` takes every field from one reading under one lock (`checkLocked`). |
| +3. The repeated-key and upper-case-key fixtures in `ctlops/ops_test.go` are wrapped in arrays, so they reach `DecodeStrict`'s key checks. |
| + |
| +Tests: TestReloadFetchesBeforeVerifying (local files spoiled, the bucket's good set loads; all four objects fetched in order and written at 0600), TestReloadFetchFailureKeepsOldSets (a failed fetch, an oversized object, no fetcher: 502 `fetch_failed`, no local file written, both sets kept, `reload_failed` audited), TestStatusAuditSnapshot (200,000 views while passing and failing audits are recorded concurrently), TestS3FetcherReadsPrefixedObject (fake `GetObject`; no AWS call). The existing reload tests now change the fake bucket instead of the local files; the removed-key case (TestReloadKeepsOldSetOnBadFile) now arrives by fetch. Config tests gain the three fields and a bad prefix. |
| + |
| +Mutation checks (each applied by script, the named test run, then restored and checked with `cmp`): |
| + |
| +15. Verify before fetching (`reload` called before the fetches, `ctlops/ops.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedctl -run 'TestReloadFetchesBeforeVerifying' -count=1`. Observed: FAIL, `operator_test.go:455: reload = 422 {"code":"certification_images_invalid",...}, want the bucket's 2 certificates and 1 image`. Restored. |
| +16. Fetched objects not written. Same command. Observed: FAIL, the same line, 422 `certification_images_invalid`. Restored. |
| +17. Each object written as soon as it is fetched. Command: `... -run 'TestReloadFetchFailureKeepsOldSets' -count=1`. Observed: FAIL, `operator_test.go:498: failed fetch: .../keys.json = "{\"keys\":[]}", want it unwritten (...)`. Restored. |
| +18. A fetch failure skipped (`continue`). Same command. Observed: FAIL, `operator_test.go:497: reload with a failed fetch = 200 {"certificates":0,"certification_images":0}, want 502 fetch_failed`. Restored. |
| +19. No size bound (`false && len(b) > MaxObject`). Same command. Observed: FAIL, `operator_test.go:501: reload with an oversized object = 200 {...}, want 502 fetch_failed`. Restored. |
| +20. Status audit fields from two readings (round 1's `view`). Command: `... -run 'TestStatusAuditSnapshot' -count=1`. Observed: FAIL, `operator_test.go:541: status view 16937 = {Ran:true Passed:false Passing:true AgeMS:999}: passing from one audit, failed from another`; with `-count=10`, 10 of 10 runs failed. Restored. |
| +21. Repeated keys allowed (`if false && stack[n-1].keys[key]`, `hostedwire/api.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedctl/ctlops -run 'TestCandidatesFileRules' -count=1`. Observed: FAIL, `ops_test.go:50: a repeated key: parse = <nil>, want ErrCandidates`. Restored. |
| +22. Upper-case keys allowed (`if false && !validWireKey(key)`). Same command. Observed: FAIL, `ops_test.go:50: an upper-case key: parse = <nil>, want ErrCandidates`. Restored. |
| +23. No bucket owner on `GetObject`. Command: `CGO_ENABLED=0 go test ./cmd/equipo-hosted-controller -run 'TestS3FetcherReadsPrefixedObject' -count=1`. Observed: FAIL, `fetcher_test.go:48: GetObject input = bucket "cfg" key "controller/cert-keys.json" owner "", deadline true; want ...`. Restored. |
| +24. No timeout (`context.WithCancel`). Same command. Observed: FAIL, `fetcher_test.go:48: ... owner "123456789012", deadline false; want ... a deadline`. Restored. |
| + |
| +Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./internal/hostedwire ./cmd/equipo-hosted-controller ./internal/isolatedjob -count=1` ok (TestProviderTypesStayInAdapter included; hostedctl 23.4 s at load average 102 to 116); `go test -race` of the touched 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 5954/9907. govulncheck was not run on the new s3 module (it needs the network). |
diff --git a/go.mod b/go.mod| index e6d65d3a..d24264e2 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -26,6 +26,7 @@ require ( |
| github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0 |
| github.com/aws/aws-sdk-go-v2/service/lambdacore v1.14.0 |
| github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0 |
| + github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 |
| github.com/aws/aws-sdk-go-v2/service/sns v1.48.0 |
| github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 |
| github.com/aws/smithy-go v1.28.9 |
| @@ -44,13 +45,16 @@ require ( |
| github.com/Masterminds/sprig/v3 v3.3.0 // indirect |
| github.com/STARRY-S/zip v0.2.1 // indirect |
| github.com/andybalholm/brotli v1.2.7 // indirect |
| + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 // indirect |
| github.com/aws/aws-sdk-go-v2/credentials v1.21.3 // indirect |
| github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 // indirect |
| github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect |
| github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect |
| github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect |
| github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect |
| + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23 // indirect |
| github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect |
| + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31 // indirect |
| github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 // indirect |
| github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect |
| github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect |
diff --git a/go.sum b/go.sum| index 7acbc2cc..a708d8a9 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -49,6 +49,8 @@ github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLj |
| github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= |
| github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc= |
| github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0= |
| +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 h1:3IZY0XAJquT3aHzbkHfPzy4ACPcEjVG0x87KOwtpqGY= |
| +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14/go.mod h1:zwM6veDkhGgQFqkBy+uT28AAYpLu+uFMlPl+rCg/73E= |
| github.com/aws/aws-sdk-go-v2/config v1.33.21 h1:NY1d3yXmplUSYnUAue0sR88svD+SJiaI+YJGp8TxSNg= |
| github.com/aws/aws-sdk-go-v2/config v1.33.21/go.mod h1:pVJNXUXaCLu9a/4/liTklg9zR3yO0xm/XBEQhgg5nzc= |
| github.com/aws/aws-sdk-go-v2/credentials v1.21.3 h1:bh+9VoJ4eDzJVEY6jfdNTBa0Dx7tdr+lWSPNovU1vXc= |
| @@ -65,12 +67,18 @@ github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0 h1:EjAV+HmAnHedN+iYZF+b4SQYtMG |
| github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0/go.mod h1:uMJiOkxaT3pV+LAeAvEaXToZ2x3nEnN53HnPdj+pcNo= |
| github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes= |
| github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE= |
| +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23 h1:9Fjh6fi/U5JEStVZijmaMpUwE/gvBJj7x2B/PjbO9To= |
| +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23/go.mod h1:iMoT2f1tClxrWAAnKCXjZQ6LOmfLrMG14wmnWpM+F14= |
| github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I= |
| github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI= |
| +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31 h1:uao4A3QZ5UmB326V6KF+qRpv9Tjz7IlnlnTbbANntlU= |
| +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31/go.mod h1:I/1+z0VwL1GhQyLgkoHDlygpUZ+iTAwOQ/NsftiUL2I= |
| github.com/aws/aws-sdk-go-v2/service/lambdacore v1.14.0 h1:HFdu2C3ZGuz55WTvSLepGCSHFFCZ/E3BVqbq9bPTp8g= |
| github.com/aws/aws-sdk-go-v2/service/lambdacore v1.14.0/go.mod h1:IN/6SlTd5+2FwwqzpuTLBJdYS3K2lE7BP3hD44VyBKM= |
| github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0 h1:fDJjTeLNm1xh1Nwq+pPO/D9RbMbO1F+Kp1q8KJdPmqA= |
| github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0/go.mod h1:GEnG9FBOraRH3j7GPz/wQmuBLI7d+yjDje4IriTgQ7o= |
| +github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 h1:XptwLL+UHXgafYMIHTy59IRovLbhz3znkxY2uS/pbXU= |
| +github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0/go.mod h1:zdmCoFO/dSI7GlrwsPqFJI+WlFnSU4Tc8TJnlXrM1Do= |
| github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 h1:bIEk1HfTd3MGzvDa5YOQUodGr96D9+UTnmBLBB8ZJ10= |
| github.com/aws/aws-sdk-go-v2/service/signin v1.14.0/go.mod h1:LdwHjKqPE9VCC7sTlWcOAizZx3ZJYjmfwC/EW2tIIAE= |
| github.com/aws/aws-sdk-go-v2/service/sns v1.48.0 h1:Y19AwHx+iYmAeiWrqmm3vQ0UwLfBuV5DNuAis5mYZ0A= |
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go| index 90dde21e..f6434c00 100644 |
| --- a/internal/hostedclient/client.go |
| +++ b/internal/hostedclient/client.go |
| @@ -122,6 +122,7 @@ var refusals = map[string]struct { |
| "certificates_invalid": {http.StatusUnprocessableEntity, ErrInternal}, |
| "certification_images_invalid": {http.StatusUnprocessableEntity, ErrInternal}, |
| "alert_failed": {http.StatusBadGateway, ErrProvider}, |
| + "fetch_failed": {http.StatusBadGateway, ErrProvider}, |
| } |
| // APIError is a signed refusal from the controller. Kind is one of the |
diff --git a/internal/hostedctl/audit.go b/internal/hostedctl/audit.go| index 0a04d3b8..8092d68a 100644 |
| --- a/internal/hostedctl/audit.go |
| +++ b/internal/hostedctl/audit.go |
| @@ -69,6 +69,11 @@ func (s *auditState) record(at T, err error) { |
| func (s *auditState) check(now T) error { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| + return s.checkLocked(now) |
| +} |
| + |
| +// checkLocked is check with s.mu held. |
| +func (s *auditState) checkLocked(now T) error { |
| if !s.ran { |
| return fmt.Errorf("%w: none has run yet", ErrNetworkAudit) |
| } |
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go| index c1a825fe..41972c55 100644 |
| --- a/internal/hostedctl/controller.go |
| +++ b/internal/hostedctl/controller.go |
| @@ -72,6 +72,10 @@ type Deps struct { |
| Runner isolatedjob.Runner |
| Auditor isolatedjob.NetworkAuditor |
| Alerter Alerter |
| + // Fetcher, when set, reads the config bucket objects POST |
| + // /v1/admin/reload fetches (ctlops.FetchAndReload); without it a reload |
| + // is refused (ctlops.ErrFetch). |
| + Fetcher ctlops.Fetcher |
| // Log gets one info record for each orphan stopped or deferred, each |
| // failed network audit and each restart re-base or elapsed_unknown |
| // stop (logs.go). Nil discards them. |
| @@ -85,6 +89,7 @@ type Controller struct { |
| runner isolatedjob.Runner |
| auditor isolatedjob.NetworkAuditor |
| alerter Alerter |
| + fetcher ctlops.Fetcher // nil: reload refused |
| log *slog.Logger |
| audit auditState // the last network audit result (audit.go) |
| rebased rebasedSet // jobs re-based after a restart (refresh.go) |
| @@ -141,12 +146,16 @@ func New(cfg Config, d Deps) (*Controller, error) { |
| cfg.Egress = slices.Clone(cfg.Egress) |
| cfg.Manifest = cfg.Manifest.Clone() |
| cfg.ProxyCodeKey = slices.Clone(cfg.ProxyCodeKey) |
| + var fetcher ctlops.Fetcher |
| + if !isNil(d.Fetcher) { |
| + fetcher = d.Fetcher |
| + } |
| log := d.Log |
| if log == nil { |
| log = slog.New(slog.DiscardHandler) |
| } |
| return &Controller{cfg: cfg, store: d.Store, runner: boundedRunner{d.Runner}, auditor: boundedAuditor{d.Auditor}, |
| - alerter: d.Alerter, log: log}, nil |
| + alerter: d.Alerter, fetcher: fetcher, log: log}, nil |
| } |
| // isNil reports whether v is nil or an interface holding a nil pointer, map, |
diff --git a/internal/hostedctl/ctlops/ops.go b/internal/hostedctl/ctlops/ops.go| index a7307b04..1257c0d4 100644 |
| --- a/internal/hostedctl/ctlops/ops.go |
| +++ b/internal/hostedctl/ctlops/ops.go |
| @@ -7,6 +7,7 @@ package ctlops |
| import ( |
| "bytes" |
| + "context" |
| "crypto/sha256" |
| "encoding/binary" |
| "encoding/hex" |
| @@ -14,6 +15,7 @@ import ( |
| "errors" |
| "fmt" |
| "os" |
| + "path/filepath" |
| "strings" |
| "sync" |
| "time" |
| @@ -132,11 +134,107 @@ func (c *Candidates) Allows(image isolatedjob.ImageDigest, size isolatedjob.Size |
| return nil |
| } |
| -// Files are the controller's local files a reload re-reads: the |
| +// Files are the controller's local copies of its config bucket objects: the |
| // certificate key file, the certificate file and the certification images |
| -// file. |
| +// file, which a reload re-reads, and the operator keys file, which only a |
| +// restart reads. |
| type Files struct { |
| - CertKeys, Certificates, CertificationImages string |
| + CertKeys, Certificates, CertificationImages, Operators string |
| +} |
| + |
| +// The config bucket objects FetchAndReload fetches, by name under the |
| +// controller's prefix. |
| +const ( |
| + ObjectCertKeys = "cert-keys.json" |
| + ObjectCertificates = "certificates.json" |
| + ObjectCertificationImages = "certification-images.json" |
| + ObjectOperators = "operators.json" |
| +) |
| + |
| +// MaxObject bounds one fetched object. |
| +const MaxObject = hostedwire.MaxBody |
| + |
| +// Fetcher reads one object of the controller's config bucket prefix by |
| +// name. It bounds its own calls in time. |
| +type Fetcher interface { |
| + Fetch(ctx context.Context, name string) ([]byte, error) |
| +} |
| + |
| +// ErrFetch: an object could not be fetched or written to its local path. |
| +// The old sets are kept. |
| +var ErrFetch = errors.New("ctlops: the config bucket objects could not be fetched") |
| + |
| +// FetchAndReload fetches every config bucket object (ObjectCertKeys, |
| +// ObjectCertificates, ObjectCertificationImages, ObjectOperators) through |
| +// f, all before writing any; writes each to its path in files atomically |
| +// (a temporary file in the same directory, synced, mode 0600, then |
| +// renamed over it); and only then verifies and swaps as Reload does, from |
| +// those files. A failed or oversized fetch, or a failed write, is ErrFetch; |
| +// a verification failure is Reload's. Either way certs and cands are left |
| +// as they were. The operator keys are fetched and written for the next |
| +// start, which reads them; a reload does not change the API's keys. |
| +func FetchAndReload(ctx context.Context, f Fetcher, files Files, certs *ctlcert.Set, cands *Candidates) (hostedwire.ReloadResponse, error) { |
| + if f == nil || certs == nil || cands == nil { |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: no config bucket fetcher or no sets", ErrFetch) |
| + } |
| + cands.reload.Lock() |
| + defer cands.reload.Unlock() |
| + objects := []struct{ name, path string }{{ObjectCertKeys, files.CertKeys}, {ObjectCertificates, files.Certificates}, |
| + {ObjectCertificationImages, files.CertificationImages}, {ObjectOperators, files.Operators}} |
| + fetched := make([][]byte, len(objects)) |
| + for i, o := range objects { |
| + b, err := f.Fetch(ctx, o.name) |
| + switch { |
| + case err != nil: |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: %s: %v", ErrFetch, o.name, err) |
| + case len(b) > MaxObject: |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: %s is over %d bytes", ErrFetch, o.name, MaxObject) |
| + case o.path == "": |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: %s has no local path", ErrFetch, o.name) |
| + } |
| + fetched[i] = b |
| + } |
| + for i, o := range objects { |
| + if err := writeAtomic(o.path, fetched[i]); err != nil { |
| + return hostedwire.ReloadResponse{}, fmt.Errorf("%w: write %s: %v", ErrFetch, o.name, err) |
| + } |
| + } |
| + return reload(files, certs, cands) |
| +} |
| + |
| +// writeAtomic replaces path with b, mode 0600, so a reader sees the old |
| +// file or the new one, never part of one. |
| +func writeAtomic(path string, b []byte) error { |
| + tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".fetch-*") |
| + if err != nil { |
| + return err |
| + } |
| + done := false |
| + defer func() { |
| + if !done { |
| + _ = tmp.Close() |
| + _ = os.Remove(tmp.Name()) |
| + } |
| + }() |
| + if err := tmp.Chmod(0o600); err != nil { |
| + return err |
| + } |
| + if _, err := tmp.Write(b); err != nil { |
| + return err |
| + } |
| + if err := tmp.Sync(); err != nil { |
| + return err |
| + } |
| + if err := tmp.Close(); err != nil { |
| + return err |
| + } |
| + if err := os.Rename(tmp.Name(), path); err != nil { |
| + _ = os.Remove(tmp.Name()) |
| + done = true |
| + return err |
| + } |
| + done = true |
| + return nil |
| } |
| // Reload reads files from local disk and, if every one checks, makes them |
| @@ -153,6 +251,11 @@ func Reload(files Files, certs *ctlcert.Set, cands *Candidates) (hostedwire.Relo |
| } |
| cands.reload.Lock() |
| defer cands.reload.Unlock() |
| + return reload(files, certs, cands) |
| +} |
| + |
| +// reload is Reload with cands.reload held. |
| +func reload(files Files, certs *ctlcert.Set, cands *Candidates) (hostedwire.ReloadResponse, error) { |
| raw, err := os.ReadFile(files.CertificationImages) |
| if err != nil { |
| return hostedwire.ReloadResponse{}, fmt.Errorf("%w: %v", ErrCandidates, err) |
diff --git a/internal/hostedctl/ctlops/ops_test.go b/internal/hostedctl/ctlops/ops_test.go| index ddb44ba3..b0c6f937 100644 |
| --- a/internal/hostedctl/ctlops/ops_test.go |
| +++ b/internal/hostedctl/ctlops/ops_test.go |
| @@ -37,8 +37,8 @@ func TestCandidatesFileRules(t *testing.T) { |
| 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 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) + `]`, |
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go| index 6e4c210c..69dec0fd 100644 |
| --- a/internal/hostedctl/http.go |
| +++ b/internal/hostedctl/http.go |
| @@ -89,6 +89,7 @@ var apiErrors = []apiError{ |
| {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."}, |
| + {ctlops.ErrFetch, http.StatusBadGateway, "fetch_failed", "The config bucket could not be read. The old sets are kept."}, |
| {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."}, |
diff --git a/internal/hostedctl/launch_test.go b/internal/hostedctl/launch_test.go| index 0f930158..a738c5df 100644 |
| --- a/internal/hostedctl/launch_test.go |
| +++ b/internal/hostedctl/launch_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlops" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| @@ -53,6 +54,8 @@ type launchEnv struct { |
| store *Store |
| c *Controller |
| logs *syncBuffer // every controller's Deps.Log, as text (logs_test.go) |
| + // fetcher is every controller's Deps.Fetcher (operator_test.go). |
| + fetcher ctlops.Fetcher |
| } |
| func newLaunchEnv(t *testing.T) *launchEnv { |
| @@ -106,7 +109,7 @@ func (e *launchEnv) newController() { |
| e.logs = &syncBuffer{} |
| } |
| c, err := New(e.cfg, Deps{Store: e.store, Runner: e.run, Auditor: e.fake, Alerter: &recordingAlerter{}, |
| - Log: slog.New(slog.NewTextHandler(e.logs, nil))}) |
| + Fetcher: e.fetcher, Log: slog.New(slog.NewTextHandler(e.logs, nil))}) |
| if err != nil { |
| e.t.Fatalf("New = %v", err) |
| } |
diff --git a/internal/hostedctl/operator_test.go b/internal/hostedctl/operator_test.go| index c489ec0a..7b4929a0 100644 |
| --- a/internal/hostedctl/operator_test.go |
| +++ b/internal/hostedctl/operator_test.go |
| @@ -2,6 +2,7 @@ package hostedctl |
| import ( |
| "bytes" |
| + "context" |
| "crypto/ed25519" |
| "encoding/json" |
| "errors" |
| @@ -10,6 +11,7 @@ import ( |
| "path/filepath" |
| "reflect" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| @@ -36,33 +38,71 @@ func candVersions(d isolatedjob.ImageDigest, s isolatedjob.Size) (string, bool) |
| 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. |
| +// certification images from a fake config bucket into files in a |
| +// temporary directory: at first the test key, imgA's certificate (only: |
| +// testCerts also certifies imgB) and imgB as the one candidate, in the |
| +// bucket and on disk alike. |
| type opEnv struct { |
| *apiEnv |
| - files ctlops.Files |
| + files ctlops.Files |
| + bucket *fakeBucket |
| } |
| 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 := &opEnv{apiEnv: &apiEnv{launchEnv: newLaunchEnv(t)}, bucket: &fakeBucket{objects: map[string]string{}}, |
| + files: ctlops.Files{CertKeys: filepath.Join(dir, "keys.json"), Certificates: filepath.Join(dir, "certificates.json"), |
| + CertificationImages: filepath.Join(dir, "certification-images.json"), Operators: filepath.Join(dir, "operators.json")}} |
| + e.put(ctlops.ObjectCertKeys, string(ctlcerttest.KeysJSON())) |
| + e.put(ctlops.ObjectCertificates, string(ctlcerttest.CertsJSON(certA2()))) |
| + e.put(ctlops.ObjectCertificationImages, candidatesJSON) |
| + e.put(ctlops.ObjectOperators, `{"operators":["op-1"]}`) |
| + for name, path := range map[string]string{ctlops.ObjectCertKeys: e.files.CertKeys, ctlops.ObjectCertificates: e.files.Certificates, |
| + ctlops.ObjectCertificationImages: e.files.CertificationImages, ctlops.ObjectOperators: e.files.Operators} { |
| + e.write(path, e.bucket.objects[name]) |
| + } |
| 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.fetcher = e.bucket |
| e.newController() |
| e.audit() |
| e.serve() |
| return e |
| } |
| +// fakeBucket is the config bucket: objects by name, a failure to give for |
| +// some names, and every name fetched, in order. |
| +type fakeBucket struct { |
| + mu sync.Mutex |
| + objects map[string]string |
| + fail map[string]error |
| + fetched []string |
| +} |
| + |
| +func (b *fakeBucket) Fetch(_ context.Context, name string) ([]byte, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.fetched = append(b.fetched, name) |
| + if err := b.fail[name]; err != nil { |
| + return nil, err |
| + } |
| + o, ok := b.objects[name] |
| + if !ok { |
| + return nil, errors.New("no such object") |
| + } |
| + return []byte(o), nil |
| +} |
| + |
| +func (e *opEnv) put(name, body string) { |
| + e.bucket.mu.Lock() |
| + defer e.bucket.mu.Unlock() |
| + e.bucket.objects[name] = body |
| +} |
| + |
| func (e *opEnv) write(path, body string) { |
| e.t.Helper() |
| if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| @@ -70,6 +110,15 @@ func (e *opEnv) write(path, body string) { |
| } |
| } |
| +func (e *opEnv) read(path string) string { |
| + e.t.Helper() |
| + b, err := os.ReadFile(path) |
| + if err != nil { |
| + e.t.Fatal(err) |
| + } |
| + return string(b) |
| +} |
| + |
| func certLaunch(image isolatedjob.ImageDigest, size isolatedjob.Size) hostedwire.CertLaunchRequest { |
| return hostedwire.CertLaunchRequest{Image: image, Size: size, LaunchByUnixMS: testLaunchBy} |
| } |
| @@ -178,7 +227,7 @@ func TestCertLaunchNeedsCandidateImage(t *testing.T) { |
| 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, `[]`) |
| + e.put(ctlops.ObjectCertificationImages, `[]`) |
| 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) |
| } |
| @@ -189,7 +238,7 @@ func TestCertLaunchNeedsCandidateImage(t *testing.T) { |
| 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) |
| + e.put(ctlops.ObjectCertificationImages, 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) |
| } |
| @@ -242,8 +291,8 @@ func TestReloadKeepsOldSetOnBadFile(t *testing.T) { |
| 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, `[]`) |
| + e.put(ctlops.ObjectCertificates, string(ctlcerttest.CertsJSON(certA2(), bad))) |
| + e.put(ctlops.ObjectCertificationImages, `[]`) |
| 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) |
| @@ -252,20 +301,20 @@ func TestReloadKeepsOldSetOnBadFile(t *testing.T) { |
| 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))) |
| + e.put(ctlops.ObjectCertificates, 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) |
| + e.put(ctlops.ObjectCertificationImages, 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, `[]`) |
| + e.put(ctlops.ObjectCertificationImages, `[]`) |
| r := reload() |
| var rr hostedwire.ReloadResponse |
| if r.status != http.StatusOK || hostedwire.DecodeStrict(bytes.NewReader(r.body), &rr) != nil || rr != (hostedwire.ReloadResponse{Certificates: 2}) { |
| @@ -278,7 +327,7 @@ func TestReloadKeepsOldSetOnBadFile(t *testing.T) { |
| 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":[]}`) |
| + e.put(ctlops.ObjectCertKeys, `{"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()) |
| } |
| @@ -387,3 +436,109 @@ func TestStatusOperatorOnly(t *testing.T) { |
| t.Fatalf("audit after a failure = %+v, want ran and failing", s.NetworkAudit) |
| } |
| } |
| + |
| +// TestReloadFetchesBeforeVerifying: a reload fetches every config bucket |
| +// object first, writes each over its local file, and only then verifies: |
| +// local files that would fail do not matter, the bucket's do, and the |
| +// operator keys file is written too. |
| +func TestReloadFetchesBeforeVerifying(t *testing.T) { |
| + t.Parallel() |
| + e := newOpEnv(t) |
| + for _, p := range []string{e.files.CertKeys, e.files.Certificates, e.files.CertificationImages, e.files.Operators} { |
| + e.write(p, "not json") |
| + } |
| + certB := ctlcerttest.Cert(imgB, testHosts...) |
| + e.put(ctlops.ObjectCertificates, string(ctlcerttest.CertsJSON(certA2(), certB))) |
| + e.put(ctlops.ObjectOperators, `{"operators":["op-2"]}`) |
| + r := e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idOp, keyOp) |
| + if r.status != http.StatusOK || string(r.body) != `{"certificates":2,"certification_images":1}` { |
| + t.Fatalf("reload = %d %s, want the bucket's 2 certificates and 1 image", r.status, r.body) |
| + } |
| + want := []string{ctlops.ObjectCertKeys, ctlops.ObjectCertificates, ctlops.ObjectCertificationImages, ctlops.ObjectOperators} |
| + if !reflect.DeepEqual(e.bucket.fetched, want) { |
| + t.Fatalf("fetched %v, want %v", e.bucket.fetched, want) |
| + } |
| + for name, path := range map[string]string{ctlops.ObjectCertKeys: e.files.CertKeys, ctlops.ObjectCertificates: e.files.Certificates, |
| + ctlops.ObjectCertificationImages: e.files.CertificationImages, ctlops.ObjectOperators: e.files.Operators} { |
| + info, err := os.Stat(path) |
| + if got := e.read(path); err != nil || got != e.bucket.objects[name] || info.Mode().Perm() != 0o600 { |
| + t.Fatalf("local %s = %q (%v, %v), want the bucket's %q at 0600", name, got, info.Mode().Perm(), err, e.bucket.objects[name]) |
| + } |
| + } |
| + if !e.cfg.Certs.Valid(hostedcert.Digest(certB)) { |
| + t.Fatal("imgB's certificate from the bucket is not in the set") |
| + } |
| +} |
| + |
| +// TestReloadFetchFailureKeepsOldSets: a fetch that fails, an oversized |
| +// object, or no fetcher at all, answers fetch_failed, writes no local |
| +// file and keeps both sets. |
| +func TestReloadFetchFailureKeepsOldSets(t *testing.T) { |
| + t.Parallel() |
| + e := newOpEnv(t) |
| + before := map[string]string{} |
| + for _, p := range []string{e.files.CertKeys, e.files.Certificates, e.files.CertificationImages, e.files.Operators} { |
| + before[p] = e.read(p) |
| + } |
| + e.put(ctlops.ObjectCertKeys, `{"keys":[]}`) |
| + e.put(ctlops.ObjectCertificationImages, `[]`) |
| + kept := func(what string) { |
| + t.Helper() |
| + if !e.cfg.Certs.Valid(certA()) || e.cfg.Candidates.Allows(imgB, isolatedjob.SizeSmall) != nil { |
| + t.Fatalf("%s: imgA certified %v, imgB candidate %v; want both kept", what, e.cfg.Certs.Valid(certA()), e.cfg.Candidates.Allows(imgB, isolatedjob.SizeSmall)) |
| + } |
| + for p, b := range before { |
| + if got := e.read(p); got != b { |
| + t.Fatalf("%s: %s = %q, want it unwritten (%q)", what, p, got, b) |
| + } |
| + } |
| + } |
| + e.bucket.fail = map[string]error{ctlops.ObjectOperators: errors.New("access denied")} |
| + wantCode(t, "reload with a failed fetch", e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idOp, keyOp), http.StatusBadGateway, "fetch_failed") |
| + kept("failed fetch") |
| + e.bucket.fail = nil |
| + e.put(ctlops.ObjectOperators, strings.Repeat(" ", ctlops.MaxObject+1)) |
| + wantCode(t, "reload with an oversized object", e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idOp, keyOp), http.StatusBadGateway, "fetch_failed") |
| + kept("oversized object") |
| + e.fetcher = nil |
| + e.newController() |
| + e.audit() |
| + e.serve() |
| + wantCode(t, "reload with no fetcher", e.call("POST", "/v1/admin/reload", hostedwire.ReloadRequest{}, idOp, keyOp), http.StatusBadGateway, "fetch_failed") |
| + kept("no fetcher") |
| + if a := e.lastAudit(); a.Action != actionReloadFailed { |
| + t.Fatalf("last audit row = %+v, want reload_failed", a) |
| + } |
| +} |
| + |
| +// TestStatusAuditSnapshot: while audits that pass and fail are recorded |
| +// concurrently, every status view is one audit's: never passing unless |
| +// that audit passed. |
| +func TestStatusAuditSnapshot(t *testing.T) { |
| + t.Parallel() |
| + var s auditState |
| + stop := make(chan struct{}) |
| + var wg sync.WaitGroup |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + for i := T(1); ; i++ { |
| + select { |
| + case <-stop: |
| + return |
| + default: |
| + } |
| + var err error |
| + if i%2 == 0 { |
| + err = errors.New("fail") |
| + } |
| + s.record(i, err) |
| + } |
| + }() |
| + defer func() { close(stop); wg.Wait() }() |
| + for i := 0; i < 200000; i++ { |
| + if v := s.view(T(time.Second)); v.Passing && !v.Passed { |
| + t.Fatalf("status view %d = %+v: passing from one audit, failed from another", i, v) |
| + } |
| + } |
| +} |
diff --git a/internal/hostedctl/ops.go b/internal/hostedctl/ops.go| index 7f5155b7..454c32c0 100644 |
| --- a/internal/hostedctl/ops.go |
| +++ b/internal/hostedctl/ops.go |
| @@ -86,13 +86,14 @@ func serveCerts(_ context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwi |
| 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. |
| +// serveReload fetches the config bucket objects into Config.Files, then |
| +// re-reads them (ctlops.FetchAndReload), 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) |
| + res, err := ctlops.FetchAndReload(ctx, c.fetcher, 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() |
| @@ -180,13 +181,12 @@ func (c *Controller) Status(ctx context.Context) (hostedwire.StatusResponse, err |
| return s, nil |
| } |
| -// view is the last audit's result at now; the age counts from when it |
| -// began. |
| +// view is the last audit's result at now, every field from one reading |
| +// under one lock; 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} |
| + v := hostedwire.AuditStatus{Ran: s.ran, Passed: s.passed, Passing: s.checkLocked(now) == nil} |
| if s.ran { |
| v.AgeMS = time.Duration(now - s.at).Milliseconds() |
| } |