| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "database/sql" |
| 8 | "encoding/base64" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "os" |
| 17 | "path/filepath" |
| 18 | "strconv" |
| 19 | "strings" |
| 20 | "sync" |
| 21 | "sync/atomic" |
| 22 | "syscall" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "amadan.net/oficina/alta/adopt" |
| 27 | "amadan.net/oficina/alta/carlosop" |
| 28 | "amadan.net/oficina/alta/carlosop/fakecarlos" |
| 29 | "amadan.net/oficina/alta/homeop" |
| 30 | "amadan.net/oficina/alta/homeop/fakehome" |
| 31 | "amadan.net/oficina/alta/provision" |
| 32 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 33 | ) |
| 34 | |
| 35 | const ( |
| 36 | dirOrigin = "https://oficina.works" |
| 37 | account = "bds" |
| 38 | owner = "adopt-owner-canary@oficina.test" |
| 39 | served = "v1.4.0" |
| 40 | // plainCanary prefixes every plain value seeded into the fake |
| 41 | // console: none may appear in any output. |
| 42 | plainCanary = "plain-value-canary-" |
| 43 | ) |
| 44 | |
| 45 | // rig is everything alta-adopt reaches, faked: Home's two roles, the |
| 46 | // CARLOS console and the six apps' origins. |
| 47 | type rig struct { |
| 48 | t *testing.T |
| 49 | |
| 50 | mu sync.Mutex |
| 51 | now time.Time |
| 52 | |
| 53 | home *fakehome.Home |
| 54 | plans atomic.Int64 // POST /operator/v1/plan on either role |
| 55 | homeURL map[string]string |
| 56 | carlos *fakecarlos.Fake |
| 57 | public *http.Client |
| 58 | |
| 59 | siteMu sync.Mutex |
| 60 | seen map[string]int |
| 61 | loaded map[string]bool |
| 62 | releases map[string]string // an app's served release, when not served |
| 63 | |
| 64 | dir, cfgPath, state string |
| 65 | dek, opKey, pre string |
| 66 | cfg map[string]any // what writeConfig writes |
| 67 | tokens [][]byte // every token buffer the command read |
| 68 | out bytes.Buffer |
| 69 | } |
| 70 | |
| 71 | func newRig(t *testing.T) *rig { |
| 72 | t.Helper() |
| 73 | r := &rig{t: t, now: time.Unix(2_000_000_000, 0), seen: map[string]int{}, loaded: map[string]bool{}} |
| 74 | key, err := family.Generate() |
| 75 | if err != nil { |
| 76 | t.Fatal(err) |
| 77 | } |
| 78 | r.pre = homeop.Token() |
| 79 | r.home = fakehome.New(key.SignPub(), r.pre, adopt.HomeIssuerOrigin, dirOrigin, r.clock) |
| 80 | pins := r.home.SharePins() |
| 81 | r.home.AddPerson(owner) |
| 82 | for _, a := range provision.Slugs() { |
| 83 | r.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a)) |
| 84 | } |
| 85 | r.homeURL = map[string]string{} |
| 86 | for _, role := range []string{homeop.Credential, homeop.Directory} { |
| 87 | h := r.home.Handler(role) |
| 88 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 89 | if req.URL.Path == "/operator/v1/plan" { |
| 90 | r.plans.Add(1) |
| 91 | } |
| 92 | h.ServeHTTP(w, req) |
| 93 | })) |
| 94 | t.Cleanup(srv.Close) |
| 95 | r.homeURL[role] = srv.URL |
| 96 | } |
| 97 | |
| 98 | r.carlos = fakecarlos.New(account) |
| 99 | t.Cleanup(r.carlos.Close) |
| 100 | for _, a := range provision.Apps { |
| 101 | p := a.Prefix |
| 102 | r.carlos.SetVar(a.Slug, "", p+"_HOME_ISSUER", adopt.HomeIssuerOrigin) |
| 103 | r.carlos.SetVar(a.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, a.Slug)) |
| 104 | r.carlos.SetVar(a.Slug, "", p+"_ORIGIN", plainCanary+a.Slug) |
| 105 | r.carlos.SetSecret(a.Slug, "", p+"_INSTANCE_KEY") |
| 106 | r.carlos.AddInstance(carlosop.Instance{ |
| 107 | Host: routeOf(a), App: a.Slug, Slug: "s-" + a.Slug, Channel: "stable", Region: "eu", |
| 108 | CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, |
| 109 | ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`), |
| 110 | }) |
| 111 | // The canonical name is a domain claimed for the record, as in |
| 112 | // production. |
| 113 | r.carlos.AttachDomain(a.Slug, adopt.CanonicalHost(a), routeOf(a), "live") |
| 114 | } |
| 115 | |
| 116 | site := httptest.NewTLSServer(http.HandlerFunc(r.site)) |
| 117 | t.Cleanup(site.Close) |
| 118 | tr := site.Client().Transport.(*http.Transport).Clone() |
| 119 | addr := site.Listener.Addr().String() |
| 120 | // Every app origin the probe names lands on the fake site. |
| 121 | tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| 122 | var d net.Dialer |
| 123 | return d.DialContext(ctx, network, addr) |
| 124 | } |
| 125 | tr.TLSClientConfig.ServerName = "example.com" |
| 126 | r.public = &http.Client{Transport: tr, Timeout: 10 * time.Second} |
| 127 | |
| 128 | raw, err := family.MarshalKeypair(key) |
| 129 | if err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | r.opKey = base64.StdEncoding.EncodeToString(raw) |
| 133 | dek := make([]byte, 32) |
| 134 | for i := range dek { |
| 135 | dek[i] = byte(7 + i) |
| 136 | } |
| 137 | r.dek = base64.StdEncoding.EncodeToString(dek) |
| 138 | r.dir = t.TempDir() |
| 139 | r.state = filepath.Join(r.dir, "adopt.db") |
| 140 | r.cfgPath = filepath.Join(r.dir, "adopt.json") |
| 141 | artifacts := map[string]string{} |
| 142 | sum := sha256.Sum256([]byte(served)) |
| 143 | for _, a := range provision.Slugs() { |
| 144 | artifacts[a] = hex.EncodeToString(sum[:]) |
| 145 | } |
| 146 | r.cfg = map[string]any{ |
| 147 | "alta_dek": r.dek, |
| 148 | "operator_key": r.opKey, |
| 149 | "operator_prefilter": r.pre, |
| 150 | "pins": map[string]string{"installation": pins.Installation, "registry": pins.Registry, "device": pins.Device}, |
| 151 | "directory_provisioning_public_key": r.home.ProvisioningPublic(), |
| 152 | "home_issuer": adopt.HomeIssuerOrigin, |
| 153 | "home_directory": dirOrigin, |
| 154 | "carlos_console": r.carlos.URL(), |
| 155 | "carlos_account": account, |
| 156 | "state": "adopt.db", |
| 157 | "artifacts": artifacts, |
| 158 | } |
| 159 | r.writeConfig() |
| 160 | return r |
| 161 | } |
| 162 | |
| 163 | // writeConfig writes r.cfg as the config file, mode 0600. |
| 164 | func (r *rig) writeConfig() { |
| 165 | r.t.Helper() |
| 166 | b, err := json.Marshal(r.cfg) |
| 167 | if err != nil { |
| 168 | r.t.Fatal(err) |
| 169 | } |
| 170 | if err := os.WriteFile(r.cfgPath, b, 0o600); err != nil { |
| 171 | r.t.Fatal(err) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | func (r *rig) clock() time.Time { |
| 176 | r.mu.Lock() |
| 177 | defer r.mu.Unlock() |
| 178 | return r.now |
| 179 | } |
| 180 | |
| 181 | func (r *rig) tick(d time.Duration) { |
| 182 | r.mu.Lock() |
| 183 | defer r.mu.Unlock() |
| 184 | r.now = r.now.Add(d) |
| 185 | } |
| 186 | |
| 187 | // site is the six apps' origins. An app answers agent-access's challenge |
| 188 | // only once a restart has loaded both of its agent keys. |
| 189 | // routeOf is the host of a's canonical record: the route its canonical |
| 190 | // domain is claimed for. |
| 191 | func routeOf(a provision.App) string { return a.Slug + "." + account + ".oncarlos.com" } |
| 192 | |
| 193 | func (r *rig) site(w http.ResponseWriter, req *http.Request) { |
| 194 | host, _, err := net.SplitHostPort(req.Host) |
| 195 | if err != nil { |
| 196 | host = req.Host |
| 197 | } |
| 198 | slug := strings.TrimSuffix(host, ".oficina.works") |
| 199 | switch req.URL.Path { |
| 200 | case "/api/version": |
| 201 | release := r.release(slug) |
| 202 | w.Header().Set("X-Carlos-Version", release) |
| 203 | _, _ = io.WriteString(w, release) |
| 204 | case "/healthz": |
| 205 | w.WriteHeader(http.StatusOK) |
| 206 | case "/api/v1/operations": |
| 207 | // Base's own door already answers the challenge below, before |
| 208 | // adoption and after it (the held door). |
| 209 | if a, _ := provision.AppBySlug(slug); !r.serving(slug) && adopt.BaselineOps(a) != adopt.OpsAgent401 { |
| 210 | // Slides, Calls and Equipo answer their own middleware's 401 |
| 211 | // before adoption; the others have no such route. |
| 212 | if adopt.BaselineOps(a) == adopt.OpsApp401 { |
| 213 | w.WriteHeader(http.StatusUnauthorized) |
| 214 | _, _ = io.WriteString(w, `{"error":"unauthorized"}`) |
| 215 | return |
| 216 | } |
| 217 | http.NotFound(w, req) |
| 218 | return |
| 219 | } |
| 220 | w.Header().Set("WWW-Authenticate", `Bearer realm="oficina"`) |
| 221 | w.Header().Set("Cache-Control", "no-store") |
| 222 | w.Header().Set("Content-Type", "application/json") |
| 223 | w.WriteHeader(http.StatusUnauthorized) |
| 224 | _, _ = io.WriteString(w, `{"error":{"code":"unauthenticated","message":"x"}}`) |
| 225 | default: |
| 226 | http.NotFound(w, req) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // release is the release slug's origin serves. |
| 231 | func (r *rig) release(slug string) string { |
| 232 | r.siteMu.Lock() |
| 233 | defer r.siteMu.Unlock() |
| 234 | if v, ok := r.releases[slug]; ok { |
| 235 | return v |
| 236 | } |
| 237 | return served |
| 238 | } |
| 239 | |
| 240 | // redeploy serves release from slug's origin, as a deploy does: the |
| 241 | // running process changes and its config and instance record do not. |
| 242 | // approved also makes release the config's reviewed artifact for slug, |
| 243 | // as Paul's approval of the redeploy did. |
| 244 | func (r *rig) redeploy(slug, release string, approved bool) { |
| 245 | r.t.Helper() |
| 246 | r.siteMu.Lock() |
| 247 | if r.releases == nil { |
| 248 | r.releases = map[string]string{} |
| 249 | } |
| 250 | r.releases[slug] = release |
| 251 | r.siteMu.Unlock() |
| 252 | if approved { |
| 253 | sum := sha256.Sum256([]byte(release)) |
| 254 | r.cfg["artifacts"].(map[string]string)[slug] = hex.EncodeToString(sum[:]) |
| 255 | r.writeConfig() |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func (r *rig) serving(slug string) bool { |
| 260 | r.siteMu.Lock() |
| 261 | defer r.siteMu.Unlock() |
| 262 | a, ok := provision.AppBySlug(slug) |
| 263 | if !ok { |
| 264 | return false |
| 265 | } |
| 266 | if n := r.carlos.RestartCount(routeOf(a)); n != r.seen[slug] { |
| 267 | vars, _, _ := r.carlos.Layer(slug, "") |
| 268 | keys := adopt.AgentKeys(a) |
| 269 | _, i := vars[keys[0]] |
| 270 | _, t := vars[keys[1]] |
| 271 | r.seen[slug], r.loaded[slug] = n, i && t |
| 272 | } |
| 273 | return r.loaded[slug] |
| 274 | } |
| 275 | |
| 276 | // tokenFD is a fresh descriptor holding the CARLOS token, as Paul's shell |
| 277 | // hands one over: alta-adopt reads and closes it. |
| 278 | func (r *rig) tokenFD() string { |
| 279 | r.t.Helper() |
| 280 | pr, pw, err := os.Pipe() |
| 281 | if err != nil { |
| 282 | r.t.Fatal(err) |
| 283 | } |
| 284 | if _, err := pw.Write(r.carlos.Token()); err != nil { |
| 285 | r.t.Fatal(err) |
| 286 | } |
| 287 | pw.Close() |
| 288 | fd, err := syscall.Dup(int(pr.Fd())) |
| 289 | if err != nil { |
| 290 | r.t.Fatal(err) |
| 291 | } |
| 292 | pr.Close() |
| 293 | return strconv.Itoa(fd) |
| 294 | } |
| 295 | |
| 296 | // cli runs alta-adopt with --config and, when token, a token descriptor. |
| 297 | func (r *rig) cli(stdin string, token bool, args ...string) (int, string) { |
| 298 | r.t.Helper() |
| 299 | args = append(args, "--config", r.cfgPath) |
| 300 | if token { |
| 301 | args = append(args, "--carlos-token-fd", r.tokenFD()) |
| 302 | } |
| 303 | var out bytes.Buffer |
| 304 | code := run(context.Background(), args, env{ |
| 305 | stdin: strings.NewReader(stdin), stdout: &out, stderr: &out, |
| 306 | now: r.clock, public: r.public, homeURL: r.homeURL, |
| 307 | tokenRead: func(b []byte) { r.tokens = append(r.tokens, b) }, |
| 308 | }) |
| 309 | r.out.Write(out.Bytes()) |
| 310 | return code, out.String() |
| 311 | } |
| 312 | |
| 313 | // ok runs a command that must succeed. |
| 314 | func (r *rig) ok(stdin string, token bool, args ...string) string { |
| 315 | r.t.Helper() |
| 316 | code, out := r.cli(stdin, token, args...) |
| 317 | if code != 0 { |
| 318 | r.t.Fatalf("alta-adopt %s: exit %d\n%s", strings.Join(args, " "), code, out) |
| 319 | } |
| 320 | return out |
| 321 | } |
| 322 | |
| 323 | // refused runs a command that must fail, naming code. |
| 324 | func (r *rig) refused(code string, stdin string, token bool, args ...string) string { |
| 325 | r.t.Helper() |
| 326 | exit, out := r.cli(stdin, token, args...) |
| 327 | if exit == 0 || !strings.Contains(out, code) { |
| 328 | r.t.Fatalf("alta-adopt %s: exit %d, want a refusal naming %s\n%s", strings.Join(args, " "), exit, code, out) |
| 329 | } |
| 330 | return out |
| 331 | } |
| 332 | |
| 333 | // writes is everything a dry run must leave alone: Home's plans and |
| 334 | // committed operations, the console's writes and restarts, and every row |
| 335 | // in the state database. |
| 336 | type writes struct { |
| 337 | plans, ops, puts, restarts, appWide, rows int64 |
| 338 | exists bool |
| 339 | } |
| 340 | |
| 341 | func (r *rig) writes() writes { |
| 342 | r.t.Helper() |
| 343 | w := writes{plans: r.plans.Load(), ops: int64(len(r.home.Requests())), appWide: int64(r.carlos.AppWideRestarts())} |
| 344 | for _, q := range r.carlos.Requests() { |
| 345 | if strings.HasPrefix(q, "PUT ") { |
| 346 | w.puts++ |
| 347 | } |
| 348 | } |
| 349 | for _, a := range provision.Apps { |
| 350 | w.restarts += int64(r.carlos.RestartCount(routeOf(a))) |
| 351 | } |
| 352 | w.rows, w.exists = r.rows() |
| 353 | return w |
| 354 | } |
| 355 | |
| 356 | // rows counts every row of every table in the state database, without |
| 357 | // creating it. |
| 358 | func (r *rig) rows() (int64, bool) { |
| 359 | r.t.Helper() |
| 360 | if _, err := os.Stat(r.state); err != nil { |
| 361 | return 0, false |
| 362 | } |
| 363 | db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") |
| 364 | if err != nil { |
| 365 | r.t.Fatal(err) |
| 366 | } |
| 367 | defer db.Close() |
| 368 | rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'") |
| 369 | if err != nil { |
| 370 | r.t.Fatal(err) |
| 371 | } |
| 372 | var tables []string |
| 373 | for rows.Next() { |
| 374 | var n string |
| 375 | if err := rows.Scan(&n); err != nil { |
| 376 | r.t.Fatal(err) |
| 377 | } |
| 378 | tables = append(tables, n) |
| 379 | } |
| 380 | rows.Close() |
| 381 | var total int64 |
| 382 | for _, tb := range tables { |
| 383 | var n int64 |
| 384 | if err := db.QueryRow(`SELECT count(*) FROM "` + tb + `"`).Scan(&n); err != nil { |
| 385 | r.t.Fatal(err) |
| 386 | } |
| 387 | total += n |
| 388 | } |
| 389 | return total, true |
| 390 | } |
| 391 | |
| 392 | // dry runs a command without --apply and asserts it wrote nothing. |
| 393 | func (r *rig) dry(stdin string, token bool, args ...string) string { |
| 394 | r.t.Helper() |
| 395 | before := r.writes() |
| 396 | out := r.ok(stdin, token, args...) |
| 397 | if after := r.writes(); after != before { |
| 398 | r.t.Fatalf("alta-adopt %s without --apply wrote: before %+v after %+v", strings.Join(args, " "), before, after) |
| 399 | } |
| 400 | return out |
| 401 | } |
| 402 | |
| 403 | // applied runs a command with --apply and asserts it wrote something. |
| 404 | func (r *rig) applied(stdin string, token bool, args ...string) string { |
| 405 | r.t.Helper() |
| 406 | before := r.writes() |
| 407 | out := r.ok(stdin, token, append(args, "--apply")...) |
| 408 | if after := r.writes(); after == before { |
| 409 | r.t.Fatalf("alta-adopt %s --apply wrote nothing\n%s", strings.Join(args, " "), out) |
| 410 | } |
| 411 | return out |
| 412 | } |
| 413 | |
| 414 | func counts(phase string) string { |
| 415 | var b strings.Builder |
| 416 | for _, q := range adopt.HomeQueries() { |
| 417 | n := 0 |
| 418 | if phase == adopt.PhasePrePlanA && (strings.HasSuffix(q, " roster_generation") || strings.HasSuffix(q, " roster_operator_receipts")) { |
| 419 | n = 1 |
| 420 | } |
| 421 | fmt.Fprintf(&b, "%d\n", n) |
| 422 | } |
| 423 | return b.String() |
| 424 | } |
| 425 | |
| 426 | func (r *rig) latestRun() string { |
| 427 | r.t.Helper() |
| 428 | db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") |
| 429 | if err != nil { |
| 430 | r.t.Fatal(err) |
| 431 | } |
| 432 | defer db.Close() |
| 433 | var id int64 |
| 434 | if err := db.QueryRow("SELECT max(id) FROM runs").Scan(&id); err != nil { |
| 435 | r.t.Fatal(err) |
| 436 | } |
| 437 | return strconv.FormatInt(id, 10) |
| 438 | } |
| 439 | |
| 440 | func (r *rig) runCount() int { |
| 441 | r.t.Helper() |
| 442 | db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") |
| 443 | if err != nil { |
| 444 | r.t.Fatal(err) |
| 445 | } |
| 446 | defer db.Close() |
| 447 | var n int |
| 448 | if err := db.QueryRow("SELECT count(*) FROM runs").Scan(&n); err != nil { |
| 449 | r.t.Fatal(err) |
| 450 | } |
| 451 | return n |
| 452 | } |
| 453 | |
| 454 | func (r *rig) confirm(kind string) { |
| 455 | r.t.Helper() |
| 456 | if err := r.home.Confirm(homeop.Directory, ""); err != nil { |
| 457 | r.t.Fatal(err) |
| 458 | } |
| 459 | if kind == homeop.KindInitialize || kind == homeop.KindRetireApps { |
| 460 | return |
| 461 | } |
| 462 | who := "" |
| 463 | if kind == homeop.KindCreateTeam { |
| 464 | who = owner |
| 465 | } |
| 466 | if err := r.home.Confirm(homeop.Credential, who); err != nil { |
| 467 | r.t.Fatal(err) |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | func (r *rig) runState(want string) { |
| 472 | r.t.Helper() |
| 473 | db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)") |
| 474 | if err != nil { |
| 475 | r.t.Fatal(err) |
| 476 | } |
| 477 | defer db.Close() |
| 478 | var state, code string |
| 479 | if err := db.QueryRow("SELECT state,code FROM runs ORDER BY id DESC LIMIT 1").Scan(&state, &code); err != nil { |
| 480 | r.t.Fatal(err) |
| 481 | } |
| 482 | if got := strings.TrimSuffix(state+" "+code, " "); got != want { |
| 483 | r.t.Fatalf("latest run %q, want %q", got, want) |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | // throughPlanA records both Home preflights, initializes the directory |
| 488 | // and runs Plan A to awaiting-configuration, all through the command. |
| 489 | func (r *rig) throughPlanA() { |
| 490 | r.t.Helper() |
| 491 | r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") |
| 492 | r.ok(provision.InitializeAttestation+"\n", false, "initialize", "--apply") |
| 493 | r.confirm(homeop.KindInitialize) |
| 494 | r.ok("", false, "advance", "--run", r.latestRun(), "--apply") |
| 495 | r.runState("done") |
| 496 | r.tick(homeop.WindowLifetime * time.Second) |
| 497 | r.ok(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA, "--apply") |
| 498 | r.ok(owner+"\n", false, "plan-a", "--apply") |
| 499 | r.confirm(homeop.KindCreateTeam) |
| 500 | r.ok("", false, "advance", "--run", r.latestRun(), "--apply") |
| 501 | r.runState("done awaiting-configuration") |
| 502 | r.tick(homeop.WindowLifetime * time.Second) |
| 503 | } |
| 504 | |
| 505 | // configured writes app's keys, restarts it and records its delivery |
| 506 | // check: configure alone, with nothing typed. |
| 507 | func (r *rig) configured(app string) { |
| 508 | r.t.Helper() |
| 509 | a, _ := provision.AppBySlug(app) |
| 510 | if out := r.ok("", true, "configure", "--app", app, "--apply"); !strings.Contains(out, adopt.SayConfigured(adopt.CanonicalHost(a))) { |
| 511 | r.t.Fatalf("configure did not finish\n%s", out) |
| 512 | } |
| 513 | if !r.checked(app) { |
| 514 | r.t.Fatalf("configure recorded no delivery check for %s", app) |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | // checked reports whether status shows app's delivery check. |
| 519 | func (r *rig) checked(app string) bool { |
| 520 | r.t.Helper() |
| 521 | for _, line := range strings.Split(r.ok("", false, "status"), "\n") { |
| 522 | if strings.HasPrefix(line, app+": ") { |
| 523 | return strings.Contains(line, ", "+adopt.SayStatusDeliveryCheck) |
| 524 | } |
| 525 | } |
| 526 | r.t.Fatalf("status has no line for %s", app) |
| 527 | return false |
| 528 | } |
| 529 | |
| 530 | // rehearse walks every subcommand of the table in order. Each runs first |
| 531 | // without --apply, which must write nothing anywhere; then, where it |
| 532 | // writes, with --apply, which must write. |
| 533 | func rehearse(t *testing.T) *rig { |
| 534 | r := newRig(t) |
| 535 | cal, _ := provision.AppBySlug(adopt.CanaryApp) |
| 536 | |
| 537 | // Nothing exists yet: a dry run does not even create the state. |
| 538 | r.dry(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize) |
| 539 | if _, exists := r.rows(); exists { |
| 540 | t.Fatal("a dry run created the state database") |
| 541 | } |
| 542 | r.dry("", true, "preflight") |
| 543 | r.dry("", false, "status") |
| 544 | r.applied(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize) |
| 545 | |
| 546 | r.dry("", false, "initialize") |
| 547 | r.applied(provision.InitializeAttestation+"\n", false, "initialize") |
| 548 | r.confirm(homeop.KindInitialize) |
| 549 | run := r.latestRun() |
| 550 | r.dry("", false, "advance", "--run", run) |
| 551 | r.applied("", false, "advance", "--run", run) |
| 552 | r.runState("done") |
| 553 | r.tick(homeop.WindowLifetime * time.Second) |
| 554 | |
| 555 | r.dry(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA) |
| 556 | r.applied(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA) |
| 557 | r.dry("", false, "plan-a") |
| 558 | r.applied(owner+"\n", false, "plan-a") |
| 559 | r.confirm(homeop.KindCreateTeam) |
| 560 | run = r.latestRun() |
| 561 | r.dry("", false, "advance", "--run", run) |
| 562 | r.applied("", false, "advance", "--run", run) |
| 563 | r.runState("done awaiting-configuration") |
| 564 | r.tick(homeop.WindowLifetime * time.Second) |
| 565 | |
| 566 | r.dry("", true, "configure", "--app", adopt.CanaryApp) |
| 567 | r.applied("", true, "configure", "--app", adopt.CanaryApp) |
| 568 | if !r.checked(adopt.CanaryApp) { |
| 569 | t.Fatal("configure recorded no delivery check") |
| 570 | } |
| 571 | |
| 572 | r.dry("", true, "activate", "--apps", adopt.CanaryApp) |
| 573 | r.applied("", true, "activate", "--apps", adopt.CanaryApp) |
| 574 | r.confirm(homeop.KindAddApps) |
| 575 | run = r.latestRun() |
| 576 | r.dry("", true, "advance", "--run", run) |
| 577 | r.applied("", true, "advance", "--run", run) |
| 578 | r.runState("done") |
| 579 | r.tick(homeop.WindowLifetime * time.Second) |
| 580 | |
| 581 | // The rollback's dry run names the keys it would remove, the bundle |
| 582 | // and the host it would restart. |
| 583 | keys, host := adopt.AgentKeys(cal), adopt.CanonicalHost(cal) |
| 584 | if out := r.dry("", true, "rollback-config", "--app", adopt.CanaryApp); !strings.Contains(out, adopt.SayRollbackWould(keys, "default", host)) { |
| 585 | t.Fatalf("rollback-config without --apply did not preview\n%s", out) |
| 586 | } |
| 587 | r.applied("", true, "rollback-config", "--app", adopt.CanaryApp) |
| 588 | if out := r.dry("", true, "rollback-config", "--app", adopt.CanaryApp); !strings.Contains(out, adopt.SayRollbackNothing(host)) { |
| 589 | t.Fatalf("a finished rollback's dry run did not say so\n%s", out) |
| 590 | } |
| 591 | |
| 592 | r.dry("", false, "disable", "--app", adopt.CanaryApp) |
| 593 | r.applied(provision.AdoptionLabel+"\n", false, "disable", "--app", adopt.CanaryApp) |
| 594 | |
| 595 | r.dry("", true, "preflight") |
| 596 | r.dry("", false, "status") |
| 597 | return r |
| 598 | } |
| 599 | |
| 600 | func TestWritesNeedApply(t *testing.T) { |
| 601 | t.Parallel() |
| 602 | r := rehearse(t) |
| 603 | if r.carlos.AppWideRestarts() != 0 { |
| 604 | t.Fatal("the app-wide restart was called") |
| 605 | } |
| 606 | for _, a := range provision.Apps { |
| 607 | if a.Slug != adopt.CanaryApp && r.carlos.RestartCount(routeOf(a)) != 0 { |
| 608 | t.Fatalf("%s restarted", a.Slug) |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | // fileState is a file's bytes and mtime, or its absence. |
| 614 | type fileState struct { |
| 615 | exists bool |
| 616 | sum [32]byte |
| 617 | mtime time.Time |
| 618 | } |
| 619 | |
| 620 | func stateOf(t *testing.T, path string) fileState { |
| 621 | t.Helper() |
| 622 | fi, err := os.Stat(path) |
| 623 | if os.IsNotExist(err) { |
| 624 | return fileState{} |
| 625 | } |
| 626 | if err != nil { |
| 627 | t.Fatal(err) |
| 628 | } |
| 629 | b, err := os.ReadFile(path) |
| 630 | if err != nil { |
| 631 | t.Fatal(err) |
| 632 | } |
| 633 | return fileState{true, sha256.Sum256(b), fi.ModTime()} |
| 634 | } |
| 635 | |
| 636 | // untouched asserts the state's committed contents did not move: the |
| 637 | // file's bytes and mtime are the same, a WAL that existed is the same and |
| 638 | // one that did not is at most SQLite's empty one, there is no rollback |
| 639 | // journal, and nothing else appeared beside the state. SQLite's -shm |
| 640 | // coordination file may appear or change. |
| 641 | func (r *rig) untouched(before map[string]fileState) { |
| 642 | r.t.Helper() |
| 643 | after := r.files() |
| 644 | if after[""] != before[""] { |
| 645 | r.t.Fatal("a read-only run changed the state file") |
| 646 | } |
| 647 | empty := sha256.Sum256(nil) |
| 648 | if w := after["-wal"]; before["-wal"].exists && w != before["-wal"] || !before["-wal"].exists && w.exists && w.sum != empty { |
| 649 | r.t.Fatal("a read-only run changed the WAL") |
| 650 | } |
| 651 | if after["-journal"].exists { |
| 652 | r.t.Fatal("a read-only run left a rollback journal") |
| 653 | } |
| 654 | ents, err := os.ReadDir(r.dir) |
| 655 | if err != nil { |
| 656 | r.t.Fatal(err) |
| 657 | } |
| 658 | for _, e := range ents { |
| 659 | switch strings.TrimPrefix(e.Name(), filepath.Base(r.state)) { |
| 660 | case "", "-wal", "-shm": |
| 661 | default: |
| 662 | if e.Name() != filepath.Base(r.cfgPath) { |
| 663 | r.t.Fatalf("a read-only run left %s beside the state", e.Name()) |
| 664 | } |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | func (r *rig) files() map[string]fileState { |
| 670 | r.t.Helper() |
| 671 | m := map[string]fileState{} |
| 672 | for _, s := range []string{"", "-wal", "-shm", "-journal"} { |
| 673 | m[s] = stateOf(r.t, r.state+s) |
| 674 | } |
| 675 | return m |
| 676 | } |
| 677 | |
| 678 | // read-only runs: the dry runs that read the state, and status. |
| 679 | func (r *rig) readOnly() string { |
| 680 | r.t.Helper() |
| 681 | var out strings.Builder |
| 682 | out.WriteString(r.ok("", false, "status")) |
| 683 | out.WriteString(r.ok("", true, "preflight")) |
| 684 | out.WriteString(r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize)) |
| 685 | return out.String() |
| 686 | } |
| 687 | |
| 688 | func TestDryRunLeavesStateUntouched(t *testing.T) { |
| 689 | t.Parallel() |
| 690 | r := newRig(t) |
| 691 | r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") |
| 692 | |
| 693 | // Make the journal's migration pending again: its ledger rows and |
| 694 | // tables go, so any open by Alta's store would apply it to the file. |
| 695 | db, err := sql.Open("sqlite", "file:"+r.state+"?_pragma=busy_timeout(5000)") |
| 696 | if err != nil { |
| 697 | t.Fatal(err) |
| 698 | } |
| 699 | for _, q := range []string{ |
| 700 | "DELETE FROM rastrillo_migrations WHERE id LIKE 'adopt/%'", |
| 701 | "DROP TABLE adopt_home_preflights", "DROP TABLE adopt_baselines", "DROP TABLE adopt_writes", "DROP TABLE adopt_rollbacks", |
| 702 | "DROP TABLE adopt_afters", "DROP TABLE adopt_witnesses", "DROP TABLE adopt_checks", |
| 703 | "PRAGMA wal_checkpoint(TRUNCATE)", |
| 704 | } { |
| 705 | if _, err := db.Exec(q); err != nil { |
| 706 | t.Fatalf("%s: %v", q, err) |
| 707 | } |
| 708 | } |
| 709 | db.Close() |
| 710 | before := r.files() |
| 711 | if !before[""].exists || before["-wal"].exists || before["-shm"].exists { |
| 712 | t.Fatalf("setup: %+v", before) |
| 713 | } |
| 714 | out := r.readOnly() |
| 715 | r.untouched(before) |
| 716 | // The pending migration was applied to the copy, which the runs read. |
| 717 | if !strings.Contains(out, adopt.SayStatusPreflight(adopt.PhasePreInitialize, false)) { |
| 718 | t.Fatalf("status did not read the migrated copy\n%s", out) |
| 719 | } |
| 720 | |
| 721 | // Committed transactions still in the WAL, with another process |
| 722 | // holding the state open, are read too, and the WAL is untouched. |
| 723 | r.holdOpen(func(js *adopt.Store) { |
| 724 | if err := js.SaveHomePreflight(context.Background(), adopt.HomePreflight{Phase: adopt.PhasePrePlanA}); err != nil { |
| 725 | t.Fatal(err) |
| 726 | } |
| 727 | before := r.files() |
| 728 | if !before["-wal"].exists { |
| 729 | t.Fatal("setup: no WAL") |
| 730 | } |
| 731 | out := r.readOnly() |
| 732 | r.untouched(before) |
| 733 | if !strings.Contains(out, adopt.SayStatusPreflight(adopt.PhasePrePlanA, true)) { |
| 734 | t.Fatalf("status did not read the WAL\n%s", out) |
| 735 | } |
| 736 | }) |
| 737 | } |
| 738 | |
| 739 | func TestInitializeRefusedWithoutHomePreflight(t *testing.T) { |
| 740 | t.Parallel() |
| 741 | r := newRig(t) |
| 742 | r.refused("home-preflight-missing", provision.InitializeAttestation+"\n", false, "initialize", "--apply") |
| 743 | if r.plans.Load() != 0 || len(r.home.Requests()) != 0 || r.runCount() != 0 { |
| 744 | t.Fatal("a refused initialize reached Home or opened a run") |
| 745 | } |
| 746 | // The same command, once the attestation is recorded, opens the plan. |
| 747 | r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") |
| 748 | r.applied(provision.InitializeAttestation+"\n", false, "initialize") |
| 749 | if r.plans.Load() != 1 { |
| 750 | t.Fatalf("plans %d", r.plans.Load()) |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | func TestPlanARefusedWithoutHomePreflight(t *testing.T) { |
| 755 | t.Parallel() |
| 756 | r := newRig(t) |
| 757 | r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") |
| 758 | r.ok(provision.InitializeAttestation+"\n", false, "initialize", "--apply") |
| 759 | r.confirm(homeop.KindInitialize) |
| 760 | r.ok("", false, "advance", "--run", r.latestRun(), "--apply") |
| 761 | r.tick(homeop.WindowLifetime * time.Second) |
| 762 | before := r.writes() |
| 763 | r.refused("home-preflight-missing", owner+"\n", false, "plan-a", "--apply") |
| 764 | if after := r.writes(); after != before { |
| 765 | t.Fatalf("a refused plan-a wrote: %+v %+v", before, after) |
| 766 | } |
| 767 | r.ok(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA, "--apply") |
| 768 | r.applied(owner+"\n", false, "plan-a") |
| 769 | } |
| 770 | |
| 771 | // holdOpen opens the state as another process would and runs during |
| 772 | // while it holds it open. |
| 773 | func (r *rig) holdOpen(during func(js *adopt.Store)) { |
| 774 | r.t.Helper() |
| 775 | db, err := provision.OpenDB(r.state) |
| 776 | if err != nil { |
| 777 | r.t.Fatal(err) |
| 778 | } |
| 779 | defer db.Close() |
| 780 | dek, _ := base64.StdEncoding.DecodeString(r.dek) |
| 781 | ps, err := provision.NewStore(context.Background(), db, dek, r.clock, adopt.Schema) |
| 782 | if err != nil { |
| 783 | r.t.Fatal(err) |
| 784 | } |
| 785 | js, err := adopt.NewStore(ps) |
| 786 | if err != nil { |
| 787 | r.t.Fatal(err) |
| 788 | } |
| 789 | during(js) |
| 790 | } |
| 791 | |
| 792 | // Plan C waits on Plan B alone (Paul, 2026-11-17): activate refuses every |
| 793 | // app but the canary, before reading CARLOS, until calendar is active, |
| 794 | // and says what comes first; then the same command opens Plan C with no |
| 795 | // live check. |
| 796 | func TestActivateNonCanaryRefusedBeforePlanB(t *testing.T) { |
| 797 | t.Parallel() |
| 798 | r := newRig(t) |
| 799 | r.throughPlanA() |
| 800 | r.configured("docs") |
| 801 | r.configured(adopt.CanaryApp) |
| 802 | refusedNow := func(why string) { |
| 803 | t.Helper() |
| 804 | before, reads := r.writes(), len(r.carlos.Requests()) |
| 805 | for _, args := range [][]string{{"--apps", "docs", "--apply"}, {"--apps", "docs"}, {"--apps", "calendar,docs", "--apply"}} { |
| 806 | out := r.refused("refused: canary-not-active", "", true, append([]string{"activate"}, args...)...) |
| 807 | if !strings.Contains(out, adopt.HintCanary) { |
| 808 | t.Fatalf("%s: activate %v: no hint\n%s", why, args, out) |
| 809 | } |
| 810 | } |
| 811 | if after := r.writes(); after != before { |
| 812 | t.Fatalf("%s: a refused activate wrote: %+v %+v", why, before, after) |
| 813 | } |
| 814 | if n := len(r.carlos.Requests()); n != reads { |
| 815 | t.Fatalf("%s: a refused activate read CARLOS %d times", why, n-reads) |
| 816 | } |
| 817 | } |
| 818 | refusedNow("before Plan B") |
| 819 | |
| 820 | // Plan B opened but not yet through: still refused. |
| 821 | r.applied("", true, "activate", "--apps", adopt.CanaryApp) |
| 822 | refusedNow("Plan B open") |
| 823 | r.confirm(homeop.KindAddApps) |
| 824 | r.ok("", true, "advance", "--run", r.latestRun(), "--apply") |
| 825 | r.runState("done") |
| 826 | r.tick(homeop.WindowLifetime * time.Second) |
| 827 | |
| 828 | r.applied("", true, "activate", "--apps", "docs") |
| 829 | r.confirm(homeop.KindAddApps) |
| 830 | r.ok("", true, "advance", "--run", r.latestRun(), "--apply") |
| 831 | r.runState("done") |
| 832 | if st := r.home.InstanceState("docs"); st != "live" { |
| 833 | t.Fatalf("docs is %q at Home", st) |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | // A process that died after the after snapshot and before its delivery |
| 838 | // check is resumed by configure alone: no second write or restart, and |
| 839 | // the check recorded. |
| 840 | func TestConfigureResumesDeliveryCheck(t *testing.T) { |
| 841 | t.Parallel() |
| 842 | r := newRig(t) |
| 843 | r.throughPlanA() |
| 844 | r.configured("docs") |
| 845 | // The check lost, as if the process had died before saving it. |
| 846 | db, err := sql.Open("sqlite", "file:"+r.state+"?_pragma=busy_timeout(5000)") |
| 847 | if err != nil { |
| 848 | t.Fatal(err) |
| 849 | } |
| 850 | if _, err := db.Exec("DELETE FROM adopt_witnesses WHERE app='docs'"); err != nil { |
| 851 | t.Fatal(err) |
| 852 | } |
| 853 | db.Close() |
| 854 | if r.checked("docs") { |
| 855 | t.Fatal("setup: the check is still there") |
| 856 | } |
| 857 | docs, _ := provision.AppBySlug("docs") |
| 858 | puts, restarts := r.writes().puts, r.carlos.RestartCount(routeOf(docs)) |
| 859 | r.configured("docs") |
| 860 | if r.writes().puts != puts || r.carlos.RestartCount(routeOf(docs)) != restarts { |
| 861 | t.Fatal("the resume wrote or restarted again") |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | // A write that landed before its restart is resumed by configure alone, |
| 866 | // and the resume restarts nothing once the canonical domain has left the |
| 867 | // record the baseline saw (Astra review, 2026-11-18). |
| 868 | func TestConfigureResumeRestartsNothingAfterTheClaimMoved(t *testing.T) { |
| 869 | t.Parallel() |
| 870 | const other = "docs-2.bds.oncarlos.com" |
| 871 | docs, _ := provision.AppBySlug("docs") |
| 872 | cases := map[string]struct { |
| 873 | edit func(r *rig) |
| 874 | code string |
| 875 | }{ |
| 876 | "re-pointed": {func(r *rig) { |
| 877 | r.carlos.AddInstance(carlosop.Instance{Host: other, App: "docs", Slug: "s-docs-2", Channel: "stable", Region: "eu"}) |
| 878 | r.carlos.AttachDomain("docs", adopt.CanonicalHost(docs), other, "live") |
| 879 | }, "restart-binding-changed"}, |
| 880 | "detached": {func(r *rig) { r.carlos.DetachDomain("docs", adopt.CanonicalHost(docs)) }, "restart-binding-domain-missing"}, |
| 881 | } |
| 882 | for name, tc := range cases { |
| 883 | t.Run(name, func(t *testing.T) { |
| 884 | t.Parallel() |
| 885 | r := newRig(t) |
| 886 | r.throughPlanA() |
| 887 | // The write lands; the restart that follows it does not. |
| 888 | r.carlos.FailRestart(http.StatusServiceUnavailable) |
| 889 | r.refused("", "", true, "configure", "--app", "docs", "--apply") |
| 890 | r.carlos.FailRestart(0) |
| 891 | puts := r.writes().puts |
| 892 | if puts == 0 { |
| 893 | t.Fatal("setup: the write did not land") |
| 894 | } |
| 895 | tc.edit(r) |
| 896 | out := r.refused("", "", true, "configure", "--app", "docs", "--apply") |
| 897 | if !strings.Contains(out, tc.code) { |
| 898 | t.Fatalf("the resume did not name %s\n%s", tc.code, out) |
| 899 | } |
| 900 | if n := r.carlos.RestartCount(routeOf(docs)) + r.carlos.RestartCount(other); n != 0 { |
| 901 | t.Fatalf("the resume restarted %d times", n) |
| 902 | } |
| 903 | if r.writes().puts != puts { |
| 904 | t.Fatal("the resume wrote again") |
| 905 | } |
| 906 | }) |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | // A served release that is not the reviewed one is refused before |
| 911 | // anything is written (Astra review, 2026-11-17): by preflight, by |
| 912 | // configure's dry run and by configure itself, which journals and sends |
| 913 | // nothing. Activation stays refused. |
| 914 | func TestConfigureRefusesUnreviewedReleaseBeforeWriting(t *testing.T) { |
| 915 | t.Parallel() |
| 916 | r := newRig(t) |
| 917 | r.throughPlanA() |
| 918 | other := sha256.Sum256([]byte("v9.9.9")) |
| 919 | r.cfg["artifacts"].(map[string]string)[adopt.CanaryApp] = hex.EncodeToString(other[:]) |
| 920 | r.writeConfig() |
| 921 | if out := r.refused("preflight-refused", "", true, "preflight"); !strings.Contains(out, adopt.SayActivateApp(adopt.CanaryApp, []string{"artifact-mismatch"})) { |
| 922 | t.Fatalf("preflight did not name the release\n%s", out) |
| 923 | } |
| 924 | before := r.writes() |
| 925 | r.refused("artifact-mismatch", "", true, "configure", "--app", adopt.CanaryApp) |
| 926 | r.refused("artifact-mismatch", "", true, "configure", "--app", adopt.CanaryApp, "--apply") |
| 927 | if after := r.writes(); after != before { |
| 928 | t.Fatalf("a refused configure wrote: %+v %+v", before, after) |
| 929 | } |
| 930 | if r.checked(adopt.CanaryApp) { |
| 931 | t.Fatal("a delivery check was recorded for an unreviewed release") |
| 932 | } |
| 933 | r.refused("activate-refused", "", true, "activate", "--apps", adopt.CanaryApp) |
| 934 | } |
| 935 | |
| 936 | // Docs, slides, calls and memoria were redeployed to releases Paul |
| 937 | // approved after configure had landed their writes and recorded their |
| 938 | // delivery checks (2026-11-19). Activation refuses the stale checks; |
| 939 | // configure, run again, checks each app on its new release, writing and |
| 940 | // restarting nothing, and activation then goes through. |
| 941 | func TestConfigureRechecksApprovedRedeploy(t *testing.T) { |
| 942 | t.Parallel() |
| 943 | r := newRig(t) |
| 944 | r.throughPlanA() |
| 945 | r.configured(adopt.CanaryApp) |
| 946 | r.applied("", true, "activate", "--apps", adopt.CanaryApp) |
| 947 | r.confirm(homeop.KindAddApps) |
| 948 | r.ok("", true, "advance", "--run", r.latestRun(), "--apply") |
| 949 | r.runState("done") |
| 950 | r.tick(homeop.WindowLifetime * time.Second) |
| 951 | apps := []string{"docs", "slides", "calls", "memoria"} |
| 952 | for _, a := range apps { |
| 953 | r.configured(a) |
| 954 | } |
| 955 | for _, a := range apps { |
| 956 | r.redeploy(a, "v1.5.0-2-gabcdef1", true) |
| 957 | } |
| 958 | list := strings.Join(apps, ",") |
| 959 | if out := r.refused("activate-refused", "", true, "activate", "--apps", list); !strings.Contains(out, "delivery-check-superseded") || !strings.Contains(out, "not-delivered") { |
| 960 | t.Fatalf("activate did not refuse the stale checks as production did\n%s", out) |
| 961 | } |
| 962 | |
| 963 | before := r.writes() |
| 964 | for _, a := range apps { |
| 965 | r.configured(a) |
| 966 | } |
| 967 | after := r.writes() |
| 968 | if after.puts != before.puts || after.restarts != before.restarts || after.appWide != before.appWide || after.plans != before.plans || after.ops != before.ops { |
| 969 | t.Fatalf("the re-check wrote or restarted: %+v %+v", before, after) |
| 970 | } |
| 971 | |
| 972 | r.applied("", true, "activate", "--apps", list) |
| 973 | r.confirm(homeop.KindAddApps) |
| 974 | r.ok("", true, "advance", "--run", r.latestRun(), "--apply") |
| 975 | r.runState("done") |
| 976 | for _, a := range apps { |
| 977 | if st := r.home.InstanceState(a); st != "live" { |
| 978 | t.Fatalf("%s is %q at Home", a, st) |
| 979 | } |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | // A redeploy to a release Paul did not approve keeps today's refusal: |
| 984 | // configure records no check, and activation stays refused. |
| 985 | func TestConfigureRefusesUnapprovedRedeploy(t *testing.T) { |
| 986 | t.Parallel() |
| 987 | r := newRig(t) |
| 988 | r.throughPlanA() |
| 989 | r.configured(adopt.CanaryApp) |
| 990 | r.redeploy(adopt.CanaryApp, "v1.5.0", false) |
| 991 | before := r.writes() |
| 992 | out := r.refused("check-not-delivered", "", true, "configure", "--app", adopt.CanaryApp, "--apply") |
| 993 | if !strings.Contains(out, "adopt: the served version changed") || !strings.Contains(out, "redeploy-artifact-mismatch") { |
| 994 | t.Fatalf("configure did not refuse the unapproved release\n%s", out) |
| 995 | } |
| 996 | if after := r.writes(); after != before { |
| 997 | t.Fatalf("a refused re-check wrote: %+v %+v", before, after) |
| 998 | } |
| 999 | r.refused("activate-refused", "", true, "activate", "--apps", adopt.CanaryApp) |
| 1000 | } |
| 1001 | |
| 1002 | // The witness and the live checks are gone (Paul, 2026-11-17): their |
| 1003 | // commands are unknown, and nothing is opened or written. |
| 1004 | func TestRemovedCommandsAreUnknown(t *testing.T) { |
| 1005 | t.Parallel() |
| 1006 | r := newRig(t) |
| 1007 | for _, args := range [][]string{{"witness", "--app", "docs", "--apply"}, {"live", "--event", "7", "--apply"}} { |
| 1008 | code, out := r.cli("", true, args...) |
| 1009 | if code != 2 || !strings.Contains(out, adopt.Usage) { |
| 1010 | t.Fatalf("alta-adopt %s: exit %d\n%s", args[0], code, out) |
| 1011 | } |
| 1012 | if strings.Contains(adopt.Usage, " "+args[0]+" ") { |
| 1013 | t.Fatalf("the usage still lists %s", args[0]) |
| 1014 | } |
| 1015 | } |
| 1016 | if _, exists := r.rows(); exists { |
| 1017 | t.Fatal("an unknown command created the state") |
| 1018 | } |
| 1019 | } |
| 1020 | |
| 1021 | func TestConfigFileModeRefused(t *testing.T) { |
| 1022 | t.Parallel() |
| 1023 | r := newRig(t) |
| 1024 | for _, mode := range []os.FileMode{0o644, 0o640, 0o604, 0o660, 0o700} { |
| 1025 | if err := os.Chmod(r.cfgPath, mode); err != nil { |
| 1026 | t.Fatal(err) |
| 1027 | } |
| 1028 | r.refused(adopt.RefuseConfigMode, "", true, "status") |
| 1029 | r.refused(adopt.RefuseConfigMode, counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply") |
| 1030 | } |
| 1031 | if _, exists := r.rows(); exists || r.plans.Load() != 0 || len(r.carlos.Requests()) != 0 { |
| 1032 | t.Fatal("a refused config reached something") |
| 1033 | } |
| 1034 | if err := os.Chmod(r.cfgPath, 0o600); err != nil { |
| 1035 | t.Fatal(err) |
| 1036 | } |
| 1037 | r.ok("", false, "status") |
| 1038 | } |
| 1039 | |
| 1040 | func TestConfigFileOtherOwnerRefused(t *testing.T) { |
| 1041 | t.Parallel() |
| 1042 | if err := ownedByUser(fakeStat{uid: uint32(os.Getuid()) + 1}); err == nil { |
| 1043 | t.Fatal("a file another user owns was accepted") |
| 1044 | } |
| 1045 | if err := ownedByUser(fakeStat{uid: uint32(os.Getuid())}); err != nil { |
| 1046 | t.Fatalf("own file refused: %v", err) |
| 1047 | } |
| 1048 | } |
| 1049 | |
| 1050 | func TestTokenFDRefusesStandardStreams(t *testing.T) { |
| 1051 | t.Parallel() |
| 1052 | r := newRig(t) |
| 1053 | for _, fd := range []string{"0", "1", "2"} { |
| 1054 | code, out := r.cli("", false, "preflight", "--carlos-token-fd", fd) |
| 1055 | if code == 0 || !strings.Contains(out, adopt.RefuseTokenFD) { |
| 1056 | t.Fatalf("fd %s: exit %d\n%s", fd, code, out) |
| 1057 | } |
| 1058 | } |
| 1059 | if len(r.carlos.Requests()) != 0 { |
| 1060 | t.Fatal("the console was reached") |
| 1061 | } |
| 1062 | } |
| 1063 | |
| 1064 | // secrets are every value no output may carry. |
| 1065 | func (r *rig) secrets() map[string]string { |
| 1066 | r.t.Helper() |
| 1067 | s := map[string]string{ |
| 1068 | "token": string(r.carlos.Token()), "dek": r.dek, "operator key": r.opKey, "prefilter": r.pre, |
| 1069 | "owner": owner, "vd1 digest": "vd1:", "cv1 version": "cv1:", "plain value": plainCanary, |
| 1070 | "agent issuer value": adopt.Issuer, "home issuer value": adopt.HomeIssuerOrigin, |
| 1071 | } |
| 1072 | if _, sqid, ok := r.home.Team(provision.AdoptionLabel); ok { |
| 1073 | s["team sqid"] = sqid |
| 1074 | } |
| 1075 | return s |
| 1076 | } |
| 1077 | |
| 1078 | // binding reads the environment_binding the activation sent, from the |
| 1079 | // held request. |
| 1080 | func (r *rig) binding(app string) string { |
| 1081 | r.t.Helper() |
| 1082 | db, err := provision.OpenDB(r.state) |
| 1083 | if err != nil { |
| 1084 | r.t.Fatal(err) |
| 1085 | } |
| 1086 | defer db.Close() |
| 1087 | dek, _ := base64.StdEncoding.DecodeString(r.dek) |
| 1088 | ps, err := provision.NewStore(context.Background(), db, dek, r.clock, adopt.Schema) |
| 1089 | if err != nil { |
| 1090 | r.t.Fatal(err) |
| 1091 | } |
| 1092 | req, ok, err := ps.LastRequest(context.Background(), provision.AdoptionLabel, app, "activate") |
| 1093 | if err != nil || !ok { |
| 1094 | r.t.Fatalf("no activation request: %v", err) |
| 1095 | } |
| 1096 | var w struct { |
| 1097 | Input struct { |
| 1098 | Evidence struct { |
| 1099 | Binding string `json:"environment_binding"` |
| 1100 | } `json:"evidence"` |
| 1101 | } `json:"operation_input"` |
| 1102 | } |
| 1103 | if err := json.Unmarshal(req.Bytes, &w); err != nil || w.Input.Evidence.Binding == "" { |
| 1104 | r.t.Fatalf("activation request: %v", err) |
| 1105 | } |
| 1106 | return w.Input.Evidence.Binding |
| 1107 | } |
| 1108 | |
| 1109 | func TestOutputScrub(t *testing.T) { |
| 1110 | t.Parallel() |
| 1111 | r := rehearse(t) |
| 1112 | secrets := r.secrets() |
| 1113 | secrets["environment binding"] = r.binding(adopt.CanaryApp) |
| 1114 | // Refusals and help print too. |
| 1115 | r.cli("", false) |
| 1116 | r.cli("", false, "help") |
| 1117 | r.cli("not-an-oficina-app\n", false, "disable", "--app", adopt.CanaryApp, "--apply") |
| 1118 | r.cli("", true, "configure", "--app", "nope") |
| 1119 | out := r.out.String() |
| 1120 | if out == "" { |
| 1121 | t.Fatal("no output captured") |
| 1122 | } |
| 1123 | for name, v := range secrets { |
| 1124 | if v != "" && strings.Contains(out, v) { |
| 1125 | t.Errorf("output carries the %s", name) |
| 1126 | } |
| 1127 | } |
| 1128 | } |
| 1129 | |
| 1130 | func TestTokenNeverInEnvOrDisk(t *testing.T) { |
| 1131 | t.Parallel() |
| 1132 | r := newRig(t) |
| 1133 | token := r.carlos.Token() |
| 1134 | // A token read for a run that stops before reaching CARLOS is zeroed |
| 1135 | // too. |
| 1136 | if err := os.Chmod(r.cfgPath, 0o644); err != nil { |
| 1137 | t.Fatal(err) |
| 1138 | } |
| 1139 | r.refused(adopt.RefuseConfigMode, "", true, "preflight") |
| 1140 | if err := os.Chmod(r.cfgPath, 0o600); err != nil { |
| 1141 | t.Fatal(err) |
| 1142 | } |
| 1143 | r.throughPlanA() |
| 1144 | r.ok("", true, "preflight") |
| 1145 | r.configured("docs") |
| 1146 | r.ok("", true, "status") |
| 1147 | if n := len(r.carlos.Requests()); n == 0 { |
| 1148 | t.Fatal("the token was never used") |
| 1149 | } |
| 1150 | for _, kv := range os.Environ() { |
| 1151 | if strings.Contains(kv, string(token)) { |
| 1152 | t.Fatal("the token is in the environment") |
| 1153 | } |
| 1154 | } |
| 1155 | err := filepath.WalkDir(r.dir, func(path string, d os.DirEntry, err error) error { |
| 1156 | if err != nil || d.IsDir() { |
| 1157 | return err |
| 1158 | } |
| 1159 | b, err := os.ReadFile(path) |
| 1160 | if err != nil { |
| 1161 | return err |
| 1162 | } |
| 1163 | if bytes.Contains(b, token) { |
| 1164 | t.Errorf("the token is on disk in %s", filepath.Base(path)) |
| 1165 | } |
| 1166 | return nil |
| 1167 | }) |
| 1168 | if err != nil { |
| 1169 | t.Fatal(err) |
| 1170 | } |
| 1171 | if strings.Contains(r.out.String(), string(token)) { |
| 1172 | t.Fatal("the token was printed") |
| 1173 | } |
| 1174 | if len(r.tokens) == 0 { |
| 1175 | t.Fatal("no token was read") |
| 1176 | } |
| 1177 | for i, b := range r.tokens { |
| 1178 | if len(b) == 0 || !bytes.Equal(b, make([]byte, len(b))) { |
| 1179 | t.Fatalf("token buffer %d was not zeroed", i) |
| 1180 | } |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | type fakeStat struct{ uid uint32 } |
| 1185 | |
| 1186 | func (f fakeStat) Owner() (uint32, bool) { return f.uid, true } |
| 1187 | |