package thin import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" ) // fakeCarlos is Carloku as the preview executor sees it: each command is // recorded with its environment and directory; ship remembers the folder // it was given and promote serves it at the app's origin. type fakeCarlos struct { t *testing.T list string fail map[string]string calls [][]string envs [][]string dirs []string shipped string served string } func (f *fakeCarlos) run(_ context.Context, dir string, env []string, args []string) (string, error) { f.calls, f.envs, f.dirs = append(f.calls, args), append(f.envs, env), append(f.dirs, dir) verb := args[0] if len(args) > 1 && args[0] == "apps" { verb += " " + args[1] } if out, ok := f.fail[verb]; ok { return out, errors.New("exit status 1") } switch verb { case "apps list": return f.list, nil case "deploy": return "created tmp-tk1, a temporary app. It moves to the Trash in 7 days, at 2026-11-18 16:00 UTC\n", nil case "apps ttl": return "expiry set tmp-tk1 moves to the Trash in 7 days, at 2026-11-18 16:05 UTC\n", nil case "ship": f.shipped = args[len(args)-1] return "shipped\n", nil case "channels": return "using https://console.example as ci\nCHANNEL VERSION PROMOTED TAG DIGESTS\nedge p0 2026-11-11T16:00:00Z no\n", nil case "promote": f.served = f.shipped return "promoted\n", nil } f.t.Fatalf("a command outside the templates: %v", args) return "", nil } // verbs are the commands run, in order. func (f *fakeCarlos) verbs() string { var out []string for _, c := range f.calls { v := c[0] if c[0] == "apps" { v += " " + c[1] } out = append(out, v) } return strings.Join(out, ", ") } const listHeader = "APP STATE REGION \n" // previewRig is a remote whose task branch holds files at the candidate, // an Engineer with a preview credential talking to fakeCarlos, and a // marker origin that serves what was promoted. func previewRig(t *testing.T, files map[string]string, links map[string]string) (*Engineer, *fakeCarlos, *[]string, stepRow) { 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("threatmin\n"), 0644) gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "base") base := gitOut(t, work, "rev-parse", "HEAD") gitOut(t, work, "checkout", "-q", "-b", "equipo/tk1-barber-mockups") for p, body := range files { os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0755) os.WriteFile(filepath.Join(work, p), []byte(body), 0644) } for p, target := range links { os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0755) os.Symlink(target, filepath.Join(work, p)) } gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "mockups") cand := gitOut(t, work, "rev-parse", "HEAD") remote := filepath.Join(root, "remote.git") gitOut(t, root, "clone", "-q", "--bare", work, remote) os.MkdirAll(filepath.Join(root, "state"), 0700) os.MkdirAll(filepath.Join(root, "work"), 0700) s, err := OpenState(context.Background(), filepath.Join(root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) f := &hubForge{dir: remote} fc := &fakeCarlos{t: t, list: listHeader, fail: map[string]string{}} origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if fc.served == "" || r.URL.Path != "/"+previewMarker { http.NotFound(w, r) return } w.Header().Set("Content-Security-Policy", previewCSP("https://equipo.example")) http.ServeFile(w, r, filepath.Join(fc.served, previewMarker)) })) t.Cleanup(origin.Close) var confirms []string e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test", Preview: &PreviewOptions{Carlos: "/usr/local/bin/carlos", Token: "svc-token", Console: "https://console.example", Account: "previews", Domain: "bds.oncarlos.com", Run: fc.run, URL: func(app string) string { return origin.URL }}, ConfirmPreview: func(_ context.Context, step string, attempt int64, digest string) error { confirms = append(confirms, step+"/"+itoa(attempt)+"/"+digest) return nil }} 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.Origin = "https://equipo.example" e.O.Runner.Executable = previewScannerFixture(t) r := stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s_pv1", Attempt: 1, Specialist: wire.SpecialistPreview, Repo: "amadan.net/paulca/threatmin", Branch: "equipo/tk1-barber-mockups", Title: "Barber mockups", BaseSHA: base, CandidateSHA: cand}} if err := s.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil { t.Fatal(err) } previewVerifyFor, previewVerifyEvery = 300*time.Millisecond, 50*time.Millisecond return e, fc, &confirms, r } var mockups = map[string]string{ "release/preview.json": `{"output": "mockups"}`, "mockups/index.html": "
Tuesday 10:00
\n", "src/not-in-preview.txt": "kept out\n", } // TestPreviewFirstPublish: the first preview of a task exports exactly // the output directory from git objects, reports it built with its // digest, then creates the temporary app with a placeholder, ships and // promotes the export, each mutation behind its own publish check bound // to the digest, with the token only in the environment and nothing run // from the repository; the marker then confirms it is served. func TestPreviewFirstPublish(t *testing.T) { e, fc, confirms, r := previewRig(t, mockups, nil) var built *wire.PreviewResult rep := e.Exec(context.Background(), r, func(p wire.StepReport) { if p.Preview != nil { built = p.Preview } }) if built == nil || built.Phase != wire.PreviewBuilt || built.Files != 4 || len(built.Digest) != 64 { t.Fatalf("built %+v", built) } if rep.State != wire.StepDone || rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || rep.Preview.App != "tmp-tk1" || rep.Preview.Digest != built.Digest || rep.Preview.Version != "p-s_pv1-1" || rep.Reason != "" { t.Fatalf("report %+v %+v", rep, rep.Preview) } if rep.Preview.ExpiresAt == nil || !rep.Preview.ExpiresAt.Equal(time.Date(2026, 11, 18, 16, 0, 0, 0, time.UTC)) || !strings.HasPrefix(rep.Preview.URL, "http") { t.Fatalf("url and expiry %+v", rep.Preview) } if got := fc.verbs(); got != "apps list, deploy, ship, channels, promote" { t.Fatalf("commands %s", got) } acct := []string{"--account", "previews", "--console", "https://console.example"} cmd := func(verb []string, rest ...string) []string { return append(append(append([]string{}, verb...), acct...), rest...) } want := [][]string{ cmd([]string{"apps", "list"}), cmd([]string{"deploy"}, "--temporary", "--ttl", "7d", "--app", "tk1", "--kind", "static", "--version", "p0-s_pv1-1", "--no-prompt"), cmd([]string{"ship"}, "--app", "tmp-tk1", "--kind", "static", "--version", "p-s_pv1-1", "--no-prompt"), cmd([]string{"channels"}, "--app", "tmp-tk1"), cmd([]string{"promote"}, "--app", "tmp-tk1", "--no-prompt", "p-s_pv1-1", "edge"), } for i, w := range want { if strings.Join(fc.calls[i][:len(w)], " ") != strings.Join(w, " ") { t.Fatalf("command %d: %v", i, fc.calls[i]) } } if len(*confirms) != 3 { t.Fatalf("publish checks %v", *confirms) } for _, c := range *confirms { if c != "s_pv1/1/"+built.Digest { t.Fatalf("check %q", c) } } for i, c := range fc.calls { if strings.Contains(strings.Join(c, " "), "svc-token") || !slicesHas(fc.envs[i], "CARLOS_SERVICE_TOKEN=svc-token") { t.Fatalf("the token in argv or missing from the environment: %v", c) } if entries, _ := os.ReadDir(fc.dirs[i]); len(entries) != 0 || strings.Contains(fc.dirs[i], "workspace") { t.Fatalf("carlos ran from %s holding %v", fc.dirs[i], entries) } } got := map[string]bool{} filepath.WalkDir(fc.served, func(p string, d os.DirEntry, err error) error { if err == nil && !d.IsDir() { rel, _ := filepath.Rel(fc.served, p) got[rel] = true } return nil }) if len(got) != 5 || !got["index.html"] || !got["css/site.css"] || !got["booking.html"] || !got[previewMarker] { t.Fatalf("served %v", got) } // The placeholder deploy served the runner's own page, never the export. hold := fc.calls[1][len(fc.calls[1])-1] if raw, _ := os.ReadFile(filepath.Join(hold, "index.html")); strings.Contains(string(raw), "Book a cut") { t.Fatal("the create served repository content") } } func slicesHas(list []string, s string) bool { for _, x := range list { if x == s { return true } } return false } // TestPreviewReplacesInPlace: a live preview is renewed first, then the // new export shipped and promoted to the same app; never a second app. func TestPreviewReplacesInPlace(t *testing.T) { e, fc, confirms, r := previewRig(t, mockups, nil) fc.list = listHeader + "tmp-tk1 live Ireland expires in 6d\n" rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || !rep.Preview.ExpiresAt.Equal(time.Date(2026, 11, 18, 16, 5, 0, 0, time.UTC)) { t.Fatalf("report %+v", rep.Preview) } if got := fc.verbs(); got != "apps list, apps ttl, ship, channels, promote" || len(*confirms) != 3 { t.Fatalf("commands %s, checks %d", got, len(*confirms)) } if strings.Join(fc.calls[1], " ") != "apps ttl --account previews --console https://console.example --app tmp-tk1 7d" { t.Fatalf("ttl %v", fc.calls[1]) } } // TestPreviewRefusedStates: an expired preview, a kept app, or a state // that cannot be read changes nothing. func TestPreviewRefusedStates(t *testing.T) { for list, reason := range map[string]string{ listHeader + "tmp-tk1 trashed Ireland purged in 2d\n": "preview_expired", listHeader + "tmp-tk1 live Ireland\n": "preview_state", "something else\n": "preview_state", } { e, fc, confirms, r := previewRig(t, mockups, nil) fc.list = list rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepFailed || rep.Reason != reason || fc.verbs() != "apps list" || len(*confirms) != 0 { t.Fatalf("%q: %+v commands %s", list, rep, fc.verbs()) } } e, fc, _, r := previewRig(t, mockups, nil) fc.fail["deploy"] = "this account already has 20 temporary apps, the most it can hold. Make one permanent..." if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "preview_cap" { t.Fatalf("cap %+v", rep) } } // TestPreviewExportGuards: only regular files of a clean output path, the // marker's name reserved, within the caps; anything else publishes // nothing and runs no carlos command. func TestPreviewExportGuards(t *testing.T) { with := func(extra map[string]string) map[string]string { out := map[string]string{} for k, v := range mockups { out[k] = v } for k, v := range extra { out[k] = v } return out } for name, c := range map[string]struct { files map[string]string links map[string]string reason string }{ "a symlink": {mockups, map[string]string{"mockups/secret": "/etc/passwd"}, "preview_config"}, "scanner config": {with(map[string]string{"mockups/.gitleaks.toml": "[allowlist]\nregexes=['.*']"}), nil, "preview_config"}, "scanner ignore": {with(map[string]string{"mockups/.gitleaksignore": "config.js:github-pat:1"}), nil, "preview_config"}, "git ignore": {with(map[string]string{"mockups/.gitignore": "*"}), nil, "preview_config"}, "nested scanner config": {with(map[string]string{"mockups/assets/.gitleaks.toml": "[allowlist]\nregexes=['.*']"}), nil, "preview_config"}, "a dot file": {with(map[string]string{"mockups/.carlos/config": "x"}), nil, "preview_config"}, "the marker's name": {with(map[string]string{"mockups/" + previewMarker: "{}"}), nil, "preview_config"}, "a build command": {with(map[string]string{"release/preview.json": `{"output": "mockups", "build": ["make"]}`}), nil, "preview_config"}, "a path outside": {with(map[string]string{"release/preview.json": `{"output": "../etc"}`}), nil, "preview_config"}, "a dot output": {with(map[string]string{"release/preview.json": `{"output": ".git"}`}), nil, "preview_config"}, "an empty output": {with(map[string]string{"release/preview.json": `{"output": "missing"}`}), nil, "preview_config"}, "a file too large": {with(map[string]string{"mockups/video.bin": strings.Repeat("v", previewMaxFile+1)}), nil, "preview_too_large"}, } { e, fc, _, r := previewRig(t, c.files, c.links) rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepFailed || rep.Reason != c.reason || len(fc.calls) != 0 { t.Fatalf("%s: %+v commands %s", name, rep, fc.verbs()) } } } // TestPreviewPublishCheckRefused: a refusal before any mutation stops the // step with nothing sent after it. func TestPreviewPublishCheckRefused(t *testing.T) { for at, want := range map[int]string{1: "apps list", 2: "apps list, deploy", 3: "apps list, deploy, ship, channels"} { e, fc, _, r := previewRig(t, mockups, nil) n := 0 e.ConfirmPreview = func(context.Context, string, int64, string) error { if n++; n == at { return ErrWithdrawn } return nil } rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || fc.verbs() != want { t.Fatalf("refused at check %d: %+v commands %s", at, rep, fc.verbs()) } } // Not built yet on the instance: asked again, then on. e, fc, _, r := previewRig(t, mockups, nil) n := 0 previewBuiltWait = time.Millisecond e.ConfirmPreview = func(context.Context, string, int64, string) error { if n++; n < 3 { return ErrPreviewNotBuilt } return nil } if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || fc.verbs() != "apps list, deploy, ship, channels, promote" { t.Fatalf("after not built %+v %s", rep, fc.verbs()) } } // TestPreviewUnconfirmed: an origin that never answers with this export, // or answers through a redirect, leaves the preview unconfirmed, and // nothing is sent again. func TestPreviewUnconfirmed(t *testing.T) { e, fc, _, r := previewRig(t, mockups, nil) right := "" elsewhere := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { http.ServeFile(w, req, right) })) defer elsewhere.Close() redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { right = filepath.Join(fc.served, previewMarker) http.Redirect(w, req, elsewhere.URL+req.URL.Path, http.StatusFound) })) defer redirect.Close() e.Preview.URL = func(string) string { return redirect.URL } rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.Preview == nil || rep.Preview.Outcome != wire.PreviewUnconfirmed || rep.Preview.URL != "" || strings.Count(fc.verbs(), "promote") != 1 { t.Fatalf("through a redirect %+v %s", rep.Preview, fc.verbs()) } e, fc, _, r = previewRig(t, mockups, nil) stale := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Write([]byte(`{"task":"tk1","candidate":"` + r.CandidateSHA + `","step":"s_pv1","attempt":1,"digest":"an-older-export"}`)) })) defer stale.Close() e.Preview.URL = func(string) string { return stale.URL } if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.Preview == nil || rep.Preview.Outcome != wire.PreviewUnconfirmed { t.Fatalf("another export served %+v", rep.Preview) } e, fc, _, r = previewRig(t, mockups, nil) fc.fail["promote"] = "refused" rep = e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.Preview.Outcome != wire.PreviewUnconfirmed || rep.Reason != "preview_failed" { t.Fatalf("a failed promote %+v %+v", rep, rep.Preview) } } // TestPreviewAfterRestart: a preview that may have changed Carloku is // held across a restart and only reconciles: no command runs, the marker // decides. func TestPreviewAfterRestart(t *testing.T) { e, fc, _, r := previewRig(t, mockups, nil) e.ConfirmPreview = func(context.Context, string, int64, string) error { return nil } fc.fail["ship"] = "lost" e.Exec(context.Background(), r, func(wire.StepReport) {}) ctx := context.Background() if err := e.O.State.RecoverSteps(ctx, nil); err != nil { t.Fatal(err) } if reps := outbox(t, e.O.State); len(reps) != 0 { t.Fatalf("recovery reported %+v", reps) } held, ok, err := e.O.State.nextStep(ctx) if err != nil || !ok || held.Phase != phasePreviewPublishing { t.Fatalf("held %+v %v %v", held, ok, err) } before := len(fc.calls) fc.served = filepath.Join(e.root(), stepKey(r), "preview") rep := e.Exec(ctx, held, func(wire.StepReport) {}) if rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || len(fc.calls) != before { t.Fatalf("reconciled %+v, %d commands after", rep.Preview, len(fc.calls)-before) } } // TestHasPreviewAndOptions: Review's evidence reads the candidate's git // objects; the credential file is owner-only, complete and strict. func TestHasPreviewAndOptions(t *testing.T) { dir := t.TempDir() write := func(mode os.FileMode, v map[string]string) string { p := filepath.Join(dir, "cred.json") raw, _ := json.Marshal(v) os.WriteFile(p, raw, mode) os.Chmod(p, mode) return p } good := map[string]string{"carlos": "/usr/local/bin/carlos", "token": "t", "console": "https://console.example", "account": "previews", "domain": "bds.oncarlos.com"} if _, err := LoadPreviewOptions(write(0o600, good)); err != nil { t.Fatal(err) } if _, err := LoadPreviewOptions(write(0o644, good)); err == nil { t.Fatal("a readable credential file was taken") } for k, v := range map[string]string{"carlos": "carlos", "console": "http://console.example", "domain": "a/b", "extra": "x"} { bad := map[string]string{} for kk, vv := range good { bad[kk] = vv } bad[k] = v if _, err := LoadPreviewOptions(write(0o600, bad)); err == nil { t.Fatalf("%s=%s taken", k, v) } } } // TestPreviewCredentialRefusals: a link, any mode but 0600, a file inside // a directory sandboxes mount, or content that is not the expected JSON // is refused, and the error never carries the content. func TestPreviewCredentialRefusals(t *testing.T) { dir := t.TempDir() good := `{"carlos":"/usr/local/bin/carlos","token":"t0ken","console":"https://console.example","account":"previews","domain":"bds.oncarlos.com"}` file := filepath.Join(dir, "cred.json") os.WriteFile(file, []byte(good), 0o600) if _, err := LoadPreviewOptions(file); err != nil { t.Fatal(err) } link := filepath.Join(dir, "link.json") os.Symlink(file, link) if _, err := LoadPreviewOptions(link); err == nil { t.Fatal("a link was followed") } for _, mode := range []os.FileMode{0o400, 0o640, 0o644, 0o700, os.ModeSetuid | 0o600} { os.Chmod(file, mode) if _, err := LoadPreviewOptions(file); err == nil { t.Fatalf("mode %o taken", mode) } } os.Chmod(file, 0o600) os.WriteFile(file, []byte(`{"token":"s3cret-value","stray_key_with_secret":"s3cret-value"}`), 0o600) _, err := LoadPreviewOptions(file) if err == nil || strings.Contains(err.Error(), "s3cret") || strings.Contains(err.Error(), "stray_key") { t.Fatalf("decoder error leaked: %v", err) } os.WriteFile(file, []byte(good), 0o600) work := filepath.Join(dir, "work") os.MkdirAll(work, 0o700) inside := filepath.Join(work, "cred.json") os.WriteFile(inside, []byte(good), 0o600) cfg := runner.Config{PreviewCredentialPath: inside, WorkspaceRoot: work, ScratchRoot: filepath.Join(dir, "scratch"), StateDir: filepath.Join(dir, "state")} if previewOptions(cfg, nil) != nil { t.Fatal("a credential inside the workspace root was taken") } cfg.PreviewCredentialPath = file if previewOptions(cfg, nil) == nil { t.Fatal("a credential outside every mounted root was refused") } } // TestPreviewEmptyAccount: a previews account with no apps at all is a // listing (carlos says "no apps in this account", with no header), so the // first preview is created. func TestPreviewEmptyAccount(t *testing.T) { for _, list := range []string{"no apps in this account\n", "using https://console.example as a service credential (CARLOS_SERVICE_TOKEN)\n\x1b[2mno apps in this account\x1b[0m\n"} { e, fc, _, r := previewRig(t, mockups, nil) fc.list = list rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || fc.verbs() != "apps list, deploy, ship, channels, promote" { t.Fatalf("%q: %+v %s", list, rep, fc.verbs()) } } } // TestPreviewCancelledAfterRestart: a preview cancelled while it may have // published still reconciles after a restart: never a plain cancel, never // a command. func TestPreviewCancelledAfterRestart(t *testing.T) { e, fc, _, r := previewRig(t, mockups, nil) fc.fail["ship"] = "lost" e.Exec(context.Background(), r, func(wire.StepReport) {}) ctx := context.Background() if err := e.O.State.RequestStepCancel(ctx, "cancel-1", wire.CancelStepCommand{Person: r.Person, TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt}); err != nil { t.Fatal(err) } if err := e.O.State.RecoverSteps(ctx, nil); err != nil { t.Fatal(err) } if reps := outbox(t, e.O.State); len(reps) != 0 { t.Fatalf("recovery reported %+v", reps) } held, ok, err := e.O.State.nextStep(ctx) if err != nil || !ok || held.Phase != phasePreviewPublishing || !held.Cancel { t.Fatalf("held %+v %v %v", held, ok, err) } before := len(fc.calls) cctx, cancel := context.WithCancel(ctx) cancel() fc.served = filepath.Join(e.root(), stepKey(r), "preview") rep := e.Exec(cctx, held, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || len(fc.calls) != before { t.Fatalf("reconciled %s %+v, %d commands", rep.State, rep.Preview, len(fc.calls)-before) } }