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"` ExistingTeam string `json:"existing_team,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.ExistingTeam != "" { if !validTeamSQID(p.ExistingTeam) || (p.Kind != "create-team" && p.Kind != "add-apps") || (p.Role == "directory" && p.Label != "oficina") { return false } for _, app := range p.Apps { if directorydata.CanonicalOrigin(app) == "" { return false } } } else if p.Role == "directory" && p.Label == "oficina" && (p.Kind == "create-team" || p.Kind == "add-apps") { 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 ExistingTeam 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,existing_team) VALUES(?,'pending',?,?,?,?,?)", p.PlanID, p.Kind, strings.Join(apps, ","), index, p.Expires, p.ExistingTeam); 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,existing_team) VALUES(?,'pending',?,?,?,?,?,?)", p.PlanID, p.Kind, label, strings.Join(apps, ","), name, p.Expires, p.ExistingTeam); 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,existing_team FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &apps, &index, &v.Expires, &window, &v.ExistingTeam) } else { e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,label,apps,sealed_name,expires_at,window_expires_at,existing_team FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &label, &apps, &sealed, &v.Expires, &window, &v.ExistingTeam) } 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 } // Ends lists when each surviving plan row ends: a pending plan's expiry, an // open window's. Boot schedules a sweep for each, so a row that survives a // restart is still deleted on time. func (s *PlanStore) Ends(ctx context.Context, now time.Time) ([]int64, error) { rows, e := s.db.QueryContext(ctx, "SELECT CASE state WHEN 'open' THEN window_expires_at ELSE expires_at END FROM operator_plans LIMIT 2") if e != nil { return nil, ErrUnavailable } defer rows.Close() var out []int64 for rows.Next() { var end int64 if rows.Scan(&end) != nil { return nil, ErrUnavailable } out = append(out, end) } if rows.Err() != nil { return nil, ErrUnavailable } return out, nil } // Pending returns the role's one pending, unexpired plan. func (s *PlanStore) Pending(ctx context.Context, now time.Time) (PlanView, error) { v, sealed, e := scanPlan(ctx, s.db, s.role, "state='pending' AND expires_at>?", now.Unix()) 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 }