Operator: expiry sweeps that cannot be rolled back, real plan-bytes gates
Review-pass findings: - An open window's row was deleted only by a later plan access. Sweeps now run at plan expiry and at window expiry (scheduled when the plan is stored and when the window opens, on the endpoint's clock), and before every operation in their own statement, so a refused operation's rollback no longer brings an expired row back. TestOperatorExpirySweepsRunUnprompted and TestOperatorHTTPExpiredWindowRowSweptBeforeARefusedOperation call no Sweep by hand. - The 'signed plan bytes absent' assertions searched a slice that was only the key id. They now decode the envelope and search file, WAL and SHM for the payload and signature, raw and as base64url text, and for the plan's own owner and display_name fields. - register-consumer: the 4,096 cap is checked first and refused; any INSERT failure after it is unavailable (the trigger stays as the backstop).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+167
−21
internal/home/operator_ceremony_test.go+4 −2internal/home/operator_confirm.go+1 −0internal/home/operator_http.go+20 −6internal/home/operator_http_test.go+81 −2internal/operator/http_verbs.go+22 −9internal/operator/http_verbs_test.go+39 −2
CI passed — run details
diff --git a/internal/home/operator_ceremony_test.go b/internal/home/operator_ceremony_test.go| index 665a792..47515f2 100644 |
| --- a/internal/home/operator_ceremony_test.go |
| +++ b/internal/home/operator_ceremony_test.go |
| @@ -377,7 +377,9 @@ func TestOperatorPrivacyGatesOverTheWholeSequence(t *testing.T) { |
| sealtest.AssertNoPlaintext(t, path) |
| for _, suffix := range []string{"", "-wal", "-shm"} { |
| b, _ := os.ReadFile(path + suffix) |
| - for _, secret := range [][]byte{plan[10:60], records["docs"][10:60], []byte(f.prefilter)} { |
| + secrets := append(signedPlanParts(t, plan), []byte(f.prefilter)) |
| + secrets = append(secrets, signedPlanParts(t, records["docs"])[:4]...) |
| + for _, secret := range secrets { |
| if bytes.Contains(b, secret) { |
| t.Fatal("private operator bytes at rest in", path+suffix) |
| } |
| @@ -388,7 +390,7 @@ func TestOperatorPrivacyGatesOverTheWholeSequence(t *testing.T) { |
| if !strings.Contains(logs, "operator http") { |
| t.Fatal("captured no operator log lines; the gate would pass by not looking") |
| } |
| - for _, canary := range []string{sealtest.CanaryAddress, operatorName, operatorLabel, f.prefilter, fixtureToken(90), string(plan[10:40])} { |
| + for _, canary := range []string{sealtest.CanaryAddress, operatorName, operatorLabel, f.prefilter, fixtureToken(90), string(signedPlanParts(t, plan)[2][:40])} { |
| if strings.Contains(strings.ToLower(logs), strings.ToLower(canary)) { |
| t.Fatalf("log line carries %q", canary) |
| } |
diff --git a/internal/home/operator_confirm.go b/internal/home/operator_confirm.go| index cae5896..e2fb9c2 100644 |
| --- a/internal/home/operator_confirm.go |
| +++ b/internal/home/operator_confirm.go |
| @@ -252,6 +252,7 @@ func (a *App) handleCredentialConfirmPost(w http.ResponseWriter, r *http.Request |
| func (a *App) afterOpen(w http.ResponseWriter, r *http.Request, page string, v operator.PlanView, err error, opened func(operator.PlanView) map[string]any) { |
| switch { |
| case err == nil: |
| + a.op.sweepAt(v.WindowExpires) |
| a.logger.Info("operator confirm", "role", a.op.role, "outcome", "opened") |
| a.render(w, r, http.StatusOK, page, opened(v)) |
| case errors.Is(err, operator.ErrBusy): |
diff --git a/internal/home/operator_http.go b/internal/home/operator_http.go| index fb05126..7672f1e 100644 |
| --- a/internal/home/operator_http.go |
| +++ b/internal/home/operator_http.go |
| @@ -207,6 +207,24 @@ type operatorEndpoint struct { |
| credential *operator.CredentialHTTP |
| apps []string |
| now func() time.Time |
| + // after schedules the expiry sweeps; time.AfterFunc outside tests. |
| + after func(time.Duration, func()) |
| +} |
| + |
| +// sweepAt deletes the role's expired plan rows one second after unix (a |
| +// plan's expiry, or an open window's), even if nothing else touches the role |
| +// before then. Boot and every plan access sweep too; this is what keeps an |
| +// unconfirmed owner blind index from lingering on an idle role. |
| +func (e *operatorEndpoint) sweepAt(unix int64) { |
| + wait := time.Unix(unix, 0).Sub(e.now()) + time.Second |
| + if wait < 0 { |
| + wait = 0 |
| + } |
| + if wait > (operator.PlanLifetime+operator.WindowLifetime+5)*time.Second { |
| + return |
| + } |
| + plans, clock := e.plans, e.now |
| + e.after(wait, func() { _ = plans.Sweep(context.Background(), clock()) }) |
| } |
| func (a *App) newOperatorEndpoint(cfg *Runtime) error { |
| @@ -223,7 +241,7 @@ func (a *App) newOperatorEndpoint(cfg *Runtime) error { |
| if err != nil { |
| return errOperatorConfig |
| } |
| - e := &operatorEndpoint{role: cfg.role, subject: s.config.OperatorSubject, prefilter: s.prefilter, verifier: s.verifier, plans: plans, apps: operatorApps(), now: s.now} |
| + e := &operatorEndpoint{role: cfg.role, subject: s.config.OperatorSubject, prefilter: s.prefilter, verifier: s.verifier, plans: plans, apps: operatorApps(), now: s.now, after: func(d time.Duration, f func()) { time.AfterFunc(d, f) }} |
| if cfg.role == "credential" { |
| e.host = a.credentialHost |
| resolve, err := NewOperatorPersonResolver(a.secrets.Pepper) |
| @@ -448,11 +466,7 @@ func (a *App) submitPlan(w http.ResponseWriter, body []byte) { |
| a.operatorAnswer(w, "plan", "plan", "", operatorDown) |
| return |
| } |
| - // Deleted at expiry even if nothing else touches the role before then. |
| - if wait := time.Until(time.Unix(plan.Expires, 0)) + time.Second; wait > 0 && wait <= (operator.PlanLifetime+5)*time.Second { |
| - plans, clock := a.op.plans, a.op.now |
| - time.AfterFunc(wait, func() { _ = plans.Sweep(context.Background(), clock()) }) |
| - } |
| + a.op.sweepAt(plan.Expires) |
| a.operatorLog("plan", "plan", operatorOutcome{http.StatusOK, "ok"}, "") |
| w.Header().Set("Content-Type", "application/json") |
| w.WriteHeader(http.StatusOK) |
diff --git a/internal/home/operator_http_test.go b/internal/home/operator_http_test.go| index 9828dd4..4bc54af 100644 |
| --- a/internal/home/operator_http_test.go |
| +++ b/internal/home/operator_http_test.go |
| @@ -523,8 +523,10 @@ func TestOperatorPlanSubmitStoresClosedFieldsOnly(t *testing.T) { |
| sealtest.AssertNoPlaintext(t, path) |
| for _, suffix := range []string{"", "-wal", "-shm"} { |
| b, _ := os.ReadFile(path + suffix) |
| - if bytes.Contains(b, plan) || bytes.Contains(b, []byte(plan[20:80])) { |
| - t.Fatal("signed plan bytes at rest in", filepath.Base(path+suffix)) |
| + for _, secret := range signedPlanParts(t, plan) { |
| + if bytes.Contains(b, secret) { |
| + t.Fatalf("signed plan bytes at rest in %s: %.40q", filepath.Base(path+suffix), secret) |
| + } |
| } |
| } |
| } |
| @@ -538,3 +540,80 @@ func TestOperatorPlanSubmitStoresClosedFieldsOnly(t *testing.T) { |
| } |
| sealtest.AssertNoPlaintext(t, f.credential.dbPath) |
| } |
| + |
| +// signedPlanParts is what "the signed plan bytes" means at rest: the payload |
| +// and the signature, raw and as their base64url text, plus the plan's own |
| +// spelling of its account-authored fields. |
| +func signedPlanParts(t *testing.T, raw []byte) [][]byte { |
| + t.Helper() |
| + var env struct { |
| + V int `json:"v"` |
| + KID string `json:"kid"` |
| + Payload string `json:"payload"` |
| + Signature string `json:"signature"` |
| + } |
| + if err := json.Unmarshal(raw, &env); err != nil { |
| + t.Fatal(err) |
| + } |
| + payload, err := base64.RawURLEncoding.DecodeString(env.Payload) |
| + sig, err2 := base64.RawURLEncoding.DecodeString(env.Signature) |
| + if err != nil || err2 != nil || len(sig) != 64 { |
| + t.Fatal("plan envelope") |
| + } |
| + return [][]byte{payload, sig, []byte(env.Payload), []byte(env.Signature), []byte(`"owner":"` + sealtest.CanaryAddress + `"`), []byte(`"display_name":"` + operatorName + `"`)} |
| +} |
| + |
| +// The expiry sweeps run on their own: a pending plan and an open window |
| +// are deleted at their end with no further request and no Sweep by hand. |
| +func TestOperatorExpirySweepsRunUnprompted(t *testing.T) { |
| + f := newOperatorFixture(t) |
| + var pending []func() |
| + var waits []time.Duration |
| + clock := time.Now() |
| + for _, a := range []*App{f.credential.App, f.directory} { |
| + a.op.after = func(d time.Duration, fn func()) { waits = append(waits, d); pending = append(pending, fn) } |
| + a.op.now = func() time.Time { return clock } |
| + } |
| + fire := func(keep bool) { |
| + for _, fn := range pending { |
| + fn() |
| + } |
| + if !keep { |
| + pending = nil |
| + } |
| + } |
| + // A plan nobody confirms. |
| + signInFully(t, f.credential, sealtest.CanaryAddress) |
| + if rec := f.post("credential", operatorPlanPath, f.plan(t, "credential", "create-team", []string{"docs"}, nil), nil); rec.Code != 200 { |
| + t.Fatal(rec.Code) |
| + } |
| + if len(pending) != 1 || waits[0] < 600*time.Second || waits[0] > 602*time.Second { |
| + t.Fatal("no expiry sweep scheduled for the plan", waits) |
| + } |
| + clock = clock.Add(601 * time.Second) |
| + fire(false) |
| + if f.countRows(t, f.credential.App, "operator_plans") != 0 { |
| + t.Fatal("unconfirmed plan row left after expiry") |
| + } |
| + // A window that is opened, then left. |
| + clock = time.Now() |
| + if rec := f.post("directory", operatorPlanPath, f.plan(t, "directory", "add-apps", []string{"docs"}, nil), nil); rec.Code != 200 { |
| + t.Fatal(rec.Code) |
| + } |
| + if rec := f.confirm(t, "directory", f.paulDirectory(t, f.paulCredential(t)), ""); rec.Code != 200 { |
| + t.Fatal(rec.Code) |
| + } |
| + if len(pending) != 2 || waits[len(waits)-1] < operator.WindowLifetime*time.Second || waits[len(waits)-1] > (operator.WindowLifetime+2)*time.Second { |
| + t.Fatal("no expiry sweep scheduled for the window", waits) |
| + } |
| + clock = clock.Add((operator.WindowLifetime - 2) * time.Second) |
| + fire(true) |
| + if f.countRows(t, f.directory, "operator_plans") != 1 { |
| + t.Fatal("window swept before it expired") |
| + } |
| + clock = clock.Add(3 * time.Second) |
| + fire(false) |
| + if f.countRows(t, f.directory, "operator_plans") != 0 { |
| + t.Fatal("expired window row left") |
| + } |
| +} |
diff --git a/internal/operator/http_verbs.go b/internal/operator/http_verbs.go| index 3e7269c..3cf99ee 100644 |
| --- a/internal/operator/http_verbs.go |
| +++ b/internal/operator/http_verbs.go |
| @@ -57,12 +57,14 @@ func (d *Directory) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error) |
| if d == nil { |
| return nil, ErrRefused |
| } |
| + // Expired plan rows go before the operation, in their own statement, so |
| + // a refused operation's rollback cannot bring them back. |
| + if e := sweepPlans(ctx, d.engine.db, d.engine.now().Unix()); e != nil { |
| + return nil, e |
| + } |
| return d.engine.Execute(ctx, raw, func(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) { |
| action := r.authorization.Action |
| now := d.engine.now().Unix() |
| - if e := sweepPlans(ctx, c, now); e != nil { |
| - return nil, e |
| - } |
| w, sealed, e := window(ctx, c, "directory", now) |
| if e != nil { |
| return nil, e |
| @@ -179,6 +181,10 @@ func (d *Directory) disable(ctx context.Context, c *sql.Conn, r Request, w PlanV |
| // ---- credential ---- |
| +// ConsumerCap is the consumers table's limit (and its trigger's): a runaway |
| +// provisioner's ceiling, not a scale target. |
| +const ConsumerCap = 4096 |
| + |
| // RegisterInput carries the directory's signed provisioning record and |
| // nothing else: the consumer, audience and app come from what verifies. |
| type RegisterInput struct { |
| @@ -229,12 +235,12 @@ func (h *CredentialHTTP) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, e |
| return nil, ErrRefused |
| } |
| c := h.c |
| + if e := sweepPlans(ctx, c.engine.db, c.engine.now().Unix()); e != nil { |
| + return nil, e |
| + } |
| return c.engine.Execute(ctx, raw, func(ctx context.Context, conn *sql.Conn, r Request) ([]byte, error) { |
| action := r.authorization.Action |
| now := c.engine.now().Unix() |
| - if e := sweepPlans(ctx, conn, now); e != nil { |
| - return nil, e |
| - } |
| w, _, e := window(ctx, conn, "credential", now) |
| if e != nil { |
| return nil, e |
| @@ -305,7 +311,7 @@ func (h *CredentialHTTP) register(ctx context.Context, c *sql.Conn, r Request, w |
| return nil, ErrRefused |
| } |
| } |
| - var clash int |
| + var clash, total int |
| e = c.QueryRowContext(ctx, "SELECT count(*) FROM consumers WHERE consumer_id=? OR origin=?", b.Consumer, b.Audience).Scan(&clash) |
| if e != nil { |
| return nil, ErrUnavailable |
| @@ -313,10 +319,17 @@ func (h *CredentialHTTP) register(ctx context.Context, c *sql.Conn, r Request, w |
| if clash != 0 { |
| return nil, ErrRefused |
| } |
| + // The cap is a refusal; the trigger behind it is the backstop, so any |
| + // INSERT failure past this point is unavailable, not refused. |
| + if e = c.QueryRowContext(ctx, "SELECT count(*) FROM consumers").Scan(&total); e != nil { |
| + return nil, ErrUnavailable |
| + } |
| + if total >= ConsumerCap { |
| + return nil, ErrRefused |
| + } |
| now := h.c.engine.now() |
| if _, e = c.ExecContext(ctx, "INSERT INTO consumers(consumer_id,origin,app,state,created_at,operation_id) VALUES(?,?,?,'active',?,?)", b.Consumer, b.Audience, b.App, now.UTC().Format(time.DateOnly), r.authorization.OperationID); e != nil { |
| - // The cap trigger is the only expected failure here. |
| - return nil, ErrRefused |
| + return nil, ErrUnavailable |
| } |
| return h.manifestResult(ctx, c, r) |
| } |
diff --git a/internal/operator/http_verbs_test.go b/internal/operator/http_verbs_test.go| index 276727f..7834375 100644 |
| --- a/internal/operator/http_verbs_test.go |
| +++ b/internal/operator/http_verbs_test.go |
| @@ -212,9 +212,13 @@ func TestOperatorPlanStoreOnePendingOneOpenAndExpiredRowsDeleted(t *testing.T) { |
| if e != nil && !errors.Is(e, os.ErrNotExist) { |
| t.Fatal(e) |
| } |
| - for _, secret := range [][]byte{[]byte("PRIVATE-TEAM-NAME-CANARY"), raw, raw2, raw3} { |
| + 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.Fatal("plan bytes or name at rest") |
| + t.Fatalf("plan bytes or name at rest: %.40q", secret) |
| } |
| } |
| } |
| @@ -707,3 +711,36 @@ func TestOperatorHTTPCredentialInspect(t *testing.T) { |
| } |
| _ = 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") |
| + } |
| +} |