package hostops import ( "context" "encoding/json" "errors" "testing" "time" "github.com/carlosframework/platform/internal/hostclaim" ) // wakeResetFixture builds a serving claim whose holder has an attempting // wake-retry episode, as a reset finds it after StopAttempt. func wakeResetFixture(t *testing.T) (*ControlWriter, hostclaim.Observed, func() time.Time) { t.Helper() w, raw, clock := testWriter(t) ctx := t.Context() seedAdmission(t, raw, "bab", "demo", openAdmission("app")) host := "x.example" nh := hostclaim.NewHolder{Family: "instance", Key: "apps/bab/demo/instances/x.example.json", Account: "bab", App: "demo", Host: host, Region: "ie", RecordRegion: "ie", CreatedAt: clock()} record := []byte(`{"schema":1,"host":"x.example","account":"bab","app":"demo","region":"ie","created_at":"2026-10-07T12:00:00Z"}`) o, err := hostclaim.Read(ctx, raw, host) if err != nil { t.Fatal(err) } for _, tr := range []func(*hostclaim.Claim) error{ hostclaim.BeginCreate(nh, record, "create", "console", clock()), hostclaim.CompleteCreate("create", "box"), } { if o, err = hostclaim.Update(ctx, raw, o, tr); err != nil { t.Fatal(err) } } attempt := hostclaim.WakeRetryAttempt{ID: "a1", Box: "box", Enrollment: "enr", BootID: "boot", ControllerID: "ctl", InvocationID: "inv", LaunchInputs: "in"} if o, err = hostclaim.Update(ctx, raw, o, hostclaim.ReserveWakeRetryAttempt(hostclaim.WakeRetryReservation{HolderIncarnation: o.Claim.Holder.Incarnation, EpisodeID: "ep1", Attempt: attempt, Now: clock()})); err != nil { t.Fatal(err) } return w, o, clock } // claimStep returns the exact before and after bytes of one transition on // o, as hostclaim.Update would write them. func claimStep(t *testing.T, o hostclaim.Observed, tr func(*hostclaim.Claim) error) MutationTarget { t.Helper() before, err := json.Marshal(o.Claim) if err != nil { t.Fatal(err) } var next hostclaim.Claim if err := json.Unmarshal(before, &next); err != nil { t.Fatal(err) } if err := tr(&next); err != nil { t.Fatal(err) } next.Gen++ after, err := json.Marshal(&next) if err != nil { t.Fatal(err) } return MutationTarget{Method: "Put", Key: "control/hosts/" + o.Host + ".json", Before: before, After: after} } func registerFor(t *testing.T, w *ControlWriter, o hostclaim.Observed, id, kind, incarnation string, clock func() time.Time) context.Context { t.Helper() h, err := w.RegisterStart(t.Context(), "bab", "demo", "app", id, Registration{Kind: kind, Host: o.Host, Owner: testOwner, AppID: "app", Epoch: 1, Claim: SavedObservation(o), Incarnation: incarnation, CreatedAt: clock()}, clock()) if err != nil { t.Fatal(err) } return h.Lifecycle(t.Context()) } func resetStep(incarnation, observed, episode, request string) func(*hostclaim.Claim) error { return hostclaim.ResetWakeRetry(hostclaim.WakeRetryReset{HolderIncarnation: incarnation, ObservedEpisode: observed, NewEpisodeID: episode, OperatorRequest: request, AttemptSettled: true}) } // R2: a reset-wake-retry registration's lifecycle grant admits only the // exact ResetWakeRetry transition for its registered holder incarnation. // Any other same-app claim write under it is refused. func TestPlan9C2ResetGrantAdmitsOnlyResetWakeRetry(t *testing.T) { w, o, clock := wakeResetFixture(t) inc := o.Claim.Holder.Incarnation ctx := registerFor(t, w, o, "reset", RegistrationWakeRetryReset, inc, clock) cases := []struct { name string tr func(*hostclaim.Claim) error admit bool }{ {"exact reset", resetStep(inc, "ep1", "ep2", "req"), true}, {"generation only", func(*hostclaim.Claim) error { return nil }, false}, {"stamp bump", func(c *hostclaim.Claim) error { c.Holder.Stamp++; return nil }, false}, {"reset plus stamp", func(c *hostclaim.Claim) error { if err := resetStep(inc, "ep1", "ep2", "req")(c); err != nil { return err } c.Holder.Stamp++ return nil }, false}, {"reset plus retired incarnation", func(c *hostclaim.Claim) error { if err := resetStep(inc, "ep1", "ep2", "req")(c); err != nil { return err } c.RetiredIncarnations = append(c.RetiredIncarnations, "old") return nil }, false}, {"drop wake retry", func(c *hostclaim.Claim) error { c.Holder.WakeRetry = nil; return nil }, false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { err := authorizeClaimWrite(ctx, w.raw, o.Host, claimStep(t, o, tc.tr)) if tc.admit && err != nil { t.Fatalf("exact reset refused: %v", err) } if !tc.admit && !errors.Is(err, ErrPending) { t.Fatalf("reset grant admitted %s: %v", tc.name, err) } }) } } // R2: the reset grant is bound to the incarnation the registration saved, // not to whichever holder the claim names at write time. func TestPlan9C2ResetGrantRefusesOtherIncarnation(t *testing.T) { w, o, clock := wakeResetFixture(t) ctx := registerFor(t, w, o, "reset", RegistrationWakeRetryReset, "some-other-incarnation", clock) err := authorizeClaimWrite(ctx, w.raw, o.Host, claimStep(t, o, resetStep(o.Claim.Holder.Incarnation, "ep1", "ep2", "req"))) if !errors.Is(err, ErrPending) { t.Fatalf("reset grant admitted a reset for an unregistered incarnation: %v", err) } } // R2 keeps every other registration kind's grant as main has it. func TestPlan9C2OtherKindsKeepSameAppGrant(t *testing.T) { w, o, clock := wakeResetFixture(t) ctx := registerFor(t, w, o, "create2", "create", o.Claim.Holder.Incarnation, clock) if err := authorizeClaimWrite(ctx, w.raw, o.Host, claimStep(t, o, func(*hostclaim.Claim) error { return nil })); err != nil { t.Fatalf("create grant lost its same-app write: %v", err) } } // 5-M10: a host-census report needs no lifecycle grant, but only as a // create-only Put. Authenticity is the reader's: ProductionAuthority.census // verifies each report against the roster's per-box census key (see the // forged-report case in TestReconcileFrozenBackfillRepairsLegacyHolder). func TestPlan9C2CensusReportsAreCreateOnlyWithoutGrant(t *testing.T) { w, raw, _ := testWriter(t) key := "control/host-census/res/box.json" for _, tc := range []struct { name string t MutationTarget ok bool }{ {"create", MutationTarget{Method: "Put", Key: key, After: []byte(`{}`)}, true}, {"overwrite", MutationTarget{Method: "Put", Key: key, ETag: "tag", After: []byte(`{}`)}, false}, {"delete", MutationTarget{Method: "Delete", Key: key, ETag: "tag"}, false}, } { family, matched, err := lifecycleFamily(t.Context(), raw, w, tc.t) if !matched || (tc.ok && (err != nil || family != "lifecycle-census")) || (!tc.ok && !errors.Is(err, ErrIdentity)) { t.Fatalf("%s: %q %v %v", tc.name, family, matched, err) } } }