ha: arm durable departure recovery before local workers
Connect the shared proof cache, identity repository, journal, inventory and edge ticks to one cancellable consumer. Persist bounded discovery, age retries and hourly coverage pages. Notify durable enrollment from acquire proof hits and strip inherited AWS configuration from tenant children.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
20 files changed,
+1,168
−20
internal/activator/backend_exec.go+1 −1internal/activator/termination_credentials_test.go+27 −0internal/edge/hadepartures_test.go+9 −3internal/hadeparture/consumer.go+4 −0internal/host/agent.go+34 −1internal/host/hadeparture_credentials_test.go+37 −0internal/host/hadeparture_identity.go+21 −11internal/host/hadeparture_identity_test.go+1 −1internal/host/hadepartures.go+347 −0internal/host/hadepartures_test.go+88 −0internal/host/hadepartures_wiring.go+181 −0internal/host/hadepartures_wiring_test.go+170 −0internal/hostenv/hostenv.go+1 −0internal/lease/termination_proof.go+10 −2internal/lease/termination_proof_test.go+38 −0internal/objstore/termination_credentials_test.go+62 −0internal/provision/departure_inventory.go+1 −1internal/provision/departure_inventory_test.go+37 −0internal/registry/ha_journal.go+63 −0internal/registry/ha_journal_test.go+36 −0
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index ce1e75d45..caffe9fbf 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -3124,7 +3124,7 @@ func childEnv(fileEnv map[string]string) []string { |
| values[k] = v |
| } |
| for _, kv := range os.Environ() { |
| - if strings.HasPrefix(kv, "CARLOS_") { |
| + if strings.HasPrefix(kv, "CARLOS_") || strings.HasPrefix(kv, "AWS_") { |
| continue |
| } |
| k, v, ok := strings.Cut(kv, "=") |
diff --git a/internal/activator/termination_credentials_test.go b/internal/activator/termination_credentials_test.go| new file mode 100644 |
| index 000000000..e46559655 |
| --- /dev/null |
| +++ b/internal/activator/termination_credentials_test.go |
| @@ -0,0 +1,27 @@ |
| +package activator |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestTerminationProofCredentials(t *testing.T) { |
| + for _, key := range []string{"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_SHARED_CREDENTIALS_FILE", "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_CONTAINER_CREDENTIALS_FULL_URI"} { |
| + t.Setenv(key, "box-role-only") |
| + } |
| + for _, kv := range childEnv(nil) { |
| + if strings.HasPrefix(kv, "AWS_") { |
| + t.Fatal("inherited box credential configuration", strings.SplitN(kv, "=", 2)[0]) |
| + } |
| + } |
| + env := childEnv(map[string]string{"AWS_ACCESS_KEY_ID": "tenant-store-key"}) |
| + found := false |
| + for _, kv := range env { |
| + if kv == "AWS_ACCESS_KEY_ID=tenant-store-key" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Fatal("tenant-scoped delivered credential removed") |
| + } |
| +} |
diff --git a/internal/edge/hadepartures_test.go b/internal/edge/hadepartures_test.go| index 1b068b0fb..e6f527c53 100644 |
| --- a/internal/edge/hadepartures_test.go |
| +++ b/internal/edge/hadepartures_test.go |
| @@ -10,7 +10,7 @@ import ( |
| ) |
| func TestDepartureAgeOnSkippedFold(t *testing.T) { |
| - s := release.NewDirStore(t.TempDir()) |
| + s := newChangeIndexStore(t) |
| now := time.Now().UTC().Truncate(time.Second) |
| raw := []byte(`{"v":1,"box":"peer","region":"eu-west-1","placement":"","data_bucket":"data","secrets_key_fp":"fp","generation":"` + now.Format(time.RFC3339) + `","hosts":{}}`) |
| etag, err := s.Put(context.Background(), "control/edges/peer.json", raw, "") |
| @@ -18,6 +18,8 @@ func TestDepartureAgeOnSkippedFold(t *testing.T) { |
| t.Fatal(err) |
| } |
| m := newHomeMap(s, "self") |
| + watch := release.NewChangeWatch(s) |
| + m.watch = func() *release.ChangeWatch { return watch } |
| calls := 0 |
| m.departureTick = func(ctx context.Context, v DepartureView) { |
| calls++ |
| @@ -27,13 +29,17 @@ func TestDepartureAgeOnSkippedFold(t *testing.T) { |
| } |
| _ = m.poll(context.Background()) |
| // The callback runs on the real poll even when its hosts refresh is skipped. |
| - m.watch = func() *release.ChangeWatch { return release.NewChangeWatch(s) } |
| + s.reset() |
| + m.lastHosts = now |
| + m.hostsAge = time.Hour |
| _ = m.poll(context.Background()) |
| _ = m.poll(context.Background()) |
| + if got := s.count("Get", edgesPrefix) + s.count("List", edgesPrefix); got != 0 { |
| + t.Fatalf("skipped fold membership reads %d", got) |
| + } |
| if calls != 3 { |
| t.Fatalf("callbacks %d", calls) |
| } |
| - _ = s.Put // keep fixture writes separate from observations |
| } |
| func TestDepartureHomeScopeAndPools(t *testing.T) { |
| for _, placement := range []string{"", `,"placement":""`, `,"placement":null`} { |
diff --git a/internal/hadeparture/consumer.go b/internal/hadeparture/consumer.go| index 85fccd6cd..adf81e231 100644 |
| --- a/internal/hadeparture/consumer.go |
| +++ b/internal/hadeparture/consumer.go |
| @@ -20,6 +20,7 @@ func (e *InitError) Error() string { return "ha_consumer_init_" + e.Stage } |
| func (e *InitError) Unwrap() error { return e.Err } |
| type Consumer struct { |
| + OnRetry func() |
| initialize func(context.Context) error |
| record func(context.Context, Message) error |
| work func(context.Context) error |
| @@ -143,6 +144,9 @@ func (c *Consumer) receive(ctx context.Context, q Queue) { |
| return |
| } |
| if err != nil { |
| + if c.OnRetry != nil { |
| + c.OnRetry() |
| + } |
| if c.wait(ctx, retryDelay(failures)) != nil { |
| return |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 7aebf0ec5..521c5c770 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -190,6 +190,7 @@ import ( |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/fleetapi" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/instancectl" |
| @@ -415,6 +416,8 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| guard.Announce() |
| var act edge.Activator |
| + var departures *Controller |
| + var departureLife hadeparture.Lifecycle |
| var svc *activator.Service |
| var coordinator *activator.CoordinationClient |
| // egressStatus is root's GET /egress for the status tick (#328): set |
| @@ -581,6 +584,10 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| Unit: &activator.UnitBackend{OptDir: release.OptDir()}, |
| }, reg) // the registry satisfies activator.DueStore directly |
| svc.DutyStore = reg |
| + departures, departureLife, err = armHADepartures(agentCtx, departureArm{Getenv: os.Getenv, Registry: reg, Service: svc, Backend: eb, Confirmer: confirmer, Inventory: boxDepartureInventory, OpenStore: openDeployStore}) |
| + if err != nil { |
| + log.Printf("ha_departure_init code=unavailable") |
| + } |
| armHAPlacement(svc, PageOperator) |
| // Sizes (#329): the provisioning passes' PolicyChanged tells this |
| // Service a row's size column moved, and the status tick reads each |
| @@ -1059,6 +1066,11 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // which may not have run yet. Disarmed, it returns nil for good and |
| // both keep today's full reads. |
| edge.WithChangeWatch(armedChangeWatch.Load), |
| + edge.WithDepartureTick(func(ctx context.Context, v edge.DepartureView) { |
| + if departures != nil { |
| + _ = departures.Tick(ctx, v) |
| + } |
| + }), |
| }, |
| // The edge-local door (#175 P7), only when CARLOS_EDGE_DOOR names a |
| // socket. It presents this box's public address, the one the edges |
| @@ -1153,6 +1165,13 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| armEdgeAssetCache(os.Getenv, dataDir(), assetcache.Statfs, boxAssets, e.EnableAssetCache) |
| }, edgeOpts...) |
| + if departureLife != nil { |
| + stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + if err := departureLife.Stop(stopCtx); err != nil { |
| + log.Printf("ha_departure_stop code=deadline") |
| + } |
| + stopCancel() |
| + } |
| var seedErr error |
| shutdownCtx, shutdownCancel, seedErr = joinAgentShutdown(seedCtx, seedCancel, seedServer, cancelStartup, startupDone, dutiesDone) |
| if seedErr != nil { |
| @@ -1907,7 +1926,21 @@ func reconcileSerializedAuth(ctx context.Context, s release.Store, reg *registry |
| // Writes still go to s, and a key written through the snapshot store is |
| // read from s afterwards. Disarmed, or when the view cannot vouch, rs is |
| // s and the pass walks the bucket as before. |
| - rs, _, _ := viewStore(ctx, s) |
| + rs, epoch, cached := viewStore(ctx, s) |
| + source, complete := provision.DepartureSource(rs) |
| + walkStarted := time.Now() |
| + if !cached { |
| + source = walkStarted |
| + complete = true |
| + } |
| + if !cached { |
| + if v := armedRecordView.Load(); v != nil { |
| + if sn := v.Snapshot(); sn != nil { |
| + epoch = sn.Epoch |
| + } |
| + } |
| + } |
| + cfg.Departures = boxDepartureInventory.Begin(fmt.Sprintf("%d/%d", epoch, walkStarted.UnixNano()), walkStarted, source, complete && cfg.PolicyScope == nil) |
| // A fresh row is minted at the layout this box's intent names |
| // (ReconcileConfig.Layout): nested on a nested box, so a new tenant |
| // never runs flat there. Set here, the one place both callers pass |
diff --git a/internal/host/hadeparture_credentials_test.go b/internal/host/hadeparture_credentials_test.go| new file mode 100644 |
| index 000000000..a18e6bf33 |
| --- /dev/null |
| +++ b/internal/host/hadeparture_credentials_test.go |
| @@ -0,0 +1,37 @@ |
| +package host |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestTerminationProofCredentials(t *testing.T) { |
| + paths, err := filepath.Glob("units/carlos-instance*.service") |
| + if err != nil || len(paths) < 10 { |
| + t.Fatalf("unit inventory %v %v", paths, err) |
| + } |
| + for _, path := range paths { |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + text := string(raw) |
| + if filepath.Base(path) == "carlos-instance-control.service" { |
| + if !strings.Contains(text, "RestrictAddressFamilies=AF_UNIX") { |
| + t.Fatal("control service network expanded") |
| + } |
| + continue |
| + } |
| + var deny string |
| + for _, line := range strings.Split(text, "\n") { |
| + if strings.HasPrefix(line, "IPAddressDeny=") { |
| + deny += " " + line |
| + } |
| + } |
| + if !strings.Contains(deny, "169.254.169.254/32") || !strings.Contains(deny, "fd00:ec2::254/128") { |
| + t.Fatalf("tenant metadata path not isolated: %s", path) |
| + } |
| + } |
| +} |
diff --git a/internal/host/hadeparture_identity.go b/internal/host/hadeparture_identity.go| index c459a0681..123106c29 100644 |
| --- a/internal/host/hadeparture_identity.go |
| +++ b/internal/host/hadeparture_identity.go |
| @@ -152,14 +152,21 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error) |
| if !ok { |
| return false, w.StartedAt, errDepartureIdentity |
| } |
| - keys, err := l.ListPage(ctx, boxid.Prefix, w.Cursor, 32) |
| - if err != nil { |
| - return false, w.StartedAt, err |
| - } |
| - if len(keys) > 32 { |
| - return false, w.StartedAt, errDepartureIdentity |
| + if len(w.Keys) == 0 { |
| + keys, e := l.ListPage(ctx, boxid.Prefix, w.Cursor, 1000) |
| + if e != nil { |
| + return false, w.StartedAt, e |
| + } |
| + if len(keys) > 1000 { |
| + return false, w.StartedAt, errDepartureIdentity |
| + } |
| + w.Keys = keys |
| + w.Offset = 0 |
| } |
| - for _, key := range keys { |
| + gets := 0 |
| + for w.Offset < len(w.Keys) && gets < 32 { |
| + key := w.Keys[w.Offset] |
| + w.Offset++ |
| if key <= w.Cursor || !strings.HasPrefix(key, boxid.Prefix) || !strings.HasSuffix(key, ".json") { |
| w.Failed = true |
| continue |
| @@ -177,6 +184,7 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error) |
| if known { |
| continue |
| } |
| + gets++ |
| raw, e := boxid.Load(ctx, r.Store, ref) |
| if e == nil { |
| _, e = r.verify(ctx, ref, raw) |
| @@ -185,14 +193,16 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error) |
| w.Failed = true |
| } |
| } |
| - if len(keys) > 0 { |
| - w.Cursor = keys[len(keys)-1] |
| - } |
| - finished := len(keys) < 32 |
| + pageDone := w.Offset == len(w.Keys) |
| + finished := pageDone && len(w.Keys) < 1000 |
| complete := finished && !w.Failed |
| at := w.StartedAt |
| if finished { |
| w = registry.HAIdentityWalk{} |
| + } else if pageDone { |
| + w.Cursor = w.Keys[len(w.Keys)-1] |
| + w.Keys = nil |
| + w.Offset = 0 |
| } |
| if err = r.Registry.SaveHAIdentityWalk(ctx, w); err != nil { |
| return false, at, err |
diff --git a/internal/host/hadeparture_identity_test.go b/internal/host/hadeparture_identity_test.go| index a5d8f4ba5..d2a5fafa1 100644 |
| --- a/internal/host/hadeparture_identity_test.go |
| +++ b/internal/host/hadeparture_identity_test.go |
| @@ -80,7 +80,7 @@ func TestDepartureUnknownIdentityBudget(t *testing.T) { |
| t.Fatalf("first page %v %v", done, err) |
| } |
| walk, err := reg.LoadHAIdentityWalk(ctx) |
| - if err != nil || walk.Cursor == "" { |
| + if err != nil || walk.Offset != 32 || len(walk.Keys) != 35 { |
| t.Fatalf("durable cursor %+v %v", walk, err) |
| } |
| done, at, err := repo.Walk(ctx) |
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go| new file mode 100644 |
| index 000000000..953b9d6dd |
| --- /dev/null |
| +++ b/internal/host/hadepartures.go |
| @@ -0,0 +1,347 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "slices" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/awsterminations" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +var errDepartureScope = errors.New("ha_departure_scope_invalid") |
| + |
| +type LocalPolicy struct { |
| + Scope hadeparture.Scope |
| + Pools []string |
| + Denied bool |
| +} |
| + |
| +func CanAdopt(h provision.DepartureHost, p LocalPolicy) bool { |
| + if p.Denied || h.Kind != "instance" || !h.HA || h.Lifetime == "" || h.Placement != p.Scope.Placement { |
| + return false |
| + } |
| + if len(p.Pools) == 0 { |
| + return h.Pool == "" |
| + } |
| + return slices.Contains(p.Pools, h.Pool) |
| +} |
| + |
| +type RescanResult struct { |
| + Inventory provision.InventorySnapshot |
| + EvidenceAt time.Time |
| + Finished bool |
| + Matches, Unresolved int |
| +} |
| + |
| +func CanCompleteDeparture(r RescanResult) bool { |
| + return r.Finished && r.Matches == 0 && r.Unresolved == 0 && r.Inventory.FreshAfter(r.EvidenceAt) |
| +} |
| +func departureCoverageGap(h provision.DepartureHost, s hadeparture.Scope) bool { |
| + return h.Kind == "sidecar" && !h.HA && h.Placement == s.Placement |
| +} |
| + |
| +type DepartureConfig struct { |
| + Registry *registry.Registry |
| + Identities *departureIdentities |
| + Confirmer *termfence.Confirmer |
| + Cache *termfence.ProofCache |
| + ProofStore func(context.Context, string, string) (termfence.ProofStore, error) |
| + Self hadeparture.Box |
| + DeploymentBucket string |
| + Inventory func() provision.InventorySnapshot |
| + Policy func() LocalPolicy |
| + Invalidate func(string, string) |
| + Now func() time.Time |
| + Logf func(string, ...any) |
| + // Pending is the B4 scan-page entry. A nil entry retains all work. |
| + Pending func(context.Context, registry.HADeparture, provision.InventorySnapshot) error |
| + Page func(context.Context, registry.HADeparture, []provision.DepartureHost) error |
| +} |
| +type Controller struct { |
| + cfg DepartureConfig |
| + consumer *hadeparture.Consumer |
| + mu sync.Mutex |
| + view hadeparture.DepartureView |
| + wake chan struct{} |
| + peerOffset int |
| + evidence map[string]bool |
| +} |
| + |
| +func NewController(cfg DepartureConfig) (*Controller, error) { |
| + if cfg.Registry == nil || cfg.Identities == nil || cfg.Confirmer == nil || cfg.Cache == nil || cfg.Inventory == nil || cfg.Policy == nil || cfg.DeploymentBucket == "" || !boxid.ValidBox(cfg.Self.Ref) || !departureCloud(cfg.Self).Complete() { |
| + return nil, &hadeparture.InitError{Stage: "dependencies", Err: errDepartureScope} |
| + } |
| + c := &Controller{cfg: cfg, wake: make(chan struct{}, 1), evidence: map[string]bool{}} |
| + c.consumer = hadeparture.NewConsumer(func(ctx context.Context) error { _, err := cfg.Registry.TerminationInbox(ctx, c.now(), 1); return err }, c.record, c.work) |
| + c.consumer.OnRetry = func() { c.logf("Termination recovery is retrying after a queue error.") } |
| + return c, nil |
| +} |
| +func departureCloud(b hadeparture.Box) boxid.Cloud { |
| + return boxid.Cloud{Provider: "aws", Account: b.Account, Region: b.Scope.CloudRegion, InstanceID: b.InstanceID} |
| +} |
| +func (c *Controller) now() time.Time { |
| + if c.cfg.Now != nil { |
| + return c.cfg.Now() |
| + } |
| + return time.Now() |
| +} |
| +func (c *Controller) logf(f string, args ...any) { |
| + if c.cfg.Logf != nil { |
| + c.cfg.Logf(f, args...) |
| + } else { |
| + log.Printf(f, args...) |
| + } |
| +} |
| +func (c *Controller) Start(ctx context.Context, makeQueue func(context.Context) (hadeparture.Queue, error)) (hadeparture.Lifecycle, error) { |
| + life, err := c.consumer.Start(ctx, makeQueue) |
| + if err != nil { |
| + c.logf("Termination recovery has not started: %s.", "initialization") |
| + return life, err |
| + } |
| + return life, nil |
| +} |
| +func (c *Controller) record(ctx context.Context, m hadeparture.Message) error { |
| + if _, err := awsterminations.Hint(m.Body, departureCloud(c.cfg.Self)); err != nil { |
| + return nil |
| + } |
| + return c.cfg.Registry.RecordTermination(ctx, m.ID, m.Body, c.now()) |
| +} |
| +func departureID(bucket string, b hadeparture.Box) string { |
| + raw, _ := json.Marshal([]string{bucket, b.Account, b.Scope.CloudRegion, b.Ref, b.InstanceID, b.RecordSHA256}) |
| + return fmt.Sprintf("%x", sha256.Sum256(raw)) |
| +} |
| +func (c *Controller) Enqueue(ctx context.Context, box hadeparture.BoxObservation) error { |
| + return c.enqueue(ctx, box, "") |
| +} |
| +func (c *Controller) enqueue(ctx context.Context, box hadeparture.BoxObservation, inbox string) error { |
| + bound, ok, err := c.cfg.Identities.Resolve(ctx, box.Box.Ref, box.Box.InstanceID) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok || !bound.Known || bound.PlacementNull || !box.Known || box.PlacementNull || bound.Box != box.Box || bound.Box.Scope != c.cfg.Self.Scope || bound.Box.Account != c.cfg.Self.Account || bound.Box.InstanceID == c.cfg.Self.InstanceID { |
| + return errDepartureScope |
| + } |
| + identity, err := c.cfg.Identities.Proof(ctx, bound.Box.Ref, bound.Box.InstanceID) |
| + if err != nil { |
| + return err |
| + } |
| + if c.cfg.ProofStore == nil { |
| + return errDepartureScope |
| + } |
| + api, err := c.cfg.ProofStore(ctx, identity.Bucket(), identity.Evidence().Cloud.Region) |
| + if err != nil { |
| + return err |
| + } |
| + proof, found, readErr := c.cfg.Cache.Load(ctx, api, identity) |
| + if !found || readErr != nil { |
| + proof, err = c.cfg.Confirmer.PersistTermination(ctx, api, identity, c.cfg.Self.Ref, c.cfg.Cache) |
| + if err != nil { |
| + return errors.Join(readErr, err) |
| + } |
| + } |
| + raw, _ := json.Marshal(proof) |
| + d := registry.HADeparture{Departure: hadeparture.Departure{ID: departureID(c.cfg.DeploymentBucket, bound.Box), Box: bound.Box, EdgesKey: bound.EdgesKey, EdgesETag: bound.EdgesETag, ObservedAt: c.now()}, ProofKey: identity.Key(), ProofDigest: fmt.Sprintf("%x", sha256.Sum256(raw))} |
| + if err = c.cfg.Registry.EnrollDeparture(ctx, d, inbox); err != nil { |
| + return err |
| + } |
| + if c.cfg.Invalidate != nil { |
| + c.cfg.Invalidate(bound.Box.Ref, bound.Box.InstanceID) |
| + } |
| + return nil |
| +} |
| +func (c *Controller) confirmed(ctx context.Context, iid string) error { |
| + box, ok, err := c.cfg.Identities.Resolve(ctx, "", iid) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok { |
| + return errDepartureIdentity |
| + } |
| + return c.Enqueue(ctx, box) |
| +} |
| +func (c *Controller) Tick(_ context.Context, v hadeparture.DepartureView) error { |
| + v.Peers = slices.Clone(v.Peers) |
| + c.mu.Lock() |
| + c.view = v |
| + c.mu.Unlock() |
| + select { |
| + case c.wake <- struct{}{}: |
| + default: |
| + } |
| + return nil |
| +} |
| +func (c *Controller) work(ctx context.Context) error { |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-c.consumer.Started(): |
| + } |
| + c.logf("Termination recovery is running.") |
| + defer c.logf("Termination recovery has stopped. Pending recovery will resume when the box starts again.") |
| + timer := time.NewTicker(30 * time.Second) |
| + defer timer.Stop() |
| + lastStep := time.Time{} |
| + for { |
| + // Replay is independent of the edge's first usable snapshot. |
| + if time.Since(lastStep) >= 30*time.Second { |
| + lastStep = time.Now() |
| + if err := c.step(ctx); err != nil && ctx.Err() == nil { |
| + c.logf("ha_departure_retry code=journal") |
| + } |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-timer.C: |
| + case <-c.wake: |
| + } |
| + } |
| +} |
| +func (c *Controller) step(ctx context.Context) error { |
| + ctx, cancel := context.WithTimeout(ctx, 25*time.Second) |
| + defer cancel() |
| + c.mu.Lock() |
| + v := c.view |
| + c.mu.Unlock() |
| + observations := append([]hadeparture.BoxObservation{v.Self}, v.Peers...) |
| + // Rotate the bounded identity/suspicion page; no fold lock spans I/O. |
| + if len(observations) > 0 { |
| + for n := 0; n < min(32, len(observations)); n++ { |
| + o := observations[(c.peerOffset+n)%len(observations)] |
| + if !o.Known || o.PlacementNull { |
| + continue |
| + } |
| + bound, err := c.cfg.Identities.Observe(ctx, o) |
| + if err != nil { |
| + continue |
| + } |
| + if bound.Box.Ref == c.cfg.Self.Ref || o.PublishedAt.IsZero() || o.PublishedAt.After(c.now().Add(time.Minute)) { |
| + continue |
| + } |
| + if v.Self.Known && !v.Self.PlacementNull && v.Self.Box.Scope == c.cfg.Self.Scope && c.now().Sub(o.PublishedAt) > 15*time.Minute { |
| + if due, err := c.cfg.Registry.ClaimHAConfirmation(ctx, bound.Box.Ref, c.now()); err == nil && due { |
| + _ = c.Enqueue(ctx, bound) |
| + } |
| + } |
| + } |
| + c.peerOffset = (c.peerOffset + min(32, len(observations))) % len(observations) |
| + } |
| + rows, err := c.cfg.Registry.TerminationInbox(ctx, c.now(), 32) |
| + if err != nil { |
| + return err |
| + } |
| + unknown := false |
| + for _, row := range rows { |
| + iid, e := awsterminations.Hint(row.Body, departureCloud(c.cfg.Self)) |
| + if e != nil { |
| + if e = c.cfg.Registry.RejectTermination(ctx, row.Key); e != nil { |
| + return e |
| + } |
| + continue |
| + } |
| + o, known, e := c.cfg.Identities.Resolve(ctx, "", iid) |
| + if e == nil && !known { |
| + unknown = true |
| + if e = c.cfg.Registry.RetryTermination(ctx, row.Key, c.now().Add(30*time.Second), "identity_walk"); e != nil { |
| + return e |
| + } |
| + continue |
| + } |
| + if e == nil { |
| + e = c.enqueue(ctx, o, row.Key) |
| + } |
| + if e != nil { |
| + if e = c.cfg.Registry.RetryTermination(ctx, row.Key, c.now().Add(30*time.Second), "evidence"); e != nil { |
| + return e |
| + } |
| + } |
| + } |
| + if unknown { |
| + complete, started, e := c.cfg.Identities.Walk(ctx) |
| + if e != nil { |
| + return e |
| + } |
| + for _, row := range rows { |
| + iid, e := awsterminations.Hint(row.Body, departureCloud(c.cfg.Self)) |
| + if e != nil { |
| + continue |
| + } |
| + _, known, e := c.cfg.Identities.Resolve(ctx, "", iid) |
| + if e == nil && !known && complete && !row.ReceivedAt.After(started) { |
| + if e = c.cfg.Registry.RejectTermination(ctx, row.Key); e != nil { |
| + return e |
| + } |
| + } |
| + } |
| + } |
| + pending, err := c.cfg.Registry.PendingDepartures(ctx, c.now(), 1) |
| + if err != nil { |
| + return err |
| + } |
| + for _, d := range pending { |
| + if !c.evidence[d.ID] { |
| + o, known, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, d.Box.InstanceID) |
| + if e == nil && !known { |
| + e = errDepartureIdentity |
| + } |
| + if e == nil { |
| + e = c.Enqueue(ctx, o) |
| + } |
| + if e == nil { |
| + d.ObservedAt = c.now() |
| + e = c.cfg.Registry.ReobserveDeparture(ctx, d.ID, d.ObservedAt) |
| + } |
| + if e != nil { |
| + _, e = c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), "resume_evidence", false) |
| + if e != nil { |
| + return e |
| + } |
| + continue |
| + } |
| + c.evidence[d.ID] = true |
| + } |
| + inv := c.cfg.Inventory() |
| + gap := false |
| + var blockers []provision.DepartureHost |
| + for _, h := range inv.Records { |
| + if departureCoverageGap(h, d.Box.Scope) { |
| + gap = true |
| + blockers = append(blockers, h) |
| + } |
| + } |
| + code := "pending" |
| + if gap { |
| + code = "blocked_host" |
| + } |
| + // B4 may still import supported hosts from an incomplete departure. |
| + if c.cfg.Pending != nil { |
| + if err = c.cfg.Pending(ctx, d, inv); err != nil { |
| + code = "scan_retry" |
| + } |
| + } |
| + page, e := c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), code, gap) |
| + if e != nil { |
| + return e |
| + } |
| + if page { |
| + c.logf("ha_departure_blocked id=%s code=legacy_sidecar", d.ID) |
| + if c.cfg.Page != nil { |
| + if err = c.cfg.Page(ctx, d, blockers); err != nil { |
| + c.logf("ha_departure_page code=failed") |
| + } |
| + } |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/host/hadepartures_test.go b/internal/host/hadepartures_test.go| new file mode 100644 |
| index 000000000..2e1eed07d |
| --- /dev/null |
| +++ b/internal/host/hadepartures_test.go |
| @@ -0,0 +1,88 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "path/filepath" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +type departureEmptyQueue struct{ calls atomic.Int32 } |
| + |
| +func (q *departureEmptyQueue) Receive(ctx context.Context, d time.Duration) ([]hadeparture.Message, error) { |
| + q.calls.Add(1) |
| + return nil, nil |
| +} |
| +func (q *departureEmptyQueue) Delete(context.Context, string) error { |
| + return errors.New("unexpected_delete") |
| +} |
| +func TestTerminationConsumerStartupBoundJournal(t *testing.T) { |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + var reads atomic.Int32 |
| + c, err := NewController(DepartureConfig{Registry: reg, Identities: &departureIdentities{Registry: reg}, Confirmer: &termfence.Confirmer{}, Cache: &termfence.ProofCache{}, Self: hadeparture.Box{Ref: "self", InstanceID: "i-0123456789abcdef0", Account: "111122223333", Scope: hadeparture.Scope{CloudRegion: "eu-west-1", DataBucket: "data", SecretsKeyFP: "fp"}}, DeploymentBucket: "deployment", Inventory: func() provision.InventorySnapshot { reads.Add(1); return provision.InventorySnapshot{} }, Policy: func() LocalPolicy { return LocalPolicy{} }}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + q := &departureEmptyQueue{} |
| + life, err := c.Start(t.Context(), func(context.Context) (hadeparture.Queue, error) { return q, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case <-life.Started(): |
| + case <-time.After(time.Second): |
| + t.Fatal("startup waited for inventory") |
| + } |
| + if !life.Running() || reads.Load() != 0 { |
| + t.Fatalf("startup running %v inventory %d", life.Running(), reads.Load()) |
| + } |
| + if _, err = c.Start(t.Context(), func(context.Context) (hadeparture.Queue, error) { return q, nil }); err == nil { |
| + t.Fatal("second receiver") |
| + } |
| + if err = life.Stop(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if q.calls.Load() != 1 || life.Running() { |
| + t.Fatalf("lifecycle calls %d running %v", q.calls.Load(), life.Running()) |
| + } |
| +} |
| +func TestDepartureCoverageIsolation(t *testing.T) { |
| + at := time.Now() |
| + scope := hadeparture.Scope{CloudRegion: "eu-west-1", Placement: "", DataBucket: "data", SecretsKeyFP: "fp"} |
| + p := LocalPolicy{Scope: scope, Pools: []string{"hapair"}} |
| + supported := provision.DepartureHost{Host: "shop.example.com", Kind: "instance", Placement: "", Pool: "hapair", Lifetime: "life", HA: true} |
| + if !CanAdopt(supported, p) { |
| + t.Fatal("hapair policy refused") |
| + } |
| + supported.Pool = "cohort1" |
| + if CanAdopt(supported, p) { |
| + t.Fatal("pool widened") |
| + } |
| + for _, pool := range []string{"", "hapair", "cohort1"} { |
| + h := provision.DepartureHost{Kind: "sidecar", Placement: "", Pool: pool} |
| + if !departureCoverageGap(h, scope) { |
| + t.Fatal("lockless sidecar hidden", pool) |
| + } |
| + h.Placement = "us" |
| + if departureCoverageGap(h, scope) { |
| + t.Fatal("foreign sidecar blocked departure") |
| + } |
| + } |
| + if CanCompleteDeparture(RescanResult{Inventory: provision.InventorySnapshot{Complete: true, WalkStartedAt: at.Add(time.Second), SourceReadStartedAt: at.Add(time.Second)}, EvidenceAt: at, Finished: true, Unresolved: 1}) { |
| + t.Fatal("unresolved certified complete") |
| + } |
| + cloud := boxid.Cloud{Provider: "aws", Account: "111122223333", Region: "eu-west-1", InstanceID: "i-0123456789abcdef0"} |
| + _ = cloud |
| +} |
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go| new file mode 100644 |
| index 000000000..c468fc091 |
| --- /dev/null |
| +++ b/internal/host/hadepartures_wiring.go |
| @@ -0,0 +1,181 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "log" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/awsterminations" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +const departureQueueEnv = "CARLOS_TERMINATION_QUEUE_URL" |
| +const departureBindingsEnv = "CARLOS_HA_FIXED_BOX_IDENTITIES" |
| + |
| +var boxDepartureInventory = &provision.DepartureInventory{} |
| + |
| +type departureArm struct { |
| + Getenv func(string) string |
| + Registry *registry.Registry |
| + Service *activator.Service |
| + Backend *activator.ExecBackend |
| + Confirmer *termfence.Confirmer |
| + Inventory *provision.DepartureInventory |
| + OpenStore func(context.Context) (release.Store, error) |
| + MakeQueue func(context.Context) (hadeparture.Queue, error) |
| + ProofStore func(context.Context, string, string) (termfence.ProofStore, error) |
| + Verifier boxid.Verifier |
| + Self hadeparture.Box |
| +} |
| + |
| +func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadeparture.Lifecycle, error) { |
| + enabled, _ := strconv.ParseBool(a.Getenv("CARLOS_REGION_HA")) |
| + if !enabled { |
| + return nil, nil, nil |
| + } |
| + started := time.Now() |
| + fail := func(stage string, err error) (*Controller, hadeparture.Lifecycle, error) { |
| + log.Printf("Termination recovery has not started: %s.", stage) |
| + return nil, nil, &hadeparture.InitError{Stage: stage, Err: err} |
| + } |
| + if a.Registry == nil || a.Service == nil || a.Backend == nil || a.Confirmer == nil || a.Inventory == nil || a.OpenStore == nil { |
| + return fail("dependencies", errDepartureScope) |
| + } |
| + if a.Getenv(departureQueueEnv) == "" && a.MakeQueue == nil { |
| + return fail("queue_setting", errDepartureScope) |
| + } |
| + if a.Self.Ref == "" { |
| + self := lease.CurrentSelf() |
| + a.Self = hadeparture.Box{Ref: self.Ref, InstanceID: self.IID, Account: self.Account, Scope: hadeparture.Scope{CloudRegion: self.Region, Placement: a.Getenv("CARLOS_REGION"), DataBucket: a.Backend.Cfg.Bucket, SecretsKeyFP: edgesFileSecretsFP(a.Getenv)}} |
| + } |
| + if !departureCloud(a.Self).Complete() || a.Self.Scope.DataBucket == "" || a.Self.Scope.SecretsKeyFP == "" || a.Self.Scope.DataBucket != a.Backend.Cfg.Bucket || a.Self.Scope.CloudRegion != a.Backend.Cfg.Region { |
| + return fail("identity", errDepartureScope) |
| + } |
| + fixed := map[string]string{a.Self.Ref: a.Self.InstanceID} |
| + if raw := a.Getenv(departureBindingsEnv); raw != "" { |
| + if json.Unmarshal([]byte(raw), &fixed) != nil || fixed == nil { |
| + return fail("identity_bindings", errDepartureIdentity) |
| + } |
| + if iid, ok := fixed[a.Self.Ref]; ok && iid != a.Self.InstanceID { |
| + return fail("identity_bindings", errDepartureIdentity) |
| + } |
| + fixed[a.Self.Ref] = a.Self.InstanceID |
| + } |
| + if a.Verifier.Certs == nil { |
| + certs, err := boxid.EmbeddedCerts() |
| + if err != nil { |
| + return fail("certificates", err) |
| + } |
| + a.Verifier = boxid.Verifier{Account: a.Self.Account, Certs: certs} |
| + } |
| + initCtx, cancel := context.WithDeadline(ctx, started.Add(hadeparture.InitializeTimeout)) |
| + defer cancel() |
| + store, err := a.OpenStore(initCtx) |
| + if err != nil { |
| + return fail("store", err) |
| + } |
| + repo := &departureIdentities{Registry: a.Registry, Store: store, Verifier: a.Verifier, Fixed: fixed, Region: a.Self.Scope.CloudRegion} |
| + cache := &termfence.ProofCache{} |
| + if a.ProofStore == nil { |
| + data, err := release.NewS3StoreIn(initCtx, a.Self.Scope.DataBucket, a.Self.Scope.CloudRegion) |
| + if err != nil { |
| + return fail("data_store", err) |
| + } |
| + a.ProofStore = func(_ context.Context, bucket, region string) (termfence.ProofStore, error) { |
| + if bucket != a.Self.Scope.DataBucket || region != a.Self.Scope.CloudRegion { |
| + return nil, errDepartureScope |
| + } |
| + return termfence.NewProofStore(data.Client), nil |
| + } |
| + } |
| + c, err := NewController(DepartureConfig{Registry: a.Registry, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy { |
| + return LocalPolicy{Scope: a.Self.Scope, Pools: provision.ParseBoxPools(a.Getenv("CARLOS_POOLS"))} |
| + }, Invalidate: a.Service.InvalidateDutyHolder, Page: func(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost) error { |
| + var messages []string |
| + for _, h := range hosts { |
| + messages = append(messages, fmt.Sprintf("Duties for sidecar %s cannot be recovered by this version. Keep the departure records. The departure stays open. Upgrading alone will not recover the sidecar.", h.Host)) |
| + } |
| + return PageOperator(ctx, alerting.LevelWarning, fmt.Sprintf("Duties from box %s need attention", d.Box.Ref), strings.Join(messages, "\n")) |
| + }}) |
| + if err != nil { |
| + return fail("controller", err) |
| + } |
| + makeQueue := a.MakeQueue |
| + if makeQueue == nil { |
| + makeQueue = func(ctx context.Context) (hadeparture.Queue, error) { |
| + cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(a.Self.Scope.CloudRegion), awsconfig.WithRetryMaxAttempts(1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return awsterminations.New(ctx, cfg, a.Getenv(departureQueueEnv), departureCloud(a.Self)) |
| + } |
| + } |
| + queue := func(ctx context.Context) (hadeparture.Queue, error) { |
| + bounded, cancel := context.WithDeadline(ctx, started.Add(hadeparture.InitializeTimeout)) |
| + defer cancel() |
| + return makeQueue(bounded) |
| + } |
| + if err = initCtx.Err(); err != nil { |
| + return fail("deadline", err) |
| + } |
| + // Install before workers start; a failed Start restores the prior callback. |
| + previous := a.Confirmer.OnConfirmed |
| + a.Confirmer.OnConfirmed = c.confirmed |
| + life, err := c.Start(ctx, queue) |
| + if err != nil { |
| + a.Confirmer.OnConfirmed = previous |
| + return nil, life, err |
| + } |
| + a.Backend.TerminationProofs = &lease.TerminationProofAdapter{Cache: cache, Confirmer: a.Confirmer, Resolve: repo.Proof, Lifetime: func(ctx context.Context, bucket, prefix, region string) (string, error) { |
| + if bucket != a.Backend.Cfg.Bucket || region != a.Backend.Cfg.Region { |
| + return "", errDepartureScope |
| + } |
| + host := strings.TrimPrefix(prefix, strings.Trim(a.Backend.Cfg.Prefix, "/")+"/") |
| + if a.Backend.Cfg.Prefix == "" { |
| + host = prefix |
| + } |
| + host = strings.TrimSuffix(host, "/") |
| + if activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) != prefix || !provision.ValidHostShape(host) { |
| + return "", errDepartureScope |
| + } |
| + snapshot := departureInventorySnapshot(a.Inventory) |
| + if !snapshot.Complete { |
| + return "", errDepartureIdentity |
| + } |
| + for _, h := range snapshot.Records { |
| + if h.Host == host && h.HA && h.Placement == a.Self.Scope.Placement && h.Lifetime != "" { |
| + return h.Lifetime, nil |
| + } |
| + } |
| + return "", errDepartureIdentity |
| + }} |
| + a.Service.AdoptionIdentity = func(ctx context.Context, ref, iid string) (bool, error) { |
| + o, known, err := repo.Resolve(ctx, ref, iid) |
| + return known && o.Known && !o.PlacementNull && o.Box.Account == a.Self.Account && o.Box.Scope == a.Self.Scope, err |
| + } |
| + return c, life, nil |
| +} |
| + |
| +func departureInventorySnapshot(inventory *provision.DepartureInventory) provision.InventorySnapshot { |
| + s := inventory.Snapshot() |
| + if view := armedRecordView.Load(); view != nil { |
| + if sn := view.Snapshot(); sn != nil && !strings.HasPrefix(s.Generation, fmt.Sprintf("%d/", sn.Epoch)) { |
| + s.Complete = false |
| + } |
| + } |
| + return s |
| +} |
diff --git a/internal/host/hadepartures_wiring_test.go b/internal/host/hadepartures_wiring_test.go| new file mode 100644 |
| index 000000000..d62221199 |
| --- /dev/null |
| +++ b/internal/host/hadepartures_wiring_test.go |
| @@ -0,0 +1,170 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "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/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +type departureProofStore struct { |
| + mu sync.Mutex |
| + body []byte |
| + gets, puts int |
| + bucket, key string |
| +} |
| + |
| +func (p *departureProofStore) GetObject(_ context.Context, in *s3.GetObjectInput, _ ...func(*s3.Options)) (*s3.GetObjectOutput, error) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + p.gets++ |
| + p.bucket = aws.ToString(in.Bucket) |
| + p.key = aws.ToString(in.Key) |
| + if p.body == nil { |
| + return nil, os.ErrNotExist |
| + } |
| + return &s3.GetObjectOutput{Body: io.NopCloser(strings.NewReader(string(p.body)))}, nil |
| +} |
| +func (p *departureProofStore) PutObject(_ context.Context, in *s3.PutObjectInput, _ ...func(*s3.Options)) (*s3.PutObjectOutput, error) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + if aws.ToString(in.IfNoneMatch) != "*" { |
| + return nil, errors.New("not_create_only") |
| + } |
| + p.puts++ |
| + p.bucket = aws.ToString(in.Bucket) |
| + p.key = aws.ToString(in.Key) |
| + p.body, _ = io.ReadAll(in.Body) |
| + return &s3.PutObjectOutput{}, nil |
| +} |
| +func departureArmFixture(t *testing.T) (departureArm, *departureProofStore, *int) { |
| + t.Helper() |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + s := boxidtest.NewSigner(t) |
| + store := release.NewDirStore(t.TempDir()) |
| + _, raw := s.Record(t, "dead", "111122223333", "eu-west-1", "i-1123456789abcdef0") |
| + if _, err = store.Put(t.Context(), boxid.Key("dead"), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + proof := &departureProofStore{} |
| + describes := 0 |
| + self := hadeparture.Box{Ref: "self", InstanceID: "i-0123456789abcdef0", Account: "111122223333", Scope: hadeparture.Scope{CloudRegion: "eu-west-1", DataBucket: "regional-data", SecretsKeyFP: "fp"}} |
| + confirmer := &termfence.Confirmer{Self: func() boxid.Cloud { return departureCloud(self) }, Logf: func(string, ...any) {}, API: func(context.Context, string) (termfence.EC2, error) { |
| + return describeInstances(func(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) { |
| + describes++ |
| + return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{OwnerId: aws.String(self.Account), Instances: []ec2types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: &ec2types.InstanceState{Name: ec2types.InstanceStateNameTerminated}}}}}}, nil |
| + }), nil |
| + }} |
| + env := map[string]string{"CARLOS_REGION_HA": "true", "CARLOS_DEPLOYMENT_BUCKET": "deployment-in-us-east-1", departureBindingsEnv: `{"dead":"i-1123456789abcdef0"}`} |
| + cfg := activator.Config{Bucket: "regional-data", Region: "eu-west-1", Prefix: "instances"} |
| + return departureArm{Getenv: func(k string) string { return env[k] }, Registry: reg, Service: &activator.Service{}, Backend: &activator.ExecBackend{Cfg: cfg}, Confirmer: confirmer, Inventory: &provision.DepartureInventory{}, OpenStore: func(context.Context) (release.Store, error) { return store, nil }, MakeQueue: func(context.Context) (hadeparture.Queue, error) { return &departureEmptyQueue{}, nil }, ProofStore: func(_ context.Context, b, r string) (termfence.ProofStore, error) { |
| + if b != cfg.Bucket || r != cfg.Region { |
| + t.Errorf("proof scope %s %s", b, r) |
| + } |
| + return proof, nil |
| + }, Verifier: boxid.Verifier{Account: self.Account, Certs: s.Certs()}, Self: self}, proof, &describes |
| +} |
| +func TestTerminationProofBucket(t *testing.T) { |
| + a, p, describes := departureArmFixture(t) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + c, life, err := armHADepartures(ctx, a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer life.Stop(t.Context()) |
| + select { |
| + case <-life.Started(): |
| + case <-time.After(time.Second): |
| + t.Fatal("startup") |
| + } |
| + o, err := c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = c.Enqueue(t.Context(), o); err != nil { |
| + t.Fatal(err) |
| + } |
| + if p.bucket != "regional-data" || !strings.HasPrefix(p.key, "control/terminations/v1/111122223333/eu-west-1/i-1123456789abcdef0/") || p.puts != 1 || *describes != 1 { |
| + t.Fatalf("proof %+v describes %d", p, *describes) |
| + } |
| + adapter := a.Backend.TerminationProofs |
| + if adapter == nil || adapter.Cache != c.cfg.Cache || adapter.Confirmer != a.Confirmer { |
| + t.Fatal("unshared adapter") |
| + } |
| + identity, err := adapter.Resolve(t.Context(), "dead", o.Box.InstanceID) |
| + if err != nil || identity.Bucket() != p.bucket || identity.Key() != p.key { |
| + t.Fatalf("acquire identity %+v %v", identity, err) |
| + } |
| + // Positive callback enrollment is idempotent, and needs no second Describe. |
| + if yes, err := a.Confirmer.Terminated(t.Context(), o.Box.InstanceID); err != nil || !yes { |
| + t.Fatalf("confirmation %v %v", yes, err) |
| + } |
| + pending, err := a.Registry.PendingDepartures(t.Context(), time.Now().Add(time.Hour), 32) |
| + if err != nil || len(pending) != 1 || *describes != 1 { |
| + t.Fatalf("pending %+v %v describes %d", pending, err, *describes) |
| + } |
| +} |
| +func TestHADepartureArmLifecycle(t *testing.T) { |
| + a, _, _ := departureArmFixture(t) |
| + a.Getenv = func(string) string { return "" } |
| + if c, l, e := armHADepartures(t.Context(), a); c != nil || l != nil || e != nil || a.Backend.TerminationProofs != nil { |
| + t.Fatal("disabled changed behavior") |
| + } |
| + a, _, _ = departureArmFixture(t) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + c, l, e := armHADepartures(ctx, a) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + observer := l |
| + select { |
| + case <-observer.Started(): |
| + case <-time.After(time.Second): |
| + t.Fatal("observer did not start") |
| + } |
| + if _, e = c.Start(ctx, a.MakeQueue); e == nil { |
| + t.Fatal("second receiver") |
| + } |
| + cancel() |
| + select { |
| + case <-l.Done(): |
| + case <-time.After(time.Second): |
| + t.Fatal("parent cancellation not joined") |
| + } |
| + if l.Running() { |
| + t.Fatal("cancelled running") |
| + } |
| + source, err := os.ReadFile("agent.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body := string(source) |
| + arm := strings.Index(body, "armHADepartures(agentCtx,") |
| + start := strings.Index(body, "Start: svc.Start,") |
| + if arm < 0 || start < arm || strings.Count(body, "armHADepartures(") != 1 { |
| + t.Fatal("agent arm order/count") |
| + } |
| +} |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index aeef72cd6..77512fc30 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -93,6 +93,7 @@ var Optional = []string{ |
| "CARLOS_S3_QUIRKS", |
| "CARLOS_STEERING_ZONE_ID", |
| "CARLOS_SWAP", |
| + "CARLOS_TERMINATION_QUEUE_URL", |
| "CARLOS_UNIT_SETTLE", |
| "CARLOS_VERSIONS_GRACE", |
| "CARLOS_WILDCARD_DOMAINS", |
diff --git a/internal/lease/termination_proof.go b/internal/lease/termination_proof.go| index 81851b064..1899d88cb 100644 |
| --- a/internal/lease/termination_proof.go |
| +++ b/internal/lease/termination_proof.go |
| @@ -59,9 +59,17 @@ func bindTerminationProof(ctx context.Context, client *s3.Client, bucket, prefix |
| 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 |
| } |
| + notify := func() (bool, error) { |
| + if adapter.Confirmer != nil && adapter.Confirmer.OnConfirmed != nil { |
| + if err := adapter.Confirmer.OnConfirmed(ctx, iid); err != nil { |
| + return false, err |
| + } |
| + } |
| + return currentLifetime() |
| + } |
| _, found, readErr := adapter.Cache.Load(ctx, termfence.NewProofStore(client), binding) |
| if found && readErr == nil { |
| - return currentLifetime() |
| + return notify() |
| } |
| if adapter.Confirmer == nil { |
| return false, readErr |
| @@ -70,7 +78,7 @@ func bindTerminationProof(ctx context.Context, client *s3.Client, bucket, prefix |
| if err != nil { |
| return false, errors.Join(readErr, err) |
| } |
| - return currentLifetime() |
| + return notify() |
| } |
| return p |
| } |
diff --git a/internal/lease/termination_proof_test.go b/internal/lease/termination_proof_test.go| index d41781684..ee9c8055d 100644 |
| --- a/internal/lease/termination_proof_test.go |
| +++ b/internal/lease/termination_proof_test.go |
| @@ -233,3 +233,41 @@ func TestTerminationProofRequestBudget(t *testing.T) { |
| t.Fatalf("GET=%d Describe=%d", proofGets(), api.calls) |
| } |
| } |
| + |
| +func TestRequestConfirmationEnqueuesFromAcquire(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) |
| + 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) |
| + } |
| + api := &proofEC2{} |
| + notified := 0 |
| + confirmer := &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) {}, OnConfirmed: func(context.Context, string) error { |
| + notified++ |
| + if notified == 1 { |
| + return errors.New("journal_offline") |
| + } |
| + return nil |
| + }} |
| + adapter := &TerminationProofAdapter{Cache: &termfence.ProofCache{}, 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 }} |
| + client, _, err := newLeaserClient(t.Context(), me.Region) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + view := hafresh.View{Lock: hafresh.Lock{Owner: hafresh.OwnerFor(hafresh.Self{Ref: "departed", IID: "i-1123456789abcdef0"}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)}} |
| + p := bindTerminationProof(WithTerminationProof(t.Context(), adapter), client, fx.Bucket, "instances/shop", me.Region, hafresh.Marker{Lifetime: "life"}, me, view, hafresh.Proofs{}) |
| + if yes, err := p.OwnerTerminated("i-1123456789abcdef0"); yes || err == nil || notified != 1 { |
| + t.Fatalf("journal failure yes=%v err=%v notifications=%d", yes, err, notified) |
| + } |
| + if yes, err := p.OwnerTerminated("i-1123456789abcdef0"); !yes || err != nil || notified != 2 || api.calls != 1 { |
| + t.Fatalf("cached retry yes=%v err=%v notifications=%d describes=%d", yes, err, notified, api.calls) |
| + } |
| +} |
diff --git a/internal/objstore/termination_credentials_test.go b/internal/objstore/termination_credentials_test.go| new file mode 100644 |
| index 000000000..27065dea4 |
| --- /dev/null |
| +++ b/internal/objstore/termination_credentials_test.go |
| @@ -0,0 +1,62 @@ |
| +package objstore |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestTerminationProofCredentials(t *testing.T) { |
| + // CopyObject and multipart completion authorize the destination through |
| + // PutObject too. The inline policy must refuse it even if the deployment's |
| + // store prefix causes the permissions boundary to match the data bucket. |
| + const proof = "arn:aws:s3:::regional-data/control/terminations/v1/111122223333/eu-west-1/i-1123456789abcdef0/digest.json" |
| + for _, deny := range []bool{false, true} { |
| + var p policyDocument |
| + if err := json.Unmarshal([]byte(storePolicyJSON("arn:aws:s3:::tenant-store", nil, deny)), &p); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, op := range []string{"s3:PutObject", "s3:GetObject", "s3:DeleteObject", "s3:PutObjectTagging"} { |
| + allowed := false |
| + for _, s := range p.Statement { |
| + if s.Effect != "Allow" { |
| + continue |
| + } |
| + action := false |
| + for _, a := range s.Action { |
| + if a == op || a == "s3:*" || a == "*" { |
| + action = true |
| + } |
| + } |
| + resource, _ := filepath.Match(s.Resource, proof) |
| + if strings.HasSuffix(s.Resource, "/*") { |
| + resource = strings.HasPrefix(proof, strings.TrimSuffix(s.Resource, "*")) |
| + } |
| + allowed = allowed || (action && resource) |
| + } |
| + if allowed { |
| + t.Fatalf("store/app credential permits %s on proof", op) |
| + } |
| + } |
| + } |
| + raw, err := os.ReadFile("../../infra/modules/region-host/main.tf") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tf := string(raw) |
| + start := strings.Index(tf, `resource "aws_iam_policy" "store_user_boundary"`) |
| + end := strings.Index(tf[start:], `resource "aws_iam_role_policy" "host_store"`) |
| + if start < 0 || end < 0 { |
| + t.Fatal("boundary missing") |
| + } |
| + boundary := tf[start : start+end] |
| + if !strings.Contains(boundary, `Resource = "arn:aws:s3:::${var.store_bucket_prefix}*/*"`) { |
| + t.Fatal("store boundary changed; re-evaluate intersection") |
| + } |
| + // The box's own data-bucket object grant covers the proof and its locks. |
| + if !strings.Contains(tf, `Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"]`+"\n Resource = [\n \"${var.deployment_bucket_arn}/*\",\n \"${var.data_bucket_arn}/*\",") { |
| + t.Fatal("trusted box data grant changed") |
| + } |
| +} |
diff --git a/internal/provision/departure_inventory.go b/internal/provision/departure_inventory.go| index f73864e1c..a1f862317 100644 |
| --- a/internal/provision/departure_inventory.go |
| +++ b/internal/provision/departure_inventory.go |
| @@ -100,7 +100,7 @@ func (p *DeparturePass) family(kind string, hosts []DepartureHost, complete bool |
| } |
| func departureInstance(rec Record, raw []byte) (DepartureHost, bool) { |
| life, err := LifetimeEntryOf(rec) |
| - return DepartureHost{Account: rec.Account, App: rec.App, Host: rec.Host, Kind: rec.Kind, Placement: rec.Region, Pool: rec.Pool, Lifetime: life.ID, Revision: fmt.Sprintf("%x", sha256.Sum256(raw)), HA: rec.HA}, err == nil && !departureNullRegion(raw) |
| + return DepartureHost{Account: rec.Account, App: rec.App, Host: rec.Host, Kind: rec.KindOrDefault(), Placement: rec.Region, Pool: rec.Pool, Lifetime: life.ID, Revision: fmt.Sprintf("%x", sha256.Sum256(raw)), HA: rec.HA}, err == nil && !departureNullRegion(raw) |
| } |
| func departureSidecar(rec SidecarRecord, raw []byte) (DepartureHost, bool) { |
| life, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
diff --git a/internal/provision/departure_inventory_test.go b/internal/provision/departure_inventory_test.go| index 518f6f4d1..bb037ab28 100644 |
| --- a/internal/provision/departure_inventory_test.go |
| +++ b/internal/provision/departure_inventory_test.go |
| @@ -1,6 +1,7 @@ |
| package provision |
| import ( |
| + "github.com/carlosframework/platform/internal/release" |
| "testing" |
| "time" |
| ) |
| @@ -60,3 +61,39 @@ func TestDepartureInventoryAfterEvidence(t *testing.T) { |
| t.Fatal("mutable snapshot") |
| } |
| } |
| + |
| +func TestDepartureInventorySourceRefresh(t *testing.T) { |
| + s := dirStore(t) |
| + sqid := writeAccountManifest(t, s, acctID, "Shop") |
| + reg := regWith(t) |
| + defer reg.Close() |
| + view := NewRecordView(s, release.NewChangeWatch(s)) |
| + if err := view.Rebuild(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + old := view.Snapshot() |
| + evidence := time.Now() |
| + rec := Record{Schema: 1, Host: "shop.example.com", Slug: "shop", App: "shop", Account: sqid, Channel: "edge", Pool: "hapair", HA: true, CreatedAt: time.Now()} |
| + if err := CreateRecord(ctx, s, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + inv := &DepartureInventory{} |
| + pass := inv.Begin("old", time.Now(), old.SourceReadStartedAt, old.Complete) |
| + cfg := ReconcileConfig{DataDir: t.TempDir(), Departures: pass} |
| + _ = Reconcile(ctx, old.Store(s), reg, cfg) |
| + _ = ReconcileSidecars(ctx, old.Store(s), reg, cfg) |
| + if inv.Snapshot().FreshAfter(evidence) { |
| + t.Fatal("post-evidence pass over old source certified fresh") |
| + } |
| + if err := view.Rebuild(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + fresh := view.Snapshot() |
| + cfg.Departures = inv.Begin("fresh", time.Now(), fresh.SourceReadStartedAt, fresh.Complete) |
| + _ = Reconcile(ctx, fresh.Store(s), reg, cfg) |
| + _ = ReconcileSidecars(ctx, fresh.Store(s), reg, cfg) |
| + snap := inv.Snapshot() |
| + if !snap.FreshAfter(evidence) || len(snap.Records) != 1 || snap.Records[0].Host != rec.Host || snap.Records[0].Kind != "instance" { |
| + t.Fatalf("fresh inventory %+v", snap) |
| + } |
| +} |
diff --git a/internal/registry/ha_journal.go b/internal/registry/ha_journal.go| index e5fc25c69..eafe25af4 100644 |
| --- a/internal/registry/ha_journal.go |
| +++ b/internal/registry/ha_journal.go |
| @@ -61,6 +61,7 @@ func (r *Registry) migrateHAJournal() error { |
| CREATE TABLE IF NOT EXISTS ha_termination_inbox(key TEXT PRIMARY KEY,message_id TEXT NOT NULL,body BLOB NOT NULL CHECK(length(body)<=65536),received INTEGER NOT NULL,next_attempt INTEGER NOT NULL,last_error TEXT NOT NULL DEFAULT ''); |
| CREATE TABLE IF NOT EXISTS ha_departures(id TEXT PRIMARY KEY,body BLOB NOT NULL,phase TEXT NOT NULL DEFAULT 'pending',next_attempt INTEGER NOT NULL,last_page INTEGER NOT NULL DEFAULT 0,last_error TEXT NOT NULL DEFAULT ''); |
| CREATE TABLE IF NOT EXISTS ha_box_identities(ref TEXT PRIMARY KEY,iid TEXT NOT NULL UNIQUE,body BLOB NOT NULL); |
| + CREATE TABLE IF NOT EXISTS ha_confirmation_retries(ref TEXT PRIMARY KEY,next_attempt INTEGER NOT NULL,attempts INTEGER NOT NULL); |
| CREATE TABLE IF NOT EXISTS ha_identity_walk(id INTEGER PRIMARY KEY CHECK(id=1),body BLOB NOT NULL); |
| `) |
| return err |
| @@ -121,12 +122,74 @@ func (r *Registry) SaveHAIdentityWalk(ctx context.Context, w HAIdentityWalk) err |
| _, err := r.haJournal(ctx, haJournalRequest{Op: "walk_save", Walk: w}) |
| return err |
| } |
| +func (r *Registry) ReobserveDeparture(ctx context.Context, id string, at time.Time) error { |
| + _, err := r.haJournal(ctx, haJournalRequest{Op: "reobserve", ID: id, At: at}) |
| + return err |
| +} |
| +func (r *Registry) ClaimHAConfirmation(ctx context.Context, ref string, at time.Time) (bool, error) { |
| + out, err := r.haJournal(ctx, haJournalRequest{Op: "confirmation", ID: ref, At: at}) |
| + return out.Found, err |
| +} |
| + |
| func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJournalResponse, err error) { |
| if r.remote != nil { |
| resp, e := r.remote.call(ctx, remoteRequest{Method: "HAJournal", HAJournal: q}, nil) |
| return resp.HAJournal, e |
| } |
| switch q.Op { |
| + case "reobserve": |
| + tx, e := r.beginClaimTransaction(ctx, true) |
| + if e != nil { |
| + return out, e |
| + } |
| + defer tx.Rollback() |
| + var body []byte |
| + if e = tx.QueryRowContext(ctx, `SELECT body FROM ha_departures WHERE id=? AND phase<>'complete'`, q.ID).Scan(&body); e != nil { |
| + return out, e |
| + } |
| + var d HADeparture |
| + if e = json.Unmarshal(body, &d); e != nil { |
| + return out, e |
| + } |
| + if q.At.IsZero() || q.At.Before(d.ObservedAt) { |
| + return out, ErrHAJournal |
| + } |
| + d.ObservedAt = q.At |
| + d.InventoryGeneration = "" |
| + d.Phase = "pending" |
| + body, e = json.Marshal(d) |
| + if e != nil { |
| + return out, e |
| + } |
| + if _, e = tx.ExecContext(ctx, `UPDATE ha_departures SET body=?,phase='pending' WHERE id=?`, body, q.ID); e != nil { |
| + return out, e |
| + } |
| + err = tx.Commit() |
| + |
| + case "confirmation": |
| + tx, e := r.beginClaimTransaction(ctx, true) |
| + if e != nil { |
| + return out, e |
| + } |
| + defer tx.Rollback() |
| + var next int64 |
| + var attempts int |
| + e = tx.QueryRowContext(ctx, `SELECT next_attempt,attempts FROM ha_confirmation_retries WHERE ref=?`, q.ID).Scan(&next, &attempts) |
| + if e != nil && !errors.Is(e, sql.ErrNoRows) { |
| + return out, e |
| + } |
| + if journalTime(q.At) < next { |
| + return out, nil |
| + } |
| + waits := []time.Duration{30 * time.Second, time.Minute, 2 * time.Minute, 5 * time.Minute} |
| + wait := waits[min(attempts, 3)] |
| + _, e = tx.ExecContext(ctx, `INSERT INTO ha_confirmation_retries(ref,next_attempt,attempts) VALUES(?,?,?) ON CONFLICT(ref) DO UPDATE SET next_attempt=excluded.next_attempt,attempts=excluded.attempts`, q.ID, journalTime(q.At.Add(wait)), min(attempts+1, 3)) |
| + if e != nil { |
| + return out, e |
| + } |
| + err = tx.Commit() |
| + out.Found = err == nil |
| + |
| case "record": |
| if q.ID == "" || len(q.ID) > 1024 || len(q.Body) > hadeparture.MaxBodyBytes || q.At.IsZero() { |
| return out, ErrHAJournal |
diff --git a/internal/registry/ha_journal_test.go b/internal/registry/ha_journal_test.go| index acc780c3e..8189b35ae 100644 |
| --- a/internal/registry/ha_journal_test.go |
| +++ b/internal/registry/ha_journal_test.go |
| @@ -123,3 +123,39 @@ func TestDepartureIdentityPersistence(t *testing.T) { |
| t.Fatalf("reopen %+v %v %v", got, ok, err) |
| } |
| } |
| + |
| +func TestDepartureAgeRetryBudget(t *testing.T) { |
| + r, _ := adoptRegistry(t) |
| + ctx := context.Background() |
| + raw := []byte("verified") |
| + b := HABoxIdentity{Ref: "box", IID: "i-12345678", Account: "111122223333", Region: "eu-west-1", Raw: raw, Digest: fmt.Sprintf("%x", sha256.Sum256(raw))} |
| + if err := r.SaveHAIdentity(ctx, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now() |
| + for _, wait := range []time.Duration{30 * time.Second, 60 * time.Second, 120 * time.Second, 300 * time.Second, 300 * time.Second} { |
| + if ok, err := r.ClaimHAConfirmation(ctx, b.Ref, now); err != nil || !ok { |
| + t.Fatalf("due %v %v", ok, err) |
| + } |
| + if ok, err := r.ClaimHAConfirmation(ctx, b.Ref, now.Add(wait-time.Nanosecond)); err != nil || ok { |
| + t.Fatalf("early %v %v", ok, err) |
| + } |
| + now = now.Add(wait) |
| + } |
| +} |
| + |
| +func TestDepartureResumeRequiresFreshEvidence(t *testing.T) { |
| + r, _ := adoptRegistry(t) |
| + at := time.Now() |
| + d := HADeparture{Departure: hadeparture.Departure{ID: "departure", Box: hadeparture.Box{Ref: "box", InstanceID: "i-12345678"}, ObservedAt: at}, ProofKey: "proof", ProofDigest: "digest"} |
| + if err := r.EnrollDeparture(t.Context(), d, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := r.ReobserveDeparture(t.Context(), d.ID, at.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := r.PendingDepartures(t.Context(), at.Add(2*time.Hour), 32) |
| + if err != nil || len(rows) != 1 || !rows[0].ObservedAt.Equal(at.Add(time.Hour)) { |
| + t.Fatalf("resume %+v %v", rows, err) |
| + } |
| +} |