| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io/fs" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "slices" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/runner" |
| 20 | "amadan.net/oficina/equipo/internal/wire" |
| 21 | ) |
| 22 | |
| 23 | // The deploy key the fake carlos mints: assembled so the repository's own |
| 24 | // scan does not read it as a credential. |
| 25 | var fakeDeployToken = strings.Join([]string{"cst", "Qm9vZ3lXb29naWU", "x7Lp2Rk9"}, "_") |
| 26 | |
| 27 | // fakeCarlosScript writes a carlos that records each run (its argv, one |
| 28 | // argument per line, its working directory and its environment) and acts |
| 29 | // as the real one does for the five templates: accounts list prints the |
| 30 | // file accounts beside it; apps list the file apps; services create |
| 31 | // prints its minted line and one CARLOS_SERVICE_TOKEN line (or fails when |
| 32 | // a file mintfail is there); deploy serves the folder it was given and |
| 33 | // prints the live line (or fails, making nothing, when a file fail is |
| 34 | // there, or makes the app and then fails when a file halffail is). |
| 35 | func fakeCarlosScript(t *testing.T, dir, live string) (bin, calls, served string) { |
| 36 | t.Helper() |
| 37 | bin, calls, served = filepath.Join(dir, "carlos"), filepath.Join(dir, "calls"), filepath.Join(dir, "served") |
| 38 | apps, accounts := filepath.Join(dir, "apps"), filepath.Join(dir, "accounts") |
| 39 | if err := os.WriteFile(apps, []byte("using https://console.carloku.com as paul@keymail.dev\nno apps in this account\n"), 0o644); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | if err := os.WriteFile(accounts, []byte("NAME SQID ROLE\npaulca kmnpq owner\noficina bcdfg owner\nshared hjkmn member\n"), 0o644); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | script := "#!/bin/sh\n" + |
| 46 | "{ echo CALL; for a in \"$@\"; do printf 'ARG %s\\n' \"$a\"; done; printf 'PWD %s\\n' \"$(pwd)\"; env | sort | sed 's/^/ENV /'; } >> '" + calls + "'\n" + |
| 47 | "if [ \"$1\" = accounts ]; then cat '" + accounts + "'; exit 0; fi\n" + |
| 48 | "if [ \"$1\" = apps ]; then cat '" + apps + "'; exit 0; fi\n" + |
| 49 | "if [ \"$1\" = services ]; then\n" + |
| 50 | " if [ -e '" + filepath.Join(dir, "mintfail") + "' ]; then echo 'services create: unexpected response (status 502)'; exit 1; fi\n" + |
| 51 | " for last in \"$@\"; do :; done\n" + |
| 52 | " echo 'using https://console.carloku.com as paul@keymail.dev'\n" + |
| 53 | " printf 'minted service:%s/%s (role deploy, app %s, rungs edge)\\n\\n' \"${10}\" \"$last\" \"$6\"\n" + |
| 54 | " printf ' CARLOS_SERVICE_TOKEN=%s\\n\\n' '" + fakeDeployToken + "'\n" + |
| 55 | " exit 0\n" + |
| 56 | "fi\n" + |
| 57 | "if [ -e '" + filepath.Join(dir, "fail") + "' ]; then echo 'deploy: upload failed'; exit 1; fi\n" + |
| 58 | "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" + |
| 59 | "for last in \"$@\"; do :; done\n" + |
| 60 | "rm -rf '" + served + "' && cp -R \"$last\" '" + served + "'\n" + |
| 61 | "echo \"deploying " + live + "\"\n" + |
| 62 | "printf '\\033[32mlive\\033[0m %s\\n' '" + live + "'\n" |
| 63 | if err := os.WriteFile(bin, []byte(script), 0o755); err != nil { |
| 64 | t.Fatal(err) |
| 65 | } |
| 66 | return bin, calls, served |
| 67 | } |
| 68 | |
| 69 | // carlosRun is one recorded run of the fake carlos. |
| 70 | type carlosRun struct { |
| 71 | args []string |
| 72 | pwd string |
| 73 | env []string |
| 74 | } |
| 75 | |
| 76 | func carlosRuns(t *testing.T, calls string) []carlosRun { |
| 77 | t.Helper() |
| 78 | raw, err := os.ReadFile(calls) |
| 79 | if errors.Is(err, os.ErrNotExist) { |
| 80 | return nil |
| 81 | } |
| 82 | if err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | var out []carlosRun |
| 86 | for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") { |
| 87 | switch { |
| 88 | case line == "CALL": |
| 89 | out = append(out, carlosRun{}) |
| 90 | case strings.HasPrefix(line, "ARG "): |
| 91 | out[len(out)-1].args = append(out[len(out)-1].args, strings.TrimPrefix(line, "ARG ")) |
| 92 | case strings.HasPrefix(line, "PWD "): |
| 93 | out[len(out)-1].pwd = strings.TrimPrefix(line, "PWD ") |
| 94 | case strings.HasPrefix(line, "ENV "): |
| 95 | out[len(out)-1].env = append(out[len(out)-1].env, strings.TrimPrefix(line, "ENV ")) |
| 96 | } |
| 97 | } |
| 98 | return out |
| 99 | } |
| 100 | |
| 101 | func (r carlosRun) envOf(key string) (string, bool) { |
| 102 | for _, kv := range r.env { |
| 103 | if v, ok := strings.CutPrefix(kv, key+"="); ok { |
| 104 | return v, true |
| 105 | } |
| 106 | } |
| 107 | return "", false |
| 108 | } |
| 109 | |
| 110 | func verbsOf(runs []carlosRun) []string { |
| 111 | var out []string |
| 112 | for _, r := range runs { |
| 113 | out = append(out, strings.Join(r.args[:2], " ")) |
| 114 | } |
| 115 | return out |
| 116 | } |
| 117 | |
| 118 | // siteRig is a remote whose default branch holds the merged commit of a |
| 119 | // website task (and a task branch beside it), an Engineer with CARLOS |
| 120 | // sites through the fake carlos and the person's login, and a marker |
| 121 | // origin that serves what carlos was last given. |
| 122 | type siteRig struct { |
| 123 | e *Engineer |
| 124 | r stepRow |
| 125 | merged string |
| 126 | unmerged string |
| 127 | bin string |
| 128 | calls string |
| 129 | apps string |
| 130 | creds string |
| 131 | planted string |
| 132 | logs *bytes.Buffer |
| 133 | confirms []string |
| 134 | } |
| 135 | |
| 136 | const ( |
| 137 | rigConsole = "console.carloku.com" |
| 138 | rigSqid = "kmnpq" |
| 139 | rigName = "paulca" |
| 140 | rigApp = "site-sample" |
| 141 | rigKeyName = "eq-sample-ab12" |
| 142 | ) |
| 143 | |
| 144 | // target is a dispatch for the rig's place in mode. |
| 145 | func rigTarget(mode string) *wire.PublishDispatch { |
| 146 | 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} |
| 147 | if mode != wire.SitePublish { |
| 148 | d.DeployName = rigKeyName |
| 149 | } |
| 150 | return d |
| 151 | } |
| 152 | |
| 153 | func newSiteRig(t *testing.T, files map[string]string) *siteRig { |
| 154 | t.Helper() |
| 155 | root := t.TempDir() |
| 156 | work := filepath.Join(root, "seed") |
| 157 | gitOut(t, root, "init", "-q", "-b", "main", work) |
| 158 | os.WriteFile(filepath.Join(work, "README.md"), []byte("sample\n"), 0o644) |
| 159 | gitOut(t, work, "add", "-A") |
| 160 | gitOut(t, work, "commit", "-q", "-m", "base") |
| 161 | gitOut(t, work, "checkout", "-q", "-b", "equipo/tk1-quick-site") |
| 162 | for p, body := range files { |
| 163 | os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0o755) |
| 164 | os.WriteFile(filepath.Join(work, p), []byte(body), 0o644) |
| 165 | } |
| 166 | gitOut(t, work, "add", "-A") |
| 167 | gitOut(t, work, "commit", "-q", "-m", "site") |
| 168 | gitOut(t, work, "checkout", "-q", "main") |
| 169 | gitOut(t, work, "merge", "-q", "--no-ff", "-m", "Merge the site", "equipo/tk1-quick-site") |
| 170 | merged := gitOut(t, work, "rev-parse", "HEAD") |
| 171 | // A commit on another branch only: never on the default branch. |
| 172 | gitOut(t, work, "checkout", "-q", "-b", "equipo/tk2-other") |
| 173 | os.WriteFile(filepath.Join(work, "site", "extra.html"), []byte("<p>not merged</p>\n"), 0o644) |
| 174 | gitOut(t, work, "add", "-A") |
| 175 | gitOut(t, work, "commit", "-q", "-m", "unmerged") |
| 176 | unmerged := gitOut(t, work, "rev-parse", "HEAD") |
| 177 | remote := filepath.Join(root, "remote.git") |
| 178 | gitOut(t, root, "clone", "-q", "--bare", work, remote) |
| 179 | for _, d := range []string{"state", "work", "bin", "home/.carlos", ".carlos", "state/.carlos"} { |
| 180 | os.MkdirAll(filepath.Join(root, d), 0o700) |
| 181 | } |
| 182 | // The person's own configuration, where carlos would find it walking |
| 183 | // up from the runner's folders: another console and account. |
| 184 | planted := `{"console": "https://console.evil.example", "account": "elsewhere"}` |
| 185 | os.WriteFile(filepath.Join(root, ".carlos", "config"), []byte(planted), 0o600) |
| 186 | os.WriteFile(filepath.Join(root, "state", ".carlos", "config"), []byte(planted), 0o600) |
| 187 | creds := filepath.Join(root, "home", ".carlos", "credentials") |
| 188 | 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) |
| 189 | s, err := OpenState(context.Background(), filepath.Join(root, "state")) |
| 190 | if err != nil { |
| 191 | t.Fatal(err) |
| 192 | } |
| 193 | t.Cleanup(func() { s.Close() }) |
| 194 | bin, calls, served := fakeCarlosScript(t, filepath.Join(root, "bin"), "https://site-sample.bds.oncarlos.com") |
| 195 | origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 196 | if r.URL.Path != "/"+siteMarker { |
| 197 | http.NotFound(w, r) |
| 198 | return |
| 199 | } |
| 200 | http.ServeFile(w, r, filepath.Join(served, siteMarker)) |
| 201 | })) |
| 202 | t.Cleanup(origin.Close) |
| 203 | rig := &siteRig{merged: merged, unmerged: unmerged, bin: bin, calls: calls, apps: filepath.Join(root, "bin", "apps"), creds: creds, planted: planted, logs: &bytes.Buffer{}} |
| 204 | f := &hubForge{dir: remote} |
| 205 | check := func(purpose string) func(context.Context, string, int64, string, string) error { |
| 206 | return func(_ context.Context, step string, attempt int64, digest, destination string) error { |
| 207 | rig.confirms = append(rig.confirms, purpose+":"+step+"/"+itoa(attempt)+"/"+digest+"/"+destination) |
| 208 | return nil |
| 209 | } |
| 210 | } |
| 211 | e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test", |
| 212 | Site: &SiteOptions{Carlos: bin, Credentials: creds, State: filepath.Join(root, "state", "site"), URL: func(string) string { return origin.URL }}, |
| 213 | ConfirmPublish: check("publish"), ConfirmMint: check("mint")} |
| 214 | 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 |
| 215 | e.O.Runner.Executable = previewScannerFixture(t) |
| 216 | e.O.Logger = slog.New(slog.NewTextHandler(rig.logs, &slog.HandlerOptions{Level: slog.LevelDebug})) |
| 217 | rig.e = e |
| 218 | 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)}} |
| 219 | if err := s.AcceptDispatch(context.Background(), "d1", rig.r.DispatchCommand); err != nil { |
| 220 | t.Fatal(err) |
| 221 | } |
| 222 | previewVerifyFor, previewVerifyEvery = 300*time.Millisecond, 50*time.Millisecond |
| 223 | return rig |
| 224 | } |
| 225 | |
| 226 | // step is the rig's step in mode with id. |
| 227 | func (rig *siteRig) step(id, mode string) stepRow { |
| 228 | r := rig.r |
| 229 | r.StepID, r.Publish = id, rigTarget(mode) |
| 230 | return r |
| 231 | } |
| 232 | |
| 233 | // noSecretOutsideKeys: the deploy key's secret is only in its key file: |
| 234 | // never in a report, the logs, argv, or any other file of the state. |
| 235 | func (rig *siteRig) noSecretOutsideKeys(t *testing.T, reports ...wire.StepReport) { |
| 236 | t.Helper() |
| 237 | for _, rep := range reports { |
| 238 | raw, _ := json.Marshal(rep) |
| 239 | if strings.Contains(string(raw), fakeDeployToken) { |
| 240 | t.Fatalf("the secret is in a report: %s", raw) |
| 241 | } |
| 242 | } |
| 243 | if strings.Contains(rig.logs.String(), fakeDeployToken) || strings.Contains(rig.logs.String(), "login-secret") { |
| 244 | t.Fatalf("the secret is in the logs: %s", rig.logs) |
| 245 | } |
| 246 | for _, run := range carlosRuns(t, rig.calls) { |
| 247 | if strings.Contains(strings.Join(run.args, " "), fakeDeployToken) { |
| 248 | t.Fatalf("the secret is in argv %q", run.args) |
| 249 | } |
| 250 | } |
| 251 | keys := filepath.Join(rig.e.Site.State, "keys") |
| 252 | filepath.WalkDir(rig.e.O.Runner.StateDir, func(p string, d fs.DirEntry, err error) error { |
| 253 | if err != nil || d.IsDir() || strings.HasPrefix(p, keys+string(filepath.Separator)) { |
| 254 | return nil |
| 255 | } |
| 256 | if raw, err := os.ReadFile(p); err == nil && bytes.Contains(raw, []byte(fakeDeployToken)) { |
| 257 | t.Fatalf("the secret is in %s", p) |
| 258 | } |
| 259 | return nil |
| 260 | }) |
| 261 | } |
| 262 | |
| 263 | var quickSite = map[string]string{ |
| 264 | "release/preview.json": `{"output": "site"}`, |
| 265 | "site/index.html": "<h1>Quick site</h1>\n", |
| 266 | "site/style.css": "body{margin:0}\n", |
| 267 | "site/_headers": "/*\n Cache-Control: max-age=60\n", |
| 268 | "src/kept-out.txt": "not published\n", |
| 269 | } |
| 270 | |
| 271 | // TestSiteSetupThenPublish: a setup exports the merged commit's site from |
| 272 | // git objects, scans it, reports it built; for a name this runner has no |
| 273 | // record of, reads the account's apps with the person's login (the name |
| 274 | // must be free); deploys with the login behind its publish check; then |
| 275 | // behind its mint check mints the app's edge-only deploy key, stored 0600 |
| 276 | // and reported only as held. Every command has fixed flags naming the |
| 277 | // place's sqid and console, from an empty private directory whose |
| 278 | // environment holds only what it needs. The next publish deploys with the |
| 279 | // key alone: the login is not in its environment. The project's own |
| 280 | // _headers is published; Equipo adds none. The secret is nowhere else. |
| 281 | func TestSiteSetupThenPublish(t *testing.T) { |
| 282 | rig := newSiteRig(t, quickSite) |
| 283 | var built *wire.PublishResult |
| 284 | rep := rig.e.Exec(context.Background(), rig.r, func(p wire.StepReport) { |
| 285 | if p.Publish != nil { |
| 286 | built = p.Publish |
| 287 | } |
| 288 | }) |
| 289 | if built == nil || built.Phase != wire.PublishBuilt || built.Files != 3 || len(built.Digest) != 64 { |
| 290 | t.Fatalf("built %+v", built) |
| 291 | } |
| 292 | 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 { |
| 293 | t.Fatalf("report %+v %+v", rep, rep.Publish) |
| 294 | } |
| 295 | dest := wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp) |
| 296 | if want := []string{"publish:s_pub1/1/" + built.Digest + "/" + dest, "mint:s_pub1/1/" + built.Digest + "/" + dest}; !slices.Equal(rig.confirms, want) { |
| 297 | t.Fatalf("checks %v\nwant %v", rig.confirms, want) |
| 298 | } |
| 299 | runs := carlosRuns(t, rig.calls) |
| 300 | if got := verbsOf(runs); !slices.Equal(got, []string{"apps list", "deploy --kind", "services create"}) { |
| 301 | t.Fatalf("runs %v", got) |
| 302 | } |
| 303 | origin := "https://" + rigConsole |
| 304 | if want := []string{"apps", "list", "--account-id", rigSqid, "--console", origin}; !slices.Equal(runs[0].args, want) { |
| 305 | t.Fatalf("list argv %q", runs[0].args) |
| 306 | } |
| 307 | stage := runs[1].args[len(runs[1].args)-1] |
| 308 | version := "s-" + rig.merged[:12] + "-pub1-1" |
| 309 | 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 { |
| 310 | t.Fatalf("deploy argv %q", runs[1].args) |
| 311 | } |
| 312 | if want := []string{"services", "create", "--role", "deploy", "--app", rigApp, "--rungs", "edge", "--account-id", rigSqid, "--console", origin, rigKeyName}; !slices.Equal(runs[2].args, want) { |
| 313 | t.Fatalf("mint argv %q", runs[2].args) |
| 314 | } |
| 315 | for _, run := range runs { |
| 316 | for _, kv := range run.env { |
| 317 | k, _, _ := strings.Cut(kv, "=") |
| 318 | if !slices.Contains([]string{"HOME", "PATH", "CARLOS_CREDENTIALS", "CARLOS_CONFIG", "CARLOS_NO_UPDATE_CHECK", "PWD", "SHLVL", "_"}, k) { |
| 319 | t.Fatalf("a login run saw %s", kv) |
| 320 | } |
| 321 | } |
| 322 | if v, _ := run.envOf("CARLOS_CREDENTIALS"); v != rig.creds { |
| 323 | t.Fatalf("login run credentials %q", v) |
| 324 | } |
| 325 | config, _ := run.envOf("CARLOS_CONFIG") |
| 326 | raw, err := os.ReadFile(config) |
| 327 | if !strings.HasPrefix(config, rig.e.Site.State) || err != nil || strings.TrimSpace(string(raw)) != "{}" { |
| 328 | t.Fatalf("configuration %q: %q %v", config, raw, err) |
| 329 | } |
| 330 | if home, _ := run.envOf("HOME"); home != run.pwd || !strings.HasPrefix(run.pwd, rig.e.Site.State) { |
| 331 | t.Fatalf("ran from %s with HOME %s", run.pwd, home) |
| 332 | } |
| 333 | if strings.Contains(strings.Join(run.args, " "), "evil") || strings.Contains(strings.Join(run.args, " "), "elsewhere") { |
| 334 | t.Fatalf("the planted configuration reached argv %q", run.args) |
| 335 | } |
| 336 | } |
| 337 | served := map[string]bool{} |
| 338 | entries, _ := os.ReadDir(filepath.Join(filepath.Dir(rig.calls), "served")) |
| 339 | for _, en := range entries { |
| 340 | served[en.Name()] = true |
| 341 | } |
| 342 | if len(served) != 4 || !served["index.html"] || !served["style.css"] || !served["_headers"] || !served[siteMarker] { |
| 343 | t.Fatalf("published %v", served) |
| 344 | } |
| 345 | if raw, _ := os.ReadFile(filepath.Join(filepath.Dir(rig.calls), "served", "_headers")); string(raw) != quickSite["site/_headers"] { |
| 346 | t.Fatalf("the project's _headers changed: %q", raw) |
| 347 | } |
| 348 | keyFile := filepath.Join(rig.e.Site.State, "keys", rigConsole, rigSqid, rigApp+".json") |
| 349 | info, err := os.Stat(keyFile) |
| 350 | if err != nil || info.Mode().Perm() != 0o600 { |
| 351 | t.Fatalf("key file %v %v", info, err) |
| 352 | } |
| 353 | if dir, _ := os.Stat(filepath.Dir(keyFile)); dir.Mode().Perm() != 0o700 { |
| 354 | t.Fatalf("key folder mode %v", dir.Mode()) |
| 355 | } |
| 356 | reach := rig.e.Site.Reach(context.Background()) |
| 357 | 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 { |
| 358 | t.Fatalf("reach %+v", reach) |
| 359 | } |
| 360 | 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"}}) { |
| 361 | t.Fatalf("logins %+v", reach.Logins) |
| 362 | } |
| 363 | if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil { |
| 364 | t.Fatalf("reach invalid: %v", err) |
| 365 | } |
| 366 | // The next publish: the key alone. |
| 367 | rig.confirms = nil |
| 368 | next := rig.e.Exec(context.Background(), rig.step("s_pub2", wire.SitePublish), func(wire.StepReport) {}) |
| 369 | if next.State != wire.StepDone || next.Publish.Outcome != wire.PublishPublished || !next.Publish.DeployHeld { |
| 370 | t.Fatalf("second publish %+v %+v", next, next.Publish) |
| 371 | } |
| 372 | runs = carlosRuns(t, rig.calls) |
| 373 | last := runs[len(runs)-1] |
| 374 | if got := verbsOf(runs); !slices.Equal(got, []string{"apps list", "deploy --kind", "services create", "accounts list", "deploy --kind"}) { |
| 375 | t.Fatalf("runs %v", got) |
| 376 | } |
| 377 | if tok, _ := last.envOf("CARLOS_SERVICE_TOKEN"); tok != fakeDeployToken { |
| 378 | t.Fatal("the publish did not use the deploy key") |
| 379 | } |
| 380 | if c, _ := last.envOf("CARLOS_CONSOLE"); c != origin { |
| 381 | t.Fatalf("console %q", c) |
| 382 | } |
| 383 | if v, _ := last.envOf("CARLOS_CREDENTIALS"); v == rig.creds || !strings.HasPrefix(v, rig.e.Site.State) { |
| 384 | t.Fatalf("the login reached a key publish: %q", v) |
| 385 | } else if _, err := os.Stat(v); err == nil { |
| 386 | t.Fatalf("the absent credentials file exists: %s", v) |
| 387 | } |
| 388 | if len(rig.confirms) != 1 || !strings.HasPrefix(rig.confirms[0], "publish:s_pub2/") { |
| 389 | t.Fatalf("checks %v", rig.confirms) |
| 390 | } |
| 391 | rig.noSecretOutsideKeys(t, rep, next) |
| 392 | } |
| 393 | |
| 394 | // TestSiteSetupNameTaken: before a setup's deploy, an app of that name |
| 395 | // already in the account (live, kept, in the Trash, with or without the |
| 396 | // header and region), or a list that cannot be read strictly, refuses the |
| 397 | // publish before its check: nothing is deployed or minted. |
| 398 | func TestSiteSetupNameTaken(t *testing.T) { |
| 399 | using := "using https://console.carloku.com as p@x\n" |
| 400 | for name, list := range map[string]string{ |
| 401 | "live": using + listHeader + "site-sample live eu-west expires in 3 days\n", |
| 402 | "no header": using + "site-sample live\n", |
| 403 | "trashed": using + listHeader + "site-sample trashed eu-west\n", |
| 404 | "unreadable": "something went wrong\n", |
| 405 | "no using": "no apps in this account\n", |
| 406 | "odd line": using + "other-app live\nwhat is this\n", |
| 407 | } { |
| 408 | rig := newSiteRig(t, quickSite) |
| 409 | os.WriteFile(rig.apps, []byte(list), 0o644) |
| 410 | rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) |
| 411 | runs := carlosRuns(t, rig.calls) |
| 412 | if rep.State != wire.StepFailed || rep.Reason != "publish_app_taken" || len(runs) != 1 || runs[0].args[0] != "apps" || len(rig.confirms) != 0 { |
| 413 | t.Fatalf("%s: %+v, runs %v, checks %v", name, rep, verbsOf(runs), rig.confirms) |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // TestSiteListed: the strict list parser. |
| 419 | func TestSiteListed(t *testing.T) { |
| 420 | using := "using https://console.carloku.com as p@x\n" |
| 421 | for name, c := range map[string]struct { |
| 422 | out string |
| 423 | present, ok bool |
| 424 | }{ |
| 425 | "empty account": {using + "no apps in this account\n", false, true}, |
| 426 | "others, header": {using + listHeader + "site-other live\n", false, true}, |
| 427 | "others, none": {using + "site-other live\nsite-third trashed\n", false, true}, |
| 428 | "listed, region": {using + listHeader + "site-sample live eu-west expires in 2 days\n", true, true}, |
| 429 | "listed, plain": {"\x1b[2m" + using + "\x1b[0msite-sample live\n", true, true}, |
| 430 | "header only": {using + listHeader, false, false}, |
| 431 | "nothing": {"", false, false}, |
| 432 | "no using": {"site-other live\n", false, false}, |
| 433 | "bad state": {using + "site-other gone\n", false, false}, |
| 434 | "empty then apps": {using + "no apps in this account\nsite-sample live\n", false, false}, |
| 435 | } { |
| 436 | present, ok := siteListed(c.out, "site-sample") |
| 437 | if present != c.present || ok != c.ok { |
| 438 | t.Errorf("%s: present %t ok %t", name, present, ok) |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | // TestSiteMintRecovery: a mint runs only with this runner's own record of |
| 444 | // creating the app at exactly this place: behind its mint check, it mints |
| 445 | // with the login, then deploys with the new key behind its publish check, |
| 446 | // never with the login. With no record it never adopts: an app it did not |
| 447 | // make refuses publish_app_unproven, a missing app publish_app_missing, |
| 448 | // an unreadable list fails; none mints or deploys. A record for another |
| 449 | // account proves nothing here. |
| 450 | func TestSiteMintRecovery(t *testing.T) { |
| 451 | rig := newSiteRig(t, quickSite) |
| 452 | if err := rig.e.Site.created(siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp}, "tk1"); err != nil { |
| 453 | t.Fatal(err) |
| 454 | } |
| 455 | rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SiteMint), func(wire.StepReport) {}) |
| 456 | if rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished || !rep.Publish.DeployHeld { |
| 457 | t.Fatalf("mint %+v %+v", rep, rep.Publish) |
| 458 | } |
| 459 | runs := carlosRuns(t, rig.calls) |
| 460 | if got := verbsOf(runs); !slices.Equal(got, []string{"services create", "deploy --kind"}) { |
| 461 | t.Fatalf("runs %v", got) |
| 462 | } |
| 463 | if v, _ := runs[0].envOf("CARLOS_CREDENTIALS"); v != rig.creds { |
| 464 | t.Fatal("the mint did not use the login") |
| 465 | } |
| 466 | if tok, _ := runs[1].envOf("CARLOS_SERVICE_TOKEN"); tok != fakeDeployToken { |
| 467 | t.Fatal("the deploy after a mint did not use the new key") |
| 468 | } |
| 469 | if v, _ := runs[1].envOf("CARLOS_CREDENTIALS"); v == rig.creds { |
| 470 | t.Fatal("the login deployed a created app again") |
| 471 | } |
| 472 | if len(rig.confirms) != 2 || !strings.HasPrefix(rig.confirms[0], "mint:") || !strings.HasPrefix(rig.confirms[1], "publish:") { |
| 473 | t.Fatalf("checks %v", rig.confirms) |
| 474 | } |
| 475 | rig.noSecretOutsideKeys(t, rep) |
| 476 | |
| 477 | using := "using https://console.carloku.com as p@x\n" |
| 478 | for name, c := range map[string]struct{ list, reason string }{ |
| 479 | "not ours": {using + "site-sample live\n", reasonPublishAppUnproven}, |
| 480 | "absent": {using + "no apps in this account\n", reasonPublishAppMissing}, |
| 481 | "unreadable": {"oops\n", "publish_failed"}, |
| 482 | } { |
| 483 | rig := newSiteRig(t, quickSite) |
| 484 | // Another account's record is no proof here. |
| 485 | rig.e.Site.created(siteTarget{Console: rigConsole, Sqid: "bcdfg", App: rigApp}, "tk1") |
| 486 | os.WriteFile(rig.apps, []byte(c.list), 0o644) |
| 487 | rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SiteMint), func(wire.StepReport) {}) |
| 488 | if rep.State != wire.StepFailed || rep.Reason != c.reason || len(rig.confirms) != 0 { |
| 489 | t.Fatalf("%s: %+v checks %v", name, rep, rig.confirms) |
| 490 | } |
| 491 | if got := verbsOf(carlosRuns(t, rig.calls)); !slices.Equal(got, []string{"apps list"}) { |
| 492 | t.Fatalf("%s: runs %v", name, got) |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | // TestSiteMintLost: a mint whose answer fails or cannot be read leaves no |
| 498 | // key, and the runner says the name is lost (it may be live on CARLOS) |
| 499 | // until it holds a key; the setup's site is still published. A refused |
| 500 | // mint check mints nothing and loses nothing. |
| 501 | func TestSiteMintLost(t *testing.T) { |
| 502 | rig := newSiteRig(t, quickSite) |
| 503 | os.WriteFile(filepath.Join(filepath.Dir(rig.calls), "mintfail"), nil, 0o644) |
| 504 | rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) |
| 505 | if rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.DeployHeld { |
| 506 | t.Fatalf("lost mint %+v %+v", rep, rep.Publish) |
| 507 | } |
| 508 | reach := rig.e.Site.Reach(context.Background()) |
| 509 | if len(reach.Deploys) != 1 || !reach.Deploys[0].Lost || reach.Deploys[0].Name != rigKeyName || reach.Deploys[0].Fingerprint != "" { |
| 510 | t.Fatalf("reach %+v", reach.Deploys) |
| 511 | } |
| 512 | if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil { |
| 513 | t.Fatalf("reach invalid: %v", err) |
| 514 | } |
| 515 | // A mint step recovers it with a new key: held, and the first one's |
| 516 | // name still said lost (CARLOS may hold it live). |
| 517 | os.Remove(filepath.Join(filepath.Dir(rig.calls), "mintfail")) |
| 518 | recovery := rig.step("s_pub2", wire.SiteMint) |
| 519 | recovery.Publish.DeployName = "eq-sample-cd34" |
| 520 | again := rig.e.Exec(context.Background(), recovery, func(wire.StepReport) {}) |
| 521 | if again.State != wire.StepDone || !again.Publish.DeployHeld { |
| 522 | t.Fatalf("recovery %+v %+v", again, again.Publish) |
| 523 | } |
| 524 | reach = rig.e.Site.Reach(context.Background()) |
| 525 | 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 { |
| 526 | t.Fatalf("after recovery %+v", reach.Deploys) |
| 527 | } |
| 528 | if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil { |
| 529 | t.Fatalf("reach invalid: %v", err) |
| 530 | } |
| 531 | |
| 532 | rig = newSiteRig(t, quickSite) |
| 533 | rig.e.ConfirmMint = func(context.Context, string, int64, string, string) error { return ErrWithdrawn } |
| 534 | rep = rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) |
| 535 | if rep.State != wire.StepDone || rep.Publish.DeployHeld { |
| 536 | t.Fatalf("refused mint check %+v", rep.Publish) |
| 537 | } |
| 538 | if got := verbsOf(carlosRuns(t, rig.calls)); !slices.Equal(got, []string{"apps list", "deploy --kind"}) { |
| 539 | t.Fatalf("runs %v", got) |
| 540 | } |
| 541 | if reach := rig.e.Site.Reach(context.Background()); len(reach.Deploys) != 0 { |
| 542 | t.Fatalf("a refused mint left %+v", reach.Deploys) |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | // TestSitePublishFence: the target, the version and the folder are checked |
| 547 | // before anything runs: a destination hash that does not bind the parts, |
| 548 | // a part out of shape, an unknown mode or a key name where none belongs is |
| 549 | // refused; so is a merged commit that is not on the default branch, a |
| 550 | // publish with no key, a key for another place, a carlos too old, a scan |
| 551 | // that finds a secret or cannot run, and an instance that refuses the |
| 552 | // check. carlos runs for none of them; none reports built. |
| 553 | func TestSitePublishFence(t *testing.T) { |
| 554 | rig := newSiteRig(t, quickSite) |
| 555 | run := func(r stepRow, want string) { |
| 556 | t.Helper() |
| 557 | built := false |
| 558 | rep := rig.e.Exec(context.Background(), r, func(p wire.StepReport) { built = built || p.Publish != nil }) |
| 559 | if n := len(carlosRuns(t, rig.calls)); n != 0 || built || rep.Reason != want || (want == "withdrawn") != (rep.State == wire.StepCancelled) { |
| 560 | t.Fatalf("%+v: %+v, %d runs, built %t; want %s", r.Publish, rep, n, built, want) |
| 561 | } |
| 562 | } |
| 563 | bad := func(f func(d *wire.PublishDispatch)) stepRow { |
| 564 | r := rig.step("s_pub1", wire.SiteSetup) |
| 565 | f(r.Publish) |
| 566 | return r |
| 567 | } |
| 568 | for name, r := range map[string]stepRow{ |
| 569 | "app flag": bad(func(d *wire.PublishDispatch) { d.App = "--help" }), |
| 570 | "app arg": bad(func(d *wire.PublishDispatch) { d.App = "site-x --account other" }), |
| 571 | "app path": bad(func(d *wire.PublishDispatch) { d.App = "site-../x" }), |
| 572 | "console path": bad(func(d *wire.PublishDispatch) { d.Console = "console.carloku.com/../x" }), |
| 573 | "console scheme": bad(func(d *wire.PublishDispatch) { d.Console = "https://console.carloku.com" }), |
| 574 | "sqid": bad(func(d *wire.PublishDispatch) { d.Account = "--all" }), |
| 575 | "rehashed": bad(func(d *wire.PublishDispatch) { d.Account = "bcdfg" }), |
| 576 | "other app": bad(func(d *wire.PublishDispatch) { d.App = "site-other" }), |
| 577 | "mode": bad(func(d *wire.PublishDispatch) { d.Mode = "adopt" }), |
| 578 | "no key name": bad(func(d *wire.PublishDispatch) { d.DeployName = "" }), |
| 579 | "key name arg": bad(func(d *wire.PublishDispatch) { d.DeployName = "eq-x --role admin" }), |
| 580 | "no target": bad(func(d *wire.PublishDispatch) { *d = wire.PublishDispatch{} }), |
| 581 | "into": bad(func(d *wire.PublishDispatch) { d.Into = "-main" }), |
| 582 | } { |
| 583 | _ = name |
| 584 | run(r, "policy_rejected") |
| 585 | } |
| 586 | pub := rig.step("s_pub1", wire.SitePublish) |
| 587 | pub.Publish.DeployName = rigKeyName |
| 588 | run(pub, "policy_rejected") |
| 589 | run(rig.step("s_pub1", wire.SitePublish), reasonPublishKeyMissing) |
| 590 | off := rig.r |
| 591 | off.CandidateSHA = rig.unmerged |
| 592 | run(off, "publish_not_merged") |
| 593 | confirm := rig.e.ConfirmPublish |
| 594 | rig.e.ConfirmPublish = func(context.Context, string, int64, string, string) error { return ErrWithdrawn } |
| 595 | os.WriteFile(rig.apps, []byte("using x\nno apps in this account\n"), 0o644) |
| 596 | 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") { |
| 597 | t.Fatalf("refused check: %+v %v", rep, verbsOf(carlosRuns(t, rig.calls))) |
| 598 | } |
| 599 | rig.e.ConfirmPublish = confirm |
| 600 | os.Remove(rig.calls) |
| 601 | // A carlos older than the minimum, or one whose version is unreadable. |
| 602 | for _, v := range []string{"v0.32.2", ""} { |
| 603 | rig.e.Site.CLI = &carlosCLI{Bin: rig.bin, Read: func(context.Context, string) string { return v }} |
| 604 | run(rig.r, wire.ReasonCarlosOutdated) |
| 605 | } |
| 606 | rig.e.Site.CLI = nil |
| 607 | // No login: a setup cannot run. |
| 608 | creds := rig.e.Site.Credentials |
| 609 | rig.e.Site.Credentials = "" |
| 610 | run(rig.r, "publish_off") |
| 611 | rig.e.Site.Credentials = creds |
| 612 | // The secret scan, on the exact export. |
| 613 | files := map[string]string{"release/preview.json": `{"output": "site"}`, "site/index.html": "<p>x</p>\n", |
| 614 | "site/config.js": `const token = "` + "ghp_" + strings.Join([]string{"Vw3K", "8pRt", "a9Qz", "6LmN", "2sDx", "7bJh", "4cFv", "0uEy", "5nWi"}, "") + `"; // gitleaks:allow` + "\n", |
| 615 | "site/gitleaks.toml": "[allowlist]\nregexes = ['.*']\n"} |
| 616 | secret := newSiteRig(t, files) |
| 617 | if rep := secret.e.Exec(context.Background(), secret.r, func(wire.StepReport) {}); rep.Reason != reasonPublishSecrets || carlosRuns(t, secret.calls) != nil { |
| 618 | t.Fatalf("a secret published: %+v", rep) |
| 619 | } |
| 620 | unscanned := newSiteRig(t, quickSite) |
| 621 | unscanned.e.O.Runner.Executable = filepath.Join(t.TempDir(), "missing-runner") |
| 622 | if rep := unscanned.e.Exec(context.Background(), unscanned.r, func(wire.StepReport) {}); rep.Reason != reasonPublishScanner || carlosRuns(t, unscanned.calls) != nil { |
| 623 | t.Fatalf("published unscanned: %+v", rep) |
| 624 | } |
| 625 | site := rig.e.Site |
| 626 | rig.e.Site = nil |
| 627 | run(rig.r, "publish_off") |
| 628 | rig.e.Site = site |
| 629 | } |
| 630 | |
| 631 | // TestSitePublishKeyForAnotherPlace: a key is found only at its own |
| 632 | // console, sqid and app: a key held for the same app in another account |
| 633 | // is not this place's. |
| 634 | func TestSitePublishKeyForAnotherPlace(t *testing.T) { |
| 635 | rig := newSiteRig(t, quickSite) |
| 636 | other := siteTarget{Console: rigConsole, Sqid: "bcdfg", Name: "oficina", App: rigApp, DeployName: rigKeyName} |
| 637 | p, _ := rig.e.Site.keyPath(other) |
| 638 | raw, _ := json.Marshal(deployKey{Console: rigConsole, Account: "bcdfg", App: rigApp, Name: rigKeyName, Token: fakeDeployToken, Fingerprint: "0123456789abcdef"}) |
| 639 | if err := writeSecret(p, raw); err != nil { |
| 640 | t.Fatal(err) |
| 641 | } |
| 642 | rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SitePublish), func(wire.StepReport) {}) |
| 643 | if rep.Reason != reasonPublishKeyMissing || carlosRuns(t, rig.calls) != nil { |
| 644 | t.Fatalf("another place's key used: %+v", rep) |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | // TestSitePublishRestart: an attempt that may have changed CARLOS only |
| 649 | // reconciles after a restart: it never deploys or mints again; the marker |
| 650 | // over the URL this attempt's deploy printed decides. A mint attempt that |
| 651 | // restarted before its deploy fails, its lost name kept. |
| 652 | func TestSitePublishRestart(t *testing.T) { |
| 653 | rig := newSiteRig(t, quickSite) |
| 654 | first := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}) |
| 655 | for _, phase := range []string{phaseSitePublishing, phaseSiteMinting} { |
| 656 | again := rig.r |
| 657 | again.Phase = phase |
| 658 | rep := rig.e.Exec(context.Background(), again, func(wire.StepReport) {}) |
| 659 | 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 { |
| 660 | t.Fatalf("%s reconciled %+v", phase, rep.Publish) |
| 661 | } |
| 662 | } |
| 663 | if n := len(carlosRuns(t, rig.calls)); n != 3 { |
| 664 | t.Fatalf("carlos ran %d times", n) |
| 665 | } |
| 666 | mint := rig.step("s_pub1", wire.SiteMint) |
| 667 | mint.Phase = phaseSiteMinting |
| 668 | if rep := rig.e.Exec(context.Background(), mint, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != reasonPublishMintFailed { |
| 669 | t.Fatalf("mint restart %+v", rep) |
| 670 | } |
| 671 | if n := len(carlosRuns(t, rig.calls)); n != 3 { |
| 672 | t.Fatalf("a restart ran carlos: %d", n) |
| 673 | } |
| 674 | } |
| 675 | |
| 676 | // TestSiteDeployArgs: the templates are built from fixed parts and |
| 677 | // checked values; nothing else can be produced, whatever they are given. |
| 678 | func TestSiteDeployArgs(t *testing.T) { |
| 679 | tg, ok := targetOf(rigTarget(wire.SiteSetup)) |
| 680 | if !ok { |
| 681 | t.Fatal("rig target refused") |
| 682 | } |
| 683 | got, err := siteDeployArgs(tg, "s-0123456789ab-pub1-1", "/state/steps/k/site") |
| 684 | 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"} |
| 685 | if err != nil || !slices.Equal(got, want) { |
| 686 | t.Fatalf("%q %v", got, err) |
| 687 | } |
| 688 | for _, c := range [][2]string{ |
| 689 | {"--console=x", "/s/site"}, |
| 690 | {"s-0123456789ab-a-1 --x", "/s/site"}, |
| 691 | {"s-0123456789AB-a-1", "/s/site"}, |
| 692 | {"s-0123456789ab-a-1", "relative/site"}, |
| 693 | {"s-0123456789ab-a-1", "/s/../site"}, |
| 694 | {"s-0123456789ab-a-1", "/s/site\n--x"}, |
| 695 | {"s-0123456789ab-a-1", "/"}, |
| 696 | } { |
| 697 | if args, err := siteDeployArgs(tg, c[0], c[1]); err == nil { |
| 698 | t.Fatalf("built %q from %q", args, c) |
| 699 | } |
| 700 | } |
| 701 | tg.DeployName = "eq x" |
| 702 | if _, err := siteMintArgs(tg); err == nil { |
| 703 | t.Fatal("a mint built with a bad name") |
| 704 | } |
| 705 | 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 { |
| 706 | t.Fatal("a key with more rungs than edge accepted") |
| 707 | } |
| 708 | 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 { |
| 709 | t.Fatal("two tokens accepted") |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | // TestProbeSite: carlos is found on PATH; the signed-in credential is used |
| 714 | // only when it is this user's own regular file, mode 0600, outside every |
| 715 | // directory a sandbox mounts (else sites still publish with held keys, |
| 716 | // and set up none); the state may not lie inside a sandbox mount. The |
| 717 | // probe runs no carlos command at all. The reach reads only the live |
| 718 | // https consoles of the credential file. |
| 719 | func TestProbeSite(t *testing.T) { |
| 720 | root := t.TempDir() |
| 721 | bin, calls, _ := fakeCarlosScript(t, root, "https://site-x.example") |
| 722 | creds := filepath.Join(root, "credentials") |
| 723 | 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) |
| 724 | t.Setenv("PATH", root+":/usr/bin:/bin") |
| 725 | t.Setenv("CARLOS_CREDENTIALS", creds) |
| 726 | c := runner.Config{StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "ws")} |
| 727 | s := ProbeSite(c, nil) |
| 728 | if s == nil || s.Carlos != bin || s.Credentials != creds { |
| 729 | t.Fatalf("probe %+v", s) |
| 730 | } |
| 731 | if carlosRuns(t, calls) != nil { |
| 732 | t.Fatal("the probe ran carlos") |
| 733 | } |
| 734 | if got := s.loginConsoles(); !slices.Equal(got, []string{wire.FlagshipConsole, wire.TitoConsole}) { |
| 735 | t.Fatalf("consoles %v", got) |
| 736 | } |
| 737 | os.Chmod(creds, 0o644) |
| 738 | if s := ProbeSite(c, nil); s == nil || s.Credentials != "" { |
| 739 | t.Fatalf("a readable credential accepted: %+v", s) |
| 740 | } |
| 741 | os.Chmod(creds, 0o600) |
| 742 | link := filepath.Join(root, "link") |
| 743 | os.Symlink(creds, link) |
| 744 | t.Setenv("CARLOS_CREDENTIALS", link) |
| 745 | if s := ProbeSite(c, nil); s == nil || s.Credentials != "" { |
| 746 | t.Fatal("a linked credential accepted") |
| 747 | } |
| 748 | inside := filepath.Join(c.WorkspaceRoot, "credentials") |
| 749 | os.MkdirAll(c.WorkspaceRoot, 0o700) |
| 750 | os.WriteFile(inside, []byte("{}"), 0o600) |
| 751 | t.Setenv("CARLOS_CREDENTIALS", inside) |
| 752 | if s := ProbeSite(c, nil); s == nil || s.Credentials != "" { |
| 753 | t.Fatal("a credential inside the workspace accepted") |
| 754 | } |
| 755 | if ProbeSite(runner.Config{StateDir: filepath.Join(c.WorkspaceRoot, "state"), WorkspaceRoot: c.WorkspaceRoot}, nil) != nil { |
| 756 | t.Fatal("site state inside the workspace accepted") |
| 757 | } |
| 758 | if ProbeSite(runner.Config{WorkspaceRoot: c.WorkspaceRoot}, nil) != nil { |
| 759 | t.Fatal("paired with no state") |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | // TestOwnedAccounts: only the owner rows of a NAME SQID ROLE table, each |
| 764 | // validated; anything else is no account at all. |
| 765 | func TestOwnedAccounts(t *testing.T) { |
| 766 | got := ownedAccounts("NAME SQID ROLE\npaulca kmnpq owner\nfriend bcdfg member\nbad-- -x owner\npaulca kmnpq owner\nkeymail hjkmn owner extra\n") |
| 767 | if !slices.Equal(got, []wire.ReachAccount{{Name: "paulca", Sqid: "kmnpq"}}) { |
| 768 | t.Fatalf("accounts %+v", got) |
| 769 | } |
| 770 | if got := ownedAccounts("Error: not logged in\n"); len(got) != 0 { |
| 771 | t.Fatalf("accounts from an error %+v", got) |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | // TestCarlosHealth: the version comes from carlos's own first line; the |
| 776 | // health is missing with no binary, outdated when the version is |
| 777 | // unreadable or below the minimum, else ok with the version. |
| 778 | func TestCarlosHealth(t *testing.T) { |
| 779 | dir := t.TempDir() |
| 780 | write := func(name, out string) string { |
| 781 | p := filepath.Join(dir, name) |
| 782 | os.WriteFile(p, []byte("#!/bin/sh\n[ \"$1\" = version ] && printf '"+out+"'\n"), 0o755) |
| 783 | return p |
| 784 | } |
| 785 | 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") |
| 786 | if v := carlosVersionOf(context.Background(), cur); v != "v0.43.3" { |
| 787 | t.Fatalf("version %q", v) |
| 788 | } |
| 789 | 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, ""}} { |
| 790 | c := &carlosCLI{Bin: bin, Read: carlosVersionOf} |
| 791 | if state, v := c.Health(context.Background()); state != want[0] || v != want[1] { |
| 792 | t.Errorf("%s: %s %s", bin, state, v) |
| 793 | } |
| 794 | } |
| 795 | var nilCLI *carlosCLI |
| 796 | if state, _ := nilCLI.Health(context.Background()); state != wire.CarlosMissing { |
| 797 | t.Fatal("no carlos is not missing") |
| 798 | } |
| 799 | } |
| 800 | |
| 801 | // TestHandshakeHelloWithholdsPlaces: the first hello never carries the |
| 802 | // reach or the carlos health (an older instance would refuse it); after a |
| 803 | // protocol 31 welcome the next hello, sent at once, does; at 30 none ever |
| 804 | // does, and the publish and mint checks are refused here, never sent. |
| 805 | func TestHandshakeHelloWithholdsPlaces(t *testing.T) { |
| 806 | hello := func() wire.Hello { |
| 807 | 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"}, |
| 808 | 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{}}}} |
| 809 | } |
| 810 | for _, protocol := range []int{wire.ProtocolAssistantFiles, wire.ProtocolPlaces} { |
| 811 | inst := newFakeInstance(t) |
| 812 | link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) |
| 813 | c := <-inst.conns |
| 814 | _, raw := read(t, c, wire.FrameHello) |
| 815 | if strings.Contains(string(raw), `"reach"`) || strings.Contains(string(raw), `"carlos`) || !strings.Contains(string(raw), `"linux"`) { |
| 816 | t.Fatalf("handshake hello: %s", raw) |
| 817 | } |
| 818 | 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"}`)}) |
| 819 | write(t, c, welcome) |
| 820 | read(t, c, wire.FrameSync) |
| 821 | _, raw = read(t, c, wire.FrameHello) |
| 822 | if got := strings.Contains(string(raw), `"reach"`) && strings.Contains(string(raw), `"carlos":"ok"`); got != (protocol >= wire.ProtocolPlaces) { |
| 823 | t.Fatalf("protocol %d hello: %s", protocol, raw) |
| 824 | } |
| 825 | if protocol < wire.ProtocolPlaces { |
| 826 | dest := wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp) |
| 827 | if err := link.ConfirmPublish(context.Background(), "s_1", 1, strings.Repeat("a", 64), dest); !errors.Is(err, ErrNoAuthority) { |
| 828 | t.Fatalf("a deploy check at %d: %v", protocol, err) |
| 829 | } |
| 830 | if err := link.ConfirmMint(context.Background(), "s_1", 1, strings.Repeat("a", 64), dest); !errors.Is(err, ErrNoAuthority) { |
| 831 | t.Fatalf("a mint check at %d: %v", protocol, err) |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | // TestSiteSetupFailedDeploy: attempted is never proven. A setup whose |
| 838 | // deploy failed having made nothing records nothing, so an app someone |
| 839 | // else makes later is never adopted by a mint; one whose deploy made the |
| 840 | // app (it is listed right after the failure, the name free just before) |
| 841 | // is recorded as made here, and a mint gets its key. |
| 842 | func TestSiteSetupFailedDeploy(t *testing.T) { |
| 843 | rig := newSiteRig(t, quickSite) |
| 844 | os.WriteFile(filepath.Join(filepath.Dir(rig.calls), "fail"), nil, 0o644) |
| 845 | if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); rep.Reason != "publish_failed" || rep.Publish.DeployHeld { |
| 846 | t.Fatalf("failed deploy %+v", rep) |
| 847 | } |
| 848 | if rig.e.Site.madeHere(siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp}) { |
| 849 | t.Fatal("a deploy that made nothing recorded the app as made here") |
| 850 | } |
| 851 | os.Remove(filepath.Join(filepath.Dir(rig.calls), "fail")) |
| 852 | // Someone else makes the app meanwhile: the mint refuses it. |
| 853 | os.WriteFile(rig.apps, []byte("using https://console.carloku.com as p@x\nsite-sample live\n"), 0o644) |
| 854 | if rep := rig.e.Exec(context.Background(), rig.step("s_pub2", wire.SiteMint), func(wire.StepReport) {}); rep.Reason != reasonPublishAppUnproven { |
| 855 | t.Fatalf("adopted: %+v", rep) |
| 856 | } |
| 857 | if slices.Contains(verbsOf(carlosRuns(t, rig.calls)), "services create") { |
| 858 | t.Fatal("minted for an app not made here") |
| 859 | } |
| 860 | |
| 861 | half := newSiteRig(t, quickSite) |
| 862 | os.WriteFile(filepath.Join(filepath.Dir(half.calls), "halffail"), nil, 0o644) |
| 863 | if rep := half.e.Exec(context.Background(), half.r, func(wire.StepReport) {}); rep.Reason != "publish_failed" { |
| 864 | t.Fatalf("half-failed deploy %+v", rep) |
| 865 | } |
| 866 | if !half.e.Site.madeHere(siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp}) { |
| 867 | t.Fatal("the app the deploy made is not recorded") |
| 868 | } |
| 869 | os.Remove(filepath.Join(filepath.Dir(half.calls), "halffail")) |
| 870 | if rep := half.e.Exec(context.Background(), half.step("s_pub2", wire.SiteMint), func(wire.StepReport) {}); rep.State != wire.StepDone || !rep.Publish.DeployHeld { |
| 871 | t.Fatalf("mint after a half-failed deploy %+v", rep) |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | // TestSiteLostAndHeld: a stop between storing a key and removing its |
| 876 | // intent leaves both; the key wins, the spent intent goes, and the reach |
| 877 | // stays valid (one entry per key). |
| 878 | func TestSiteLostAndHeld(t *testing.T) { |
| 879 | rig := newSiteRig(t, quickSite) |
| 880 | if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); !rep.Publish.DeployHeld { |
| 881 | t.Fatalf("setup %+v", rep.Publish) |
| 882 | } |
| 883 | tg := siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp, DeployName: rigKeyName} |
| 884 | lost, _ := rig.e.Site.lostPath(tg) |
| 885 | if err := writeSecret(lost, []byte(`{"name":"`+rigKeyName+`"}`)); err != nil { |
| 886 | t.Fatal(err) |
| 887 | } |
| 888 | reach := rig.e.Site.Reach(context.Background()) |
| 889 | if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil || len(reach.Deploys) != 1 || reach.Deploys[0].Lost { |
| 890 | t.Fatalf("reach %+v %v", reach.Deploys, err) |
| 891 | } |
| 892 | if _, err := os.Stat(lost); !errors.Is(err, os.ErrNotExist) { |
| 893 | t.Fatal("the spent intent stayed") |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | // TestRecoverStepsKeepsSiteMinting: a publish that restarted while it |
| 898 | // minted is reconciled, never ended as a plain restart. |
| 899 | func TestRecoverStepsKeepsSiteMinting(t *testing.T) { |
| 900 | ctx := context.Background() |
| 901 | s, err := OpenState(ctx, t.TempDir()) |
| 902 | if err != nil { |
| 903 | t.Fatal(err) |
| 904 | } |
| 905 | defer s.Close() |
| 906 | for i, phase := range []string{phaseSitePublishing, phaseSiteMinting} { |
| 907 | d := dispatchFor("tk"+itoa(int64(i)), "s_p"+itoa(int64(i)), 1) |
| 908 | d.Specialist, d.CandidateSHA, d.Publish = wire.SpecialistPublish, strings.Repeat("a", 40), rigTarget(wire.SiteSetup) |
| 909 | if err := s.AcceptDispatch(ctx, "c"+itoa(int64(i)), d); err != nil { |
| 910 | t.Fatal(err) |
| 911 | } |
| 912 | if err := s.setStepPhase(ctx, stepRow{DispatchCommand: d}, phase, "", d.CandidateSHA); err != nil { |
| 913 | t.Fatal(err) |
| 914 | } |
| 915 | } |
| 916 | if err := s.RecoverSteps(ctx, nil); err != nil { |
| 917 | t.Fatal(err) |
| 918 | } |
| 919 | if reps := outbox(t, s); len(reps) != 0 { |
| 920 | t.Fatalf("ended as restarted: %+v", reps) |
| 921 | } |
| 922 | } |
| 923 | |
| 924 | // TestSiteCreationProofSurvives: the proof is written as soon as the |
| 925 | // setup's deploy succeeded, before the marker is polled; a restart whose |
| 926 | // own marker answers from the app's address restores a missing one. |
| 927 | func TestSiteCreationProofSurvives(t *testing.T) { |
| 928 | rig := newSiteRig(t, quickSite) |
| 929 | dead := httptest.NewServer(http.NotFoundHandler()) |
| 930 | t.Cleanup(dead.Close) |
| 931 | served := rig.e.Site.URL |
| 932 | rig.e.Site.URL = func(string) string { return dead.URL } |
| 933 | tg := siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp} |
| 934 | 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) { |
| 935 | t.Fatalf("unconfirmed setup %+v, made here %t", rep.Publish, rig.e.Site.madeHere(tg)) |
| 936 | } |
| 937 | p, _ := rig.e.Site.createdPath(tg) |
| 938 | os.Remove(p) |
| 939 | rig.e.Site.URL = served |
| 940 | again := rig.r |
| 941 | again.Phase = phaseSitePublishing |
| 942 | if rep := rig.e.Exec(context.Background(), again, func(wire.StepReport) {}); rep.Publish.Outcome != wire.PublishPublished || !rig.e.Site.madeHere(tg) { |
| 943 | t.Fatalf("reconcile %+v, made here %t", rep.Publish, rig.e.Site.madeHere(tg)) |
| 944 | } |
| 945 | } |
| 946 | |
| 947 | // TestStepEngineReconcilesCancelledSitePublish: a cancelled site publish |
| 948 | // that may have changed CARLOS still reaches Exec, which only |
| 949 | // reconciles; any other cancelled step is reported cancelled unrun. |
| 950 | func TestStepEngineReconcilesCancelledSitePublish(t *testing.T) { |
| 951 | ctx := context.Background() |
| 952 | s, err := OpenState(ctx, t.TempDir()) |
| 953 | if err != nil { |
| 954 | t.Fatal(err) |
| 955 | } |
| 956 | defer s.Close() |
| 957 | var ran []string |
| 958 | e := &StepEngine{State: s, Notify: func() {}, Exec: func(_ context.Context, r stepRow, _ func(wire.StepReport)) wire.StepReport { |
| 959 | ran = append(ran, r.StepID) |
| 960 | return wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepDone, Termination: true, Findings: []wire.Finding{}} |
| 961 | }} |
| 962 | for _, c := range []struct { |
| 963 | id, specialist, phase string |
| 964 | }{{"s_a", wire.SpecialistPublish, phaseSiteMinting}, {"s_b", wire.SpecialistPublish, phaseSitePublishing}, {"s_c", wire.SpecialistPublish, ""}, {"s_d", wire.SpecialistReview, phaseSiteMinting}} { |
| 965 | d := dispatchFor("tk", c.id, 1) |
| 966 | d.Specialist = c.specialist |
| 967 | r := stepRow{DispatchCommand: d, Phase: c.phase, Cancel: true} |
| 968 | e.runOne(ctx, r) |
| 969 | } |
| 970 | if !slices.Equal(ran, []string{"s_a", "s_b"}) { |
| 971 | t.Fatalf("ran %v", ran) |
| 972 | } |
| 973 | } |
| 974 | |