Operator: registration admits only what the reload admits; review round 4 fixes
Fable's whole-code review, discussion 94. Blocker 1: NewCredentialHTTP takes admit(id, origin), wired to the registry reload's own predicate (registryAdmits: consumerName and assertion.NewVerifier), and register-consumer calls it before the collision checks and the INSERT, so no committed row can be one the reload, and the next boot, would refuse. Tests: a record whose audience is the credential origin is refused with the table empty; TestOperatorRegisteredRowsAlwaysReload registers through the HTTP fixture, refuses two bad audiences, and a fresh registry load and a fresh NewRuntime both succeed. Blocker 2: a retire-apps window for sheets refuses retiring alpha-docs and leaves it active; the docs window then retires it. Non-blocking notes: - the post-commit registry reload runs on context.Background(); - boot schedules sweepAt for every plan row that survives the boot sweep; - the confirm POSTs' freshness/method check now lives only inside the write (the Open admit closure), and a stale session there gets the 303; both mutants are killed; - TestOperatorPagesUnderTheScriptlessSweep puts both confirm pages and both transport routes under the served-CSP and no-script sweep; - the legacy schema diagnostic skips exactly the directory's HTTP migration set (ServingSchema less Schema), so a true mismatch is not hidden behind a standing false one; a change to that set is still a mismatch; - a body that is neither a verified operation nor a verified inspect logs verb '-'.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+320
−28
internal/home/consumer_registry.go+15 −4internal/home/legacy_schema_diagnostic.go+57 −0internal/home/legacy_schema_diagnostic_test.go+30 −0internal/home/noscript_test.go+70 −0internal/home/operator_ceremony_test.go+38 −0internal/home/operator_confirm.go+27 −6internal/home/operator_http.go+21 −3internal/operator/http_verbs.go+8 −5internal/operator/http_verbs_test.go+31 −10internal/operator/plan.go+23 −0
diff --git a/internal/home/consumer_registry.go b/internal/home/consumer_registry.go| index f013ec1..e0248d9 100644 |
| --- a/internal/home/consumer_registry.go |
| +++ b/internal/home/consumer_registry.go |
| @@ -69,11 +69,9 @@ func (r *consumerRegistry) load(ctx context.Context, db *sql.DB, credential stri |
| return errExchangeConfig |
| } |
| union := maps.Clone(r.env) |
| + admits := registryAdmits(credential, keys) |
| for id, origin := range active { |
| - if !consumerName(id) { |
| - return errExchangeConfig |
| - } |
| - if _, err := assertion.NewVerifier(credential, origin, keys); err != nil { |
| + if !admits(id, origin) { |
| return errExchangeConfig |
| } |
| union[id] = origin |
| @@ -94,3 +92,16 @@ func (a *App) consumers() map[string]string { |
| } |
| return a.runtime.consumers |
| } |
| + |
| +// registryAdmits is the one admission rule for a table consumer: the reload |
| +// applies it to every row, and credential.register-consumer applies it before |
| +// it writes one, so no committed row can be one the next boot refuses. |
| +func registryAdmits(credential string, keys map[string][]byte) func(id, origin string) bool { |
| + return func(id, origin string) bool { |
| + if !consumerName(id) { |
| + return false |
| + } |
| + _, err := assertion.NewVerifier(credential, origin, keys) |
| + return err == nil |
| + } |
| +} |
diff --git a/internal/home/legacy_schema_diagnostic.go b/internal/home/legacy_schema_diagnostic.go| index 08ad742..6250921 100644 |
| --- a/internal/home/legacy_schema_diagnostic.go |
| +++ b/internal/home/legacy_schema_diagnostic.go |
| @@ -7,6 +7,7 @@ import ( |
| _ "embed" |
| "encoding/json" |
| "log/slog" |
| + "sync" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| ) |
| @@ -94,6 +95,55 @@ func inspectLegacySchema(ctx context.Context, d *sql.DB) (result legacyDiagnosti |
| return |
| } |
| +// legacyDiagnosticAdditive is the operator endpoint's additive directory |
| +// set (oficina_directory_operator_http): its ledger rows and exactly the |
| +// objects it creates are not the historical profile's business, and are |
| +// skipped so that every directory boot does not read "mismatch" and hide a |
| +// true one behind it. Only exact matches are skipped; a changed HTTP table is |
| +// still a mismatch. If the set cannot be replayed, nothing is skipped. |
| +var legacyDiagnosticAdditive = sync.OnceValues(func() (map[string]string, map[string]legacyDiagnosticObject) { |
| + ledger, objects := map[string]string{}, map[string]legacyDiagnosticObject{} |
| + // ServingSchema less Schema: the additive set, without reaching into the |
| + // operator package (TestLegacyDiagnosticCannotExpandAcceptedProfiles). |
| + frozen := map[string]bool{} |
| + for _, m := range (Runtime{role: "directory"}).Schema().All() { |
| + frozen[m.ID] = true |
| + } |
| + var all []migrate.Migration |
| + for _, m := range (Runtime{role: "directory"}).ServingSchema().All() { |
| + if !frozen[m.ID] { |
| + all = append(all, m) |
| + } |
| + } |
| + if len(all) == 0 { |
| + return nil, nil |
| + } |
| + d, err := migrate.Replay(context.Background(), all) |
| + if err != nil { |
| + return nil, nil |
| + } |
| + defer d.Close() |
| + for _, m := range all { |
| + ledger[m.ID] = migrate.Checksum(m.SQL) |
| + } |
| + rows, err := d.Query("SELECT type,name,tbl_name,coalesce(sql,'') FROM sqlite_schema") |
| + if err != nil { |
| + return nil, nil |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var o legacyDiagnosticObject |
| + if rows.Scan(&o.Type, &o.Name, &o.Table, &o.SQL) != nil { |
| + return nil, nil |
| + } |
| + objects[o.Type+"/"+o.Name] = o |
| + } |
| + if rows.Err() != nil { |
| + return nil, nil |
| + } |
| + return ledger, objects |
| +}) |
| + |
| func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResult { |
| unavailable := legacyDiagnosticResult{status: "unavailable"} |
| mismatch := legacyDiagnosticResult{status: "mismatch"} |
| @@ -101,6 +151,7 @@ func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResul |
| if !ok { |
| return unavailable |
| } |
| + additiveLedger, additiveObjects := legacyDiagnosticAdditive() |
| expected := map[string]string{} |
| for _, m := range migrations { |
| expected[m.ID] = migrate.Checksum(m.SQL) |
| @@ -120,6 +171,9 @@ func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResul |
| rows.Close() |
| return unavailable |
| } |
| + if sum.Valid && additiveLedger[id.String] == sum.String && id.Valid { |
| + continue |
| + } |
| if !id.Valid || !sum.Valid || count > legacyDiagnosticMaxRows || expected[id.String] != sum.String { |
| matched = false |
| } |
| @@ -155,6 +209,9 @@ func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResul |
| } |
| object := legacyDiagnosticObject{kind.String, name.String, table.String, statement.String} |
| key := kind.String + "/" + name.String |
| + if extra, ok := additiveObjects[key]; ok && extra == object && kind.Valid && name.Valid && table.Valid && statement.Valid { |
| + continue |
| + } |
| prior, exists := objects[key] |
| if !kind.Valid || !name.Valid || !table.Valid || !statement.Valid || count > legacyDiagnosticMaxRows || !exists || prior != object { |
| matched = false |
diff --git a/internal/home/legacy_schema_diagnostic_test.go b/internal/home/legacy_schema_diagnostic_test.go| index 4e61072..3d7ef08 100644 |
| --- a/internal/home/legacy_schema_diagnostic_test.go |
| +++ b/internal/home/legacy_schema_diagnostic_test.go |
| @@ -400,3 +400,33 @@ func TestLegacyDiagnosticBeginFailureEvictsOpenTransaction(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// The operator endpoint's additive directory set (ServingSchema) does not |
| +// turn every directory boot into "mismatch"; a change to one of its own |
| +// tables still is one. |
| +func TestLegacyDiagnosticSkipsOnlyTheExactOperatorHTTPSet(t *testing.T) { |
| + d := legacyDiagnosticFixture(t, true, true) |
| + if _, err := migrate.Apply(t.Context(), d, (Runtime{role: "directory"}).ServingSchema()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if result := inspectLegacySchema(t.Context(), d.Writer()); result.status != "match" { |
| + t.Fatal("serving schema read as a mismatch", result) |
| + } |
| + for name, statement := range map[string]string{ |
| + "changed": "ALTER TABLE operator_plans ADD COLUMN foreign_value INTEGER", |
| + "ledger": "UPDATE rastrillo_migrations SET checksum='" + strings.Repeat("0", 64) + "' WHERE id LIKE 'oficina_directory_operator_http/%'", |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + d := legacyDiagnosticFixture(t, true, true) |
| + if _, err := migrate.Apply(t.Context(), d, (Runtime{role: "directory"}).ServingSchema()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec(statement); err != nil { |
| + t.Fatal(err) |
| + } |
| + if result := inspectLegacySchema(t.Context(), d.Writer()); result.status != "mismatch" { |
| + t.Fatal("drift in the HTTP set hidden", result) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/home/noscript_test.go b/internal/home/noscript_test.go| index 98795a8..3e0cc40 100644 |
| --- a/internal/home/noscript_test.go |
| +++ b/internal/home/noscript_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "io/fs" |
| "net/http" |
| "net/http/httptest" |
| + "net/url" |
| "os" |
| "path" |
| "path/filepath" |
| @@ -15,6 +16,7 @@ import ( |
| "testing" |
| "amadan.net/oficina/estilo.git/theme" |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/ui" |
| "github.com/go-chi/chi/v5" |
| @@ -508,3 +510,71 @@ var busyScript = regexp.MustCompile(`<script defer src=["']/static/busy\.js\?v=[ |
| func hasOtherScript(body string) bool { |
| return strings.Contains(busyScript.ReplaceAllString(body, ""), "<script") |
| } |
| + |
| +// The operator endpoint's pages and routes, which the sweep above cannot |
| +// reach (its fixture has no HOME_OPERATOR_HTTP): both confirm pages on both |
| +// outcomes and both transport routes, on both origins, under the served |
| +// policy. No inline or eval'd script, and no script but estilo's busy rule. |
| +func TestOperatorPagesUnderTheScriptlessSweep(t *testing.T) { |
| + f := newOperatorFixture(t) |
| + signInFully(t, f.credential, sealtest.CanaryAddress) |
| + f.submit(t, "directory", "create-team", []string{"docs"}) |
| + f.submit(t, "credential", "create-team", []string{"docs"}) |
| + paul := f.paulCredential(t) |
| + directory := f.paulDirectory(t, paul) |
| + stranger := signInFully(t, f.credential, "stranger@example.invalid") |
| + type probe struct { |
| + role, method, path string |
| + form url.Values |
| + cookie *http.Cookie |
| + } |
| + probes := []probe{ |
| + {"credential", "GET", operatorConfirm, nil, paul}, |
| + {"credential", "GET", operatorConfirm, nil, stranger}, |
| + {"credential", "GET", operatorConfirm, nil, nil}, |
| + {"credential", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}, "owner": {"wrong@example.invalid"}}, paul}, |
| + {"credential", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}, "owner": {sealtest.CanaryAddress}}, paul}, |
| + {"directory", "GET", operatorConfirm, nil, directory}, |
| + {"directory", "GET", operatorConfirm, nil, nil}, |
| + {"directory", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(91)}}, directory}, |
| + {"directory", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}}, directory}, |
| + {"credential", "POST", operatorPath, nil, nil}, |
| + {"directory", "POST", operatorPlanPath, nil, nil}, |
| + } |
| + for i, p := range probes { |
| + a := f.app(p.role) |
| + mux := http.NewServeMux() |
| + mux.Handle("/", a.Router()) |
| + h, cleanup, err := rastrillo.Handler(rastrillo.Options{Mux: mux, Logger: quietLogger(), CSP: a.SecurityPolicy()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cleanup != nil { |
| + t.Cleanup(func() { cleanup() }) |
| + } |
| + body := "" |
| + if p.form != nil { |
| + body = p.form.Encode() |
| + } |
| + req := httptest.NewRequest(p.method, roleOrigin(p.role)+p.path, strings.NewReader(body)) |
| + if p.form != nil { |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", roleOrigin(p.role)) |
| + } |
| + if p.cookie != nil { |
| + req.AddCookie(p.cookie) |
| + } |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, req) |
| + csp := rec.Header().Get("Content-Security-Policy") |
| + if !strings.Contains(csp, "default-src 'self'") || strings.Contains(csp, "'unsafe-eval'") || strings.Contains(strings.Replace(csp, "style-src 'self' 'unsafe-inline'", "", 1), "'unsafe-inline'") { |
| + t.Errorf("probe %d (%s %s %s): CSP %q", i, p.role, p.method, p.path, csp) |
| + } |
| + if hasOtherScript(rec.Body.String()) { |
| + t.Errorf("probe %d (%s %s %s, %d) carries a script beyond busy.js", i, p.role, p.method, p.path, rec.Code) |
| + } |
| + } |
| + if f.openCount(t, f.directory) != 1 || f.openCount(t, f.credential.App) != 1 { |
| + t.Fatal("the sweep did not reach the confirm pages' success paths") |
| + } |
| +} |
diff --git a/internal/home/operator_ceremony_test.go b/internal/home/operator_ceremony_test.go| index 47515f2..99366ed 100644 |
| --- a/internal/home/operator_ceremony_test.go |
| +++ b/internal/home/operator_ceremony_test.go |
| @@ -16,7 +16,9 @@ import ( |
| "amadan.net/oficina/home/internal/home/directorydata" |
| "amadan.net/oficina/home/internal/home/sealtest" |
| "amadan.net/oficina/home/internal/operator" |
| + "amadan.net/oficina/home/roster" |
| "amadan.net/rastrillo/rastrillo/assertion" |
| + family "amadan.net/rastrillo/rastrillo/crypto" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| json "github.com/go-json-experiment/json" |
| @@ -438,3 +440,39 @@ func TestOperatorRoutesAreNoStore(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// Blocker 1, #94: register-consumer admits exactly what the registry reload |
| +// admits, so every row it commits reloads — and boots — cleanly. |
| +func TestOperatorRegisteredRowsAlwaysReload(t *testing.T) { |
| + f := newOperatorFixture(t) |
| + signInFully(t, f.credential, sealtest.CanaryAddress) |
| + f.provisionTeam(t) |
| + page, _ := family.Generate() |
| + for _, audience := range []string{Origin, "https://id.oficina.works:8443"} { |
| + b := roster.Bindings{Issuer: Origin, Directory: directoryOrigin, Consumer: "self-docs", App: "docs", Team: "Uk", Audience: audience} |
| + record, err := roster.SignProvisioning(f.provisioning, hexID(f.provisioning), roster.Provisioning{Version: 1, Operation: fixtureToken(71), Sequence: 1, Bindings: b, Generation: generationToken(), MinEpoch: 2, Keys: []roster.Key{{ID: hexID(page), Public: rawURLPub(page)}}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec, _ := f.run(t, "credential", "credential.register-consumer", func(in operator.InputBase) any { |
| + return operator.RegisterInput{InputBase: in, Record: record} |
| + }); rec.Code != 403 { |
| + t.Fatal("registered an audience the reload refuses", audience, rec.Code) |
| + } |
| + } |
| + if f.countRows(t, f.credential.App, "consumers") != 1 { |
| + t.Fatal("refused registration wrote a row") |
| + } |
| + fresh := newConsumerRegistry(f.credential.runtime.consumers) |
| + if err := fresh.load(context.Background(), f.credential.db.Writer(), Origin, f.credential.runtime.keys); err != nil { |
| + t.Fatal("a committed row fails the reload", err) |
| + } |
| + if _, ok := fresh.snapshot()[operatorLabel+"-docs"]; !ok { |
| + t.Fatal("registered consumer missing from a fresh union") |
| + } |
| + cfg := *f.credential.runtime |
| + cfg.registry, cfg.operator = nil, nil |
| + if _, err := NewRuntime(cfg, f.credential.db, quietLogger()); err != nil { |
| + t.Fatal("the credential role no longer boots", err) |
| + } |
| +} |
diff --git a/internal/home/operator_confirm.go b/internal/home/operator_confirm.go| index e2fb9c2..2ec2082 100644 |
| --- a/internal/home/operator_confirm.go |
| +++ b/internal/home/operator_confirm.go |
| @@ -77,7 +77,9 @@ func (a *App) directoryOperatorSession(w http.ResponseWriter, r *http.Request) ( |
| a.notFound(w, r) |
| return s, false |
| } |
| - if !ok || !directoryFresh(s, time.Now()) { |
| + // A POST's freshness is checked inside the write only (the Open admit |
| + // closure), so that check is the one that counts. |
| + if !ok || (r.Method == http.MethodGet && !directoryFresh(s, time.Now())) { |
| if r.Method != http.MethodGet { |
| http.Redirect(w, r, operatorConfirm, http.StatusSeeOther) |
| return s, false |
| @@ -113,10 +115,20 @@ func (a *App) handleDirectoryConfirmPost(w http.ResponseWriter, r *http.Request) |
| a.renderOperatorRefusal(w, r, "operator_confirm.html", http.StatusBadRequest, "Nothing was opened.") |
| return |
| } |
| + stale := false |
| v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(operator.PlanView) bool { |
| - // Subject and freshness again, inside the write. |
| - return s.Subject == a.op.subject && directoryFresh(s, time.Now()) |
| + // Subject and freshness inside the write: the POST's only freshness |
| + // check. A stale session goes back through the GET's fresh exchange. |
| + if s.Subject != a.op.subject || !directoryFresh(s, time.Now()) { |
| + stale = true |
| + return false |
| + } |
| + return true |
| }) |
| + if stale { |
| + http.Redirect(w, r, operatorConfirm, http.StatusSeeOther) |
| + return |
| + } |
| a.afterOpen(w, r, "operator_confirm.html", v, err, func(view operator.PlanView) map[string]any { |
| return map[string]any{"Opened": operatorTime(view.WindowExpires), "Prefix": view.Prefix()} |
| }) |
| @@ -169,7 +181,9 @@ func (a *App) credentialOperatorSession(w http.ResponseWriter, r *http.Request) |
| a.notFound(w, r) |
| return s, false |
| } |
| - if !ok || !credentialFresh(s, time.Now()) { |
| + // A POST's freshness and method are checked inside the write only (the |
| + // Open admit closure), so that check is the one that counts. |
| + if !ok || (r.Method == http.MethodGet && !credentialFresh(s, time.Now())) { |
| if r.Method != http.MethodGet { |
| http.Redirect(w, r, operatorConfirm, http.StatusSeeOther) |
| return s, false |
| @@ -228,10 +242,13 @@ func (a *App) handleCredentialConfirmPost(w http.ResponseWriter, r *http.Request |
| } |
| typed := strings.TrimSpace(r.PostFormValue("owner")) |
| pepper := a.secrets.Pepper |
| + stale := false |
| v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(v operator.PlanView) bool { |
| - // Subject, freshness and method again, inside the write; then the |
| - // typed owner must blind-index to Home's stored owner_index. |
| + // Subject, freshness and method inside the write — the POST's only |
| + // check of them — then the typed owner must blind-index to Home's |
| + // stored owner_index. |
| if s.Subject != a.op.subject || !credentialFresh(s, time.Now()) { |
| + stale = true |
| return false |
| } |
| if v.OwnerIndex == "" { |
| @@ -239,6 +256,10 @@ func (a *App) handleCredentialConfirmPost(w http.ResponseWriter, r *http.Request |
| } |
| return typed != "" && hmac.Equal([]byte(blindIndex(pepper, typed)), []byte(v.OwnerIndex)) |
| }) |
| + if stale { |
| + http.Redirect(w, r, operatorConfirm, http.StatusSeeOther) |
| + return |
| + } |
| if err == nil { |
| a.clearOperatorIntent(w, r) |
| } |
diff --git a/internal/home/operator_http.go b/internal/home/operator_http.go| index 7672f1e..4cc4252 100644 |
| --- a/internal/home/operator_http.go |
| +++ b/internal/home/operator_http.go |
| @@ -253,7 +253,7 @@ func (a *App) newOperatorEndpoint(cfg *Runtime) error { |
| return errOperatorConfig |
| } |
| pepper := a.secrets.Pepper |
| - e.credential, err = operator.NewCredentialHTTP(c, s.config.DirectoryProvisioningPublicKey, cfg.consumers, e.apps, func(address string) string { return blindIndex(pepper, address) }) |
| + e.credential, err = operator.NewCredentialHTTP(c, s.config.DirectoryProvisioningPublicKey, cfg.consumers, e.apps, func(address string) string { return blindIndex(pepper, address) }, registryAdmits(cfg.origins.Credential, cfg.keys)) |
| if err != nil { |
| return errOperatorConfig |
| } |
| @@ -267,6 +267,14 @@ func (a *App) newOperatorEndpoint(cfg *Runtime) error { |
| if err = plans.Sweep(context.Background(), s.now()); err != nil { |
| return err |
| } |
| + // A row that survived a restart is still deleted at its end. |
| + ends, err := plans.Ends(context.Background(), s.now()) |
| + if err != nil { |
| + return err |
| + } |
| + for _, end := range ends { |
| + e.sweepAt(end) |
| + } |
| a.op = e |
| return nil |
| } |
| @@ -400,7 +408,9 @@ func (a *App) handleOperator(w http.ResponseWriter, r *http.Request) { |
| // fails, answer unavailable: Alta's exact replay returns the |
| // stored result and reloads again, so a retired consumer never |
| // stays admitted behind a 200. |
| - if err = a.runtime.registry.load(r.Context(), a.db.Writer(), a.origins.Credential, a.runtime.keys); err != nil { |
| + // Not the request's context: a client gone after the commit |
| + // must not leave the union stale (load bounds itself). |
| + if err = a.runtime.registry.load(context.Background(), a.db.Writer(), a.origins.Credential, a.runtime.keys); err != nil { |
| err = operator.ErrUnavailable |
| } |
| } |
| @@ -414,7 +424,15 @@ func (a *App) handleOperator(w http.ResponseWriter, r *http.Request) { |
| } else { |
| out, err = a.op.credential.InspectHTTP(r.Context(), body) |
| } |
| - a.operatorResult(w, "inspect", a.op.role+".inspect", "", out, err) |
| + // Neither a verified operation nor a verified inspect: the log says |
| + // "-", not which of the two it failed to be. |
| + verb := a.op.role + ".inspect" |
| + if errors.Is(err, operator.ErrRefused) { |
| + route, verb = "operation", "-" |
| + } else { |
| + route = "inspect" |
| + } |
| + a.operatorResult(w, route, verb, "", out, err) |
| } |
| func (a *App) operatorResult(w http.ResponseWriter, route, verb, op string, out []byte, err error) { |
diff --git a/internal/operator/http_verbs.go b/internal/operator/http_verbs.go| index 3cf99ee..e792109 100644 |
| --- a/internal/operator/http_verbs.go |
| +++ b/internal/operator/http_verbs.go |
| @@ -203,21 +203,24 @@ type CredentialHTTP struct { |
| env map[string]string |
| apps map[string]bool |
| ownerIndex func(string) string |
| + admit func(id, origin string) bool |
| } |
| // NewCredentialHTTP pins the directory's provisioning public key (the |
| // credential role's first pin of anything the directory signs), the |
| // HOME_CONSUMERS manifest it must never collide with, the compiled app |
| -// registry and the blind index that compares the typed owner. |
| -func NewCredentialHTTP(c *Credential, provisioningPublic string, env map[string]string, apps []string, ownerIndex func(string) string) (*CredentialHTTP, error) { |
| - if c == nil || ownerIndex == nil || len(env) == 0 || len(apps) == 0 { |
| +// registry and the blind index that compares the typed owner. admit is the |
| +// registry reload's own admission predicate: no row is committed that the |
| +// reload — and so the next boot — would refuse (discussion 94, blocker 1). |
| +func NewCredentialHTTP(c *Credential, provisioningPublic string, env map[string]string, apps []string, ownerIndex func(string) string, admit func(id, origin string) bool) (*CredentialHTTP, error) { |
| + if c == nil || ownerIndex == nil || admit == nil || len(env) == 0 || len(apps) == 0 { |
| return nil, ErrRefused |
| } |
| k, e := public(provisioningPublic) |
| if e != nil || bytes.Equal(k, c.engine.verifier.key) || bytes.Equal(k, c.signer.SignPub()) { |
| return nil, ErrRefused |
| } |
| - h := &CredentialHTTP{c, []roster.Key{{ID: keyID(k), Public: provisioningPublic}}, map[string]string{}, map[string]bool{}, ownerIndex} |
| + h := &CredentialHTTP{c, []roster.Key{{ID: keyID(k), Public: provisioningPublic}}, map[string]string{}, map[string]bool{}, ownerIndex, admit} |
| for id, origin := range env { |
| if !atom(id, 64) || !Origin(origin) { |
| return nil, ErrRefused |
| @@ -303,7 +306,7 @@ func (h *CredentialHTTP) register(ctx context.Context, c *sql.Conn, r Request, w |
| return nil, ErrRefused |
| } |
| b := verified.Bindings() |
| - if !h.apps[b.App] || !contains(w.Apps, b.App) || !atom(b.Consumer, 64) || !Origin(b.Audience) { |
| + if !h.apps[b.App] || !contains(w.Apps, b.App) || !atom(b.Consumer, 64) || !Origin(b.Audience) || !h.admit(b.Consumer, b.Audience) { |
| return nil, ErrRefused |
| } |
| for id, origin := range h.env { |
diff --git a/internal/operator/http_verbs_test.go b/internal/operator/http_verbs_test.go| index 7834375..e67545e 100644 |
| --- a/internal/operator/http_verbs_test.go |
| +++ b/internal/operator/http_verbs_test.go |
| @@ -18,6 +18,7 @@ import ( |
| 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" |
| @@ -469,11 +470,18 @@ func newHTTPCredential(t *testing.T) *httpCredential { |
| t.Fatal(e) |
| } |
| env := map[string]string{"directory": "https://oficina.works", "docs": "https://docs.oficina.works"} |
| - f.http, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.dirKey.SignPub()), env, httpApps, func(a string) string { return credentialIndex(f.pepper, a) }) |
| + // 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 "" }); e != ErrRefused { |
| + 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) |
| @@ -594,14 +602,17 @@ func TestOperatorHTTPRegisterConsumerOnlyFromTheDirectoryRecord(t *testing.T) { |
| } |
| 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"), |
| - "issuer-swap": nil, |
| + "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() |
| @@ -634,6 +645,16 @@ func TestOperatorHTTPRegisterConsumerOnlyFromTheDirectoryRecord(t *testing.T) { |
| 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"} }) |
diff --git a/internal/operator/plan.go b/internal/operator/plan.go| index f95d836..921300b 100644 |
| --- a/internal/operator/plan.go |
| +++ b/internal/operator/plan.go |
| @@ -350,6 +350,29 @@ func (s *PlanStore) open(v PlanView, sealed []byte) (PlanView, error) { |
| return v, nil |
| } |
| +// Ends lists when each surviving plan row ends: a pending plan's expiry, an |
| +// open window's. Boot schedules a sweep for each, so a row that survives a |
| +// restart is still deleted on time. |
| +func (s *PlanStore) Ends(ctx context.Context, now time.Time) ([]int64, error) { |
| + rows, e := s.db.QueryContext(ctx, "SELECT CASE state WHEN 'open' THEN window_expires_at ELSE expires_at END FROM operator_plans LIMIT 2") |
| + if e != nil { |
| + return nil, ErrUnavailable |
| + } |
| + defer rows.Close() |
| + var out []int64 |
| + for rows.Next() { |
| + var end int64 |
| + if rows.Scan(&end) != nil { |
| + return nil, ErrUnavailable |
| + } |
| + out = append(out, end) |
| + } |
| + if rows.Err() != nil { |
| + return nil, ErrUnavailable |
| + } |
| + return out, nil |
| +} |
| + |
| // Pending returns the role's one pending, unexpired plan. |
| func (s *PlanStore) Pending(ctx context.Context, now time.Time) (PlanView, error) { |
| v, sealed, e := scanPlan(ctx, s.db, s.role, "state='pending' AND expires_at>?", now.Unix()) |