package operator import ( "bytes" "context" "encoding/base64" "testing" "time" "amadan.net/oficina/home/internal/home/directorydata" "amadan.net/oficina/home/roster" family "amadan.net/rastrillo/rastrillo/crypto" "github.com/go-json-experiment/json" ) func adoptionRoute(r directorydata.Route) bool { if r.Label == "oficina" { return directorydata.CanonicalBinding(r.Label, r.App, r.ConsumerID, r.Origin) } return r.Origin == "https://"+r.Label+"."+r.App+".oficina.works" } func adoptionDirectory(t *testing.T) *httpDirectory { t.Helper() f := newHTTPDirectory(t) f.directory.policy.ValidateRoute = adoptionRoute f.openPlan(t, func(p *Plan) { p.Kind, p.Apps, p.Label, p.DisplayName = "initialize", nil, "", "" }) if _, e := f.run(t, "directory.initialize", func(b InputBase) any { return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"} }); e != nil { t.Fatal(e) } *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Label, p.ExistingTeam = "oficina", "Uk" }) return f } func adoptionPending(t *testing.T) (*httpDirectory, VerificationInput) { t.Helper() f := adoptionDirectory(t) if _, e := f.seedHTTP(t, 1, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != nil { t.Fatal(e) } raw := f.input(t, "directory.provision-consumer", func(b InputBase) any { return ProvisionInput{b, token(10), "Uk", "docs", "docs", "https://docs.oficina.works", 0} }) out, e := f.directory.ExecuteHTTP(context.Background(), raw) if e != nil { t.Fatal(e) } again, e := f.directory.ExecuteHTTP(context.Background(), raw) if e != nil || !bytes.Equal(out, again) || countRows(t, f.db, "roster_consumers") != 1 { t.Fatal("provision replay", e) } var result Result if json.Unmarshal(out, &result) != nil { t.Fatal("result") } f.bearer = result.Bearer var digest []byte if e = f.db.QueryRow("SELECT record_digest FROM directory_operator_consumer_records").Scan(&digest); e != nil { t.Fatal(e) } return f, VerificationInput{Consumer: "docs", TeamSQID: "Uk", App: "docs", Audience: "https://docs.oficina.works", Generation: token(10), RecordSequence: 1, RecordDigest: base64.RawURLEncoding.EncodeToString(digest), Epoch: 2, Owner: "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", Issued: f.now.Unix(), Expires: f.now.Unix() + 600} } func TestExistingPlanScopePersistenceAndExpiry(t *testing.T) { f := newHTTPDirectory(t) p, raw := f.signPlan(t, func(p *Plan) { p.Label, p.ExistingTeam = "oficina", "Uk" }) verified, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now) if e != nil || verified.ExistingTeam != "Uk" { t.Fatal(e) } if e = f.plans.Submit(context.Background(), p, "", *f.now); e != nil { t.Fatal(e) } // A new reader, as after restart, must see the stored scope. reopened, _ := NewPlanStore(f.db, "directory", f.engine.sealer) v, e := reopened.Pending(context.Background(), *f.now) if e != nil || v.ExistingTeam != "Uk" { t.Fatal("scope not durable", e) } if _, e = reopened.Open(context.Background(), p.PlanID, *f.now, func(v PlanView) bool { return v.ExistingTeam == "Uk" }); e != nil { t.Fatal(e) } *f.now = f.now.Add(WindowLifetime * time.Second) if e = reopened.Sweep(context.Background(), *f.now); e != nil || countRows(t, f.db, "operator_plans") != 0 { t.Fatal("scope survived expiry", e) } for name, edit := range map[string]func(*Plan){ "label": func(p *Plan) { p.Label = "other" }, "retire": func(p *Plan) { p.Kind = "retire-apps"; p.DisplayName = "" }, "initialize": func(p *Plan) { p.Kind = "initialize"; p.Label = ""; p.Apps = nil; p.DisplayName = "" }, "invalid-sqid": func(p *Plan) { p.ExistingTeam = "oficina" }, "zero-sqid": func(p *Plan) { p.ExistingTeam = "bM" }, "ordinary-create-reserved": func(p *Plan) { p.ExistingTeam = "" }, "ordinary-add-reserved": func(p *Plan) { p.ExistingTeam = ""; p.Kind = "add-apps"; p.DisplayName = "" }, "unknown-app": func(p *Plan) { p.Apps = []string{"unknown"} }, } { t.Run(name, func(t *testing.T) { q := p edit(&q) if _, e := SignPlan(f.key, q, append(httpApps, "unknown")); e != ErrRefused { t.Fatal("invalid adoption scope admitted", e) } }) } } func TestExistingReservedLabelAndNativeWritesRefused(t *testing.T) { f := newDirectoryFixture(t) f.initialize(t) if _, e := f.seed(t, 1, "oficina"); e != ErrRefused { t.Fatal("native seed claimed reserved label", e) } h := adoptionDirectory(t) if _, e := h.seedHTTP(t, 2, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != ErrRefused { t.Fatal("different valid seed team", e) } if _, e := h.seedHTTP(t, 1, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != nil { t.Fatal(e) } for name, edit := range map[string]func(*ProvisionInput){ "team": func(p *ProvisionInput) { p.TeamSQID = "gb" }, "consumer": func(p *ProvisionInput) { p.Consumer = "other" }, "new-origin": func(p *ProvisionInput) { p.Audience = "https://oficina.docs.oficina.works" }, "other-app-origin": func(p *ProvisionInput) { p.Audience = "https://sheets.oficina.works" }, } { t.Run(name, func(t *testing.T) { _, e := h.run(t, "directory.provision-consumer", func(b InputBase) any { p := ProvisionInput{b, token(10), "Uk", "docs", "docs", "https://docs.oficina.works", 0} edit(&p) return p }) if e != ErrRefused { t.Fatal(e) } }) } raw := h.input(t, "directory.provision-consumer", func(b InputBase) any { return ProvisionInput{b, token(10), "Uk", "docs", "docs", "https://docs.oficina.works", 0} }) if _, e := h.directory.Execute(context.Background(), raw); e != ErrRefused { t.Fatal("native canonical provision", e) } } func TestExistingActivationDiscoveryAndRevocation(t *testing.T) { f, in := adoptionPending(t) store, e := directorydata.New(f.db, f.engine.sealer, directorydata.Config{Apps: httpApps, ValidateRoute: adoptionRoute}) if e != nil { t.Fatal(e) } if choices, e := store.AgentChoices(context.Background(), in.Owner); e != nil || len(choices) != 0 { t.Fatal("pending visible", e) } wrong := in wrong.TeamSQID = "gb" if _, e = f.run(t, "directory.verify-consumer", func(b InputBase) any { wrong.InputBase = b; return wrong }); e != ErrRefused { t.Fatal("wrong verify team", e) } raw := f.input(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }) if _, e = f.directory.Execute(context.Background(), raw); e != ErrRefused { t.Fatal("native canonical verification", e) } out, e := f.directory.ExecuteHTTP(context.Background(), raw) if e != nil { t.Fatal(e) } var window Result if json.Unmarshal(out, &window) != nil { t.Fatal("verify result") } ev := activation(in, window.Attempt) ev.AliasHost = "docs.oficina.works" if _, e = f.run(t, "directory.activate-consumer", func(b InputBase) any { return ActivationInput{b, ev} }); e != ErrRefused { t.Fatal("new-instance policy on existing app", e) } ev.Policy = existingActivationPolicy for name, edit := range map[string]func(*ActivationEvidence){"team": func(e *ActivationEvidence) { e.TeamSQID = "gb" }, "origin": func(e *ActivationEvidence) { e.Audience = "https://oficina.docs.oficina.works" }, "manifest": func(e *ActivationEvidence) { e.ManifestDigest = "" }} { t.Run(name, func(t *testing.T) { p := ev edit(&p) if _, e := f.run(t, "directory.activate-consumer", func(b InputBase) any { return ActivationInput{b, p} }); e != ErrRefused { t.Fatal(e) } }) } raw = f.input(t, "directory.activate-consumer", func(b InputBase) any { return ActivationInput{b, ev} }) if _, e = f.directory.Execute(context.Background(), raw); e != ErrRefused { t.Fatal("native adoption activation", e) } out, e = f.directory.ExecuteHTTP(context.Background(), raw) if e != nil { t.Fatal(e) } again, e := f.directory.ExecuteHTTP(context.Background(), raw) if e != nil || !bytes.Equal(out, again) { t.Fatal("activation replay", e) } choices, e := store.AgentChoices(context.Background(), in.Owner) if e != nil || len(choices) != 1 || choices[0].Origin != in.Audience { t.Fatal("live canonical discovery", e, choices) } // The old reader cannot consume these rows. Only an adoption-capable // build is a valid post-activation rollback target. old, _ := directorydata.New(f.db, f.engine.sealer, directorydata.Config{Apps: httpApps, ValidateRoute: func(r directorydata.Route) bool { return r.Origin == "https://"+r.Label+"."+r.App+".oficina.works" }}) if _, e = old.AgentChoices(context.Background(), in.Owner); e != directorydata.ErrUnavailable { t.Fatal("old reader compatibility unexpectedly changed", e) } compatible, _ := directorydata.New(f.db, f.engine.sealer, directorydata.Config{Apps: httpApps, ValidateRoute: adoptionRoute}) if choices, e = compatible.AgentChoices(context.Background(), in.Owner); e != nil || len(choices) != 1 { t.Fatal("compatible rollback reader", e) } if _, e = f.db.Exec("DELETE FROM memberships WHERE person_ref=?", in.Owner); e != nil { t.Fatal(e) } if choices, e = store.AgentChoices(context.Background(), in.Owner); e != nil || len(choices) != 0 { t.Fatal("removed member retained discovery", e) } } func openCredentialAdoption(t *testing.T, f *httpCredential) { openCredentialAdoptionPlan(t, f, "create-team", "Uk", "docs") } func openCredentialAdoptionPlan(t *testing.T, f *httpCredential, kind, team string, apps ...string) { t.Helper() p := Plan{Version: 1, Purpose: "operator-plan", Role: "credential", Origin: f.auth.Origin, Installation: token(1), Registry: token(2), Device: token(3), PlanID: token(f.attempt + 100), Kind: kind, Apps: apps, ExistingTeam: team, Issued: f.now.Unix(), Expires: f.now.Unix() + 600} index := "" if kind == "create-team" { p.Owner = ownerCanary index = credentialIndex(f.pepper, ownerCanary) } raw, e := SignPlan(f.key, p, httpApps) if e != nil { t.Fatal(e) } p, e = f.http.c.engine.verifier.VerifyPlan(raw, httpApps, *f.now) if e != nil { t.Fatal(e) } if e = f.plans.Submit(context.Background(), p, index, *f.now); e != nil { t.Fatal(e) } if _, e = f.plans.Open(context.Background(), p.PlanID, *f.now, func(v PlanView) bool { return v.ExistingTeam == team && (kind != "add-apps" || v.OwnerIndex == "") }); e != nil { t.Fatal(e) } } func TestExistingAddAppsKeepsTeamAndRegistrations(t *testing.T) { f, _ := adoptionPending(t) *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Kind, p.Label, p.DisplayName, p.ExistingTeam, p.Apps = "add-apps", "oficina", "", "Uk", []string{"sheets"} }) out, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { return ProvisionInput{b, token(10), "Uk", "sheets", "sheets", "https://sheets.oficina.works", 0} }) if e != nil { t.Fatal("add canonical app", e) } if countRows(t, f.db, "teams") != 1 || countRows(t, f.db, "memberships") != 1 || countRows(t, f.db, "team_instances") != 2 { t.Fatal("add apps replaced the team") } var result Result if json.Unmarshal(out, &result) != nil { t.Fatal("provision result") } c := newHTTPCredential(t) c.http.env["sheets"] = "https://sheets.oficina.works" openCredentialAdoption(t, c) if _, e = c.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { t.Fatal(e) } *c.now = c.now.Add(WindowLifetime * time.Second) openCredentialAdoptionPlan(t, c, "add-apps", "Uk", "sheets") // Use the actual directory record and signer. Both fixtures share the // canonical issuer/directory; this tests derivative verification too. c.http.provisioning = []roster.Key{{ID: keyID(f.directory.signer.SignPub()), Public: base64.RawURLEncoding.EncodeToString(f.directory.signer.SignPub())}} out, e = c.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, result.Record} }) if e != nil { t.Fatal("existing sheets registration", e) } var registered Result if json.Unmarshal(out, ®istered) != nil { t.Fatal("register result") } want, _ := ManifestDigest(c.http.env) if registered.Manifest != want || countRows(t, c.db, "consumers") != 0 { t.Fatal("add-apps modified registry") } } func TestExistingConfirmedTeamScopeIsIndependentOfStoredTeam(t *testing.T) { t.Run("seed", func(t *testing.T) { f := adoptionDirectory(t) *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Label, p.ExistingTeam = "oficina", "gb" }) if _, e := f.seedHTTP(t, 1, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != ErrRefused { t.Fatal("valid next team escaped confirmed scope", e) } }) t.Run("provision", func(t *testing.T) { f, _ := adoptionPending(t) *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Kind, p.Label, p.DisplayName, p.ExistingTeam, p.Apps = "add-apps", "oficina", "", "gb", []string{"sheets"} }) if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { return ProvisionInput{b, token(10), "Uk", "sheets", "sheets", "https://sheets.oficina.works", 0} }); e != ErrRefused { t.Fatal("valid stored team escaped confirmed scope", e) } }) t.Run("verify", func(t *testing.T) { f, in := adoptionPending(t) *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Kind, p.Label, p.DisplayName, p.ExistingTeam = "add-apps", "oficina", "", "gb" }) in.Issued = f.now.Unix() in.Expires = in.Issued + 600 if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != ErrRefused { t.Fatal("valid pending binding escaped confirmed scope", e) } }) } func TestExistingRegistrationPreservesManifestAndOwnerScope(t *testing.T) { f := newHTTPCredential(t) openCredentialAdoption(t, f) if _, e := f.run(t, "credential.owner-seed", func(b InputBase) any { return OwnerInput{b, "https://oficina.works", 2, "gb", ownerCanary, true} }); e != ErrRefused { t.Fatal("different owner-seed team", e) } if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { t.Fatal(e) } record := f.record(t, f.dirKey, "docs", "docs", "https://docs.oficina.works") out, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, record} }) if e != nil { t.Fatal(e) } var result Result if json.Unmarshal(out, &result) != nil { t.Fatal("result") } want, _ := ManifestDigest(f.http.env) if result.Manifest != want || countRows(t, f.db, "consumers") != 0 || f.http.env["docs"] != "https://docs.oficina.works" { t.Fatal("existing registration changed") } } func TestExistingRegistrationRejectsSubstitutions(t *testing.T) { for _, name := range []string{"missing", "wrong-origin", "wrong-id", "table-clash", "wrong-key", "new-origin", "other-team", "ordinary-window"} { t.Run(name, func(t *testing.T) { f := newHTTPCredential(t) if name == "ordinary-window" { f.openPlan(t, "create-team", "docs") } else { openCredentialAdoption(t, f) } if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { t.Fatal(e) } key := f.dirKey consumer, origin := "docs", "https://docs.oficina.works" switch name { case "missing": delete(f.http.env, "docs") case "wrong-origin": f.http.env["docs"] = "https://other.docs.oficina.works" case "wrong-id": consumer = "other" case "table-clash": if _, e := f.db.Exec("INSERT INTO consumers VALUES('docs','https://other.docs.oficina.works','docs','active','2026-11-02',?)", token(85)); e != nil { t.Fatal(e) } case "wrong-key": key, _ = family.Generate() case "new-origin": origin = "https://oficina.docs.oficina.works" case "other-team": if _, e := f.db.Exec("UPDATE operator_plans SET existing_team='gb'"); e != nil { t.Fatal(e) } } record := f.record(t, key, consumer, "docs", origin) if _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, record} }); e != ErrRefused { t.Fatal("substitution admitted", e) } }) } }