oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "net/http"
8 "net/http/httptest"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/runner"
16 "amadan.net/oficina/equipo/internal/wire"
17)
18
19// fakeCarlos is Carloku as the preview executor sees it: each command is
20// recorded with its environment and directory; ship remembers the folder
21// it was given and promote serves it at the app's origin.
22type fakeCarlos struct {
23 t *testing.T
24 list string
25 fail map[string]string
26 calls [][]string
27 envs [][]string
28 dirs []string
29 shipped string
30 served string
31}
32
33func (f *fakeCarlos) run(_ context.Context, dir string, env []string, args []string) (string, error) {
34 f.calls, f.envs, f.dirs = append(f.calls, args), append(f.envs, env), append(f.dirs, dir)
35 verb := args[0]
36 if len(args) > 1 && args[0] == "apps" {
37 verb += " " + args[1]
38 }
39 if out, ok := f.fail[verb]; ok {
40 return out, errors.New("exit status 1")
41 }
42 switch verb {
43 case "apps list":
44 return f.list, nil
45 case "deploy":
46 return "created tmp-tk1, a temporary app. It moves to the Trash in 7 days, at 2026-11-18 16:00 UTC\n", nil
47 case "apps ttl":
48 return "expiry set tmp-tk1 moves to the Trash in 7 days, at 2026-11-18 16:05 UTC\n", nil
49 case "ship":
50 f.shipped = args[len(args)-1]
51 return "shipped\n", nil
52 case "channels":
53 return "using https://console.example as ci\nCHANNEL VERSION PROMOTED TAG DIGESTS\nedge p0 2026-11-11T16:00:00Z no\n", nil
54 case "promote":
55 f.served = f.shipped
56 return "promoted\n", nil
57 }
58 f.t.Fatalf("a command outside the templates: %v", args)
59 return "", nil
60}
61
62// verbs are the commands run, in order.
63func (f *fakeCarlos) verbs() string {
64 var out []string
65 for _, c := range f.calls {
66 v := c[0]
67 if c[0] == "apps" {
68 v += " " + c[1]
69 }
70 out = append(out, v)
71 }
72 return strings.Join(out, ", ")
73}
74
75const listHeader = "APP STATE REGION \n"
76
77// previewRig is a remote whose task branch holds files at the candidate,
78// an Engineer with a preview credential talking to fakeCarlos, and a
79// marker origin that serves what was promoted.
80func previewRig(t *testing.T, files map[string]string, links map[string]string) (*Engineer, *fakeCarlos, *[]string, stepRow) {
81 t.Helper()
82 root := t.TempDir()
83 work := filepath.Join(root, "seed")
84 gitOut(t, root, "init", "-q", "-b", "main", work)
85 os.WriteFile(filepath.Join(work, "README.md"), []byte("threatmin\n"), 0644)
86 gitOut(t, work, "add", "-A")
87 gitOut(t, work, "commit", "-q", "-m", "base")
88 base := gitOut(t, work, "rev-parse", "HEAD")
89 gitOut(t, work, "checkout", "-q", "-b", "equipo/tk1-barber-mockups")
90 for p, body := range files {
91 os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0755)
92 os.WriteFile(filepath.Join(work, p), []byte(body), 0644)
93 }
94 for p, target := range links {
95 os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0755)
96 os.Symlink(target, filepath.Join(work, p))
97 }
98 gitOut(t, work, "add", "-A")
99 gitOut(t, work, "commit", "-q", "-m", "mockups")
100 cand := gitOut(t, work, "rev-parse", "HEAD")
101 remote := filepath.Join(root, "remote.git")
102 gitOut(t, root, "clone", "-q", "--bare", work, remote)
103 os.MkdirAll(filepath.Join(root, "state"), 0700)
104 os.MkdirAll(filepath.Join(root, "work"), 0700)
105 s, err := OpenState(context.Background(), filepath.Join(root, "state"))
106 if err != nil {
107 t.Fatal(err)
108 }
109 t.Cleanup(func() { s.Close() })
110 f := &hubForge{dir: remote}
111 fc := &fakeCarlos{t: t, list: listHeader, fail: map[string]string{}}
112 origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
113 if fc.served == "" || r.URL.Path != "/"+previewMarker {
114 http.NotFound(w, r)
115 return
116 }
117 w.Header().Set("Content-Security-Policy", previewCSP("https://equipo.example"))
118 http.ServeFile(w, r, filepath.Join(fc.served, previewMarker))
119 }))
120 t.Cleanup(origin.Close)
121 var confirms []string
122 e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test",
123 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 }},
124 ConfirmPreview: func(_ context.Context, step string, attempt int64, digest string) error {
125 confirms = append(confirms, step+"/"+itoa(attempt)+"/"+digest)
126 return nil
127 }}
128 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
129 e.O.Runner.Origin = "https://equipo.example"
130 e.O.Runner.Executable = previewScannerFixture(t)
131 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}}
132 if err := s.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil {
133 t.Fatal(err)
134 }
135 previewVerifyFor, previewVerifyEvery = 300*time.Millisecond, 50*time.Millisecond
136 return e, fc, &confirms, r
137}
138
139var mockups = map[string]string{
140 "release/preview.json": `{"output": "mockups"}`,
141 "mockups/index.html": "<h1>Book a cut</h1>\n",
142 "mockups/css/site.css": "body{margin:0}\n",
143 "mockups/booking.html": "<p>Tuesday 10:00</p>\n",
144 "src/not-in-preview.txt": "kept out\n",
145}
146
147// TestPreviewFirstPublish: the first preview of a task exports exactly
148// the output directory from git objects, reports it built with its
149// digest, then creates the temporary app with a placeholder, ships and
150// promotes the export, each mutation behind its own publish check bound
151// to the digest, with the token only in the environment and nothing run
152// from the repository; the marker then confirms it is served.
153func TestPreviewFirstPublish(t *testing.T) {
154 e, fc, confirms, r := previewRig(t, mockups, nil)
155 var built *wire.PreviewResult
156 rep := e.Exec(context.Background(), r, func(p wire.StepReport) {
157 if p.Preview != nil {
158 built = p.Preview
159 }
160 })
161 if built == nil || built.Phase != wire.PreviewBuilt || built.Files != 4 || len(built.Digest) != 64 {
162 t.Fatalf("built %+v", built)
163 }
164 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 != "" {
165 t.Fatalf("report %+v %+v", rep, rep.Preview)
166 }
167 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") {
168 t.Fatalf("url and expiry %+v", rep.Preview)
169 }
170 if got := fc.verbs(); got != "apps list, deploy, ship, channels, promote" {
171 t.Fatalf("commands %s", got)
172 }
173 acct := []string{"--account", "previews", "--console", "https://console.example"}
174 cmd := func(verb []string, rest ...string) []string {
175 return append(append(append([]string{}, verb...), acct...), rest...)
176 }
177 want := [][]string{
178 cmd([]string{"apps", "list"}),
179 cmd([]string{"deploy"}, "--temporary", "--ttl", "7d", "--app", "tk1", "--kind", "static", "--version", "p0-s_pv1-1", "--no-prompt"),
180 cmd([]string{"ship"}, "--app", "tmp-tk1", "--kind", "static", "--version", "p-s_pv1-1", "--no-prompt"),
181 cmd([]string{"channels"}, "--app", "tmp-tk1"),
182 cmd([]string{"promote"}, "--app", "tmp-tk1", "--no-prompt", "p-s_pv1-1", "edge"),
183 }
184 for i, w := range want {
185 if strings.Join(fc.calls[i][:len(w)], " ") != strings.Join(w, " ") {
186 t.Fatalf("command %d: %v", i, fc.calls[i])
187 }
188 }
189 if len(*confirms) != 3 {
190 t.Fatalf("publish checks %v", *confirms)
191 }
192 for _, c := range *confirms {
193 if c != "s_pv1/1/"+built.Digest {
194 t.Fatalf("check %q", c)
195 }
196 }
197 for i, c := range fc.calls {
198 if strings.Contains(strings.Join(c, " "), "svc-token") || !slicesHas(fc.envs[i], "CARLOS_SERVICE_TOKEN=svc-token") {
199 t.Fatalf("the token in argv or missing from the environment: %v", c)
200 }
201 if entries, _ := os.ReadDir(fc.dirs[i]); len(entries) != 0 || strings.Contains(fc.dirs[i], "workspace") {
202 t.Fatalf("carlos ran from %s holding %v", fc.dirs[i], entries)
203 }
204 }
205 got := map[string]bool{}
206 filepath.WalkDir(fc.served, func(p string, d os.DirEntry, err error) error {
207 if err == nil && !d.IsDir() {
208 rel, _ := filepath.Rel(fc.served, p)
209 got[rel] = true
210 }
211 return nil
212 })
213 if len(got) != 5 || !got["index.html"] || !got["css/site.css"] || !got["booking.html"] || !got[previewMarker] {
214 t.Fatalf("served %v", got)
215 }
216 // The placeholder deploy served the runner's own page, never the export.
217 hold := fc.calls[1][len(fc.calls[1])-1]
218 if raw, _ := os.ReadFile(filepath.Join(hold, "index.html")); strings.Contains(string(raw), "Book a cut") {
219 t.Fatal("the create served repository content")
220 }
221}
222
223func slicesHas(list []string, s string) bool {
224 for _, x := range list {
225 if x == s {
226 return true
227 }
228 }
229 return false
230}
231
232// TestPreviewReplacesInPlace: a live preview is renewed first, then the
233// new export shipped and promoted to the same app; never a second app.
234func TestPreviewReplacesInPlace(t *testing.T) {
235 e, fc, confirms, r := previewRig(t, mockups, nil)
236 fc.list = listHeader + "tmp-tk1 live Ireland expires in 6d\n"
237 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
238 if rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || !rep.Preview.ExpiresAt.Equal(time.Date(2026, 11, 18, 16, 5, 0, 0, time.UTC)) {
239 t.Fatalf("report %+v", rep.Preview)
240 }
241 if got := fc.verbs(); got != "apps list, apps ttl, ship, channels, promote" || len(*confirms) != 3 {
242 t.Fatalf("commands %s, checks %d", got, len(*confirms))
243 }
244 if strings.Join(fc.calls[1], " ") != "apps ttl --account previews --console https://console.example --app tmp-tk1 7d" {
245 t.Fatalf("ttl %v", fc.calls[1])
246 }
247}
248
249// TestPreviewRefusedStates: an expired preview, a kept app, or a state
250// that cannot be read changes nothing.
251func TestPreviewRefusedStates(t *testing.T) {
252 for list, reason := range map[string]string{
253 listHeader + "tmp-tk1 trashed Ireland purged in 2d\n": "preview_expired",
254 listHeader + "tmp-tk1 live Ireland\n": "preview_state",
255 "something else\n": "preview_state",
256 } {
257 e, fc, confirms, r := previewRig(t, mockups, nil)
258 fc.list = list
259 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
260 if rep.State != wire.StepFailed || rep.Reason != reason || fc.verbs() != "apps list" || len(*confirms) != 0 {
261 t.Fatalf("%q: %+v commands %s", list, rep, fc.verbs())
262 }
263 }
264 e, fc, _, r := previewRig(t, mockups, nil)
265 fc.fail["deploy"] = "this account already has 20 temporary apps, the most it can hold. Make one permanent..."
266 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "preview_cap" {
267 t.Fatalf("cap %+v", rep)
268 }
269}
270
271// TestPreviewExportGuards: only regular files of a clean output path, the
272// marker's name reserved, within the caps; anything else publishes
273// nothing and runs no carlos command.
274func TestPreviewExportGuards(t *testing.T) {
275 with := func(extra map[string]string) map[string]string {
276 out := map[string]string{}
277 for k, v := range mockups {
278 out[k] = v
279 }
280 for k, v := range extra {
281 out[k] = v
282 }
283 return out
284 }
285 for name, c := range map[string]struct {
286 files map[string]string
287 links map[string]string
288 reason string
289 }{
290 "a symlink": {mockups, map[string]string{"mockups/secret": "/etc/passwd"}, "preview_config"},
291 "scanner config": {with(map[string]string{"mockups/.gitleaks.toml": "[allowlist]\nregexes=['.*']"}), nil, "preview_config"},
292 "scanner ignore": {with(map[string]string{"mockups/.gitleaksignore": "config.js:github-pat:1"}), nil, "preview_config"},
293 "git ignore": {with(map[string]string{"mockups/.gitignore": "*"}), nil, "preview_config"},
294 "nested scanner config": {with(map[string]string{"mockups/assets/.gitleaks.toml": "[allowlist]\nregexes=['.*']"}), nil, "preview_config"},
295 "a dot file": {with(map[string]string{"mockups/.carlos/config": "x"}), nil, "preview_config"},
296 "the marker's name": {with(map[string]string{"mockups/" + previewMarker: "{}"}), nil, "preview_config"},
297 "a build command": {with(map[string]string{"release/preview.json": `{"output": "mockups", "build": ["make"]}`}), nil, "preview_config"},
298 "a path outside": {with(map[string]string{"release/preview.json": `{"output": "../etc"}`}), nil, "preview_config"},
299 "a dot output": {with(map[string]string{"release/preview.json": `{"output": ".git"}`}), nil, "preview_config"},
300 "an empty output": {with(map[string]string{"release/preview.json": `{"output": "missing"}`}), nil, "preview_config"},
301 "a file too large": {with(map[string]string{"mockups/video.bin": strings.Repeat("v", previewMaxFile+1)}), nil, "preview_too_large"},
302 } {
303 e, fc, _, r := previewRig(t, c.files, c.links)
304 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
305 if rep.State != wire.StepFailed || rep.Reason != c.reason || len(fc.calls) != 0 {
306 t.Fatalf("%s: %+v commands %s", name, rep, fc.verbs())
307 }
308 }
309}
310
311// TestPreviewPublishCheckRefused: a refusal before any mutation stops the
312// step with nothing sent after it.
313func TestPreviewPublishCheckRefused(t *testing.T) {
314 for at, want := range map[int]string{1: "apps list", 2: "apps list, deploy", 3: "apps list, deploy, ship, channels"} {
315 e, fc, _, r := previewRig(t, mockups, nil)
316 n := 0
317 e.ConfirmPreview = func(context.Context, string, int64, string) error {
318 if n++; n == at {
319 return ErrWithdrawn
320 }
321 return nil
322 }
323 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
324 if rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || fc.verbs() != want {
325 t.Fatalf("refused at check %d: %+v commands %s", at, rep, fc.verbs())
326 }
327 }
328 // Not built yet on the instance: asked again, then on.
329 e, fc, _, r := previewRig(t, mockups, nil)
330 n := 0
331 previewBuiltWait = time.Millisecond
332 e.ConfirmPreview = func(context.Context, string, int64, string) error {
333 if n++; n < 3 {
334 return ErrPreviewNotBuilt
335 }
336 return nil
337 }
338 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" {
339 t.Fatalf("after not built %+v %s", rep, fc.verbs())
340 }
341}
342
343// TestPreviewUnconfirmed: an origin that never answers with this export,
344// or answers through a redirect, leaves the preview unconfirmed, and
345// nothing is sent again.
346func TestPreviewUnconfirmed(t *testing.T) {
347 e, fc, _, r := previewRig(t, mockups, nil)
348 right := ""
349 elsewhere := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
350 http.ServeFile(w, req, right)
351 }))
352 defer elsewhere.Close()
353 redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
354 right = filepath.Join(fc.served, previewMarker)
355 http.Redirect(w, req, elsewhere.URL+req.URL.Path, http.StatusFound)
356 }))
357 defer redirect.Close()
358 e.Preview.URL = func(string) string { return redirect.URL }
359 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
360 if rep.State != wire.StepDone || rep.Preview == nil || rep.Preview.Outcome != wire.PreviewUnconfirmed || rep.Preview.URL != "" || strings.Count(fc.verbs(), "promote") != 1 {
361 t.Fatalf("through a redirect %+v %s", rep.Preview, fc.verbs())
362 }
363
364 e, fc, _, r = previewRig(t, mockups, nil)
365 stale := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
366 w.Write([]byte(`{"task":"tk1","candidate":"` + r.CandidateSHA + `","step":"s_pv1","attempt":1,"digest":"an-older-export"}`))
367 }))
368 defer stale.Close()
369 e.Preview.URL = func(string) string { return stale.URL }
370 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.Preview == nil || rep.Preview.Outcome != wire.PreviewUnconfirmed {
371 t.Fatalf("another export served %+v", rep.Preview)
372 }
373
374 e, fc, _, r = previewRig(t, mockups, nil)
375 fc.fail["promote"] = "refused"
376 rep = e.Exec(context.Background(), r, func(wire.StepReport) {})
377 if rep.State != wire.StepDone || rep.Preview.Outcome != wire.PreviewUnconfirmed || rep.Reason != "preview_failed" {
378 t.Fatalf("a failed promote %+v %+v", rep, rep.Preview)
379 }
380}
381
382// TestPreviewAfterRestart: a preview that may have changed Carloku is
383// held across a restart and only reconciles: no command runs, the marker
384// decides.
385func TestPreviewAfterRestart(t *testing.T) {
386 e, fc, _, r := previewRig(t, mockups, nil)
387 e.ConfirmPreview = func(context.Context, string, int64, string) error { return nil }
388 fc.fail["ship"] = "lost"
389 e.Exec(context.Background(), r, func(wire.StepReport) {})
390 ctx := context.Background()
391 if err := e.O.State.RecoverSteps(ctx, nil); err != nil {
392 t.Fatal(err)
393 }
394 if reps := outbox(t, e.O.State); len(reps) != 0 {
395 t.Fatalf("recovery reported %+v", reps)
396 }
397 held, ok, err := e.O.State.nextStep(ctx)
398 if err != nil || !ok || held.Phase != phasePreviewPublishing {
399 t.Fatalf("held %+v %v %v", held, ok, err)
400 }
401 before := len(fc.calls)
402 fc.served = filepath.Join(e.root(), stepKey(r), "preview")
403 rep := e.Exec(ctx, held, func(wire.StepReport) {})
404 if rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || len(fc.calls) != before {
405 t.Fatalf("reconciled %+v, %d commands after", rep.Preview, len(fc.calls)-before)
406 }
407}
408
409// TestHasPreviewAndOptions: Review's evidence reads the candidate's git
410// objects; the credential file is owner-only, complete and strict.
411func TestHasPreviewAndOptions(t *testing.T) {
412 dir := t.TempDir()
413 write := func(mode os.FileMode, v map[string]string) string {
414 p := filepath.Join(dir, "cred.json")
415 raw, _ := json.Marshal(v)
416 os.WriteFile(p, raw, mode)
417 os.Chmod(p, mode)
418 return p
419 }
420 good := map[string]string{"carlos": "/usr/local/bin/carlos", "token": "t", "console": "https://console.example", "account": "previews", "domain": "bds.oncarlos.com"}
421 if _, err := LoadPreviewOptions(write(0o600, good)); err != nil {
422 t.Fatal(err)
423 }
424 if _, err := LoadPreviewOptions(write(0o644, good)); err == nil {
425 t.Fatal("a readable credential file was taken")
426 }
427 for k, v := range map[string]string{"carlos": "carlos", "console": "http://console.example", "domain": "a/b", "extra": "x"} {
428 bad := map[string]string{}
429 for kk, vv := range good {
430 bad[kk] = vv
431 }
432 bad[k] = v
433 if _, err := LoadPreviewOptions(write(0o600, bad)); err == nil {
434 t.Fatalf("%s=%s taken", k, v)
435 }
436 }
437}
438
439// TestPreviewCredentialRefusals: a link, any mode but 0600, a file inside
440// a directory sandboxes mount, or content that is not the expected JSON
441// is refused, and the error never carries the content.
442func TestPreviewCredentialRefusals(t *testing.T) {
443 dir := t.TempDir()
444 good := `{"carlos":"/usr/local/bin/carlos","token":"t0ken","console":"https://console.example","account":"previews","domain":"bds.oncarlos.com"}`
445 file := filepath.Join(dir, "cred.json")
446 os.WriteFile(file, []byte(good), 0o600)
447 if _, err := LoadPreviewOptions(file); err != nil {
448 t.Fatal(err)
449 }
450 link := filepath.Join(dir, "link.json")
451 os.Symlink(file, link)
452 if _, err := LoadPreviewOptions(link); err == nil {
453 t.Fatal("a link was followed")
454 }
455 for _, mode := range []os.FileMode{0o400, 0o640, 0o644, 0o700, os.ModeSetuid | 0o600} {
456 os.Chmod(file, mode)
457 if _, err := LoadPreviewOptions(file); err == nil {
458 t.Fatalf("mode %o taken", mode)
459 }
460 }
461 os.Chmod(file, 0o600)
462 os.WriteFile(file, []byte(`{"token":"s3cret-value","stray_key_with_secret":"s3cret-value"}`), 0o600)
463 _, err := LoadPreviewOptions(file)
464 if err == nil || strings.Contains(err.Error(), "s3cret") || strings.Contains(err.Error(), "stray_key") {
465 t.Fatalf("decoder error leaked: %v", err)
466 }
467 os.WriteFile(file, []byte(good), 0o600)
468 work := filepath.Join(dir, "work")
469 os.MkdirAll(work, 0o700)
470 inside := filepath.Join(work, "cred.json")
471 os.WriteFile(inside, []byte(good), 0o600)
472 cfg := runner.Config{PreviewCredentialPath: inside, WorkspaceRoot: work, ScratchRoot: filepath.Join(dir, "scratch"), StateDir: filepath.Join(dir, "state")}
473 if previewOptions(cfg, nil) != nil {
474 t.Fatal("a credential inside the workspace root was taken")
475 }
476 cfg.PreviewCredentialPath = file
477 if previewOptions(cfg, nil) == nil {
478 t.Fatal("a credential outside every mounted root was refused")
479 }
480}
481
482// TestPreviewEmptyAccount: a previews account with no apps at all is a
483// listing (carlos says "no apps in this account", with no header), so the
484// first preview is created.
485func TestPreviewEmptyAccount(t *testing.T) {
486 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"} {
487 e, fc, _, r := previewRig(t, mockups, nil)
488 fc.list = list
489 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
490 if rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || fc.verbs() != "apps list, deploy, ship, channels, promote" {
491 t.Fatalf("%q: %+v %s", list, rep, fc.verbs())
492 }
493 }
494}
495
496// TestPreviewCancelledAfterRestart: a preview cancelled while it may have
497// published still reconciles after a restart: never a plain cancel, never
498// a command.
499func TestPreviewCancelledAfterRestart(t *testing.T) {
500 e, fc, _, r := previewRig(t, mockups, nil)
501 fc.fail["ship"] = "lost"
502 e.Exec(context.Background(), r, func(wire.StepReport) {})
503 ctx := context.Background()
504 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 {
505 t.Fatal(err)
506 }
507 if err := e.O.State.RecoverSteps(ctx, nil); err != nil {
508 t.Fatal(err)
509 }
510 if reps := outbox(t, e.O.State); len(reps) != 0 {
511 t.Fatalf("recovery reported %+v", reps)
512 }
513 held, ok, err := e.O.State.nextStep(ctx)
514 if err != nil || !ok || held.Phase != phasePreviewPublishing || !held.Cancel {
515 t.Fatalf("held %+v %v %v", held, ok, err)
516 }
517 before := len(fc.calls)
518 cctx, cancel := context.WithCancel(ctx)
519 cancel()
520 fc.served = filepath.Join(e.root(), stepKey(r), "preview")
521 rep := e.Exec(cctx, held, func(wire.StepReport) {})
522 if rep.State != wire.StepDone || rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || len(fc.calls) != before {
523 t.Fatalf("reconciled %s %+v, %d commands", rep.State, rep.Preview, len(fc.calls)-before)
524 }
525}
526