package provision import ( "context" "errors" "fmt" "net/http" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/alta/console" "amadan.net/oficina/alta/homeop" "github.com/go-json-experiment/json/jsontext" ) // fakeObserver is the CARLOS half as the engine meets it: it answers a // fixed observation, or refuses. type fakeObserver struct { mu sync.Mutex obs Observation err error calls []string } func (f *fakeObserver) Observe(_ context.Context, app, team string) (Observation, error) { f.mu.Lock() defer f.mu.Unlock() f.calls = append(f.calls, app+"/"+team) if f.err != nil { return Observation{}, f.err } return f.obs, nil } func (f *fakeObserver) set(err error) { f.mu.Lock() defer f.mu.Unlock() f.err = err } func (f *fakeObserver) count() int { f.mu.Lock() defer f.mu.Unlock() return len(f.calls) } // testRefusal is a refusal as adopt.Refusal answers it. type testRefusal struct{ codes []string } func (r *testRefusal) Error() string { return "refused" } func (r *testRefusal) RefusalCodes() []string { return r.codes } var goodObservation = Observation{AppVersion: "v1.4.0", ArtifactDigest: artifactDigest("v1.4.0"), EnvironmentBinding: artifactDigest("binding")} func newObserver() *fakeObserver { return &fakeObserver{obs: goodObservation} } // offline is a transport that counts every request and answers none: the // console and the instances' own origins as an adoption must never meet // them. type offline struct { mu sync.Mutex n int } func (o *offline) RoundTrip(*http.Request) (*http.Response, error) { o.mu.Lock() defer o.mu.Unlock() o.n++ return nil, errors.New("offline: an adoption made a network call") } func (o *offline) count() int { o.mu.Lock() defer o.mu.Unlock() return o.n } type adoptHarness struct { *harness net *offline } // newAdoption is an initialized Home whose env manifest holds the six // canonical consumers, as production's HOME_CONSUMERS does. func newAdoption(t *testing.T, apps ...string) *adoptHarness { t.Helper() h := newHarness(t) h.initialized() if len(apps) == 0 { apps = Slugs() } for _, a := range apps { h.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a)) } return &adoptHarness{harness: h, net: &offline{}} } // engine is Alta's engine as alta-adopt builds it: no console or public // network at all, and the given Observer (nil for none). func (a *adoptHarness) adopter(hook func(string) error, obs Observer) *Engine { e := a.engine(hook) e.cfg.Observer = obs e.cfg.Console = &console.Client{HTTP: &http.Client{Transport: a.net}, Base: "https://console.invalid", Account: account, Tokens: a.tokens} e.cfg.Public = &http.Client{Transport: a.net} return e } func (a *adoptHarness) proposed() string { a.t.Helper() ins, o, _ := a.engine(nil).cfg.Home.Inspect(a.ctx(), homeop.Directory) if o != homeop.OK || ins.TeamSQID == "" { a.t.Fatalf("inspect %v", o) } return ins.TeamSQID } // planA runs Plan A to its end. func (a *adoptHarness) planA(e *Engine) int64 { a.t.Helper() run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary) if err != nil { a.t.Fatal(err) } a.confirm(homeop.KindCreateTeam) if r := a.drive(e, run, 20); r.State != "done" || r.Code != "awaiting-configuration" { a.t.Fatalf("plan A %s %s", r.State, r.Code) } return run } // activate starts and confirms a Plan B/C run once Plan A's windows have // closed. func (a *adoptHarness) activate(e *Engine, apps ...string) int64 { a.t.Helper() a.tick(homeop.WindowLifetime * time.Second) run, err := e.ActivateAdopted(a.ctx(), apps) if err != nil { a.t.Fatal(err) } a.confirm(homeop.KindAddApps) return run } func (a *adoptHarness) plans(run int64) map[string]homeop.Plan { a.t.Helper() r, err := a.store.Run(a.ctx(), run) if err != nil { a.t.Fatal(err) } subs, err := a.store.Plans(a.ctx(), r.PlanID) if err != nil { a.t.Fatal(err) } out := map[string]homeop.Plan{} for role, s := range subs { raw, err := homeop.EnvelopePayload(s.Signed) if err != nil { a.t.Fatalf("%s plan: %v", role, err) } var p homeop.Plan if err := homeop.Decode(raw, &p); err != nil { a.t.Fatalf("%s plan: %v", role, err) } out[role] = p } return out } // signed decodes the operation input of the last request Alta holds for // app's purpose. func (a *adoptHarness) signed(app, purpose string, v any) homeop.Authorization { a.t.Helper() req, ok, err := a.store.LastRequest(a.ctx(), AdoptionLabel, app, purpose) if err != nil || !ok { a.t.Fatalf("no %s request for %s: %v", purpose, app, err) } var w struct { Version int `json:"version"` Authorization jsontext.Value `json:"signed_authorization"` Input jsontext.Value `json:"operation_input"` } if err := homeop.Decode(req.Bytes, &w); err != nil { a.t.Fatal(err) } if err := homeop.Decode(w.Input, v); err != nil { a.t.Fatal(err) } r, err := homeop.ReadRequest(req.Bytes) if err != nil { a.t.Fatal(err) } return r.Authorization } func (a *adoptHarness) evidence(app string) homeop.ActivationEvidence { a.t.Helper() var in homeop.ActivationInput a.signed(app, "activate", &in) return in.Evidence } func (a *adoptHarness) step(app, name string) Step { a.t.Helper() s, ok, err := a.store.Step(a.ctx(), AdoptionLabel, app, name) if err != nil || !ok { a.t.Fatalf("no %s step for %s: %v", name, app, err) } return s } // onceEach: no committed operation repeats beyond its exact replays, // which Requests never lists. func onceEach(t *testing.T, reqs []string) { t.Helper() seen := map[string]int{} for _, r := range reqs { if seen[r]++; seen[r] > 1 { t.Fatalf("%s committed twice: %v", r, reqs) } } } func countOf(reqs []string, entry string) int { n := 0 for _, r := range reqs { if r == entry { n++ } } return n } func failCode(t *testing.T, err error, code string) { t.Helper() var fl *Fail if !errors.As(err, &fl) || fl.Code != code { t.Fatalf("got %v, want failed: %s", err, code) } } func TestAdoptionPlanACarriesExistingTeamOnBothRoles(t *testing.T) { a := newAdoption(t) e := a.adopter(nil, nil) _, err := e.StartAdoption(a.ctx(), "Oficina team", ownerCanary) failCode(t, err, "name-not-oficina") _, err = e.StartAdoption(a.ctx(), "Oficina", "Paul <"+ownerCanary+">") failCode(t, err, "owner-shape") if used, _ := a.store.LabelUsed(a.ctx(), AdoptionLabel); used { t.Fatal("a refused start recorded the team") } proposed := a.proposed() run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } if r, _ := a.store.Run(a.ctx(), run); !r.Adoption || r.Kind != homeop.KindCreateTeam || r.Label != AdoptionLabel || strings.Join(r.Apps, ",") != strings.Join(Slugs(), ",") { t.Fatalf("run %+v", r) } checkA := func(plans map[string]homeop.Plan) { t.Helper() if len(plans) != 2 { t.Fatalf("roles %d", len(plans)) } for role, p := range plans { if p.ExistingTeam != proposed || p.Kind != homeop.KindCreateTeam || strings.Join(p.Apps, ",") != strings.Join(Slugs(), ",") { t.Fatalf("%s plan existing %q kind %s apps %v", role, p.ExistingTeam, p.Kind, p.Apps) } } if d := plans[homeop.Directory]; d.Label != AdoptionLabel || d.DisplayName != "Oficina" || d.Owner != "" { t.Fatal("directory plan fields") } if c := plans[homeop.Credential]; c.Owner != ownerCanary || c.Label != "" || c.DisplayName != "" { t.Fatal("credential plan fields") } } first := a.plans(run) checkA(first) _, err = e.StartAdoption(a.ctx(), "Oficina", ownerCanary) failCode(t, err, "label-used") // Unconfirmed until it expired: a fresh plan binds the same team. a.tick((homeop.PlanLifetime + 1) * time.Second) if err := e.Resubmit(a.ctx(), run); err != nil { t.Fatal(err) } again := a.plans(run) if again[homeop.Directory].PlanID == first[homeop.Directory].PlanID { t.Fatal("resubmit reused the expired plan") } checkA(again) a.confirm(homeop.KindCreateTeam) if r := a.drive(e, run, 20); r.State != "done" || r.Code != "awaiting-configuration" { t.Fatalf("plan A %s %s", r.State, r.Code) } // The address went with the seed: no input, no owner-seed request, no // credential plan bytes, nowhere in the files. var n int _ = a.store.DB().QueryRow("SELECT (SELECT count(*) FROM owner_inputs)+(SELECT count(*) FROM operator_requests WHERE action='credential.owner-seed')+(SELECT count(*) FROM plan_submissions WHERE role='credential' AND sealed_plan IS NOT NULL)").Scan(&n) if n != 0 { t.Fatalf("%d rows still carry the owner", n) } _, _ = a.store.DB().Exec("PRAGMA wal_checkpoint(TRUNCATE)") if a.scan(ownerCanary) || strings.Contains(a.logs.String(), ownerCanary) { t.Fatal("the owner's address survives the seed") } // Plan B: add-apps on both roles, the seeded team, no owner. team, _ := a.store.Team(a.ctx(), AdoptionLabel) b := a.activate(a.adopter(nil, newObserver()), "calendar") plans := a.plans(b) if len(plans) != 2 { t.Fatalf("plan B roles %d", len(plans)) } for role, p := range plans { if p.ExistingTeam != team.TeamSQID || p.Kind != homeop.KindAddApps || strings.Join(p.Apps, ",") != "calendar" || p.Owner != "" || p.DisplayName != "" { t.Fatalf("plan B %s: existing %q kind %s apps %v", role, p.ExistingTeam, p.Kind, p.Apps) } } if plans[homeop.Directory].Label != AdoptionLabel || plans[homeop.Credential].Label != "" { t.Fatal("plan B labels") } // Plan B unconfirmed until it expired: re-signed for the same team. a.tick((homeop.PlanLifetime + 1) * time.Second) if err := e.Resubmit(a.ctx(), b); err != nil { t.Fatal(err) } for role, p := range a.plans(b) { if p.ExistingTeam != team.TeamSQID || p.Kind != homeop.KindAddApps || p.PlanID == plans[role].PlanID { t.Fatalf("resubmitted plan B %s: existing %q", role, p.ExistingTeam) } } } func TestAdoptionSeedsAtProposedSQIDOnly(t *testing.T) { t.Run("at the proposal", func(t *testing.T) { a := newAdoption(t) proposed := a.proposed() a.planA(a.adopter(nil, nil)) _, sqid, ok := a.home.Team(AdoptionLabel) team, _ := a.store.Team(a.ctx(), AdoptionLabel) if !ok || sqid != proposed || team.TeamSQID != proposed || a.home.TeamCount() != 1 { t.Fatalf("seeded at %q, Alta holds %q, proposed %q", sqid, team.TeamSQID, proposed) } var seed homeop.SeedInput a.signed("", "seed-team", &seed) if seed.TeamSQID != proposed || seed.Label != AdoptionLabel || seed.Name != "Oficina" { t.Fatal("seed-team input") } if a.home.Calls[homeop.CredentialOwnerSeed] != 1 || a.home.Calls[homeop.DirectorySeedTeam] != 1 { t.Fatalf("owner-seed %d, seed-team %d", a.home.Calls[homeop.CredentialOwnerSeed], a.home.Calls[homeop.DirectorySeedTeam]) } }) t.Run("proposal moved", func(t *testing.T) { // Alta's copy of the plan binds another SQID than the directory // now proposes: nothing is signed against the proposal. a := newAdoption(t) e := a.adopter(nil, nil) run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } r, _ := a.store.Run(a.ctx(), run) p := a.plans(run)[homeop.Directory] p.ExistingTeam = "txxz" raw, err := homeop.SignPlan(a.key, p) if err != nil { t.Fatal(err) } sealed, err := a.store.seal(planPurpose(r.PlanID, homeop.Directory), raw) if err != nil { t.Fatal(err) } if _, err := a.store.DB().Exec("UPDATE plan_submissions SET sealed_plan=? WHERE plan_id=? AND role='directory'", sealed, r.PlanID); err != nil { t.Fatal(err) } a.confirm(homeop.KindCreateTeam) if r := a.drive(e, run, 5); r.State != "failed" || r.Code != "proposal-moved" { t.Fatalf("run %s %s", r.State, r.Code) } if a.home.Calls[homeop.CredentialOwnerSeed] != 0 || a.home.TeamCount() != 0 { t.Fatal("an owner-seed was sent for a moved proposal") } }) t.Run("plan unreadable", func(t *testing.T) { a := newAdoption(t) e := a.adopter(nil, nil) run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } a.confirm(homeop.KindCreateTeam) if _, err := a.store.DB().Exec("UPDATE plan_submissions SET sealed_plan=NULL WHERE role='directory'"); err != nil { t.Fatal(err) } if r := a.drive(e, run, 5); r.State != "failed" || r.Code != "plan-unreadable" { t.Fatalf("run %s %s", r.State, r.Code) } if a.home.Calls[homeop.CredentialOwnerSeed] != 0 { t.Fatal("an owner-seed was sent without the confirmed plan") } }) } // Each entry point refuses what comes before its phase, before anything // is recorded or planned. func TestAdoptionRefusesOutOfOrder(t *testing.T) { fresh := &adoptHarness{harness: newHarness(t), net: &offline{}} _, err := fresh.adopter(nil, nil).StartAdoption(fresh.ctx(), "Oficina", ownerCanary) failCode(t, err, "home-not-initialized") for _, role := range []string{homeop.Credential, homeop.Directory} { a := newAdoption(t) if role == homeop.Credential { a.cred.Close() } else { a.dir.Close() } _, err := a.adopter(nil, nil).StartAdoption(a.ctx(), "Oficina", ownerCanary) var fl *Fail if !errors.As(err, &fl) || !strings.HasPrefix(fl.Code, "home-"+role+"-") { t.Fatalf("%s unreachable: %v", role, err) } if used, _ := a.store.LabelUsed(a.ctx(), AdoptionLabel); used { t.Fatal("recorded with Home unreachable") } } // A fresh Plan A binds the proposal Home answers now, or none. r := newAdoption(t) planned, err := r.adopter(nil, nil).StartAdoption(r.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } r.dir.Close() failCode(t, r.adopter(nil, nil).Resubmit(r.ctx(), planned), "no-proposed-team") // docs is missing from the env manifest: Plan A seeds, provisions docs // and stops at its register. a := newAdoption(t, "sheets", "slides", "calendar", "calls", "memoria") e := a.adopter(nil, newObserver()) _, err = e.ActivateAdopted(a.ctx(), []string{"calendar"}) failCode(t, err, "no-team") _, err = e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel) failCode(t, err, "no-team") run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } _, err = e.ActivateAdopted(a.ctx(), []string{"calendar"}) failCode(t, err, "team-not-seeded") _, err = e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel) failCode(t, err, "team-not-seeded") a.confirm(homeop.KindCreateTeam) if r := a.drive(e, run, 10); r.State != "failed" || r.Code != "register-refused" { t.Fatalf("plan A %s %s", r.State, r.Code) } a.tick(homeop.WindowLifetime * time.Second) for code, apps := range map[string][]string{ "no-apps": nil, "unknown-app": {"calendar", "mail"}, "not-registered": {"docs"}, } { _, err := e.ActivateAdopted(a.ctx(), apps) failCode(t, err, code) } _, err = e.ActivateAdopted(a.ctx(), []string{"calendar", "calendar"}) failCode(t, err, "unknown-app") _, err = e.DisableAdopted(a.ctx(), "sheets", AdoptionLabel) failCode(t, err, "not-provisioned") var n int _ = a.store.DB().QueryRow("SELECT count(*) FROM runs WHERE kind<>'create-team' AND label=?", AdoptionLabel).Scan(&n) if n != 0 { t.Fatal("a refused call recorded a run") } } func TestAdoptionRegisterInsertsNothing(t *testing.T) { a := newAdoption(t) a.planA(a.adopter(nil, nil)) if n := a.home.ConsumerCount(); n != 0 { t.Fatalf("register inserted %d credential consumers", n) } env := map[string]string{"directory": dirOrigin, "alta": "https://alta.example.test"} for _, s := range Slugs() { env[s] = homeop.CanonicalOrigin(s) } want := homeop.ManifestDigest(env) reqs := a.home.Requests() for _, s := range Slugs() { if got := str(a.step(s, StepRegister).Data, "manifest_digest"); got != want { t.Fatalf("%s manifest digest is not the env manifest's", s) } if countOf(reqs, homeop.CredentialRegister+":"+s) != 1 || countOf(reqs, homeop.DirectoryProvision+":"+s) != 1 { t.Fatalf("%s: %v", s, reqs) } if got := a.home.InstanceState(s); got != "pending" { t.Fatalf("%s directory row %q", s, got) } } // Without the exact env entry Home refuses, and Alta stops there. b := newAdoption(t, "docs", "sheets", "slides", "calendar", "calls") e := b.adopter(nil, nil) run, err := e.StartAdoption(b.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } b.confirm(homeop.KindCreateTeam) if r := b.drive(e, run, 20); r.State != "failed" || r.Code != "register-refused" { t.Fatalf("run %s %s", r.State, r.Code) } if b.home.ConsumerCount() != 0 { t.Fatal("a refused register inserted a consumer") } } func TestAdoptionMakesNoConsoleCalls(t *testing.T) { a := newAdoption(t) obs := newObserver() e := a.adopter(nil, obs) a.planA(e) run := a.activate(e, "calendar") if r := a.drive(e, run, 10); r.State != "done" || r.Code != "" { t.Fatalf("plan B %s %s", r.State, r.Code) } a.tick(homeop.WindowLifetime * time.Second) off, err := e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel) if err != nil { t.Fatal(err) } if err := a.home.Confirm(homeop.Directory, ""); err != nil { t.Fatal(err) } if r := a.drive(e, off, 5); r.State != "done" { t.Fatalf("disable %s %s", r.State, r.Code) } if n := a.net.count(); n != 0 { t.Fatalf("%d console or instance requests", n) } } func TestActivateAdoptedUsesExistingPolicy(t *testing.T) { a := newAdoption(t) obs := newObserver() e := a.adopter(nil, obs) a.planA(e) run := a.activate(e, "calendar") if r := a.drive(e, run, 10); r.State != "done" { t.Fatalf("plan B %s %s", r.State, r.Code) } team, _ := a.store.Team(a.ctx(), AdoptionLabel) ev := a.evidence("calendar") if ev.Policy != homeop.ExistingActivationPolicy || ev.Consumer != "calendar" || ev.App != "calendar" || ev.Audience != "https://calendar.oficina.works" || ev.AliasHost != "calendar.oficina.works" || ev.TeamSQID != team.TeamSQID || ev.Owner != team.OwnerRef { t.Fatalf("evidence %+v", ev) } if ev.AppVersion != goodObservation.AppVersion || ev.ArtifactDigest != goodObservation.ArtifactDigest || ev.EnvironmentBinding != goodObservation.EnvironmentBinding { t.Fatal("evidence does not carry the observation") } if ev.ManifestDigest != str(a.step("calendar", StepRegister).Data, "manifest_digest") { t.Fatal("evidence does not carry the register result's manifest") } if strings.Join(obs.calls, ",") != "calendar/"+team.TeamSQID { t.Fatalf("observed %v", obs.calls) } reqs := a.home.Requests() onceEach(t, reqs) if countOf(reqs, homeop.DirectoryActivate+":calendar") != 1 || a.home.InstanceState("calendar") != "live" { t.Fatalf("requests %v", reqs) } for _, s := range Slugs() { if s != "calendar" && a.home.InstanceState(s) != "pending" { t.Fatalf("%s activated by a calendar plan", s) } } a.tick(homeop.WindowLifetime * time.Second) _, err := e.ActivateAdopted(a.ctx(), []string{"calendar"}) failCode(t, err, "app-active") } func TestActivateAdoptedWithoutObserverFails(t *testing.T) { a := newAdoption(t) a.planA(a.adopter(nil, nil)) a.tick(homeop.WindowLifetime * time.Second) bare := a.adopter(nil, nil) _, err := bare.ActivateAdopted(a.ctx(), []string{"calendar"}) failCode(t, err, "no-observer") var n int _ = a.store.DB().QueryRow("SELECT count(*) FROM runs WHERE kind='add-apps'").Scan(&n) if n != 0 { t.Fatal("a run was recorded without an observer") } if err := a.home.Confirm(homeop.Directory, ""); err == nil { t.Fatal("a plan was submitted without an observer") } // An engine without one that advances the run never activates. run, err := a.adopter(nil, newObserver()).ActivateAdopted(a.ctx(), []string{"calendar"}) if err != nil { t.Fatal(err) } a.confirm(homeop.KindAddApps) if r := a.drive(bare, run, 5); r.State != "failed" || r.Code != "no-observer" { t.Fatalf("run %s %s", r.State, r.Code) } if countOf(a.home.Requests(), homeop.DirectoryActivate+":calendar") != 0 { t.Fatal("activated without an observer") } } func TestActivateAdoptedParksOnObserverRefusal(t *testing.T) { a := newAdoption(t) obs := newObserver() obs.set(&testRefusal{codes: []string{"delivery-check-superseded", "missing-delivery-check"}}) e := a.adopter(nil, obs) a.planA(e) run := a.activate(e, "calendar") if r := a.drive(e, run, 3); r.State != "parked" || r.Code != "observe-delivery-check-superseded,missing-delivery-check" { t.Fatalf("run %s %s", r.State, r.Code) } if s := a.step("calendar", StepActivate); s.State != "parked" || s.Code != "observe-delivery-check-superseded,missing-delivery-check" { t.Fatalf("step %s %s", s.State, s.Code) } obs.set(errors.New("carlos unreachable")) if r := a.drive(e, run, 2); r.State != "parked" || r.Code != "observer-unavailable" { t.Fatalf("run %s %s", r.State, r.Code) } if countOf(a.home.Requests(), homeop.DirectoryActivate+":calendar") != 0 || a.home.Calls[homeop.DirectoryActivate] != 0 { t.Fatal("activation sent on a refused observation") } // The refusal clears: the same run activates. obs.set(nil) if r := a.drive(e, run, 3); r.State != "done" { t.Fatalf("run %s %s", r.State, r.Code) } // An observation Home would refuse is never signed. for name, bad := range map[string]Observation{ "version": {AppVersion: "v1 4", ArtifactDigest: goodObservation.ArtifactDigest, EnvironmentBinding: goodObservation.EnvironmentBinding}, "artifact": {AppVersion: "v1", ArtifactDigest: "c2hh", EnvironmentBinding: goodObservation.EnvironmentBinding}, "binding": {AppVersion: "v1", ArtifactDigest: goodObservation.ArtifactDigest, EnvironmentBinding: ""}, } { t.Run(name, func(t *testing.T) { b := newAdoption(t) e := b.adopter(nil, &fakeObserver{obs: bad}) b.planA(e) run := b.activate(e, "calendar") if r := b.drive(e, run, 3); r.State != "failed" || r.Code != "observation-shape" { t.Fatalf("run %s %s", r.State, r.Code) } if b.home.Calls[homeop.DirectoryActivate] != 0 { t.Fatal("a malformed observation was sent") } }) } } func TestActivateAdoptedStartedNotBeforeRecordedIssued(t *testing.T) { for _, lose := range []bool{false, true} { t.Run(fmt.Sprintf("verify answer lost %v", lose), func(t *testing.T) { a := newAdoption(t) e := a.adopter(nil, newObserver()) a.planA(e) if lose { lost := false a.home.LoseAnswer = func(action string) bool { if action == homeop.DirectoryVerify && !lost { lost = true return true } return false } } run := a.activate(e, "calendar") if r := a.drive(e, run, 10); r.State != "done" { t.Fatalf("run %s %s", r.State, r.Code) } var vin homeop.VerificationInput a.signed("calendar", "verify", &vin) recorded := num(a.step("calendar", StepVerify).Data, "issued_at") ev := a.evidence("calendar") if ev.Started != recorded || recorded < vin.Issued { t.Fatalf("started %d, recorded %d, Home's issued %d", ev.Started, recorded, vin.Issued) } if lose && recorded <= vin.Issued { t.Fatal("a replayed attempt recorded Home's issued_at, which its result does not carry") } if !lose && recorded != vin.Issued { t.Fatal("a fresh attempt did not record the issued_at it signed") } if ev.Completed < ev.Started { t.Fatal("completed before started") } if countOf(a.home.Requests(), homeop.DirectoryVerify+":calendar") != 1 { t.Fatal("verify committed twice") } }) } } func TestActivateAdoptedReverifiesLapsedAttempt(t *testing.T) { a := newAdoption(t) obs := newObserver() obs.set(&testRefusal{codes: []string{"missing-delivery-check"}}) e := a.adopter(nil, obs) a.planA(e) run := a.activate(e, "calendar") a.drive(e, run, 2) first := a.signed("calendar", "verify", &homeop.VerificationInput{}) // The attempt lapses while the observation is refused. a.tick(600 * time.Second) obs.set(nil) if r := a.drive(e, run, 5); r.State != "done" { t.Fatalf("run %s %s", r.State, r.Code) } var vin homeop.VerificationInput second := a.signed("calendar", "verify", &vin) if second.OperationID == first.OperationID { t.Fatal("the lapsed attempt was not replaced") } ev := a.evidence("calendar") if ev.Attempt != second.OperationID || ev.Started != num(a.step("calendar", StepVerify).Data, "issued_at") || ev.Started < vin.Issued { t.Fatal("activation does not carry the new attempt") } reqs := a.home.Requests() if countOf(reqs, homeop.DirectoryVerify+":calendar") != 2 || countOf(reqs, homeop.DirectoryActivate+":calendar") != 1 { t.Fatalf("requests %v", reqs) } } func TestOrdinaryRunsStillRefuseOficina(t *testing.T) { a := newAdoption(t) e := a.adopter(nil, nil) _, err := a.engine(nil).CreateTeam(a.ctx(), NewTeam{Label: AdoptionLabel, Name: "Oficina", Owner: ownerCanary, Apps: []string{"docs"}}) failCode(t, err, "label-reserved") a.planA(e) a.tick(homeop.WindowLifetime * time.Second) _, err = a.engine(nil).AddApps(a.ctx(), AdoptionLabel, []string{"calendar"}, RunOptions{}) failCode(t, err, "label-reserved") _, err = a.engine(nil).RetireApps(a.ctx(), AdoptionLabel, []string{"calendar"}, AdoptionLabel) failCode(t, err, "label-reserved") // A run under the label that is not an adoption never advances. before := len(a.home.Requests()) id, err := a.store.NewRun(a.ctx(), homeop.KindAddApps, AdoptionLabel, []string{"calendar"}, RunOptions{}) if err != nil { t.Fatal(err) } failCode(t, e.Advance(a.ctx(), id), "label-reserved") if r, _ := a.store.Run(a.ctx(), id); r.State != "failed" || r.Code != "label-reserved" { t.Fatalf("run %s %s", r.State, r.Code) } if len(a.home.Requests()) != before { t.Fatal("an ordinary run under oficina reached Home") } } func TestDisableAdoptedRequiresTypedLabel(t *testing.T) { a := newAdoption(t) e := a.adopter(nil, newObserver()) a.planA(e) run := a.activate(e, "calendar") if r := a.drive(e, run, 10); r.State != "done" { t.Fatalf("plan B %s %s", r.State, r.Code) } a.tick(homeop.WindowLifetime * time.Second) for _, typed := range []string{"", "Oficina", "oficin", " oficina", "calendar"} { _, err := e.DisableAdopted(a.ctx(), "calendar", typed) failCode(t, err, "label-mismatch") } _, err := e.DisableAdopted(a.ctx(), "mail", AdoptionLabel) failCode(t, err, "unknown-app") var n int _ = a.store.DB().QueryRow("SELECT count(*) FROM runs WHERE kind='retire-apps'").Scan(&n) if n != 0 { t.Fatal("a refused disable recorded a run") } before := a.home.Requests() off, err := e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel) if err != nil { t.Fatal(err) } plans := a.plans(off) d, ok := plans[homeop.Directory] if len(plans) != 1 || !ok || d.Kind != homeop.KindRetireApps || d.Label != AdoptionLabel || d.ExistingTeam != "" || strings.Join(d.Apps, ",") != "calendar" { t.Fatalf("disable plans %d", len(plans)) } if err := a.home.Confirm(homeop.Directory, ""); err != nil { t.Fatal(err) } if r := a.drive(e, off, 5); r.State != "done" { t.Fatalf("disable %s %s", r.State, r.Code) } after := a.home.Requests() if got := after[len(before):]; strings.Join(got, ",") != homeop.DirectoryDisable+":calendar" { t.Fatalf("disable sent %v", got) } if a.home.InstanceState("calendar") != "disabled" || a.home.Calls[homeop.CredentialRetire] != 0 { t.Fatal("disable state") } // The app stays the suite's: its env consumer, its team row. team, _ := a.store.Team(a.ctx(), AdoptionLabel) if team.Apps["calendar"] != "active" { t.Fatalf("calendar %q", team.Apps["calendar"]) } a.tick(homeop.WindowLifetime * time.Second) _, err = e.ActivateAdopted(a.ctx(), []string{"calendar"}) failCode(t, err, "app-disabled") } // adoptionActs runs Plan A and Plan B for calendar cleanly and returns // each plan's acts in order. func adoptionActs(t *testing.T) (planA, planB []string) { a := newAdoption(t) var acts *[]string e := a.adopter(func(k string) error { *acts = append(*acts, k); return nil }, newObserver()) acts = &planA a.planA(e) acts = &planB run := a.activate(e, "calendar") if r := a.drive(e, run, 10); r.State != "done" { t.Fatalf("clean plan B %s %s", r.State, r.Code) } return planA, planB } // crashAt returns a hook that fails at the i-th act, once. func crashAt(i int, crashed *bool) func(string) error { n := 0 return func(string) error { if n == i && !*crashed { *crashed = true return errors.New("kill -9") } n++ return nil } } // TestAdoptionCrashAfterEveryAct: Alta dies after each act has taken // effect at Home and before it is recorded; a fresh engine resumes by // exact replay and nothing is committed twice. func TestAdoptionCrashAfterEveryAct(t *testing.T) { planA, planB := adoptionActs(t) if len(planA) != 2+2*len(Apps) || strings.Join(planB, ",") != "verify,activate" { t.Fatalf("acts %v / %v", planA, planB) } for i := range planA { t.Run(fmt.Sprintf("A%02d-%s", i, planA[i]), func(t *testing.T) { a := newAdoption(t) crashed := false e := a.adopter(crashAt(i, &crashed), nil) run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } a.confirm(homeop.KindCreateTeam) for j := 0; j < 20 && !crashed; j++ { _ = e.Advance(a.ctx(), run) a.tick(5 * time.Second) } if !crashed { t.Fatalf("act %d never reached", i) } a.tick(time.Minute) if r := a.drive(a.adopter(nil, nil), run, 20); r.State != "done" || r.Code != "awaiting-configuration" { t.Fatalf("after crash at %s: %s %s", planA[i], r.State, r.Code) } if a.home.TeamCount() != 1 { t.Fatalf("teams %d", a.home.TeamCount()) } for _, s := range Slugs() { if a.home.InstanceState(s) != "pending" { t.Fatalf("%s %q", s, a.home.InstanceState(s)) } } reqs := a.home.Requests() onceEach(t, reqs) if len(reqs) != 1+len(planA) || a.home.ConsumerCount() != 0 { t.Fatalf("requests %v", reqs) } }) } for i := range planB { t.Run(fmt.Sprintf("B%02d-%s", i, planB[i]), func(t *testing.T) { a := newAdoption(t) a.planA(a.adopter(nil, nil)) crashed := false obs := newObserver() e := a.adopter(crashAt(i, &crashed), obs) run := a.activate(e, "calendar") for j := 0; j < 10 && !crashed; j++ { _ = e.Advance(a.ctx(), run) a.tick(5 * time.Second) } if !crashed { t.Fatalf("act %d never reached", i) } a.tick(time.Minute) if r := a.drive(a.adopter(nil, obs), run, 10); r.State != "done" { t.Fatalf("after crash at %s: %s %s", planB[i], r.State, r.Code) } // The activation was observed once and replayed exactly. if obs.count() != 1 || a.home.InstanceState("calendar") != "live" { t.Fatalf("observed %d times", obs.count()) } reqs := a.home.Requests() onceEach(t, reqs) if !slices.Contains(reqs, homeop.DirectoryActivate+":calendar") { t.Fatalf("requests %v", reqs) } }) } } // Plan A interrupted after the seed, its window then closing: the team is // seeded, some apps registered. A continuation under a fresh add-apps // window for the stored SQID completes only the missing steps. func TestAdoptionContinuesAfterTheWindowCloses(t *testing.T) { a := newAdoption(t) e := a.adopter(nil, nil) _, err := e.ContinueAdoption(a.ctx()) failCode(t, err, "no-team") run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary) if err != nil { t.Fatal(err) } _, err = e.ContinueAdoption(a.ctx()) failCode(t, err, "team-not-seeded") a.confirm(homeop.KindCreateTeam) // Dies after sheets' register committed at Home (acts: owner-seed, // seed-team, then each app's provision and register: docs, sheets). crashed := false dying := a.adopter(crashAt(5, &crashed), nil) for j := 0; j < 10 && !crashed; j++ { _ = dying.Advance(a.ctx(), run) a.tick(5 * time.Second) } if !crashed { t.Fatal("never reached sheets' register") } a.tick(homeop.WindowLifetime * time.Second) if r := a.drive(e, run, 3); r.State != "parked" || r.Code != "window-expired" { t.Fatalf("stranded run %s %s", r.State, r.Code) } // The lost answer was recovered by exact replay, outside the window. if _, ok, _ := a.store.Done(a.ctx(), AdoptionLabel, "sheets", StepRegister); !ok { t.Fatal("sheets' committed register was not recovered") } failCode(t, e.Resubmit(a.ctx(), run), "use-continue-adoption") _, err = e.StartAdoption(a.ctx(), "Oficina", ownerCanary) failCode(t, err, "label-used") team, _ := a.store.Team(a.ctx(), AdoptionLabel) next, err := e.ContinueAdoption(a.ctx()) if err != nil { t.Fatal(err) } if r, _ := a.store.Run(a.ctx(), run); r.State != "superseded" { t.Fatalf("stranded run %s", r.State) } missing := "slides,calendar,calls,memoria,equipo,base" if r, _ := a.store.Run(a.ctx(), next); !r.Adoption || r.Kind != homeop.KindCreateTeam || strings.Join(r.Apps, ",") != missing { t.Fatalf("continuation run %+v", r) } plans := a.plans(next) if len(plans) != 2 { t.Fatalf("roles %d", len(plans)) } for role, p := range plans { if p.Kind != homeop.KindAddApps || p.ExistingTeam != team.TeamSQID || strings.Join(p.Apps, ",") != missing || p.Owner != "" || p.DisplayName != "" { t.Fatalf("%s continuation plan: kind %s existing %q apps %v", role, p.Kind, p.ExistingTeam, p.Apps) } } if plans[homeop.Directory].Label != AdoptionLabel { t.Fatal("continuation directory label") } a.confirm(homeop.KindAddApps) if r := a.drive(e, next, 10); r.State != "done" || r.Code != "awaiting-configuration" { t.Fatalf("continuation %s %s", r.State, r.Code) } if a.home.TeamCount() != 1 || a.home.ConsumerCount() != 0 { t.Fatal("teams or credential consumers") } for _, s := range Slugs() { if a.home.InstanceState(s) != "pending" { t.Fatalf("%s %q", s, a.home.InstanceState(s)) } if _, ok, _ := a.store.Done(a.ctx(), AdoptionLabel, s, StepRegister); !ok { t.Fatalf("%s not registered", s) } } reqs := a.home.Requests() onceEach(t, reqs) if len(reqs) != 1+2+2*len(Apps) || a.home.Calls[homeop.DirectorySeedTeam] != 1 || a.home.Calls[homeop.CredentialOwnerSeed] != 1 { t.Fatalf("requests %v", reqs) } _, err = e.ContinueAdoption(a.ctx()) failCode(t, err, "plan-a-complete") // Plan B follows as usual. ob := a.adopter(nil, newObserver()) b := a.activate(ob, "calendar") if r := a.drive(ob, b, 10); r.State != "done" || a.home.InstanceState("calendar") != "live" { t.Fatalf("plan B %s %s", r.State, r.Code) } }