package provision import ( "context" "errors" "fmt" "strings" "testing" "time" "amadan.net/oficina/alta/console" "amadan.net/oficina/alta/homeop" ) // checkEndState is what every successful lagged run must leave, however // it got there: one team, six consumers, six instances bound to the owned // environment, environments exactly the recipe, no key regenerated, no // address and no platform value left in Alta. func checkEndState(t *testing.T, h *harness) { t.Helper() if n := h.home.TeamCount(); n != 1 { t.Fatalf("teams at Home = %d, want 1", n) } if n := h.home.ConsumerCount(); n != len(allApps) { t.Fatalf("credential consumers = %d, want %d", n, len(allApps)) } if n := h.con.InstanceCount(); n != len(allApps) { t.Fatalf("instances = %d, want %d", n, len(allApps)) } e := h.engine(nil) for _, slug := range allApps { app, _ := AppBySlug(slug) env, _, ok := h.con.Instance(RouteHost("lagged", slug, account)) if !ok || env != "lagged" { t.Fatalf("%s instance bound to %q", slug, env) } if _, state, ok := h.con.Claim(PublicHost("lagged", slug)); !ok || state != "live" { t.Fatalf("%s claim %q", slug, state) } if err := e.AuditEnvironment(h.ctx(), "lagged", app); err != nil { t.Fatalf("%s audit: %v", slug, err) } vars, owner, _ := h.con.Env(slug, "lagged") if owner != "alta" { t.Fatalf("%s environment owner %q", slug, owner) } for k, v := range vars { if v.Kind == "secret" && !console.PlatformManaged(k) && h.con.SecretWrites[slug+"/lagged/"+k] != 1 { t.Fatalf("%s %s written %d times: a generated key was regenerated", slug, k, h.con.SecretWrites[slug+"/lagged/"+k]) } } want := "pending" if app.Roster { want = "live" } if got := h.home.InstanceState(ConsumerID("lagged", slug)); got != want { t.Fatalf("%s directory row %q, want %q", slug, got, want) } } // The roster bearer reached Docs, sealed, and is Home's. if v, err := h.con.Open("docs", "lagged", "DOCS_TEAM_ROSTER_TOKEN"); err != nil || len(v) != 43 { t.Fatalf("roster token: %q %v", v, err) } // Generated keys are 32 random bytes. if v, err := h.con.Open("calls", "lagged", "CALLS_DEK"); err != nil || len(b64(v)) != 32 { t.Fatalf("CALLS_DEK: %v", err) } // Privacy (§12): no address after step 13 anywhere in Alta's DB, and // no platform value ever. var n int _ = h.store.DB().QueryRow("SELECT count(*) FROM owner_inputs").Scan(&n) if n != 0 { t.Fatal("owner input survives step 13") } _ = h.store.DB().QueryRow("SELECT count(*) FROM operator_requests WHERE action='credential.owner-seed'").Scan(&n) if n != 0 { t.Fatal("owner-seed request survives step 13") } // Only a create-team plan's credential half carries the owner; an // add-apps plan carries none and may stay until it expires. _ = h.store.DB().QueryRow("SELECT count(*) FROM plan_submissions WHERE role='credential' AND sealed_plan IS NOT NULL AND plan_id IN (SELECT plan_id FROM runs WHERE kind='create-team')").Scan(&n) if n != 0 { t.Fatal("a credential plan carrying the owner survives step 13") } _, _ = h.store.DB().Exec("PRAGMA wal_checkpoint(TRUNCATE)") for _, needle := range []string{ownerCanary, "fakeconsole", "PLATFORM-VALUE-CANARY", "lagged.test"} { if h.scan(needle) { t.Fatalf("%q found in Alta's database files", needle) } } for _, needle := range []string{ownerCanary, "lagged", "PLATFORM-VALUE-CANARY"} { if strings.Contains(h.logs.String(), needle) { t.Fatalf("%q in Alta's logs", needle) } } } func TestCreateTeamEndToEnd(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) run := h.createLagged(e) r := h.drive(e, run, 40) if r.State != "done" { steps, _ := h.store.Steps(h.ctx(), "lagged") t.Fatalf("run %s %s; steps %+v", r.State, r.Code, steps) } checkEndState(t, h) // Every Home write was under the one plan id Paul confirmed. if h.home.Calls[homeop.CredentialOwnerSeed] != 1 || h.home.Calls[homeop.DirectorySeedTeam] != 1 { t.Fatalf("owner-seed %d, seed-team %d", h.home.Calls[homeop.CredentialOwnerSeed], h.home.Calls[homeop.DirectorySeedTeam]) } } // countActs runs a whole create-team and returns its acts in order. func countActs(t *testing.T) []string { h := newHarness(t) h.initialized() var acts []string e := h.engine(func(k string) error { acts = append(acts, k); return nil }) run := h.createLagged(e) if r := h.drive(e, run, 40); r.State != "done" { t.Fatalf("clean run %s %s", r.State, r.Code) } return acts } // TestCrashAfterEveryAct is §12's crash injection: after every act (the // remote effect has happened, Alta has not recorded it) the process dies; // a fresh engine over the same database resumes by probing and reaches // the same end state with no duplicate instance, consumer or team. func TestCrashAfterEveryAct(t *testing.T) { acts := countActs(t) if len(acts) < 20 { t.Fatalf("only %d acts: %v", len(acts), acts) } for i := range acts { t.Run(fmt.Sprintf("%02d-%s", i, strings.ReplaceAll(acts[i], "/", "-")), func(t *testing.T) { h := newHarness(t) h.initialized() n := 0 crashed := false e := h.engine(func(k string) error { if n == i && !crashed { crashed = true return errors.New("kill -9") } n++ return nil }) run := h.createLagged(e) for j := 0; j < 40 && !crashed; j++ { _ = e.Advance(h.ctx(), run) h.con.Walk() h.tick(5 * time.Second) } if !crashed { t.Fatalf("act %d never reached", i) } // The crashed process's lock is stale on restart. h.tick(11 * time.Minute) if r, _ := h.store.Run(h.ctx(), run); r.State != "done" { // The window may have closed during the restart: Paul // confirms a fresh plan for the same apps. if r2 := h.drive(h.engine(nil), run, 40); r2.State != "done" { next, err := h.engine(nil).AddApps(h.ctx(), "lagged", allApps, RunOptions{}) if err != nil { t.Fatalf("resume plan: %v (run %s %s)", err, r2.State, r2.Code) } kind := homeop.KindAddApps if _, _, seeded := h.home.Team("lagged"); !seeded { kind = homeop.KindCreateTeam } h.confirm(kind) if r3 := h.drive(h.engine(nil), next, 40); r3.State != "done" { t.Fatalf("after crash at %s: %s %s", acts[i], r3.State, r3.Code) } } } checkEndState(t, h) }) } } // TestLostAnswersAreRecoveredByReplay: Home commits and the answer is // lost on the way back, for every verb. Nothing is inferred from it; the // exact replay returns the stored result. func TestLostAnswersAreRecoveredByReplay(t *testing.T) { for _, action := range []string{homeop.CredentialOwnerSeed, homeop.DirectorySeedTeam, homeop.DirectoryProvision, homeop.CredentialRegister, homeop.DirectoryVerify, homeop.DirectoryActivate} { t.Run(action, func(t *testing.T) { h := newHarness(t) h.initialized() lost := false h.home.LoseAnswer = func(a string) bool { if a == action && !lost { lost = true return true } return false } e := h.engine(nil) run := h.createLagged(e) if r := h.drive(e, run, 40); r.State != "done" { t.Fatalf("%s %s", r.State, r.Code) } if !lost { t.Fatal("no answer was lost") } checkEndState(t, h) }) } } // TestExpiredReceiptTakesANewOwnerSeed: replay returns the same expired // receipt by design, so an expired one leads to a new owner-seed, not a // stuck step 4. func TestExpiredReceiptTakesANewOwnerSeed(t *testing.T) { h := newHarness(t) h.initialized() down := true h.home.Outage = func(a string) bool { return down && a == homeop.DirectorySeedTeam } e := h.engine(nil) run := h.createLagged(e) _ = e.Advance(h.ctx(), run) if h.home.Calls[homeop.CredentialOwnerSeed] != 1 { t.Fatalf("owner-seed calls %d", h.home.Calls[homeop.CredentialOwnerSeed]) } h.tick(6 * time.Minute) // the receipt (300 s) and the signed seed-team expire down = false if r := h.drive(e, run, 40); r.State != "done" { t.Fatalf("%s %s", r.State, r.Code) } if h.home.Calls[homeop.CredentialOwnerSeed] != 2 { t.Fatalf("owner-seed calls %d, want a second for the expired receipt", h.home.Calls[homeop.CredentialOwnerSeed]) } checkEndState(t, h) } // TestStreamResyncAfterLostDatabase: Alta's stream rows are gone (a DB // restored from before its last operations). Home refuses the stale // sequence; Alta re-reads Home's head through a signed inspect and goes on. func TestStreamResyncAfterLostDatabase(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) run := h.createLagged(e) _ = e.Advance(h.ctx(), run) seq, _ := h.home.Stream(homeop.Directory) if seq < 3 { t.Fatalf("directory sequence %d", seq) } // Roll Alta's view back to sequence 1, as a restored backup would. var oldHead string if err := h.store.DB().QueryRow("SELECT head FROM operator_requests WHERE role='directory' AND sequence=1").Scan(&oldHead); err != nil { t.Fatal(err) } if err := h.store.SetStream(h.ctx(), homeop.Directory, 1, oldHead); err != nil { t.Fatal(err) } if r := h.drive(e, run, 40); r.State != "done" { t.Fatalf("%s %s", r.State, r.Code) } got, head := h.home.Stream(homeop.Directory) if s, hd, _, _ := h.store.Stream(h.ctx(), homeop.Directory); s != got || hd != head { t.Fatalf("Alta's stream %d/%s, Home's %d/%s", s, hd, got, head) } audit, _ := h.store.AuditLog(h.ctx(), "lagged", 500) found := false for _, a := range audit { found = found || a.Event == "stream-resync" } if !found { t.Fatal("no stream-resync in the audit") } } func TestWindowExpiryParksAndAddAppsResumes(t *testing.T) { h := newHarness(t) h.initialized() h.con.DomainPolls = 1000 // domains do not issue within the window e := h.engine(nil) run := h.createLagged(e) r := h.drive(e, run, 5) if r.State != "parked" { t.Fatalf("%s %s", r.State, r.Code) } h.tick(homeop.WindowLifetime * time.Second) for _, a := range allApps { h.con.SetDomainState(PublicHost("lagged", a), "live") } if r = h.drive(e, run, 10); r.State != "parked" || r.Code != "window-expired" { t.Fatalf("after window: %s %s", r.State, r.Code) } next, err := e.AddApps(h.ctx(), "lagged", allApps, RunOptions{}) if err != nil { t.Fatal(err) } h.confirm(homeop.KindAddApps) if r = h.drive(e, next, 40); r.State != "done" { t.Fatalf("add-apps: %s %s", r.State, r.Code) } checkEndState(t, h) } func TestLabelsAreNeverReused(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) run := h.createLagged(e) h.drive(e, run, 40) _, err := e.CreateTeam(h.ctx(), NewTeam{Label: "lagged", Name: "Again", Owner: ownerCanary, Apps: []string{"docs"}}) var fl *Fail if !errors.As(err, &fl) || fl.Code != "label-used" { t.Fatalf("reused label: %v", err) } // "oficina" is the canonical apps' team, adopted on Home's own path, // never a new team's label; refused before anything is recorded. if _, err := e.CreateTeam(h.ctx(), NewTeam{Label: "oficina", Name: "Oficina", Owner: ownerCanary, Apps: []string{"docs"}}); !errors.As(err, &fl) || fl.Code != "label-reserved" { t.Fatalf("reserved label: %v", err) } if used, err := h.store.LabelUsed(h.ctx(), "oficina"); err != nil || used { t.Fatalf("a refused reserved label was recorded: %v %v", used, err) } // Ordinary add-apps and retire refuse it too: adopting the canonical // apps is Home's own signed scope, never an ordinary plan under the label. if _, err := e.AddApps(h.ctx(), "oficina", []string{"docs"}, RunOptions{}); !errors.As(err, &fl) || fl.Code != "label-reserved" { t.Fatalf("add-apps under the reserved label: %v", err) } if _, err := e.RetireApps(h.ctx(), "oficina", []string{"docs"}, "oficina"); !errors.As(err, &fl) || fl.Code != "label-reserved" { t.Fatalf("retire under the reserved label: %v", err) } // Alta's label rule is tighter than Home's. for _, bad := range []string{"a", "Lagged", "-lag", "lag-", strings.Repeat("a", 33), "la_g"} { if _, err := e.CreateTeam(h.ctx(), NewTeam{Label: bad, Name: "x", Owner: ownerCanary, Apps: []string{"docs"}}); !errors.As(err, &fl) || fl.Code != "label-shape" { t.Fatalf("label %q: %v", bad, err) } } } func TestOwnerMustAlreadyExist(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) _, err := e.CreateTeam(h.ctx(), NewTeam{Label: "alpha", Name: "Alpha", Owner: "nobody@nowhere.test", Apps: []string{"docs"}}) var fl *Fail if !errors.As(err, &fl) || fl.Code != "plan-refused-credential" { t.Fatalf("unknown owner: %v", err) } } func TestDocsMailUnderTheWrongPrefixRefuses(t *testing.T) { h := newHarness(t) h.initialized() h.con.MailPrefix["docs"] = "CARLOS_SMTP" // Docs reads DOCS_SMTP_* only e := h.engine(nil) run := h.createLagged(e) r := h.drive(e, run, 10) if r.State != "failed" || r.Code != "mail-prefix-docs" { t.Fatalf("%s %s", r.State, r.Code) } } func TestPlatformKeysAwaitTheWalk(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "beta", Name: "Beta", Owner: ownerCanary, Apps: []string{"calls"}}) if err != nil { t.Fatal(err) } h.confirm(homeop.KindCreateTeam) _ = e.Advance(h.ctx(), run) st, _, _ := h.store.Step(h.ctx(), "beta", "calls", StepEnv) if st.Code != "awaiting-platform-keys" { t.Fatalf("env step %s %s", st.State, st.Code) } // No instance before PLATFORM keys are there (§6). if h.con.InstanceCount() != 0 { t.Fatal("instance created before the platform keys arrived") } h.con.Walk() if r := h.drive(e, run, 20); r.State != "done" { t.Fatalf("%s %s", r.State, r.Code) } vars, _, _ := h.con.Env("calls", "beta") if _, ok := vars["CARLOS_RELAY"]; !ok { t.Fatal("no relay identity") } } func TestForkedEnvironmentKeepsKeysAndDropsTrack1Extras(t *testing.T) { h := newHarness(t) h.initialized() // Paul: carlos env fork --from lagged --to lagged-team --scope alta, // then the rebind. The fork carries lagged's own keys only. h.con.SetEnv("memoria", "lagged-team", "alta", map[string]fakeVar{ "MEMORIA_DEK": {Kind: "secret", Envelope: sealFor(t, h, "memoria", "till-data-key")}, "MEMORIA_INSTANCE_KEY": {Kind: "secret", Envelope: sealFor(t, h, "memoria", "instance")}, "MEMORIA_ORIGIN": {Kind: "env", Value: "https://lagged.memoria.oficina.works"}, "MEMORIA_OWNERS": {Kind: "env", Value: ownerCanary}, "MEMORIA_AI": {Kind: "env", Value: ""}, "OFICINA_DASHBOARD_TEAM": {Kind: "env", Value: ""}, }) h.con.AddInstance("memoria", RouteHost("lagged", "memoria", account), "lagged-team") h.con.AddClaim("memoria", PublicHost("lagged", "memoria"), RouteHost("lagged", "memoria", account), "live") e := h.engine(nil) run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "lagged", Name: "Lagged", Owner: ownerCanary, Apps: []string{"memoria"}, Forked: true}) if err != nil { t.Fatal(err) } h.confirm(homeop.KindCreateTeam) if r := h.drive(e, run, 20); r.State != "done" { t.Fatalf("%s %s", r.State, r.Code) } vars, _, _ := h.con.Env("memoria", "lagged-team") for _, k := range []string{"MEMORIA_AI", "OFICINA_DASHBOARD_TEAM"} { if _, ok := vars[k]; ok { t.Fatalf("%s survived the fork", k) } } if v, _ := h.con.Open("memoria", "lagged-team", "MEMORIA_DEK"); v != "till-data-key" { t.Fatal("the forked DEK was regenerated: Till's data would be unreadable") } if _, restarts, _ := h.con.Instance(RouteHost("lagged", "memoria", account)); restarts == 0 { t.Fatal("config changed under a running instance without a restart") } } func TestExtraKeyInAnUnforkedEnvironmentRefuses(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "gamma", Name: "Gamma", Owner: ownerCanary, Apps: []string{"sheets"}}) if err != nil { t.Fatal(err) } h.confirm(homeop.KindCreateTeam) if r := h.drive(e, run, 20); r.State != "done" { t.Fatalf("%s %s", r.State, r.Code) } vars, _, _ := h.con.Env("sheets", "gamma") vars["SNEAKY"] = fakeVar{Kind: "env", Value: "x"} h.con.SetEnv("sheets", "gamma", "alta", vars) app, _ := AppBySlug("sheets") var fl *Fail if err := e.AuditEnvironment(h.ctx(), "gamma", app); !errors.As(err, &fl) || fl.Code != "audit-extra-key" { t.Fatalf("audit with an extra key: %v", err) } } func TestDeprovision(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) run := h.createLagged(e) h.drive(e, run, 40) h.tick(homeop.WindowLifetime * time.Second) var fl *Fail if _, err := e.RetireApps(h.ctx(), "lagged", []string{"calls"}, "laged"); !errors.As(err, &fl) || fl.Code != "label-mismatch" { t.Fatalf("mistyped label: %v", err) } ret, err := e.RetireApps(h.ctx(), "lagged", []string{"docs", "calls"}, "lagged") if err != nil { t.Fatal(err) } h.confirm(homeop.KindRetireApps) if r := h.drive(e, ret, 10); r.State != "done" { t.Fatalf("%s %s", r.State, r.Code) } for _, a := range []string{"docs", "calls"} { if got := h.home.InstanceState(ConsumerID("lagged", a)); got != "disabled" { t.Fatalf("%s directory %q", a, got) } if got := h.home.ConsumerState(ConsumerID("lagged", a)); got != "retired" { t.Fatalf("%s credential %q", a, got) } if _, _, ok := h.con.Claim(PublicHost("lagged", a)); ok { t.Fatalf("%s claim survives", a) } if _, _, ok := h.con.Instance(RouteHost("lagged", a, account)); ok { t.Fatalf("%s instance survives", a) } // The owned environment survives (no delete verb exists). if _, _, ok := h.con.Env(a, "lagged"); !ok { t.Fatalf("%s environment gone", a) } } // Retired hostnames are never reused. h.tick(homeop.WindowLifetime * time.Second) if _, err := e.AddApps(h.ctx(), "lagged", []string{"calls"}, RunOptions{}); !errors.As(err, &fl) || fl.Code != "app-retired" { t.Fatalf("re-adding a retired app: %v", err) } // Untouched apps keep running. if _, _, ok := h.con.Instance(RouteHost("lagged", "sheets", account)); !ok { t.Fatal("sheets went with them") } } func TestInitializeNeedsTheTypedAttestation(t *testing.T) { h := newHarness(t) e := h.engine(nil) var fl *Fail if _, err := e.StartInitialize(h.ctx(), "yes"); !errors.As(err, &fl) || fl.Code != "attestation-mismatch" { t.Fatalf("%v", err) } // Before initialize, no team can be created. if _, err := e.CreateTeam(h.ctx(), NewTeam{Label: "alpha", Name: "Alpha", Owner: ownerCanary, Apps: []string{"docs"}}); !errors.As(err, &fl) || fl.Code != "home-not-initialized" { t.Fatalf("%v", err) } h.initialized() if _, err := e.StartInitialize(h.ctx(), InitializeAttestation); !errors.As(err, &fl) || fl.Code != "already-initialized" { t.Fatalf("%v", err) } } func TestPlanIsTheSameOnBothRoles(t *testing.T) { h := newHarness(t) h.initialized() e := h.engine(nil) run := h.createLagged(e) r, _ := h.store.Run(h.ctx(), run) plans, _ := h.store.Plans(h.ctx(), r.PlanID) if len(plans) != 2 { t.Fatalf("plans %d", len(plans)) } for role, p := range plans { raw, _ := homeop.EnvelopePayload(p.Signed) var plan homeop.Plan if err := homeop.Decode(raw, &plan); err != nil || plan.PlanID != r.PlanID { t.Fatalf("%s plan %v", role, err) } if role == homeop.Directory && (plan.Label != "lagged" || plan.DisplayName != "Lagged" || plan.Owner != "") { t.Fatalf("directory plan %+v", plan) } if role == homeop.Credential && (plan.Owner != ownerCanary || plan.Label != "" || plan.DisplayName != "") { t.Fatalf("credential plan carries %+v", plan) } } _ = context.Background }