package main import ( "bytes" "context" "crypto/sha256" "database/sql" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "io" "net" "net/http" "net/http/httptest" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "syscall" "testing" "time" "amadan.net/oficina/alta/adopt" "amadan.net/oficina/alta/carlosop" "amadan.net/oficina/alta/carlosop/fakecarlos" "amadan.net/oficina/alta/homeop" "amadan.net/oficina/alta/homeop/fakehome" "amadan.net/oficina/alta/provision" family "amadan.net/rastrillo/rastrillo/crypto" ) const ( dirOrigin = "https://oficina.works" account = "bds" owner = "adopt-owner-canary@oficina.test" served = "v1.4.0" // plainCanary prefixes every plain value seeded into the fake // console: none may appear in any output. plainCanary = "plain-value-canary-" ) // rig is everything alta-adopt reaches, faked: Home's two roles, the // CARLOS console and the six apps' origins. type rig struct { t *testing.T mu sync.Mutex now time.Time home *fakehome.Home plans atomic.Int64 // POST /operator/v1/plan on either role homeURL map[string]string carlos *fakecarlos.Fake public *http.Client siteMu sync.Mutex seen map[string]int loaded map[string]bool releases map[string]string // an app's served release, when not served dir, cfgPath, state string dek, opKey, pre string cfg map[string]any // what writeConfig writes tokens [][]byte // every token buffer the command read out bytes.Buffer } func newRig(t *testing.T) *rig { t.Helper() r := &rig{t: t, now: time.Unix(2_000_000_000, 0), seen: map[string]int{}, loaded: map[string]bool{}} key, err := family.Generate() if err != nil { t.Fatal(err) } r.pre = homeop.Token() r.home = fakehome.New(key.SignPub(), r.pre, adopt.HomeIssuerOrigin, dirOrigin, r.clock) pins := r.home.SharePins() r.home.AddPerson(owner) for _, a := range provision.Slugs() { r.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a)) } r.homeURL = map[string]string{} for _, role := range []string{homeop.Credential, homeop.Directory} { h := r.home.Handler(role) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path == "/operator/v1/plan" { r.plans.Add(1) } h.ServeHTTP(w, req) })) t.Cleanup(srv.Close) r.homeURL[role] = srv.URL } r.carlos = fakecarlos.New(account) t.Cleanup(r.carlos.Close) for _, a := range provision.Apps { p := a.Prefix r.carlos.SetVar(a.Slug, "", p+"_HOME_ISSUER", adopt.HomeIssuerOrigin) r.carlos.SetVar(a.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, a.Slug)) r.carlos.SetVar(a.Slug, "", p+"_ORIGIN", plainCanary+a.Slug) r.carlos.SetSecret(a.Slug, "", p+"_INSTANCE_KEY") r.carlos.AddInstance(carlosop.Instance{ Host: routeOf(a), App: a.Slug, Slug: "s-" + a.Slug, Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`), }) // The canonical name is a domain claimed for the record, as in // production. r.carlos.AttachDomain(a.Slug, adopt.CanonicalHost(a), routeOf(a), "live") } site := httptest.NewTLSServer(http.HandlerFunc(r.site)) t.Cleanup(site.Close) tr := site.Client().Transport.(*http.Transport).Clone() addr := site.Listener.Addr().String() // Every app origin the probe names lands on the fake site. tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, network, addr) } tr.TLSClientConfig.ServerName = "example.com" r.public = &http.Client{Transport: tr, Timeout: 10 * time.Second} raw, err := family.MarshalKeypair(key) if err != nil { t.Fatal(err) } r.opKey = base64.StdEncoding.EncodeToString(raw) dek := make([]byte, 32) for i := range dek { dek[i] = byte(7 + i) } r.dek = base64.StdEncoding.EncodeToString(dek) r.dir = t.TempDir() r.state = filepath.Join(r.dir, "adopt.db") r.cfgPath = filepath.Join(r.dir, "adopt.json") artifacts := map[string]string{} sum := sha256.Sum256([]byte(served)) for _, a := range provision.Slugs() { artifacts[a] = hex.EncodeToString(sum[:]) } r.cfg = map[string]any{ "alta_dek": r.dek, "operator_key": r.opKey, "operator_prefilter": r.pre, "pins": map[string]string{"installation": pins.Installation, "registry": pins.Registry, "device": pins.Device}, "directory_provisioning_public_key": r.home.ProvisioningPublic(), "home_issuer": adopt.HomeIssuerOrigin, "home_directory": dirOrigin, "carlos_console": r.carlos.URL(), "carlos_account": account, "state": "adopt.db", "artifacts": artifacts, } r.writeConfig() return r } // writeConfig writes r.cfg as the config file, mode 0600. func (r *rig) writeConfig() { r.t.Helper() b, err := json.Marshal(r.cfg) if err != nil { r.t.Fatal(err) } if err := os.WriteFile(r.cfgPath, b, 0o600); err != nil { r.t.Fatal(err) } } func (r *rig) clock() time.Time { r.mu.Lock() defer r.mu.Unlock() return r.now } func (r *rig) tick(d time.Duration) { r.mu.Lock() defer r.mu.Unlock() r.now = r.now.Add(d) } // site is the six apps' origins. An app answers agent-access's challenge // only once a restart has loaded both of its agent keys. // routeOf is the host of a's canonical record: the route its canonical // domain is claimed for. func routeOf(a provision.App) string { return a.Slug + "." + account + ".oncarlos.com" } func (r *rig) site(w http.ResponseWriter, req *http.Request) { host, _, err := net.SplitHostPort(req.Host) if err != nil { host = req.Host } slug := strings.TrimSuffix(host, ".oficina.works") switch req.URL.Path { case "/api/version": release := r.release(slug) w.Header().Set("X-Carlos-Version", release) _, _ = io.WriteString(w, release) case "/healthz": w.WriteHeader(http.StatusOK) case "/api/v1/operations": // Base's own door already answers the challenge below, before // adoption and after it (the held door). if a, _ := provision.AppBySlug(slug); !r.serving(slug) && adopt.BaselineOps(a) != adopt.OpsAgent401 { // Slides, Calls and Equipo answer their own middleware's 401 // before adoption; the others have no such route. if adopt.BaselineOps(a) == adopt.OpsApp401 { w.WriteHeader(http.StatusUnauthorized) _, _ = io.WriteString(w, `{"error":"unauthorized"}`) return } http.NotFound(w, req) return } w.Header().Set("WWW-Authenticate", `Bearer realm="oficina"`) w.Header().Set("Cache-Control", "no-store") w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusUnauthorized) _, _ = io.WriteString(w, `{"error":{"code":"unauthenticated","message":"x"}}`) default: http.NotFound(w, req) } } // release is the release slug's origin serves. func (r *rig) release(slug string) string { r.siteMu.Lock() defer r.siteMu.Unlock() if v, ok := r.releases[slug]; ok { return v } return served } // redeploy serves release from slug's origin, as a deploy does: the // running process changes and its config and instance record do not. // approved also makes release the config's reviewed artifact for slug, // as Paul's approval of the redeploy did. func (r *rig) redeploy(slug, release string, approved bool) { r.t.Helper() r.siteMu.Lock() if r.releases == nil { r.releases = map[string]string{} } r.releases[slug] = release r.siteMu.Unlock() if approved { sum := sha256.Sum256([]byte(release)) r.cfg["artifacts"].(map[string]string)[slug] = hex.EncodeToString(sum[:]) r.writeConfig() } } func (r *rig) serving(slug string) bool { r.siteMu.Lock() defer r.siteMu.Unlock() a, ok := provision.AppBySlug(slug) if !ok { return false } if n := r.carlos.RestartCount(routeOf(a)); n != r.seen[slug] { vars, _, _ := r.carlos.Layer(slug, "") keys := adopt.AgentKeys(a) _, i := vars[keys[0]] _, t := vars[keys[1]] r.seen[slug], r.loaded[slug] = n, i && t } return r.loaded[slug] } // tokenFD is a fresh descriptor holding the CARLOS token, as Paul's shell // hands one over: alta-adopt reads and closes it. func (r *rig) tokenFD() string { r.t.Helper() pr, pw, err := os.Pipe() if err != nil { r.t.Fatal(err) } if _, err := pw.Write(r.carlos.Token()); err != nil { r.t.Fatal(err) } pw.Close() fd, err := syscall.Dup(int(pr.Fd())) if err != nil { r.t.Fatal(err) } pr.Close() return strconv.Itoa(fd) } // cli runs alta-adopt with --config and, when token, a token descriptor. func (r *rig) cli(stdin string, token bool, args ...string) (int, string) { r.t.Helper() args = append(args, "--config", r.cfgPath) if token { args = append(args, "--carlos-token-fd", r.tokenFD()) } var out bytes.Buffer code := run(context.Background(), args, env{ stdin: strings.NewReader(stdin), stdout: &out, stderr: &out, now: r.clock, public: r.public, homeURL: r.homeURL, tokenRead: func(b []byte) { r.tokens = append(r.tokens, b) }, }) r.out.Write(out.Bytes()) return code, out.String() } // ok runs a command that must succeed. func (r *rig) ok(stdin string, token bool, args ...string) string { r.t.Helper() code, out := r.cli(stdin, token, args...) if code != 0 { r.t.Fatalf("alta-adopt %s: exit %d\n%s", strings.Join(args, " "), code, out) } return out } // refused runs a command that must fail, naming code. func (r *rig) refused(code string, stdin string, token bool, args ...string) string { r.t.Helper() exit, out := r.cli(stdin, token, args...) if exit == 0 || !strings.Contains(out, code) { r.t.Fatalf("alta-adopt %s: exit %d, want a refusal naming %s\n%s", strings.Join(args, " "), exit, code, out) } return out } // writes is everything a dry run must leave alone: Home's plans and // committed operations, the console's writes and restarts, and every row // in the state database. type writes struct { plans, ops, puts, restarts, appWide, rows int64 exists bool } func (r *rig) writes() writes { r.t.Helper() w := writes{plans: r.plans.Load(), ops: int64(len(r.home.Requests())), appWide: int64(r.carlos.AppWideRestarts())} for _, q := range r.carlos.Requests() { if strings.HasPrefix(q, "PUT ") { w.puts++ } } for _, a := range provision.Apps { w.restarts += int64(r.carlos.RestartCount(routeOf(a))) } w.rows, w.exists = r.rows() return w } // rows counts every row of every table in the state database, without // creating it. func (r *rig) rows() (int64, bool) { r.t.Helper() if _, err := os.Stat(r.state); err != nil { return 0, false } db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { r.t.Fatal(err) } defer db.Close() rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'") if err != nil { r.t.Fatal(err) } var tables []string for rows.Next() { var n string if err := rows.Scan(&n); err != nil { r.t.Fatal(err) } tables = append(tables, n) } rows.Close() var total int64 for _, tb := range tables { var n int64 if err := db.QueryRow(`SELECT count(*) FROM "` + tb + `"`).Scan(&n); err != nil { r.t.Fatal(err) } total += n } return total, true } // dry runs a command without --apply and asserts it wrote nothing. func (r *rig) dry(stdin string, token bool, args ...string) string { r.t.Helper() before := r.writes() out := r.ok(stdin, token, args...) if after := r.writes(); after != before { r.t.Fatalf("alta-adopt %s without --apply wrote: before %+v after %+v", strings.Join(args, " "), before, after) } return out } // applied runs a command with --apply and asserts it wrote something. func (r *rig) applied(stdin string, token bool, args ...string) string { r.t.Helper() before := r.writes() out := r.ok(stdin, token, append(args, "--apply")...) if after := r.writes(); after == before { r.t.Fatalf("alta-adopt %s --apply wrote nothing\n%s", strings.Join(args, " "), out) } return out } func counts(phase string) string { var b strings.Builder for _, q := range adopt.HomeQueries() { n := 0 if phase == adopt.PhasePrePlanA && (strings.HasSuffix(q, " roster_generation") || strings.HasSuffix(q, " roster_operator_receipts")) { n = 1 } fmt.Fprintf(&b, "%d\n", n) } return b.String() } func (r *rig) latestRun() string { r.t.Helper() db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { r.t.Fatal(err) } defer db.Close() var id int64 if err := db.QueryRow("SELECT max(id) FROM runs").Scan(&id); err != nil { r.t.Fatal(err) } return strconv.FormatInt(id, 10) } func (r *rig) runCount() int { r.t.Helper() db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { r.t.Fatal(err) } defer db.Close() var n int if err := db.QueryRow("SELECT count(*) FROM runs").Scan(&n); err != nil { r.t.Fatal(err) } return n } func (r *rig) confirm(kind string) { r.t.Helper() if err := r.home.Confirm(homeop.Directory, ""); err != nil { r.t.Fatal(err) } if kind == homeop.KindInitialize || kind == homeop.KindRetireApps { return } who := "" if kind == homeop.KindCreateTeam { who = owner } if err := r.home.Confirm(homeop.Credential, who); err != nil { r.t.Fatal(err) } } func (r *rig) runState(want string) { r.t.Helper() db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { r.t.Fatal(err) } defer db.Close() var state, code string if err := db.QueryRow("SELECT state,code FROM runs ORDER BY id DESC LIMIT 1").Scan(&state, &code); err != nil { r.t.Fatal(err) } if got := strings.TrimSuffix(state+" "+code, " "); got != want { r.t.Fatalf("latest run %q, want %q", got, want) } } // throughPlanA records both Home preflights, initializes the directory // and runs Plan A to awaiting-configuration, all through the command. func (r *rig) throughPlanA() { r.t.Helper() r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") r.ok(provision.InitializeAttestation+"\n", false, "initialize", "--apply") r.confirm(homeop.KindInitialize) r.ok("", false, "advance", "--run", r.latestRun(), "--apply") r.runState("done") r.tick(homeop.WindowLifetime * time.Second) r.ok(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA, "--apply") r.ok(owner+"\n", false, "plan-a", "--apply") r.confirm(homeop.KindCreateTeam) r.ok("", false, "advance", "--run", r.latestRun(), "--apply") r.runState("done awaiting-configuration") r.tick(homeop.WindowLifetime * time.Second) } // configured writes app's keys, restarts it and records its delivery // check: configure alone, with nothing typed. func (r *rig) configured(app string) { r.t.Helper() a, _ := provision.AppBySlug(app) if out := r.ok("", true, "configure", "--app", app, "--apply"); !strings.Contains(out, adopt.SayConfigured(adopt.CanonicalHost(a))) { r.t.Fatalf("configure did not finish\n%s", out) } if !r.checked(app) { r.t.Fatalf("configure recorded no delivery check for %s", app) } } // checked reports whether status shows app's delivery check. func (r *rig) checked(app string) bool { r.t.Helper() for _, line := range strings.Split(r.ok("", false, "status"), "\n") { if strings.HasPrefix(line, app+": ") { return strings.Contains(line, ", "+adopt.SayStatusDeliveryCheck) } } r.t.Fatalf("status has no line for %s", app) return false } // rehearse walks every subcommand of the table in order. Each runs first // without --apply, which must write nothing anywhere; then, where it // writes, with --apply, which must write. func rehearse(t *testing.T) *rig { r := newRig(t) cal, _ := provision.AppBySlug(adopt.CanaryApp) // Nothing exists yet: a dry run does not even create the state. r.dry(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize) if _, exists := r.rows(); exists { t.Fatal("a dry run created the state database") } r.dry("", true, "preflight") r.dry("", false, "status") r.applied(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize) r.dry("", false, "initialize") r.applied(provision.InitializeAttestation+"\n", false, "initialize") r.confirm(homeop.KindInitialize) run := r.latestRun() r.dry("", false, "advance", "--run", run) r.applied("", false, "advance", "--run", run) r.runState("done") r.tick(homeop.WindowLifetime * time.Second) r.dry(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA) r.applied(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA) r.dry("", false, "plan-a") r.applied(owner+"\n", false, "plan-a") r.confirm(homeop.KindCreateTeam) run = r.latestRun() r.dry("", false, "advance", "--run", run) r.applied("", false, "advance", "--run", run) r.runState("done awaiting-configuration") r.tick(homeop.WindowLifetime * time.Second) r.dry("", true, "configure", "--app", adopt.CanaryApp) r.applied("", true, "configure", "--app", adopt.CanaryApp) if !r.checked(adopt.CanaryApp) { t.Fatal("configure recorded no delivery check") } r.dry("", true, "activate", "--apps", adopt.CanaryApp) r.applied("", true, "activate", "--apps", adopt.CanaryApp) r.confirm(homeop.KindAddApps) run = r.latestRun() r.dry("", true, "advance", "--run", run) r.applied("", true, "advance", "--run", run) r.runState("done") r.tick(homeop.WindowLifetime * time.Second) // The rollback's dry run names the keys it would remove, the bundle // and the host it would restart. keys, host := adopt.AgentKeys(cal), adopt.CanonicalHost(cal) if out := r.dry("", true, "rollback-config", "--app", adopt.CanaryApp); !strings.Contains(out, adopt.SayRollbackWould(keys, "default", host)) { t.Fatalf("rollback-config without --apply did not preview\n%s", out) } r.applied("", true, "rollback-config", "--app", adopt.CanaryApp) if out := r.dry("", true, "rollback-config", "--app", adopt.CanaryApp); !strings.Contains(out, adopt.SayRollbackNothing(host)) { t.Fatalf("a finished rollback's dry run did not say so\n%s", out) } r.dry("", false, "disable", "--app", adopt.CanaryApp) r.applied(provision.AdoptionLabel+"\n", false, "disable", "--app", adopt.CanaryApp) r.dry("", true, "preflight") r.dry("", false, "status") return r } func TestWritesNeedApply(t *testing.T) { t.Parallel() r := rehearse(t) if r.carlos.AppWideRestarts() != 0 { t.Fatal("the app-wide restart was called") } for _, a := range provision.Apps { if a.Slug != adopt.CanaryApp && r.carlos.RestartCount(routeOf(a)) != 0 { t.Fatalf("%s restarted", a.Slug) } } } // fileState is a file's bytes and mtime, or its absence. type fileState struct { exists bool sum [32]byte mtime time.Time } func stateOf(t *testing.T, path string) fileState { t.Helper() fi, err := os.Stat(path) if os.IsNotExist(err) { return fileState{} } if err != nil { t.Fatal(err) } b, err := os.ReadFile(path) if err != nil { t.Fatal(err) } return fileState{true, sha256.Sum256(b), fi.ModTime()} } // untouched asserts the state's committed contents did not move: the // file's bytes and mtime are the same, a WAL that existed is the same and // one that did not is at most SQLite's empty one, there is no rollback // journal, and nothing else appeared beside the state. SQLite's -shm // coordination file may appear or change. func (r *rig) untouched(before map[string]fileState) { r.t.Helper() after := r.files() if after[""] != before[""] { r.t.Fatal("a read-only run changed the state file") } empty := sha256.Sum256(nil) if w := after["-wal"]; before["-wal"].exists && w != before["-wal"] || !before["-wal"].exists && w.exists && w.sum != empty { r.t.Fatal("a read-only run changed the WAL") } if after["-journal"].exists { r.t.Fatal("a read-only run left a rollback journal") } ents, err := os.ReadDir(r.dir) if err != nil { r.t.Fatal(err) } for _, e := range ents { switch strings.TrimPrefix(e.Name(), filepath.Base(r.state)) { case "", "-wal", "-shm": default: if e.Name() != filepath.Base(r.cfgPath) { r.t.Fatalf("a read-only run left %s beside the state", e.Name()) } } } } func (r *rig) files() map[string]fileState { r.t.Helper() m := map[string]fileState{} for _, s := range []string{"", "-wal", "-shm", "-journal"} { m[s] = stateOf(r.t, r.state+s) } return m } // read-only runs: the dry runs that read the state, and status. func (r *rig) readOnly() string { r.t.Helper() var out strings.Builder out.WriteString(r.ok("", false, "status")) out.WriteString(r.ok("", true, "preflight")) out.WriteString(r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize)) return out.String() } func TestDryRunLeavesStateUntouched(t *testing.T) { t.Parallel() r := newRig(t) r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") // Make the journal's migration pending again: its ledger rows and // tables go, so any open by Alta's store would apply it to the file. db, err := sql.Open("sqlite", "file:"+r.state+"?_pragma=busy_timeout(5000)") if err != nil { t.Fatal(err) } for _, q := range []string{ "DELETE FROM rastrillo_migrations WHERE id LIKE 'adopt/%'", "DROP TABLE adopt_home_preflights", "DROP TABLE adopt_baselines", "DROP TABLE adopt_writes", "DROP TABLE adopt_rollbacks", "DROP TABLE adopt_afters", "DROP TABLE adopt_witnesses", "DROP TABLE adopt_checks", "PRAGMA wal_checkpoint(TRUNCATE)", } { if _, err := db.Exec(q); err != nil { t.Fatalf("%s: %v", q, err) } } db.Close() before := r.files() if !before[""].exists || before["-wal"].exists || before["-shm"].exists { t.Fatalf("setup: %+v", before) } out := r.readOnly() r.untouched(before) // The pending migration was applied to the copy, which the runs read. if !strings.Contains(out, adopt.SayStatusPreflight(adopt.PhasePreInitialize, false)) { t.Fatalf("status did not read the migrated copy\n%s", out) } // Committed transactions still in the WAL, with another process // holding the state open, are read too, and the WAL is untouched. r.holdOpen(func(js *adopt.Store) { if err := js.SaveHomePreflight(context.Background(), adopt.HomePreflight{Phase: adopt.PhasePrePlanA}); err != nil { t.Fatal(err) } before := r.files() if !before["-wal"].exists { t.Fatal("setup: no WAL") } out := r.readOnly() r.untouched(before) if !strings.Contains(out, adopt.SayStatusPreflight(adopt.PhasePrePlanA, true)) { t.Fatalf("status did not read the WAL\n%s", out) } }) } func TestInitializeRefusedWithoutHomePreflight(t *testing.T) { t.Parallel() r := newRig(t) r.refused("home-preflight-missing", provision.InitializeAttestation+"\n", false, "initialize", "--apply") if r.plans.Load() != 0 || len(r.home.Requests()) != 0 || r.runCount() != 0 { t.Fatal("a refused initialize reached Home or opened a run") } // The same command, once the attestation is recorded, opens the plan. r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") r.applied(provision.InitializeAttestation+"\n", false, "initialize") if r.plans.Load() != 1 { t.Fatalf("plans %d", r.plans.Load()) } } func TestPlanARefusedWithoutHomePreflight(t *testing.T) { t.Parallel() r := newRig(t) r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") r.ok(provision.InitializeAttestation+"\n", false, "initialize", "--apply") r.confirm(homeop.KindInitialize) r.ok("", false, "advance", "--run", r.latestRun(), "--apply") r.tick(homeop.WindowLifetime * time.Second) before := r.writes() r.refused("home-preflight-missing", owner+"\n", false, "plan-a", "--apply") if after := r.writes(); after != before { t.Fatalf("a refused plan-a wrote: %+v %+v", before, after) } r.ok(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA, "--apply") r.applied(owner+"\n", false, "plan-a") } // holdOpen opens the state as another process would and runs during // while it holds it open. func (r *rig) holdOpen(during func(js *adopt.Store)) { r.t.Helper() db, err := provision.OpenDB(r.state) if err != nil { r.t.Fatal(err) } defer db.Close() dek, _ := base64.StdEncoding.DecodeString(r.dek) ps, err := provision.NewStore(context.Background(), db, dek, r.clock, adopt.Schema) if err != nil { r.t.Fatal(err) } js, err := adopt.NewStore(ps) if err != nil { r.t.Fatal(err) } during(js) } // Plan C waits on Plan B alone (Paul, 2026-11-17): activate refuses every // app but the canary, before reading CARLOS, until calendar is active, // and says what comes first; then the same command opens Plan C with no // live check. func TestActivateNonCanaryRefusedBeforePlanB(t *testing.T) { t.Parallel() r := newRig(t) r.throughPlanA() r.configured("docs") r.configured(adopt.CanaryApp) refusedNow := func(why string) { t.Helper() before, reads := r.writes(), len(r.carlos.Requests()) for _, args := range [][]string{{"--apps", "docs", "--apply"}, {"--apps", "docs"}, {"--apps", "calendar,docs", "--apply"}} { out := r.refused("refused: canary-not-active", "", true, append([]string{"activate"}, args...)...) if !strings.Contains(out, adopt.HintCanary) { t.Fatalf("%s: activate %v: no hint\n%s", why, args, out) } } if after := r.writes(); after != before { t.Fatalf("%s: a refused activate wrote: %+v %+v", why, before, after) } if n := len(r.carlos.Requests()); n != reads { t.Fatalf("%s: a refused activate read CARLOS %d times", why, n-reads) } } refusedNow("before Plan B") // Plan B opened but not yet through: still refused. r.applied("", true, "activate", "--apps", adopt.CanaryApp) refusedNow("Plan B open") r.confirm(homeop.KindAddApps) r.ok("", true, "advance", "--run", r.latestRun(), "--apply") r.runState("done") r.tick(homeop.WindowLifetime * time.Second) r.applied("", true, "activate", "--apps", "docs") r.confirm(homeop.KindAddApps) r.ok("", true, "advance", "--run", r.latestRun(), "--apply") r.runState("done") if st := r.home.InstanceState("docs"); st != "live" { t.Fatalf("docs is %q at Home", st) } } // A process that died after the after snapshot and before its delivery // check is resumed by configure alone: no second write or restart, and // the check recorded. func TestConfigureResumesDeliveryCheck(t *testing.T) { t.Parallel() r := newRig(t) r.throughPlanA() r.configured("docs") // The check lost, as if the process had died before saving it. db, err := sql.Open("sqlite", "file:"+r.state+"?_pragma=busy_timeout(5000)") if err != nil { t.Fatal(err) } if _, err := db.Exec("DELETE FROM adopt_witnesses WHERE app='docs'"); err != nil { t.Fatal(err) } db.Close() if r.checked("docs") { t.Fatal("setup: the check is still there") } docs, _ := provision.AppBySlug("docs") puts, restarts := r.writes().puts, r.carlos.RestartCount(routeOf(docs)) r.configured("docs") if r.writes().puts != puts || r.carlos.RestartCount(routeOf(docs)) != restarts { t.Fatal("the resume wrote or restarted again") } } // A write that landed before its restart is resumed by configure alone, // and the resume restarts nothing once the canonical domain has left the // record the baseline saw (Astra review, 2026-11-18). func TestConfigureResumeRestartsNothingAfterTheClaimMoved(t *testing.T) { t.Parallel() const other = "docs-2.bds.oncarlos.com" docs, _ := provision.AppBySlug("docs") cases := map[string]struct { edit func(r *rig) code string }{ "re-pointed": {func(r *rig) { r.carlos.AddInstance(carlosop.Instance{Host: other, App: "docs", Slug: "s-docs-2", Channel: "stable", Region: "eu"}) r.carlos.AttachDomain("docs", adopt.CanonicalHost(docs), other, "live") }, "restart-binding-changed"}, "detached": {func(r *rig) { r.carlos.DetachDomain("docs", adopt.CanonicalHost(docs)) }, "restart-binding-domain-missing"}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { t.Parallel() r := newRig(t) r.throughPlanA() // The write lands; the restart that follows it does not. r.carlos.FailRestart(http.StatusServiceUnavailable) r.refused("", "", true, "configure", "--app", "docs", "--apply") r.carlos.FailRestart(0) puts := r.writes().puts if puts == 0 { t.Fatal("setup: the write did not land") } tc.edit(r) out := r.refused("", "", true, "configure", "--app", "docs", "--apply") if !strings.Contains(out, tc.code) { t.Fatalf("the resume did not name %s\n%s", tc.code, out) } if n := r.carlos.RestartCount(routeOf(docs)) + r.carlos.RestartCount(other); n != 0 { t.Fatalf("the resume restarted %d times", n) } if r.writes().puts != puts { t.Fatal("the resume wrote again") } }) } } // A served release that is not the reviewed one is refused before // anything is written (Astra review, 2026-11-17): by preflight, by // configure's dry run and by configure itself, which journals and sends // nothing. Activation stays refused. func TestConfigureRefusesUnreviewedReleaseBeforeWriting(t *testing.T) { t.Parallel() r := newRig(t) r.throughPlanA() other := sha256.Sum256([]byte("v9.9.9")) r.cfg["artifacts"].(map[string]string)[adopt.CanaryApp] = hex.EncodeToString(other[:]) r.writeConfig() if out := r.refused("preflight-refused", "", true, "preflight"); !strings.Contains(out, adopt.SayActivateApp(adopt.CanaryApp, []string{"artifact-mismatch"})) { t.Fatalf("preflight did not name the release\n%s", out) } before := r.writes() r.refused("artifact-mismatch", "", true, "configure", "--app", adopt.CanaryApp) r.refused("artifact-mismatch", "", true, "configure", "--app", adopt.CanaryApp, "--apply") if after := r.writes(); after != before { t.Fatalf("a refused configure wrote: %+v %+v", before, after) } if r.checked(adopt.CanaryApp) { t.Fatal("a delivery check was recorded for an unreviewed release") } r.refused("activate-refused", "", true, "activate", "--apps", adopt.CanaryApp) } // Docs, slides, calls and memoria were redeployed to releases Paul // approved after configure had landed their writes and recorded their // delivery checks (2026-11-19). Activation refuses the stale checks; // configure, run again, checks each app on its new release, writing and // restarting nothing, and activation then goes through. func TestConfigureRechecksApprovedRedeploy(t *testing.T) { t.Parallel() r := newRig(t) r.throughPlanA() r.configured(adopt.CanaryApp) r.applied("", true, "activate", "--apps", adopt.CanaryApp) r.confirm(homeop.KindAddApps) r.ok("", true, "advance", "--run", r.latestRun(), "--apply") r.runState("done") r.tick(homeop.WindowLifetime * time.Second) apps := []string{"docs", "slides", "calls", "memoria"} for _, a := range apps { r.configured(a) } for _, a := range apps { r.redeploy(a, "v1.5.0-2-gabcdef1", true) } list := strings.Join(apps, ",") if out := r.refused("activate-refused", "", true, "activate", "--apps", list); !strings.Contains(out, "delivery-check-superseded") || !strings.Contains(out, "not-delivered") { t.Fatalf("activate did not refuse the stale checks as production did\n%s", out) } before := r.writes() for _, a := range apps { r.configured(a) } after := r.writes() if after.puts != before.puts || after.restarts != before.restarts || after.appWide != before.appWide || after.plans != before.plans || after.ops != before.ops { t.Fatalf("the re-check wrote or restarted: %+v %+v", before, after) } r.applied("", true, "activate", "--apps", list) r.confirm(homeop.KindAddApps) r.ok("", true, "advance", "--run", r.latestRun(), "--apply") r.runState("done") for _, a := range apps { if st := r.home.InstanceState(a); st != "live" { t.Fatalf("%s is %q at Home", a, st) } } } // A redeploy to a release Paul did not approve keeps today's refusal: // configure records no check, and activation stays refused. func TestConfigureRefusesUnapprovedRedeploy(t *testing.T) { t.Parallel() r := newRig(t) r.throughPlanA() r.configured(adopt.CanaryApp) r.redeploy(adopt.CanaryApp, "v1.5.0", false) before := r.writes() out := r.refused("check-not-delivered", "", true, "configure", "--app", adopt.CanaryApp, "--apply") if !strings.Contains(out, "adopt: the served version changed") || !strings.Contains(out, "redeploy-artifact-mismatch") { t.Fatalf("configure did not refuse the unapproved release\n%s", out) } if after := r.writes(); after != before { t.Fatalf("a refused re-check wrote: %+v %+v", before, after) } r.refused("activate-refused", "", true, "activate", "--apps", adopt.CanaryApp) } // The witness and the live checks are gone (Paul, 2026-11-17): their // commands are unknown, and nothing is opened or written. func TestRemovedCommandsAreUnknown(t *testing.T) { t.Parallel() r := newRig(t) for _, args := range [][]string{{"witness", "--app", "docs", "--apply"}, {"live", "--event", "7", "--apply"}} { code, out := r.cli("", true, args...) if code != 2 || !strings.Contains(out, adopt.Usage) { t.Fatalf("alta-adopt %s: exit %d\n%s", args[0], code, out) } if strings.Contains(adopt.Usage, " "+args[0]+" ") { t.Fatalf("the usage still lists %s", args[0]) } } if _, exists := r.rows(); exists { t.Fatal("an unknown command created the state") } } func TestConfigFileModeRefused(t *testing.T) { t.Parallel() r := newRig(t) for _, mode := range []os.FileMode{0o644, 0o640, 0o604, 0o660, 0o700} { if err := os.Chmod(r.cfgPath, mode); err != nil { t.Fatal(err) } r.refused(adopt.RefuseConfigMode, "", true, "status") r.refused(adopt.RefuseConfigMode, counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") } if _, exists := r.rows(); exists || r.plans.Load() != 0 || len(r.carlos.Requests()) != 0 { t.Fatal("a refused config reached something") } if err := os.Chmod(r.cfgPath, 0o600); err != nil { t.Fatal(err) } r.ok("", false, "status") } func TestConfigFileOtherOwnerRefused(t *testing.T) { t.Parallel() if err := ownedByUser(fakeStat{uid: uint32(os.Getuid()) + 1}); err == nil { t.Fatal("a file another user owns was accepted") } if err := ownedByUser(fakeStat{uid: uint32(os.Getuid())}); err != nil { t.Fatalf("own file refused: %v", err) } } func TestTokenFDRefusesStandardStreams(t *testing.T) { t.Parallel() r := newRig(t) for _, fd := range []string{"0", "1", "2"} { code, out := r.cli("", false, "preflight", "--carlos-token-fd", fd) if code == 0 || !strings.Contains(out, adopt.RefuseTokenFD) { t.Fatalf("fd %s: exit %d\n%s", fd, code, out) } } if len(r.carlos.Requests()) != 0 { t.Fatal("the console was reached") } } // secrets are every value no output may carry. func (r *rig) secrets() map[string]string { r.t.Helper() s := map[string]string{ "token": string(r.carlos.Token()), "dek": r.dek, "operator key": r.opKey, "prefilter": r.pre, "owner": owner, "vd1 digest": "vd1:", "cv1 version": "cv1:", "plain value": plainCanary, "agent issuer value": adopt.Issuer, "home issuer value": adopt.HomeIssuerOrigin, } if _, sqid, ok := r.home.Team(provision.AdoptionLabel); ok { s["team sqid"] = sqid } return s } // binding reads the environment_binding the activation sent, from the // held request. func (r *rig) binding(app string) string { r.t.Helper() db, err := provision.OpenDB(r.state) if err != nil { r.t.Fatal(err) } defer db.Close() dek, _ := base64.StdEncoding.DecodeString(r.dek) ps, err := provision.NewStore(context.Background(), db, dek, r.clock, adopt.Schema) if err != nil { r.t.Fatal(err) } req, ok, err := ps.LastRequest(context.Background(), provision.AdoptionLabel, app, "activate") if err != nil || !ok { r.t.Fatalf("no activation request: %v", err) } var w struct { Input struct { Evidence struct { Binding string `json:"environment_binding"` } `json:"evidence"` } `json:"operation_input"` } if err := json.Unmarshal(req.Bytes, &w); err != nil || w.Input.Evidence.Binding == "" { r.t.Fatalf("activation request: %v", err) } return w.Input.Evidence.Binding } func TestOutputScrub(t *testing.T) { t.Parallel() r := rehearse(t) secrets := r.secrets() secrets["environment binding"] = r.binding(adopt.CanaryApp) // Refusals and help print too. r.cli("", false) r.cli("", false, "help") r.cli("not-an-oficina-app\n", false, "disable", "--app", adopt.CanaryApp, "--apply") r.cli("", true, "configure", "--app", "nope") out := r.out.String() if out == "" { t.Fatal("no output captured") } for name, v := range secrets { if v != "" && strings.Contains(out, v) { t.Errorf("output carries the %s", name) } } } func TestTokenNeverInEnvOrDisk(t *testing.T) { t.Parallel() r := newRig(t) token := r.carlos.Token() // A token read for a run that stops before reaching CARLOS is zeroed // too. if err := os.Chmod(r.cfgPath, 0o644); err != nil { t.Fatal(err) } r.refused(adopt.RefuseConfigMode, "", true, "preflight") if err := os.Chmod(r.cfgPath, 0o600); err != nil { t.Fatal(err) } r.throughPlanA() r.ok("", true, "preflight") r.configured("docs") r.ok("", true, "status") if n := len(r.carlos.Requests()); n == 0 { t.Fatal("the token was never used") } for _, kv := range os.Environ() { if strings.Contains(kv, string(token)) { t.Fatal("the token is in the environment") } } err := filepath.WalkDir(r.dir, func(path string, d os.DirEntry, err error) error { if err != nil || d.IsDir() { return err } b, err := os.ReadFile(path) if err != nil { return err } if bytes.Contains(b, token) { t.Errorf("the token is on disk in %s", filepath.Base(path)) } return nil }) if err != nil { t.Fatal(err) } if strings.Contains(r.out.String(), string(token)) { t.Fatal("the token was printed") } if len(r.tokens) == 0 { t.Fatal("no token was read") } for i, b := range r.tokens { if len(b) == 0 || !bytes.Equal(b, make([]byte, len(b))) { t.Fatalf("token buffer %d was not zeroed", i) } } } type fakeStat struct{ uid uint32 } func (f fakeStat) Owner() (uint32, bool) { return f.uid, true }