Adoption state: sealed journal
runs.adoption and CreateAdoption/NewAdoptionRun in provision (no environments rows for the oficina team). adopt.Store journals Home preflights, insert-only baselines, writes, rollbacks, after snapshots, witnesses and live checks, sealed under alta/adopt/<table>/<key>, with secure_delete on; LiveGate is the one live-check rule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+1,154
−3
adopt/migrations/0001_adopt.sql+62 −0adopt/store.go+346 −0adopt/store_test.go+438 −0provision/migrations/0003_adoption.sql+5 −0provision/store.go+104 −3provision/store_adopt_test.go+199 −0
diff --git a/adopt/migrations/0001_adopt.sql b/adopt/migrations/0001_adopt.sql| new file mode 100644 |
| index 0000000..e5ca39a |
| --- /dev/null |
| +++ b/adopt/migrations/0001_adopt.sql |
| @@ -0,0 +1,62 @@ |
| +-- The adoption journal (existing-team adoption, CARLOS half). Every |
| +-- payload is AEAD under ALTA_DEK, sealed under the purpose |
| +-- alta/adopt/<table>/<key>, so a row copied to another key does not open. |
| +-- Payloads carry vd1: digests, cv1: versions, the two agent keys' values |
| +-- and Home's stream heads: none of them is ever stored in the clear. |
| + |
| +-- Home's state before a phase: 'pre-initialize' or 'pre-plan-a'. |
| +CREATE TABLE adopt_home_preflights ( |
| + phase TEXT PRIMARY KEY CHECK (phase IN ('pre-initialize', 'pre-plan-a')), |
| + sealed BLOB NOT NULL |
| +) STRICT; |
| + |
| +-- One baseline per app, captured once and never rebaselined. |
| +CREATE TABLE adopt_baselines ( |
| + app TEXT PRIMARY KEY, |
| + sealed BLOB NOT NULL |
| +) STRICT; |
| +-- INSERT OR REPLACE deletes without firing a delete trigger, so a second |
| +-- insert for an app is refused before conflict resolution can run. |
| +CREATE TRIGGER adopt_baselines_once BEFORE INSERT ON adopt_baselines |
| +WHEN EXISTS (SELECT 1 FROM adopt_baselines WHERE app = NEW.app) |
| +BEGIN |
| + SELECT RAISE(ABORT, 'adopt: a baseline is captured once'); |
| +END; |
| +CREATE TRIGGER adopt_baselines_no_update BEFORE UPDATE ON adopt_baselines |
| +BEGIN |
| + SELECT RAISE(ABORT, 'adopt: a baseline is never rebaselined'); |
| +END; |
| +CREATE TRIGGER adopt_baselines_no_delete BEFORE DELETE ON adopt_baselines |
| +BEGIN |
| + SELECT RAISE(ABORT, 'adopt: a baseline is never deleted'); |
| +END; |
| + |
| +-- Per app: the write (sent, landed, stopped), its rollback, the after |
| +-- snapshot and Paul's witness. Each is the latest state for its app. |
| +CREATE TABLE adopt_writes ( |
| + app TEXT PRIMARY KEY, |
| + sealed BLOB NOT NULL |
| +) STRICT; |
| + |
| +CREATE TABLE adopt_rollbacks ( |
| + app TEXT PRIMARY KEY, |
| + sealed BLOB NOT NULL |
| +) STRICT; |
| + |
| +CREATE TABLE adopt_afters ( |
| + app TEXT PRIMARY KEY, |
| + sealed BLOB NOT NULL |
| +) STRICT; |
| + |
| +CREATE TABLE adopt_witnesses ( |
| + app TEXT PRIMARY KEY, |
| + sealed BLOB NOT NULL |
| +) STRICT; |
| + |
| +-- The live checks' outcomes, every one kept: a check that ever failed |
| +-- keeps Plan C refused. Names and outcomes are fixed codes. |
| +CREATE TABLE adopt_checks ( |
| + id INTEGER PRIMARY KEY, |
| + name TEXT NOT NULL, |
| + outcome TEXT NOT NULL CHECK (outcome IN ('passed', 'failed')) |
| +) STRICT; |
diff --git a/adopt/store.go b/adopt/store.go| new file mode 100644 |
| index 0000000..fc5a8c1 |
| --- /dev/null |
| +++ b/adopt/store.go |
| @@ -0,0 +1,346 @@ |
| +package adopt |
| + |
| +// The adoption journal: what the CARLOS half observed, wrote and was |
| +// told, kept in Alta's database beside the engine's own state. Every |
| +// payload is sealed under ALTA_DEK with the purpose |
| +// alta/adopt/<table>/<key> before it is stored, so no vd1: digest, cv1: |
| +// version, agent key value or Home head is ever on disk in the clear. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "embed" |
| + "encoding/json" |
| + "errors" |
| + "slices" |
| + |
| + "amadan.net/oficina/alta/provision" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrationFS embed.FS |
| + |
| +// Schema is the journal's migration set. The command applies it beside |
| +// Alta's own: provision.NewStore(ctx, db, dek, now, adopt.Schema). |
| +var Schema = migrate.MustFromFS(migrationFS, "adopt") |
| + |
| +var ( |
| + // ErrSchemaMissing is a database without the journal's migrations. |
| + // NewStore applies nothing itself. |
| + ErrSchemaMissing = errors.New("adopt: the adoption journal's schema is not applied") |
| + // ErrBaselineExists is a second baseline for an app: a baseline is |
| + // captured once and never rebaselined. |
| + ErrBaselineExists = errors.New("adopt: the app already has its baseline") |
| + // ErrLiveChecksMissing is the live-check gate closed: a check |
| + // RequiredLiveChecks names has not passed, or one has failed. |
| + ErrLiveChecksMissing = errors.New("live-checks-missing") |
| +) |
| + |
| +// Home preflight phases. |
| +const ( |
| + PhasePreInitialize = "pre-initialize" |
| + PhasePrePlanA = "pre-plan-a" |
| +) |
| + |
| +// CanaryApp is the app Plan B activates before the live checks run. |
| +const CanaryApp = "calendar" |
| + |
| +// Store is the adoption journal over Alta's provision store. |
| +type Store struct { |
| + ps *provision.Store |
| + db *sql.DB |
| +} |
| + |
| +// NewStore opens the journal over ps. It refuses with ErrSchemaMissing |
| +// unless every one of Schema's migrations is in the database's ledger. |
| +func NewStore(ps *provision.Store) (*Store, error) { |
| + if ps == nil { |
| + return nil, errors.New("adopt: no provision store") |
| + } |
| + db := ps.DB() |
| + ctx := context.Background() |
| + var n int |
| + if err := db.QueryRowContext(ctx, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='rastrillo_migrations'").Scan(&n); err != nil { |
| + return nil, err |
| + } |
| + if n == 0 { |
| + return nil, ErrSchemaMissing |
| + } |
| + for _, m := range Schema.All() { |
| + if err := db.QueryRowContext(ctx, "SELECT count(*) FROM rastrillo_migrations WHERE id=?", m.ID).Scan(&n); err != nil { |
| + return nil, err |
| + } |
| + if n == 0 { |
| + return nil, ErrSchemaMissing |
| + } |
| + } |
| + return &Store{ps: ps, db: db}, nil |
| +} |
| + |
| +// Tables, and so the middle of each payload's purpose. |
| +const ( |
| + tHomePreflights = "adopt_home_preflights" |
| + tBaselines = "adopt_baselines" |
| + tWrites = "adopt_writes" |
| + tRollbacks = "adopt_rollbacks" |
| + tAfters = "adopt_afters" |
| + tWitnesses = "adopt_witnesses" |
| +) |
| + |
| +func purpose(table, key string) string { return "alta/adopt/" + table + "/" + key } |
| + |
| +func knownApp(app string) error { |
| + if _, ok := provision.AppBySlug(app); !ok { |
| + return errors.New("adopt: not an Oficina app") |
| + } |
| + return nil |
| +} |
| + |
| +// exec runs one statement on a connection with secure_delete on, however |
| +// the database was opened: a replaced record is overwritten, not left in |
| +// a free page. |
| +func (s *Store) exec(ctx context.Context, q string, args ...any) (sql.Result, error) { |
| + conn, err := s.db.Conn(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer conn.Close() |
| + if _, err := conn.ExecContext(ctx, "PRAGMA secure_delete=ON"); err != nil { |
| + return nil, err |
| + } |
| + return conn.ExecContext(ctx, q, args...) |
| +} |
| + |
| +func (s *Store) sealed(table, key string, v any) ([]byte, error) { |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return s.ps.SealAdoption(purpose(table, key), b) |
| +} |
| + |
| +// put replaces table's row for key with v, sealed. |
| +func (s *Store) put(ctx context.Context, table, col, key string, v any) error { |
| + sealed, err := s.sealed(table, key, v) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = s.exec(ctx, "INSERT INTO "+table+"("+col+",sealed) VALUES(?,?) ON CONFLICT("+col+") DO UPDATE SET sealed=excluded.sealed", key, sealed) |
| + return err |
| +} |
| + |
| +// get opens table's row for key into v; false when there is none. |
| +func (s *Store) get(ctx context.Context, table, col, key string, v any) (bool, error) { |
| + var sealed []byte |
| + err := s.db.QueryRowContext(ctx, "SELECT sealed FROM "+table+" WHERE "+col+"=?", key).Scan(&sealed) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + b, err := s.ps.OpenAdoption(purpose(table, key), sealed) |
| + if err != nil { |
| + return false, errors.New("adopt: a journal row does not open") |
| + } |
| + if err := json.Unmarshal(b, v); err != nil { |
| + return false, errors.New("adopt: a journal row does not decode") |
| + } |
| + return true, nil |
| +} |
| + |
| +func homePhase(phase string) error { |
| + if phase != PhasePreInitialize && phase != PhasePrePlanA { |
| + return errors.New("adopt: not a Home preflight phase") |
| + } |
| + return nil |
| +} |
| + |
| +// SaveHomePreflight records Home's state before r.Phase, replacing an |
| +// earlier preflight for the same phase. |
| +func (s *Store) SaveHomePreflight(ctx context.Context, r HomePreflight) error { |
| + if err := homePhase(r.Phase); err != nil { |
| + return err |
| + } |
| + return s.put(ctx, tHomePreflights, "phase", r.Phase, r) |
| +} |
| + |
| +// HomePreflight reads the preflight recorded before phase. |
| +func (s *Store) HomePreflight(ctx context.Context, phase string) (HomePreflight, bool, error) { |
| + if err := homePhase(phase); err != nil { |
| + return HomePreflight{}, false, err |
| + } |
| + var r HomePreflight |
| + ok, err := s.get(ctx, tHomePreflights, "phase", phase, &r) |
| + return r, ok, err |
| +} |
| + |
| +// SaveBaseline records app's baseline. It is captured once: a second |
| +// one is refused with ErrBaselineExists, and the table refuses any |
| +// update, delete or replacement of a stored one. |
| +func (s *Store) SaveBaseline(ctx context.Context, app string, snap Snapshot) error { |
| + if err := knownApp(app); err != nil { |
| + return err |
| + } |
| + sealed, err := s.sealed(tBaselines, app, snap) |
| + if err != nil { |
| + return err |
| + } |
| + conn, err := s.db.Conn(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer conn.Close() |
| + if _, err := conn.ExecContext(ctx, "PRAGMA secure_delete=ON"); err != nil { |
| + return err |
| + } |
| + tx, err := conn.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var n int |
| + if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM adopt_baselines WHERE app=?", app).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + return ErrBaselineExists |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO adopt_baselines(app,sealed) VALUES(?,?)", app, sealed); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// Baseline reads app's baseline. |
| +func (s *Store) Baseline(ctx context.Context, app string) (Snapshot, bool, error) { |
| + var snap Snapshot |
| + ok, err := s.get(ctx, tBaselines, "app", app, &snap) |
| + return snap, ok, err |
| +} |
| + |
| +var ( |
| + writeStates = []string{"sent", "landed", "stopped"} |
| + rollbackStates = []string{"sent", "unset", "restarted", "stopped"} |
| +) |
| + |
| +// SaveWrite records the latest state of r.App's write. |
| +func (s *Store) SaveWrite(ctx context.Context, r WriteRecord) error { |
| + if err := knownApp(r.App); err != nil { |
| + return err |
| + } |
| + if !slices.Contains(writeStates, r.State) { |
| + return errors.New("adopt: not a write state") |
| + } |
| + return s.put(ctx, tWrites, "app", r.App, r) |
| +} |
| + |
| +// Write reads app's write record. |
| +func (s *Store) Write(ctx context.Context, app string) (WriteRecord, bool, error) { |
| + var r WriteRecord |
| + ok, err := s.get(ctx, tWrites, "app", app, &r) |
| + return r, ok, err |
| +} |
| + |
| +// SaveRollback records the latest state of r.App's rollback. |
| +func (s *Store) SaveRollback(ctx context.Context, r RollbackRecord) error { |
| + if err := knownApp(r.App); err != nil { |
| + return err |
| + } |
| + if !slices.Contains(rollbackStates, r.State) { |
| + return errors.New("adopt: not a rollback state") |
| + } |
| + return s.put(ctx, tRollbacks, "app", r.App, r) |
| +} |
| + |
| +// Rollback reads app's rollback record. |
| +func (s *Store) Rollback(ctx context.Context, app string) (RollbackRecord, bool, error) { |
| + var r RollbackRecord |
| + ok, err := s.get(ctx, tRollbacks, "app", app, &r) |
| + return r, ok, err |
| +} |
| + |
| +// SaveAfter records app's after snapshot, replacing an earlier one. |
| +func (s *Store) SaveAfter(ctx context.Context, app string, snap Snapshot) error { |
| + if err := knownApp(app); err != nil { |
| + return err |
| + } |
| + return s.put(ctx, tAfters, "app", app, snap) |
| +} |
| + |
| +// After reads app's after snapshot. |
| +func (s *Store) After(ctx context.Context, app string) (Snapshot, bool, error) { |
| + var snap Snapshot |
| + ok, err := s.get(ctx, tAfters, "app", app, &snap) |
| + return snap, ok, err |
| +} |
| + |
| +// SaveWitness records Paul's witness for w.App, replacing a voided one. |
| +func (s *Store) SaveWitness(ctx context.Context, w Witness) error { |
| + if err := knownApp(w.App); err != nil { |
| + return err |
| + } |
| + return s.put(ctx, tWitnesses, "app", w.App, w) |
| +} |
| + |
| +// Witness reads app's witness. |
| +func (s *Store) Witness(ctx context.Context, app string) (Witness, bool, error) { |
| + var w Witness |
| + ok, err := s.get(ctx, tWitnesses, "app", app, &w) |
| + return w, ok, err |
| +} |
| + |
| +// SaveCheck appends one live check's outcome, "passed" or "failed". |
| +// Every outcome is kept: a failure is never overwritten by a later pass. |
| +func (s *Store) SaveCheck(ctx context.Context, name, outcome string) error { |
| + if !slices.Contains(RequiredLiveChecks, name) { |
| + return errors.New("adopt: not a live check") |
| + } |
| + if outcome != "passed" && outcome != "failed" { |
| + return errors.New("adopt: not a live check outcome") |
| + } |
| + _, err := s.exec(ctx, "INSERT INTO adopt_checks(name,outcome) VALUES(?,?)", name, outcome) |
| + return err |
| +} |
| + |
| +// LiveGate is the live-check rule, the one implementation of it. The |
| +// canary app activates before the checks run, so it is never gated. |
| +// Every other app is admitted only when each of RequiredLiveChecks has |
| +// passed and no check has ever failed; otherwise ErrLiveChecksMissing. |
| +func (s *Store) LiveGate(ctx context.Context, app string) error { |
| + if app == CanaryApp { |
| + return nil |
| + } |
| + rows, err := s.db.QueryContext(ctx, "SELECT name,outcome FROM adopt_checks") |
| + if err != nil { |
| + return err |
| + } |
| + defer rows.Close() |
| + passed := map[string]bool{} |
| + failed := false |
| + for rows.Next() { |
| + var name, outcome string |
| + if err := rows.Scan(&name, &outcome); err != nil { |
| + return err |
| + } |
| + switch outcome { |
| + case "passed": |
| + passed[name] = true |
| + default: |
| + failed = true |
| + } |
| + } |
| + if err := rows.Err(); err != nil { |
| + return err |
| + } |
| + if failed || knownApp(app) != nil { |
| + return ErrLiveChecksMissing |
| + } |
| + for _, name := range RequiredLiveChecks { |
| + if !passed[name] { |
| + return ErrLiveChecksMissing |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/adopt/store_test.go b/adopt/store_test.go| new file mode 100644 |
| index 0000000..846f468 |
| --- /dev/null |
| +++ b/adopt/store_test.go |
| @@ -0,0 +1,438 @@ |
| +package adopt |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/carlosop" |
| + "amadan.net/oficina/alta/provision" |
| +) |
| + |
| +const ( |
| + valueCanary = "plain-value-canary-QX7" |
| + ownerCanary = "adopt-owner-canary@lagged.test" |
| + digestA = "vd1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" |
| + digestB = "vd1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" |
| + versionA = "cv1:1111111111111111111111111111" |
| + versionB = "cv1:2222222222222222222222222222" |
| +) |
| + |
| +var at = time.Date(2026, 11, 16, 9, 30, 0, 0, time.UTC) |
| + |
| +func clock() time.Time { return at } |
| + |
| +// journal opens a provision store at path with adopt's schema applied, |
| +// as the command does, and the adopt store over it. |
| +func journal(t *testing.T, path string) (*provision.Store, *Store) { |
| + t.Helper() |
| + db, err := provision.OpenDB(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + ps, err := provision.NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), clock, Schema) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s, err := NewStore(ps) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return ps, s |
| +} |
| + |
| +func newJournal(t *testing.T) *Store { |
| + t.Helper() |
| + _, s := journal(t, filepath.Join(t.TempDir(), "alta.db")) |
| + return s |
| +} |
| + |
| +func snapshot(app, version, digest string) Snapshot { |
| + id, eff := inst() |
| + id.App = app |
| + return Snapshot{ |
| + Identity: IdentityOf(id, eff), |
| + WriteLayer: "env1", |
| + Layer: carlosop.Layer{Bundle: "env1", Version: version, Vars: []carlosop.Var{ |
| + {Key: "DOCS_TITLE", Kind: "env", Value: valueCanary, Digest: digest}, |
| + {Key: "DOCS_SECRET", Kind: "secret", Digest: digestB}, |
| + }}, |
| + Layers: map[string]string{"default": versionB, "environment": version}, |
| + Vars: []carlosop.EffectiveVar{ |
| + {Key: "DOCS_TITLE", Kind: "env", Digest: digest, From: "environment", Shadows: []string{"default"}}, |
| + {Key: "DOCS_SECRET", Kind: "secret", Digest: digestB, From: "environment"}, |
| + }, |
| + HomeIssuer: "https://id.oficina.works", HomeConsumer: app, |
| + Delivery: Delivery{Version: "v1.2.3\n", Header: "v1.2.3", Health: 200, Ops: OpsApp401, At: at}, |
| + At: at, |
| + } |
| +} |
| + |
| +func receipt() *carlosop.Receipt { |
| + return &carlosop.Receipt{ |
| + Bundle: "env1", VersionBefore: versionA, VersionAfter: versionB, Changed: true, |
| + Set: []string{"DOCS_AGENT_ISSUER", "DOCS_AGENT_TEAM"}, |
| + Digests: map[string]string{"DOCS_AGENT_ISSUER": digestA, "DOCS_AGENT_TEAM": digestB}, |
| + Others: map[string]struct{ Before, After string }{"default": {versionA, versionA}}, |
| + } |
| +} |
| + |
| +func TestAdoptStoreRefusesUnmigratedDB(t *testing.T) { |
| + db, err := provision.OpenDB(filepath.Join(t.TempDir(), "alta.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + ps, err := provision.NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), clock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := NewStore(ps); !errors.Is(err, ErrSchemaMissing) { |
| + t.Fatalf("unmigrated: %v", err) |
| + } |
| + if _, err := NewStore(nil); err == nil { |
| + t.Fatal("nil store accepted") |
| + } |
| + // NewStore applies nothing itself. |
| + var n int |
| + if err := db.QueryRow("SELECT count(*) FROM sqlite_master WHERE name LIKE 'adopt_%'").Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("adopt tables %d, %v", n, err) |
| + } |
| + // A ledger missing one of adopt's migrations is refused too. |
| + path := filepath.Join(t.TempDir(), "alta.db") |
| + ps2, _ := journal(t, path) |
| + if _, err := ps2.DB().Exec("DELETE FROM rastrillo_migrations WHERE id LIKE 'adopt/%'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := NewStore(ps2); !errors.Is(err, ErrSchemaMissing) { |
| + t.Fatalf("ledger without adopt: %v", err) |
| + } |
| +} |
| + |
| +func TestBaselineIsInsertOnly(t *testing.T) { |
| + ctx := context.Background() |
| + s := newJournal(t) |
| + if _, ok, err := s.Baseline(ctx, "docs"); err != nil || ok { |
| + t.Fatalf("empty baseline %v %v", ok, err) |
| + } |
| + first := snapshot("docs", versionA, digestA) |
| + if err := s.SaveBaseline(ctx, "docs", first); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.SaveBaseline(ctx, "docs", snapshot("docs", versionB, digestB)); !errors.Is(err, ErrBaselineExists) { |
| + t.Fatalf("rebaseline: %v", err) |
| + } |
| + got, ok, err := s.Baseline(ctx, "docs") |
| + if err != nil || !ok || !reflect.DeepEqual(got, first) { |
| + t.Fatalf("baseline after refusal: %v %v\n%+v", ok, err, got) |
| + } |
| + // The table itself refuses: no code path rewrites a baseline. |
| + if _, err := s.db.Exec("UPDATE adopt_baselines SET sealed=x'00' WHERE app='docs'"); err == nil { |
| + t.Fatal("baseline updated") |
| + } |
| + if _, err := s.db.Exec("DELETE FROM adopt_baselines WHERE app='docs'"); err == nil { |
| + t.Fatal("baseline deleted") |
| + } |
| + for _, q := range []string{ |
| + "INSERT OR REPLACE INTO adopt_baselines(app,sealed) VALUES('docs',x'00')", |
| + "INSERT INTO adopt_baselines(app,sealed) VALUES('docs',x'00') ON CONFLICT(app) DO UPDATE SET sealed=excluded.sealed", |
| + } { |
| + if _, err := s.db.Exec(q); err == nil { |
| + t.Fatalf("baseline rewritten by %s", q) |
| + } |
| + } |
| + if got, ok, err := s.Baseline(ctx, "docs"); err != nil || !ok || !reflect.DeepEqual(got, first) { |
| + t.Fatalf("baseline after raw rewrites: %v %v", ok, err) |
| + } |
| + if err := s.SaveBaseline(ctx, "mail", first); err == nil { |
| + t.Fatal("baseline for an app Alta does not know") |
| + } |
| +} |
| + |
| +func TestHomePreflightByPhase(t *testing.T) { |
| + ctx := context.Background() |
| + s := newJournal(t) |
| + gen := "gen-1" |
| + pre := HomePreflight{Phase: "pre-initialize", CredentialSeq: 4, DirectorySeq: 0, CredentialHead: "head-a", Counts: map[string]int64{"teams": 0}, AttestedAt: at} |
| + planA := HomePreflight{Phase: "pre-plan-a", CredentialSeq: 4, DirectorySeq: 1, CredentialHead: "head-a", Generation: &gen, ProposedID: 12, ProposedSQID: "q8s", Counts: map[string]int64{"teams": 3}, AttestedAt: at} |
| + if _, ok, err := s.HomePreflight(ctx, "pre-initialize"); err != nil || ok { |
| + t.Fatalf("empty %v %v", ok, err) |
| + } |
| + if err := s.SaveHomePreflight(ctx, pre); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.SaveHomePreflight(ctx, planA); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, want := range []HomePreflight{pre, planA} { |
| + got, ok, err := s.HomePreflight(ctx, want.Phase) |
| + if err != nil || !ok || !reflect.DeepEqual(got, want) { |
| + t.Fatalf("%s: %v %v\n%+v", want.Phase, ok, err, got) |
| + } |
| + } |
| + // A repeated preflight replaces its phase's record, and only it. |
| + again := planA |
| + again.ProposedID, again.ProposedSQID = 13, "q9t" |
| + if err := s.SaveHomePreflight(ctx, again); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _, _ := s.HomePreflight(ctx, "pre-plan-a"); got.ProposedID != 13 { |
| + t.Fatalf("plan-a %+v", got) |
| + } |
| + if got, _, _ := s.HomePreflight(ctx, "pre-initialize"); !reflect.DeepEqual(got, pre) { |
| + t.Fatalf("initialize %+v", got) |
| + } |
| + for _, phase := range []string{"", "plan-b", "pre-plan-b"} { |
| + if err := s.SaveHomePreflight(ctx, HomePreflight{Phase: phase}); err == nil { |
| + t.Fatalf("saved phase %q", phase) |
| + } |
| + if _, _, err := s.HomePreflight(ctx, phase); err == nil { |
| + t.Fatalf("read phase %q", phase) |
| + } |
| + } |
| +} |
| + |
| +func TestJournalRoundTrips(t *testing.T) { |
| + ctx := context.Background() |
| + s := newJournal(t) |
| + w := WriteRecord{App: "docs", State: "sent", Sent: map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": valueCanary}} |
| + if err := s.SaveWrite(ctx, w); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.State, w.Receipt = "landed", receipt() |
| + if err := s.SaveWrite(ctx, w); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ok, err := s.Write(ctx, "docs"); err != nil || !ok || !reflect.DeepEqual(got, w) { |
| + t.Fatalf("write %v %v\n%+v", ok, err, got) |
| + } |
| + r := RollbackRecord{App: "docs", State: "unset", Receipt: receipt(), Code: "witness-refused"} |
| + if err := s.SaveRollback(ctx, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ok, err := s.Rollback(ctx, "docs"); err != nil || !ok || !reflect.DeepEqual(got, r) { |
| + t.Fatalf("rollback %v %v\n%+v", ok, err, got) |
| + } |
| + after := snapshot("docs", versionB, digestB) |
| + if err := s.SaveAfter(ctx, "docs", after); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ok, err := s.After(ctx, "docs"); err != nil || !ok || !reflect.DeepEqual(got, after) { |
| + t.Fatalf("after %v %v\n%+v", ok, err, got) |
| + } |
| + wit := Witness{App: "docs", Typed: "docs", Identity: after.Identity, Delivery: after.Delivery, AfterVersion: versionB, At: at} |
| + if err := s.SaveWitness(ctx, wit); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, ok, err := s.Witness(ctx, "docs"); err != nil || !ok || !reflect.DeepEqual(got, wit) { |
| + t.Fatalf("witness %v %v\n%+v", ok, err, got) |
| + } |
| + for name, f := range map[string]func() (bool, error){ |
| + "write": func() (bool, error) { _, ok, err := s.Write(ctx, "sheets"); return ok, err }, |
| + "rollback": func() (bool, error) { _, ok, err := s.Rollback(ctx, "sheets"); return ok, err }, |
| + "after": func() (bool, error) { _, ok, err := s.After(ctx, "sheets"); return ok, err }, |
| + "witness": func() (bool, error) { _, ok, err := s.Witness(ctx, "sheets"); return ok, err }, |
| + } { |
| + if ok, err := f(); ok || err != nil { |
| + t.Fatalf("%s for an app with none: %v %v", name, ok, err) |
| + } |
| + } |
| +} |
| + |
| +func TestJournalRefusesUnknownAppsAndStates(t *testing.T) { |
| + ctx := context.Background() |
| + s := newJournal(t) |
| + for _, st := range []string{"", "landing", "unset"} { |
| + if err := s.SaveWrite(ctx, WriteRecord{App: "docs", State: st}); err == nil { |
| + t.Fatalf("write state %q", st) |
| + } |
| + } |
| + for _, st := range []string{"", "landed", "rolled-back"} { |
| + if err := s.SaveRollback(ctx, RollbackRecord{App: "docs", State: st}); err == nil { |
| + t.Fatalf("rollback state %q", st) |
| + } |
| + } |
| + for _, app := range []string{"", "mail", "Docs"} { |
| + if err := s.SaveWrite(ctx, WriteRecord{App: app, State: "sent"}); err == nil { |
| + t.Fatalf("write for %q", app) |
| + } |
| + if err := s.SaveRollback(ctx, RollbackRecord{App: app, State: "sent"}); err == nil { |
| + t.Fatalf("rollback for %q", app) |
| + } |
| + if err := s.SaveAfter(ctx, app, Snapshot{}); err == nil { |
| + t.Fatalf("after for %q", app) |
| + } |
| + if err := s.SaveWitness(ctx, Witness{App: app}); err == nil { |
| + t.Fatalf("witness for %q", app) |
| + } |
| + } |
| +} |
| + |
| +func TestLiveGateCanaryAndRest(t *testing.T) { |
| + ctx := context.Background() |
| + s := newJournal(t) |
| + if err := s.LiveGate(ctx, "calendar"); err != nil { |
| + t.Fatalf("canary gated: %v", err) |
| + } |
| + rest := []string{"docs", "sheets", "slides", "calls", "memoria"} |
| + gated := func(why string) { |
| + t.Helper() |
| + for _, app := range append(rest, "", "mail") { |
| + err := s.LiveGate(ctx, app) |
| + if !errors.Is(err, ErrLiveChecksMissing) || err.Error() != "live-checks-missing" { |
| + t.Fatalf("%s: %q gate %v", why, app, err) |
| + } |
| + } |
| + } |
| + gated("none recorded") |
| + for _, name := range RequiredLiveChecks[:len(RequiredLiveChecks)-1] { |
| + if err := s.SaveCheck(ctx, name, "passed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + gated("one missing") |
| + last := RequiredLiveChecks[len(RequiredLiveChecks)-1] |
| + if err := s.SaveCheck(ctx, last, "passed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, app := range rest { |
| + if err := s.LiveGate(ctx, app); err != nil { |
| + t.Fatalf("%s gated with every check passed: %v", app, err) |
| + } |
| + } |
| + if err := s.LiveGate(ctx, "calendar"); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A failure stays on the record: passing again later does not open |
| + // the gate. |
| + if err := s.SaveCheck(ctx, "owner-revoked-refused", "failed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + gated("one failed") |
| + if err := s.SaveCheck(ctx, "owner-revoked-refused", "passed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + gated("failed then passed") |
| + if err := s.LiveGate(ctx, "calendar"); err != nil { |
| + t.Fatalf("canary gated by the rest's checks: %v", err) |
| + } |
| + if err := s.SaveCheck(ctx, "made-up", "passed"); err == nil { |
| + t.Fatal("unknown check recorded") |
| + } |
| + for _, outcome := range []string{"", "pass", "skipped"} { |
| + if err := s.SaveCheck(ctx, "member-allowed", outcome); err == nil { |
| + t.Fatalf("outcome %q recorded", outcome) |
| + } |
| + } |
| +} |
| + |
| +// A sealed row opens only under its own table and key. |
| +func TestAdoptRowsBoundToTheirKey(t *testing.T) { |
| + ctx := context.Background() |
| + s := newJournal(t) |
| + if err := s.SaveWrite(ctx, WriteRecord{App: "docs", State: "sent", Sent: map[string]string{"DOCS_AGENT_TEAM": valueCanary}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.db.Exec("INSERT INTO adopt_writes(app,sealed) SELECT 'sheets',sealed FROM adopt_writes WHERE app='docs'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := s.Write(ctx, "sheets"); err == nil { |
| + t.Fatal("a row copied to another app opened") |
| + } |
| + if _, err := s.db.Exec("INSERT INTO adopt_witnesses(app,sealed) SELECT 'docs',sealed FROM adopt_writes WHERE app='docs'"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := s.Witness(ctx, "docs"); err == nil { |
| + t.Fatal("a row copied to another table opened") |
| + } |
| +} |
| + |
| +func TestAdoptRowsAreSealed(t *testing.T) { |
| + ctx := context.Background() |
| + path := filepath.Join(t.TempDir(), "alta.db") |
| + ps, s := journal(t, path) |
| + if err := ps.CreateAdoption(ctx, "Oficina", ownerCanary, provision.Slugs()); err != nil { |
| + t.Fatal(err) |
| + } |
| + before, after := snapshot("docs", versionA, digestA), snapshot("docs", versionB, digestB) |
| + steps := []error{ |
| + s.SaveHomePreflight(ctx, HomePreflight{Phase: "pre-plan-a", CredentialHead: versionA, ProposedSQID: valueCanary, AttestedAt: at}), |
| + s.SaveBaseline(ctx, "docs", before), |
| + s.SaveWrite(ctx, WriteRecord{App: "docs", State: "landed", Sent: map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": valueCanary}, Receipt: receipt()}), |
| + s.SaveRollback(ctx, RollbackRecord{App: "docs", State: "sent", Receipt: receipt()}), |
| + s.SaveAfter(ctx, "docs", after), |
| + s.SaveWitness(ctx, Witness{App: "docs", Typed: "docs", Identity: after.Identity, Delivery: after.Delivery, AfterVersion: versionB, At: at}), |
| + s.SaveCheck(ctx, "member-allowed", "passed"), |
| + } |
| + for i, err := range steps { |
| + if err != nil { |
| + t.Fatalf("save %d: %v", i, err) |
| + } |
| + } |
| + canaries := []string{"vd1:", "cv1:", valueCanary, ownerCanary, Issuer} |
| + scan := func(when string) { |
| + t.Helper() |
| + seen := 0 |
| + for _, f := range []string{path, path + "-wal"} { |
| + raw, err := os.ReadFile(f) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seen += len(raw) |
| + for _, c := range canaries { |
| + if bytes.Contains(raw, []byte(c)) { |
| + t.Fatalf("%s: %s holds %q in the clear", when, filepath.Base(f), c) |
| + } |
| + } |
| + } |
| + if seen == 0 { |
| + t.Fatalf("%s: nothing on disk", when) |
| + } |
| + } |
| + scan("open") |
| + // Closing checkpoints the WAL into the database file. |
| + if err := ps.DB().Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + scan("closed") |
| +} |
| + |
| +// secure_delete is on for every journal write, however the database |
| +// was opened: an overwritten record is not left in a free page. |
| +func TestJournalTurnsSecureDeleteOn(t *testing.T) { |
| + ctx := context.Background() |
| + db, err := sql.Open("sqlite", "file:"+filepath.Join(t.TempDir(), "alta.db")+"?_pragma=secure_delete(0)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + db.SetMaxOpenConns(1) |
| + ps, err := provision.NewStore(ctx, db, bytes.Repeat([]byte{4}, 32), clock, Schema) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s, err := NewStore(ps) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var on int |
| + if err := db.QueryRow("PRAGMA secure_delete").Scan(&on); err != nil || on != 0 { |
| + t.Fatalf("precondition: secure_delete %d, %v", on, err) |
| + } |
| + if err := s.SaveWrite(ctx, WriteRecord{App: "docs", State: "sent"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := db.QueryRow("PRAGMA secure_delete").Scan(&on); err != nil || on != 1 { |
| + t.Fatalf("secure_delete %d, %v", on, err) |
| + } |
| +} |
diff --git a/provision/migrations/0003_adoption.sql b/provision/migrations/0003_adoption.sql| new file mode 100644 |
| index 0000000..481f0b3 |
| --- /dev/null |
| +++ b/provision/migrations/0003_adoption.sql |
| @@ -0,0 +1,5 @@ |
| +-- An adoption run (existing-team-adoption.md): the existing suite's team, |
| +-- label oficina, whose instances Alta never created and whose |
| +-- environments Alta does not own. Marked so the engine never runs an |
| +-- ordinary recipe step for it. |
| +ALTER TABLE runs ADD COLUMN adoption INTEGER NOT NULL DEFAULT 0 CHECK (adoption IN (0, 1)); |
diff --git a/provision/store.go b/provision/store.go| index cd096b0..eeffa49 100644 |
| --- a/provision/store.go |
| +++ b/provision/store.go |
| @@ -74,6 +74,35 @@ func (s *Store) DB() *sql.DB { return s.db } |
| func (s *Store) seal(purpose string, b []byte) ([]byte, error) { return s.sealer.Seal(purpose, b) } |
| func (s *Store) open(purpose string, b []byte) ([]byte, error) { return s.sealer.Open(purpose, b) } |
| +// adoptionPurpose admits only alta/adopt/<table>/<key>: the adoption |
| +// journal seals under ALTA_DEK, and can never open Alta's own rows (the |
| +// owner's address, plans, requests). |
| +func adoptionPurpose(purpose string) error { |
| + rest, ok := strings.CutPrefix(purpose, "alta/adopt/") |
| + table, key, two := strings.Cut(rest, "/") |
| + if !ok || !two || table == "" || key == "" { |
| + return errors.New("provision: not an adoption purpose") |
| + } |
| + return nil |
| +} |
| + |
| +// SealAdoption seals an adoption journal payload under purpose, which |
| +// must be alta/adopt/<table>/<key>. |
| +func (s *Store) SealAdoption(purpose string, b []byte) ([]byte, error) { |
| + if err := adoptionPurpose(purpose); err != nil { |
| + return nil, err |
| + } |
| + return s.seal(purpose, b) |
| +} |
| + |
| +// OpenAdoption opens what SealAdoption sealed under the same purpose. |
| +func (s *Store) OpenAdoption(purpose string, b []byte) ([]byte, error) { |
| + if err := adoptionPurpose(purpose); err != nil { |
| + return nil, err |
| + } |
| + return s.open(purpose, b) |
| +} |
| + |
| // ---- teams ---- |
| // Team is one team as Alta holds it. No address. |
| @@ -136,6 +165,57 @@ func (s *Store) CreateTeam(ctx context.Context, label, name, env string, forked |
| return tx.Commit() |
| } |
| +// adoptionApps refuses an empty, unknown or repeated app list. |
| +func adoptionApps(apps []string) error { |
| + if len(apps) == 0 { |
| + return errors.New("provision: an adoption names at least one app") |
| + } |
| + seen := map[string]bool{} |
| + for _, a := range apps { |
| + if _, ok := AppBySlug(a); !ok || seen[a] { |
| + return errors.New("provision: an adoption names an unknown or repeated app") |
| + } |
| + seen[a] = true |
| + } |
| + return nil |
| +} |
| + |
| +// CreateAdoption records the existing suite's team, label AdoptionLabel: |
| +// its sealed name, the owner's sealed address and its apps, in one |
| +// transaction. It records no environment, and so no environments row: |
| +// the six instances keep the environments they run in, which Alta never |
| +// created, and the §8 guard admits none of them. |
| +func (s *Store) CreateAdoption(ctx context.Context, name, owner string, apps []string) error { |
| + if err := adoptionApps(apps); err != nil { |
| + return err |
| + } |
| + sealed, err := s.seal(namePurpose(AdoptionLabel), []byte(name)) |
| + if err != nil { |
| + return err |
| + } |
| + addr, err := s.seal(ownerPurpose(AdoptionLabel), []byte(owner)) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO teams(label,sealed_name,environment,forked,created_at) VALUES(?,?,'',0,?)", AdoptionLabel, sealed, s.now().Unix()); err != nil { |
| + return fmt.Errorf("provision: label taken: %w", err) |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?)", AdoptionLabel, addr); err != nil { |
| + return err |
| + } |
| + for _, app := range apps { |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", AdoptionLabel, app); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
| + |
| // AddApps records apps joining a team (an add-apps run). A retired app is |
| // refused: its hostnames are dead for good. |
| func (s *Store) AddApps(ctx context.Context, label string, apps []string) error { |
| @@ -323,6 +403,9 @@ type Run struct { |
| // Options is the profile and samples choice the run writes recipes |
| // with (create-team and add-apps; the others record outside). |
| Options RunOptions |
| + // Adoption marks a run for the existing suite's team (label |
| + // AdoptionLabel), whose instances Alta never created. |
| + Adoption bool |
| } |
| // NewRun starts a run. Any unfinished run for the same label is |
| @@ -332,6 +415,24 @@ func (s *Store) NewRun(ctx context.Context, kind, label string, apps []string, o |
| if !ok { |
| return 0, errors.New("provision: unknown profile") |
| } |
| + return s.newRun(ctx, kind, label, apps, opt, false) |
| +} |
| + |
| +// NewAdoptionRun starts a create-team or add-apps run for the existing |
| +// suite's team, label AdoptionLabel, marked as an adoption. It writes no |
| +// recipe, so it records the default options. Like NewRun, it supersedes |
| +// any unfinished run for the label. |
| +func (s *Store) NewAdoptionRun(ctx context.Context, kind string, apps []string) (int64, error) { |
| + if kind != "create-team" && kind != "add-apps" { |
| + return 0, errors.New("provision: an adoption run is create-team or add-apps") |
| + } |
| + if err := adoptionApps(apps); err != nil { |
| + return 0, err |
| + } |
| + return s.newRun(ctx, kind, AdoptionLabel, apps, RunOptions{Profile: ProfileOutside}, true) |
| +} |
| + |
| +func (s *Store) newRun(ctx context.Context, kind, label string, apps []string, opt RunOptions, adoption bool) (int64, error) { |
| now := s.now().Unix() |
| tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| @@ -346,7 +447,7 @@ func (s *Store) NewRun(ctx context.Context, kind, label string, apps []string, o |
| return 0, err |
| } |
| } |
| - res, err := tx.ExecContext(ctx, "INSERT INTO runs(label,kind,apps,state,created_at,updated_at,profile,samples) VALUES(?,?,?,'planned',?,?,?,?)", label, kind, strings.Join(apps, ","), now, now, string(opt.Profile), opt.Samples) |
| + 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) |
| if err != nil { |
| return 0, err |
| } |
| @@ -364,7 +465,7 @@ func scanRun(sc interface{ Scan(...any) error }) (Run, error) { |
| var exp sql.NullInt64 |
| var c, u int64 |
| var profile string |
| - if err := sc.Scan(&r.ID, &r.Label, &r.Kind, &apps, &plan, &exp, &r.State, &r.Code, &c, &u, &profile, &r.Options.Samples); err != nil { |
| + 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 { |
| return Run{}, err |
| } |
| r.Options.Profile = Profile(profile) |
| @@ -375,7 +476,7 @@ func scanRun(sc interface{ Scan(...any) error }) (Run, error) { |
| return r, nil |
| } |
| -const runCols = "id,label,kind,apps,plan_id,plan_expires_at,state,code,created_at,updated_at,profile,samples" |
| +const runCols = "id,label,kind,apps,plan_id,plan_expires_at,state,code,created_at,updated_at,profile,samples,adoption" |
| func (s *Store) Run(ctx context.Context, id int64) (Run, error) { |
| return scanRun(s.db.QueryRowContext(ctx, "SELECT "+runCols+" FROM runs WHERE id=?", id)) |
diff --git a/provision/store_adopt_test.go b/provision/store_adopt_test.go| new file mode 100644 |
| index 0000000..b03f12e |
| --- /dev/null |
| +++ b/provision/store_adopt_test.go |
| @@ -0,0 +1,199 @@ |
| +package provision |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func adoptStore(t *testing.T) *Store { |
| + t.Helper() |
| + db, err := OpenDB(filepath.Join(t.TempDir(), "alta.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + s, err := NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), func() time.Time { return time.Unix(2_000_000_000, 0) }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +// The six existing instances keep the environments they run in, which |
| +// Alta never created: an adoption team owns none, so the §8 guard admits |
| +// no environment write or read for any app under it. |
| +func TestCreateAdoptionWritesNoEnvironmentRows(t *testing.T) { |
| + ctx := context.Background() |
| + s := adoptStore(t) |
| + if err := s.CreateAdoption(ctx, "Oficina", ownerCanary, Slugs()); err != nil { |
| + t.Fatal(err) |
| + } |
| + var n int |
| + if err := s.DB().QueryRowContext(ctx, "SELECT count(*) FROM environments").Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("environments rows %d, %v", n, err) |
| + } |
| + team, err := s.Team(ctx, AdoptionLabel) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if team.Name != "Oficina" || team.Environment != "" || team.Forked || len(team.Apps) != len(Apps) { |
| + t.Fatalf("team %+v", team) |
| + } |
| + for _, a := range Apps { |
| + if team.Apps[a.Slug] != "active" { |
| + t.Fatalf("%s state %q", a.Slug, team.Apps[a.Slug]) |
| + } |
| + } |
| + if owner, ok, err := s.Owner(ctx, AdoptionLabel); err != nil || !ok || owner != ownerCanary { |
| + t.Fatalf("owner %v %v", ok, err) |
| + } |
| + g := Guard{Store: s, Account: account} |
| + for _, a := range Apps { |
| + for _, env := range []string{"", AdoptionLabel, "production", a.Slug} { |
| + for _, write := range []bool{false, true} { |
| + if err := g.Environment(ctx, a.Slug, env, write); err == nil { |
| + t.Fatalf("guard admitted %s environment %q (write %v)", a.Slug, env, write) |
| + } |
| + } |
| + } |
| + } |
| + // The guard is not refusing everything: an ordinary team's own |
| + // environment is still admitted. |
| + if err := s.CreateTeam(ctx, "acme", "Acme", "acme-env", false, ownerCanary, []string{"docs"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := g.Environment(ctx, "docs", "acme-env", true); err != nil { |
| + t.Fatalf("ordinary environment refused: %v", err) |
| + } |
| +} |
| + |
| +func TestCreateAdoptionRefusesBadInput(t *testing.T) { |
| + ctx := context.Background() |
| + for name, apps := range map[string][]string{ |
| + "none": nil, |
| + "unknown": {"docs", "mail"}, |
| + "duplicate": {"docs", "docs"}, |
| + } { |
| + s := adoptStore(t) |
| + if err := s.CreateAdoption(ctx, "Oficina", ownerCanary, apps); err == nil { |
| + t.Fatalf("%s: accepted %v", name, apps) |
| + } |
| + if used, _ := s.LabelUsed(ctx, AdoptionLabel); used { |
| + t.Fatalf("%s: a refused adoption recorded the label", name) |
| + } |
| + } |
| + s := adoptStore(t) |
| + if err := s.CreateAdoption(ctx, "Oficina", ownerCanary, []string{"calendar"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.CreateAdoption(ctx, "Oficina", ownerCanary, []string{"calendar"}); err == nil { |
| + t.Fatal("a second adoption was recorded") |
| + } |
| +} |
| + |
| +func TestAdoptionRunColumnScanned(t *testing.T) { |
| + ctx := context.Background() |
| + s := adoptStore(t) |
| + ordinary, err := s.NewRun(ctx, "create-team", "acme", []string{"docs"}, RunOptions{Profile: ProfileOutside}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id, err := s.NewAdoptionRun(ctx, "create-team", Slugs()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r, err := s.Run(ctx, id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !r.Adoption || r.Label != AdoptionLabel || r.Kind != "create-team" || strings.Join(r.Apps, ",") != strings.Join(Slugs(), ",") || r.State != "planned" { |
| + t.Fatalf("adoption run %+v", r) |
| + } |
| + if r.Options != (RunOptions{Profile: ProfileOutside}) { |
| + t.Fatalf("adoption run options %+v", r.Options) |
| + } |
| + var raw int |
| + if err := s.DB().QueryRowContext(ctx, "SELECT adoption FROM runs WHERE id=?", id).Scan(&raw); err != nil || raw != 1 { |
| + t.Fatalf("adoption column %d, %v", raw, err) |
| + } |
| + if o, err := s.Run(ctx, ordinary); err != nil || o.Adoption { |
| + t.Fatalf("ordinary run %+v, %v", o, err) |
| + } |
| + runs, err := s.Runs(ctx, AdoptionLabel) |
| + if err != nil || len(runs) != 1 || !runs[0].Adoption { |
| + t.Fatalf("runs %+v, %v", runs, err) |
| + } |
| + live, err := s.LiveRuns(ctx) |
| + if err != nil || len(live) != 2 || live[0].Adoption || !live[1].Adoption { |
| + t.Fatalf("live runs %+v, %v", live, err) |
| + } |
| + // One live plan per team holds for adoption runs too. |
| + next, err := s.NewAdoptionRun(ctx, "add-apps", []string{"calendar"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, _ := s.Run(ctx, id); r.State != "superseded" { |
| + t.Fatalf("earlier adoption run %s", r.State) |
| + } |
| + if r, _ := s.Run(ctx, next); !r.Adoption || r.Kind != "add-apps" { |
| + t.Fatalf("add-apps run %+v", r) |
| + } |
| +} |
| + |
| +func TestNewAdoptionRunRefusesOtherKindsAndApps(t *testing.T) { |
| + ctx := context.Background() |
| + s := adoptStore(t) |
| + for _, kind := range []string{"initialize", "retire-apps", ""} { |
| + if _, err := s.NewAdoptionRun(ctx, kind, []string{"calendar"}); err == nil { |
| + t.Fatalf("adoption run of kind %q", kind) |
| + } |
| + } |
| + for _, apps := range [][]string{nil, {"mail"}, {"docs", "docs"}} { |
| + if _, err := s.NewAdoptionRun(ctx, "add-apps", apps); err == nil { |
| + t.Fatalf("adoption run for %v", apps) |
| + } |
| + } |
| + var n int |
| + if err := s.DB().QueryRowContext(ctx, "SELECT count(*) FROM runs").Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("refused runs recorded %d, %v", n, err) |
| + } |
| +} |
| + |
| +// adopt seals its journal through the Store, and only under its own |
| +// purposes: it can never open Alta's owner address or plan bytes. |
| +func TestAdoptionSealIsConfinedToItsPurposes(t *testing.T) { |
| + ctx := context.Background() |
| + s := adoptStore(t) |
| + if err := s.CreateAdoption(ctx, "Oficina", ownerCanary, []string{"calendar"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + var sealed []byte |
| + if err := s.DB().QueryRowContext(ctx, "SELECT sealed_address FROM owner_inputs WHERE label=?", AdoptionLabel).Scan(&sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.OpenAdoption(ownerPurpose(AdoptionLabel), sealed); err == nil { |
| + t.Fatal("adopt opened the owner address") |
| + } |
| + if _, err := s.SealAdoption(ownerPurpose(AdoptionLabel), []byte("x")); err == nil { |
| + t.Fatal("adopt sealed under the owner purpose") |
| + } |
| + for _, p := range []string{"alta/adopt", "alta/adopt/", "alta/adoptx/t/k", "alta/owner/oficina"} { |
| + if _, err := s.SealAdoption(p, []byte("x")); err == nil { |
| + t.Fatalf("sealed under %q", p) |
| + } |
| + } |
| + b, err := s.SealAdoption("alta/adopt/t/k", []byte("x")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, err := s.OpenAdoption("alta/adopt/t/k", b); err != nil || string(got) != "x" { |
| + t.Fatalf("round trip %q, %v", got, err) |
| + } |
| + if _, err := s.OpenAdoption("alta/adopt/t/other", b); err == nil { |
| + t.Fatal("opened under another key's purpose") |
| + } |
| +} |