package operator import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "database/sql" "encoding/base64" stdjson "encoding/json" "errors" "slices" "time" "amadan.net/oficina/home/internal/home/directorydata" "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 } // 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() 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.seedTeamForWindow(ctx, c, r, true, w.ExistingTeam) 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.provisionForWindow(ctx, c, r, w.ExistingTeam) case "directory.verify-consumer": var in VerificationInput if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) || !routeScope(w.ExistingTeam, w.Label, in.TeamSQID, in.App, in.Consumer, in.Audience) { return nil, ErrRefused } if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil { return nil, e } return d.verifyConsumerForWindow(ctx, c, r, w.ExistingTeam) case "directory.activate-consumer": var in ActivationInput if DecodeInput(r, &in) != nil || !contains(w.Apps, in.Evidence.App) || !routeScope(w.ExistingTeam, w.Label, in.Evidence.TeamSQID, in.Evidence.App, in.Evidence.Consumer, in.Evidence.Audience) { return nil, ErrRefused } if _, e := fence(ctx, c, in.Evidence.TeamSQID, w.Label); e != nil { return nil, e } return d.activateForWindow(ctx, c, r, w.ExistingTeam) 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 ---- // 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 { 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 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. 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, admit} 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 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() 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 } if w.ExistingTeam != "" && in.TeamSQID != w.ExistingTeam { 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) || !h.admit(b.Consumer, b.Audience) { return nil, ErrRefused } if w.ExistingTeam != "" { if b.Team != w.ExistingTeam || !directorydata.CanonicalBinding("oficina", b.App, b.Consumer, b.Audience) || h.env[b.Consumer] != b.Audience { return nil, ErrRefused } for id, origin := range h.env { if id != b.Consumer && origin == b.Audience { return nil, ErrRefused } } var clash int if c.QueryRowContext(ctx, "SELECT count(*) FROM consumers WHERE consumer_id=? OR origin=?", b.Consumer, b.Audience).Scan(&clash) != nil { return nil, ErrUnavailable } if clash != 0 { return nil, ErrRefused } // Verify the existing registration; never duplicate it in the table. return h.manifestResult(ctx, c, r) } for id, origin := range h.env { if id == b.Consumer || origin == b.Audience { return nil, ErrRefused } } 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 } 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 { return nil, ErrUnavailable } 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 .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, ®istry, &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) }