carlos / platform Public

ha: observe verified regional capacity without claims: review fixes r1

claude agent, operated by paul@keymail.dev 6e78e4cc081ad89415554eb87b4cadc2d9adb828 parent 85e9e37
4 files changed, +329 −23
  • internal/console/hacapacity.go +1 −1
  • internal/console/hacapacity_observe.go +110 −19
  • internal/console/hacapacity_observe_test.go +102 −0
  • internal/console/hacapacity_test.go +116 −3

CI failed — run details

Intent

Human

<task-notification> <task-id>b7bor2n8o</task-id> <tool-use-id>toolu_01U8cqdvcAA7AN31mPVWNw9W</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/b7bor2n8o.output</output-file> <status>completed</status> <summary>Background command "Push T0, check T1 header, wait for T1" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>afed257f89556f713</task-id> <tool-use-id>toolu_01F3K2GN3Ys6gTpgP7CaY9Wk</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/afed257f89556f713.output</output-file> <status>completed</status> <summary>Agent "Review T1 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**T1 review: bounded HA capacity observation (79176bba..85e9e37f)** **Spec compliance: ✅.** Nothing missing, extra or misunderstood. One reading of I2 is contested: the precedence-table wording supports what the code does, but I2's literal text does not (P2-1 below). **Code quality: needs fixes.** One P2 to decide and fix in this task. Everything else is P3. I found no P1. **What I checked and found correct** - **Precedence order:** checks run scope, then identity, then liveness, then headroom, then pool, in that order (`hacapacity.go:336-515`). A valid exclusion beats an unknown field. The "no HA neighbor + null placement" row pins this. - **Fail-safe defaults:** - The home region matches only placement `""` or an omitted field. Explicit null is unknown. - Self-stale edges are excluded before any status is needed. Missing status is unknown; stale status is excluded; an empty `metrics.instance_id` is unknown. - Admission requires explicit `box_role`, `admitted` and `drained`. This is stricter than P3a's legacy default, as the design requires. - Headroom goes through `boxchoice.Placeable` with the 15-minute bar, and bad totals are rejected first. Pool narrowing requires `accepts_inbound=true` plus `serves_shared_pool` or `named_pools` membership. - **Aggregation:** one positive witness allows a create despite other unknowns. Complete-zero needs every file classified. `MissingNamedPoolsOnly` is set only when every unknown is `named_pools_missing`. - **Identity:** - Each in-scope ref is verified once per pass through `boxid.Load` and `Verifier.Enroll`, using the AWS region from config, never from the file. Account checks happen inside Enroll. - The g- derivation matches `internal/host/boxreference.go:97` byte for byte, with the shared golden vector. - Fixed pins check region and instance. Unbound refs are excluded with C11. Duplicate instance IDs and refs make the set unknown. - The status-label case-alias fix is correct, because `LoadBoxesComplete` reads sequentially, so there is no race on the view maps. - **Runner:** - One loop (`sync.Once` on both the server and the observer). Fixed ticker, 45 s deadline, one pass in flight (it waits for the result). - On timeout or error it publishes unknown immediately. Expiry (under 120 s from pass start, checked with `!now.Before(started)`) is recomputed on every use. - Readers use only atomic loads. Published observations are never mutated. - Started from serve only when HA regions are set, never from NewServer. SIGTERM cancels the runner and waits for it to finish. - **Bounded reads:** - Edges: `MaxKeys=201` plus a truncation check. - Status: one `ListObjectsV2` with `MaxKeys=1000`. A truncated page is incomplete. The 24 h filter runs before the 200 cap. Missing modification times are kept. `ModLister` is hidden, so there is no second LIST. - Body limits use `LimitReader(cap+1)` at the transport. The S3 client is a clone with `NopRetryer` and one attempt, proven against a failing transport, and the shared client is unchanged. - **Wiring and copy:** `TimeS3Store` returns the bare `*release.S3Store`, so the production store is supported. C05–C08 and C11 match `copy-approved.md` word for word. No shared package changed. **Findings** - **P2-1 (I2: malformed evidence becomes zero).** Identity records that are malformed are treated as conclusively invalid, so they are excluded instead of unknown. - Where: `hacapacity_observe.go:409-411` (any `haJSON` failure, such as duplicate keys or non-JSON, becomes `identity_invalid`). Also `:413-419`, where a non-object record skips the version check, and `:424-427`, where every `Enroll` error becomes `identity_invalid`. That includes decode failures: "record is not JSON", trailing data, unknown fields, "document is not base64" and "document is not JSON" (`internal/boxid/verify.go:71-134`). - The test pins this behaviour: `hacapacity_test.go:313-316` stores `identity_document:"bad"` and expects `CompleteZero`. - Failure: one corrupt record on an in-scope box turns that region's answer into complete-zero, which means a noRoom refusal, an operator page and a metric of 0. It should be unknown (C04, no metric). - Fix: treat decode, base64 and JSON-shape failures as unknown. Exclude only a well-formed record that fails verification: bad signature, wrong account, wrong region, record naming a different box, or no instance. - Why P2 and not P1: row 2 of the precedence table says "conclusively invalid identity is excluded", which arguably covers this. I2 literally forbids it. The controller should decide which wins. - **P3-1 (key hygiene).** Any key under `control/edges/` or a recent `status/boxes/` key that is not `&lt;ref&gt;.json` fails the whole observation (`hacapacity_observe.go:318-320, 364-367`). Every other reader skips such keys (`edgesfile/snapshot.go:257`). This matches the design's "unassignable key" rule for S3. The directory adapter also counts DirStore `*.tmp` files and fails on subdirectories (`:202-204`), unlike `DirStore.List` (`release/store.go:640`). Local passes can therefore fail transiently while a box is writing. - **P3-2.** Null `named_pools` is reported as `named_pools_malformed`, so it gets C04 rather than C10 (`hacapacity.go:502-507`). Ruling 6 groups null with absent; whether null should earn the "missing publication" flag needs a decision. - **P3-3.** C11 is logged on every pass for each unbound box (`hacapacity_observe.go:439`), about 1440 lines a day per box. Log only when the state changes. - **P3-4.** `haJSON` has no depth limit (`hacapacity.go:59-110`). A 1 MiB body of `[` characters recurses about a million frames every minute before `json.Unmarshal`'s 10k depth limit is reached. Producers are trusted boxes, so this is hardening. - **P3-5.** Shutdown waits without a time limit: the runner's `&lt;-result` (`hacapacity_observe.go:492`) and SIGTERM's `&lt;-capacityDone` (`main.go`) will hang if a store ignores cancellation. The S3 SDK does honour context, so the risk is low. - **P3-6.** Edges fields are read by exact key (`hacapacity.go:346` and others), while host and console structs decode case-insensitively. This is the same alias family as the status-label fix. Producers are Go marshal output, so it is low risk. - **P3-7.** A file whose scope is unknown can name another box's ref without creating a ref conflict, because conflicts are only collected for in-scope files (`hacapacity_observe.go:381-402`). It already blocks complete-zero; the only effect is that it cannot cancel a peer's positive witness. - **P3-8.** An empty `secrets_key_fp` from a box with no key is unknown, not an exclusion (`hacapacity.go:364-366`). That is conservative. In practice neighbours are excluded anyway because hosts always publish `lifetimes-1`. - **P3-9.** The config size limit reuses `haCapacityIdentityLimit` (`hacapacity.go:112`). The value (64 KiB) is right; only the name is misleading. **Tests:** they are not vacuous. They run the golden bytes through the real DirStore, the decoder, a real signer and the real S3 transport. The implementer's five mutations line up with the assertions I read. One gap (P3): no test removes the identity record of an in-scope fresh box. Missing identity is only covered through the oversize-read case. **⚠️ Could not verify** - Whether the regional count should require `accepts_inbound` (currently it does not, since inbound sits in step 5). That is the metric's meaning, which T2 decides. - That production `control/edges/` and `status/boxes/` hold only `&lt;ref&gt;.json` keys. Otherwise P3-1 becomes a permanent outage of HA creates. - That the dev console has `CONSOLE_HOME_REGION`, `CARLOS_SECRETS_PUBKEY`, `CARLOS_AWS_ACCOUNT` and the new config set. Without them it logs C05 and every HA create refuses as unknown. This needs checking on the dev card. - I re-ran no tests, as instructed.</result> <usage><subagent_tokens>171898</subagent_tokens><tool_uses>59</tool_uses><duration_ms>625049</duration_ms></usage> </task-notification>

Attributed to this commit: 17.6 g CO₂e (2,171,896 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p2b-build, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/hacapacity.go b/internal/console/hacapacity.go
index 1903b342f..6d25781df 100644
--- a/internal/console/hacapacity.go
+++ b/internal/console/hacapacity.go
@@ -501,7 +501,7 @@ func haPool(fields haFields, pool string) (eligible, known bool, code string) {
}
pools, ok := haField[[]string](fields, "named_pools")
if !ok {
- if _, present := fields["named_pools"]; !present {
+ if raw, present := fields["named_pools"]; !present || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return false, false, "named_pools_missing"
}
return false, false, "named_pools_malformed"
diff --git a/internal/console/hacapacity_observe.go b/internal/console/hacapacity_observe.go
index 197413430..a4309508f 100644
--- a/internal/console/hacapacity_observe.go
+++ b/internal/console/hacapacity_observe.go
@@ -2,7 +2,11 @@ package console
import (
"context"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/base64"
"encoding/json"
+ "errors"
"fmt"
"io"
"log"
@@ -199,6 +203,9 @@ func (s *haCapacityStore) dirPage(ctx context.Context, prefix string, limit int)
}
mods := make([]haObject, 0, len(entries))
for _, e := range entries {
+ if e.IsDir() || strings.HasSuffix(e.Name(), ".tmp") {
+ continue
+ }
if !e.Type().IsRegular() {
return nil, false, errHACapacity
}
@@ -406,24 +413,9 @@ func (o *haObserver) observe(ctx context.Context, start time.Time) *HACapacityOb
f.identityCode = "identity_missing"
continue
}
- if haJSON(raw, false) != nil {
- f.identityCode = "identity_invalid"
- continue
- }
- var identity haFields
- if json.Unmarshal(raw, &identity) == nil {
- if version, ok := haField[int](identity, "v"); !ok || version != 1 {
- f.identityCode = "identity_version"
- continue
- }
- }
- if o.verifier.Account == "" || o.verifier.Certs[o.config.Regions[region].AWSRegion] == nil {
- f.identityCode = "identity_verifier_unavailable"
- continue
- }
- ev, err := o.verifier.Enroll(raw, boxid.Expect{Box: f.ref, AWSRegion: o.config.Regions[region].AWSRegion})
- if err != nil {
- f.identityCode = "identity_invalid"
+ ev, code := o.enrollIdentity(raw, f.ref, o.config.Regions[region].AWSRegion)
+ if code != "" {
+ f.identityCode = code
continue
}
f.instance = ev.Cloud.InstanceID
@@ -436,7 +428,6 @@ func (o *haObserver) observe(ctx context.Context, start time.Time) *HACapacityOb
}
} else if f.ref != haGroupReference(ev.Cloud.Account, f.instance) {
f.identityCode = "identity_unbound"
- log.Printf(haUnboundCopy+" observation=%s box=%s", obs.id, f.ref)
}
}
for _, indices := range instances {
@@ -456,6 +447,104 @@ func (o *haObserver) observe(ctx context.Context, start time.Time) *HACapacityOb
}
return obs
}
+
+// enrollIdentity separates malformed evidence from proven verification failures.
+// boxid.ErrUnverified covers both, so its presence alone cannot establish zero.
+func (o *haObserver) enrollIdentity(raw []byte, ref, region string) (boxid.Evidence, string) {
+ var record haFields
+ if haJSON(raw, false) != nil || json.Unmarshal(raw, &record) != nil || record == nil {
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ if version, ok := haField[int](record, "v"); !ok || version != 1 {
+ return boxid.Evidence{}, "identity_version"
+ }
+ for key := range record {
+ switch key {
+ case "v", "box", "identity_document", "identity_signature", "written_at":
+ default:
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ }
+ for _, key := range []string{"box", "identity_document", "identity_signature", "written_at"} {
+ if _, present := record[key]; key == "written_at" && !present {
+ continue
+ }
+ if _, ok := haField[string](record, key); !ok {
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ }
+ var rec boxid.Record
+ if json.Unmarshal(raw, &rec) != nil {
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ doc, err := base64.StdEncoding.DecodeString(rec.IdentityDocument)
+ if err != nil {
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ sig, err := base64.StdEncoding.DecodeString(rec.IdentitySignature)
+ if err != nil {
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ var fields haFields
+ if haJSON(doc, false) != nil || json.Unmarshal(doc, &fields) != nil || fields == nil {
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ // AWS documents contain additional fields (including nullable fields).
+ // Check the types consumed by Enroll, without rejecting that AWS schema.
+ for _, key := range []string{"accountId", "region", "instanceId"} {
+ if _, present := fields[key]; present {
+ if _, ok := haField[string](fields, key); !ok {
+ return boxid.Evidence{}, "identity_malformed"
+ }
+ }
+ }
+ account, _ := haField[string](fields, "accountId")
+ docRegion, _ := haField[string](fields, "region")
+ instance, _ := haField[string](fields, "instanceId")
+ if o.verifier.Account == "" || o.verifier.Certs[region] == nil {
+ return boxid.Evidence{}, "identity_verifier_unavailable"
+ }
+ ev, err := o.verifier.Enroll(raw, boxid.Expect{Box: ref, AWSRegion: region})
+ if err == nil {
+ return ev, ""
+ }
+ // Prove the failure independently instead of matching untyped error text.
+ // Any remaining verifier failure stays unknown, including missing certs.
+ if rec.Box != ref {
+ return boxid.Evidence{}, "identity_invalid"
+ }
+ if cert := o.verifier.Certs[docRegion]; cert != nil {
+ signatureErr := cert.CheckSignature(x509.SHA256WithRSA, doc, sig)
+ if errors.Is(signatureErr, rsa.ErrVerification) ||
+ (signatureErr == nil && (account != o.verifier.Account || docRegion != region || instance == "")) {
+ return boxid.Evidence{}, "identity_invalid"
+ }
+ }
+ return boxid.Evidence{}, "identity_unreadable"
+}
+
+func haLogUnboundChanges(obs *HACapacityObservation, previous map[string]bool) map[string]bool {
+ if obs.unavailable != "" {
+ return previous
+ }
+ current := map[string]bool{}
+ for _, f := range obs.files {
+ if f.identityCode == "identity_unbound" {
+ current[f.ref] = true
+ if !previous[f.ref] {
+ log.Printf(haUnboundCopy+" code=C11 state=enter observation=%s box=%s", obs.id, f.ref)
+ }
+ }
+ }
+ for ref := range previous {
+ if !current[ref] {
+ // C11's approved prose describes exclusion, so only use it on entry.
+ log.Printf("code=C11 state=leave observation=%s box=%s", obs.id, ref)
+ }
+ }
+ return current
+}
+
func (o *haObserver) start(ctx context.Context) <-chan struct{} {
o.once.Do(func() { go o.run(ctx) })
return o.done
@@ -466,6 +555,7 @@ func (o *haObserver) run(ctx context.Context) {
defer stop()
log.Print(haStartCopy)
incomplete := map[string]bool{}
+ unbound := map[string]bool{}
for {
if ctx.Err() != nil {
return
@@ -499,6 +589,7 @@ func (o *haObserver) run(ctx context.Context) {
if ctx.Err() != nil {
return
}
+ unbound = haLogUnboundChanges(obs, unbound)
for _, r := range o.config.universe {
bad := !obs.Regional(r, o.clock.Now()).Complete
if bad && !incomplete[r] {
diff --git a/internal/console/hacapacity_observe_test.go b/internal/console/hacapacity_observe_test.go
index 62011b42f..51fcb6b85 100644
--- a/internal/console/hacapacity_observe_test.go
+++ b/internal/console/hacapacity_observe_test.go
@@ -1,10 +1,12 @@
package console
import (
+ "bytes"
"context"
"encoding/xml"
"fmt"
"io"
+ "log"
"net/http"
"os"
"path/filepath"
@@ -584,3 +586,103 @@ func TestHACapacityUnknownUnsupportedStore(t *testing.T) {
t.Fatal("unsupported store available")
}
}
+
+func TestHACapacityDirectoryIgnoresScratch(t *testing.T) {
+ o, _, _ := haFixture(t)
+ adapter := o.store.(*haCapacityStore)
+ for _, prefix := range []string{edgesFilePrefix, haStatusPrefix} {
+ dir := filepath.Join(adapter.directory, filepath.FromSlash(prefix))
+ if err := os.WriteFile(filepath.Join(dir, "leo.json.tmp"), []byte("partial"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(filepath.Join(dir, ".carlos-write-test"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, ".carlos-write-test", "partial.json"), []byte("partial"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(filepath.Join(dir, "subdirectory"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if obs := haObserve(t, o); obs.Decide("ie", "hapair", haTestNow).Kind != HACapacityAllow {
+ t.Fatalf("scratch poisoned observation: %s %+v", obs.unavailable, obs.Blockers("ie", haTestNow))
+ }
+}
+
+// The runner writes logs from another goroutine.
+type haLogBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (b *haLogBuffer) Write(p []byte) (int, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.Write(p)
+}
+func (b *haLogBuffer) String() string { b.mu.Lock(); defer b.mu.Unlock(); return b.buf.String() }
+
+func TestHACapacityRunnerUnboundTransitions(t *testing.T) {
+ o, store, signer := haFixture(t)
+ // Keep the configured binding immutable while the runner is active.
+ delete(o.config.FixedBoxes, "leo")
+ var logs haLogBuffer
+ prior := log.Writer()
+ log.SetOutput(&logs)
+ t.Cleanup(func() { log.SetOutput(prior) })
+ clock, _, cancel, done := haRunner(t, o, 0, 3)
+ haWait(t, func() bool { return strings.Count(logs.String(), "code=C11") == 1 })
+ next := func(sequence uint64) {
+ clock.advance(time.Minute, true)
+ haWait(t, func() bool {
+ obs := o.current.Load()
+ return obs != nil && o.sequence.Load() >= sequence && obs.started.Equal(clock.Now())
+ })
+ }
+ next(2) // Still unbound.
+ next(3) // Failed LIST does not establish a state change.
+ next(4) // Still unbound after recovery.
+ _, wrong := signer.Record(t, "leo", "999988887777", "eu-west-1", "i-0123456789abcdef0")
+ haPut(t, store, boxid.Key("leo"), wrong)
+ next(5)
+ haWait(t, func() bool { return strings.Count(logs.String(), "code=C11") == 2 })
+ next(6) // Still excluded, but no longer unbound.
+ _, valid := signer.Record(t, "leo", moveTestAccount, "eu-west-1", "i-0123456789abcdef0")
+ haPut(t, store, boxid.Key("leo"), valid)
+ next(7)
+ haWait(t, func() bool { return strings.Count(logs.String(), "code=C11") == 3 })
+ cancel()
+ haAwait(t, done)
+ got := logs.String()
+ if strings.Count(got, "code=C11") != 3 || strings.Count(got, "state=enter") != 2 || strings.Count(got, "state=leave") != 1 || strings.Count(got, haUnboundCopy) != 2 {
+ t.Fatalf("unexpected transitions: %s", got)
+ }
+}
+
+func TestHACapacityS3ScratchKeysRemainUnknown(t *testing.T) {
+ for _, prefix := range []string{edgesFilePrefix, haStatusPrefix} {
+ for _, name := range []string{"leo.json.tmp", "subdirectory/leo.json"} {
+ t.Run(prefix+name, func(t *testing.T) {
+ store := haS3(t, func(r *http.Request) (*http.Response, error) {
+ if r.URL.Query().Get("list-type") != "2" {
+ t.Fatal("unexpected body read")
+ }
+ var objects []haXMLObject
+ if r.URL.Query().Get("prefix") == prefix {
+ at := haTestNow.Format(time.RFC3339)
+ objects = []haXMLObject{{Key: prefix + name, LastModified: &at}}
+ }
+ return haResponse(r, 200, io.NopCloser(strings.NewReader(haListXML(objects, false)))), nil
+ })
+ o := newHAObserver(haConfig(t), newHACapacityStore(store, ""), boxid.Verifier{}, haTestFP)
+ obs := haObserve(t, o)
+ for _, region := range o.config.universe {
+ if d := obs.Decide(region, "hapair", haTestNow); d.Kind != HACapacityUnknown {
+ t.Fatalf("%s: %+v", region, d)
+ }
+ }
+ })
+ }
+ }
+}
diff --git a/internal/console/hacapacity_test.go b/internal/console/hacapacity_test.go
index 611fb8ada..4672cb2e9 100644
--- a/internal/console/hacapacity_test.go
+++ b/internal/console/hacapacity_test.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "encoding/base64"
"encoding/json"
"fmt"
"os"
@@ -284,7 +285,7 @@ func TestHACapacityIdentityAndScopePrecedence(t *testing.T) {
if v.Count != tt.count || v.Complete != tt.complete || d.Kind != tt.kind {
t.Fatalf("regional=%+v decision=%+v blockers=%+v", v, d, obs.Blockers("ie", haTestNow))
}
- if d.MissingNamedPoolsOnly != (tt.name == "missing pools") {
+ if d.MissingNamedPoolsOnly != (tt.name == "missing pools" || tt.name == "null pools") {
t.Fatalf("missing pool discriminator: %+v", d)
}
})
@@ -300,6 +301,7 @@ func TestHACapacityIdentityAndScopeSignedEvidence(t *testing.T) {
}{
{"wrong account", "999988887777", "eu-west-1", "i-0123456789abcdef0", HACapacityCompleteZero},
{"wrong signed region", moveTestAccount, "us-east-1", "i-0123456789abcdef0", HACapacityCompleteZero},
+ {"no instance", moveTestAccount, "eu-west-1", "", HACapacityCompleteZero},
{"copied signed identity", moveTestAccount, "eu-west-1", "i-0123456789abcdef1", HACapacityUnknown},
} {
t.Run(tt.name, func(t *testing.T) {
@@ -311,8 +313,8 @@ func TestHACapacityIdentityAndScopeSignedEvidence(t *testing.T) {
})
}
haPut(t, s, boxid.Key("leo"), []byte(`{"v":1,"box":"leo","identity_document":"bad","identity_signature":"bad"}`))
- if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != HACapacityCompleteZero {
- t.Fatalf("invalid signature: %+v", d)
+ if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown {
+ t.Fatalf("malformed identity: %+v", d)
}
haPut(t, s, boxid.Key("leo"), original)
delete(o.config.FixedBoxes, "leo")
@@ -525,3 +527,114 @@ func TestHACapacityIdentityAndScopeStatusLabelAlias(t *testing.T) {
t.Fatalf("borrowed status under another key: %+v", d)
}
}
+
+func TestHACapacityIdentityMalformedAndVerification(t *testing.T) {
+ o, store, _ := haFixture(t)
+ original, _, err := store.Get(context.Background(), boxid.Key("leo"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ edit := func(field string, value any) []byte {
+ return haEdit(t, original, func(m map[string]any) { m[field] = value })
+ }
+ doc := func(raw string) []byte {
+ return edit("identity_document", base64.StdEncoding.EncodeToString([]byte(raw)))
+ }
+ for _, tt := range []struct {
+ name string
+ raw []byte
+ want HACapacityDecisionKind
+ code string
+ }{
+ {"absent", nil, HACapacityUnknown, "identity_missing"},
+ {"not JSON", []byte("bad"), HACapacityUnknown, "identity_malformed"},
+ {"duplicate keys", []byte(strings.Replace(string(original), `"v":1`, `"v":1,"v":1`, 1)), HACapacityUnknown, "identity_malformed"},
+ {"trailing data", append(append([]byte{}, original...), []byte("{}")...), HACapacityUnknown, "identity_malformed"},
+ {"unknown field", edit("unknown", true), HACapacityUnknown, "identity_malformed"},
+ {"array", []byte("[]"), HACapacityUnknown, "identity_malformed"},
+ {"string", []byte(`"leo"`), HACapacityUnknown, "identity_malformed"},
+ {"null", []byte("null"), HACapacityUnknown, "identity_malformed"},
+ {"unknown version", edit("v", 2), HACapacityUnknown, "identity_version"},
+ {"wrong version type", edit("v", "1"), HACapacityUnknown, "identity_version"},
+ {"wrong field type", edit("box", 42), HACapacityUnknown, "identity_malformed"},
+ {"null field", edit("identity_signature", nil), HACapacityUnknown, "identity_malformed"},
+ {"document not base64", edit("identity_document", "bad"), HACapacityUnknown, "identity_malformed"},
+ {"signature not base64", edit("identity_signature", "bad"), HACapacityUnknown, "identity_malformed"},
+ {"document not JSON", doc("bad"), HACapacityUnknown, "identity_malformed"},
+ {"document array", doc("[]"), HACapacityUnknown, "identity_malformed"},
+ {"document null", doc("null"), HACapacityUnknown, "identity_malformed"},
+ {"document duplicate", doc(`{"region":"eu-west-1","region":"eu-west-1"}`), HACapacityUnknown, "identity_malformed"},
+ {"document trailing", doc(`{}{}`), HACapacityUnknown, "identity_malformed"},
+ {"document wrong type", doc(`{"instanceId":42}`), HACapacityUnknown, "identity_malformed"},
+ {"document null instance", doc(`{"instanceId":null}`), HACapacityUnknown, "identity_malformed"},
+ {"unavailable document certificate", doc(`{"region":"unknown","accountId":"123","instanceId":"i-123"}`), HACapacityUnknown, "identity_unreadable"},
+ {"different reference", edit("box", "sophie"), HACapacityCompleteZero, "identity_invalid"},
+ {"bad signature", edit("identity_signature", base64.StdEncoding.EncodeToString([]byte("bad signature"))), HACapacityCompleteZero, "identity_invalid"},
+ {"valid", original, HACapacityAllow, ""},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ if tt.raw == nil {
+ if err := store.Delete(context.Background(), boxid.Key("leo")); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ haPut(t, store, boxid.Key("leo"), tt.raw)
+ }
+ obs := haObserve(t, o)
+ d := obs.Decide("ie", "hapair", haTestNow)
+ v := obs.Regional("ie", haTestNow)
+ if d.Kind != tt.want || v.Complete != (tt.want != HACapacityUnknown) {
+ t.Fatalf("decision=%+v regional=%+v blockers=%+v", d, v, obs.Blockers("ie", haTestNow))
+ }
+ if tt.code != "" {
+ if b := obs.Blockers("ie", haTestNow); len(b) != 1 || b[0].Code != tt.code {
+ t.Fatalf("blockers=%+v want %s", b, tt.code)
+ }
+ }
+ })
+ }
+}
+
+func TestHACapacityNamedPoolPublication(t *testing.T) {
+ o, store, _ := haFixture(t)
+ for _, tt := range []struct {
+ name string
+ value any
+ missing bool
+ code string
+ }{
+ {"absent", nil, true, "named_pools_missing"},
+ {"null", nil, true, "named_pools_missing"},
+ {"wrong type", "hapair", false, "named_pools_malformed"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ haPut(t, store, edgesFilePrefix+"leo.json", haEdit(t, haGolden(t), func(m map[string]any) {
+ m["named_pools"] = tt.value
+ if tt.name == "absent" {
+ delete(m, "named_pools")
+ }
+ }))
+ obs := haObserve(t, o)
+ if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown || d.MissingNamedPoolsOnly != tt.missing {
+ t.Fatalf("%+v", d)
+ }
+ if b := obs.CreateBlockers("ie", "hapair", haTestNow); len(b) != 1 || b[0].Code != tt.code {
+ t.Fatalf("%+v", b)
+ }
+ })
+ }
+}
+
+func TestHACapacityIdentityVerifierFailureIsUnknown(t *testing.T) {
+ o, _, _ := haFixture(t)
+ cert := *o.verifier.Certs["eu-west-1"]
+ cert.PublicKey = nil
+ o.verifier.Certs["eu-west-1"] = &cert
+ obs := haObserve(t, o)
+ if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown {
+ t.Fatalf("verifier failure became exclusion: %+v", d)
+ }
+ if b := obs.Blockers("ie", haTestNow); len(b) != 1 || b[0].Code != "identity_unreadable" {
+ t.Fatalf("blockers=%+v", b)
+ }
+}