oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1package provision
2
3import (
4 "context"
5 "database/sql"
6 "embed"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "slices"
11 "strings"
12 "time"
13
14 "amadan.net/oficina/home/handoff/seal"
15 "amadan.net/rastrillo/rastrillo/migrate"
16 _ "modernc.org/sqlite"
17)
18
19//go:embed migrations/*.sql
20var migrationFS embed.FS
21
22// Schema is Alta's own migration set.
23var Schema = migrate.MustFromFS(migrationFS, "alta")
24
25// ErrBusy is the run lock already held.
26var ErrBusy = errors.New("provision: another run is advancing")
27
28// Store is Alta's sealed SQLite state.
29type Store struct {
30 db *sql.DB
31 sealer *seal.Sealer
32 now func() time.Time
33}
34
35// OpenDB opens path with the pragmas Alta's privacy rule needs:
36// secure_delete, so a deleted address is overwritten, not left in a free
37// page. One writer connection, as SQLite allows one.
38func OpenDB(path string) (*sql.DB, error) {
39 dsn := "file:" + path + "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)&_pragma=secure_delete(1)&_time_format=sqlite&_timezone=UTC"
40 db, err := sql.Open("sqlite", dsn)
41 if err != nil {
42 return nil, err
43 }
44 db.SetMaxOpenConns(1)
45 if err := db.Ping(); err != nil {
46 db.Close()
47 return nil, err
48 }
49 return db, nil
50}
51
52// NewStore applies extra (sessions, handoff) and Alta's schema and seals
53// with dek (ALTA_DEK, 32 bytes).
54func NewStore(ctx context.Context, db *sql.DB, dek []byte, now func() time.Time, extra ...*migrate.Set) (*Store, error) {
55 if len(dek) != 32 {
56 return nil, errors.New("provision: ALTA_DEK must be 32 bytes")
57 }
58 s, err := seal.New(dek, "oficina/alta")
59 if err != nil {
60 return nil, err
61 }
62 sets := append([]*migrate.Set{Schema}, extra...)
63 if _, err := migrate.Apply(ctx, migrate.Pool(db), migrate.Merge(sets...)); err != nil {
64 return nil, fmt.Errorf("provision: migrate: %w", err)
65 }
66 if now == nil {
67 now = time.Now
68 }
69 return &Store{db: db, sealer: s, now: now}, nil
70}
71
72func (s *Store) DB() *sql.DB { return s.db }
73
74func (s *Store) seal(purpose string, b []byte) ([]byte, error) { return s.sealer.Seal(purpose, b) }
75func (s *Store) open(purpose string, b []byte) ([]byte, error) { return s.sealer.Open(purpose, b) }
76
77// adoptionPurpose admits only alta/adopt/<table>/<key>: the adoption
78// journal seals under ALTA_DEK, and can never open Alta's own rows (the
79// owner's address, plans, requests).
80func adoptionPurpose(purpose string) error {
81 rest, ok := strings.CutPrefix(purpose, "alta/adopt/")
82 table, key, two := strings.Cut(rest, "/")
83 if !ok || !two || table == "" || key == "" {
84 return errors.New("provision: not an adoption purpose")
85 }
86 return nil
87}
88
89// SealAdoption seals an adoption journal payload under purpose, which
90// must be alta/adopt/<table>/<key>.
91func (s *Store) SealAdoption(purpose string, b []byte) ([]byte, error) {
92 if err := adoptionPurpose(purpose); err != nil {
93 return nil, err
94 }
95 return s.seal(purpose, b)
96}
97
98// OpenAdoption opens what SealAdoption sealed under the same purpose.
99func (s *Store) OpenAdoption(purpose string, b []byte) ([]byte, error) {
100 if err := adoptionPurpose(purpose); err != nil {
101 return nil, err
102 }
103 return s.open(purpose, b)
104}
105
106// ---- teams ----
107
108// Team is one team as Alta holds it. No address.
109type Team struct {
110 Label, Name, Environment string
111 Forked bool
112 TeamID int64
113 TeamSQID string
114 Epoch int64
115 Generation string
116 OwnerRef string
117 CreatedAt time.Time
118 Apps map[string]string // app -> active|retired
119}
120
121func namePurpose(label string) string { return "alta/team-name/" + label }
122func ownerPurpose(label string) string { return "alta/owner/" + label }
123
124// LabelUsed reports whether label was ever used.
125func (s *Store) LabelUsed(ctx context.Context, label string) (bool, error) {
126 var n int
127 err := s.db.QueryRowContext(ctx, "SELECT count(*) FROM teams WHERE label=?", label).Scan(&n)
128 return n > 0, err
129}
130
131// CreateTeam records a new label, its sealed name, its environment and
132// the owner's sealed address, in one transaction.
133func (s *Store) CreateTeam(ctx context.Context, label, name, env string, forked bool, owner string, apps []string) error {
134 sealed, err := s.seal(namePurpose(label), []byte(name))
135 if err != nil {
136 return err
137 }
138 addr, err := s.seal(ownerPurpose(label), []byte(owner))
139 if err != nil {
140 return err
141 }
142 tx, err := s.db.BeginTx(ctx, nil)
143 if err != nil {
144 return err
145 }
146 defer tx.Rollback()
147 f := 0
148 if forked {
149 f = 1
150 }
151 if _, err := tx.ExecContext(ctx, "INSERT INTO teams(label,sealed_name,environment,forked,created_at) VALUES(?,?,?,?,?)", label, sealed, env, f, s.now().Unix()); err != nil {
152 return fmt.Errorf("provision: label taken: %w", err)
153 }
154 if _, err := tx.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?)", label, addr); err != nil {
155 return err
156 }
157 for _, app := range apps {
158 if _, err := tx.ExecContext(ctx, "INSERT INTO environments(app,environment,label) VALUES(?,?,?)", app, env, label); err != nil {
159 return fmt.Errorf("provision: environment %s already Alta's for %s: %w", env, app, err)
160 }
161 if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", label, app); err != nil {
162 return err
163 }
164 }
165 return tx.Commit()
166}
167
168// adoptionApps refuses an empty, unknown or repeated app list.
169func adoptionApps(apps []string) error {
170 if len(apps) == 0 {
171 return errors.New("provision: an adoption names at least one app")
172 }
173 seen := map[string]bool{}
174 for _, a := range apps {
175 if _, ok := AppBySlug(a); !ok || seen[a] {
176 return errors.New("provision: an adoption names an unknown or repeated app")
177 }
178 seen[a] = true
179 }
180 return nil
181}
182
183// CreateAdoption records the existing suite's team, label AdoptionLabel:
184// its sealed name, the owner's sealed address and its apps, in one
185// transaction. It records no environment, and so no environments row:
186// the six instances keep the environments they run in, which Alta never
187// created, and the §8 guard admits none of them.
188func (s *Store) CreateAdoption(ctx context.Context, name, owner string, apps []string) error {
189 if err := adoptionApps(apps); err != nil {
190 return err
191 }
192 sealed, err := s.seal(namePurpose(AdoptionLabel), []byte(name))
193 if err != nil {
194 return err
195 }
196 addr, err := s.seal(ownerPurpose(AdoptionLabel), []byte(owner))
197 if err != nil {
198 return err
199 }
200 tx, err := s.db.BeginTx(ctx, nil)
201 if err != nil {
202 return err
203 }
204 defer tx.Rollback()
205 if _, err := tx.ExecContext(ctx, "INSERT INTO teams(label,sealed_name,environment,forked,created_at) VALUES(?,?,'',0,?)", AdoptionLabel, sealed, s.now().Unix()); err != nil {
206 return fmt.Errorf("provision: label taken: %w", err)
207 }
208 if _, err := tx.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?)", AdoptionLabel, addr); err != nil {
209 return err
210 }
211 for _, app := range apps {
212 if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", AdoptionLabel, app); err != nil {
213 return err
214 }
215 }
216 return tx.Commit()
217}
218
219// AddAdoptionApps records newly supported canonical apps in the existing
220// team. Adoption owns no environments and must never reserve one here.
221func (s *Store) AddAdoptionApps(ctx context.Context, apps []string) error {
222 if err := adoptionApps(apps); err != nil {
223 return err
224 }
225 t, err := s.Team(ctx, AdoptionLabel)
226 if err != nil {
227 return err
228 }
229 tx, err := s.db.BeginTx(ctx, nil)
230 if err != nil {
231 return err
232 }
233 defer tx.Rollback()
234 for _, app := range apps {
235 switch t.Apps[app] {
236 case "retired":
237 return errors.New("provision: retired adoption app")
238 case "active":
239 continue
240 }
241 if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", AdoptionLabel, app); err != nil {
242 return err
243 }
244 }
245 return tx.Commit()
246}
247
248// AddApps records apps joining a team (an add-apps run). A retired app is
249// refused: its hostnames are dead for good.
250func (s *Store) AddApps(ctx context.Context, label string, apps []string) error {
251 t, err := s.Team(ctx, label)
252 if err != nil {
253 return err
254 }
255 tx, err := s.db.BeginTx(ctx, nil)
256 if err != nil {
257 return err
258 }
259 defer tx.Rollback()
260 for _, app := range apps {
261 switch t.Apps[app] {
262 case "retired":
263 return fmt.Errorf("provision: %s was retired from this team and is never re-added", app)
264 case "active":
265 continue
266 }
267 if _, err := tx.ExecContext(ctx, "INSERT INTO environments(app,environment,label) VALUES(?,?,?)", app, t.Environment, label); err != nil {
268 return err
269 }
270 if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", label, app); err != nil {
271 return err
272 }
273 }
274 return tx.Commit()
275}
276
277// RetireApp marks an app retired.
278func (s *Store) RetireApp(ctx context.Context, label, app string) error {
279 _, err := s.db.ExecContext(ctx, "UPDATE team_apps SET state='retired' WHERE label=? AND app=?", label, app)
280 return err
281}
282
283// Team reads one team.
284func (s *Store) Team(ctx context.Context, label string) (Team, error) {
285 var t Team
286 var sealed []byte
287 var forked int
288 var id, epoch sql.NullInt64
289 var sqid, gen, owner sql.NullString
290 var created int64
291 err := s.db.QueryRowContext(ctx, "SELECT label,sealed_name,environment,forked,team_id,team_sqid,epoch,generation,owner_ref,created_at FROM teams WHERE label=?", label).Scan(&t.Label, &sealed, &t.Environment, &forked, &id, &sqid, &epoch, &gen, &owner, &created)
292 if err != nil {
293 return Team{}, err
294 }
295 name, err := s.open(namePurpose(label), sealed)
296 if err != nil {
297 return Team{}, err
298 }
299 t.Name, t.Forked, t.TeamID, t.TeamSQID, t.Epoch, t.Generation, t.OwnerRef = string(name), forked == 1, id.Int64, sqid.String, epoch.Int64, gen.String, owner.String
300 t.CreatedAt = time.Unix(created, 0)
301 t.Apps = map[string]string{}
302 rows, err := s.db.QueryContext(ctx, "SELECT app,state FROM team_apps WHERE label=?", label)
303 if err != nil {
304 return Team{}, err
305 }
306 defer rows.Close()
307 for rows.Next() {
308 var app, state string
309 if err := rows.Scan(&app, &state); err != nil {
310 return Team{}, err
311 }
312 t.Apps[app] = state
313 }
314 return t, rows.Err()
315}
316
317// Teams lists every label, newest first.
318func (s *Store) Teams(ctx context.Context) ([]Team, error) {
319 rows, err := s.db.QueryContext(ctx, "SELECT label FROM teams ORDER BY created_at DESC, label")
320 if err != nil {
321 return nil, err
322 }
323 var labels []string
324 for rows.Next() {
325 var l string
326 if err := rows.Scan(&l); err != nil {
327 rows.Close()
328 return nil, err
329 }
330 labels = append(labels, l)
331 }
332 rows.Close()
333 var out []Team
334 for _, l := range labels {
335 t, err := s.Team(ctx, l)
336 if err != nil {
337 return nil, err
338 }
339 out = append(out, t)
340 }
341 return out, nil
342}
343
344// SetSeeded records what seed-team committed.
345// SetSeeded records what seed-team committed and marks the team step
346// done, in one transaction: a crash between the two would leave a team
347// sqid with its step undone, a state the owner-forgetting guard would
348// otherwise never see as seeded.
349func (s *Store) SetSeeded(ctx context.Context, label string, id int64, sqid string, epoch int64, generation, ownerRef string, step map[string]any) error {
350 data, err := json.Marshal(step)
351 if err != nil {
352 return err
353 }
354 tx, err := s.db.BeginTx(ctx, nil)
355 if err != nil {
356 return err
357 }
358 defer tx.Rollback()
359 if _, err := tx.ExecContext(ctx, "UPDATE teams SET team_id=?,team_sqid=?,epoch=?,generation=?,owner_ref=? WHERE label=?", id, sqid, epoch, generation, ownerRef, label); err != nil {
360 return err
361 }
362 if _, err := tx.ExecContext(ctx, "INSERT INTO steps(label,app,step,state,code,data,updated_at) VALUES(?,'',?,'done','',?,?) ON CONFLICT(label,app,step) DO UPDATE SET state='done',code='',data=excluded.data,updated_at=excluded.updated_at", label, StepTeam, string(data), s.now().Unix()); err != nil {
363 return err
364 }
365 return tx.Commit()
366}
367
368// ---- owner input ----
369
370// Owner returns the sealed owner address, if Alta still holds it.
371func (s *Store) Owner(ctx context.Context, label string) (string, bool, error) {
372 var sealed []byte
373 err := s.db.QueryRowContext(ctx, "SELECT sealed_address FROM owner_inputs WHERE label=?", label).Scan(&sealed)
374 if errors.Is(err, sql.ErrNoRows) {
375 return "", false, nil
376 }
377 if err != nil {
378 return "", false, err
379 }
380 b, err := s.open(ownerPurpose(label), sealed)
381 if err != nil {
382 return "", false, err
383 }
384 return string(b), true, nil
385}
386
387// SetOwner stores a retyped owner address (§4: the stopgap allowlist edit
388// after step 13 has Paul retype it, and Alta deletes it again once
389// written).
390func (s *Store) SetOwner(ctx context.Context, label, addr string) error {
391 sealed, err := s.seal(ownerPurpose(label), []byte(addr))
392 if err != nil {
393 return err
394 }
395 _, err = s.db.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?) ON CONFLICT(label) DO UPDATE SET sealed_address=excluded.sealed_address", label, sealed)
396 return err
397}
398
399// ForgetOwner deletes every row that carries the owner's address: the
400// owner input, the credential role's plan bytes and every owner-seed
401// request (§4, step 13). secure_delete overwrites them.
402func (s *Store) ForgetOwner(ctx context.Context, label string) error {
403 tx, err := s.db.BeginTx(ctx, nil)
404 if err != nil {
405 return err
406 }
407 defer tx.Rollback()
408 if _, err := tx.ExecContext(ctx, "DELETE FROM owner_inputs WHERE label=?", label); err != nil {
409 return err
410 }
411 if _, err := tx.ExecContext(ctx, "DELETE FROM operator_requests WHERE label=? AND action='credential.owner-seed'", label); err != nil {
412 return err
413 }
414 if _, err := tx.ExecContext(ctx, "UPDATE plan_submissions SET sealed_plan=NULL WHERE role='credential' AND plan_id IN (SELECT plan_id FROM runs WHERE label=? AND plan_id IS NOT NULL)", label); err != nil {
415 return err
416 }
417 return tx.Commit()
418}
419
420// ---- runs ----
421
422// Run is one (team, plan) run.
423type Run struct {
424 ID int64
425 Label string
426 Kind string
427 Apps []string
428 PlanID string
429 PlanExpires int64
430 State, Code string
431 Created, Upd time.Time
432 // Options is the profile and samples choice the run writes recipes
433 // with (create-team and add-apps; the others record outside).
434 Options RunOptions
435 // Adoption marks a run for the existing suite's team (label
436 // AdoptionLabel), whose instances Alta never created.
437 Adoption bool
438}
439
440// NewRun starts a run. Any unfinished run for the same label is
441// superseded: one live plan per team.
442func (s *Store) NewRun(ctx context.Context, kind, label string, apps []string, opt RunOptions) (int64, error) {
443 opt, ok := opt.Normal()
444 if !ok {
445 return 0, errors.New("provision: unknown profile")
446 }
447 return s.newRun(ctx, kind, label, apps, opt, false)
448}
449
450// NewAdoptionRun starts a create-team or add-apps run for the existing
451// suite's team, label AdoptionLabel, marked as an adoption. It writes no
452// recipe, so it records the default options. Like NewRun, it supersedes
453// any unfinished run for the label.
454func (s *Store) NewAdoptionRun(ctx context.Context, kind string, apps []string) (int64, error) {
455 if kind != "create-team" && kind != "add-apps" {
456 return 0, errors.New("provision: an adoption run is create-team or add-apps")
457 }
458 if err := adoptionApps(apps); err != nil {
459 return 0, err
460 }
461 return s.newRun(ctx, kind, AdoptionLabel, apps, RunOptions{Profile: ProfileOutside}, true)
462}
463
464func (s *Store) newRun(ctx context.Context, kind, label string, apps []string, opt RunOptions, adoption bool) (int64, error) {
465 now := s.now().Unix()
466 tx, err := s.db.BeginTx(ctx, nil)
467 if err != nil {
468 return 0, err
469 }
470 defer tx.Rollback()
471 if _, err := tx.ExecContext(ctx, "UPDATE runs SET state='superseded',updated_at=? WHERE label=? AND kind<>'initialize' AND state IN ('planned','running','parked')", now, label); err != nil {
472 return 0, err
473 }
474 if kind == "initialize" {
475 if _, err := tx.ExecContext(ctx, "UPDATE runs SET state='superseded',updated_at=? WHERE kind='initialize' AND state IN ('planned','running','parked')", now); err != nil {
476 return 0, err
477 }
478 }
479 res, err := tx.ExecContext(ctx, "INSERT INTO runs(label,kind,apps,state,created_at,updated_at,profile,samples,adoption) VALUES(?,?,?,'planned',?,?,?,?,?)", label, kind, strings.Join(apps, ","), now, now, string(opt.Profile), opt.Samples, adoption)
480 if err != nil {
481 return 0, err
482 }
483 id, err := res.LastInsertId()
484 if err != nil {
485 return 0, err
486 }
487 return id, tx.Commit()
488}
489
490func scanRun(sc interface{ Scan(...any) error }) (Run, error) {
491 var r Run
492 var apps string
493 var plan sql.NullString
494 var exp sql.NullInt64
495 var c, u int64
496 var profile string
497 if err := sc.Scan(&r.ID, &r.Label, &r.Kind, &apps, &plan, &exp, &r.State, &r.Code, &c, &u, &profile, &r.Options.Samples, &r.Adoption); err != nil {
498 return Run{}, err
499 }
500 r.Options.Profile = Profile(profile)
501 if apps != "" {
502 r.Apps = strings.Split(apps, ",")
503 }
504 r.PlanID, r.PlanExpires, r.Created, r.Upd = plan.String, exp.Int64, time.Unix(c, 0), time.Unix(u, 0)
505 return r, nil
506}
507
508const runCols = "id,label,kind,apps,plan_id,plan_expires_at,state,code,created_at,updated_at,profile,samples,adoption"
509
510func (s *Store) Run(ctx context.Context, id int64) (Run, error) {
511 return scanRun(s.db.QueryRowContext(ctx, "SELECT "+runCols+" FROM runs WHERE id=?", id))
512}
513
514// Runs lists a label's runs, newest first ("" lists initialize runs).
515func (s *Store) Runs(ctx context.Context, label string) ([]Run, error) {
516 rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE label=? ORDER BY id DESC LIMIT 50", label)
517 if err != nil {
518 return nil, err
519 }
520 defer rows.Close()
521 var out []Run
522 for rows.Next() {
523 r, err := scanRun(rows)
524 if err != nil {
525 return nil, err
526 }
527 out = append(out, r)
528 }
529 return out, rows.Err()
530}
531
532// LastOptions is the options of label's newest create-team or add-apps
533// run: what a run continued without a fresh choice writes with. A label
534// with none has the default (outside, no samples).
535func (s *Store) LastOptions(ctx context.Context, label string) (RunOptions, error) {
536 r, err := scanRun(s.db.QueryRowContext(ctx, "SELECT "+runCols+" FROM runs WHERE label=? AND kind IN ('create-team','add-apps') ORDER BY id DESC LIMIT 1", label))
537 if errors.Is(err, sql.ErrNoRows) {
538 return RunOptions{Profile: ProfileOutside}, nil
539 }
540 if err != nil {
541 return RunOptions{}, err
542 }
543 return r.Options, nil
544}
545
546// WrittenOptions is the run options app's environment was written with,
547// as step 7 recorded them when it finished. ok is false while step 7 is
548// not done. A step recorded before options existed reads as outside.
549func (s *Store) WrittenOptions(ctx context.Context, label, app string) (RunOptions, bool, error) {
550 d, ok, err := s.Done(ctx, label, app, StepEnv)
551 if err != nil || !ok {
552 return RunOptions{}, false, err
553 }
554 opt := RunOptions{Profile: ProfileOutside}
555 if p, _ := d["profile"].(string); p != "" {
556 opt.Profile = Profile(p)
557 }
558 opt.Samples, _ = d["samples"].(bool)
559 if opt, ok = opt.Normal(); !ok {
560 return RunOptions{}, false, errors.New("provision: unknown profile recorded")
561 }
562 return opt, true, nil
563}
564
565// AppOptions is the choice app runs under when Paul makes none: the one
566// its environment was written with (step 7 done), else that of the newest
567// create-team or add-apps run naming it, else the default.
568func (s *Store) AppOptions(ctx context.Context, label, app string) (RunOptions, error) {
569 if opt, ok, err := s.WrittenOptions(ctx, label, app); err != nil || ok {
570 return opt, err
571 }
572 rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE label=? AND kind IN ('create-team','add-apps') ORDER BY id DESC", label)
573 if err != nil {
574 return RunOptions{}, err
575 }
576 defer rows.Close()
577 for rows.Next() {
578 r, err := scanRun(rows)
579 if err != nil {
580 return RunOptions{}, err
581 }
582 if slices.Contains(r.Apps, app) {
583 return r.Options, nil
584 }
585 }
586 if err := rows.Err(); err != nil {
587 return RunOptions{}, err
588 }
589 return RunOptions{Profile: ProfileOutside}, nil
590}
591
592// LiveRuns lists every run not finished.
593func (s *Store) LiveRuns(ctx context.Context) ([]Run, error) {
594 rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE state IN ('planned','running','parked') ORDER BY id")
595 if err != nil {
596 return nil, err
597 }
598 defer rows.Close()
599 var out []Run
600 for rows.Next() {
601 r, err := scanRun(rows)
602 if err != nil {
603 return nil, err
604 }
605 out = append(out, r)
606 }
607 return out, rows.Err()
608}
609
610func (s *Store) SetRunState(ctx context.Context, id int64, state, code string) error {
611 _, err := s.db.ExecContext(ctx, "UPDATE runs SET state=?,code=?,updated_at=? WHERE id=?", state, code, s.now().Unix(), id)
612 return err
613}
614
615func (s *Store) SetRunPlan(ctx context.Context, id int64, planID string, expires int64) error {
616 _, err := s.db.ExecContext(ctx, "UPDATE runs SET plan_id=?,plan_expires_at=?,state='planned',code='',updated_at=? WHERE id=?", planID, expires, s.now().Unix(), id)
617 return err
618}
619
620// ---- plans ----
621
622// PlanSubmission is one role's copy of a plan.
623type PlanSubmission struct {
624 PlanID, Role, State string
625 Expires, Window int64
626 Signed []byte
627}
628
629func planPurpose(id, role string) string { return "alta/plan/" + id + "/" + role }
630
631func (s *Store) SavePlan(ctx context.Context, id, role string, signed []byte, expires int64) error {
632 sealed, err := s.seal(planPurpose(id, role), signed)
633 if err != nil {
634 return err
635 }
636 _, err = s.db.ExecContext(ctx, "INSERT INTO plan_submissions(plan_id,role,sealed_plan,state,expires_at) VALUES(?,?,?,'signed',?)", id, role, sealed, expires)
637 return err
638}
639
640func (s *Store) Plans(ctx context.Context, id string) (map[string]PlanSubmission, error) {
641 rows, err := s.db.QueryContext(ctx, "SELECT plan_id,role,sealed_plan,state,expires_at,window_expires_at FROM plan_submissions WHERE plan_id=?", id)
642 if err != nil {
643 return nil, err
644 }
645 defer rows.Close()
646 out := map[string]PlanSubmission{}
647 for rows.Next() {
648 var p PlanSubmission
649 var sealed []byte
650 var w sql.NullInt64
651 if err := rows.Scan(&p.PlanID, &p.Role, &sealed, &p.State, &p.Expires, &w); err != nil {
652 return nil, err
653 }
654 p.Window = w.Int64
655 if sealed != nil {
656 if p.Signed, err = s.open(planPurpose(p.PlanID, p.Role), sealed); err != nil {
657 return nil, err
658 }
659 }
660 out[p.Role] = p
661 }
662 return out, rows.Err()
663}
664
665func (s *Store) MarkPlan(ctx context.Context, id, role, state string, window int64) error {
666 var w any
667 if window > 0 {
668 w = window
669 }
670 _, err := s.db.ExecContext(ctx, "UPDATE plan_submissions SET state=?,window_expires_at=coalesce(?,window_expires_at) WHERE plan_id=? AND role=?", state, w, id, role)
671 return err
672}
673
674// DropExpiredPlans deletes the signed bytes of every plan past its expiry
675// and window: they are kept only to retry a busy role.
676func (s *Store) DropExpiredPlans(ctx context.Context) error {
677 now := s.now().Unix()
678 _, err := s.db.ExecContext(ctx, "UPDATE plan_submissions SET sealed_plan=NULL WHERE expires_at<=? AND (window_expires_at IS NULL OR window_expires_at<=?)", now, now)
679 return err
680}
681
682// ---- steps ----
683
684// Step is one recorded step. Data is non-secret JSON.
685type Step struct {
686 Label, App, Name, State, Code string
687 Data map[string]any
688 Updated time.Time
689}
690
691func (s *Store) Step(ctx context.Context, label, app, name string) (Step, bool, error) {
692 st := Step{Label: label, App: app, Name: name}
693 var data string
694 var u int64
695 err := s.db.QueryRowContext(ctx, "SELECT state,code,data,updated_at FROM steps WHERE label=? AND app=? AND step=?", label, app, name).Scan(&st.State, &st.Code, &data, &u)
696 if errors.Is(err, sql.ErrNoRows) {
697 return st, false, nil
698 }
699 if err != nil {
700 return st, false, err
701 }
702 st.Updated = time.Unix(u, 0)
703 if err := json.Unmarshal([]byte(data), &st.Data); err != nil {
704 return st, false, err
705 }
706 return st, true, nil
707}
708
709// Done reports whether a step is done, and its data.
710func (s *Store) Done(ctx context.Context, label, app, name string) (map[string]any, bool, error) {
711 st, ok, err := s.Step(ctx, label, app, name)
712 if err != nil || !ok || st.State != "done" {
713 return nil, false, err
714 }
715 return st.Data, true, nil
716}
717
718func (s *Store) SetStep(ctx context.Context, label, app, name, state, code string, data map[string]any) error {
719 if data == nil {
720 data = map[string]any{}
721 }
722 b, err := json.Marshal(data)
723 if err != nil {
724 return err
725 }
726 _, err = s.db.ExecContext(ctx, "INSERT INTO steps(label,app,step,state,code,data,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(label,app,step) DO UPDATE SET state=excluded.state,code=excluded.code,data=excluded.data,updated_at=excluded.updated_at", label, app, name, state, code, string(b), s.now().Unix())
727 return err
728}
729
730// Steps lists a team's steps.
731func (s *Store) Steps(ctx context.Context, label string) ([]Step, error) {
732 rows, err := s.db.QueryContext(ctx, "SELECT app,step,state,code,data,updated_at FROM steps WHERE label=? ORDER BY app,step", label)
733 if err != nil {
734 return nil, err
735 }
736 defer rows.Close()
737 var out []Step
738 for rows.Next() {
739 st := Step{Label: label}
740 var data string
741 var u int64
742 if err := rows.Scan(&st.App, &st.Name, &st.State, &st.Code, &data, &u); err != nil {
743 return nil, err
744 }
745 _ = json.Unmarshal([]byte(data), &st.Data)
746 st.Updated = time.Unix(u, 0)
747 out = append(out, st)
748 }
749 return out, rows.Err()
750}
751
752// ---- operator requests and streams ----
753
754// OpRequest is one signed operation Alta holds.
755type OpRequest struct {
756 ID int64
757 Role, OperationID, Action string
758 Label, App, Purpose, Head string
759 Sequence, Expires int64
760 State string
761 Bytes []byte
762}
763
764func requestPurpose(opID string) string { return "alta/request/" + opID }
765
766// NextJournal reserves a journal sequence for a request about to be
767// signed (Home requires journal_sequence > 0; it is Alta's own counter).
768func (s *Store) NextJournal(ctx context.Context) (int64, error) {
769 var n sql.NullInt64
770 err := s.db.QueryRowContext(ctx, "SELECT max(id) FROM operator_requests").Scan(&n)
771 return n.Int64 + 1, err
772}
773
774// SaveRequest stores a signed request, sealed, before it is sent.
775func (s *Store) SaveRequest(ctx context.Context, r OpRequest) error {
776 sealed, err := s.seal(requestPurpose(r.OperationID), r.Bytes)
777 if err != nil {
778 return err
779 }
780 _, err = s.db.ExecContext(ctx, "INSERT INTO operator_requests(id,role,sequence,operation_id,action,label,app,purpose,head,sealed_request,state,expires_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,'signed',?,?)", r.ID, r.Role, r.Sequence, r.OperationID, r.Action, r.Label, r.App, r.Purpose, r.Head, sealed, r.Expires, s.now().Unix())
781 return err
782}
783
784func (s *Store) scanRequest(sc interface{ Scan(...any) error }) (OpRequest, error) {
785 var r OpRequest
786 var sealed []byte
787 if err := sc.Scan(&r.ID, &r.Role, &r.Sequence, &r.OperationID, &r.Action, &r.Label, &r.App, &r.Purpose, &r.Head, &sealed, &r.State, &r.Expires); err != nil {
788 return OpRequest{}, err
789 }
790 b, err := s.open(requestPurpose(r.OperationID), sealed)
791 if err != nil {
792 return OpRequest{}, err
793 }
794 r.Bytes = b
795 return r, nil
796}
797
798const reqCols = "id,role,sequence,operation_id,action,label,app,purpose,head,sealed_request,state,expires_at"
799
800// LastRequest is the newest request for (label, app, purpose) that is
801// not refused: the one to replay.
802func (s *Store) LastRequest(ctx context.Context, label, app, purpose string) (OpRequest, bool, error) {
803 r, err := s.scanRequest(s.db.QueryRowContext(ctx, "SELECT "+reqCols+" FROM operator_requests WHERE label=? AND app=? AND purpose=? AND state<>'refused' ORDER BY id DESC LIMIT 1", label, app, purpose))
804 if errors.Is(err, sql.ErrNoRows) {
805 return OpRequest{}, false, nil
806 }
807 return r, err == nil, err
808}
809
810// RequestByHead finds the request Alta signed whose authorization hashes
811// to head on role, if it holds one.
812func (s *Store) RequestByHead(ctx context.Context, role, head string) (OpRequest, bool, error) {
813 r, err := s.scanRequest(s.db.QueryRowContext(ctx, "SELECT "+reqCols+" FROM operator_requests WHERE role=? AND head=?", role, head))
814 if errors.Is(err, sql.ErrNoRows) {
815 return OpRequest{}, false, nil
816 }
817 return r, err == nil, err
818}
819
820func (s *Store) MarkRequest(ctx context.Context, id int64, state string) error {
821 _, err := s.db.ExecContext(ctx, "UPDATE operator_requests SET state=? WHERE id=?", state, id)
822 return err
823}
824
825// Commit records a committed request and advances the role's stream in
826// one transaction.
827func (s *Store) Commit(ctx context.Context, r OpRequest) error {
828 tx, err := s.db.BeginTx(ctx, nil)
829 if err != nil {
830 return err
831 }
832 defer tx.Rollback()
833 if _, err := tx.ExecContext(ctx, "UPDATE operator_requests SET state='committed' WHERE id=?", r.ID); err != nil {
834 return err
835 }
836 if _, err := tx.ExecContext(ctx, "INSERT INTO operator_streams(role,sequence,head,updated_at) VALUES(?,?,?,?) ON CONFLICT(role) DO UPDATE SET sequence=excluded.sequence,head=excluded.head,updated_at=excluded.updated_at WHERE excluded.sequence>operator_streams.sequence", r.Role, r.Sequence, r.Head, s.now().Unix()); err != nil {
837 return err
838 }
839 return tx.Commit()
840}
841
842// Stream is a role's position: the last committed sequence and head.
843func (s *Store) Stream(ctx context.Context, role string) (int64, string, bool, error) {
844 var seq int64
845 var head string
846 err := s.db.QueryRowContext(ctx, "SELECT sequence,head FROM operator_streams WHERE role=?", role).Scan(&seq, &head)
847 if errors.Is(err, sql.ErrNoRows) {
848 return 0, "", false, nil
849 }
850 return seq, head, err == nil, err
851}
852
853// SetStream adopts Home's position (resync through inspect).
854func (s *Store) SetStream(ctx context.Context, role string, seq int64, head string) error {
855 _, err := s.db.ExecContext(ctx, "INSERT INTO operator_streams(role,sequence,head,updated_at) VALUES(?,?,?,?) ON CONFLICT(role) DO UPDATE SET sequence=excluded.sequence,head=excluded.head,updated_at=excluded.updated_at", role, seq, head, s.now().Unix())
856 return err
857}
858
859// ---- audit ----
860
861// AuditEntry is one audit row.
862type AuditEntry struct {
863 At time.Time
864 RunID int64
865 Label, App, Event, Detail string
866}
867
868func (s *Store) Audit(ctx context.Context, runID int64, label, app, event, detail string) {
869 _, _ = s.db.ExecContext(ctx, "INSERT INTO audit(at,run_id,label,app,event,detail) VALUES(?,?,?,?,?,?)", s.now().Unix(), runID, label, app, event, detail)
870}
871
872func (s *Store) AuditLog(ctx context.Context, label string, limit int) ([]AuditEntry, error) {
873 rows, err := s.db.QueryContext(ctx, "SELECT at,run_id,label,app,event,detail FROM audit WHERE label=? ORDER BY id DESC LIMIT ?", label, limit)
874 if err != nil {
875 return nil, err
876 }
877 defer rows.Close()
878 var out []AuditEntry
879 for rows.Next() {
880 var e AuditEntry
881 var at int64
882 if err := rows.Scan(&at, &e.RunID, &e.Label, &e.App, &e.Event, &e.Detail); err != nil {
883 return nil, err
884 }
885 e.At = time.Unix(at, 0)
886 out = append(out, e)
887 }
888 return out, rows.Err()
889}
890
891// ---- lock ----
892
893// Lock takes the one-run-at-a-time lock. A lock older than stale is
894// taken over: its holder crashed (a run resumes by probing, so taking
895// over a dead holder's run is safe).
896func (s *Store) Lock(ctx context.Context, runID int64, stale time.Duration) error {
897 now := s.now().Unix()
898 res, err := s.db.ExecContext(ctx, "INSERT INTO run_lock(singleton,run_id,acquired_at) VALUES(1,?,?) ON CONFLICT(singleton) DO UPDATE SET run_id=excluded.run_id,acquired_at=excluded.acquired_at WHERE run_lock.acquired_at<?", runID, now, now-int64(stale.Seconds()))
899 if err != nil {
900 return err
901 }
902 if n, _ := res.RowsAffected(); n == 0 {
903 return ErrBusy
904 }
905 return nil
906}
907
908func (s *Store) Unlock(ctx context.Context, runID int64) {
909 _, _ = s.db.ExecContext(context.WithoutCancel(ctx), "DELETE FROM run_lock WHERE run_id=?", runID)
910}
911
912// ---- the §8 guard ----
913
914type deprovisionKey struct{}
915type proposalKey struct{}
916
917// WithDeprovision marks ctx as inside retire-apps run id: the only
918// context in which the console client may send a DELETE.
919func WithDeprovision(ctx context.Context, runID int64) context.Context {
920 return context.WithValue(ctx, deprovisionKey{}, runID)
921}
922
923// proposal is a team not yet recorded, whose hosts and environment a
924// preflight may READ (never write): checking a label must not burn it.
925type proposal struct {
926 label, env string
927 apps []string
928}
929
930func withProposal(ctx context.Context, label, env string, apps []string) context.Context {
931 return context.WithValue(ctx, proposalKey{}, proposal{label, env, apps})
932}
933
934// Guard implements console.Guard from Alta's records.
935type Guard struct {
936 Store *Store
937 Account string
938}
939
940func (g Guard) proposed(ctx context.Context, app string) (proposal, bool) {
941 p, ok := ctx.Value(proposalKey{}).(proposal)
942 if !ok {
943 return proposal{}, false
944 }
945 for _, a := range p.apps {
946 if a == app {
947 return p, true
948 }
949 }
950 return proposal{}, false
951}
952
953// Environment admits env for app only if Alta's records own it (or, for
954// a read, a preflight proposes it).
955func (g Guard) Environment(ctx context.Context, app, env string, write bool) error {
956 if env == "" {
957 return errors.New("empty environment")
958 }
959 if p, ok := g.proposed(ctx, app); ok && !write && p.env == env {
960 return nil
961 }
962 var n int
963 if err := g.Store.db.QueryRowContext(ctx, "SELECT count(*) FROM environments WHERE app=? AND environment=?", app, env).Scan(&n); err != nil {
964 return err
965 }
966 if n == 0 {
967 return errors.New("environment not Alta's")
968 }
969 return nil
970}
971
972// Host admits only <label>-<app>.<account>.oncarlos.com and
973// <label>.<app>.oficina.works for a label Alta holds with that app.
974func (g Guard) Host(ctx context.Context, app, host string, write bool) error {
975 label := ""
976 switch {
977 case strings.HasSuffix(host, "-"+app+"."+g.Account+".oncarlos.com"):
978 label = strings.TrimSuffix(host, "-"+app+"."+g.Account+".oncarlos.com")
979 case strings.HasSuffix(host, "."+app+"."+PublicDomain):
980 label = strings.TrimSuffix(host, "."+app+"."+PublicDomain)
981 default:
982 return errors.New("host outside Alta's shapes")
983 }
984 if !LabelPattern.MatchString(label) {
985 return errors.New("host label outside Alta's shapes")
986 }
987 if p, ok := g.proposed(ctx, app); ok && !write && p.label == label {
988 return nil
989 }
990 var n int
991 if err := g.Store.db.QueryRowContext(ctx, "SELECT count(*) FROM team_apps WHERE label=? AND app=?", label, app).Scan(&n); err != nil {
992 return err
993 }
994 if n == 0 {
995 return errors.New("host for a team or app Alta does not hold")
996 }
997 return nil
998}
999
1000// Delete admits a DELETE only inside a live retire-apps run naming app.
1001func (g Guard) Delete(ctx context.Context, app, host string) error {
1002 id, ok := ctx.Value(deprovisionKey{}).(int64)
1003 if !ok {
1004 return errors.New("delete outside a deprovision run")
1005 }
1006 r, err := g.Store.Run(ctx, id)
1007 if err != nil {
1008 return err
1009 }
1010 if r.Kind != "retire-apps" || (r.State != "running" && r.State != "parked" && r.State != "planned") {
1011 return errors.New("delete outside a live deprovision run")
1012 }
1013 for _, a := range r.Apps {
1014 if a == app {
1015 return nil
1016 }
1017 }
1018 return errors.New("delete for an app the deprovision run does not name")
1019}
1020
1021// ---- sessions' idle clock ----
1022
1023// Seen records a session's activity and reports whether it was idle
1024// longer than idle (then the caller signs it out).
1025func (s *Store) Seen(ctx context.Context, tokenHash string, idle time.Duration) (expired bool, err error) {
1026 now := s.now().Unix()
1027 var last int64
1028 err = s.db.QueryRowContext(ctx, "SELECT seen_at FROM session_seen WHERE token_hash=?", tokenHash).Scan(&last)
1029 if err == nil && now-last > int64(idle.Seconds()) {
1030 _, err = s.db.ExecContext(ctx, "DELETE FROM session_seen WHERE token_hash=?", tokenHash)
1031 return true, err
1032 }
1033 if err != nil && !errors.Is(err, sql.ErrNoRows) {
1034 return false, err
1035 }
1036 _, err = s.db.ExecContext(ctx, "INSERT INTO session_seen(token_hash,seen_at) VALUES(?,?) ON CONFLICT(token_hash) DO UPDATE SET seen_at=excluded.seen_at", tokenHash, now)
1037 return false, err
1038}
1039
1040// SweepSeen drops idle-clock rows older than a session can live.
1041func (s *Store) SweepSeen(ctx context.Context, older time.Duration) {
1042 _, _ = s.db.ExecContext(ctx, "DELETE FROM session_seen WHERE seen_at<?", s.now().Add(-older).Unix())
1043}
1044