| 1 | package operator |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "embed" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "errors" |
| 10 | "io/fs" |
| 11 | "net/mail" |
| 12 | "slices" |
| 13 | "strings" |
| 14 | "time" |
| 15 | "unicode" |
| 16 | "unicode/utf8" |
| 17 | |
| 18 | "amadan.net/oficina/home/internal/home/directorydata" |
| 19 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 20 | "amadan.net/rastrillo/rastrillo/migrate" |
| 21 | ) |
| 22 | |
| 23 | // The HTTP operator transport (implementation/team-provisioning-amendment.md) |
| 24 | // keeps its tables in their own migration sets, so the frozen native-command |
| 25 | // schema profiles do not move. A database carrying them is refused by the |
| 26 | // native command's exact ledger check, as any additive foreign ledger is. |
| 27 | // |
| 28 | //go:embed http_migrations |
| 29 | var httpMigrations embed.FS |
| 30 | |
| 31 | var CredentialHTTPSchema = httpSchema("credential") |
| 32 | var DirectoryHTTPSchema = httpSchema("directory") |
| 33 | |
| 34 | func httpSchema(role string) *migrate.Set { |
| 35 | f, e := fs.Sub(httpMigrations, "http_migrations/"+role) |
| 36 | if e != nil { |
| 37 | panic(e) |
| 38 | } |
| 39 | return migrate.MustFromFS(f, "oficina_"+role+"_operator_http") |
| 40 | } |
| 41 | |
| 42 | const ( |
| 43 | PlanContext = "oficina/home/operator-plan/v1" |
| 44 | PlanLimit = 8 << 10 |
| 45 | // PlanLifetime bounds a pending plan, and WindowLifetime the window its |
| 46 | // confirmation opens. Neither is ever extended. |
| 47 | PlanLifetime = 900 |
| 48 | WindowLifetime = 900 |
| 49 | ) |
| 50 | |
| 51 | // ErrBusy is a refusal that says only "a plan is already pending or open". |
| 52 | var ErrBusy = errors.New("operator: busy") |
| 53 | |
| 54 | // Plan is what Alta signs and submits to each role. Home verifies it, keeps |
| 55 | // only the closed fields it needs (sealed or blind-indexed where they are |
| 56 | // account-authored) and never stores these bytes. |
| 57 | type Plan struct { |
| 58 | Version int `json:"version"` |
| 59 | Purpose string `json:"purpose"` |
| 60 | Role string `json:"role"` |
| 61 | Origin string `json:"origin"` |
| 62 | Installation string `json:"installation"` |
| 63 | Registry string `json:"registry"` |
| 64 | Device string `json:"device"` |
| 65 | PlanID string `json:"plan_id"` |
| 66 | Kind string `json:"kind"` |
| 67 | Apps []string `json:"apps"` |
| 68 | Label string `json:"label,omitzero"` |
| 69 | DisplayName string `json:"display_name,omitzero"` |
| 70 | Owner string `json:"owner,omitzero"` |
| 71 | ExistingTeam string `json:"existing_team,omitzero"` |
| 72 | Issued int64 `json:"issued_at"` |
| 73 | Expires int64 `json:"expires_at"` |
| 74 | } |
| 75 | |
| 76 | func planKind(role, kind string) bool { |
| 77 | switch kind { |
| 78 | case "create-team", "add-apps", "retire-apps": |
| 79 | return role == "credential" || role == "directory" |
| 80 | case "initialize": |
| 81 | return role == "directory" |
| 82 | } |
| 83 | return false |
| 84 | } |
| 85 | |
| 86 | // teamName is the directory's own team-name rule, restated so a plan is |
| 87 | // refused at submit rather than at seed-team. |
| 88 | func teamName(s string) bool { |
| 89 | if len(s) == 0 || len(s) > 255 || !utf8.ValidString(s) || strings.TrimSpace(s) == "" { |
| 90 | return false |
| 91 | } |
| 92 | for _, r := range s { |
| 93 | if unicode.IsControl(r) { |
| 94 | return false |
| 95 | } |
| 96 | } |
| 97 | return true |
| 98 | } |
| 99 | |
| 100 | // ownerAddress is the exact form owner-seed accepts. |
| 101 | func ownerAddress(s string) bool { |
| 102 | if len(s) == 0 || len(s) > 320 || !utf8.ValidString(s) { |
| 103 | return false |
| 104 | } |
| 105 | a, e := mail.ParseAddress(s) |
| 106 | return e == nil && a.Address == s && a.Name == "" |
| 107 | } |
| 108 | |
| 109 | func (p Plan) valid(apps map[string]bool) bool { |
| 110 | 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 { |
| 111 | return false |
| 112 | } |
| 113 | if p.ExistingTeam != "" { |
| 114 | if !validTeamSQID(p.ExistingTeam) || (p.Kind != "create-team" && p.Kind != "add-apps") || (p.Role == "directory" && p.Label != "oficina") { |
| 115 | return false |
| 116 | } |
| 117 | for _, app := range p.Apps { |
| 118 | if directorydata.CanonicalOrigin(app) == "" { |
| 119 | return false |
| 120 | } |
| 121 | } |
| 122 | } else if p.Role == "directory" && p.Label == "oficina" && (p.Kind == "create-team" || p.Kind == "add-apps") { |
| 123 | return false |
| 124 | } |
| 125 | if p.Kind == "initialize" { |
| 126 | return len(p.Apps) == 0 && p.Label == "" && p.DisplayName == "" && p.Owner == "" |
| 127 | } |
| 128 | if len(p.Apps) == 0 || len(p.Apps) > 8 { |
| 129 | return false |
| 130 | } |
| 131 | seen := map[string]bool{} |
| 132 | for _, app := range p.Apps { |
| 133 | if !apps[app] || seen[app] { |
| 134 | return false |
| 135 | } |
| 136 | seen[app] = true |
| 137 | } |
| 138 | if p.Role == "directory" { |
| 139 | return p.Owner == "" && directorydata.ValidLabel(p.Label) && (p.Kind == "create-team") == (p.DisplayName != "") && (p.DisplayName == "" || teamName(p.DisplayName)) |
| 140 | } |
| 141 | return p.Label == "" && p.DisplayName == "" && (p.Kind == "create-team") == (p.Owner != "") && (p.Owner == "" || ownerAddress(p.Owner)) |
| 142 | } |
| 143 | |
| 144 | // SignPlan is Alta's half, kept here so tests and Alta sign the one format. |
| 145 | func SignPlan(k *family.Keypair, p Plan, apps []string) ([]byte, error) { |
| 146 | set := map[string]bool{} |
| 147 | for _, a := range apps { |
| 148 | set[a] = true |
| 149 | } |
| 150 | if !signingKey(k) || !p.valid(set) { |
| 151 | return nil, ErrRefused |
| 152 | } |
| 153 | payload, e := encode(p) |
| 154 | if e != nil { |
| 155 | return nil, ErrRefused |
| 156 | } |
| 157 | sig, e := family.Sign(k, PlanContext, payload) |
| 158 | if e != nil { |
| 159 | return nil, ErrUnavailable |
| 160 | } |
| 161 | out, e := encode(envelope{1, keyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) |
| 162 | if e != nil || len(out) > PlanLimit { |
| 163 | return nil, ErrRefused |
| 164 | } |
| 165 | return out, nil |
| 166 | } |
| 167 | |
| 168 | // VerifyPlan checks the pinned key, the plan context, this role's exact pins, |
| 169 | // the closed fields and the clock. apps is the compiled registry. |
| 170 | func (v *Verifier) VerifyPlan(raw []byte, apps []string, now time.Time) (Plan, error) { |
| 171 | var env envelope |
| 172 | var p Plan |
| 173 | if v == nil || len(raw) == 0 || len(raw) > PlanLimit || strictCanonical(raw, &env) != nil || env.Version != 1 || env.KeyID != v.kid { |
| 174 | return Plan{}, ErrRefused |
| 175 | } |
| 176 | payload, ok := canonical(env.Payload, -1) |
| 177 | sig, ok2 := canonical(env.Signature, 64) |
| 178 | if !ok || !ok2 || len(payload) > PlanLimit || !family.Verify(v.key, PlanContext, payload, sig) || strictCanonical(payload, &p) != nil { |
| 179 | return Plan{}, ErrRefused |
| 180 | } |
| 181 | set := map[string]bool{} |
| 182 | for _, a := range apps { |
| 183 | set[a] = true |
| 184 | } |
| 185 | pins := v.pins |
| 186 | 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 { |
| 187 | return Plan{}, ErrRefused |
| 188 | } |
| 189 | return p, nil |
| 190 | } |
| 191 | |
| 192 | // PlanView is Home's own copy of a stored plan: never the signed bytes, never |
| 193 | // the owner's address. DisplayName is opened only on the directory. |
| 194 | type PlanView struct { |
| 195 | ID, State, Kind, Label, DisplayName, OwnerIndex string |
| 196 | ExistingTeam string |
| 197 | Apps []string |
| 198 | Expires, WindowExpires int64 |
| 199 | } |
| 200 | |
| 201 | // Prefix is the first 8 hex digits of the plan id, the one thing Paul |
| 202 | // compares across the two confirm pages. |
| 203 | func (p PlanView) Prefix() string { return planPrefix(p.ID) } |
| 204 | func planPrefix(id string) string { |
| 205 | b, ok := canonical(id, 32) |
| 206 | if !ok { |
| 207 | return "" |
| 208 | } |
| 209 | return hex.EncodeToString(b[:4]) |
| 210 | } |
| 211 | |
| 212 | // PlanStore keeps one role's plan rows. Expired rows are deleted, never |
| 213 | // left (secure_delete is on), so an unconfirmed blind index does not linger. |
| 214 | type PlanStore struct { |
| 215 | db *sql.DB |
| 216 | role string |
| 217 | sealer Sealer |
| 218 | } |
| 219 | |
| 220 | func NewPlanStore(db *sql.DB, role string, sealer Sealer) (*PlanStore, error) { |
| 221 | if db == nil || sealer == nil || (role != "credential" && role != "directory") { |
| 222 | return nil, ErrRefused |
| 223 | } |
| 224 | return &PlanStore{db, role, sealer}, nil |
| 225 | } |
| 226 | |
| 227 | func hexHash(s string) bool { |
| 228 | b, e := hex.DecodeString(s) |
| 229 | return e == nil && len(b) == 32 && hex.EncodeToString(b) == s |
| 230 | } |
| 231 | |
| 232 | func planNamePurpose(id string) string { return "directory.operator-plan-name/" + id } |
| 233 | |
| 234 | type execer interface { |
| 235 | ExecContext(context.Context, string, ...any) (sql.Result, error) |
| 236 | QueryRowContext(context.Context, string, ...any) *sql.Row |
| 237 | } |
| 238 | |
| 239 | func sweepPlans(ctx context.Context, x execer, now int64) error { |
| 240 | _, e := x.ExecContext(ctx, "DELETE FROM operator_plans WHERE (state='pending' AND expires_at<=?) OR (state='open' AND window_expires_at<=?)", now, now) |
| 241 | if e != nil { |
| 242 | return ErrUnavailable |
| 243 | } |
| 244 | return nil |
| 245 | } |
| 246 | |
| 247 | // Sweep deletes every expired plan row. |
| 248 | func (s *PlanStore) Sweep(ctx context.Context, now time.Time) error { |
| 249 | return sweepPlans(ctx, s.db, now.Unix()) |
| 250 | } |
| 251 | |
| 252 | // withTx runs f inside BEGIN IMMEDIATE on one connection. |
| 253 | func withTx(ctx context.Context, db *sql.DB, f func(*sql.Conn) error) error { |
| 254 | ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 255 | defer cancel() |
| 256 | c, e := db.Conn(ctx) |
| 257 | if e != nil { |
| 258 | return ErrUnavailable |
| 259 | } |
| 260 | defer c.Close() |
| 261 | if _, e = c.ExecContext(ctx, "BEGIN IMMEDIATE"); e != nil { |
| 262 | return ErrUnavailable |
| 263 | } |
| 264 | if e = f(c); e != nil { |
| 265 | _, _ = c.ExecContext(context.Background(), "ROLLBACK") |
| 266 | return e |
| 267 | } |
| 268 | if _, e = c.ExecContext(ctx, "COMMIT"); e != nil { |
| 269 | _, _ = c.ExecContext(context.Background(), "ROLLBACK") |
| 270 | return ErrUnavailable |
| 271 | } |
| 272 | return nil |
| 273 | } |
| 274 | |
| 275 | // Submit stores a verified plan's closed fields. ownerIndex is the credential |
| 276 | // role's blind index of the owner, computed by the caller from an existing |
| 277 | // person; the address itself never reaches this function's writes. |
| 278 | func (s *PlanStore) Submit(ctx context.Context, p Plan, ownerIndex string, now time.Time) error { |
| 279 | if s == nil || p.Role != s.role { |
| 280 | return ErrRefused |
| 281 | } |
| 282 | if s.role == "credential" && ((p.Kind == "create-team") != (ownerIndex != "") || (ownerIndex != "" && !hexHash(ownerIndex))) { |
| 283 | return ErrRefused |
| 284 | } |
| 285 | if s.role == "directory" && ownerIndex != "" { |
| 286 | return ErrRefused |
| 287 | } |
| 288 | apps := slices.Clone(p.Apps) |
| 289 | slices.Sort(apps) |
| 290 | // Swept in its own statement, so a refusal below cannot roll it back. |
| 291 | if e := s.Sweep(ctx, now); e != nil { |
| 292 | return e |
| 293 | } |
| 294 | return withTx(ctx, s.db, func(c *sql.Conn) error { |
| 295 | var n int |
| 296 | if c.QueryRowContext(ctx, "SELECT count(*) FROM operator_plans WHERE state='pending' OR plan_id=?", p.PlanID).Scan(&n) != nil { |
| 297 | return ErrUnavailable |
| 298 | } |
| 299 | if n != 0 { |
| 300 | return ErrBusy |
| 301 | } |
| 302 | if s.role == "credential" { |
| 303 | var index any |
| 304 | if ownerIndex != "" { |
| 305 | index = ownerIndex |
| 306 | } |
| 307 | 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 { |
| 308 | return ErrUnavailable |
| 309 | } |
| 310 | return nil |
| 311 | } |
| 312 | var label, name any |
| 313 | if p.Label != "" { |
| 314 | label = p.Label |
| 315 | } |
| 316 | if p.DisplayName != "" { |
| 317 | sealed, e := s.sealer.Seal(planNamePurpose(p.PlanID), []byte(p.DisplayName)) |
| 318 | if e != nil { |
| 319 | return ErrUnavailable |
| 320 | } |
| 321 | name = sealed |
| 322 | } |
| 323 | 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 { |
| 324 | return ErrUnavailable |
| 325 | } |
| 326 | return nil |
| 327 | }) |
| 328 | } |
| 329 | |
| 330 | func scanPlan(ctx context.Context, q execer, role, where string, args ...any) (PlanView, []byte, error) { |
| 331 | var v PlanView |
| 332 | var apps string |
| 333 | var label, index sql.NullString |
| 334 | var window sql.NullInt64 |
| 335 | var sealed []byte |
| 336 | var e error |
| 337 | if role == "credential" { |
| 338 | 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) |
| 339 | } else { |
| 340 | 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) |
| 341 | } |
| 342 | if errors.Is(e, sql.ErrNoRows) { |
| 343 | return PlanView{}, nil, ErrRefused |
| 344 | } |
| 345 | if e != nil { |
| 346 | return PlanView{}, nil, ErrUnavailable |
| 347 | } |
| 348 | if apps != "" { |
| 349 | v.Apps = strings.Split(apps, ",") |
| 350 | } |
| 351 | v.Label, v.OwnerIndex, v.WindowExpires = label.String, index.String, window.Int64 |
| 352 | return v, sealed, nil |
| 353 | } |
| 354 | |
| 355 | func (s *PlanStore) open(v PlanView, sealed []byte) (PlanView, error) { |
| 356 | if sealed == nil { |
| 357 | return v, nil |
| 358 | } |
| 359 | name, e := s.sealer.Open(planNamePurpose(v.ID), sealed) |
| 360 | if e != nil { |
| 361 | return PlanView{}, ErrUnavailable |
| 362 | } |
| 363 | v.DisplayName = string(name) |
| 364 | return v, nil |
| 365 | } |
| 366 | |
| 367 | // Ends lists when each surviving plan row ends: a pending plan's expiry, an |
| 368 | // open window's. Boot schedules a sweep for each, so a row that survives a |
| 369 | // restart is still deleted on time. |
| 370 | func (s *PlanStore) Ends(ctx context.Context, now time.Time) ([]int64, error) { |
| 371 | rows, e := s.db.QueryContext(ctx, "SELECT CASE state WHEN 'open' THEN window_expires_at ELSE expires_at END FROM operator_plans LIMIT 2") |
| 372 | if e != nil { |
| 373 | return nil, ErrUnavailable |
| 374 | } |
| 375 | defer rows.Close() |
| 376 | var out []int64 |
| 377 | for rows.Next() { |
| 378 | var end int64 |
| 379 | if rows.Scan(&end) != nil { |
| 380 | return nil, ErrUnavailable |
| 381 | } |
| 382 | out = append(out, end) |
| 383 | } |
| 384 | if rows.Err() != nil { |
| 385 | return nil, ErrUnavailable |
| 386 | } |
| 387 | return out, nil |
| 388 | } |
| 389 | |
| 390 | // Pending returns the role's one pending, unexpired plan. |
| 391 | func (s *PlanStore) Pending(ctx context.Context, now time.Time) (PlanView, error) { |
| 392 | v, sealed, e := scanPlan(ctx, s.db, s.role, "state='pending' AND expires_at>?", now.Unix()) |
| 393 | if e != nil { |
| 394 | return PlanView{}, e |
| 395 | } |
| 396 | return s.open(v, sealed) |
| 397 | } |
| 398 | |
| 399 | // Open opens the window for the pending plan named id, re-checking expiry |
| 400 | // inside the write. admit sees Home's copy before anything changes; the |
| 401 | // credential role compares the typed owner's blind index there. |
| 402 | func (s *PlanStore) Open(ctx context.Context, id string, now time.Time, admit func(PlanView) bool) (PlanView, error) { |
| 403 | var out PlanView |
| 404 | if s == nil || !CanonicalToken(id) || admit == nil { |
| 405 | return out, ErrRefused |
| 406 | } |
| 407 | if e := s.Sweep(ctx, now); e != nil { |
| 408 | return out, e |
| 409 | } |
| 410 | e := withTx(ctx, s.db, func(c *sql.Conn) error { |
| 411 | v, sealed, e := scanPlan(ctx, c, s.role, "plan_id=? AND state='pending' AND expires_at>?", id, now.Unix()) |
| 412 | if e != nil { |
| 413 | return e |
| 414 | } |
| 415 | if v, e = s.open(v, sealed); e != nil { |
| 416 | return e |
| 417 | } |
| 418 | if !admit(v) { |
| 419 | return ErrRefused |
| 420 | } |
| 421 | var open int |
| 422 | if c.QueryRowContext(ctx, "SELECT count(*) FROM operator_plans WHERE state='open'").Scan(&open) != nil { |
| 423 | return ErrUnavailable |
| 424 | } |
| 425 | if open != 0 { |
| 426 | return ErrBusy |
| 427 | } |
| 428 | window := now.Unix() + WindowLifetime |
| 429 | if _, e = c.ExecContext(ctx, "UPDATE operator_plans SET state='open',window_expires_at=? WHERE plan_id=? AND state='pending'", window, id); e != nil { |
| 430 | return ErrUnavailable |
| 431 | } |
| 432 | v.State, v.WindowExpires = "open", window |
| 433 | out = v |
| 434 | return nil |
| 435 | }) |
| 436 | return out, e |
| 437 | } |
| 438 | |
| 439 | // window is the role's one open, unexpired window, read on the operation's |
| 440 | // own locked connection. No window is a refusal. |
| 441 | func window(ctx context.Context, c *sql.Conn, role string, now int64) (PlanView, []byte, error) { |
| 442 | return scanPlan(ctx, c, role, "state='open' AND window_expires_at>?", now) |
| 443 | } |
| 444 | |
| 445 | // windowKinds is §5's table: which plan kinds admit which verb. |
| 446 | func windowAdmits(kind, action string) bool { |
| 447 | switch action { |
| 448 | case "directory.initialize": |
| 449 | return kind == "initialize" |
| 450 | case "directory.seed-team", "credential.owner-seed": |
| 451 | return kind == "create-team" |
| 452 | case "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "credential.register-consumer": |
| 453 | return kind == "create-team" || kind == "add-apps" |
| 454 | case "directory.disable-consumer", "credential.retire-consumer": |
| 455 | return kind == "retire-apps" |
| 456 | } |
| 457 | return false |
| 458 | } |
| 459 | |