| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "archive/tar" |
| 5 | "bytes" |
| 6 | "compress/gzip" |
| 7 | "context" |
| 8 | "crypto/sha256" |
| 9 | "encoding/hex" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "slices" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/equipo" |
| 21 | "amadan.net/oficina/equipo/internal/runner" |
| 22 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 23 | runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| 24 | "amadan.net/rastrillo/rastrillo" |
| 25 | ) |
| 26 | |
| 27 | type macRig struct { |
| 28 | h macInstallHost |
| 29 | home string |
| 30 | ids map[string]string |
| 31 | calls []string |
| 32 | enrolled *runner.Config |
| 33 | readable map[string]bool |
| 34 | // archives are what the fake download serves, by URL; fetched the |
| 35 | // URLs asked for. |
| 36 | archives map[string][]byte |
| 37 | fetched []string |
| 38 | // loaded is whether launchd has the agent; stuck keeps it loaded |
| 39 | // through a bootout; bootoutErr is what bootout answers. |
| 40 | loaded, stuck bool |
| 41 | bootoutErr error |
| 42 | // bootoutTakesDown is a bootout that answers bootoutErr after it |
| 43 | // took the agent out; bootstrapErr is what bootstrap answers. |
| 44 | bootoutTakesDown bool |
| 45 | bootstrapErr error |
| 46 | // dsclHome is the home the user directory records ("" for none); |
| 47 | // loggedOut is the user having no login session; childHomes the |
| 48 | // homes npm and xcodebuild were run with. |
| 49 | dsclHome string |
| 50 | loggedOut bool |
| 51 | childHomes []string |
| 52 | // cwd is the directory the installer changed into ("" before it did). |
| 53 | cwd string |
| 54 | } |
| 55 | |
| 56 | func newMacRig(t *testing.T) *macRig { |
| 57 | t.Helper() |
| 58 | old := rastrillo.BuildVersion |
| 59 | rastrillo.BuildVersion = "abc1234" |
| 60 | t.Cleanup(func() { rastrillo.BuildVersion = old }) |
| 61 | root := t.TempDir() |
| 62 | users := filepath.Join(root, "Users") |
| 63 | x := &macRig{home: filepath.Join(users, "equipo-paul"), dsclHome: filepath.Join(users, "equipo-paul"), ids: map[string]string{"-un": "equipo-paul\n", "-u": "502\n", "-Gn": "staff everyone localaccounts _developer\n"}, readable: map[string]bool{}, archives: map[string][]byte{}} |
| 64 | for _, d := range []string{x.home, filepath.Join(users, "paul"), filepath.Join(users, "Shared")} { |
| 65 | if err := os.MkdirAll(d, 0700); err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | } |
| 69 | self := filepath.Join(root, "downloaded-equipo-runner") |
| 70 | if err := os.WriteFile(self, []byte("#!verified runner\n"), 0700); err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | x.h = macInstallHost{goos: "darwin", goarch: "arm64", users: users, self: self, scannerPin: fmt.Sprintf("%x", sha256.Sum256([]byte("scanner"))), |
| 74 | exec: func(_ context.Context, name string, args ...string) (string, error) { |
| 75 | switch name { |
| 76 | case "/usr/bin/id": |
| 77 | return x.ids[args[0]], nil |
| 78 | case "/usr/bin/dscl": |
| 79 | if x.dsclHome == "" || strings.Join(args, " ") != ". -read /Users/"+strings.TrimSpace(x.ids["-un"])+" NFSHomeDirectory" { |
| 80 | return "", errors.New("eDSRecordNotFound") |
| 81 | } |
| 82 | return "NFSHomeDirectory: " + x.dsclHome + "\n", nil |
| 83 | case "/usr/sbin/scutil": |
| 84 | return "Tito Studio\n", nil |
| 85 | } |
| 86 | return "", errors.New("unexpected " + name) |
| 87 | }, |
| 88 | exposed: func(p string) bool { return x.readable[filepath.Base(p)] }, |
| 89 | fetch: func(_ context.Context, url string, _ int64) ([]byte, error) { |
| 90 | if strings.HasSuffix(url, "/gitleaks") { |
| 91 | return []byte("scanner"), nil |
| 92 | } |
| 93 | x.fetched = append(x.fetched, url) |
| 94 | if b, ok := x.archives[url]; ok { |
| 95 | return b, nil |
| 96 | } |
| 97 | return nil, errors.New("404 " + url) |
| 98 | }, |
| 99 | npmCI: func(_ context.Context, npm, prefix, home string) error { |
| 100 | x.calls = append(x.calls, "npm "+npm+" "+prefix) |
| 101 | x.childHomes = append(x.childHomes, home) |
| 102 | if _, err := os.Stat(filepath.Join(prefix, "package-lock.json")); err != nil { |
| 103 | return err |
| 104 | } |
| 105 | return nil |
| 106 | }, |
| 107 | // As runner.Enrol tells it: the link notice, the link, waiting. |
| 108 | enrol: func(_ context.Context, cfg runner.Config, out io.Writer) error { |
| 109 | x.enrolled = &cfg |
| 110 | cfg.EnrolNotify(runner.EnrolNotice{Link: true}) |
| 111 | _, _ = io.WriteString(out, "[https://equipo.example/runners/enrol?code=ABCDEFGHIJ](https://equipo.example/runners/enrol?code=ABCDEFGHIJ)\nABCDEFGHIJ\n") |
| 112 | cfg.EnrolNotify(runner.EnrolNotice{Waiting: true}) |
| 113 | return nil |
| 114 | }, |
| 115 | chdir: func(dir string) error { x.cwd = dir; return nil }, |
| 116 | launchctl: func(ctx context.Context, args ...string) error { |
| 117 | // launchctl is a program: a cancelled context never starts it. |
| 118 | if ctx.Err() != nil { |
| 119 | return ctx.Err() |
| 120 | } |
| 121 | x.calls = append(x.calls, "launchctl "+strings.Join(args, " ")) |
| 122 | switch args[0] { |
| 123 | case "print": |
| 124 | if len(args) == 2 && args[1] == "gui/"+strings.TrimSpace(x.ids["-u"]) { |
| 125 | // The login session, not the agent: not a call. |
| 126 | x.calls = x.calls[:len(x.calls)-1] |
| 127 | if x.loggedOut { |
| 128 | return errors.New("Could not find domain for user gui: 502") |
| 129 | } |
| 130 | return nil |
| 131 | } |
| 132 | if !x.loaded { |
| 133 | return errors.New("could not find service") |
| 134 | } |
| 135 | case "bootout": |
| 136 | if x.bootoutErr != nil { |
| 137 | if x.bootoutTakesDown { |
| 138 | x.loaded = false |
| 139 | } |
| 140 | return x.bootoutErr |
| 141 | } |
| 142 | x.loaded = x.stuck |
| 143 | case "bootstrap": |
| 144 | if x.bootstrapErr != nil { |
| 145 | return x.bootstrapErr |
| 146 | } |
| 147 | x.loaded = true |
| 148 | } |
| 149 | return nil |
| 150 | }, |
| 151 | stopWait: 300 * time.Millisecond, |
| 152 | verify: func(string) error { return nil }, |
| 153 | firstLaunch: func(_ context.Context, home string) { |
| 154 | x.calls = append(x.calls, "firstLaunch") |
| 155 | x.childHomes = append(x.childHomes, home) |
| 156 | }, |
| 157 | } |
| 158 | // Stand-ins for the pinned Node and ripgrep archives, pinned the same |
| 159 | // way (their digests), served by the fake download. |
| 160 | node, rg := toolArchive(t, "node-v1", "bin/node"), toolArchive(t, "rg-1", "rg") |
| 161 | x.archives["https://nodejs.example/node.tar.gz"], x.archives["https://rg.example/rg.tar.gz"] = node, rg |
| 162 | x.h.tools = []mac.Tool{ |
| 163 | {Name: mac.Node.Name, URL: "https://nodejs.example/node.tar.gz", SHA256: digest(node), Root: "node-v1", Binary: "bin/node"}, |
| 164 | {Name: mac.Ripgrep.Name, URL: "https://rg.example/rg.tar.gz", SHA256: digest(rg), Root: "rg-1", Binary: "rg"}, |
| 165 | } |
| 166 | return x |
| 167 | } |
| 168 | |
| 169 | func digest(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } |
| 170 | |
| 171 | // toolArchive is a .tar.gz holding one executable under root. |
| 172 | func toolArchive(t *testing.T, root, bin string) []byte { |
| 173 | t.Helper() |
| 174 | var buf bytes.Buffer |
| 175 | z := gzip.NewWriter(&buf) |
| 176 | tw := tar.NewWriter(z) |
| 177 | body := []byte("#!/bin/sh\n") |
| 178 | if err := tw.WriteHeader(&tar.Header{Name: root + "/" + bin, Mode: 0755, Size: int64(len(body)), Typeflag: tar.TypeReg}); err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | _, _ = tw.Write(body) |
| 182 | _ = tw.Close() |
| 183 | _ = z.Close() |
| 184 | return buf.Bytes() |
| 185 | } |
| 186 | |
| 187 | func (x *macRig) install() (int, string, string) { |
| 188 | var out, errout bytes.Buffer |
| 189 | code := installMac(context.Background(), []string{"--release", "abc1234", "--origin", "https://equipo.example", "--instance", "team1"}, x.h, &out, &errout) |
| 190 | return code, out.String(), errout.String() |
| 191 | } |
| 192 | |
| 193 | // The installer refuses before touching anything: not a Mac, root, an |
| 194 | // administrator, a user without equipo in its name, a home of another person |
| 195 | // this user can open. |
| 196 | func TestInstallMacRefusals(t *testing.T) { |
| 197 | for name, c := range map[string]struct { |
| 198 | set func(*macRig) |
| 199 | want string |
| 200 | }{ |
| 201 | "linux": {func(x *macRig) { x.h.goos = "linux" }, "runner.mac.platform"}, |
| 202 | "intel": {func(x *macRig) { x.h.goarch = "amd64" }, "runner.mac.platform"}, |
| 203 | "root": {func(x *macRig) { x.ids["-u"], x.ids["-un"] = "0\n", "root\n" }, "runner.mac.root"}, |
| 204 | "administrator": {func(x *macRig) { x.ids["-Gn"] = "staff admin _developer\n" }, "runner.mac.admin"}, |
| 205 | "own account": {func(x *macRig) { x.ids["-un"] = "paul\n" }, "runner.mac.user"}, |
| 206 | |
| 207 | "readable home": {func(x *macRig) { x.readable["paul"] = true }, "runner.mac.home"}, |
| 208 | "homes unknown": {func(x *macRig) { x.h.users = filepath.Join(x.home, "missing") }, "runner.mac.homes_unknown"}, |
| 209 | "another's home": {func(x *macRig) { x.dsclHome = filepath.Join(filepath.Dir(x.home), "paul") }, "runner.install.destination"}, |
| 210 | "no home": {func(x *macRig) { x.dsclHome = "" }, "runner.install.destination"}, |
| 211 | "logged out": {func(x *macRig) { x.loggedOut = true }, "runner.mac.not_logged_in"}, |
| 212 | } { |
| 213 | x := newMacRig(t) |
| 214 | c.set(x) |
| 215 | code, _, errout := x.install() |
| 216 | want := equipo.RunnerSetupCopy(c.want) |
| 217 | switch c.want { |
| 218 | case "runner.mac.home": |
| 219 | want = fmt.Sprintf(want, filepath.Join(filepath.Dir(x.home), "paul"), "equipo-paul") |
| 220 | case "runner.mac.not_logged_in": |
| 221 | want = "Log in as equipo-paul on this Mac (fast user switching) and keep it logged in, then run this again.\n" |
| 222 | } |
| 223 | if code != 1 || !strings.Contains(errout, want) || x.enrolled != nil || len(x.calls) != 0 || len(x.fetched) != 0 { |
| 224 | t.Fatalf("%s: code %d %q calls %v", name, code, errout, x.calls) |
| 225 | } |
| 226 | if _, err := os.Stat(filepath.Join(x.home, ".local")); !os.IsNotExist(err) { |
| 227 | t.Fatalf("%s: installed something", name) |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // One command: the verified runner copied into ~/.local/lib, srt |
| 233 | // installed from the pinned lockfile, a private env file, the link |
| 234 | // printed for Paul to tap (enrolled as a worker named for the Mac), |
| 235 | // then the launchd agent written and loaded. |
| 236 | func TestInstallMac(t *testing.T) { |
| 237 | x := newMacRig(t) |
| 238 | code, out, errout := x.install() |
| 239 | if code != 0 { |
| 240 | t.Fatalf("code %d: %s", code, errout) |
| 241 | } |
| 242 | lib := filepath.Join(x.home, ".local/lib/equipo-runner") |
| 243 | if raw, _ := os.ReadFile(filepath.Join(lib, "equipo-runner")); string(raw) != "#!verified runner\n" { |
| 244 | t.Fatal("runner not installed") |
| 245 | } |
| 246 | if !strings.Contains(out, "(https://equipo.example/runners/enrol?code=ABCDEFGHIJ)") || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.tap")) || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.installed")) { |
| 247 | t.Fatalf("out %q err %q", out, errout) |
| 248 | } |
| 249 | env := filepath.Join(x.home, ".config/equipo-runner/runner.env") |
| 250 | values, err := runnersetup.ReadEnvFile(env) |
| 251 | if err != nil { |
| 252 | t.Fatal(err) |
| 253 | } |
| 254 | share := filepath.Join(x.home, ".local/share/equipo-runner") |
| 255 | for k, v := range map[string]string{"EQUIPO_ORIGIN": "https://equipo.example", "EQUIPO_INSTANCE_ID": "team1", "EQUIPO_RUNNER_STATE_DIR": share + "/state", "EQUIPO_SCRATCH_ROOT": share + "/scratch", "EQUIPO_WORKSPACE_ROOT": share + "/work", "EQUIPO_MACHINE_LABEL": "Tito Studio", "EQUIPO_SRT_PATH": lib + "/srt/node_modules/.bin/srt", "EQUIPO_NODE_PATH": lib + "/tools/node-v1/bin/node", "EQUIPO_RG_PATH": lib + "/tools/rg-1/rg", "EQUIPO_GIT_PATH": "/usr/bin/git"} { |
| 256 | if values[k] != v { |
| 257 | t.Fatalf("%s=%q, want %q", k, values[k], v) |
| 258 | } |
| 259 | } |
| 260 | if x.enrolled == nil || !x.enrolled.WorkerOnly || x.enrolled.MachineLabel != "Tito Studio" || x.enrolled.StateDir != share+"/state" { |
| 261 | t.Fatalf("enrolled %+v", x.enrolled) |
| 262 | } |
| 263 | plist := filepath.Join(x.home, "Library/LaunchAgents/io.amadan.equipo-runner.plist") |
| 264 | raw, err := os.ReadFile(plist) |
| 265 | if err != nil || !bytes.Equal(raw, mac.LaunchAgent(filepath.Join(lib, "equipo-runner"), env, filepath.Join(x.home, "Library/Logs/equipo-runner"))) { |
| 266 | t.Fatalf("plist %v", err) |
| 267 | } |
| 268 | want := []string{"launchctl print gui/502/io.amadan.equipo-runner", "npm " + lib + "/tools/node-v1/bin/npm " + lib + "/srt", "firstLaunch", "launchctl bootstrap gui/502 " + plist} |
| 269 | if !slices.Equal(x.calls, want) { |
| 270 | t.Fatalf("calls %v", x.calls) |
| 271 | } |
| 272 | // A download whose digest is not the pin installs nothing of it: one |
| 273 | // line, no srt, checks run outside the sandbox and say so. |
| 274 | x = newMacRig(t) |
| 275 | x.archives["https://rg.example/rg.tar.gz"] = toolArchive(t, "rg-1", "rg-tampered") |
| 276 | if code, _, errout := x.install(); code != 0 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.no_srt")) { |
| 277 | t.Fatalf("tampered ripgrep: %d %q", code, errout) |
| 278 | } |
| 279 | values, _ = runnersetup.ReadEnvFile(filepath.Join(x.home, ".config/equipo-runner/runner.env")) |
| 280 | if _, ok := values["EQUIPO_SRT_PATH"]; ok { |
| 281 | t.Fatal("srt path without its ripgrep") |
| 282 | } |
| 283 | if _, err := os.Stat(filepath.Join(x.home, ".local/lib/equipo-runner/tools/rg-1")); !os.IsNotExist(err) { |
| 284 | t.Fatal("an archive that is not the pin was unpacked") |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | func TestEnvFileAndExits(t *testing.T) { |
| 289 | for _, c := range []struct { |
| 290 | in []string |
| 291 | rest []string |
| 292 | file string |
| 293 | ok bool |
| 294 | }{ |
| 295 | {[]string{"run"}, []string{"run"}, "", true}, |
| 296 | {[]string{"run", "--env-file", "/x/runner.env"}, []string{"run"}, "/x/runner.env", true}, |
| 297 | {[]string{"probe", "--env-file", "/x/runner.env"}, []string{"probe"}, "/x/runner.env", true}, |
| 298 | {[]string{"enrol", "--env-file", "/x/runner.env"}, nil, "", false}, |
| 299 | {[]string{"run", "--env-file"}, nil, "", false}, |
| 300 | {[]string{"run", "--env-file", "/a", "--env-file", "/b"}, nil, "", false}, |
| 301 | } { |
| 302 | rest, file, ok := cutEnvFile(c.in) |
| 303 | if ok != c.ok || file != c.file || !slices.Equal(rest, c.rest) { |
| 304 | t.Fatalf("%v: %v %q %v", c.in, rest, file, ok) |
| 305 | } |
| 306 | } |
| 307 | if supersededExit("darwin") != 0 || supersededExit("linux") != 3 || mac.ExitUpdated == 0 { |
| 308 | t.Fatal("exit statuses") |
| 309 | } |
| 310 | // The file is what the runner reads: a bad origin in it is reported. |
| 311 | dir := t.TempDir() |
| 312 | env := filepath.Join(dir, "runner.env") |
| 313 | if err := os.WriteFile(env, []byte("EQUIPO_ORIGIN=\"http://example.com\"\n"), 0600); err != nil { |
| 314 | t.Fatal(err) |
| 315 | } |
| 316 | var out, log bytes.Buffer |
| 317 | if run(context.Background(), []string{"run", "--env-file", env}, strings.NewReader(""), &out, &log, func(string) string { return "" }) != 1 || !strings.Contains(log.String(), "EQUIPO_ORIGIN") { |
| 318 | t.Fatalf("env file not read: %q", log.String()) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | // The line asking Paul to open the link comes only with a link, right |
| 323 | // before it. A Mac whose enrolment is still valid keeps it and says it |
| 324 | // is already on the team (Paul's Studio, 2026-11-11: the line came with |
| 325 | // no link after it). |
| 326 | func TestInstallMacLinkLine(t *testing.T) { |
| 327 | tap, already, ready := equipo.RunnerSetupCopy("runner.mac.tap"), equipo.RunnerSetupCopy("runner.mac.already"), equipo.RunnerSetupCopy("runner.mac.installed") |
| 328 | link := "[https://equipo.example/runners/enrol?code=ABCDEFGHIJ](https://equipo.example/runners/enrol?code=ABCDEFGHIJ)\nABCDEFGHIJ\n" |
| 329 | install := func(x *macRig) string { |
| 330 | var both bytes.Buffer |
| 331 | if code := installMac(context.Background(), []string{"--release", "abc1234", "--origin", "https://equipo.example", "--instance", "team1"}, x.h, &both, &both); code != 0 { |
| 332 | t.Fatalf("code %d: %s", code, both.String()) |
| 333 | } |
| 334 | return both.String() |
| 335 | } |
| 336 | kept := newMacRig(t) |
| 337 | kept.h.enrol = func(_ context.Context, cfg runner.Config, _ io.Writer) error { |
| 338 | cfg.EnrolNotify(runner.EnrolNotice{Kept: true}) |
| 339 | return nil |
| 340 | } |
| 341 | if got := install(kept); strings.Contains(got, tap) || !strings.HasSuffix(got, already+"\n"+ready+"\n") { |
| 342 | t.Fatalf("kept enrolment: %q", got) |
| 343 | } |
| 344 | if got := install(newMacRig(t)); strings.Count(got, tap) != 1 || !strings.Contains(got, tap+"\n"+link) || strings.Contains(got, already) { |
| 345 | t.Fatalf("new enrolment: %q", got) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | // Installing again over a running runner stops it first: nothing is |
| 350 | // replaced while it runs, and the enrolment check gets the state lock |
| 351 | // the running runner held (here the test holds it until bootout). |
| 352 | func TestInstallMacAgain(t *testing.T) { |
| 353 | x := newMacRig(t) |
| 354 | x.loaded = true |
| 355 | state := filepath.Join(x.home, ".local/share/equipo-runner/state") |
| 356 | held, err := runner.LockState(state) |
| 357 | if err != nil { |
| 358 | t.Fatal(err) |
| 359 | } |
| 360 | launchctl := x.h.launchctl |
| 361 | x.h.launchctl = func(ctx context.Context, args ...string) error { |
| 362 | if args[0] == "bootout" && held != nil { |
| 363 | held.Close() |
| 364 | held = nil |
| 365 | } |
| 366 | return launchctl(ctx, args...) |
| 367 | } |
| 368 | npmCI := x.h.npmCI |
| 369 | x.h.npmCI = func(ctx context.Context, npm, prefix, home string) error { |
| 370 | if held != nil { |
| 371 | t.Error("dependencies replaced under a running runner") |
| 372 | } |
| 373 | return npmCI(ctx, npm, prefix, home) |
| 374 | } |
| 375 | x.h.enrol = func(_ context.Context, cfg runner.Config, _ io.Writer) error { |
| 376 | lock, err := runner.LockState(cfg.StateDir) |
| 377 | if err != nil { |
| 378 | return err |
| 379 | } |
| 380 | return lock.Close() |
| 381 | } |
| 382 | if code, _, errout := x.install(); code != 0 { |
| 383 | t.Fatalf("reinstall: %d %s", code, errout) |
| 384 | } |
| 385 | if held != nil { |
| 386 | held.Close() |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | // The instance's role decides: a Mac it enrolled as a primary stops the |
| 391 | // installer, which says why and loads no agent. |
| 392 | func TestInstallMacEnrolledAsPrimary(t *testing.T) { |
| 393 | x := newMacRig(t) |
| 394 | x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolledAsPrimary } |
| 395 | code, _, errout := x.install() |
| 396 | if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.needs_primary")) || slices.Contains(x.calls, "launchctl bootstrap gui/502 "+filepath.Join(x.home, "Library/LaunchAgents/io.amadan.equipo-runner.plist")) { |
| 397 | t.Fatalf("%d %q %v", code, errout, x.calls) |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // A runner that does not stop changes nothing: a bootout that fails, an |
| 402 | // agent launchd still has after the wait, or a state lock still held |
| 403 | // (a runner started by hand) all stop the installer before it touches |
| 404 | // anything, with words saying so. |
| 405 | func TestInstallMacWhenTheRunnerWillNotStop(t *testing.T) { |
| 406 | for name, set := range map[string]func(*macRig) error{ |
| 407 | "bootout fails": func(x *macRig) error { x.loaded, x.bootoutErr = true, errors.New("Boot-out failed: 5"); return nil }, |
| 408 | "agent stays": func(x *macRig) error { x.loaded, x.stuck = true, true; return nil }, |
| 409 | "lock still held": func(x *macRig) error { |
| 410 | x.loaded = true |
| 411 | _, err := runner.LockState(filepath.Join(x.home, ".local/share/equipo-runner/state")) |
| 412 | return err |
| 413 | }, |
| 414 | "held, not loaded": func(x *macRig) error { |
| 415 | _, err := runner.LockState(filepath.Join(x.home, ".local/share/equipo-runner/state")) |
| 416 | return err |
| 417 | }, |
| 418 | } { |
| 419 | x := newMacRig(t) |
| 420 | if err := set(x); err != nil { |
| 421 | t.Fatal(err) |
| 422 | } |
| 423 | code, _, errout := x.install() |
| 424 | if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.still_running")) { |
| 425 | t.Fatalf("%s: %d %q", name, code, errout) |
| 426 | } |
| 427 | if _, err := os.Stat(filepath.Join(x.home, ".local/lib")); !os.IsNotExist(err) || len(x.fetched) != 0 || x.enrolled != nil { |
| 428 | t.Fatalf("%s: changed something", name) |
| 429 | } |
| 430 | // A runner taken out of launchd that still holds its lock is |
| 431 | // given back to launchd: nothing was changed. |
| 432 | if x.loaded != (name != "held, not loaded") { |
| 433 | t.Fatalf("%s: left unloaded: %v", name, x.calls) |
| 434 | } |
| 435 | // A refused bootout, the agent still there, is the answer: no |
| 436 | // waiting on it. |
| 437 | if name == "bootout fails" && strings.Join(x.calls[len(x.calls)-2:], ",") != "launchctl bootout gui/502/io.amadan.equipo-runner,launchctl print gui/502/io.amadan.equipo-runner" { |
| 438 | t.Fatalf("waited after a failed bootout: %v", x.calls) |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | // What npm installed is checked against the pins compiled into the |
| 444 | // runner: anything else is not the sandbox, said in one line, and no |
| 445 | // srt path is written. |
| 446 | func TestInstallMacVerifiesThePins(t *testing.T) { |
| 447 | x := newMacRig(t) |
| 448 | x.h.verify = func(string) error { return mac.ErrUnpinned } |
| 449 | if code, _, errout := x.install(); code != 0 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.no_srt")) { |
| 450 | t.Fatalf("%d %q", code, errout) |
| 451 | } |
| 452 | values, _ := runnersetup.ReadEnvFile(filepath.Join(x.home, ".config/equipo-runner/runner.env")) |
| 453 | if _, ok := values["EQUIPO_SRT_PATH"]; ok { |
| 454 | t.Fatal("an unpinned srt configured") |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | // The name macOS's Add User dialog gives "Paul Equipo" is accepted: its |
| 459 | // home is /Users/paulequipo and the install goes ahead there. |
| 460 | func TestInstallMacAddUserDialogName(t *testing.T) { |
| 461 | x := newMacRig(t) |
| 462 | home := filepath.Join(filepath.Dir(x.home), "paulequipo") |
| 463 | if err := os.MkdirAll(home, 0700); err != nil { |
| 464 | t.Fatal(err) |
| 465 | } |
| 466 | x.home, x.dsclHome, x.ids["-un"] = home, home, "paulequipo\n" |
| 467 | if code, _, errout := x.install(); code != 0 { |
| 468 | t.Fatalf("%d %q", code, errout) |
| 469 | } |
| 470 | if _, err := os.Stat(filepath.Join(home, ".local/lib/equipo-runner/equipo-runner")); err != nil { |
| 471 | t.Fatal("not installed in paulequipo's home") |
| 472 | } |
| 473 | // The refusal says why in words. |
| 474 | if got := equipo.RunnerSetupCopy("runner.mac.user"); got != "Equipo runs in its own Mac user so it can't reach your files. Create a Standard user with 'equipo' in its account name, then run this again." { |
| 475 | t.Fatalf("refusal %q", got) |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | // A readable home is closed for this user alone with an ACL, and the |
| 480 | // message says how and how to undo it, with the same entry. |
| 481 | func TestInstallMacHomeACLMessage(t *testing.T) { |
| 482 | x := newMacRig(t) |
| 483 | x.readable["paul"] = true |
| 484 | _, _, errout := x.install() |
| 485 | paul := filepath.Join(filepath.Dir(x.home), "paul") |
| 486 | want := "This user can get into another person's home folder (" + paul + "). An administrator can close it with: sudo chmod +a \"equipo-paul deny list,search,readattr,readextattr,readsecurity\" " + paul + " (to undo it: sudo chmod -a \"equipo-paul deny list,search,readattr,readextattr,readsecurity\" " + paul + ")\n" |
| 487 | if errout != want { |
| 488 | t.Fatalf("message %q", errout) |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | // Under su or sudo, HOME is the caller's: the installer uses the home the |
| 493 | // user directory records, for itself and for npm and xcodebuild, and never |
| 494 | // writes to the inherited one. |
| 495 | func TestInstallMacIgnoresInheritedHome(t *testing.T) { |
| 496 | x := newMacRig(t) |
| 497 | caller := filepath.Join(filepath.Dir(x.home), "paul") |
| 498 | t.Setenv("HOME", caller) |
| 499 | t.Setenv("USER", "paul") |
| 500 | if code, _, errout := x.install(); code != 0 { |
| 501 | t.Fatalf("%d %q", code, errout) |
| 502 | } |
| 503 | if _, err := os.Stat(filepath.Join(x.home, ".local/lib/equipo-runner/equipo-runner")); err != nil { |
| 504 | t.Fatal("not installed in the user's own home") |
| 505 | } |
| 506 | if entries, _ := os.ReadDir(caller); len(entries) != 0 { |
| 507 | t.Fatalf("wrote to the caller's home: %v", entries) |
| 508 | } |
| 509 | if !slices.Equal(x.childHomes, []string{x.home, x.home}) { |
| 510 | t.Fatalf("npm and xcodebuild ran with homes %v", x.childHomes) |
| 511 | } |
| 512 | env := userEnv([]string{"HOME=" + caller, "USER=paul", "LOGNAME=paul", "PATH=/opt/bin", "LANG=C"}, x.home, "equipo-paul", "PATH=/usr/bin") |
| 513 | if !slices.Equal(env, []string{"LANG=C", "HOME=" + x.home, "USER=equipo-paul", "LOGNAME=equipo-paul", "PATH=/usr/bin"}) { |
| 514 | t.Fatalf("env %v", env) |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | // Enrolment says how it is going: a quiet line while it waits, each |
| 519 | // failure it waits out, and at the end why it stopped, in words, on |
| 520 | // stderr and in the install log. "Runner installation is unavailable." |
| 521 | // never comes alone. |
| 522 | func TestInstallMacEnrolmentInWords(t *testing.T) { |
| 523 | unavailable := equipo.RunnerSetupCopy("runner.install.unavailable") |
| 524 | for name, c := range map[string]struct { |
| 525 | err error |
| 526 | want []string |
| 527 | bare bool |
| 528 | }{ |
| 529 | "expired": {runner.ErrEnrolmentExpired, []string{"The link expired before it was approved. Run the install command again for a new link."}, false}, |
| 530 | "turned down": {runner.ErrEnrolmentRefused, []string{"Equipo turned this link down, so this machine was not added. Run the install command again for a new link."}, false}, |
| 531 | "server": {&runner.EnrolAnswerError{Status: 503, Key: "service.unavailable"}, []string{"Adding this machine to Equipo failed: Equipo answered HTTP 503 (service.unavailable)", unavailable}, true}, |
| 532 | } { |
| 533 | t.Run(name, func(t *testing.T) { |
| 534 | x := newMacRig(t) |
| 535 | x.h.enrol = func(_ context.Context, cfg runner.Config, out io.Writer) error { |
| 536 | _, _ = io.WriteString(out, "[https://equipo.example/runners/enrol?code=ABCDEFGHJK](https://equipo.example/runners/enrol?code=ABCDEFGHJK)\nABCDEFGHJK\n") |
| 537 | cfg.EnrolNotify(runner.EnrolNotice{Waiting: true}) |
| 538 | cfg.EnrolNotify(runner.EnrolNotice{Retry: &runner.EnrolAnswerError{Status: 502}}) |
| 539 | return c.err |
| 540 | } |
| 541 | code, _, errout := x.install() |
| 542 | want := "Waiting for you to approve…\nEquipo did not answer properly (Equipo answered HTTP 502). Trying again.\n" + strings.Join(c.want, "\n") + "\n" |
| 543 | if code != 1 || !strings.HasSuffix(errout, want) { |
| 544 | t.Fatalf("%d %q", code, errout) |
| 545 | } |
| 546 | if !c.bare && strings.Contains(errout, unavailable) { |
| 547 | t.Fatal("the bare unavailable line") |
| 548 | } |
| 549 | log, _ := os.ReadFile(filepath.Join(x.home, "Library/Logs/equipo-runner/install.log")) |
| 550 | for _, line := range append([]string{"Waiting for you to approve…", "Equipo answered HTTP 502"}, c.want...) { |
| 551 | if !strings.Contains(string(log), line) { |
| 552 | t.Fatalf("install log lacks %q:\n%s", line, log) |
| 553 | } |
| 554 | } |
| 555 | }) |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | func TestInstallMacScannerDigestPreservesExistingBinary(t *testing.T) { |
| 560 | x := newMacRig(t) |
| 561 | if code, _, errout := x.install(); code != 0 { |
| 562 | t.Fatal("initial install", code, errout) |
| 563 | } |
| 564 | path := filepath.Join(x.home, ".local/lib/equipo-runner/gitleaks") |
| 565 | if raw, err := os.ReadFile(path); err != nil || string(raw) != "scanner" { |
| 566 | t.Fatal("scanner not bundled", err) |
| 567 | } |
| 568 | fetch := x.h.fetch |
| 569 | x.h.fetch = func(ctx context.Context, url string, limit int64) ([]byte, error) { |
| 570 | if strings.HasSuffix(url, "/gitleaks") { |
| 571 | return []byte("tampered"), nil |
| 572 | } |
| 573 | return fetch(ctx, url, limit) |
| 574 | } |
| 575 | if code, _, _ := x.install(); code == 0 { |
| 576 | t.Fatal("changed scanner installed") |
| 577 | } |
| 578 | if raw, err := os.ReadFile(path); err != nil || string(raw) != "scanner" { |
| 579 | t.Fatal("bad scanner replaced installed bytes", err) |
| 580 | } |
| 581 | } |
| 582 | |