ha: retain verified box incarnations across fixed-ref replacement
Keep historical bindings and observations immutable while resolving the newest verified incarnation. Reload a fixed identity when its independent configured iid changes, and preserve replacement edges during old departure completion. Delay inventory-only recovery pages until the existing backstop plus jitter has elapsed. Add RED/GREEN regressions for rebinding, invalid records, history migration and page timing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/host/hadeparture_identity.go+18 −26internal/host/hadepartures_rebind_test.go+160 −0internal/host/hadepartures_scan.go+1 −1internal/registry/ha_identity_history.go+107 −0internal/registry/ha_identity_history_test.go+89 −0internal/registry/ha_journal.go+6 −32
Intent
<task-notification> <task-id>bipj945sb</task-id> <tool-use-id>toolu_019UyAqdtnCySjixAMX1ZjSK</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/bipj945sb.output</output-file> <status>completed</status> <summary>Background command "Wait for B4 fix round 1" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>ac232706c4174e2eb</task-id> <tool-use-id>toolu_01EtqoXAfRgdYMTGtVaNEH3z</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/ac232706c4174e2eb.output</output-file> <status>completed</status> <summary>Agent "Opus review Task B4" 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>All eight findings are addressed, and the P15 deletion rule holds. One new Important item comes from the ruling itself, not from the implementer, and needs your decision before the 5B drill. Line numbers refer to `internal/host/hadepartures_scan.go` at 3adb8fb6 unless another file is named. I ran no suites. **Verdicts:** - **Critical 1 (replacement edges file deleted): ADDRESSED.** Only `d.EdgesETag` is ever passed to the delete (`:410`, `:451`). A changed object is never deleted (`:426-441`). If the re-read shows the same ETag, the delete is retried without a rescan (`:444-451`). - **Critical 2 (non-strict locks block every departure): ADDRESSED.** `unrelatedDepartureLock` (`:48-74`) is applied at `:177`. `TestDepartureUnrelatedLockCensus` covers 13 modes. - **Important 1 (successor validation on unrelated hosts): ADDRESSED.** Hosts that never matched skip validation (`:187-189`). Hosts that did match are still strictly validated (`:211-228`). - **Important 2 (error paths skip backoff and page): ADDRESSED.** Every exit in ScanPass goes through `retryScan` (`:95-300`). `complete()` sends every error through a deferred `retryScan` (`:342-348`), and `retryScan` uses a detached 5 s context (`:308`). - **Important 3 (weak witnesses): ADDRESSED.** Receivers B and C now have distinct identities and use the real `AdoptionIdentity`. There are new witnesses for legacy and unrelated owners, the duplicate completed event, index-conflict maxima (k ≤ 4) and the 180-receive idle hour. - **Minor 1 (expiry checked after the read): ADDRESSED.** The read start is taken before `ReadLock` (`:164`) and compared at `:251`. - **Minor 2 (permission fault reused C3): ADDRESSED.** It now logs only `ha_departure_permission_fault key=…` (`:317-319`). The alert flag clears only when a phase actually progresses. - **Minor 3 (mutex held across the network Delete): ADDRESSED.** `ackIID` no longer holds the lock during the Delete, and removes the handle only if it is still current (`hadepartures.go:481-505`). **P15 deletion rule:** - Only the exact retained ETag is ever deleted. - A changed object is never deleted. - A changed object counts as a replacement only when a verified `Resolve(ref, "")` shows a different iid for the same ref, account and scope. **New Critical: 0. New Important: 1, a consequence of Ruling P15 rather than an implementer defect.** - The identity cache is keyed by ref and refuses to rebind an enrolled ref, so on a receiver that already enrolled D, `Resolve(ref, "")` keeps returning D's old iid (`:433-436`). - A fixed box recreated under the same ref (e.g. `leo`) therefore leaves the old box's departure open forever on every such receiver. It pages hourly, and D's queue message is redelivered until retention runs out. - Nothing gets deleted, so it is safe. But it is the normal fixed-pair sequence on dev. - Two ways out: - a verified rebinding path for fixed refs (expected iid from config plus a signed record); - an explicit operator step in the 5B card. There are also 3 Minors: - Repeated AccessDenied is logged once an hour. - An `indexed → indexed` save is refused, which is practically unreachable. - Pre-existing: a not-yet-fresh inventory pages C3 on every departure's first pass and on every restart. The full write-up is in `.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/task-B4-review-r2.md`.</result> <usage><subagent_tokens>244367</subagent_tokens><tool_uses>8</tool_uses><duration_ms>122597</duration_ms></usage> </task-notification>
Attributed to this commit: 6.01 g CO₂e (783,629 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p1b3b-duties, 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/host/hadeparture_identity.go b/internal/host/hadeparture_identity.go| index 8d4c1f23b..99c8c3daf 100644 |
| --- a/internal/host/hadeparture_identity.go |
| +++ b/internal/host/hadeparture_identity.go |
| @@ -79,23 +79,7 @@ func (r *departureIdentities) verify(ctx context.Context, ref string, raw []byte |
| if len(raw) > 64*1024 { |
| return registry.HABoxIdentity{}, errDepartureIdentity |
| } |
| - var rec boxid.Record |
| - if json.Unmarshal(raw, &rec) != nil { |
| - return registry.HABoxIdentity{}, errDepartureIdentity |
| - } |
| - doc, err := base64.StdEncoding.DecodeString(rec.IdentityDocument) |
| - if err != nil { |
| - return registry.HABoxIdentity{}, errDepartureIdentity |
| - } |
| - var cloud struct { |
| - Region string `json:"region"` |
| - } |
| - if json.Unmarshal(doc, &cloud) != nil { |
| - return registry.HABoxIdentity{}, errDepartureIdentity |
| - } |
| - // The region selects a certificate. Enroll verifies the signed document |
| - // before any field from it can be used as evidence. |
| - ev, err := r.Verifier.Enroll(raw, boxid.Expect{Box: ref, AWSRegion: cloud.Region}) |
| + ev, err := r.Verifier.Enroll(raw, boxid.Expect{Box: ref, AWSRegion: r.Region}) |
| if err != nil { |
| return registry.HABoxIdentity{}, err |
| } |
| @@ -104,20 +88,28 @@ func (r *departureIdentities) verify(ctx context.Context, ref string, raw []byte |
| return old, err |
| } |
| expected := r.Fixed[ref] |
| - if known { |
| + if expected == "" && known { |
| expected = old.IID |
| - if old.Digest != ev.RecordSHA256 { |
| + } |
| + if strings.HasPrefix(ref, "g-") && len(ref) == 22 { |
| + if ref != groupReferenceOf(ev.Cloud.Account, ev.Cloud.InstanceID) { |
| return old, errDepartureIdentity |
| } |
| - } |
| - if expected == "" && ref == groupReferenceOf(ev.Cloud.Account, ev.Cloud.InstanceID) { |
| expected = ev.Cloud.InstanceID |
| } |
| if expected == "" || expected != ev.Cloud.InstanceID { |
| return old, errDepartureIdentity |
| } |
| + if known && old.Digest != ev.RecordSHA256 { |
| + if old.IID == ev.Cloud.InstanceID { |
| + return old, errDepartureIdentity |
| + } |
| + if _, exists, e := r.Registry.HAIdentity(ctx, "", ev.Cloud.InstanceID); e != nil || exists { |
| + return old, errors.Join(e, errDepartureIdentity) |
| + } |
| + } |
| b := registry.HABoxIdentity{Ref: ref, IID: ev.Cloud.InstanceID, Account: ev.Cloud.Account, Region: ev.Cloud.Region, Digest: ev.RecordSHA256, Raw: raw} |
| - if known { |
| + if known && old.Digest == b.Digest { |
| b.Observation = old.Observation |
| } |
| if err = r.Registry.SaveHAIdentity(ctx, b); err != nil { |
| @@ -145,14 +137,14 @@ func (r *departureIdentities) Resolve(ctx context.Context, ref, iid string) (had |
| return o, true, nil |
| } |
| func (r *departureIdentities) Observe(ctx context.Context, o hadeparture.BoxObservation) (hadeparture.BoxObservation, error) { |
| - if !o.Known || o.PlacementNull || o.Box.Scope.CloudRegion == "" || o.Box.Scope.DataBucket == "" || o.Box.Scope.SecretsKeyFP == "" || !boxid.ValidBox(o.Box.Ref) || o.EdgesKey != "control/edges/"+o.Box.Ref+".json" || o.EdgesETag == "" { |
| + if !o.Known || o.PlacementNull || o.Box.Scope.CloudRegion != r.Region || o.Box.Scope.DataBucket == "" || o.Box.Scope.SecretsKeyFP == "" || !boxid.ValidBox(o.Box.Ref) || o.EdgesKey != "control/edges/"+o.Box.Ref+".json" || o.EdgesETag == "" { |
| return o, errDepartureIdentity |
| } |
| b, ok, err := r.Registry.HAIdentity(ctx, o.Box.Ref, "") |
| if err != nil { |
| return o, err |
| } |
| - if !ok { |
| + if !ok || r.Fixed[o.Box.Ref] != "" && r.Fixed[o.Box.Ref] != b.IID { |
| store, e := r.store(ctx) |
| if e != nil { |
| return o, e |
| @@ -227,12 +219,12 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error) |
| w.Blocked = append(w.Blocked, "ref:"+strings.TrimSuffix(strings.TrimPrefix(key, boxid.Prefix), ".json")) |
| continue |
| } |
| - _, known, e := r.Resolve(ctx, ref, "") |
| + current, known, e := r.Resolve(ctx, ref, "") |
| if e != nil { |
| w.Blocked = append(w.Blocked, "ref:"+strings.TrimSuffix(strings.TrimPrefix(key, boxid.Prefix), ".json")) |
| continue |
| } |
| - if known { |
| + if known && (r.Fixed[ref] == "" || r.Fixed[ref] == current.Box.InstanceID) { |
| continue |
| } |
| gets++ |
diff --git a/internal/host/hadepartures_rebind_test.go b/internal/host/hadepartures_rebind_test.go| new file mode 100644 |
| index 000000000..874c3ddbb |
| --- /dev/null |
| +++ b/internal/host/hadepartures_rebind_test.go |
| @@ -0,0 +1,160 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func TestDepartureSameRefRecreation(t *testing.T) { |
| + for _, mode := range []string{"verified", "unsigned", "forged", "wrong-account", "wrong-region", "unconfigured", "duplicate-iid"} { |
| + t.Run(mode, func(t *testing.T) { |
| + x := newScanRig(t, 1) |
| + signer := boxidtest.NewSigner(t) |
| + repo := &departureIdentities{Registry: x.r, Store: x.store, Verifier: boxid.Verifier{Account: x.d.Box.Account, Certs: signer.Certs()}, Fixed: map[string]string{x.d.Box.Ref: x.d.Box.InstanceID}, Region: x.d.Box.Scope.CloudRegion} |
| + _, oldRaw := signer.Record(t, x.d.Box.Ref, x.d.Box.Account, repo.Region, x.d.Box.InstanceID) |
| + if _, err := x.store.Put(t.Context(), boxid.Key(x.d.Box.Ref), oldRaw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + obs := hadeparture.BoxObservation{Known: true, Box: x.d.Box, EdgesKey: x.d.EdgesKey, EdgesETag: x.d.EdgesETag} |
| + old, err := repo.Observe(t.Context(), obs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x.c.cfg.Identities = repo |
| + x.d.Box = old.Box |
| + db, err := sql.Open("sqlite", x.r.Path()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + body, _ := json.Marshal(x.d) |
| + if _, err = db.Exec(`UPDATE ha_departures SET body=? WHERE id=?`, body, x.d.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.pass(t) |
| + newIID := "i-2123456789abcdef0" |
| + if mode != "unconfigured" { |
| + repo.Fixed[x.d.Box.Ref] = newIID |
| + } |
| + account, region := x.d.Box.Account, repo.Region |
| + if mode == "wrong-account" { |
| + account = "444455556666" |
| + } |
| + if mode == "wrong-region" { |
| + region = "us-east-1" |
| + } |
| + rec, raw := signer.Record(t, x.d.Box.Ref, account, region, newIID) |
| + if mode == "unsigned" { |
| + rec.IdentitySignature = "" |
| + raw, _ = json.Marshal(rec) |
| + } |
| + if mode == "forged" { |
| + _, raw = boxidtest.NewSigner(t).Record(t, x.d.Box.Ref, account, region, newIID) |
| + } |
| + if mode == "duplicate-iid" { |
| + repo.Fixed["other"] = newIID |
| + _, other := signer.Record(t, "other", account, region, newIID) |
| + if _, err = repo.verify(t.Context(), "other", other); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + _, oldTag, err := x.store.Get(t.Context(), boxid.Key(x.d.Box.Ref)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = x.store.Put(t.Context(), boxid.Key(x.d.Box.Ref), raw, oldTag); err != nil { |
| + t.Fatal(err) |
| + } |
| + edgeRaw, _ := json.Marshal(edgesfile.PlacementView{V: 1, Box: x.d.Box.Ref, BoxID: x.d.Box.Ref, Region: repo.Region, DataBucket: x.d.Box.Scope.DataBucket, SecretsKeyFP: x.d.Box.Scope.SecretsKeyFP}) |
| + tag, err := x.store.Put(t.Context(), x.d.EdgesKey, edgeRaw, x.d.EdgesETag) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + obs.EdgesETag = tag |
| + got, observeErr := repo.Observe(t.Context(), obs) |
| + if mode == "verified" { |
| + if observeErr != nil || got.Box.InstanceID != newIID { |
| + t.Fatalf("replacement did not rebind: iid=%s err=%v", got.Box.InstanceID, observeErr) |
| + } |
| + proof, err := repo.Proof(t.Context(), old.Box.Ref, old.Box.InstanceID) |
| + if err != nil || proof.Evidence().RecordSHA256 != old.Box.RecordSHA256 { |
| + t.Fatalf("old proof lost: %+v %v", proof, err) |
| + } |
| + } else if mode != "unconfigured" && observeErr == nil { |
| + t.Fatalf("%s replacement accepted: %+v", mode, got) |
| + } |
| + retained, ok, err := repo.Resolve(t.Context(), old.Box.Ref, old.Box.InstanceID) |
| + if err != nil || !ok || retained.Box != old.Box || mode == "verified" && retained != old { |
| + t.Fatalf("old incarnation changed: %+v %v", retained, err) |
| + } |
| + latest, ok, err := repo.Resolve(t.Context(), old.Box.Ref, "") |
| + want := old.Box.InstanceID |
| + if mode == "verified" { |
| + want = newIID |
| + } |
| + if err != nil || !ok || latest.Box.InstanceID != want { |
| + t.Fatalf("latest=%+v err=%v", latest, err) |
| + } |
| + // First completion loses the retained-revision race; the retry resolves the replacement. |
| + _, _ = x.c.ScanPass(t.Context()) |
| + x.now = x.now.Add(301 * time.Second) |
| + _, _ = x.c.ScanPass(t.Context()) |
| + d, err := x.r.Departure(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if (d.Phase == "complete") != (mode == "verified") { |
| + t.Fatalf("phase=%s mode=%s", d.Phase, mode) |
| + } |
| + if _, current, err := x.store.Get(t.Context(), x.d.EdgesKey); err != nil || current != tag { |
| + t.Fatalf("replacement edges deleted: %s %v", current, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureInventoryWaitPageBound(t *testing.T) { |
| + x := newScanRig(t, 1) |
| + start := x.now |
| + if err := x.r.ReobserveDeparture(t.Context(), x.d.ID, start); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.inv.Complete = false |
| + pages, notices := 0, 0 |
| + x.c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { pages++; return nil } |
| + x.c.cfg.Logf = func(format string, _ ...any) { |
| + if strings.HasPrefix(format, "Duties from box") { |
| + notices++ |
| + } |
| + } |
| + for _, step := range []struct { |
| + age time.Duration |
| + want int |
| + }{{0, 0}, {30 * time.Minute, 0}, {33 * time.Minute, 0}, {38 * time.Minute, 1}, {65 * time.Minute, 1}, {98 * time.Minute, 2}} { |
| + x.now = start.Add(step.age) |
| + if _, err := x.c.ScanPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + d, err := x.r.Departure(t.Context(), x.d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if pages != step.want || notices != step.want || (step.want == 0 && !d.LastPage.IsZero()) { |
| + t.Fatalf("age=%s pages=%d notices=%d last_page=%s, want=%d", step.age, pages, notices, d.LastPage, step.want) |
| + } |
| + if x.locks.reads != 0 || x.imports != 0 || d.Phase == "complete" { |
| + t.Fatal("stale inventory made progress") |
| + } |
| + } |
| +} |
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go| index 77606a9b1..efc629aca 100644 |
| --- a/internal/host/hadepartures_scan.go |
| +++ b/internal/host/hadepartures_scan.go |
| @@ -130,7 +130,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| d.Phase = "scanning" |
| } |
| if !inv.FreshAfter(d.ObservedAt) { |
| - return false, c.retryScan(ctx, d, nil, "inventory", true) |
| + return false, c.retryScan(ctx, d, nil, "inventory", c.now().Sub(d.ObservedAt) > release.ChangeIndexBackstop+release.ChangeIndexBackstop/10) |
| } |
| if c.cfg.NewReader == nil || c.cfg.Prefix == nil { |
| return false, c.retryScan(ctx, d, nil, "reader", true) |
diff --git a/internal/registry/ha_identity_history.go b/internal/registry/ha_identity_history.go| new file mode 100644 |
| index 000000000..156ac63e1 |
| --- /dev/null |
| +++ b/internal/registry/ha_identity_history.go |
| @@ -0,0 +1,107 @@ |
| +package registry |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| +) |
| + |
| +func (r *Registry) migrateHAIdentityHistory() error { |
| + var count int |
| + if err := r.sql.QueryRow(`SELECT count(*) FROM pragma_table_info('ha_box_identities') WHERE name='digest'`).Scan(&count); err != nil { |
| + return err |
| + } |
| + if count != 0 { |
| + return nil |
| + } |
| + tx, err := r.beginClaimTransaction(context.Background(), true) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if err = tx.QueryRowContext(context.Background(), `SELECT count(*) FROM pragma_table_info('ha_box_identities') WHERE name='digest'`).Scan(&count); err != nil { |
| + return err |
| + } |
| + if count != 0 { |
| + return tx.Commit() |
| + } |
| + _, err = tx.ExecContext(context.Background(), ` |
| + CREATE TABLE ha_box_identity_history(ref TEXT NOT NULL,digest TEXT NOT NULL,iid TEXT NOT NULL UNIQUE,body BLOB NOT NULL,observation BLOB NOT NULL,PRIMARY KEY(ref,digest)); |
| + INSERT INTO ha_box_identity_history(ref,digest,iid,body,observation) SELECT ref,json_extract(body,'$.Digest'),iid,body,COALESCE(json_extract(body,'$.Observation'),'{}') FROM ha_box_identities; |
| + DROP TABLE ha_box_identities; |
| + ALTER TABLE ha_box_identity_history RENAME TO ha_box_identities; |
| + `) |
| + if err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +func (r *Registry) saveHAIdentity(ctx context.Context, b HABoxIdentity) error { |
| + if b.Ref == "" || b.IID == "" || b.Account == "" || b.Region == "" || len(b.Raw) > 64*1024 || len(b.Raw) == 0 || b.Digest != fmt.Sprintf("%x", sha256.Sum256(b.Raw)) { |
| + return ErrHAJournal |
| + } |
| + body, err := json.Marshal(b) |
| + if err != nil { |
| + return err |
| + } |
| + observation, err := json.Marshal(b.Observation) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := r.beginClaimTransaction(ctx, true) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var oldBody []byte |
| + err = tx.QueryRowContext(ctx, `SELECT body FROM ha_box_identities WHERE ref=? AND digest=?`, b.Ref, b.Digest).Scan(&oldBody) |
| + if err == nil { |
| + var old HABoxIdentity |
| + if err = json.Unmarshal(oldBody, &old); err != nil { |
| + return err |
| + } |
| + if old.Ref != b.Ref || old.IID != b.IID || old.Account != b.Account || old.Region != b.Region || old.Digest != b.Digest || !bytes.Equal(old.Raw, b.Raw) { |
| + return ErrHAJournal |
| + } |
| + // Only the current incarnation's observation can advance. Binding bytes never change. |
| + _, err = tx.ExecContext(ctx, `UPDATE ha_box_identities SET observation=? WHERE ref=? AND digest=? AND rowid=(SELECT max(rowid) FROM ha_box_identities WHERE ref=?)`, observation, b.Ref, b.Digest, b.Ref) |
| + } else if errors.Is(err, sql.ErrNoRows) { |
| + var account, region string |
| + err = tx.QueryRowContext(ctx, `SELECT json_extract(body,'$.Account'),json_extract(body,'$.Region') FROM ha_box_identities WHERE ref=? ORDER BY rowid DESC LIMIT 1`, b.Ref).Scan(&account, ®ion) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + if err == nil && (account != b.Account || region != b.Region) { |
| + return ErrHAJournal |
| + } |
| + _, err = tx.ExecContext(ctx, `INSERT INTO ha_box_identities(ref,digest,iid,body,observation) VALUES(?,?,?,?,?)`, b.Ref, b.Digest, b.IID, body, observation) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +func (r *Registry) loadHAIdentity(ctx context.Context, ref, iid string) (b HABoxIdentity, found bool, err error) { |
| + if ref == "" && iid == "" { |
| + return b, false, nil |
| + } |
| + var body, observation []byte |
| + err = r.sql.QueryRowContext(ctx, `SELECT body,observation FROM ha_box_identities WHERE (?='' OR ref=?) AND (?='' OR iid=?) ORDER BY rowid DESC LIMIT 1`, ref, ref, iid, iid).Scan(&body, &observation) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return b, false, nil |
| + } |
| + if err != nil { |
| + return b, false, err |
| + } |
| + if err = json.Unmarshal(body, &b); err != nil { |
| + return b, false, err |
| + } |
| + err = json.Unmarshal(observation, &b.Observation) |
| + return b, err == nil, err |
| +} |
diff --git a/internal/registry/ha_identity_history_test.go b/internal/registry/ha_identity_history_test.go| new file mode 100644 |
| index 000000000..4f5227685 |
| --- /dev/null |
| +++ b/internal/registry/ha_identity_history_test.go |
| @@ -0,0 +1,89 @@ |
| +package registry |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/json" |
| + "fmt" |
| + "reflect" |
| + "testing" |
| +) |
| + |
| +func TestDepartureIdentityIncarnations(t *testing.T) { |
| + for _, remote := range []bool{false, true} { |
| + t.Run(fmt.Sprint(remote), func(t *testing.T) { |
| + var r *Registry |
| + if remote { |
| + r, _ = remoteTestRegistry(t) |
| + } else { |
| + r, _ = adoptRegistry(t) |
| + } |
| + first := HABoxIdentity{Ref: "box", IID: "i-12345678", Account: "111122223333", Region: "eu-west-1", Raw: []byte("first")} |
| + first.Digest = fmt.Sprintf("%x", sha256.Sum256(first.Raw)) |
| + first.Observation.EdgesETag = "old" |
| + second := first |
| + second.Raw = []byte("second") |
| + second.IID = "i-87654321" |
| + second.Digest = fmt.Sprintf("%x", sha256.Sum256(second.Raw)) |
| + second.Observation.EdgesETag = "new" |
| + for _, b := range []HABoxIdentity{first, second} { |
| + if err := r.SaveHAIdentity(t.Context(), b); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Delayed observations cannot change historical evidence or make it latest. |
| + stale := first |
| + stale.Observation.EdgesETag = "stale" |
| + _ = r.SaveHAIdentity(t.Context(), stale) |
| + for _, q := range []struct { |
| + ref, iid string |
| + want HABoxIdentity |
| + }{{"box", "", second}, {"box", first.IID, first}, {"", first.IID, first}, {"box", second.IID, second}} { |
| + got, ok, err := r.HAIdentity(t.Context(), q.ref, q.iid) |
| + if err != nil || !ok || !reflect.DeepEqual(got, q.want) { |
| + t.Fatalf("query %s/%s: %+v %v", q.ref, q.iid, got, err) |
| + } |
| + } |
| + for _, bad := range []HABoxIdentity{func() HABoxIdentity { b := first; b.Ref = "alias"; return b }(), func() HABoxIdentity { b := first; b.IID = "i-99999999"; return b }(), func() HABoxIdentity { b := first; b.Account = "999999999999"; return b }(), func() HABoxIdentity { |
| + b := first |
| + b.Raw = []byte("changed") |
| + b.Digest = fmt.Sprintf("%x", sha256.Sum256(b.Raw)) |
| + return b |
| + }()} { |
| + if err := r.SaveHAIdentity(t.Context(), bad); err == nil { |
| + t.Fatalf("mutated binding accepted: %+v", bad) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureIdentityMigration(t *testing.T) { |
| + r, path := adoptRegistry(t) |
| + b := HABoxIdentity{Ref: "fixed", IID: "i-12345678", Account: "111122223333", Region: "eu-west-1", Raw: []byte("legacy")} |
| + b.Digest = fmt.Sprintf("%x", sha256.Sum256(b.Raw)) |
| + b.Observation.EdgesETag = "retained" |
| + body, _ := json.Marshal(b) |
| + if _, err := r.sql.Exec(`DROP TABLE ha_box_identities; CREATE TABLE ha_box_identities(ref TEXT PRIMARY KEY,iid TEXT NOT NULL UNIQUE,body BLOB NOT NULL); INSERT INTO ha_box_identities(ref,iid,body) VALUES(?,?,?)`, b.Ref, b.IID, body); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.Close() |
| + for range 2 { |
| + var err error |
| + r, err = Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, ok, err := r.HAIdentity(t.Context(), b.Ref, b.IID) |
| + if err != nil || !ok || !reflect.DeepEqual(got, b) { |
| + t.Fatalf("migration changed evidence: %+v %v", got, err) |
| + } |
| + replacement := b |
| + replacement.IID = "i-87654321" |
| + replacement.Raw = []byte("replacement") |
| + replacement.Digest = fmt.Sprintf("%x", sha256.Sum256(replacement.Raw)) |
| + if err = r.SaveHAIdentity(t.Context(), replacement); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.Close() |
| + } |
| +} |
diff --git a/internal/registry/ha_journal.go b/internal/registry/ha_journal.go| index 6511ede2c..1629c600a 100644 |
| --- a/internal/registry/ha_journal.go |
| +++ b/internal/registry/ha_journal.go |
| @@ -79,7 +79,10 @@ func (r *Registry) migrateHAJournal() error { |
| CREATE TABLE IF NOT EXISTS ha_identity_pages(id INTEGER PRIMARY KEY CHECK(id=1),last_page INTEGER NOT NULL); |
| CREATE TABLE IF NOT EXISTS ha_identity_walk(id INTEGER PRIMARY KEY CHECK(id=1),body BLOB NOT NULL); |
| `) |
| - return err |
| + if err != nil { |
| + return err |
| + } |
| + return r.migrateHAIdentityHistory() |
| } |
| func journalTime(t time.Time) int64 { |
| if t.IsZero() { |
| @@ -458,38 +461,9 @@ func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJou |
| } |
| err = tx.Commit() |
| case "identity_save": |
| - b := q.Identity |
| - if b.Ref == "" || b.IID == "" || b.Account == "" || b.Region == "" || len(b.Raw) > 64*1024 || len(b.Raw) == 0 || b.Digest != fmt.Sprintf("%x", sha256.Sum256(b.Raw)) { |
| - return out, ErrHAJournal |
| - } |
| - body, e := json.Marshal(b) |
| - if e != nil { |
| - return out, e |
| - } |
| - res, e := r.sql.ExecContext(ctx, `INSERT INTO ha_box_identities(ref,iid,body) VALUES(?,?,?) ON CONFLICT(ref) DO UPDATE SET body=excluded.body WHERE iid=excluded.iid AND json_extract(body,'$.Digest')=json_extract(excluded.body,'$.Digest')`, b.Ref, b.IID, body) |
| - if e != nil { |
| - return out, e |
| - } |
| - n, e := res.RowsAffected() |
| - if e != nil { |
| - return out, e |
| - } |
| - if n != 1 { |
| - return out, ErrHAJournal |
| - } |
| + err = r.saveHAIdentity(ctx, q.Identity) |
| case "identity": |
| - var body []byte |
| - err = r.sql.QueryRowContext(ctx, `SELECT body FROM ha_box_identities WHERE (?<>'' AND ref=?) OR (?<>'' AND iid=?)`, q.ID, q.ID, q.Key, q.Key).Scan(&body) |
| - if errors.Is(err, sql.ErrNoRows) { |
| - return out, nil |
| - } |
| - if err == nil { |
| - err = json.Unmarshal(body, &out.Identity) |
| - out.Found = err == nil |
| - } |
| - if out.Found && ((q.ID != "" && q.ID != out.Identity.Ref) || (q.Key != "" && q.Key != out.Identity.IID)) { |
| - return haJournalResponse{}, ErrHAJournal |
| - } |
| + out.Identity, out.Found, err = r.loadHAIdentity(ctx, q.ID, q.Key) |
| case "walk_save": |
| if len(q.Walk.Keys) > 1000 || q.Walk.Offset < 0 || q.Walk.Offset > len(q.Walk.Keys) { |
| return out, ErrHAJournal |