package main import ( "bytes" "context" "errors" "fmt" "io" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/oficina/equipo/internal/runnerproto" ) const stagingOrigin = "https://equipo-staging.example" // liveEnrolment writes what an enrolled runner keeps in its state: a live // credential and the enrolment it came from (no record when origin is ""). func liveEnrolment(t *testing.T, state, origin, instance string) { t.Helper() if err := runnerproto.JournalCredentials(filepath.Join(state, "credentials.json"), runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Version: 1, RunnerID: "r1", Token: "t", ExpiresAt: time.Now().Add(time.Hour)}}); err != nil { t.Fatal(err) } if origin == "" { return } record := map[string]any{"origin": origin, "label": "Tito Studio", "code": map[string]string{"instance_id": instance}} if err := runnerproto.JournalCredentials(filepath.Join(state, "enrolment.json"), record); err != nil { t.Fatal(err) } } func (x *macRig) installAt(ctx context.Context, origin, instance string) (int, string) { var out, errout bytes.Buffer code := installMac(ctx, []string{"--release", "abc1234", "--origin", origin, "--instance", instance}, x.h, &out, &errout) return code, errout.String() } // snapshot is what a runner installed before runs on: its binary, the // scanner beside it, its environment file and its launchd agent. func (x *macRig) snapshot(t *testing.T) map[string]string { t.Helper() got := map[string]string{} for _, p := range []string{".local/lib/equipo-runner/equipo-runner", ".local/lib/equipo-runner/gitleaks", ".config/equipo-runner/runner.env", "Library/LaunchAgents/io.amadan.equipo-runner.plist"} { raw, err := os.ReadFile(filepath.Join(x.home, p)) if err != nil { got[p] = "missing" continue } got[p] = string(raw) } return got } // installedBefore is a Mac with a runner for origin installed and running, // enrolled there; the next install brings a newer runner. func installedBefore(t *testing.T, origin string) *macRig { t.Helper() x := newMacRig(t) if code, errout := x.installAt(context.Background(), origin, "team1"); code != 0 { t.Fatalf("first install: %d %s", code, errout) } liveEnrolment(t, filepath.Join(x.home, ".local/share/equipo-runner/state"), origin, "team1") // Something only the earlier install wrote, so putting it back shows. env := filepath.Join(x.home, ".config/equipo-runner/runner.env") values := map[string]string{"EQUIPO_ORIGIN": origin, "EQUIPO_INSTANCE_ID": "team1", "EQUIPO_MACHINE_LABEL": "Before"} if err := writeEnvFile(env, values); err != nil { t.Fatal(err) } if err := os.WriteFile(x.h.self, []byte("#!newer runner\n"), 0700); err != nil { t.Fatal(err) } x.calls, x.fetched, x.enrolled, x.childHomes = nil, nil, nil, nil return x } // A Mac user already enrolled with another Equipo (the Studio's staging // runner, then a production install, 2026-11-28) is told so in words and // nothing is changed: its runner is not stopped, its environment file is // not rewritten, nothing is downloaded and nothing is enrolled. func TestInstallMacRefusesAnotherEquipo(t *testing.T) { for name, c := range map[string]struct { record string want string // unreadable is a credential that cannot be read: whose it is // is not known, so nothing is stopped or changed either. unreadable bool }{ "another origin": {record: stagingOrigin, want: fmt.Sprintf(equipo.RunnerSetupCopy("runner.mac.other_instance"), stagingOrigin)}, "origin not known": {want: equipo.RunnerSetupCopy("runner.enrol.identity")}, // A saved origin that is not a plain web address (here with a // password and a sign-in link in it) is never printed. "origin not an address": {record: "https://paul:hunter2@equipo-staging.example/signin?token=s3cret", want: equipo.RunnerSetupCopy("runner.enrol.identity")}, "credential unreadable": {record: stagingOrigin, want: strings.TrimSuffix(equipo.RunnerSetupCopy("runner.enrol.failed"), "%s"), unreadable: true}, } { t.Run(name, func(t *testing.T) { x := installedBefore(t, stagingOrigin) state := filepath.Join(x.home, ".local/share/equipo-runner/state") switch { case c.record == "": if err := os.Remove(filepath.Join(state, "enrolment.json")); err != nil { t.Fatal(err) } case c.record != stagingOrigin: liveEnrolment(t, state, c.record, "team1") } if c.unreadable { if err := os.WriteFile(filepath.Join(state, "credentials.json"), []byte("{"), 0600); err != nil { t.Fatal(err) } } before := x.snapshot(t) code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if code != 1 || !strings.Contains(errout, c.want) || strings.Contains(errout, string(provider.ErrIdentity)) || strings.Contains(errout, "hunter2") || strings.Contains(errout, "s3cret") { t.Fatalf("%d %q", code, errout) } if len(x.calls) != 0 || !x.loaded || x.enrolled != nil || len(x.fetched) != 0 || len(x.childHomes) != 0 { t.Fatalf("changed something: calls %v loaded %v", x.calls, x.loaded) } if after := x.snapshot(t); !mapsEqual(before, after) { t.Fatalf("files changed:\n%v\n%v", before, after) } }) } } func mapsEqual(a, b map[string]string) bool { if len(a) != len(b) { return false } for k, v := range a { if b[k] != v { return false } } return true } // Anything that fails once the runner was stopped puts back what it ran // on, exactly, and starts it again: a link that expired, the person // stopping the wait (the context ends, the reload still happens), a // scanner that is not the pin, a Mac the instance takes for a primary. // A runner that was not running is put back and left stopped. func TestInstallMacPutsBackThePreviousRunner(t *testing.T) { for name, c := range map[string]struct { set func(*macRig, context.CancelFunc) want string notLoaded bool }{ "link expired": {set: func(x *macRig, _ context.CancelFunc) { x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired } }, want: "runner.enrol.expired"}, "wait stopped": {set: func(x *macRig, cancel context.CancelFunc) { x.h.enrol = func(ctx context.Context, _ runner.Config, _ io.Writer) error { cancel(); return ctx.Err() } }, want: "runner.install.unavailable"}, "scanner not the pin": {set: func(x *macRig, _ context.CancelFunc) { fetch := x.h.fetch x.h.fetch = func(ctx context.Context, url string, limit int64) ([]byte, error) { if strings.HasSuffix(url, "/gitleaks") { return []byte("tampered"), nil } return fetch(ctx, url, limit) } }, want: "runner.install.checksum"}, "taken for a primary": {set: func(x *macRig, _ context.CancelFunc) { x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolledAsPrimary } }, want: "runner.needs_primary"}, "was not running": {set: func(x *macRig, _ context.CancelFunc) { x.loaded = false x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentRefused } }, want: "runner.enrol.refused", notLoaded: true}, } { t.Run(name, func(t *testing.T) { x := installedBefore(t, "https://equipo.example") before := x.snapshot(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() c.set(x, cancel) code, errout := x.installAt(ctx, "https://equipo.example", "team1") if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy(c.want)) || !strings.HasSuffix(errout, equipo.RunnerSetupCopy("runner.mac.restored")+"\n") { t.Fatalf("%d %q", code, errout) } if after := x.snapshot(t); !mapsEqual(before, after) { t.Fatalf("not put back:\n%v\n%v", before, after) } plist := filepath.Join(x.home, "Library/LaunchAgents/io.amadan.equipo-runner.plist") reloaded := len(x.calls) > 0 && x.calls[len(x.calls)-1] == "launchctl bootstrap gui/502 "+plist if c.notLoaded == reloaded || x.loaded == c.notLoaded { t.Fatalf("loaded %v calls %v", x.loaded, x.calls) } // Nothing kept aside is left behind. if entries, _ := os.ReadDir(filepath.Join(x.home, ".local/share/equipo-runner")); len(entries) != 3 { t.Fatalf("left behind %v", entries) } }) } } // A first install that fails leaves no configuration a later login would // start, and says nothing about putting a runner back. func TestInstallMacFirstFailureLeavesNoConfig(t *testing.T) { x := newMacRig(t) x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired } code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if code != 1 || strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.restored")) || slices.ContainsFunc(x.calls, func(c string) bool { return strings.HasPrefix(c, "launchctl bootstrap") }) { t.Fatalf("%d %q %v", code, errout, x.calls) } if _, err := os.Stat(filepath.Join(x.home, ".config/equipo-runner/runner.env")); !os.IsNotExist(err) { t.Fatal("environment file left behind") } } // An install that works replaces the earlier runner and keeps nothing of // it aside. func TestInstallMacAgainKeepsNothingAside(t *testing.T) { x := installedBefore(t, "https://equipo.example") if code, errout := x.installAt(context.Background(), "https://equipo.example", "team1"); code != 0 { t.Fatalf("%d %q", code, errout) } if got := x.snapshot(t)[".local/lib/equipo-runner/equipo-runner"]; got != "#!newer runner\n" { t.Fatalf("runner %q", got) } if entries, _ := os.ReadDir(filepath.Join(x.home, ".local/share/equipo-runner")); len(entries) != 3 { t.Fatalf("left behind %v", entries) } } // Started from a folder this user cannot read (sudo su without a dash, // 2026-11-28: npm and xcodebuild failed, so no checks sandbox), the // installer moves into the user's own home before it runs anything, and // every program it runs is given its own folder. func TestInstallMacRunsFromItsHome(t *testing.T) { x := newMacRig(t) npmCI, firstLaunch := x.h.npmCI, x.h.firstLaunch x.h.npmCI = func(ctx context.Context, npm, prefix, home string) error { if x.cwd != x.home { t.Errorf("npm ran in %q", x.cwd) } return npmCI(ctx, npm, prefix, home) } x.h.firstLaunch = func(ctx context.Context, home string) { if x.cwd != x.home { t.Errorf("xcodebuild ran in %q", x.cwd) } firstLaunch(ctx, home) } if code, errout := x.installAt(context.Background(), "https://equipo.example", "team1"); code != 0 { t.Fatalf("%d %q", code, errout) } // A home it cannot move into changes nothing. x = newMacRig(t) x.h.chdir = func(string) error { return os.ErrPermission } if code, errout := x.installAt(context.Background(), "https://equipo.example", "team1"); code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.install.destination")) || len(x.calls) != 0 { t.Fatalf("%d %q %v", code, errout, x.calls) } ctx := context.Background() if dir := npmCICommand(ctx, "/n/bin/npm", "/h/.local/lib/equipo-runner/srt", "/h").Dir; dir != "/h/.local/lib/equipo-runner/srt" { t.Fatalf("npm dir %q", dir) } if dir := firstLaunchCommand(ctx, "/h").Dir; dir != "/h" { t.Fatalf("xcodebuild dir %q", dir) } if dir := systemCommand(ctx, "/bin/launchctl", "print").Dir; dir != "/" { t.Fatalf("system tool dir %q", dir) } } // An identity Enrol cannot match is said in words, not as its code, and // stands alone. func TestInstallMacIdentityInWords(t *testing.T) { x := newMacRig(t) x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return fmt.Errorf("enrol: %w", provider.ErrIdentity) } code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.enrol.identity")) || strings.Contains(errout, string(provider.ErrIdentity)) || strings.Contains(errout, equipo.RunnerSetupCopy("runner.install.unavailable")) { t.Fatalf("%d %q", code, errout) } } // A second install for the same Mac user while one is running is refused // and changes nothing (Astra, mac-install-safe): it cannot put its backup // back over what the first one installed. func TestInstallMacOneAtATime(t *testing.T) { x := installedBefore(t, "https://equipo.example") lock, err := installLock(filepath.Join(x.home, ".local/share/equipo-runner/state")) if err != nil { t.Fatal(err) } defer lock.Close() before := x.snapshot(t) code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.install.busy")) { t.Fatalf("%d %q", code, errout) } if len(x.calls) != 0 || !x.loaded || x.enrolled != nil || len(x.fetched) != 0 { t.Fatalf("changed something: %v", x.calls) } if after := x.snapshot(t); !mapsEqual(before, after) { t.Fatalf("files changed:\n%v\n%v", before, after) } } // The install command run from the runner installed here copies that // runner from where it was moved aside: it installs, and a failure puts // it back as it was. func TestInstallMacFromTheInstalledRunner(t *testing.T) { for _, fails := range []bool{false, true} { x := installedBefore(t, "https://equipo.example") binary := filepath.Join(x.home, ".local/lib/equipo-runner/equipo-runner") x.h.self = binary before := x.snapshot(t) if fails { x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired } } code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if fails { if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.restored")) || !mapsEqual(before, x.snapshot(t)) { t.Fatalf("not put back: %d %q", code, errout) } continue } if code != 0 { t.Fatalf("%d %q", code, errout) } if raw, _ := os.ReadFile(binary); string(raw) != before[".local/lib/equipo-runner/equipo-runner"] { t.Fatalf("installed %q", raw) } } } // A bootout that took the agent out but answered an error (launchctl // ended part way) is a stopped runner, not one left running: launchd // gets it back when the install does not go ahead. A give-back that // fails is said, not passed over. func TestInstallMacStopThatTookTheAgentDown(t *testing.T) { x := installedBefore(t, "https://equipo.example") x.bootoutErr, x.bootoutTakesDown = errors.New("Boot-out failed: 5"), true x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired } code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if code != 1 || !x.loaded || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.restored")) { t.Fatalf("left down: %d %q %v", code, errout, x.calls) } x = newMacRig(t) x.loaded, x.bootstrapErr = true, errors.New("Bootstrap failed: 5") lock, err := runner.LockState(filepath.Join(x.home, ".local/share/equipo-runner/state")) if err != nil { t.Fatal(err) } defer lock.Close() code, _, errout = x.install() if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.still_running")) || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.not_restored")) { t.Fatalf("a failed give-back not said: %d %q", code, errout) } } // expiredEnrolment is a runner enrolled with origin once, its credential // now expired: an install for another Equipo may replace it. func expiredEnrolment(t *testing.T, state, origin string) { t.Helper() if err := runnerproto.JournalCredentials(filepath.Join(state, "credentials.json"), runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Version: 1, RunnerID: "r0", Token: "old", ExpiresAt: time.Now().Add(-time.Hour)}}); err != nil { t.Fatal(err) } record := map[string]any{"origin": origin, "label": "Tito Studio", "code": map[string]string{"instance_id": "team1"}} if err := runnerproto.JournalCredentials(filepath.Join(state, "enrolment.json"), record); err != nil { t.Fatal(err) } } // An enrolment that published its credential and then answered an error // (the directory sync after the rename failed) is enrolled: the install // goes on with the new configuration rather than putting the earlier // one back beside the new credential (Astra round 2, mac-install-safe). func TestInstallMacEnrolledDespiteAnError(t *testing.T) { x := installedBefore(t, stagingOrigin) state := filepath.Join(x.home, ".local/share/equipo-runner/state") expiredEnrolment(t, state, stagingOrigin) x.h.enrol = func(_ context.Context, cfg runner.Config, _ io.Writer) error { liveEnrolment(t, cfg.StateDir, cfg.Origin, cfg.InstanceID) return errors.New("sync state: input/output error") } code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if code != 0 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.installed")) { t.Fatalf("%d %q", code, errout) } if env, _ := runnersetup.ReadEnvFile(filepath.Join(x.home, ".config/equipo-runner/runner.env")); env["EQUIPO_ORIGIN"] != "https://equipo.example" { t.Fatalf("configuration put back beside the new credential: %v", env) } } // A direct enrolment (equipo-runner enrol) waits for no install and // never runs beside one: while an install holds the lock it is refused // before it enrols, so the install cannot put back over what it added. func TestEnrolAloneWhileInstalling(t *testing.T) { state := filepath.Join(t.TempDir(), "state") calls := 0 enrol := func(context.Context, runner.Config, io.Writer) error { calls++; return nil } lock, err := installLock(state) if err != nil { t.Fatal(err) } if err := enrolAlone(context.Background(), runner.Config{StateDir: state}, io.Discard, enrol); !errors.Is(err, errInstallBusy) || calls != 0 { t.Fatalf("enrolled during an install: %v %d", err, calls) } lock.Close() if err := enrolAlone(context.Background(), runner.Config{StateDir: state}, io.Discard, enrol); err != nil || calls != 1 { t.Fatalf("not enrolled: %v %d", err, calls) } } // When whether the enrolment published its credential cannot be read // (the credential is unreadable after the enrolment's error), nothing // is put back beside what may be a new credential: the install stops, // saying the earlier runner is not back, and keeps it aside (Astra // round 3, mac-install-safe). func TestInstallMacEnrolmentUnknown(t *testing.T) { x := installedBefore(t, stagingOrigin) state := filepath.Join(x.home, ".local/share/equipo-runner/state") expiredEnrolment(t, state, stagingOrigin) x.h.enrol = func(_ context.Context, cfg runner.Config, _ io.Writer) error { path := filepath.Join(cfg.StateDir, "credentials.json") if err := os.Remove(path); err != nil { t.Fatal(err) } if err := os.Mkdir(path, 0700); err != nil { t.Fatal(err) } return errors.New("sync state: input/output error") } code, errout := x.installAt(context.Background(), "https://equipo.example", "team1") if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.not_restored")) || strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.restored")) { t.Fatalf("%d %q", code, errout) } if env, _ := runnersetup.ReadEnvFile(filepath.Join(x.home, ".config/equipo-runner/runner.env")); env["EQUIPO_ORIGIN"] != "https://equipo.example" { t.Fatalf("put back with the enrolment unknown: %v", env) } }