oficina / home Public

Operator: signed plans, windows, the provenance fence and the HTTP verbs

team-provisioning-amendment.md §4-§7, operator package half. Engine unchanged;
the verbs are wrapped:

- Plan (context oficina/home/operator-plan/v1): closed fields, this role's
  exact pins, kind per role, apps from the compiled registry, <= 900 s.
- PlanStore: stores only the closed fields (display name sealed, owner as the
  caller's blind index), never the signed bytes; one pending and one open per
  role (UNIQUE(state)); expired rows deleted; Open re-checks expiry inside the
  write and opens a 15-minute window that never extends.
- Directory.ExecuteHTTP: window + kind check inside the operation's
  transaction; seed-team binds the plan's label and opens the sealed name to
  compare bytes, and records operator_http_teams; provision/verify/activate
  pass the provenance fence (team seeded by this stream, window's label) and
  app-in-window; new directory.disable-consumer.
- CredentialHTTP: owner-seed existing_only and blind-indexed to the plan's
  owner_index; new register-consumer (only from the directory's signed
  provisioning record, issuer/directory fixed to the pins, collision against
  HOME_CONSUMERS and the table, returns the manifest digest) and
  retire-consumer (retired hostnames dead for good, by trigger).
- InspectHTTP on both roles: (sequence, head), plan ids and expiries, and on
  the directory generation and next proposal.
- allowedAction grows credential.register-consumer, credential.retire-consumer,
  credential.inspect, directory.disable-consumer.
- New migration sets oficina_<role>_operator_http (credential consumers with a
  4,096 cap trigger, operator_plans; directory operator_plans,
  operator_http_teams). Kept apart from the frozen native-command profiles.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 81f7a59f4ce980f98ff0277f3e44ac65a0cef2f5 parent 463ac45
9 files changed, +1,732 −28
  • internal/operator/credential.go +29 −25
  • internal/operator/directory.go +1 −0
  • internal/operator/engine_test.go +1 −1
  • internal/operator/http_migrations/credential/migrations/0001_operator_http.sql +29 −0
  • internal/operator/http_migrations/directory/migrations/0001_operator_http.sql +19 −0
  • internal/operator/http_verbs.go +518 −0
  • internal/operator/http_verbs_test.go +709 −0
  • internal/operator/plan.go +421 −0
  • internal/operator/protocol.go +5 −2
diff --git a/internal/operator/credential.go b/internal/operator/credential.go
index d76249f..d5843b0 100644
--- a/internal/operator/credential.go
+++ b/internal/operator/credential.go
@@ -46,29 +46,33 @@ func NewCredential(engine *Engine, directory string, signer *family.Keypair, bro
return &Credential{engine, directory, signer, resolve}, nil
}
func (c *Credential) Execute(ctx context.Context, raw []byte) ([]byte, error) {
- return c.engine.Execute(ctx, raw, func(ctx context.Context, conn *sql.Conn, r Request) ([]byte, error) {
- var in OwnerInput
- if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Action != "credential.owner-seed" || in.Directory != c.directory || !validTeam(in.TeamID, in.TeamSQID) || len(in.Address) == 0 || len(in.Address) > 320 || !utf8.ValidString(in.Address) {
- return nil, ErrRefused
- }
- address, e := mail.ParseAddress(in.Address)
- if e != nil || address.Address != in.Address || address.Name != "" {
- return nil, ErrRefused
- }
- now := c.engine.now()
- subject, found, e := c.resolve(ctx, conn, in.Address, in.ExistingOnly, now)
- if e != nil {
- return nil, ErrUnavailable
- }
- if !found || !PersonRef(subject) {
- return nil, ErrRefused
- }
- receipt, e := SignOwner(c.signer, OwnerReceipt{1, "owner-seed", r.authorization.OperationID, r.authorization.Origin, c.directory, in.TeamID, in.TeamSQID, subject, "owner", now.Unix(), now.Unix() + 300})
- if e != nil {
- return nil, e
- }
- result := resultFor(r)
- result.Receipt = receipt
- return encode(result)
- })
+ return c.engine.Execute(ctx, raw, c.ownerSeed)
+}
+
+// ownerSeed is credential.owner-seed's mutation, shared by the native command
+// and the HTTP path (which wraps it in a window check).
+func (c *Credential) ownerSeed(ctx context.Context, conn *sql.Conn, r Request) ([]byte, error) {
+ var in OwnerInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Action != "credential.owner-seed" || in.Directory != c.directory || !validTeam(in.TeamID, in.TeamSQID) || len(in.Address) == 0 || len(in.Address) > 320 || !utf8.ValidString(in.Address) {
+ return nil, ErrRefused
+ }
+ address, e := mail.ParseAddress(in.Address)
+ if e != nil || address.Address != in.Address || address.Name != "" {
+ return nil, ErrRefused
+ }
+ now := c.engine.now()
+ subject, found, e := c.resolve(ctx, conn, in.Address, in.ExistingOnly, now)
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if !found || !PersonRef(subject) {
+ return nil, ErrRefused
+ }
+ receipt, e := SignOwner(c.signer, OwnerReceipt{1, "owner-seed", r.authorization.OperationID, r.authorization.Origin, c.directory, in.TeamID, in.TeamSQID, subject, "owner", now.Unix(), now.Unix() + 300})
+ if e != nil {
+ return nil, e
+ }
+ result := resultFor(r)
+ result.Receipt = receipt
+ return encode(result)
}
diff --git a/internal/operator/directory.go b/internal/operator/directory.go
index c0e629c..55812eb 100644
--- a/internal/operator/directory.go
+++ b/internal/operator/directory.go
@@ -63,6 +63,7 @@ type Result struct {
Record jsontext.Value `json:"record,omitempty"`
Bearer string `json:"bearer,omitempty"`
Receipt jsontext.Value `json:"receipt,omitempty"`
+ Manifest string `json:"credential_manifest_digest,omitempty"`
}
func resultFor(r Request) Result {
diff --git a/internal/operator/engine_test.go b/internal/operator/engine_test.go
index 6ee5aa4..d361ca7 100644
--- a/internal/operator/engine_test.go
+++ b/internal/operator/engine_test.go
@@ -44,7 +44,7 @@ func newEngineFixture(t *testing.T) engineFixture {
if _, e = db.Exec("PRAGMA journal_mode=WAL"); e != nil {
t.Fatal(e)
}
- if _, e = migrate.Apply(context.Background(), handle, migrate.Merge(directorydata.Schema, directorydata.RosterSchema, directorydata.OperatorSchema, DirectorySchema)); e != nil {
+ if _, e = migrate.Apply(context.Background(), handle, migrate.Merge(directorydata.Schema, directorydata.RosterSchema, directorydata.OperatorSchema, DirectorySchema, DirectoryHTTPSchema)); e != nil {
t.Fatal(e)
}
if _, e = db.Exec("CREATE TABLE test_items(id INTEGER PRIMARY KEY)"); e != nil {
diff --git a/internal/operator/http_migrations/credential/migrations/0001_operator_http.sql b/internal/operator/http_migrations/credential/migrations/0001_operator_http.sql
new file mode 100644
index 0000000..eaf6d2b
--- /dev/null
+++ b/internal/operator/http_migrations/credential/migrations/0001_operator_http.sql
@@ -0,0 +1,29 @@
+CREATE TABLE consumers (
+ consumer_id TEXT PRIMARY KEY CHECK(length(consumer_id) BETWEEN 1 AND 64 AND consumer_id NOT GLOB '*[^a-zA-Z0-9_-]*'),
+ origin TEXT NOT NULL UNIQUE CHECK(length(origin) BETWEEN 9 AND 253 AND substr(origin,1,8)='https://'),
+ app TEXT NOT NULL CHECK(length(app) BETWEEN 1 AND 32 AND app NOT GLOB '*[^a-z]*'),
+ state TEXT NOT NULL CHECK(state IN ('active','retired')),
+ created_at TEXT NOT NULL CHECK(length(created_at)=10),
+ operation_id TEXT NOT NULL CHECK(length(operation_id)=43)
+);
+-- The cap is a runaway provisioner's limit, not a scale target.
+CREATE TRIGGER consumers_cap BEFORE INSERT ON consumers
+WHEN (SELECT count(*) FROM consumers) >= 4096
+BEGIN SELECT RAISE(ABORT,'consumer registry full'); END;
+-- A retired hostname is dead at Home for good; nothing but active->retired.
+CREATE TRIGGER consumers_retire_only BEFORE UPDATE ON consumers
+WHEN OLD.state!='active' OR NEW.state!='retired' OR NEW.consumer_id IS NOT OLD.consumer_id OR NEW.origin IS NOT OLD.origin OR NEW.app IS NOT OLD.app OR NEW.created_at IS NOT OLD.created_at OR NEW.operation_id IS NOT OLD.operation_id
+BEGIN SELECT RAISE(ABORT,'consumer registry rows only retire'); END;
+CREATE TRIGGER consumers_no_delete BEFORE DELETE ON consumers
+BEGIN SELECT RAISE(ABORT,'consumer registry rows are never deleted'); END;
+CREATE TABLE operator_plans (
+ plan_id TEXT PRIMARY KEY CHECK(length(plan_id)=43 AND plan_id NOT GLOB '*[^a-zA-Z0-9_-]*'),
+ state TEXT NOT NULL UNIQUE CHECK(state IN ('pending','open')),
+ kind TEXT NOT NULL CHECK(kind IN ('create-team','add-apps','retire-apps')),
+ apps TEXT NOT NULL CHECK(length(apps) BETWEEN 1 AND 256 AND apps NOT GLOB '*[^a-z,]*'),
+ owner_index TEXT CHECK(owner_index IS NULL OR (length(owner_index)=64 AND owner_index NOT GLOB '*[^0-9a-f]*')),
+ expires_at INTEGER NOT NULL CHECK(typeof(expires_at)='integer' AND expires_at>0),
+ window_expires_at INTEGER CHECK(window_expires_at IS NULL OR (typeof(window_expires_at)='integer' AND window_expires_at>0)),
+ CHECK((kind='create-team') = (owner_index IS NOT NULL)),
+ CHECK((state='open') = (window_expires_at IS NOT NULL))
+);
diff --git a/internal/operator/http_migrations/directory/migrations/0001_operator_http.sql b/internal/operator/http_migrations/directory/migrations/0001_operator_http.sql
new file mode 100644
index 0000000..25e0844
--- /dev/null
+++ b/internal/operator/http_migrations/directory/migrations/0001_operator_http.sql
@@ -0,0 +1,19 @@
+CREATE TABLE operator_plans (
+ plan_id TEXT PRIMARY KEY CHECK(length(plan_id)=43 AND plan_id NOT GLOB '*[^a-zA-Z0-9_-]*'),
+ state TEXT NOT NULL UNIQUE CHECK(state IN ('pending','open')),
+ kind TEXT NOT NULL CHECK(kind IN ('initialize','create-team','add-apps','retire-apps')),
+ label TEXT CHECK(label IS NULL OR (length(label) BETWEEN 1 AND 63 AND label NOT GLOB '*[^a-z0-9-]*')),
+ apps TEXT NOT NULL CHECK(length(apps)<=256 AND apps NOT GLOB '*[^a-z,]*'),
+ sealed_name BLOB CHECK(sealed_name IS NULL OR (typeof(sealed_name)='blob' AND length(sealed_name) BETWEEN 29 AND 284)),
+ expires_at INTEGER NOT NULL CHECK(typeof(expires_at)='integer' AND expires_at>0),
+ window_expires_at INTEGER CHECK(window_expires_at IS NULL OR (typeof(window_expires_at)='integer' AND window_expires_at>0)),
+ CHECK((kind='initialize') = (label IS NULL)),
+ CHECK((kind='initialize') = (apps='')),
+ CHECK((kind='create-team') = (sealed_name IS NOT NULL)),
+ CHECK((state='open') = (window_expires_at IS NOT NULL))
+);
+-- The provenance fence: teams whose seed committed through the HTTP stream.
+CREATE TABLE operator_http_teams (
+ team_id INTEGER PRIMARY KEY REFERENCES teams(id),
+ operation_id TEXT NOT NULL UNIQUE REFERENCES directory_operator_results(operation_id) DEFERRABLE INITIALLY DEFERRED
+);
diff --git a/internal/operator/http_verbs.go b/internal/operator/http_verbs.go
new file mode 100644
index 0000000..3e7269c
--- /dev/null
+++ b/internal/operator/http_verbs.go
@@ -0,0 +1,518 @@
+package operator
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ stdjson "encoding/json"
+ "errors"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/home/roster"
+ "github.com/go-json-experiment/json"
+ "github.com/go-json-experiment/json/jsontext"
+)
+
+// The verbs reachable over POST /operator/v1 (team-provisioning-amendment.md
+// §5). The engine is unchanged; each verb is wrapped by a window check, and on
+// the directory by the provenance fence, inside the operation's own
+// transaction. The native command's Execute methods are untouched.
+
+func contains(list []string, s string) bool { return slices.Contains(list, s) }
+
+// ---- directory ----
+
+type DisableInput struct {
+ InputBase
+ Generation string `json:"expected_generation"`
+ TeamSQID string `json:"team_sqid"`
+ App string `json:"app"`
+ Consumer string `json:"consumer"`
+}
+
+// fence admits only a team whose seed committed through this HTTP stream, and
+// only the window's label. It returns the team id.
+func fence(ctx context.Context, c *sql.Conn, sqid, label string) (int64, error) {
+ var id int64
+ var stored string
+ e := c.QueryRowContext(ctx, "SELECT t.id,t.label FROM teams t JOIN operator_http_teams h ON h.team_id=t.id WHERE t.sqid=?", sqid).Scan(&id, &stored)
+ if errors.Is(e, sql.ErrNoRows) {
+ return 0, ErrRefused
+ }
+ if e != nil {
+ return 0, ErrUnavailable
+ }
+ if stored != label {
+ return 0, ErrRefused
+ }
+ return id, nil
+}
+
+// ExecuteHTTP is the directory's /operator/v1 operation path.
+func (d *Directory) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if d == nil {
+ return nil, ErrRefused
+ }
+ 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
+ }
+ if !windowAdmits(w.Kind, action) {
+ return nil, ErrRefused
+ }
+ switch action {
+ case "directory.initialize":
+ return d.initialize(ctx, c, r)
+ case "directory.seed-team":
+ var in SeedInput
+ if DecodeInput(r, &in) != nil || in.Label != w.Label || sealed == nil {
+ return nil, ErrRefused
+ }
+ // The display name Paul saw on Home is the one the team gets:
+ // opened inside this transaction and compared byte for byte.
+ name, e := d.engine.sealer.Open(planNamePurpose(w.ID), sealed)
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if !bytes.Equal(name, []byte(in.Name)) {
+ return nil, ErrRefused
+ }
+ out, e := d.seed(ctx, c, r)
+ if e != nil {
+ return nil, e
+ }
+ var result Result
+ if json.Unmarshal(out, &result) != nil || result.TeamID <= 0 {
+ return nil, ErrUnavailable
+ }
+ if _, e = c.ExecContext(ctx, "INSERT INTO operator_http_teams(team_id,operation_id) VALUES(?,?)", result.TeamID, r.authorization.OperationID); e != nil {
+ return nil, ErrUnavailable
+ }
+ return out, nil
+ case "directory.provision-consumer":
+ var in ProvisionInput
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) {
+ return nil, ErrRefused
+ }
+ if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
+ return nil, e
+ }
+ return d.provision(ctx, c, r)
+ case "directory.verify-consumer":
+ var in VerificationInput
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) {
+ return nil, ErrRefused
+ }
+ if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
+ return nil, e
+ }
+ return d.verifyConsumer(ctx, c, r)
+ case "directory.activate-consumer":
+ var in ActivationInput
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.Evidence.App) {
+ return nil, ErrRefused
+ }
+ if _, e := fence(ctx, c, in.Evidence.TeamSQID, w.Label); e != nil {
+ return nil, e
+ }
+ return d.activate(ctx, c, r)
+ case "directory.disable-consumer":
+ return d.disable(ctx, c, r, w)
+ }
+ return nil, ErrRefused
+ })
+}
+
+func (d *Directory) disable(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
+ var in DisableInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !d.apps[in.App] || !contains(w.Apps, in.App) || !atom(in.Consumer, 64) {
+ return nil, ErrRefused
+ }
+ if e := generation(ctx, c, in.Generation); e != nil {
+ return nil, e
+ }
+ team, e := fence(ctx, c, in.TeamSQID, w.Label)
+ if e != nil {
+ return nil, e
+ }
+ var state string
+ e = c.QueryRowContext(ctx, "SELECT state FROM team_instances WHERE team_id=? AND app=? AND consumer_id=?", team, in.App, in.Consumer).Scan(&state)
+ if errors.Is(e, sql.ErrNoRows) {
+ return nil, ErrRefused
+ }
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if state == "disabled" {
+ return nil, ErrRefused
+ }
+ if _, e = c.ExecContext(ctx, "UPDATE team_instances SET state='disabled' WHERE team_id=? AND app=? AND consumer_id=?", team, in.App, in.Consumer); e != nil {
+ return nil, ErrUnavailable
+ }
+ if _, e = c.ExecContext(ctx, "UPDATE roster_consumers SET enabled=0 WHERE consumer_id=? AND team_id=? AND app=?", in.Consumer, team, in.App); e != nil {
+ return nil, ErrUnavailable
+ }
+ result := resultFor(r)
+ result.Generation = in.Generation
+ result.TeamID = team
+ result.TeamSQID = in.TeamSQID
+ out, e := encode(result)
+ if e != nil {
+ return nil, e
+ }
+ h := sha256.Sum256(out)
+ if _, e = c.ExecContext(ctx, "INSERT INTO roster_operator_receipts VALUES(?,1,'disable',?,?,?,?)", r.authorization.OperationID, in.Consumer, in.Generation, h[:], d.engine.now().Unix()); e != nil {
+ return nil, ErrUnavailable
+ }
+ return out, nil
+}
+
+// ---- credential ----
+
+// RegisterInput carries the directory's signed provisioning record and
+// nothing else: the consumer, audience and app come from what verifies.
+type RegisterInput struct {
+ InputBase
+ Record jsontext.Value `json:"record"`
+}
+type RetireInput struct {
+ InputBase
+ Consumer string `json:"consumer"`
+}
+
+// CredentialHTTP is the credential role's /operator/v1 path.
+type CredentialHTTP struct {
+ c *Credential
+ provisioning []roster.Key
+ env map[string]string
+ apps map[string]bool
+ ownerIndex func(string) string
+}
+
+// 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 {
+ 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}
+ for id, origin := range env {
+ if !atom(id, 64) || !Origin(origin) {
+ return nil, ErrRefused
+ }
+ h.env[id] = origin
+ }
+ for _, a := range apps {
+ h.apps[a] = true
+ }
+ return h, nil
+}
+
+func (h *CredentialHTTP) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if h == nil {
+ return nil, ErrRefused
+ }
+ c := h.c
+ 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
+ }
+ if !windowAdmits(w.Kind, action) {
+ return nil, ErrRefused
+ }
+ switch action {
+ case "credential.owner-seed":
+ var in OwnerInput
+ // Over this endpoint the owner must already exist (Paul,
+ // 2026-10-27), and must be the owner Paul typed at confirm.
+ if DecodeInput(r, &in) != nil || !in.ExistingOnly || !ownerAddress(in.Address) || !hmac.Equal([]byte(h.ownerIndex(in.Address)), []byte(w.OwnerIndex)) {
+ return nil, ErrRefused
+ }
+ return c.ownerSeed(ctx, conn, r)
+ case "credential.register-consumer":
+ return h.register(ctx, conn, r, w)
+ case "credential.retire-consumer":
+ return h.retire(ctx, conn, r, w)
+ }
+ return nil, ErrRefused
+ })
+}
+
+// claimedBindings reads a record's claimed bindings without trusting them;
+// VerifyProvisioning below is what decides.
+func claimedBindings(record []byte) (roster.Bindings, bool) {
+ var env envelope
+ if len(record) == 0 || len(record) > roster.BodyLimit || json.Unmarshal(record, &env, json.RejectUnknownMembers(true)) != nil {
+ return roster.Bindings{}, false
+ }
+ payload, ok := canonical(env.Payload, -1)
+ if !ok {
+ return roster.Bindings{}, false
+ }
+ var p roster.Provisioning
+ if json.Unmarshal(payload, &p, json.RejectUnknownMembers(true)) != nil {
+ return roster.Bindings{}, false
+ }
+ return p.Bindings, true
+}
+
+func (h *CredentialHTTP) register(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
+ var in RegisterInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial {
+ return nil, ErrRefused
+ }
+ claimed, ok := claimedBindings(in.Record)
+ if !ok {
+ return nil, ErrRefused
+ }
+ // Issuer and directory are fixed to the pinned values; the record must
+ // verify under the directory's provisioning key with exactly those.
+ expected := claimed
+ expected.Issuer = h.c.engine.verifier.pins.Origin
+ expected.Directory = h.c.directory
+ verified, e := roster.VerifyProvisioning(in.Record, h.provisioning, expected)
+ if e != nil {
+ return nil, ErrRefused
+ }
+ b := verified.Bindings()
+ if !h.apps[b.App] || !contains(w.Apps, b.App) || !atom(b.Consumer, 64) || !Origin(b.Audience) {
+ return nil, ErrRefused
+ }
+ for id, origin := range h.env {
+ if id == b.Consumer || origin == b.Audience {
+ return nil, ErrRefused
+ }
+ }
+ var clash 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
+ }
+ if clash != 0 {
+ 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 h.manifestResult(ctx, c, r)
+}
+
+func (h *CredentialHTTP) retire(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
+ var in RetireInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !atom(in.Consumer, 64) {
+ return nil, ErrRefused
+ }
+ var app, state string
+ e := c.QueryRowContext(ctx, "SELECT app,state FROM consumers WHERE consumer_id=?", in.Consumer).Scan(&app, &state)
+ if errors.Is(e, sql.ErrNoRows) {
+ return nil, ErrRefused
+ }
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if state != "active" || !contains(w.Apps, app) {
+ return nil, ErrRefused
+ }
+ if _, e = c.ExecContext(ctx, "UPDATE consumers SET state='retired' WHERE consumer_id=? AND state='active'", in.Consumer); e != nil {
+ return nil, ErrUnavailable
+ }
+ return h.manifestResult(ctx, c, r)
+}
+
+func (h *CredentialHTTP) manifestResult(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
+ table, e := ActiveConsumers(ctx, c)
+ if e != nil {
+ return nil, e
+ }
+ union := map[string]string{}
+ for id, origin := range h.env {
+ union[id] = origin
+ }
+ for id, origin := range table {
+ union[id] = origin
+ }
+ result := resultFor(r)
+ result.Manifest, e = ManifestDigest(union)
+ if e != nil {
+ return nil, e
+ }
+ return encode(result)
+}
+
+type queryer interface {
+ QueryContext(context.Context, string, ...any) (*sql.Rows, error)
+}
+
+// ActiveConsumers reads the credential registry table's active rows.
+func ActiveConsumers(ctx context.Context, q queryer) (map[string]string, error) {
+ rows, e := q.QueryContext(ctx, "SELECT consumer_id,origin FROM consumers WHERE state='active' LIMIT 4097")
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ defer rows.Close()
+ out := map[string]string{}
+ for rows.Next() {
+ var id, origin string
+ if rows.Scan(&id, &origin) != nil || !atom(id, 64) || !Origin(origin) {
+ return nil, ErrUnavailable
+ }
+ out[id] = origin
+ }
+ if rows.Err() != nil || len(out) > 4096 {
+ return nil, ErrUnavailable
+ }
+ return out, nil
+}
+
+// ManifestDigest is base64url(SHA-256(encoding/json.Marshal(
+// ["oficina/home/consumer-manifest/v1", [[id, origin], …]]))), entries sorted
+// by the unsigned byte order of consumer ID (team-provisioning-app.md §7).
+func ManifestDigest(consumers map[string]string) (string, error) {
+ ids := make([]string, 0, len(consumers))
+ for id := range consumers {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ entries := make([][2]string, 0, len(ids))
+ for _, id := range ids {
+ entries = append(entries, [2]string{id, consumers[id]})
+ }
+ b, e := stdjson.Marshal([]any{"oficina/home/consumer-manifest/v1", entries})
+ if e != nil {
+ return "", ErrUnavailable
+ }
+ sum := sha256.Sum256(b)
+ return base64.RawURLEncoding.EncodeToString(sum[:]), nil
+}
+
+// ---- inspect ----
+
+// HTTPInspection is <role>.inspect's answer: the stream position Alta
+// resynchronises from, the plan ids and expiries (never their contents),
+// and on the directory the generation and next team proposal.
+type HTTPInspection struct {
+ Version int `json:"version"`
+ Role string `json:"role"`
+ Challenge string `json:"challenge"`
+ Observed int64 `json:"observed_at"`
+ Sequence int64 `json:"sequence"`
+ Head string `json:"head"`
+ Generation *string `json:"generation,omitempty"`
+ TeamID int64 `json:"proposed_team_id,omitempty"`
+ TeamSQID string `json:"proposed_team_sqid,omitempty"`
+ PendingPlan string `json:"pending_plan,omitempty"`
+ PendingExpires int64 `json:"pending_expires_at,omitempty"`
+ OpenPlan string `json:"open_plan,omitempty"`
+ WindowExpires int64 `json:"window_expires_at,omitempty"`
+}
+
+func inspectHTTP(ctx context.Context, e *Engine, raw []byte, extra func(context.Context, *sql.Conn, *HTTPInspection) error) ([]byte, error) {
+ if e == nil {
+ return nil, ErrRefused
+ }
+ role := e.verifier.pins.Role
+ if !e.verifier.actions[role+".inspect"] {
+ return nil, ErrRefused
+ }
+ challenge, err := e.verifier.verifyInspect(raw, e.now())
+ if err != nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ c, err := e.db.Conn(ctx)
+ if err != nil {
+ return nil, ErrUnavailable
+ }
+ defer c.Close()
+ if _, err = c.ExecContext(ctx, "BEGIN"); err != nil {
+ return nil, ErrUnavailable
+ }
+ defer c.ExecContext(context.Background(), "ROLLBACK")
+ now := e.now().Unix()
+ out := HTTPInspection{Version: 1, Role: role, Challenge: challenge.Challenge, Observed: now}
+ var origin, installation, registry, device, kid string
+ var completed int64
+ err = c.QueryRowContext(ctx, "SELECT origin,installation,registry,device,sequence,head,completed_at,key_id FROM "+e.prefix+"_state WHERE singleton=1").Scan(&origin, &installation, &registry, &device, &out.Sequence, &out.Head, &completed, &kid)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrUnavailable
+ }
+ p := e.verifier.pins
+ if err == nil && (origin != p.Origin || installation != p.Installation || registry != p.Registry || device != p.Device || kid != e.verifier.kid || completed > now) {
+ return nil, ErrRefused
+ }
+ if v, _, err := scanPlan(ctx, c, role, "state='pending' AND expires_at>?", now); err == nil {
+ out.PendingPlan, out.PendingExpires = v.ID, v.Expires
+ } else if err != ErrRefused {
+ return nil, err
+ }
+ if v, _, err := scanPlan(ctx, c, role, "state='open' AND window_expires_at>?", now); err == nil {
+ out.OpenPlan, out.WindowExpires = v.ID, v.WindowExpires
+ } else if err != ErrRefused {
+ return nil, err
+ }
+ if extra != nil {
+ if err := extra(ctx, c, &out); err != nil {
+ return nil, err
+ }
+ }
+ return encode(out)
+}
+
+// InspectHTTP is directory.inspect over /operator/v1.
+func (d *Directory) InspectHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if d == nil {
+ return nil, ErrRefused
+ }
+ return inspectHTTP(ctx, d.engine, raw, func(ctx context.Context, c *sql.Conn, out *HTTPInspection) error {
+ var g string
+ err := c.QueryRowContext(ctx, "SELECT generation FROM roster_generation WHERE singleton=1").Scan(&g)
+ if err == nil {
+ if !CanonicalToken(g) {
+ return ErrUnavailable
+ }
+ out.Generation = &g
+ } else if !errors.Is(err, sql.ErrNoRows) {
+ return ErrUnavailable
+ }
+ id, sqid, err := nextTeam(ctx, c)
+ if err != nil {
+ return ErrUnavailable
+ }
+ out.TeamID, out.TeamSQID = id, sqid
+ return nil
+ })
+}
+
+// InspectHTTP is credential.inspect: new code, as the credential role had no
+// inspect before.
+func (h *CredentialHTTP) InspectHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if h == nil {
+ return nil, ErrRefused
+ }
+ return inspectHTTP(ctx, h.c.engine, raw, nil)
+}
diff --git a/internal/operator/http_verbs_test.go b/internal/operator/http_verbs_test.go
new file mode 100644
index 0000000..276727f
--- /dev/null
+++ b/internal/operator/http_verbs_test.go
@@ -0,0 +1,709 @@
+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"
+ 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)
+ }
+ for _, secret := range [][]byte{[]byte("PRIVATE-TEAM-NAME-CANARY"), raw, raw2, raw3} {
+ if bytes.Contains(disk, secret) {
+ t.Fatal("plan bytes or name at rest")
+ }
+ }
+ }
+}
+
+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"}
+ f.http, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.dirKey.SignPub()), env, httpApps, func(a string) string { return credentialIndex(f.pepper, a) })
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.key.SignPub()), env, httpApps, func(string) string { return "" }); 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"),
+ "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)
+ }
+ *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
+}
diff --git a/internal/operator/plan.go b/internal/operator/plan.go
new file mode 100644
index 0000000..f95d836
--- /dev/null
+++ b/internal/operator/plan.go
@@ -0,0 +1,421 @@
+package operator
+
+import (
+ "context"
+ "database/sql"
+ "embed"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "io/fs"
+ "net/mail"
+ "slices"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+// The HTTP operator transport (implementation/team-provisioning-amendment.md)
+// keeps its tables in their own migration sets, so the frozen native-command
+// schema profiles do not move. A database carrying them is refused by the
+// native command's exact ledger check, as any additive foreign ledger is.
+//
+//go:embed http_migrations
+var httpMigrations embed.FS
+
+var CredentialHTTPSchema = httpSchema("credential")
+var DirectoryHTTPSchema = httpSchema("directory")
+
+func httpSchema(role string) *migrate.Set {
+ f, e := fs.Sub(httpMigrations, "http_migrations/"+role)
+ if e != nil {
+ panic(e)
+ }
+ return migrate.MustFromFS(f, "oficina_"+role+"_operator_http")
+}
+
+const (
+ PlanContext = "oficina/home/operator-plan/v1"
+ PlanLimit = 8 << 10
+ // PlanLifetime bounds a pending plan, and WindowLifetime the window its
+ // confirmation opens. Neither is ever extended.
+ PlanLifetime = 900
+ WindowLifetime = 900
+)
+
+// ErrBusy is a refusal that says only "a plan is already pending or open".
+var ErrBusy = errors.New("operator: busy")
+
+// Plan is what Alta signs and submits to each role. Home verifies it, keeps
+// only the closed fields it needs (sealed or blind-indexed where they are
+// account-authored) and never stores these bytes.
+type Plan struct {
+ Version int `json:"version"`
+ Purpose string `json:"purpose"`
+ Role string `json:"role"`
+ Origin string `json:"origin"`
+ Installation string `json:"installation"`
+ Registry string `json:"registry"`
+ Device string `json:"device"`
+ PlanID string `json:"plan_id"`
+ Kind string `json:"kind"`
+ Apps []string `json:"apps"`
+ Label string `json:"label,omitzero"`
+ DisplayName string `json:"display_name,omitzero"`
+ Owner string `json:"owner,omitzero"`
+ Issued int64 `json:"issued_at"`
+ Expires int64 `json:"expires_at"`
+}
+
+func planKind(role, kind string) bool {
+ switch kind {
+ case "create-team", "add-apps", "retire-apps":
+ return role == "credential" || role == "directory"
+ case "initialize":
+ return role == "directory"
+ }
+ return false
+}
+
+// teamName is the directory's own team-name rule, restated so a plan is
+// refused at submit rather than at seed-team.
+func teamName(s string) bool {
+ if len(s) == 0 || len(s) > 255 || !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
+ return false
+ }
+ for _, r := range s {
+ if unicode.IsControl(r) {
+ return false
+ }
+ }
+ return true
+}
+
+// ownerAddress is the exact form owner-seed accepts.
+func ownerAddress(s string) bool {
+ if len(s) == 0 || len(s) > 320 || !utf8.ValidString(s) {
+ return false
+ }
+ a, e := mail.ParseAddress(s)
+ return e == nil && a.Address == s && a.Name == ""
+}
+
+func (p Plan) valid(apps map[string]bool) bool {
+ if p.Version != 1 || p.Purpose != "operator-plan" || !planKind(p.Role, p.Kind) || !Origin(p.Origin) || !CanonicalToken(p.Installation) || !CanonicalToken(p.Registry) || !CanonicalToken(p.Device) || !CanonicalToken(p.PlanID) || p.Issued <= 0 || p.Expires <= p.Issued || p.Expires-p.Issued > PlanLifetime {
+ return false
+ }
+ if p.Kind == "initialize" {
+ return len(p.Apps) == 0 && p.Label == "" && p.DisplayName == "" && p.Owner == ""
+ }
+ if len(p.Apps) == 0 || len(p.Apps) > 8 {
+ return false
+ }
+ seen := map[string]bool{}
+ for _, app := range p.Apps {
+ if !apps[app] || seen[app] {
+ return false
+ }
+ seen[app] = true
+ }
+ if p.Role == "directory" {
+ return p.Owner == "" && directorydata.ValidLabel(p.Label) && (p.Kind == "create-team") == (p.DisplayName != "") && (p.DisplayName == "" || teamName(p.DisplayName))
+ }
+ return p.Label == "" && p.DisplayName == "" && (p.Kind == "create-team") == (p.Owner != "") && (p.Owner == "" || ownerAddress(p.Owner))
+}
+
+// SignPlan is Alta's half, kept here so tests and Alta sign the one format.
+func SignPlan(k *family.Keypair, p Plan, apps []string) ([]byte, error) {
+ set := map[string]bool{}
+ for _, a := range apps {
+ set[a] = true
+ }
+ if !signingKey(k) || !p.valid(set) {
+ return nil, ErrRefused
+ }
+ payload, e := encode(p)
+ if e != nil {
+ return nil, ErrRefused
+ }
+ sig, e := family.Sign(k, PlanContext, payload)
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ out, e := encode(envelope{1, keyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)})
+ if e != nil || len(out) > PlanLimit {
+ return nil, ErrRefused
+ }
+ return out, nil
+}
+
+// VerifyPlan checks the pinned key, the plan context, this role's exact pins,
+// the closed fields and the clock. apps is the compiled registry.
+func (v *Verifier) VerifyPlan(raw []byte, apps []string, now time.Time) (Plan, error) {
+ var env envelope
+ var p Plan
+ if v == nil || len(raw) == 0 || len(raw) > PlanLimit || strictCanonical(raw, &env) != nil || env.Version != 1 || env.KeyID != v.kid {
+ return Plan{}, ErrRefused
+ }
+ payload, ok := canonical(env.Payload, -1)
+ sig, ok2 := canonical(env.Signature, 64)
+ if !ok || !ok2 || len(payload) > PlanLimit || !family.Verify(v.key, PlanContext, payload, sig) || strictCanonical(payload, &p) != nil {
+ return Plan{}, ErrRefused
+ }
+ set := map[string]bool{}
+ for _, a := range apps {
+ set[a] = true
+ }
+ pins := v.pins
+ if !p.valid(set) || p.Role != pins.Role || p.Origin != pins.Origin || p.Installation != pins.Installation || p.Registry != pins.Registry || p.Device != pins.Device || now.Unix() <= 0 || p.Issued > now.Unix() || now.Unix() >= p.Expires {
+ return Plan{}, ErrRefused
+ }
+ return p, nil
+}
+
+// PlanView is Home's own copy of a stored plan: never the signed bytes, never
+// the owner's address. DisplayName is opened only on the directory.
+type PlanView struct {
+ ID, State, Kind, Label, DisplayName, OwnerIndex string
+ Apps []string
+ Expires, WindowExpires int64
+}
+
+// Prefix is the first 8 hex digits of the plan id, the one thing Paul
+// compares across the two confirm pages.
+func (p PlanView) Prefix() string { return planPrefix(p.ID) }
+func planPrefix(id string) string {
+ b, ok := canonical(id, 32)
+ if !ok {
+ return ""
+ }
+ return hex.EncodeToString(b[:4])
+}
+
+// PlanStore keeps one role's plan rows. Expired rows are deleted, never
+// left (secure_delete is on), so an unconfirmed blind index does not linger.
+type PlanStore struct {
+ db *sql.DB
+ role string
+ sealer Sealer
+}
+
+func NewPlanStore(db *sql.DB, role string, sealer Sealer) (*PlanStore, error) {
+ if db == nil || sealer == nil || (role != "credential" && role != "directory") {
+ return nil, ErrRefused
+ }
+ return &PlanStore{db, role, sealer}, nil
+}
+
+func hexHash(s string) bool {
+ b, e := hex.DecodeString(s)
+ return e == nil && len(b) == 32 && hex.EncodeToString(b) == s
+}
+
+func planNamePurpose(id string) string { return "directory.operator-plan-name/" + id }
+
+type execer interface {
+ ExecContext(context.Context, string, ...any) (sql.Result, error)
+ QueryRowContext(context.Context, string, ...any) *sql.Row
+}
+
+func sweepPlans(ctx context.Context, x execer, now int64) error {
+ _, e := x.ExecContext(ctx, "DELETE FROM operator_plans WHERE (state='pending' AND expires_at<=?) OR (state='open' AND window_expires_at<=?)", now, now)
+ if e != nil {
+ return ErrUnavailable
+ }
+ return nil
+}
+
+// Sweep deletes every expired plan row.
+func (s *PlanStore) Sweep(ctx context.Context, now time.Time) error {
+ return sweepPlans(ctx, s.db, now.Unix())
+}
+
+// withTx runs f inside BEGIN IMMEDIATE on one connection.
+func withTx(ctx context.Context, db *sql.DB, f func(*sql.Conn) error) error {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ c, e := db.Conn(ctx)
+ if e != nil {
+ return ErrUnavailable
+ }
+ defer c.Close()
+ if _, e = c.ExecContext(ctx, "BEGIN IMMEDIATE"); e != nil {
+ return ErrUnavailable
+ }
+ if e = f(c); e != nil {
+ _, _ = c.ExecContext(context.Background(), "ROLLBACK")
+ return e
+ }
+ if _, e = c.ExecContext(ctx, "COMMIT"); e != nil {
+ _, _ = c.ExecContext(context.Background(), "ROLLBACK")
+ return ErrUnavailable
+ }
+ return nil
+}
+
+// Submit stores a verified plan's closed fields. ownerIndex is the credential
+// role's blind index of the owner, computed by the caller from an existing
+// person; the address itself never reaches this function's writes.
+func (s *PlanStore) Submit(ctx context.Context, p Plan, ownerIndex string, now time.Time) error {
+ if s == nil || p.Role != s.role {
+ return ErrRefused
+ }
+ if s.role == "credential" && ((p.Kind == "create-team") != (ownerIndex != "") || (ownerIndex != "" && !hexHash(ownerIndex))) {
+ return ErrRefused
+ }
+ if s.role == "directory" && ownerIndex != "" {
+ return ErrRefused
+ }
+ apps := slices.Clone(p.Apps)
+ slices.Sort(apps)
+ // Swept in its own statement, so a refusal below cannot roll it back.
+ if e := s.Sweep(ctx, now); e != nil {
+ return e
+ }
+ return withTx(ctx, s.db, func(c *sql.Conn) error {
+ var n int
+ if c.QueryRowContext(ctx, "SELECT count(*) FROM operator_plans WHERE state='pending' OR plan_id=?", p.PlanID).Scan(&n) != nil {
+ return ErrUnavailable
+ }
+ if n != 0 {
+ return ErrBusy
+ }
+ if s.role == "credential" {
+ var index any
+ if ownerIndex != "" {
+ index = ownerIndex
+ }
+ if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,apps,owner_index,expires_at) VALUES(?,'pending',?,?,?,?)", p.PlanID, p.Kind, strings.Join(apps, ","), index, p.Expires); e != nil {
+ return ErrUnavailable
+ }
+ return nil
+ }
+ var label, name any
+ if p.Label != "" {
+ label = p.Label
+ }
+ if p.DisplayName != "" {
+ sealed, e := s.sealer.Seal(planNamePurpose(p.PlanID), []byte(p.DisplayName))
+ if e != nil {
+ return ErrUnavailable
+ }
+ name = sealed
+ }
+ if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,label,apps,sealed_name,expires_at) VALUES(?,'pending',?,?,?,?,?)", p.PlanID, p.Kind, label, strings.Join(apps, ","), name, p.Expires); e != nil {
+ return ErrUnavailable
+ }
+ return nil
+ })
+}
+
+func scanPlan(ctx context.Context, q execer, role, where string, args ...any) (PlanView, []byte, error) {
+ var v PlanView
+ var apps string
+ var label, index sql.NullString
+ var window sql.NullInt64
+ var sealed []byte
+ var e error
+ if role == "credential" {
+ e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,apps,owner_index,expires_at,window_expires_at FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &apps, &index, &v.Expires, &window)
+ } else {
+ e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,label,apps,sealed_name,expires_at,window_expires_at FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &label, &apps, &sealed, &v.Expires, &window)
+ }
+ if errors.Is(e, sql.ErrNoRows) {
+ return PlanView{}, nil, ErrRefused
+ }
+ if e != nil {
+ return PlanView{}, nil, ErrUnavailable
+ }
+ if apps != "" {
+ v.Apps = strings.Split(apps, ",")
+ }
+ v.Label, v.OwnerIndex, v.WindowExpires = label.String, index.String, window.Int64
+ return v, sealed, nil
+}
+
+func (s *PlanStore) open(v PlanView, sealed []byte) (PlanView, error) {
+ if sealed == nil {
+ return v, nil
+ }
+ name, e := s.sealer.Open(planNamePurpose(v.ID), sealed)
+ if e != nil {
+ return PlanView{}, ErrUnavailable
+ }
+ v.DisplayName = string(name)
+ return v, 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())
+ if e != nil {
+ return PlanView{}, e
+ }
+ return s.open(v, sealed)
+}
+
+// Open opens the window for the pending plan named id, re-checking expiry
+// inside the write. admit sees Home's copy before anything changes; the
+// credential role compares the typed owner's blind index there.
+func (s *PlanStore) Open(ctx context.Context, id string, now time.Time, admit func(PlanView) bool) (PlanView, error) {
+ var out PlanView
+ if s == nil || !CanonicalToken(id) || admit == nil {
+ return out, ErrRefused
+ }
+ if e := s.Sweep(ctx, now); e != nil {
+ return out, e
+ }
+ e := withTx(ctx, s.db, func(c *sql.Conn) error {
+ v, sealed, e := scanPlan(ctx, c, s.role, "plan_id=? AND state='pending' AND expires_at>?", id, now.Unix())
+ if e != nil {
+ return e
+ }
+ if v, e = s.open(v, sealed); e != nil {
+ return e
+ }
+ if !admit(v) {
+ return ErrRefused
+ }
+ var open int
+ if c.QueryRowContext(ctx, "SELECT count(*) FROM operator_plans WHERE state='open'").Scan(&open) != nil {
+ return ErrUnavailable
+ }
+ if open != 0 {
+ return ErrBusy
+ }
+ window := now.Unix() + WindowLifetime
+ if _, e = c.ExecContext(ctx, "UPDATE operator_plans SET state='open',window_expires_at=? WHERE plan_id=? AND state='pending'", window, id); e != nil {
+ return ErrUnavailable
+ }
+ v.State, v.WindowExpires = "open", window
+ out = v
+ return nil
+ })
+ return out, e
+}
+
+// window is the role's one open, unexpired window, read on the operation's
+// own locked connection. No window is a refusal.
+func window(ctx context.Context, c *sql.Conn, role string, now int64) (PlanView, []byte, error) {
+ return scanPlan(ctx, c, role, "state='open' AND window_expires_at>?", now)
+}
+
+// windowKinds is §5's table: which plan kinds admit which verb.
+func windowAdmits(kind, action string) bool {
+ switch action {
+ case "directory.initialize":
+ return kind == "initialize"
+ case "directory.seed-team", "credential.owner-seed":
+ return kind == "create-team"
+ case "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "credential.register-consumer":
+ return kind == "create-team" || kind == "add-apps"
+ case "directory.disable-consumer", "credential.retire-consumer":
+ return kind == "retire-apps"
+ }
+ return false
+}
diff --git a/internal/operator/protocol.go b/internal/operator/protocol.go
index c56c1d6..e022651 100644
--- a/internal/operator/protocol.go
+++ b/internal/operator/protocol.go
@@ -129,11 +129,14 @@ func public(encoded string) ([]byte, error) {
}
func allowedAction(role, a string) bool {
if role == "credential" {
- return a == "credential.owner-seed"
+ switch a {
+ case "credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect":
+ return true
+ }
}
if role == "directory" {
switch a {
- case "directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer":
+ case "directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer":
return true
}
}