package thin import ( "bytes" "context" "encoding/json" "errors" "io/fs" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" ) // The deploy key the fake carlos mints: assembled so the repository's own // scan does not read it as a credential. var fakeDeployToken = strings.Join([]string{"cst", "Qm9vZ3lXb29naWU", "x7Lp2Rk9"}, "_") // fakeCarlosScript writes a carlos that records each run (its argv, one // argument per line, its working directory and its environment) and acts // as the real one does for the five templates: accounts list prints the // file accounts beside it; apps list the file apps; services create // prints its minted line and one CARLOS_SERVICE_TOKEN line (or fails when // a file mintfail is there); deploy serves the folder it was given and // prints the live line (or fails, making nothing, when a file fail is // there, or makes the app and then fails when a file halffail is). func fakeCarlosScript(t *testing.T, dir, live string) (bin, calls, served string) { t.Helper() bin, calls, served = filepath.Join(dir, "carlos"), filepath.Join(dir, "calls"), filepath.Join(dir, "served") apps, accounts := filepath.Join(dir, "apps"), filepath.Join(dir, "accounts") if err := os.WriteFile(apps, []byte("using https://console.carloku.com as paul@keymail.dev\nno apps in this account\n"), 0o644); err != nil { t.Fatal(err) } if err := os.WriteFile(accounts, []byte("NAME SQID ROLE\npaulca kmnpq owner\noficina bcdfg owner\nshared hjkmn member\n"), 0o644); err != nil { t.Fatal(err) } script := "#!/bin/sh\n" + "{ echo CALL; for a in \"$@\"; do printf 'ARG %s\\n' \"$a\"; done; printf 'PWD %s\\n' \"$(pwd)\"; env | sort | sed 's/^/ENV /'; } >> '" + calls + "'\n" + "if [ \"$1\" = accounts ]; then cat '" + accounts + "'; exit 0; fi\n" + "if [ \"$1\" = apps ]; then cat '" + apps + "'; exit 0; fi\n" + "if [ \"$1\" = services ]; then\n" + " if [ -e '" + filepath.Join(dir, "mintfail") + "' ]; then echo 'services create: unexpected response (status 502)'; exit 1; fi\n" + " for last in \"$@\"; do :; done\n" + " echo 'using https://console.carloku.com as paul@keymail.dev'\n" + " printf 'minted service:%s/%s (role deploy, app %s, rungs edge)\\n\\n' \"${10}\" \"$last\" \"$6\"\n" + " printf ' CARLOS_SERVICE_TOKEN=%s\\n\\n' '" + fakeDeployToken + "'\n" + " exit 0\n" + "fi\n" + "if [ -e '" + filepath.Join(dir, "fail") + "' ]; then echo 'deploy: upload failed'; exit 1; fi\n" + "if [ -e '" + filepath.Join(dir, "halffail") + "' ]; then printf 'using https://console.carloku.com as p@x\\nsite-sample live\\n' > '" + apps + "'; echo 'deploy: ship failed'; exit 1; fi\n" + "for last in \"$@\"; do :; done\n" + "rm -rf '" + served + "' && cp -R \"$last\" '" + served + "'\n" + "echo \"deploying " + live + "\"\n" + "printf '\\033[32mlive\\033[0m %s\\n' '" + live + "'\n" if err := os.WriteFile(bin, []byte(script), 0o755); err != nil { t.Fatal(err) } return bin, calls, served } // carlosRun is one recorded run of the fake carlos. type carlosRun struct { args []string pwd string env []string } func carlosRuns(t *testing.T, calls string) []carlosRun { t.Helper() raw, err := os.ReadFile(calls) if errors.Is(err, os.ErrNotExist) { return nil } if err != nil { t.Fatal(err) } var out []carlosRun for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") { switch { case line == "CALL": out = append(out, carlosRun{}) case strings.HasPrefix(line, "ARG "): out[len(out)-1].args = append(out[len(out)-1].args, strings.TrimPrefix(line, "ARG ")) case strings.HasPrefix(line, "PWD "): out[len(out)-1].pwd = strings.TrimPrefix(line, "PWD ") case strings.HasPrefix(line, "ENV "): out[len(out)-1].env = append(out[len(out)-1].env, strings.TrimPrefix(line, "ENV ")) } } return out } func (r carlosRun) envOf(key string) (string, bool) { for _, kv := range r.env { if v, ok := strings.CutPrefix(kv, key+"="); ok { return v, true } } return "", false } func verbsOf(runs []carlosRun) []string { var out []string for _, r := range runs { out = append(out, strings.Join(r.args[:2], " ")) } return out } // siteRig is a remote whose default branch holds the merged commit of a // website task (and a task branch beside it), an Engineer with CARLOS // sites through the fake carlos and the person's login, and a marker // origin that serves what carlos was last given. type siteRig struct { e *Engineer r stepRow merged string unmerged string bin string calls string apps string creds string planted string logs *bytes.Buffer confirms []string } const ( rigConsole = "console.carloku.com" rigSqid = "kmnpq" rigName = "paulca" rigApp = "site-sample" rigKeyName = "eq-sample-ab12" ) // target is a dispatch for the rig's place in mode. func rigTarget(mode string) *wire.PublishDispatch { d := &wire.PublishDispatch{App: rigApp, Into: "main", Console: rigConsole, Account: rigSqid, AccountName: rigName, Place: "pl_1", PlaceRevision: 1, BindingRevision: 1, Destination: wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp), Mode: mode} if mode != wire.SitePublish { d.DeployName = rigKeyName } return d } func newSiteRig(t *testing.T, files map[string]string) *siteRig { t.Helper() root := t.TempDir() work := filepath.Join(root, "seed") gitOut(t, root, "init", "-q", "-b", "main", work) os.WriteFile(filepath.Join(work, "README.md"), []byte("sample\n"), 0o644) gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "base") gitOut(t, work, "checkout", "-q", "-b", "equipo/tk1-quick-site") for p, body := range files { os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0o755) os.WriteFile(filepath.Join(work, p), []byte(body), 0o644) } gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "site") gitOut(t, work, "checkout", "-q", "main") gitOut(t, work, "merge", "-q", "--no-ff", "-m", "Merge the site", "equipo/tk1-quick-site") merged := gitOut(t, work, "rev-parse", "HEAD") // A commit on another branch only: never on the default branch. gitOut(t, work, "checkout", "-q", "-b", "equipo/tk2-other") os.WriteFile(filepath.Join(work, "site", "extra.html"), []byte("

not merged

\n"), 0o644) gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "unmerged") unmerged := gitOut(t, work, "rev-parse", "HEAD") remote := filepath.Join(root, "remote.git") gitOut(t, root, "clone", "-q", "--bare", work, remote) for _, d := range []string{"state", "work", "bin", "home/.carlos", ".carlos", "state/.carlos"} { os.MkdirAll(filepath.Join(root, d), 0o700) } // The person's own configuration, where carlos would find it walking // up from the runner's folders: another console and account. planted := `{"console": "https://console.evil.example", "account": "elsewhere"}` os.WriteFile(filepath.Join(root, ".carlos", "config"), []byte(planted), 0o600) os.WriteFile(filepath.Join(root, "state", ".carlos", "config"), []byte(planted), 0o600) creds := filepath.Join(root, "home", ".carlos", "credentials") os.WriteFile(creds, []byte(`{"version":1,"credentials":[{"console":"https://console.carloku.com","address":"p@x","token":"login-secret","expires_at":"2999-01-01T00:00:00Z"}]}`), 0o600) s, err := OpenState(context.Background(), filepath.Join(root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) bin, calls, served := fakeCarlosScript(t, filepath.Join(root, "bin"), "https://site-sample.bds.oncarlos.com") origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/"+siteMarker { http.NotFound(w, r) return } http.ServeFile(w, r, filepath.Join(served, siteMarker)) })) t.Cleanup(origin.Close) rig := &siteRig{merged: merged, unmerged: unmerged, bin: bin, calls: calls, apps: filepath.Join(root, "bin", "apps"), creds: creds, planted: planted, logs: &bytes.Buffer{}} f := &hubForge{dir: remote} check := func(purpose string) func(context.Context, string, int64, string, string) error { return func(_ context.Context, step string, attempt int64, digest, destination string) error { rig.confirms = append(rig.confirms, purpose+":"+step+"/"+itoa(attempt)+"/"+digest+"/"+destination) return nil } } e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test", Site: &SiteOptions{Carlos: bin, Credentials: creds, State: filepath.Join(root, "state", "site"), URL: func(string) string { return origin.URL }}, ConfirmPublish: check("publish"), ConfirmMint: check("mint")} e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", filepath.Join(root, "work"), filepath.Join(root, "state"), s e.O.Runner.Executable = previewScannerFixture(t) e.O.Logger = slog.New(slog.NewTextHandler(rig.logs, &slog.HandlerOptions{Level: slog.LevelDebug})) rig.e = e rig.r = stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s_pub1", Attempt: 1, Specialist: wire.SpecialistPublish, Repo: "amadan.net/paulca/sample", Branch: "equipo/tk1-quick-site", Title: "Quick site", CandidateSHA: merged, Publish: rigTarget(wire.SiteSetup)}} if err := s.AcceptDispatch(context.Background(), "d1", rig.r.DispatchCommand); err != nil { t.Fatal(err) } previewVerifyFor, previewVerifyEvery = 300*time.Millisecond, 50*time.Millisecond return rig } // step is the rig's step in mode with id. func (rig *siteRig) step(id, mode string) stepRow { r := rig.r r.StepID, r.Publish = id, rigTarget(mode) return r } // noSecretOutsideKeys: the deploy key's secret is only in its key file: // never in a report, the logs, argv, or any other file of the state. func (rig *siteRig) noSecretOutsideKeys(t *testing.T, reports ...wire.StepReport) { t.Helper() for _, rep := range reports { raw, _ := json.Marshal(rep) if strings.Contains(string(raw), fakeDeployToken) { t.Fatalf("the secret is in a report: %s", raw) } } if strings.Contains(rig.logs.String(), fakeDeployToken) || strings.Contains(rig.logs.String(), "login-secret") { t.Fatalf("the secret is in the logs: %s", rig.logs) } for _, run := range carlosRuns(t, rig.calls) { if strings.Contains(strings.Join(run.args, " "), fakeDeployToken) { t.Fatalf("the secret is in argv %q", run.args) } } keys := filepath.Join(rig.e.Site.State, "keys") filepath.WalkDir(rig.e.O.Runner.StateDir, func(p string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() || strings.HasPrefix(p, keys+string(filepath.Separator)) { return nil } if raw, err := os.ReadFile(p); err == nil && bytes.Contains(raw, []byte(fakeDeployToken)) { t.Fatalf("the secret is in %s", p) } return nil }) } var quickSite = map[string]string{ "release/preview.json": `{"output": "site"}`, "site/index.html": "

Quick site

\n", "site/style.css": "body{margin:0}\n", "site/_headers": "/*\n Cache-Control: max-age=60\n", "src/kept-out.txt": "not published\n", } // TestSiteSetupThenPublish: a setup exports the merged commit's site from // git objects, scans it, reports it built; for a name this runner has no // record of, reads the account's apps with the person's login (the name // must be free); deploys with the login behind its publish check; then // behind its mint check mints the app's edge-only deploy key, stored 0600 // and reported only as held. Every command has fixed flags naming the // place's sqid and console, from an empty private directory whose // environment holds only what it needs. The next publish deploys with the // key alone: the login is not in its environment. The project's own // _headers is published; Equipo adds none. The secret is nowhere else. func TestSiteSetupThenPublish(t *testing.T) { rig := newSiteRig(t, quickSite) var built *wire.PublishResult rep := rig.e.Exec(context.Background(), rig.r, func(p wire.StepReport) { if p.Publish != nil { built = p.Publish } }) if built == nil || built.Phase != wire.PublishBuilt || built.Files != 3 || len(built.Digest) != 64 { t.Fatalf("built %+v", built) } if rep.State != wire.StepDone || rep.Reason != "" || rep.Publish == nil || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.App != rigApp || rep.Publish.Digest != built.Digest || rep.Publish.URL != "https://site-sample.bds.oncarlos.com/" || !rep.Publish.DeployHeld { t.Fatalf("report %+v %+v", rep, rep.Publish) } dest := wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp) if want := []string{"publish:s_pub1/1/" + built.Digest + "/" + dest, "mint:s_pub1/1/" + built.Digest + "/" + dest}; !slices.Equal(rig.confirms, want) { t.Fatalf("checks %v\nwant %v", rig.confirms, want) } runs := carlosRuns(t, rig.calls) if got := verbsOf(runs); !slices.Equal(got, []string{"apps list", "deploy --kind", "services create"}) { t.Fatalf("runs %v", got) } origin := "https://" + rigConsole if want := []string{"apps", "list", "--account-id", rigSqid, "--console", origin}; !slices.Equal(runs[0].args, want) { t.Fatalf("list argv %q", runs[0].args) } stage := runs[1].args[len(runs[1].args)-1] version := "s-" + rig.merged[:12] + "-pub1-1" if want := []string{"deploy", "--kind", "static", "--account-id", rigSqid, "--console", origin, "--app", rigApp, "--channel", "edge", "--timeout", "5m", "--version", version, "--no-prompt", stage}; !slices.Equal(runs[1].args, want) || rep.Publish.Version != version { t.Fatalf("deploy argv %q", runs[1].args) } if want := []string{"services", "create", "--role", "deploy", "--app", rigApp, "--rungs", "edge", "--account-id", rigSqid, "--console", origin, rigKeyName}; !slices.Equal(runs[2].args, want) { t.Fatalf("mint argv %q", runs[2].args) } for _, run := range runs { for _, kv := range run.env { k, _, _ := strings.Cut(kv, "=") if !slices.Contains([]string{"HOME", "PATH", "CARLOS_CREDENTIALS", "CARLOS_CONFIG", "CARLOS_NO_UPDATE_CHECK", "PWD", "SHLVL", "_"}, k) { t.Fatalf("a login run saw %s", kv) } } if v, _ := run.envOf("CARLOS_CREDENTIALS"); v != rig.creds { t.Fatalf("login run credentials %q", v) } config, _ := run.envOf("CARLOS_CONFIG") raw, err := os.ReadFile(config) if !strings.HasPrefix(config, rig.e.Site.State) || err != nil || strings.TrimSpace(string(raw)) != "{}" { t.Fatalf("configuration %q: %q %v", config, raw, err) } if home, _ := run.envOf("HOME"); home != run.pwd || !strings.HasPrefix(run.pwd, rig.e.Site.State) { t.Fatalf("ran from %s with HOME %s", run.pwd, home) } if strings.Contains(strings.Join(run.args, " "), "evil") || strings.Contains(strings.Join(run.args, " "), "elsewhere") { t.Fatalf("the planted configuration reached argv %q", run.args) } } served := map[string]bool{} entries, _ := os.ReadDir(filepath.Join(filepath.Dir(rig.calls), "served")) for _, en := range entries { served[en.Name()] = true } if len(served) != 4 || !served["index.html"] || !served["style.css"] || !served["_headers"] || !served[siteMarker] { t.Fatalf("published %v", served) } if raw, _ := os.ReadFile(filepath.Join(filepath.Dir(rig.calls), "served", "_headers")); string(raw) != quickSite["site/_headers"] { t.Fatalf("the project's _headers changed: %q", raw) } keyFile := filepath.Join(rig.e.Site.State, "keys", rigConsole, rigSqid, rigApp+".json") info, err := os.Stat(keyFile) if err != nil || info.Mode().Perm() != 0o600 { t.Fatalf("key file %v %v", info, err) } if dir, _ := os.Stat(filepath.Dir(keyFile)); dir.Mode().Perm() != 0o700 { t.Fatalf("key folder mode %v", dir.Mode()) } reach := rig.e.Site.Reach(context.Background()) if reach == nil || len(reach.Deploys) != 1 || reach.Deploys[0].Name != rigKeyName || reach.Deploys[0].Lost || len(reach.Deploys[0].Fingerprint) != 16 || reach.Deploys[0].App != rigApp { t.Fatalf("reach %+v", reach) } if len(reach.Logins) != 1 || reach.Logins[0].Console != rigConsole || !slices.Equal(reach.Logins[0].Accounts, []wire.ReachAccount{{Name: "paulca", Sqid: "kmnpq"}, {Name: "oficina", Sqid: "bcdfg"}}) { t.Fatalf("logins %+v", reach.Logins) } if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil { t.Fatalf("reach invalid: %v", err) } // The next publish: the key alone. rig.confirms = nil next := rig.e.Exec(context.Background(), rig.step("s_pub2", wire.SitePublish), func(wire.StepReport) {}) if next.State != wire.StepDone || next.Publish.Outcome != wire.PublishPublished || !next.Publish.DeployHeld { t.Fatalf("second publish %+v %+v", next, next.Publish) } runs = carlosRuns(t, rig.calls) last := runs[len(runs)-1] if got := verbsOf(runs); !slices.Equal(got, []string{"apps list", "deploy --kind", "services create", "accounts list", "deploy --kind"}) { t.Fatalf("runs %v", got) } if tok, _ := last.envOf("CARLOS_SERVICE_TOKEN"); tok != fakeDeployToken { t.Fatal("the publish did not use the deploy key") } if c, _ := last.envOf("CARLOS_CONSOLE"); c != origin { t.Fatalf("console %q", c) } if v, _ := last.envOf("CARLOS_CREDENTIALS"); v == rig.creds || !strings.HasPrefix(v, rig.e.Site.State) { t.Fatalf("the login reached a key publish: %q", v) } else if _, err := os.Stat(v); err == nil { t.Fatalf("the absent credentials file exists: %s", v) } if len(rig.confirms) != 1 || !strings.HasPrefix(rig.confirms[0], "publish:s_pub2/") { t.Fatalf("checks %v", rig.confirms) } rig.noSecretOutsideKeys(t, rep, next) } // TestSiteSetupNameTaken: before a setup's deploy, an app of that name // already in the account (live, kept, in the Trash, with or without the // header and region), or a list that cannot be read strictly, refuses the // publish before its check: nothing is deployed or minted. func TestSiteSetupNameTaken(t *testing.T) { using := "using https://console.carloku.com as p@x\n" for name, list := range map[string]string{ "live": using + listHeader + "site-sample live eu-west expires in 3 days\n", "no header": using + "site-sample live\n", "trashed": using + listHeader + "site-sample trashed eu-west\n", "unreadable": "something went wrong\n", "no using": "no apps in this account\n", "odd line": using + "other-app live\nwhat is this\n", } { rig := newSiteRig(t, quickSite) os.WriteFile(rig.apps, []byte(list), 0o644) rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) runs := carlosRuns(t, rig.calls) if rep.State != wire.StepFailed || rep.Reason != "publish_app_taken" || len(runs) != 1 || runs[0].args[0] != "apps" || len(rig.confirms) != 0 { t.Fatalf("%s: %+v, runs %v, checks %v", name, rep, verbsOf(runs), rig.confirms) } } } // TestSiteListed: the strict list parser. func TestSiteListed(t *testing.T) { using := "using https://console.carloku.com as p@x\n" for name, c := range map[string]struct { out string present, ok bool }{ "empty account": {using + "no apps in this account\n", false, true}, "others, header": {using + listHeader + "site-other live\n", false, true}, "others, none": {using + "site-other live\nsite-third trashed\n", false, true}, "listed, region": {using + listHeader + "site-sample live eu-west expires in 2 days\n", true, true}, "listed, plain": {"\x1b[2m" + using + "\x1b[0msite-sample live\n", true, true}, "header only": {using + listHeader, false, false}, "nothing": {"", false, false}, "no using": {"site-other live\n", false, false}, "bad state": {using + "site-other gone\n", false, false}, "empty then apps": {using + "no apps in this account\nsite-sample live\n", false, false}, } { present, ok := siteListed(c.out, "site-sample") if present != c.present || ok != c.ok { t.Errorf("%s: present %t ok %t", name, present, ok) } } } // TestSiteMintRecovery: a mint runs only with this runner's own record of // creating the app at exactly this place: behind its mint check, it mints // with the login, then deploys with the new key behind its publish check, // never with the login. With no record it never adopts: an app it did not // make refuses publish_app_unproven, a missing app publish_app_missing, // an unreadable list fails; none mints or deploys. A record for another // account proves nothing here. func TestSiteMintRecovery(t *testing.T) { rig := newSiteRig(t, quickSite) if err := rig.e.Site.created(siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp}, "tk1"); err != nil { t.Fatal(err) } rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SiteMint), func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished || !rep.Publish.DeployHeld { t.Fatalf("mint %+v %+v", rep, rep.Publish) } runs := carlosRuns(t, rig.calls) if got := verbsOf(runs); !slices.Equal(got, []string{"services create", "deploy --kind"}) { t.Fatalf("runs %v", got) } if v, _ := runs[0].envOf("CARLOS_CREDENTIALS"); v != rig.creds { t.Fatal("the mint did not use the login") } if tok, _ := runs[1].envOf("CARLOS_SERVICE_TOKEN"); tok != fakeDeployToken { t.Fatal("the deploy after a mint did not use the new key") } if v, _ := runs[1].envOf("CARLOS_CREDENTIALS"); v == rig.creds { t.Fatal("the login deployed a created app again") } if len(rig.confirms) != 2 || !strings.HasPrefix(rig.confirms[0], "mint:") || !strings.HasPrefix(rig.confirms[1], "publish:") { t.Fatalf("checks %v", rig.confirms) } rig.noSecretOutsideKeys(t, rep) using := "using https://console.carloku.com as p@x\n" for name, c := range map[string]struct{ list, reason string }{ "not ours": {using + "site-sample live\n", reasonPublishAppUnproven}, "absent": {using + "no apps in this account\n", reasonPublishAppMissing}, "unreadable": {"oops\n", "publish_failed"}, } { rig := newSiteRig(t, quickSite) // Another account's record is no proof here. rig.e.Site.created(siteTarget{Console: rigConsole, Sqid: "bcdfg", App: rigApp}, "tk1") os.WriteFile(rig.apps, []byte(c.list), 0o644) rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SiteMint), func(wire.StepReport) {}) if rep.State != wire.StepFailed || rep.Reason != c.reason || len(rig.confirms) != 0 { t.Fatalf("%s: %+v checks %v", name, rep, rig.confirms) } if got := verbsOf(carlosRuns(t, rig.calls)); !slices.Equal(got, []string{"apps list"}) { t.Fatalf("%s: runs %v", name, got) } } } // TestSiteMintLost: a mint whose answer fails or cannot be read leaves no // key, and the runner says the name is lost (it may be live on CARLOS) // until it holds a key; the setup's site is still published. A refused // mint check mints nothing and loses nothing. func TestSiteMintLost(t *testing.T) { rig := newSiteRig(t, quickSite) os.WriteFile(filepath.Join(filepath.Dir(rig.calls), "mintfail"), nil, 0o644) rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.DeployHeld { t.Fatalf("lost mint %+v %+v", rep, rep.Publish) } reach := rig.e.Site.Reach(context.Background()) if len(reach.Deploys) != 1 || !reach.Deploys[0].Lost || reach.Deploys[0].Name != rigKeyName || reach.Deploys[0].Fingerprint != "" { t.Fatalf("reach %+v", reach.Deploys) } if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil { t.Fatalf("reach invalid: %v", err) } // A mint step recovers it with a new key: held, and the first one's // name still said lost (CARLOS may hold it live). os.Remove(filepath.Join(filepath.Dir(rig.calls), "mintfail")) recovery := rig.step("s_pub2", wire.SiteMint) recovery.Publish.DeployName = "eq-sample-cd34" again := rig.e.Exec(context.Background(), recovery, func(wire.StepReport) {}) if again.State != wire.StepDone || !again.Publish.DeployHeld { t.Fatalf("recovery %+v %+v", again, again.Publish) } reach = rig.e.Site.Reach(context.Background()) if len(reach.Deploys) != 2 || reach.Deploys[0].Name != rigKeyName || !reach.Deploys[0].Lost || reach.Deploys[1].Name != "eq-sample-cd34" || reach.Deploys[1].Lost { t.Fatalf("after recovery %+v", reach.Deploys) } if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil { t.Fatalf("reach invalid: %v", err) } rig = newSiteRig(t, quickSite) rig.e.ConfirmMint = func(context.Context, string, int64, string, string) error { return ErrWithdrawn } rep = rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.Publish.DeployHeld { t.Fatalf("refused mint check %+v", rep.Publish) } if got := verbsOf(carlosRuns(t, rig.calls)); !slices.Equal(got, []string{"apps list", "deploy --kind"}) { t.Fatalf("runs %v", got) } if reach := rig.e.Site.Reach(context.Background()); len(reach.Deploys) != 0 { t.Fatalf("a refused mint left %+v", reach.Deploys) } } // TestSitePublishFence: the target, the version and the folder are checked // before anything runs: a destination hash that does not bind the parts, // a part out of shape, an unknown mode or a key name where none belongs is // refused; so is a merged commit that is not on the default branch, a // publish with no key, a key for another place, a carlos too old, a scan // that finds a secret or cannot run, and an instance that refuses the // check. carlos runs for none of them; none reports built. func TestSitePublishFence(t *testing.T) { rig := newSiteRig(t, quickSite) run := func(r stepRow, want string) { t.Helper() built := false rep := rig.e.Exec(context.Background(), r, func(p wire.StepReport) { built = built || p.Publish != nil }) if n := len(carlosRuns(t, rig.calls)); n != 0 || built || rep.Reason != want || (want == "withdrawn") != (rep.State == wire.StepCancelled) { t.Fatalf("%+v: %+v, %d runs, built %t; want %s", r.Publish, rep, n, built, want) } } bad := func(f func(d *wire.PublishDispatch)) stepRow { r := rig.step("s_pub1", wire.SiteSetup) f(r.Publish) return r } for name, r := range map[string]stepRow{ "app flag": bad(func(d *wire.PublishDispatch) { d.App = "--help" }), "app arg": bad(func(d *wire.PublishDispatch) { d.App = "site-x --account other" }), "app path": bad(func(d *wire.PublishDispatch) { d.App = "site-../x" }), "console path": bad(func(d *wire.PublishDispatch) { d.Console = "console.carloku.com/../x" }), "console scheme": bad(func(d *wire.PublishDispatch) { d.Console = "https://console.carloku.com" }), "sqid": bad(func(d *wire.PublishDispatch) { d.Account = "--all" }), "rehashed": bad(func(d *wire.PublishDispatch) { d.Account = "bcdfg" }), "other app": bad(func(d *wire.PublishDispatch) { d.App = "site-other" }), "mode": bad(func(d *wire.PublishDispatch) { d.Mode = "adopt" }), "no key name": bad(func(d *wire.PublishDispatch) { d.DeployName = "" }), "key name arg": bad(func(d *wire.PublishDispatch) { d.DeployName = "eq-x --role admin" }), "no target": bad(func(d *wire.PublishDispatch) { *d = wire.PublishDispatch{} }), "into": bad(func(d *wire.PublishDispatch) { d.Into = "-main" }), } { _ = name run(r, "policy_rejected") } pub := rig.step("s_pub1", wire.SitePublish) pub.Publish.DeployName = rigKeyName run(pub, "policy_rejected") run(rig.step("s_pub1", wire.SitePublish), reasonPublishKeyMissing) off := rig.r off.CandidateSHA = rig.unmerged run(off, "publish_not_merged") confirm := rig.e.ConfirmPublish rig.e.ConfirmPublish = func(context.Context, string, int64, string, string) error { return ErrWithdrawn } os.WriteFile(rig.apps, []byte("using x\nno apps in this account\n"), 0o644) if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); rep.State != wire.StepCancelled || slices.Contains(verbsOf(carlosRuns(t, rig.calls)), "deploy --kind") { t.Fatalf("refused check: %+v %v", rep, verbsOf(carlosRuns(t, rig.calls))) } rig.e.ConfirmPublish = confirm os.Remove(rig.calls) // A carlos older than the minimum, or one whose version is unreadable. for _, v := range []string{"v0.32.2", ""} { rig.e.Site.CLI = &carlosCLI{Bin: rig.bin, Read: func(context.Context, string) string { return v }} run(rig.r, wire.ReasonCarlosOutdated) } rig.e.Site.CLI = nil // No login: a setup cannot run. creds := rig.e.Site.Credentials rig.e.Site.Credentials = "" run(rig.r, "publish_off") rig.e.Site.Credentials = creds // The secret scan, on the exact export. files := map[string]string{"release/preview.json": `{"output": "site"}`, "site/index.html": "

x

\n", "site/config.js": `const token = "` + "ghp_" + strings.Join([]string{"Vw3K", "8pRt", "a9Qz", "6LmN", "2sDx", "7bJh", "4cFv", "0uEy", "5nWi"}, "") + `"; // gitleaks:allow` + "\n", "site/gitleaks.toml": "[allowlist]\nregexes = ['.*']\n"} secret := newSiteRig(t, files) if rep := secret.e.Exec(context.Background(), secret.r, func(wire.StepReport) {}); rep.Reason != reasonPublishSecrets || carlosRuns(t, secret.calls) != nil { t.Fatalf("a secret published: %+v", rep) } unscanned := newSiteRig(t, quickSite) unscanned.e.O.Runner.Executable = filepath.Join(t.TempDir(), "missing-runner") if rep := unscanned.e.Exec(context.Background(), unscanned.r, func(wire.StepReport) {}); rep.Reason != reasonPublishScanner || carlosRuns(t, unscanned.calls) != nil { t.Fatalf("published unscanned: %+v", rep) } site := rig.e.Site rig.e.Site = nil run(rig.r, "publish_off") rig.e.Site = site } // TestSitePublishKeyForAnotherPlace: a key is found only at its own // console, sqid and app: a key held for the same app in another account // is not this place's. func TestSitePublishKeyForAnotherPlace(t *testing.T) { rig := newSiteRig(t, quickSite) other := siteTarget{Console: rigConsole, Sqid: "bcdfg", Name: "oficina", App: rigApp, DeployName: rigKeyName} p, _ := rig.e.Site.keyPath(other) raw, _ := json.Marshal(deployKey{Console: rigConsole, Account: "bcdfg", App: rigApp, Name: rigKeyName, Token: fakeDeployToken, Fingerprint: "0123456789abcdef"}) if err := writeSecret(p, raw); err != nil { t.Fatal(err) } rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SitePublish), func(wire.StepReport) {}) if rep.Reason != reasonPublishKeyMissing || carlosRuns(t, rig.calls) != nil { t.Fatalf("another place's key used: %+v", rep) } } // TestSitePublishRestart: an attempt that may have changed CARLOS only // reconciles after a restart: it never deploys or mints again; the marker // over the URL this attempt's deploy printed decides. A mint attempt that // restarted before its deploy fails, its lost name kept. func TestSitePublishRestart(t *testing.T) { rig := newSiteRig(t, quickSite) first := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) for _, phase := range []string{phaseSitePublishing, phaseSiteMinting} { again := rig.r again.Phase = phase rep := rig.e.Exec(context.Background(), again, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.Publish == nil || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.Digest != first.Publish.Digest || rep.Publish.URL != "https://site-sample.bds.oncarlos.com/" || !rep.Publish.DeployHeld { t.Fatalf("%s reconciled %+v", phase, rep.Publish) } } if n := len(carlosRuns(t, rig.calls)); n != 3 { t.Fatalf("carlos ran %d times", n) } mint := rig.step("s_pub1", wire.SiteMint) mint.Phase = phaseSiteMinting if rep := rig.e.Exec(context.Background(), mint, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != reasonPublishMintFailed { t.Fatalf("mint restart %+v", rep) } if n := len(carlosRuns(t, rig.calls)); n != 3 { t.Fatalf("a restart ran carlos: %d", n) } } // TestSiteDeployArgs: the templates are built from fixed parts and // checked values; nothing else can be produced, whatever they are given. func TestSiteDeployArgs(t *testing.T) { tg, ok := targetOf(rigTarget(wire.SiteSetup)) if !ok { t.Fatal("rig target refused") } got, err := siteDeployArgs(tg, "s-0123456789ab-pub1-1", "/state/steps/k/site") want := []string{"deploy", "--kind", "static", "--account-id", rigSqid, "--console", "https://console.carloku.com", "--app", rigApp, "--channel", "edge", "--timeout", "5m", "--version", "s-0123456789ab-pub1-1", "--no-prompt", "/state/steps/k/site"} if err != nil || !slices.Equal(got, want) { t.Fatalf("%q %v", got, err) } for _, c := range [][2]string{ {"--console=x", "/s/site"}, {"s-0123456789ab-a-1 --x", "/s/site"}, {"s-0123456789AB-a-1", "/s/site"}, {"s-0123456789ab-a-1", "relative/site"}, {"s-0123456789ab-a-1", "/s/../site"}, {"s-0123456789ab-a-1", "/s/site\n--x"}, {"s-0123456789ab-a-1", "/"}, } { if args, err := siteDeployArgs(tg, c[0], c[1]); err == nil { t.Fatalf("built %q from %q", args, c) } } tg.DeployName = "eq x" if _, err := siteMintArgs(tg); err == nil { t.Fatal("a mint built with a bad name") } if _, ok := mintedKey("minted service:kmnpq/eq-sample-ab12 (role deploy, app site-sample, rungs edge, beta)\n CARLOS_SERVICE_TOKEN="+fakeDeployToken+"\n", siteTarget{Sqid: rigSqid, App: rigApp, DeployName: rigKeyName}); ok { t.Fatal("a key with more rungs than edge accepted") } if _, ok := mintedKey("minted service:kmnpq/eq-sample-ab12 (role deploy, app site-sample, rungs edge)\n CARLOS_SERVICE_TOKEN=a1234567890123456\n CARLOS_SERVICE_TOKEN=b1234567890123456\n", siteTarget{Sqid: rigSqid, App: rigApp, DeployName: rigKeyName}); ok { t.Fatal("two tokens accepted") } } // TestProbeSite: carlos is found on PATH; the signed-in credential is used // only when it is this user's own regular file, mode 0600, outside every // directory a sandbox mounts (else sites still publish with held keys, // and set up none); the state may not lie inside a sandbox mount. The // probe runs no carlos command at all. The reach reads only the live // https consoles of the credential file. func TestProbeSite(t *testing.T) { root := t.TempDir() bin, calls, _ := fakeCarlosScript(t, root, "https://site-x.example") creds := filepath.Join(root, "credentials") os.WriteFile(creds, []byte(`{"version":1,"credentials":[{"console":"https://console.carloku.com","token":"x"},{"console":"https://console.platform.tito.io/","token":"y"},{"console":"http://plain.example","token":"z"},{"console":"https://old.example","token":"w","expires_at":"2001-01-01T00:00:00Z"},{"console":"https://console.carloku.com","token":"again"}]}`), 0o600) t.Setenv("PATH", root+":/usr/bin:/bin") t.Setenv("CARLOS_CREDENTIALS", creds) c := runner.Config{StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "ws")} s := ProbeSite(c, nil) if s == nil || s.Carlos != bin || s.Credentials != creds { t.Fatalf("probe %+v", s) } if carlosRuns(t, calls) != nil { t.Fatal("the probe ran carlos") } if got := s.loginConsoles(); !slices.Equal(got, []string{wire.FlagshipConsole, wire.TitoConsole}) { t.Fatalf("consoles %v", got) } os.Chmod(creds, 0o644) if s := ProbeSite(c, nil); s == nil || s.Credentials != "" { t.Fatalf("a readable credential accepted: %+v", s) } os.Chmod(creds, 0o600) link := filepath.Join(root, "link") os.Symlink(creds, link) t.Setenv("CARLOS_CREDENTIALS", link) if s := ProbeSite(c, nil); s == nil || s.Credentials != "" { t.Fatal("a linked credential accepted") } inside := filepath.Join(c.WorkspaceRoot, "credentials") os.MkdirAll(c.WorkspaceRoot, 0o700) os.WriteFile(inside, []byte("{}"), 0o600) t.Setenv("CARLOS_CREDENTIALS", inside) if s := ProbeSite(c, nil); s == nil || s.Credentials != "" { t.Fatal("a credential inside the workspace accepted") } if ProbeSite(runner.Config{StateDir: filepath.Join(c.WorkspaceRoot, "state"), WorkspaceRoot: c.WorkspaceRoot}, nil) != nil { t.Fatal("site state inside the workspace accepted") } if ProbeSite(runner.Config{WorkspaceRoot: c.WorkspaceRoot}, nil) != nil { t.Fatal("paired with no state") } } // TestOwnedAccounts: only the owner rows of a NAME SQID ROLE table, each // validated; anything else is no account at all. func TestOwnedAccounts(t *testing.T) { got := ownedAccounts("NAME SQID ROLE\npaulca kmnpq owner\nfriend bcdfg member\nbad-- -x owner\npaulca kmnpq owner\nkeymail hjkmn owner extra\n") if !slices.Equal(got, []wire.ReachAccount{{Name: "paulca", Sqid: "kmnpq"}}) { t.Fatalf("accounts %+v", got) } if got := ownedAccounts("Error: not logged in\n"); len(got) != 0 { t.Fatalf("accounts from an error %+v", got) } } // TestCarlosHealth: the version comes from carlos's own first line; the // health is missing with no binary, outdated when the version is // unreadable or below the minimum, else ok with the version. func TestCarlosHealth(t *testing.T) { dir := t.TempDir() write := func(name, out string) string { p := filepath.Join(dir, name) os.WriteFile(p, []byte("#!/bin/sh\n[ \"$1\" = version ] && printf '"+out+"'\n"), 0o755) return p } cur, old, odd := write("cur", "carlos v0.43.3\\ncommit abc\\n"), write("old", "carlos v0.32.2\\n"), write("odd", "v0.43.3\\n") if v := carlosVersionOf(context.Background(), cur); v != "v0.43.3" { t.Fatalf("version %q", v) } for bin, want := range map[string][2]string{cur: {wire.CarlosOK, "v0.43.3"}, old: {wire.CarlosOutdated, "v0.32.2"}, odd: {wire.CarlosOutdated, ""}, "": {wire.CarlosMissing, ""}} { c := &carlosCLI{Bin: bin, Read: carlosVersionOf} if state, v := c.Health(context.Background()); state != want[0] || v != want[1] { t.Errorf("%s: %s %s", bin, state, v) } } var nilCLI *carlosCLI if state, _ := nilCLI.Health(context.Background()); state != wire.CarlosMissing { t.Fatal("no carlos is not missing") } } // TestHandshakeHelloWithholdsPlaces: the first hello never carries the // reach or the carlos health (an older instance would refuse it); after a // protocol 31 welcome the next hello, sent at once, does; at 30 none ever // does, and the publish and mint checks are refused here, never sent. func TestHandshakeHelloWithholdsPlaces(t *testing.T) { hello := func() wire.Hello { return wire.Hello{Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}, Capabilities: &wire.Capabilities{Tags: []string{wire.TagLinux}, Simulators: []wire.Simulator{}, Tools: &wire.ToolHealth{Scanner: wire.ToolHealthy, Carlos: wire.CarlosOK, CarlosVersion: "v0.43.3"}, Reach: &wire.Reach{Logins: []wire.ReachLogin{}, Deploys: []wire.ReachDeploy{}}}} } for _, protocol := range []int{wire.ProtocolAssistantFiles, wire.ProtocolPlaces} { inst := newFakeInstance(t) link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) c := <-inst.conns _, raw := read(t, c, wire.FrameHello) if strings.Contains(string(raw), `"reach"`) || strings.Contains(string(raw), `"carlos`) || !strings.Contains(string(raw), `"linux"`) { t.Fatalf("handshake hello: %s", raw) } welcome, _ := json.Marshal(wire.Frame{ID: "w-s", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":` + itoa(int64(protocol)) + `,"role":"primary"}`)}) write(t, c, welcome) read(t, c, wire.FrameSync) _, raw = read(t, c, wire.FrameHello) if got := strings.Contains(string(raw), `"reach"`) && strings.Contains(string(raw), `"carlos":"ok"`); got != (protocol >= wire.ProtocolPlaces) { t.Fatalf("protocol %d hello: %s", protocol, raw) } if protocol < wire.ProtocolPlaces { dest := wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp) if err := link.ConfirmPublish(context.Background(), "s_1", 1, strings.Repeat("a", 64), dest); !errors.Is(err, ErrNoAuthority) { t.Fatalf("a deploy check at %d: %v", protocol, err) } if err := link.ConfirmMint(context.Background(), "s_1", 1, strings.Repeat("a", 64), dest); !errors.Is(err, ErrNoAuthority) { t.Fatalf("a mint check at %d: %v", protocol, err) } } } } // TestSiteSetupFailedDeploy: attempted is never proven. A setup whose // deploy failed having made nothing records nothing, so an app someone // else makes later is never adopted by a mint; one whose deploy made the // app (it is listed right after the failure, the name free just before) // is recorded as made here, and a mint gets its key. func TestSiteSetupFailedDeploy(t *testing.T) { rig := newSiteRig(t, quickSite) os.WriteFile(filepath.Join(filepath.Dir(rig.calls), "fail"), nil, 0o644) if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); rep.Reason != "publish_failed" || rep.Publish.DeployHeld { t.Fatalf("failed deploy %+v", rep) } if rig.e.Site.madeHere(siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp}) { t.Fatal("a deploy that made nothing recorded the app as made here") } os.Remove(filepath.Join(filepath.Dir(rig.calls), "fail")) // Someone else makes the app meanwhile: the mint refuses it. os.WriteFile(rig.apps, []byte("using https://console.carloku.com as p@x\nsite-sample live\n"), 0o644) if rep := rig.e.Exec(context.Background(), rig.step("s_pub2", wire.SiteMint), func(wire.StepReport) {}); rep.Reason != reasonPublishAppUnproven { t.Fatalf("adopted: %+v", rep) } if slices.Contains(verbsOf(carlosRuns(t, rig.calls)), "services create") { t.Fatal("minted for an app not made here") } half := newSiteRig(t, quickSite) os.WriteFile(filepath.Join(filepath.Dir(half.calls), "halffail"), nil, 0o644) if rep := half.e.Exec(context.Background(), half.r, func(wire.StepReport) {}); rep.Reason != "publish_failed" { t.Fatalf("half-failed deploy %+v", rep) } if !half.e.Site.madeHere(siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp}) { t.Fatal("the app the deploy made is not recorded") } os.Remove(filepath.Join(filepath.Dir(half.calls), "halffail")) if rep := half.e.Exec(context.Background(), half.step("s_pub2", wire.SiteMint), func(wire.StepReport) {}); rep.State != wire.StepDone || !rep.Publish.DeployHeld { t.Fatalf("mint after a half-failed deploy %+v", rep) } } // TestSiteLostAndHeld: a stop between storing a key and removing its // intent leaves both; the key wins, the spent intent goes, and the reach // stays valid (one entry per key). func TestSiteLostAndHeld(t *testing.T) { rig := newSiteRig(t, quickSite) if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); !rep.Publish.DeployHeld { t.Fatalf("setup %+v", rep.Publish) } tg := siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp, DeployName: rigKeyName} lost, _ := rig.e.Site.lostPath(tg) if err := writeSecret(lost, []byte(`{"name":"`+rigKeyName+`"}`)); err != nil { t.Fatal(err) } reach := rig.e.Site.Reach(context.Background()) if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil || len(reach.Deploys) != 1 || reach.Deploys[0].Lost { t.Fatalf("reach %+v %v", reach.Deploys, err) } if _, err := os.Stat(lost); !errors.Is(err, os.ErrNotExist) { t.Fatal("the spent intent stayed") } } // TestRecoverStepsKeepsSiteMinting: a publish that restarted while it // minted is reconciled, never ended as a plain restart. func TestRecoverStepsKeepsSiteMinting(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() for i, phase := range []string{phaseSitePublishing, phaseSiteMinting} { d := dispatchFor("tk"+itoa(int64(i)), "s_p"+itoa(int64(i)), 1) d.Specialist, d.CandidateSHA, d.Publish = wire.SpecialistPublish, strings.Repeat("a", 40), rigTarget(wire.SiteSetup) if err := s.AcceptDispatch(ctx, "c"+itoa(int64(i)), d); err != nil { t.Fatal(err) } if err := s.setStepPhase(ctx, stepRow{DispatchCommand: d}, phase, "", d.CandidateSHA); err != nil { t.Fatal(err) } } if err := s.RecoverSteps(ctx, nil); err != nil { t.Fatal(err) } if reps := outbox(t, s); len(reps) != 0 { t.Fatalf("ended as restarted: %+v", reps) } } // TestSiteCreationProofSurvives: the proof is written as soon as the // setup's deploy succeeded, before the marker is polled; a restart whose // own marker answers from the app's address restores a missing one. func TestSiteCreationProofSurvives(t *testing.T) { rig := newSiteRig(t, quickSite) dead := httptest.NewServer(http.NotFoundHandler()) t.Cleanup(dead.Close) served := rig.e.Site.URL rig.e.Site.URL = func(string) string { return dead.URL } tg := siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp} if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishUnconfirmed || !rig.e.Site.madeHere(tg) { t.Fatalf("unconfirmed setup %+v, made here %t", rep.Publish, rig.e.Site.madeHere(tg)) } p, _ := rig.e.Site.createdPath(tg) os.Remove(p) rig.e.Site.URL = served again := rig.r again.Phase = phaseSitePublishing if rep := rig.e.Exec(context.Background(), again, func(wire.StepReport) {}); rep.Publish.Outcome != wire.PublishPublished || !rig.e.Site.madeHere(tg) { t.Fatalf("reconcile %+v, made here %t", rep.Publish, rig.e.Site.madeHere(tg)) } } // TestStepEngineReconcilesCancelledSitePublish: a cancelled site publish // that may have changed CARLOS still reaches Exec, which only // reconciles; any other cancelled step is reported cancelled unrun. func TestStepEngineReconcilesCancelledSitePublish(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() var ran []string e := &StepEngine{State: s, Notify: func() {}, Exec: func(_ context.Context, r stepRow, _ func(wire.StepReport)) wire.StepReport { ran = append(ran, r.StepID) return wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepDone, Termination: true, Findings: []wire.Finding{}} }} for _, c := range []struct { id, specialist, phase string }{{"s_a", wire.SpecialistPublish, phaseSiteMinting}, {"s_b", wire.SpecialistPublish, phaseSitePublishing}, {"s_c", wire.SpecialistPublish, ""}, {"s_d", wire.SpecialistReview, phaseSiteMinting}} { d := dispatchFor("tk", c.id, 1) d.Specialist = c.specialist r := stepRow{DispatchCommand: d, Phase: c.phase, Cancel: true} e.runOne(ctx, r) } if !slices.Equal(ran, []string{"s_a", "s_b"}) { t.Fatalf("ran %v", ran) } }