ha: persist immutable termination proofs for bound HA acquires
Verify immutable box identity before deriving the data-bucket proof key. Persist only Describe-confirmed termination, retain its observation time across retries, and share coalesced positive and negative proof caches. Bind proof authority to every classified acquire owner and the current host lifetime. Route visitor, due and finalizer acquires through the optional shared adapter.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+1,032
−5
internal/activator/backend_exec.go+3 −0internal/activator/haadopt.go+1 −0internal/activator/hawake.go+1 −0internal/activator/termination_proof_test.go+63 −0internal/lease/ha.go+2 −1internal/lease/termination_proof.go+70 −0internal/lease/termination_proof_test.go+233 −0internal/termfence/confirm.go+17 −4internal/termfence/termination_proof.go+346 −0internal/termfence/termination_proof_test.go+296 −0
Intent
Attributed to this commit: 4.62 g CO₂e (599,862 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/activator/backend_exec.go b/internal/activator/backend_exec.go| index 19c8dfe4e..ce1e75d45 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -388,6 +388,9 @@ type ExecBackend struct { |
| // HA host whose lease expired to a surviving box (hatakeover.go). Nil: |
| // no takeover, and another box's expired HA lock is always refused. |
| OwnerTerminated func(ctx context.Context, iid string) (bool, error) |
| + // TerminationProofs replaces live-only takeover when the departure controller |
| + // installs its verified identity resolver and shared durable proof cache. |
| + TerminationProofs *lease.TerminationProofAdapter |
| // takeover is the takeover proof's log throttle (hatakeover.go). |
| takeover takeoverState |
| // sameBox is the same-box recovery's state (hasamebox.go): the hosts |
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go| index d4eacfc29..20ce3680e 100644 |
| --- a/internal/activator/haadopt.go |
| +++ b/internal/activator/haadopt.go |
| @@ -290,6 +290,7 @@ func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption |
| if err = phase("acquiring", expected, nil); err != nil { |
| return Deferred, err |
| } |
| + ctx = lease.WithTerminationProof(ctx, b.TerminationProofs) |
| ctx = context.WithValue(ctx, adoptionCauseKey{}, true) |
| held, err := lease.AcquireHAForDuty(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region, hafresh.Marker{Box: self.Ref, IID: self.IID, Lifetime: req.Lifetime}, hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}, func(v hafresh.View) error { |
| if v.ETag != view.ETag || v.Lock.Generation != view.Lock.Generation { |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index dbf2b733e..8a781cbd9 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -342,6 +342,7 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route) |
| } |
| } |
| + ctx = lease.WithTerminationProof(ctx, b.TerminationProofs) |
| proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)} |
| var held *lease.Held |
| if duty, ok := ctx.Value(dutyContextKey{}).(dutyRestriction); ok { |
diff --git a/internal/activator/termination_proof_test.go b/internal/activator/termination_proof_test.go| new file mode 100644 |
| index 000000000..09172fd05 |
| --- /dev/null |
| +++ b/internal/activator/termination_proof_test.go |
| @@ -0,0 +1,63 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +func TestTerminationProofWiring(t *testing.T) { |
| + for _, mode := range []string{"visitor", "due", "finalizer"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, req := haAdoptionFixture(t) |
| + s.b.Cfg.Region = "eu-west-1" |
| + ctx := context.Background() |
| + body, _ := json.Marshal(hafresh.Lock{Generation: 5, Owner: heldByB, ExpiresAt: time.Now().Add(-time.Hour)}) |
| + putLockFor(t, s.b, s.rt, body) |
| + var err error |
| + req.Observed, err = lease.ReadLock(ctx, s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fallbacks, resolves := 0, 0 |
| + s.b.OwnerTerminated = func(context.Context, string) (bool, error) { fallbacks++; return true, nil } |
| + s.b.TerminationProofs = &lease.TerminationProofAdapter{Cache: &termfence.ProofCache{}, Resolve: func(context.Context, string, string) (termfence.ProofIdentity, error) { |
| + resolves++ |
| + return termfence.ProofIdentity{}, errors.New("unverified") |
| + }, Lifetime: func(context.Context, string, string, string) (string, error) { return req.Lifetime, nil }} |
| + before := len(s.fx.Requests()) |
| + if mode == "finalizer" { |
| + got, err := s.a.AdoptHost(ctx, s.rt, req) |
| + if got != Deferred || err == nil { |
| + t.Fatalf("finalizer=%v %v", got, err) |
| + } |
| + } else { |
| + if mode == "due" { |
| + ctx = context.WithValue(ctx, dutyContextKey{}, dutyRestriction{allow: func(hafresh.View) error { return nil }}) |
| + } |
| + held, err := s.b.Acquire(ctx, s.rt) |
| + if held != nil { |
| + _ = held.Release(ctx) |
| + } |
| + if err == nil { |
| + t.Fatal("unverified identity granted acquire") |
| + } |
| + } |
| + if fallbacks != 0 || resolves != 1 { |
| + t.Fatalf("fallbacks=%d resolves=%d", fallbacks, resolves) |
| + } |
| + for _, r := range s.fx.Requests()[before:] { |
| + if strings.HasPrefix(r, "PUT ") { |
| + t.Fatal("refusal wrote", r) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/lease/ha.go b/internal/lease/ha.go| index f5b4ed9e1..37660360b 100644 |
| --- a/internal/lease/ha.go |
| +++ b/internal/lease/ha.go |
| @@ -109,7 +109,8 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas |
| return err |
| } |
| } |
| - d := hafresh.DecideAcquire(v, me, time.Now(), p) |
| + proofs := bindTerminationProof(ctx, client, bucket, loc, region, base, me, v, p) |
| + d := hafresh.DecideAcquire(v, me, time.Now(), proofs) |
| won = d |
| switch d.Action { |
| case hafresh.ActCreate: |
diff --git a/internal/lease/termination_proof.go b/internal/lease/termination_proof.go| new file mode 100644 |
| index 000000000..9424407d4 |
| --- /dev/null |
| +++ b/internal/lease/termination_proof.go |
| @@ -0,0 +1,70 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +// TerminationProofAdapter is shared by visitor, due and finalizer acquires. |
| +// Resolve uses verified immutable box records; Lifetime reads the authoritative |
| +// host lifetime for this bucket/prefix. Neither callback can grant a take. |
| +type TerminationProofAdapter struct { |
| + Cache *termfence.ProofCache |
| + Confirmer *termfence.Confirmer |
| + Resolve func(context.Context, string, string) (termfence.ProofIdentity, error) |
| + Lifetime func(context.Context, string, string, string) (string, error) |
| +} |
| +type terminationProofKey struct{} |
| + |
| +func WithTerminationProof(ctx context.Context, p *TerminationProofAdapter) context.Context { |
| + if p == nil { |
| + return ctx |
| + } |
| + return context.WithValue(ctx, terminationProofKey{}, p) |
| +} |
| +func bindTerminationProof(ctx context.Context, client *s3.Client, bucket, prefix, region string, base hafresh.Marker, self hafresh.Self, v hafresh.View, p hafresh.Proofs) hafresh.Proofs { |
| + adapter, enabled := ctx.Value(terminationProofKey{}).(*TerminationProofAdapter) |
| + if !enabled { |
| + return p |
| + } |
| + // The closure belongs to this classification round. DecideAcquire invokes it |
| + // only for an expired foreign owner. A CAS retry gets a fresh closure. |
| + p.OwnerTerminated = func(iid string) (bool, error) { |
| + owner, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + if !ok || !owner.HA || owner.IID != iid || iid == self.IID || v.Absent || v.Lock.Release != nil || base.Lifetime == "" || region != self.Region || adapter == nil || adapter.Cache == nil || adapter.Resolve == nil || adapter.Lifetime == nil { |
| + return false, termfence.ErrTerminationProof |
| + } |
| + lifetime, err := adapter.Lifetime(ctx, bucket, prefix, region) |
| + if err != nil { |
| + return false, err |
| + } |
| + if lifetime != base.Lifetime { |
| + return false, termfence.ErrTerminationProof |
| + } |
| + binding, err := adapter.Resolve(ctx, owner.Ref, iid) |
| + if err != nil { |
| + return false, err |
| + } |
| + e := binding.Evidence() |
| + if e.Box != owner.Ref || e.Cloud.InstanceID != iid || e.Cloud.Account != self.Account || e.Cloud.Region != region || binding.Bucket() != bucket { |
| + return false, termfence.ErrTerminationProof |
| + } |
| + _, found, readErr := adapter.Cache.Load(ctx, termfence.NewProofStore(client), binding) |
| + if found && readErr == nil { |
| + return true, nil |
| + } |
| + if adapter.Confirmer == nil { |
| + return false, readErr |
| + } |
| + _, err = adapter.Confirmer.PersistTermination(ctx, termfence.NewProofStore(client), binding, self.Ref, adapter.Cache) |
| + if err != nil { |
| + return false, errors.Join(readErr, err) |
| + } |
| + return true, nil |
| + } |
| + return p |
| +} |
diff --git a/internal/lease/termination_proof_test.go b/internal/lease/termination_proof_test.go| new file mode 100644 |
| index 000000000..9c0ac5584 |
| --- /dev/null |
| +++ b/internal/lease/termination_proof_test.go |
| @@ -0,0 +1,233 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/ec2" |
| + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +type proofEC2 struct { |
| + calls int |
| + running bool |
| +} |
| + |
| +func (p *proofEC2) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, opts ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) { |
| + p.calls++ |
| + state := ec2types.InstanceStateNameTerminated |
| + if p.running { |
| + state = ec2types.InstanceStateNameRunning |
| + } |
| + return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{OwnerId: aws.String("111122223333"), Instances: []ec2types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: &ec2types.InstanceState{Name: state}}}}}}, nil |
| +} |
| +func TestTerminationProofAcquireOnly(t *testing.T) { |
| + for _, mode := range []string{"expired", "unexpired", "equality", "same box", "malformed", "wrong lifetime", "owner CAS", "bucket", "region", "restart"} { |
| + t.Run(mode, func(t *testing.T) { |
| + ResetForTest() |
| + t.Cleanup(ResetForTest) |
| + fx := locktest.NewLockFixture(t) |
| + me := hafresh.Self{Ref: "survivor", IID: "i-0123456789abcdef0", Account: "111122223333", Region: "eu-west-1"} |
| + SetSelf(me) |
| + if err := SetObligationDir(t.TempDir()); err != nil { |
| + t.Fatal(err) |
| + } |
| + signer := boxidtest.NewSigner(t) |
| + _, raw := signer.Record(t, "departed", me.Account, me.Region, "i-1123456789abcdef0") |
| + bucket, region := fx.Bucket, me.Region |
| + if mode == "bucket" { |
| + bucket = "deployment-bucket" |
| + } |
| + if mode == "region" { |
| + region = "us-east-1" |
| + } |
| + binding, err := termfence.VerifyProofIdentity(boxid.Verifier{Account: me.Account, Certs: signer.Certs()}, raw, boxid.Expect{Box: "departed", AWSRegion: me.Region, TofuInstanceID: "i-1123456789abcdef0"}, bucket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + api := &proofEC2{} |
| + confirm := &termfence.Confirmer{Self: func() boxid.Cloud { |
| + return boxid.Cloud{Provider: "aws", Account: me.Account, Region: me.Region, InstanceID: me.IID} |
| + }, API: func(context.Context, string) (termfence.EC2, error) { return api, nil }, Logf: func(string, ...any) {}} |
| + adapter := &TerminationProofAdapter{Cache: &termfence.ProofCache{}, Confirmer: confirm, Resolve: func(ctx context.Context, ref, iid string) (termfence.ProofIdentity, error) { |
| + if ref != "departed" || iid != "i-1123456789abcdef0" { |
| + return termfence.ProofIdentity{}, errors.New("unbound") |
| + } |
| + return binding, nil |
| + }, Lifetime: func(context.Context, string, string, string) (string, error) { |
| + if mode == "wrong lifetime" { |
| + return "new-life", nil |
| + } |
| + return "life", nil |
| + }} |
| + client, _, err := newLeaserClient(context.Background(), me.Region) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if mode == "restart" { |
| + if _, err = confirm.PersistTermination(context.Background(), client, binding, me.Ref, &termfence.ProofCache{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + adapter.Confirmer = nil |
| + } |
| + at := time.Now() |
| + owner := hafresh.OwnerFor(hafresh.Self{Ref: "departed", IID: "i-1123456789abcdef0"}, 1, true) |
| + expiry := at.Add(-time.Hour) |
| + if mode == "unexpired" { |
| + expiry = at.Add(time.Hour) |
| + } |
| + if mode == "equality" { |
| + expiry = at |
| + } |
| + if mode == "same box" { |
| + owner = hafresh.OwnerFor(me, 1, true) |
| + } |
| + if mode == "malformed" { |
| + owner = "broken" |
| + } |
| + body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: owner, ExpiresAt: expiry}) |
| + fx.PutLock("instances/shop", body) |
| + fallback := 0 |
| + p := hafresh.Proofs{OwnerTerminated: func(string) (bool, error) { fallback++; return true, nil }} |
| + ctx := WithTerminationProof(context.Background(), adapter) |
| + if mode == "equality" { |
| + v, err := readView(ctx, client, fx.Bucket, "instances/shop/lock.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bound := bindTerminationProof(ctx, client, fx.Bucket, "instances/shop", region, hafresh.Marker{Lifetime: "life"}, me, v, p) |
| + if d := hafresh.DecideAcquire(v, me, at, bound); d.Action != hafresh.ActHeld { |
| + t.Fatal(d) |
| + } |
| + } else { |
| + if mode == "owner CAS" { |
| + fx.BeforeWrite(func(method, key string) { |
| + if method == "PUT" && key == "instances/shop/lock.json" { |
| + next, _ := json.Marshal(hafresh.Lock{Generation: 2, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "other", IID: "i-2123456789abcdef0"}, 1, true), ExpiresAt: expiry}) |
| + fx.PutLock("instances/shop", next) |
| + } |
| + }) |
| + } |
| + held, err := AcquireHA(ctx, fx.Bucket, "instances/shop", region, hafresh.Marker{Lifetime: "life"}, p) |
| + want := mode == "expired" || mode == "restart" |
| + if (err == nil) != want { |
| + t.Fatalf("err=%v want=%t requests=%v", err, want, fx.Requests()) |
| + } |
| + if held != nil { |
| + _ = held.Release(context.Background()) |
| + } |
| + } |
| + if fallback != 0 { |
| + t.Fatal("live callback bypassed proof") |
| + } |
| + wantDescribe := 0 |
| + if mode == "expired" || mode == "owner CAS" || mode == "restart" { |
| + wantDescribe = 1 |
| + } |
| + if api.calls != wantDescribe { |
| + t.Fatalf("describes %d want %d", api.calls, wantDescribe) |
| + } |
| + if mode == "unexpired" || mode == "equality" || mode == "same box" || mode == "malformed" || mode == "wrong lifetime" || mode == "bucket" || mode == "region" { |
| + for _, r := range fx.Requests() { |
| + if strings.Contains(r, "terminations/") { |
| + t.Fatal("proof consulted on refused/non-peer lock", r) |
| + } |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestTerminationProofRequestBudget(t *testing.T) { |
| + ResetForTest() |
| + t.Cleanup(ResetForTest) |
| + fx := locktest.NewLockFixture(t) |
| + me := hafresh.Self{Ref: "survivor", IID: "i-0123456789abcdef0", Account: "111122223333", Region: "eu-west-1"} |
| + SetSelf(me) |
| + if err := SetObligationDir(t.TempDir()); err != nil { |
| + t.Fatal(err) |
| + } |
| + signer := boxidtest.NewSigner(t) |
| + _, raw := signer.Record(t, "departed", me.Account, me.Region, "i-1123456789abcdef0") |
| + binding, err := termfence.VerifyProofIdentity(boxid.Verifier{Account: me.Account, Certs: signer.Certs()}, raw, boxid.Expect{Box: "departed", AWSRegion: me.Region, TofuInstanceID: "i-1123456789abcdef0"}, fx.Bucket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var seconds atomic.Int64 |
| + now := func() time.Time { return time.Unix(1793700000+seconds.Load(), 0) } |
| + api := &proofEC2{running: true} |
| + self := func() boxid.Cloud { |
| + return boxid.Cloud{Provider: "aws", Account: me.Account, Region: me.Region, InstanceID: me.IID} |
| + } |
| + confirmer := &termfence.Confirmer{Self: self, Now: now, API: func(context.Context, string) (termfence.EC2, error) { return api, nil }, Logf: func(string, ...any) {}} |
| + adapter := &TerminationProofAdapter{Cache: &termfence.ProofCache{Now: now}, Confirmer: confirmer, Resolve: func(context.Context, string, string) (termfence.ProofIdentity, error) { return binding, nil }, Lifetime: func(context.Context, string, string, string) (string, error) { return "life", nil }} |
| + ctx := WithTerminationProof(context.Background(), adapter) |
| + for i := 0; i < 20; i++ { |
| + body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "departed", IID: binding.Evidence().Cloud.InstanceID}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)}) |
| + fx.PutLock(fmt.Sprintf("instances/shop-%d", i), body) |
| + } |
| + var wg sync.WaitGroup |
| + for i := 0; i < 20; i++ { |
| + wg.Go(func() { |
| + held, err := AcquireHA(ctx, fx.Bucket, fmt.Sprintf("instances/shop-%d", i), me.Region, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{}) |
| + if held != nil { |
| + _ = held.Release(context.Background()) |
| + } |
| + if err == nil { |
| + t.Error("hung peer acquired") |
| + } |
| + }) |
| + } |
| + wg.Wait() |
| + proofGets := func() int { |
| + n := 0 |
| + for _, r := range fx.Requests() { |
| + if r == "GET "+binding.Key() { |
| + n++ |
| + } |
| + } |
| + return n |
| + } |
| + if proofGets() != 1 || api.calls != 1 { |
| + t.Fatalf("GET=%d Describe=%d", proofGets(), api.calls) |
| + } |
| + for _, r := range fx.Requests() { |
| + if strings.HasPrefix(r, "PUT ") { |
| + t.Fatal("hung peer wrote", r) |
| + } |
| + } |
| + other := &termfence.Confirmer{Self: self, Now: now, API: func(context.Context, string) (termfence.EC2, error) { return &proofEC2{}, nil }, Logf: func(string, ...any) {}} |
| + client, _, err := newLeaserClient(ctx, me.Region) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = other.PersistTermination(ctx, client, binding, me.Ref, &termfence.ProofCache{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + seconds.Store(10) |
| + for i := 0; i < 20; i++ { |
| + held, err := AcquireHA(ctx, fx.Bucket, fmt.Sprintf("instances/shop-%d", i), me.Region, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = held.Release(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if proofGets() != 2 || api.calls != 1 { |
| + t.Fatalf("GET=%d Describe=%d", proofGets(), api.calls) |
| + } |
| +} |
diff --git a/internal/termfence/confirm.go b/internal/termfence/confirm.go| index dddb64e45..e9db21d96 100644 |
| --- a/internal/termfence/confirm.go |
| +++ b/internal/termfence/confirm.go |
| @@ -61,6 +61,9 @@ type Confirmer struct { |
| Now func() time.Time |
| // Logf is log.Printf when nil. |
| Logf func(string, ...any) |
| + // OnConfirmed runs after cache publication, including positive cache hits. |
| + // A failed journal enqueue is retried by the next caller. |
| + OnConfirmed func(context.Context, string) error |
| apiMu sync.Mutex // serializes client construction; spans every iid |
| api EC2 |
| @@ -72,9 +75,11 @@ type Confirmer struct { |
| } |
| type confirmed struct { |
| - until time.Time |
| - yes bool |
| - err error |
| + observation Observation |
| + observedAt time.Time |
| + until time.Time |
| + yes bool |
| + err error |
| } |
| // flight is the one describe in progress for an instance id. Waiters take |
| @@ -110,6 +115,14 @@ func (c *Confirmer) logf(format string, a ...any) { |
| // while one runs wait for it and take its answer, and the answer is cached |
| // before they are released. |
| func (c *Confirmer) Terminated(ctx context.Context, iid string) (bool, error) { |
| + yes, err := c.terminated(ctx, iid) |
| + if yes && err == nil && c.OnConfirmed != nil { |
| + err = c.OnConfirmed(ctx, iid) |
| + } |
| + return yes, err |
| +} |
| + |
| +func (c *Confirmer) terminated(ctx context.Context, iid string) (bool, error) { |
| self := c.Self() |
| if !self.Complete() { |
| return false, errors.New("termfence: this box's cloud identity is incomplete") |
| @@ -219,7 +232,7 @@ func (c *Confirmer) ask(ctx context.Context, self boxid.Cloud, iid string) confi |
| if first { |
| c.logf("termfence: %s confirmed terminated (first evidence, request %s)", iid, o.RequestID) |
| } |
| - return confirmed{yes: true} |
| + return confirmed{yes: true, observation: o, observedAt: c.now()} |
| case errors.Is(err, ErrNotEvidence): |
| return confirmed{} |
| default: |
diff --git a/internal/termfence/termination_proof.go b/internal/termfence/termination_proof.go| new file mode 100644 |
| index 000000000..cca291102 |
| --- /dev/null |
| +++ b/internal/termfence/termination_proof.go |
| @@ -0,0 +1,346 @@ |
| +package termfence |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/aws/smithy-go" |
| + "github.com/carlosframework/platform/internal/boxid" |
| +) |
| + |
| +const MaxTerminationProofBytes = 2048 |
| + |
| +var ErrTerminationProof = errors.New("ha_termination_proof_invalid") |
| +var proofIID = regexp.MustCompile(`^i-([0-9a-f]{8}|[0-9a-f]{17})$`) |
| +var proofAccount = regexp.MustCompile(`^[0-9]{12}$`) |
| +var proofRegion = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]+$`) |
| + |
| +// ProofIdentity can only be constructed by verifying immutable identity bytes |
| +// and an independently supplied iid. A cache reload must verify them again. |
| +type ProofIdentity struct { |
| + evidence boxid.Evidence |
| + bucket string |
| +} |
| + |
| +func VerifyProofIdentity(v boxid.Verifier, raw []byte, expect boxid.Expect, bucket string) (ProofIdentity, error) { |
| + if expect.TofuInstanceID == "" || bucket == "" || strings.ContainsAny(bucket, "/\\\x00") { |
| + return ProofIdentity{}, ErrTerminationProof |
| + } |
| + e, err := v.Enroll(raw, expect) |
| + if err != nil { |
| + return ProofIdentity{}, err |
| + } |
| + if !proofIID.MatchString(e.Cloud.InstanceID) || !proofAccount.MatchString(e.Cloud.Account) || !proofRegion.MatchString(e.Cloud.Region) { |
| + return ProofIdentity{}, ErrTerminationProof |
| + } |
| + return ProofIdentity{evidence: e, bucket: bucket}, nil |
| +} |
| +func (b ProofIdentity) Evidence() boxid.Evidence { return b.evidence } |
| +func (b ProofIdentity) Bucket() string { return b.bucket } |
| +func (b ProofIdentity) Key() string { |
| + return "control/terminations/v1/" + b.evidence.Cloud.Account + "/" + b.evidence.Cloud.Region + "/" + b.evidence.Cloud.InstanceID + "/" + b.evidence.RecordSHA256 + ".json" |
| +} |
| +func (b ProofIdentity) valid() bool { |
| + return b.bucket != "" && b.evidence.Cloud.Complete() && b.evidence.RecordSHA256 != "" |
| +} |
| +func (b ProofIdentity) cacheKey() string { return b.bucket + "/" + b.Key() } |
| + |
| +type TerminationProof struct { |
| + V int `json:"v"` |
| + Account string `json:"account"` |
| + Region string `json:"region"` |
| + IID string `json:"iid"` |
| + BoxRef string `json:"box_ref"` |
| + BoxLifetime string `json:"box_lifetime"` |
| + IdentitySHA256 string `json:"identity_sha256"` |
| + State string `json:"state"` |
| + Source string `json:"source"` |
| + ConfirmedAt time.Time `json:"confirmed_at"` |
| + ConfirmingRef string `json:"confirming_box_ref"` |
| + ConfirmingIID string `json:"confirming_box_iid"` |
| +} |
| + |
| +type ProofStore interface { |
| + GetObject(context.Context, *s3.GetObjectInput, ...func(*s3.Options)) (*s3.GetObjectOutput, error) |
| + PutObject(context.Context, *s3.PutObjectInput, ...func(*s3.Options)) (*s3.PutObjectOutput, error) |
| +} |
| + |
| +// NewProofStore retains only the two S3 method values needed by proofs. |
| +func NewProofStore(client *s3.Client) ProofStore { |
| + return proofStoreMethods{get: client.GetObject, put: client.PutObject} |
| +} |
| + |
| +type proofStoreMethods struct { |
| + get func(context.Context, *s3.GetObjectInput, ...func(*s3.Options)) (*s3.GetObjectOutput, error) |
| + put func(context.Context, *s3.PutObjectInput, ...func(*s3.Options)) (*s3.PutObjectOutput, error) |
| +} |
| + |
| +func (s proofStoreMethods) GetObject(ctx context.Context, in *s3.GetObjectInput, opts ...func(*s3.Options)) (*s3.GetObjectOutput, error) { |
| + return s.get(ctx, in, opts...) |
| +} |
| +func (s proofStoreMethods) PutObject(ctx context.Context, in *s3.PutObjectInput, opts ...func(*s3.Options)) (*s3.PutObjectOutput, error) { |
| + return s.put(ctx, in, opts...) |
| +} |
| + |
| +type proofResult struct { |
| + proof TerminationProof |
| + found bool |
| + err error |
| + until time.Time |
| +} |
| +type proofFlight struct { |
| + done chan struct{} |
| + result proofResult |
| +} |
| +type ProofCache struct { |
| + Now func() time.Time |
| + mu sync.Mutex |
| + entries map[string]proofResult |
| + reads map[string]*proofFlight |
| + writes map[string]*proofFlight |
| + writeErrors map[string]proofResult |
| +} |
| + |
| +func (c *ProofCache) now() time.Time { |
| + if c.Now != nil { |
| + return c.Now() |
| + } |
| + return time.Now() |
| +} |
| +func (c *ProofCache) cached(key string) (proofResult, bool) { |
| + r, ok := c.entries[key] |
| + return r, ok && (r.found || c.now().Before(r.until)) |
| +} |
| + |
| +// Load validates provenance for discovery or acquire. Its result alone does not |
| +// grant import, completion or start authority. All callers share one cache. |
| +func (c *ProofCache) Load(ctx context.Context, api ProofStore, b ProofIdentity) (TerminationProof, bool, error) { |
| + if c == nil || api == nil || !b.valid() { |
| + return TerminationProof{}, false, ErrTerminationProof |
| + } |
| + key := b.cacheKey() |
| + c.mu.Lock() |
| + if r, ok := c.cached(key); ok { |
| + c.mu.Unlock() |
| + if r.found && r.proof.BoxRef != b.evidence.Box { |
| + return TerminationProof{}, false, ErrTerminationProof |
| + } |
| + return r.proof, r.found, r.err |
| + } |
| + if f := c.reads[key]; f != nil { |
| + c.mu.Unlock() |
| + select { |
| + case <-ctx.Done(): |
| + return TerminationProof{}, false, ctx.Err() |
| + case <-f.done: |
| + return f.result.proof, f.result.found, f.result.err |
| + } |
| + } |
| + f := &proofFlight{done: make(chan struct{})} |
| + if c.reads == nil { |
| + c.reads = map[string]*proofFlight{} |
| + } |
| + c.reads[key] = f |
| + c.mu.Unlock() |
| + p, found, err := readTerminationProof(ctx, api, b) |
| + c.mu.Lock() |
| + r := proofResult{proof: p, found: found, err: err, until: c.now().Add(ConfirmNegativeTTL)} |
| + if old, ok := c.entries[key]; ok && old.found { |
| + r = old |
| + } |
| + if c.entries == nil { |
| + c.entries = map[string]proofResult{} |
| + } |
| + c.entries[key] = r |
| + f.result = r |
| + delete(c.reads, key) |
| + close(f.done) |
| + c.mu.Unlock() |
| + return r.proof, r.found, r.err |
| +} |
| +func proofRequest(o *s3.Options) { o.RetryMaxAttempts = 1 } |
| +func readTerminationProof(ctx context.Context, api ProofStore, b ProofIdentity) (TerminationProof, bool, error) { |
| + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + defer cancel() |
| + out, err := api.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(b.bucket), Key: aws.String(b.Key())}, proofRequest) |
| + if err != nil { |
| + var ae smithy.APIError |
| + if errors.As(err, &ae) && ae.ErrorCode() == "NoSuchKey" { |
| + return TerminationProof{}, false, nil |
| + } |
| + return TerminationProof{}, false, err |
| + } |
| + if out == nil || out.Body == nil { |
| + return TerminationProof{}, false, ErrTerminationProof |
| + } |
| + defer out.Body.Close() |
| + if aws.ToInt64(out.ContentLength) > MaxTerminationProofBytes { |
| + return TerminationProof{}, false, ErrTerminationProof |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(out.Body, MaxTerminationProofBytes+1)) |
| + if err != nil { |
| + return TerminationProof{}, false, err |
| + } |
| + p, err := decodeTerminationProof(raw, b) |
| + return p, err == nil, err |
| +} |
| +func decodeTerminationProof(raw []byte, b ProofIdentity) (TerminationProof, error) { |
| + if len(raw) > MaxTerminationProofBytes { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + d := json.NewDecoder(bytes.NewReader(raw)) |
| + token, err := d.Token() |
| + if err != nil || token != json.Delim('{') { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + seen := map[string]bool{} |
| + for d.More() { |
| + token, err = d.Token() |
| + if err != nil { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + name, ok := token.(string) |
| + if !ok || seen[name] { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + seen[name] = true |
| + var value json.RawMessage |
| + if d.Decode(&value) != nil || bytes.Equal(value, []byte("null")) { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + } |
| + if len(seen) != 12 { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + for _, field := range []string{"v", "account", "region", "iid", "box_ref", "box_lifetime", "identity_sha256", "state", "source", "confirmed_at", "confirming_box_ref", "confirming_box_iid"} { |
| + if !seen[field] { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + } |
| + d = json.NewDecoder(bytes.NewReader(raw)) |
| + d.DisallowUnknownFields() |
| + var p TerminationProof |
| + if err = d.Decode(&p); err != nil { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + if _, err = d.Token(); err != io.EOF { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + e := b.evidence |
| + var fields map[string]json.RawMessage |
| + _ = json.Unmarshal(raw, &fields) |
| + var stamp string |
| + _ = json.Unmarshal(fields["confirmed_at"], &stamp) |
| + if p.V != 1 || p.Account != e.Cloud.Account || p.Region != e.Cloud.Region || p.IID != e.Cloud.InstanceID || p.BoxRef != e.Box || p.BoxLifetime != e.RecordSHA256 || p.IdentitySHA256 != e.RecordSHA256 || p.State != "terminated" || p.Source != "ec2-describe" || p.ConfirmedAt.IsZero() || !strings.HasSuffix(stamp, "Z") || !boxid.ValidBox(p.ConfirmingRef) || !proofIID.MatchString(p.ConfirmingIID) || p.ConfirmingIID == p.IID { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + return p, nil |
| +} |
| + |
| +// PersistTermination is the sole writer. It uses the confirmer's retained |
| +// Describe observation, including its original time, never a caller's boolean. |
| +func (c *Confirmer) PersistTermination(ctx context.Context, api ProofStore, b ProofIdentity, selfRef string, cache *ProofCache) (TerminationProof, error) { |
| + if cache == nil || api == nil || !b.valid() || !boxid.ValidBox(selfRef) || c.Self == nil { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + self := c.Self() |
| + e := b.evidence |
| + if !self.Complete() || !proofIID.MatchString(self.InstanceID) || self.Account != e.Cloud.Account || self.Region != e.Cloud.Region || self.InstanceID == e.Cloud.InstanceID { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + key := b.cacheKey() |
| + cache.mu.Lock() |
| + if r, ok := cache.cached(key); ok && r.found { |
| + cache.mu.Unlock() |
| + if r.proof.BoxRef != e.Box { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + return r.proof, nil |
| + } |
| + if failure, ok := cache.writeErrors[key]; ok && cache.now().Before(failure.until) { |
| + cache.mu.Unlock() |
| + return TerminationProof{}, failure.err |
| + } |
| + if f := cache.writes[key]; f != nil { |
| + cache.mu.Unlock() |
| + select { |
| + case <-ctx.Done(): |
| + return TerminationProof{}, ctx.Err() |
| + case <-f.done: |
| + return f.result.proof, f.result.err |
| + } |
| + } |
| + f := &proofFlight{done: make(chan struct{})} |
| + if cache.writes == nil { |
| + cache.writes = map[string]*proofFlight{} |
| + } |
| + cache.writes[key] = f |
| + cache.mu.Unlock() |
| + p, err := c.persistTermination(ctx, api, b, selfRef, self) |
| + cache.mu.Lock() |
| + r := proofResult{proof: p, found: err == nil, err: err} |
| + if err == nil { |
| + if cache.entries == nil { |
| + cache.entries = map[string]proofResult{} |
| + } |
| + cache.entries[key] = r |
| + delete(cache.writeErrors, key) |
| + } else { |
| + if cache.writeErrors == nil { |
| + cache.writeErrors = map[string]proofResult{} |
| + } |
| + r.until = cache.now().Add(ConfirmNegativeTTL) |
| + cache.writeErrors[key] = r |
| + } |
| + f.result = r |
| + delete(cache.writes, key) |
| + close(f.done) |
| + cache.mu.Unlock() |
| + return p, err |
| +} |
| +func (c *Confirmer) persistTermination(ctx context.Context, api ProofStore, b ProofIdentity, selfRef string, self boxid.Cloud) (TerminationProof, error) { |
| + e := b.evidence |
| + yes, err := c.terminated(ctx, e.Cloud.InstanceID) |
| + if err != nil { |
| + return TerminationProof{}, err |
| + } |
| + if !yes { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + c.mu.Lock() |
| + observation := c.cache[e.Cloud.InstanceID] |
| + c.mu.Unlock() |
| + if !observation.yes || observation.observedAt.IsZero() || SameAccountTerminated(self, e.Cloud.InstanceID, observation.observation) != nil { |
| + return TerminationProof{}, ErrTerminationProof |
| + } |
| + p := TerminationProof{V: 1, Account: e.Cloud.Account, Region: e.Cloud.Region, IID: e.Cloud.InstanceID, BoxRef: e.Box, BoxLifetime: e.RecordSHA256, IdentitySHA256: e.RecordSHA256, State: "terminated", Source: "ec2-describe", ConfirmedAt: observation.observedAt.UTC(), ConfirmingRef: selfRef, ConfirmingIID: self.InstanceID} |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + return TerminationProof{}, err |
| + } |
| + if _, err = decodeTerminationProof(raw, b); err != nil { |
| + return TerminationProof{}, err |
| + } |
| + putCtx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + _, err = api.PutObject(putCtx, &s3.PutObjectInput{Bucket: aws.String(b.bucket), Key: aws.String(b.Key()), Body: bytes.NewReader(raw), IfNoneMatch: aws.String("*"), ContentType: aws.String("application/json")}, proofRequest) |
| + cancel() |
| + if err == nil { |
| + return p, nil |
| + } |
| + // A conflict or ambiguous failed response may have stored another receiver's |
| + // exact incarnation. It must be read and validated, never overwritten. |
| + existing, found, readErr := readTerminationProof(ctx, api, b) |
| + if readErr == nil && found { |
| + return existing, nil |
| + } |
| + return TerminationProof{}, errors.Join(err, readErr) |
| +} |
diff --git a/internal/termfence/termination_proof_test.go b/internal/termfence/termination_proof_test.go| new file mode 100644 |
| index 000000000..978bdcb88 |
| --- /dev/null |
| +++ b/internal/termfence/termination_proof_test.go |
| @@ -0,0 +1,296 @@ |
| +package termfence |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/aws/aws-sdk-go-v2/service/ec2/types" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| +) |
| + |
| +func proofIdentity(t *testing.T) ProofIdentity { |
| + t.Helper() |
| + s := boxidtest.NewSigner(t) |
| + _, raw := s.Record(t, "departed", "111122223333", "eu-west-1", "i-1123456789abcdef0") |
| + b, err := VerifyProofIdentity(boxid.Verifier{Account: "111122223333", Certs: s.Certs()}, raw, boxid.Expect{Box: "departed", AWSRegion: "eu-west-1", TofuInstanceID: "i-1123456789abcdef0"}, "regional-data") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +type proofTransport struct { |
| + mu sync.Mutex |
| + body []byte |
| + gets, puts int |
| + failPut, losePut, denyGet bool |
| + paths []string |
| +} |
| + |
| +func (p *proofTransport) Do(r *http.Request) (*http.Response, error) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + p.paths = append(p.paths, r.Method+" "+r.URL.Host+r.URL.Path) |
| + status, body := 200, []byte{} |
| + switch r.Method { |
| + case "GET": |
| + p.gets++ |
| + if p.denyGet { |
| + status = 403 |
| + body = []byte(`<Error><Code>AccessDenied</Code></Error>`) |
| + } else if p.body == nil { |
| + status = 404 |
| + body = []byte(`<Error><Code>NoSuchKey</Code></Error>`) |
| + } else { |
| + body = bytes.Clone(p.body) |
| + } |
| + case "PUT": |
| + p.puts++ |
| + if r.Header.Get("If-None-Match") != "*" { |
| + return nil, errors.New("missing create condition") |
| + } |
| + if p.failPut { |
| + return nil, errors.New("offline") |
| + } |
| + if p.body != nil { |
| + status = 412 |
| + body = []byte(`<Error><Code>PreconditionFailed</Code></Error>`) |
| + } else { |
| + p.body, _ = io.ReadAll(r.Body) |
| + if p.losePut { |
| + return nil, errors.New("lost response") |
| + } |
| + } |
| + default: |
| + return nil, errors.New("unexpected method") |
| + } |
| + return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/xml"}}, Body: io.NopCloser(bytes.NewReader(body))}, nil |
| +} |
| +func (p *proofTransport) client() *s3.Client { |
| + return s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("key", "secret", ""), RetryMaxAttempts: 1, HTTPClient: p}, func(o *s3.Options) { o.UsePathStyle = true }) |
| +} |
| +func proofConfirmer() *confirmRig { |
| + r := newConfirmRig(&fakeEC2{out: describe("111122223333", "i-1123456789abcdef0", types.InstanceStateNameTerminated)}) |
| + r.c.Self = func() boxid.Cloud { |
| + return boxid.Cloud{Provider: "aws", Account: "111122223333", Region: "eu-west-1", InstanceID: "i-0123456789abcdef0"} |
| + } |
| + return r |
| +} |
| +func TestTerminationProofDurability(t *testing.T) { |
| + b := proofIdentity(t) |
| + for _, mode := range []string{"normal", "lost response", "conflict", "retry original time"} { |
| + t.Run(mode, func(t *testing.T) { |
| + p := &proofTransport{} |
| + api := p.client() |
| + r := proofConfirmer() |
| + cache := &ProofCache{} |
| + original := r.at |
| + if mode == "conflict" { |
| + _, err := r.c.PersistTermination(context.Background(), api, b, "survivor", &ProofCache{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.at = r.at.Add(time.Hour) |
| + } |
| + if mode == "lost response" { |
| + p.losePut = true |
| + } |
| + if mode == "retry original time" { |
| + p.failPut = true |
| + if _, err := r.c.PersistTermination(context.Background(), api, b, "survivor", cache); err == nil { |
| + t.Fatal("write failure accepted") |
| + } |
| + p.failPut = false |
| + r.at = r.at.Add(time.Hour) |
| + } |
| + proof, err := r.c.PersistTermination(context.Background(), api, b, "survivor", cache) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !proof.ConfirmedAt.Equal(original) { |
| + t.Fatalf("observation time changed: %s", proof.ConfirmedAt) |
| + } |
| + // Revalidate on a new process cache without an EC2 client, after EC2 retention. |
| + cold := &ProofCache{Now: func() time.Time { return original.Add(48 * time.Hour) }} |
| + again, ok, err := cold.Load(context.Background(), api, b) |
| + if err != nil || !ok || again != proof { |
| + t.Fatalf("restart: %v %v %+v", ok, err, again) |
| + } |
| + gets := p.gets |
| + for i := 0; i < 20; i++ { |
| + if _, ok, err = cold.Load(context.Background(), api, b); err != nil || !ok { |
| + t.Fatal(err) |
| + } |
| + } |
| + if p.gets != gets { |
| + t.Fatal("positive cache reread") |
| + } |
| + if len(r.f.ids) != 1 { |
| + t.Fatalf("describes %d", len(r.f.ids)) |
| + } |
| + }) |
| + } |
| +} |
| +func TestTerminationProofBinding(t *testing.T) { |
| + b := proofIdentity(t) |
| + p := &proofTransport{} |
| + r := proofConfirmer() |
| + if _, err := r.c.PersistTermination(context.Background(), p.client(), b, "survivor", &ProofCache{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + valid := bytes.Clone(p.body) |
| + changes := map[string]string{"version": `"v":2`, "account": `"account":"999999999999"`, "region": `"region":"eu-west-2"`, "iid": `"iid":"i-2123456789abcdef0"`, "ref": `"box_ref":"other"`, "lifetime": `"box_lifetime":"` + strings.Repeat("0", 64) + `"`, "identity": `"identity_sha256":"` + strings.Repeat("0", 64) + `"`, "state": `"state":"stopped"`, "source": `"source":"event"`, "time": `"confirmed_at":"yesterday"`, "timezone": `"confirmed_at":"2026-10-27T12:00:00+01:00"`} |
| + fields := map[string]string{"version": "v", "account": "account", "region": "region", "iid": "iid", "ref": "box_ref", "lifetime": "box_lifetime", "identity": "identity_sha256", "state": "state", "source": "source", "time": "confirmed_at", "timezone": "confirmed_at"} |
| + for name, replacement := range changes { |
| + t.Run(name, func(t *testing.T) { |
| + var m map[string]json.RawMessage |
| + _ = json.Unmarshal(valid, &m) |
| + var x map[string]json.RawMessage |
| + _ = json.Unmarshal([]byte("{"+replacement+"}"), &x) |
| + m[fields[name]] = x[fields[name]] |
| + p.body, _ = json.Marshal(m) |
| + if _, ok, err := (&ProofCache{}).Load(context.Background(), p.client(), b); ok || err == nil { |
| + t.Fatal("invalid proof accepted") |
| + } |
| + }) |
| + } |
| + for name, body := range map[string][]byte{"oversized": bytes.Repeat([]byte(" "), 2049), "duplicate": append([]byte(`{"v":1,`), valid[1:]...), "unknown": append([]byte(`{"extra":1,`), valid[1:]...), "missing": bytes.Replace(valid, []byte(`"state":"terminated",`), nil, 1), "trailing": append(bytes.Clone(valid), []byte(`{}`)...)} { |
| + t.Run(name, func(t *testing.T) { |
| + p.body = body |
| + if _, ok, err := (&ProofCache{}).Load(context.Background(), p.client(), b); ok || err == nil { |
| + t.Fatal("invalid proof accepted") |
| + } |
| + }) |
| + } |
| + if _, _, err := (&ProofCache{}).Load(context.Background(), p.client(), ProofIdentity{}); err == nil { |
| + t.Fatal("unverified identity") |
| + } |
| + signer := boxidtest.NewSigner(t) |
| + _, raw := signer.Record(t, "departed", "111122223333", "eu-west-1", "i-1123456789abcdef0") |
| + v := boxid.Verifier{Account: "111122223333", Certs: signer.Certs()} |
| + for _, expected := range []string{"", "i-2123456789abcdef0"} { |
| + if _, err := VerifyProofIdentity(v, raw, boxid.Expect{Box: "departed", AWSRegion: "eu-west-1", TofuInstanceID: expected}, "regional-data"); err == nil { |
| + t.Fatal("unsigned ref trusted") |
| + } |
| + } |
| +} |
| +func TestTerminationProofRequestBudget(t *testing.T) { |
| + b := proofIdentity(t) |
| + p := &proofTransport{} |
| + api := p.client() |
| + now := time.Now() |
| + cache := &ProofCache{Now: func() time.Time { return now }} |
| + var wg sync.WaitGroup |
| + for i := 0; i < 20; i++ { |
| + wg.Go(func() { |
| + _, ok, err := cache.Load(context.Background(), api, b) |
| + if ok || err != nil { |
| + t.Errorf("absence: %v %v", ok, err) |
| + } |
| + }) |
| + } |
| + wg.Wait() |
| + if p.gets != 1 { |
| + t.Fatalf("gets=%d", p.gets) |
| + } |
| + r := proofConfirmer() |
| + if _, err := r.c.PersistTermination(context.Background(), api, b, "survivor", &ProofCache{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + now = now.Add(10 * time.Second) |
| + for i := 0; i < 20; i++ { |
| + if _, ok, err := cache.Load(context.Background(), api, b); !ok || err != nil { |
| + t.Fatalf("present %v %v", ok, err) |
| + } |
| + } |
| + if p.gets != 2 { |
| + t.Fatalf("gets=%d", p.gets) |
| + } |
| + t.Run("local creation replaces absence", func(t *testing.T) { |
| + p := &proofTransport{} |
| + cache := &ProofCache{} |
| + _, _, _ = cache.Load(context.Background(), p.client(), b) |
| + if _, err := proofConfirmer().c.PersistTermination(context.Background(), p.client(), b, "survivor", cache); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok, err := cache.Load(context.Background(), p.client(), b); !ok || err != nil { |
| + t.Fatal(err) |
| + } |
| + if p.gets != 1 { |
| + t.Fatal(p.gets) |
| + } |
| + }) |
| + t.Run("errors remain refusals", func(t *testing.T) { |
| + p := &proofTransport{denyGet: true} |
| + cache := &ProofCache{} |
| + for i := 0; i < 20; i++ { |
| + if _, ok, err := cache.Load(context.Background(), p.client(), b); ok || err == nil { |
| + t.Fatal("error accepted") |
| + } |
| + } |
| + if p.gets != 1 { |
| + t.Fatal(p.gets) |
| + } |
| + }) |
| +} |
| +func TestRequestConfirmationEnqueues(t *testing.T) { |
| + r := proofConfirmer() |
| + var calls atomic.Int32 |
| + r.c.OnConfirmed = func(ctx context.Context, iid string) error { |
| + if calls.Add(1) == 1 { |
| + return errors.New("journal") |
| + } |
| + r.c.mu.Lock() |
| + defer r.c.mu.Unlock() |
| + if !r.c.cache[iid].yes { |
| + t.Fatal("callback before publication") |
| + } |
| + return nil |
| + } |
| + if _, err := r.c.Terminated(context.Background(), "i-1123456789abcdef0"); err == nil { |
| + t.Fatal("journal error lost") |
| + } |
| + if yes, err := r.c.Terminated(context.Background(), "i-1123456789abcdef0"); !yes || err != nil { |
| + t.Fatal(yes, err) |
| + } |
| + if calls.Load() != 2 || len(r.f.ids) != 1 { |
| + t.Fatal("positive hit not retried") |
| + } |
| +} |
| + |
| +func TestTerminationProofPersistenceRetryBound(t *testing.T) { |
| + b := proofIdentity(t) |
| + p := &proofTransport{failPut: true} |
| + r := proofConfirmer() |
| + cache := &ProofCache{Now: func() time.Time { return r.at }} |
| + for i := 0; i < 20; i++ { |
| + if _, err := r.c.PersistTermination(context.Background(), p.client(), b, "survivor", cache); err == nil { |
| + t.Fatal("failed write accepted") |
| + } |
| + } |
| + if p.puts != 1 || p.gets != 1 { |
| + t.Fatalf("failed persistence puts=%d gets=%d", p.puts, p.gets) |
| + } |
| + r.at = r.at.Add(10 * time.Second) |
| + p.failPut = false |
| + proof, err := r.c.PersistTermination(context.Background(), p.client(), b, "survivor", cache) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if p.puts != 2 || p.gets != 1 || !proof.ConfirmedAt.Equal(r.at.Add(-10*time.Second)) { |
| + t.Fatalf("retry lost original evidence: puts=%d gets=%d proof=%+v", p.puts, p.gets, proof) |
| + } |
| +} |