package operator import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "database/sql" "encoding/base64" "encoding/hex" "errors" "os" "path/filepath" "strings" "testing" "time" sharedseal "amadan.net/oficina/home/handoff/seal" "amadan.net/oficina/home/internal/home/directorydata" "amadan.net/oficina/home/roster" "amadan.net/rastrillo/rastrillo/assertion" family "amadan.net/rastrillo/rastrillo/crypto" rdb "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" "github.com/go-json-experiment/json" ) var httpApps = []string{"docs", "sheets"} // ---- directory ---- type httpDirectory struct { *directoryFixture plans *PlanStore plan byte } func newHTTPDirectory(t *testing.T) *httpDirectory { t.Helper() f := newDirectoryFixture(t) p := f.engine.verifier.pins p.Actions = []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"} v, e := NewVerifier(p) if e != nil { t.Fatal(e) } f.engine.verifier = v plans, e := NewPlanStore(f.db, "directory", f.engine.sealer) if e != nil { t.Fatal(e) } return &httpDirectory{f, plans, 200} } func (f *httpDirectory) signPlan(t *testing.T, mutate func(*Plan)) (Plan, []byte) { t.Helper() pins := f.engine.verifier.pins p := Plan{Version: 1, Purpose: "operator-plan", Role: pins.Role, Origin: pins.Origin, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device, PlanID: token(f.plan), Kind: "create-team", Apps: []string{"docs"}, Label: "alpha", DisplayName: "PRIVATE-TEAM-NAME-CANARY", Issued: f.now.Unix(), Expires: f.now.Unix() + PlanLifetime} f.plan++ if mutate != nil { mutate(&p) } raw, e := SignPlan(f.key, p, httpApps) if e != nil { t.Fatal(e) } return p, raw } // openPlan submits and confirms a plan, as Alta then Paul would. func (f *httpDirectory) openPlan(t *testing.T, mutate func(*Plan)) Plan { t.Helper() _, raw := f.signPlan(t, mutate) p, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now) if e != nil { t.Fatal(e) } if e = f.plans.Submit(context.Background(), p, "", *f.now); e != nil { t.Fatal(e) } if _, e = f.plans.Open(context.Background(), p.PlanID, *f.now, func(PlanView) bool { return true }); e != nil { t.Fatal(e) } return p } func (f *httpDirectory) run(t *testing.T, action string, build func(InputBase) any) ([]byte, error) { t.Helper() return f.directory.ExecuteHTTP(context.Background(), f.input(t, action, build)) } func (f *httpDirectory) seedHTTP(t *testing.T, id int64, label, name string) ([]byte, error) { t.Helper() sqid, _ := TeamSQID(id) proof := f.receipt(t, id) return f.run(t, "directory.seed-team", func(b InputBase) any { return SeedInput{b, token(10), id, sqid, label, name, proof} }) } // initialized brings the stream to: generation present, a create-team window // for alpha/docs open. func initializedHTTP(t *testing.T) *httpDirectory { t.Helper() f := newHTTPDirectory(t) 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) } // The initialize window stays open until it expires; one open per role. *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, nil) return f } func TestOperatorPlanVerifyRefusesWrongKeyContextPinsAndClock(t *testing.T) { f := newHTTPDirectory(t) _, good := f.signPlan(t, nil) if _, e := f.engine.verifier.VerifyPlan(good, httpApps, *f.now); e != nil { t.Fatal(e) } other, _ := family.Generate() pins := f.engine.verifier.pins base := Plan{Version: 1, Purpose: "operator-plan", Role: pins.Role, Origin: pins.Origin, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device, PlanID: token(99), Kind: "create-team", Apps: []string{"docs"}, Label: "alpha", DisplayName: "Alpha", Issued: f.now.Unix(), Expires: f.now.Unix() + 600} wrongKey, _ := SignPlan(other, base, httpApps) payload, _ := encode(base) sig, _ := family.Sign(f.key, InputContext, payload) wrongContext, _ := encode(envelope{1, keyID(f.key.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) cases := map[string][]byte{"key": wrongKey, "context": wrongContext} for name, mutate := range map[string]func(*Plan){ "role": func(p *Plan) { p.Role = "credential"; p.Label, p.DisplayName, p.Owner = "", "", "a@example.test" }, "origin": func(p *Plan) { p.Origin = "https://other.oficina.works" }, "device": func(p *Plan) { p.Device = token(77) }, "app": func(p *Plan) { p.Apps = []string{"calendar"} }, "duplicate": func(p *Plan) { p.Apps = []string{"docs", "docs"} }, "long": func(p *Plan) { p.Expires = p.Issued + PlanLifetime + 1 }, "future": func(p *Plan) { p.Issued, p.Expires = p.Issued+1, p.Issued+600 }, "name-on-add": func(p *Plan) { p.Kind = "add-apps" }, "no-name": func(p *Plan) { p.DisplayName = "" }, "owner": func(p *Plan) { p.Owner = "a@example.test" }, "label": func(p *Plan) { p.Label = "Alpha" }, "init-label": func(p *Plan) { p.Kind, p.Apps, p.DisplayName = "initialize", nil, "" }, "unknown-kind": func(p *Plan) { p.Kind = "rename" }, } { p := base mutate(&p) payload, _ := encode(p) sig, _ := family.Sign(f.key, PlanContext, payload) cases[name], _ = encode(envelope{1, keyID(f.key.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) } for name, raw := range cases { if _, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now); e != ErrRefused { t.Error(name, "accepted", e) } } if _, e := f.engine.verifier.VerifyPlan(good, httpApps, f.now.Add(PlanLifetime*time.Second)); e != ErrRefused { t.Fatal("expired plan accepted", e) } } func TestOperatorPlanStoreOnePendingOneOpenAndExpiredRowsDeleted(t *testing.T) { f := newHTTPDirectory(t) ctx := context.Background() _, raw := f.signPlan(t, nil) p, _ := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now) if e := f.plans.Submit(ctx, p, "", *f.now); e != nil { t.Fatal(e) } _, raw2 := f.signPlan(t, func(p *Plan) { p.Label = "beta" }) p2, _ := f.engine.verifier.VerifyPlan(raw2, httpApps, *f.now) if e := f.plans.Submit(ctx, p2, "", *f.now); e != ErrBusy { t.Fatal("second pending plan accepted", e) } if e := f.plans.Submit(ctx, p, "", *f.now); e != ErrBusy { t.Fatal("same plan twice", e) } view, e := f.plans.Pending(ctx, *f.now) if e != nil || view.ID != p.PlanID || view.DisplayName != p.DisplayName || view.Label != "alpha" || view.Prefix() != hex.EncodeToString(bytes.Repeat([]byte{200}, 4)) { t.Fatal("pending copy", e, view) } if _, e = f.plans.Open(ctx, p2.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrRefused { t.Fatal("opened a plan that is not the pending one", e) } if _, e = f.plans.Open(ctx, p.PlanID, *f.now, func(PlanView) bool { return false }); e != ErrRefused { t.Fatal("admit refusal ignored", e) } // Expiry: the row is deleted, not left behind, and the role is free. *f.now = time.Unix(p.Expires, 0) if _, e = f.plans.Open(ctx, p.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrRefused { t.Fatal("expired plan opened", e) } if countRows(t, f.db, "operator_plans") != 0 { t.Fatal("expired plan row left at rest") } // One open window blocks opening another until it expires. f.openPlan(t, nil) _, raw3 := f.signPlan(t, func(p *Plan) { p.Label = "gamma" }) p3, _ := f.engine.verifier.VerifyPlan(raw3, httpApps, *f.now) if e = f.plans.Submit(ctx, p3, "", *f.now); e != nil { t.Fatal("pending beside an open window", e) } if _, e = f.plans.Open(ctx, p3.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrBusy { t.Fatal("second open window", e) } *f.now = f.now.Add(WindowLifetime * time.Second) if e = f.plans.Sweep(ctx, *f.now); e != nil || countRows(t, f.db, "operator_plans") != 0 { t.Fatal("expired window row left", e) } // The display name is sealed at rest, and no plan bytes are stored. for _, suffix := range []string{"", "-wal"} { disk, e := os.ReadFile(f.path + suffix) if e != nil && !errors.Is(e, os.ErrNotExist) { t.Fatal(e) } secrets := [][]byte{[]byte("PRIVATE-TEAM-NAME-CANARY"), []byte(`"display_name":"PRIVATE-TEAM-NAME-CANARY"`)} for _, signed := range [][]byte{raw, raw2, raw3} { secrets = append(secrets, signedPlanParts(t, signed)...) } for _, secret := range secrets { if bytes.Contains(disk, secret) { t.Fatalf("plan bytes or name at rest: %.40q", secret) } } } } func TestOperatorHTTPDirectoryNeedsAnOpenWindowOfTheRightKind(t *testing.T) { f := newHTTPDirectory(t) init := func(b InputBase) any { return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"} } if _, e := f.run(t, "directory.initialize", init); e != ErrRefused { t.Fatal("no window: initialize accepted", e) } f.openPlan(t, nil) // create-team, not initialize if _, e := f.run(t, "directory.initialize", init); e != ErrRefused { t.Fatal("verb outside kind accepted", e) } if countRows(t, f.db, "roster_generation") != 0 || countRows(t, f.db, "directory_operator_state") != 0 { t.Fatal("refusal mutated") } } func TestOperatorHTTPSeedTeamBindsLabelAndExactSealedName(t *testing.T) { f := initializedHTTP(t) if _, e := f.seedHTTP(t, 1, "beta", "PRIVATE-TEAM-NAME-CANARY"); e != ErrRefused { t.Fatal("other label accepted", e) } for _, name := range []string{"PRIVATE-TEAM-NAME-CANARY ", "private-team-name-canary", "Other"} { if _, e := f.seedHTTP(t, 1, "alpha", name); e != ErrRefused { t.Fatalf("name %q accepted", name) } } if countRows(t, f.db, "teams") != 0 { t.Fatal("refused seed mutated") } if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil { t.Fatal(e) } var team int64 if e := f.db.QueryRow("SELECT team_id FROM operator_http_teams").Scan(&team); e != nil || team != 1 { t.Fatal("seed not fenced in", e) } } func TestOperatorHTTPProvenanceFenceAndScope(t *testing.T) { f := initializedHTTP(t) if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil { t.Fatal(e) } provision := func(sqid, app, consumer, audience string) error { _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { return ProvisionInput{b, token(10), sqid, app, consumer, audience, 0} }) return e } if e := provision("Uk", "sheets", "alpha-sheets", "https://alpha.sheets.oficina.works"); e != ErrRefused { t.Fatal("app outside the window's apps", e) } // A team the native path seeded (not this stream) is outside the fence, // even for a window naming its label. if _, e := f.db.Exec("INSERT INTO teams(sqid,label,sealed_name,created_at) VALUES('gb','beta',zeroblob(40),1)"); e != nil { t.Fatal(e) } if _, e := f.db.Exec("INSERT INTO memberships(team_id,person_ref,role) VALUES(2,'pr_aaaaaaaaaaaaaaaaaaaaaaaaaa','owner')"); e != nil { t.Fatal(e) } *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Kind, p.Label, p.DisplayName = "add-apps", "beta", "" }) if e := provision("gb", "docs", "beta-docs", "https://beta.docs.oficina.works"); e != ErrRefused { t.Fatal("fence: unfenced team reached", e) } if e := provision("Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works"); e != ErrRefused { t.Fatal("window for beta reached alpha", e) } if countRows(t, f.db, "team_instances") != 0 { t.Fatal("refusal mutated") } // Window expiring mid-run: the next operation refuses. *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Kind, p.DisplayName = "add-apps", "" }) if e := provision("Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works"); e != nil { t.Fatal(e) } *f.now = f.now.Add((WindowLifetime - 1) * time.Second) in := VerificationInput{Consumer: "alpha-docs", TeamSQID: "Uk", App: "docs", Audience: "https://alpha.docs.oficina.works", Generation: token(10), RecordSequence: 1, Epoch: 2, Owner: "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", Issued: f.now.Unix(), Expires: f.now.Unix() + 600} var digest []byte if e := f.db.QueryRow("SELECT record_digest FROM directory_operator_consumer_records").Scan(&digest); e != nil { t.Fatal(e) } in.RecordDigest = base64.RawURLEncoding.EncodeToString(digest) if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != nil { t.Fatal("inside window", e) } *f.now = f.now.Add(time.Second) if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != ErrRefused { t.Fatal("window expired mid-run but admitted", e) } } func TestOperatorHTTPDisableConsumerUnderRetireApps(t *testing.T) { f := initializedHTTP(t) if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil { t.Fatal(e) } if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { return ProvisionInput{b, token(10), "Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works", 0} }); e != nil { t.Fatal(e) } disable := func(b InputBase) any { return DisableInput{b, token(10), "Uk", "docs", "alpha-docs"} } if _, e := f.run(t, "directory.disable-consumer", disable); e != ErrRefused { t.Fatal("disable under create-team", e) } *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, func(p *Plan) { p.Kind, p.DisplayName = "retire-apps", "" }) if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { return ProvisionInput{b, token(10), "Uk", "sheets", "alpha-sheets", "https://alpha.sheets.oficina.works", 0} }); e != ErrRefused { t.Fatal("provision under retire-apps", e) } if _, e := f.run(t, "directory.disable-consumer", disable); e != nil { t.Fatal(e) } var state string var enabled int if e := f.db.QueryRow("SELECT i.state,c.enabled FROM team_instances i JOIN roster_consumers c USING(consumer_id)").Scan(&state, &enabled); e != nil || state != "disabled" || enabled != 0 { t.Fatal("not disabled", e) } var kind string if e := f.db.QueryRow("SELECT operation FROM roster_operator_receipts WHERE consumer_id='alpha-docs' ORDER BY rowid DESC LIMIT 1").Scan(&kind); e != nil || kind != "disable" { t.Fatal("no disable receipt", e) } if _, e := f.run(t, "directory.disable-consumer", disable); e != ErrRefused { t.Fatal("disabled twice", e) } } func TestOperatorHTTPReplayAfterWindowExpiryReturnsStoredResult(t *testing.T) { f := initializedHTTP(t) sqid, _ := TeamSQID(1) proof := f.receipt(t, 1) raw := f.input(t, "directory.seed-team", func(b InputBase) any { return SeedInput{b, token(10), 1, sqid, "alpha", "PRIVATE-TEAM-NAME-CANARY", proof} }) out, e := f.directory.ExecuteHTTP(context.Background(), raw) if e != nil { t.Fatal(e) } *f.now = f.now.Add(2 * WindowLifetime * time.Second) again, e := f.directory.ExecuteHTTP(context.Background(), raw) if e != nil || !bytes.Equal(again, out) || countRows(t, f.db, "teams") != 1 { t.Fatal("exact replay after expiry", e) } } func TestOperatorHTTPDirectoryInspectReportsStreamAndPlansOnly(t *testing.T) { f := initializedHTTP(t) pins := f.engine.verifier.pins raw, e := SignInspect(f.key, InspectChallenge{1, "operator-inspect", pins.Role, pins.Origin, pins.Installation, pins.Registry, pins.Device, token(66), f.now.Unix(), f.now.Unix() + 60}) if e != nil { t.Fatal(e) } out, e := f.directory.InspectHTTP(context.Background(), raw) if e != nil { t.Fatal(e) } var got HTTPInspection var head string if e = f.db.QueryRow("SELECT head FROM directory_operator_state").Scan(&head); e != nil { t.Fatal(e) } if json.Unmarshal(out, &got) != nil || got.Sequence != 1 || got.Head != head || got.Generation == nil || got.TeamSQID != "Uk" || got.OpenPlan == "" || got.WindowExpires == 0 { t.Fatal("inspection", string(out)) } if strings.Contains(string(out), "alpha") || strings.Contains(string(out), "CANARY") { t.Fatal("inspection carried plan contents") } } // ---- credential ---- type httpCredential struct { db *sql.DB path string now *time.Time key *family.Keypair auth Authorization http *CredentialHTTP plans *PlanStore dirKey *family.Keypair attempt byte pepper []byte resolved int } const ownerCanary = "owner-canary@example.test" func credentialIndex(pepper []byte, address string) string { m := hmac.New(sha256.New, pepper) m.Write([]byte(strings.ToLower(address))) return hex.EncodeToString(m.Sum(nil)) } func newHTTPCredential(t *testing.T) *httpCredential { t.Helper() path := filepath.Join(t.TempDir(), "credential.db") handle, e := rdb.Open(path, nil) if e != nil { t.Fatal(e) } t.Cleanup(func() { handle.Close() }) if _, e = migrate.Apply(context.Background(), handle, migrate.Merge(CredentialSchema, CredentialHTTPSchema)); e != nil { t.Fatal(e) } db := handle.Writer() if _, e = db.Exec("CREATE TABLE people(person_ref TEXT PRIMARY KEY, blind_index TEXT UNIQUE)"); e != nil { t.Fatal(e) } f := &httpCredential{db: db, path: path, attempt: 30, pepper: bytes.Repeat([]byte{9}, 32)} if _, e = db.Exec("INSERT INTO people VALUES('pr_aaaaaaaaaaaaaaaaaaaaaaaaaa',?)", credentialIndex(f.pepper, ownerCanary)); e != nil { t.Fatal(e) } f.key, _ = family.Generate() f.dirKey, _ = family.Generate() owner, _ := family.Generate() browser, _ := family.Generate() f.auth = Authorization{Version: 1, Purpose: "operator-input", Role: "credential", Origin: "https://id.oficina.works", Installation: token(1), Registry: token(2), Device: token(3), JournalSequence: 1, Issued: 2000000000, Expires: 2000000300} v, e := NewVerifier(Pins{"credential", f.auth.Origin, token(1), token(2), token(3), base64.RawURLEncoding.EncodeToString(f.key.SignPub()), []string{"credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect"}}) if e != nil { t.Fatal(e) } now := time.Unix(f.auth.Issued, 0) f.now = &now sealer, _ := sharedseal.New(bytes.Repeat([]byte{6}, 32), "oficina/operator") engine, e := NewEngine(db, v, sealer, bytes.Repeat([]byte{7}, 32), func() time.Time { return *f.now }) if e != nil { t.Fatal(e) } resolve := func(ctx context.Context, c *sql.Conn, address string, existing bool, _ time.Time) (string, bool, error) { f.resolved++ var ref string e := c.QueryRowContext(ctx, "SELECT person_ref FROM people WHERE blind_index=?", credentialIndex(f.pepper, address)).Scan(&ref) if errors.Is(e, sql.ErrNoRows) { return "", false, nil } return ref, e == nil, e } c, e := NewCredential(engine, "https://oficina.works", owner, [][]byte{browser.SignPub()}, resolve) if e != nil { t.Fatal(e) } env := map[string]string{"directory": "https://oficina.works", "docs": "https://docs.oficina.works"} // The registry reload's own admission (internal/home registryAdmits): // a consumer-name ID and an audience the assertion verifier accepts. assertionKeys := map[string][]byte{keyID(browser.SignPub()): browser.SignPub()} admit := func(id, origin string) bool { _, err := assertion.NewVerifier(f.auth.Origin, origin, assertionKeys) return atom(id, 64) && err == nil } f.http, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.dirKey.SignPub()), env, httpApps, func(a string) string { return credentialIndex(f.pepper, a) }, admit) if e != nil { t.Fatal(e) } if _, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.key.SignPub()), env, httpApps, func(string) string { return "" }, admit); e != ErrRefused { t.Fatal("Alta's key accepted as the directory provisioning pin") } f.plans, _ = NewPlanStore(db, "credential", sealer) return f } func (f *httpCredential) openPlan(t *testing.T, kind 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, 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) } if p, e = f.http.c.engine.verifier.VerifyPlan(raw, httpApps, *f.now); 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(PlanView) bool { return true }); e != nil { t.Fatal(e) } } func (f *httpCredential) run(t *testing.T, action string, input func(InputBase) any) ([]byte, error) { t.Helper() a := f.auth var sequence int64 var head string if e := f.db.QueryRow("SELECT sequence,head FROM credential_operator_state").Scan(&sequence, &head); e != nil && !errors.Is(e, sql.ErrNoRows) { t.Fatal(e) } a.Sequence, a.Previous, a.Initial = sequence+1, head, sequence == 0 a.Action, a.OperationID = action, token(f.attempt) f.attempt++ a.Issued, a.Expires = f.now.Unix(), f.now.Unix()+300 raw, e := SignRequest(f.key, a, input(InputBase{1, action, a.OperationID})) if e != nil { t.Fatal(e) } return f.http.ExecuteHTTP(context.Background(), raw) } func (f *httpCredential) record(t *testing.T, key *family.Keypair, consumer, app, audience string) []byte { t.Helper() page, _ := family.Generate() b := roster.Bindings{Issuer: f.auth.Origin, Directory: "https://oficina.works", Consumer: consumer, App: app, Team: "Uk", Audience: audience} raw, e := roster.SignProvisioning(key, keyID(key.SignPub()), roster.Provisioning{Version: 1, Operation: token(70), Sequence: 1, Bindings: b, Generation: token(10), MinEpoch: 2, Keys: []roster.Key{{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(page.SignPub())}}}) if e != nil { t.Fatal(e) } return raw } func ownerSeedInput(address string, existing bool) func(InputBase) any { return func(b InputBase) any { return OwnerInput{b, "https://oficina.works", 1, "Uk", address, existing} } } func TestOperatorHTTPOwnerSeedIsExistingOnlyAndTheTypedOwner(t *testing.T) { f := newHTTPCredential(t) if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != ErrRefused { t.Fatal("no window", e) } f.openPlan(t, "create-team", "docs") if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, false)); e != ErrRefused { t.Fatal("minting owner-seed admitted", e) } if _, e := f.db.Exec("INSERT INTO people VALUES('pr_bbbbbbbbbbbbbbbbbbbbbbbbbb',?)", credentialIndex(f.pepper, "other@example.test")); e != nil { t.Fatal(e) } if _, e := f.run(t, "credential.owner-seed", ownerSeedInput("other@example.test", true)); e != ErrRefused { t.Fatal("owner other than the confirmed one", e) } if f.resolved != 0 { t.Fatal("refused owner reached resolution") } out, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)) if e != nil { t.Fatal(e) } var result Result if json.Unmarshal(out, &result) != nil || len(result.Receipt) == 0 { t.Fatal("no receipt") } // An expired receipt needs a new owner-seed operation under a live window. *f.now = f.now.Add(301 * time.Second) if _, e = f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { t.Fatal("fresh owner-seed in a live window", e) } disk, _ := os.ReadFile(f.path) wal, _ := os.ReadFile(f.path + "-wal") if bytes.Contains(append(disk, wal...), []byte(ownerCanary)) { t.Fatal("owner address at rest") } } func TestOperatorHTTPRegisterConsumerOnlyFromTheDirectoryRecord(t *testing.T) { f := newHTTPCredential(t) // The credential stream opens with owner-seed (sequence 1, initial // authority); every other verb refuses Initial. f.openPlan(t, "create-team", "docs") if _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works")} }); e != ErrRefused { t.Fatal("register as the stream's first operation", e) } if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { t.Fatal(e) } register := func(record []byte) error { _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, record} }) return e } other, _ := family.Generate() for name, record := range map[string][]byte{ "none": []byte(`{}`), "other-key": f.record(t, other, "alpha-docs", "docs", "https://alpha.docs.oficina.works"), "alta-key": f.record(t, f.key, "alpha-docs", "docs", "https://alpha.docs.oficina.works"), "app": f.record(t, f.dirKey, "alpha-sheets", "sheets", "https://alpha.sheets.oficina.works"), "env-origin": f.record(t, f.dirKey, "team-docs", "docs", "https://docs.oficina.works"), "env-id": f.record(t, f.dirKey, "docs", "docs", "https://alpha.docs.oficina.works"), "directory": f.record(t, f.dirKey, "directory", "docs", "https://alpha.docs.oficina.works"), // Blocker 1, #94: an audience the registry reload refuses (the // credential origin itself) must never be committed. "credential-origin": f.record(t, f.dirKey, "alpha-docs", "docs", f.auth.Origin), "issuer-swap": nil, } { if record == nil { page, _ := family.Generate() b := roster.Bindings{Issuer: "https://id.other.works", Directory: "https://oficina.works", Consumer: "alpha-docs", App: "docs", Team: "Uk", Audience: "https://alpha.docs.oficina.works"} record, _ = roster.SignProvisioning(f.dirKey, keyID(f.dirKey.SignPub()), roster.Provisioning{Version: 1, Operation: token(70), Sequence: 1, Bindings: b, Generation: token(10), MinEpoch: 2, Keys: []roster.Key{{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(page.SignPub())}}}) } if e := register(record); e != ErrRefused { t.Error(name, "registered", e) } } if countRows(t, f.db, "consumers") != 0 { t.Fatal("refused registration wrote") } good := f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works") if e := register(good); e != nil { t.Fatal(e) } if e := register(good); e != ErrRefused { t.Fatal("same consumer twice", e) } var id, origin, app, state string if e := f.db.QueryRow("SELECT consumer_id,origin,app,state FROM consumers").Scan(&id, &origin, &app, &state); e != nil || id != "alpha-docs" || origin != "https://alpha.docs.oficina.works" || app != "docs" || state != "active" { t.Fatal("registered row", e) } // Retire needs a retire-apps window, and a retired origin is dead for good. retire := func() error { _, e := f.run(t, "credential.retire-consumer", func(b InputBase) any { return RetireInput{b, "alpha-docs"} }) return e } if e := retire(); e != ErrRefused { t.Fatal("retire under add-apps", e) } // A retire-apps window for another app does not reach this one. *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, "retire-apps", "sheets") if e := retire(); e != ErrRefused { t.Fatal("retired an app outside the window's apps", e) } var still string if e := f.db.QueryRow("SELECT state FROM consumers WHERE consumer_id='alpha-docs'").Scan(&still); e != nil || still != "active" { t.Fatal("refused retire changed the row", still, e) } *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, "retire-apps", "docs") out, e := f.run(t, "credential.retire-consumer", func(b InputBase) any { return RetireInput{b, "alpha-docs"} }) if e != nil { t.Fatal(e) } var result Result want, _ := ManifestDigest(map[string]string{"directory": "https://oficina.works", "docs": "https://docs.oficina.works"}) if json.Unmarshal(out, &result) != nil || result.Manifest != want { t.Fatal("manifest digest after retire", result.Manifest) } if _, e = f.db.Exec("UPDATE consumers SET state='active'"); e == nil { t.Fatal("retired consumer reactivated") } *f.now = f.now.Add(WindowLifetime * time.Second) f.openPlan(t, "add-apps", "docs") if e := register(good); e != ErrRefused { t.Fatal("retired hostname reused", e) } } func TestOperatorHTTPConsumerTableCap(t *testing.T) { f := newHTTPCredential(t) tx, _ := f.db.Begin() for i := 0; i < 4096; i++ { if _, e := tx.Exec("INSERT INTO consumers VALUES(?,?,'docs','active','2026-10-27',?)", "c"+strings.Repeat("x", 1)+itoa(i), "https://t"+itoa(i)+".docs.oficina.works", token(1)); e != nil { t.Fatal(i, e) } } if e := tx.Commit(); e != nil { t.Fatal(e) } f.openPlan(t, "create-team", "docs") if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { t.Fatal(e) } _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works")} }) if e != ErrRefused || countRows(t, f.db, "consumers") != 4096 { t.Fatal("4,097th consumer", e) } } func itoa(i int) string { if i == 0 { return "0" } s := "" for ; i > 0; i /= 10 { s = string(rune('0'+i%10)) + s } return s } func TestOperatorHTTPCredentialInspect(t *testing.T) { f := newHTTPCredential(t) f.openPlan(t, "create-team", "docs") if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { t.Fatal(e) } raw, e := SignInspect(f.key, InspectChallenge{1, "operator-inspect", "credential", f.auth.Origin, token(1), token(2), token(3), token(66), f.now.Unix(), f.now.Unix() + 60}) if e != nil { t.Fatal(e) } out, e := f.http.InspectHTTP(context.Background(), raw) var got HTTPInspection if e != nil || json.Unmarshal(out, &got) != nil || got.Role != "credential" || got.Sequence != 1 || !CanonicalToken(got.Head) || got.OpenPlan == "" || got.Generation != nil { t.Fatal("credential inspect", e, string(out)) } other, _ := family.Generate() raw, _ = SignInspect(other, InspectChallenge{1, "operator-inspect", "credential", f.auth.Origin, token(1), token(2), token(3), token(66), f.now.Unix(), f.now.Unix() + 60}) if _, e = f.http.InspectHTTP(context.Background(), raw); e != ErrRefused { t.Fatal("foreign inspect key", e) } _ = directorydata.ValidLabel } // signedPlanParts is what "the signed plan bytes" means at rest: the payload // and the signature, raw and as their base64url text. func signedPlanParts(t *testing.T, raw []byte) [][]byte { t.Helper() var env envelope if e := json.Unmarshal(raw, &env); e != nil { t.Fatal(e) } payload, ok := canonical(env.Payload, -1) sig, ok2 := canonical(env.Signature, 64) if !ok || !ok2 { t.Fatal("plan envelope") } return [][]byte{payload, sig, []byte(env.Payload), []byte(env.Signature)} } // An open window's row is gone once it expires, swept before the next // operation even though that operation is refused (its rollback must not // bring the row back). func TestOperatorHTTPExpiredWindowRowSweptBeforeARefusedOperation(t *testing.T) { f := newHTTPDirectory(t) f.openPlan(t, nil) *f.now = f.now.Add(WindowLifetime * time.Second) if _, e := f.run(t, "directory.initialize", func(b InputBase) any { return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"} }); e != ErrRefused { t.Fatal("operation after the window", e) } if countRows(t, f.db, "operator_plans") != 0 { t.Fatal("expired window row left at rest") } }