oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "path/filepath"
11 "slices"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/equipo"
17 "amadan.net/oficina/equipo/internal/runner"
18 "amadan.net/oficina/equipo/internal/runner/provider"
19 runnersetup "amadan.net/oficina/equipo/internal/runner/setup"
20 "amadan.net/oficina/equipo/internal/runnerproto"
21)
22
23const stagingOrigin = "https://equipo-staging.example"
24
25// liveEnrolment writes what an enrolled runner keeps in its state: a live
26// credential and the enrolment it came from (no record when origin is "").
27func liveEnrolment(t *testing.T, state, origin, instance string) {
28 t.Helper()
29 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 {
30 t.Fatal(err)
31 }
32 if origin == "" {
33 return
34 }
35 record := map[string]any{"origin": origin, "label": "Tito Studio", "code": map[string]string{"instance_id": instance}}
36 if err := runnerproto.JournalCredentials(filepath.Join(state, "enrolment.json"), record); err != nil {
37 t.Fatal(err)
38 }
39}
40
41func (x *macRig) installAt(ctx context.Context, origin, instance string) (int, string) {
42 var out, errout bytes.Buffer
43 code := installMac(ctx, []string{"--release", "abc1234", "--origin", origin, "--instance", instance}, x.h, &out, &errout)
44 return code, errout.String()
45}
46
47// snapshot is what a runner installed before runs on: its binary, the
48// scanner beside it, its environment file and its launchd agent.
49func (x *macRig) snapshot(t *testing.T) map[string]string {
50 t.Helper()
51 got := map[string]string{}
52 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"} {
53 raw, err := os.ReadFile(filepath.Join(x.home, p))
54 if err != nil {
55 got[p] = "missing"
56 continue
57 }
58 got[p] = string(raw)
59 }
60 return got
61}
62
63// installedBefore is a Mac with a runner for origin installed and running,
64// enrolled there; the next install brings a newer runner.
65func installedBefore(t *testing.T, origin string) *macRig {
66 t.Helper()
67 x := newMacRig(t)
68 if code, errout := x.installAt(context.Background(), origin, "team1"); code != 0 {
69 t.Fatalf("first install: %d %s", code, errout)
70 }
71 liveEnrolment(t, filepath.Join(x.home, ".local/share/equipo-runner/state"), origin, "team1")
72 // Something only the earlier install wrote, so putting it back shows.
73 env := filepath.Join(x.home, ".config/equipo-runner/runner.env")
74 values := map[string]string{"EQUIPO_ORIGIN": origin, "EQUIPO_INSTANCE_ID": "team1", "EQUIPO_MACHINE_LABEL": "Before"}
75 if err := writeEnvFile(env, values); err != nil {
76 t.Fatal(err)
77 }
78 if err := os.WriteFile(x.h.self, []byte("#!newer runner\n"), 0700); err != nil {
79 t.Fatal(err)
80 }
81 x.calls, x.fetched, x.enrolled, x.childHomes = nil, nil, nil, nil
82 return x
83}
84
85// A Mac user already enrolled with another Equipo (the Studio's staging
86// runner, then a production install, 2026-11-28) is told so in words and
87// nothing is changed: its runner is not stopped, its environment file is
88// not rewritten, nothing is downloaded and nothing is enrolled.
89func TestInstallMacRefusesAnotherEquipo(t *testing.T) {
90 for name, c := range map[string]struct {
91 record string
92 want string
93 // unreadable is a credential that cannot be read: whose it is
94 // is not known, so nothing is stopped or changed either.
95 unreadable bool
96 }{
97 "another origin": {record: stagingOrigin, want: fmt.Sprintf(equipo.RunnerSetupCopy("runner.mac.other_instance"), stagingOrigin)},
98 "origin not known": {want: equipo.RunnerSetupCopy("runner.enrol.identity")},
99 // A saved origin that is not a plain web address (here with a
100 // password and a sign-in link in it) is never printed.
101 "origin not an address": {record: "https://paul:hunter2@equipo-staging.example/signin?token=s3cret", want: equipo.RunnerSetupCopy("runner.enrol.identity")},
102 "credential unreadable": {record: stagingOrigin, want: strings.TrimSuffix(equipo.RunnerSetupCopy("runner.enrol.failed"), "%s"), unreadable: true},
103 } {
104 t.Run(name, func(t *testing.T) {
105 x := installedBefore(t, stagingOrigin)
106 state := filepath.Join(x.home, ".local/share/equipo-runner/state")
107 switch {
108 case c.record == "":
109 if err := os.Remove(filepath.Join(state, "enrolment.json")); err != nil {
110 t.Fatal(err)
111 }
112 case c.record != stagingOrigin:
113 liveEnrolment(t, state, c.record, "team1")
114 }
115 if c.unreadable {
116 if err := os.WriteFile(filepath.Join(state, "credentials.json"), []byte("{"), 0600); err != nil {
117 t.Fatal(err)
118 }
119 }
120 before := x.snapshot(t)
121 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
122 if code != 1 || !strings.Contains(errout, c.want) || strings.Contains(errout, string(provider.ErrIdentity)) || strings.Contains(errout, "hunter2") || strings.Contains(errout, "s3cret") {
123 t.Fatalf("%d %q", code, errout)
124 }
125 if len(x.calls) != 0 || !x.loaded || x.enrolled != nil || len(x.fetched) != 0 || len(x.childHomes) != 0 {
126 t.Fatalf("changed something: calls %v loaded %v", x.calls, x.loaded)
127 }
128 if after := x.snapshot(t); !mapsEqual(before, after) {
129 t.Fatalf("files changed:\n%v\n%v", before, after)
130 }
131 })
132 }
133}
134
135func mapsEqual(a, b map[string]string) bool {
136 if len(a) != len(b) {
137 return false
138 }
139 for k, v := range a {
140 if b[k] != v {
141 return false
142 }
143 }
144 return true
145}
146
147// Anything that fails once the runner was stopped puts back what it ran
148// on, exactly, and starts it again: a link that expired, the person
149// stopping the wait (the context ends, the reload still happens), a
150// scanner that is not the pin, a Mac the instance takes for a primary.
151// A runner that was not running is put back and left stopped.
152func TestInstallMacPutsBackThePreviousRunner(t *testing.T) {
153 for name, c := range map[string]struct {
154 set func(*macRig, context.CancelFunc)
155 want string
156 notLoaded bool
157 }{
158 "link expired": {set: func(x *macRig, _ context.CancelFunc) {
159 x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired }
160 }, want: "runner.enrol.expired"},
161 "wait stopped": {set: func(x *macRig, cancel context.CancelFunc) {
162 x.h.enrol = func(ctx context.Context, _ runner.Config, _ io.Writer) error { cancel(); return ctx.Err() }
163 }, want: "runner.install.unavailable"},
164 "scanner not the pin": {set: func(x *macRig, _ context.CancelFunc) {
165 fetch := x.h.fetch
166 x.h.fetch = func(ctx context.Context, url string, limit int64) ([]byte, error) {
167 if strings.HasSuffix(url, "/gitleaks") {
168 return []byte("tampered"), nil
169 }
170 return fetch(ctx, url, limit)
171 }
172 }, want: "runner.install.checksum"},
173 "taken for a primary": {set: func(x *macRig, _ context.CancelFunc) {
174 x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolledAsPrimary }
175 }, want: "runner.needs_primary"},
176 "was not running": {set: func(x *macRig, _ context.CancelFunc) {
177 x.loaded = false
178 x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentRefused }
179 }, want: "runner.enrol.refused", notLoaded: true},
180 } {
181 t.Run(name, func(t *testing.T) {
182 x := installedBefore(t, "https://equipo.example")
183 before := x.snapshot(t)
184 ctx, cancel := context.WithCancel(context.Background())
185 defer cancel()
186 c.set(x, cancel)
187 code, errout := x.installAt(ctx, "https://equipo.example", "team1")
188 if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy(c.want)) || !strings.HasSuffix(errout, equipo.RunnerSetupCopy("runner.mac.restored")+"\n") {
189 t.Fatalf("%d %q", code, errout)
190 }
191 if after := x.snapshot(t); !mapsEqual(before, after) {
192 t.Fatalf("not put back:\n%v\n%v", before, after)
193 }
194 plist := filepath.Join(x.home, "Library/LaunchAgents/io.amadan.equipo-runner.plist")
195 reloaded := len(x.calls) > 0 && x.calls[len(x.calls)-1] == "launchctl bootstrap gui/502 "+plist
196 if c.notLoaded == reloaded || x.loaded == c.notLoaded {
197 t.Fatalf("loaded %v calls %v", x.loaded, x.calls)
198 }
199 // Nothing kept aside is left behind.
200 if entries, _ := os.ReadDir(filepath.Join(x.home, ".local/share/equipo-runner")); len(entries) != 3 {
201 t.Fatalf("left behind %v", entries)
202 }
203 })
204 }
205}
206
207// A first install that fails leaves no configuration a later login would
208// start, and says nothing about putting a runner back.
209func TestInstallMacFirstFailureLeavesNoConfig(t *testing.T) {
210 x := newMacRig(t)
211 x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired }
212 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
213 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") }) {
214 t.Fatalf("%d %q %v", code, errout, x.calls)
215 }
216 if _, err := os.Stat(filepath.Join(x.home, ".config/equipo-runner/runner.env")); !os.IsNotExist(err) {
217 t.Fatal("environment file left behind")
218 }
219}
220
221// An install that works replaces the earlier runner and keeps nothing of
222// it aside.
223func TestInstallMacAgainKeepsNothingAside(t *testing.T) {
224 x := installedBefore(t, "https://equipo.example")
225 if code, errout := x.installAt(context.Background(), "https://equipo.example", "team1"); code != 0 {
226 t.Fatalf("%d %q", code, errout)
227 }
228 if got := x.snapshot(t)[".local/lib/equipo-runner/equipo-runner"]; got != "#!newer runner\n" {
229 t.Fatalf("runner %q", got)
230 }
231 if entries, _ := os.ReadDir(filepath.Join(x.home, ".local/share/equipo-runner")); len(entries) != 3 {
232 t.Fatalf("left behind %v", entries)
233 }
234}
235
236// Started from a folder this user cannot read (sudo su without a dash,
237// 2026-11-28: npm and xcodebuild failed, so no checks sandbox), the
238// installer moves into the user's own home before it runs anything, and
239// every program it runs is given its own folder.
240func TestInstallMacRunsFromItsHome(t *testing.T) {
241 x := newMacRig(t)
242 npmCI, firstLaunch := x.h.npmCI, x.h.firstLaunch
243 x.h.npmCI = func(ctx context.Context, npm, prefix, home string) error {
244 if x.cwd != x.home {
245 t.Errorf("npm ran in %q", x.cwd)
246 }
247 return npmCI(ctx, npm, prefix, home)
248 }
249 x.h.firstLaunch = func(ctx context.Context, home string) {
250 if x.cwd != x.home {
251 t.Errorf("xcodebuild ran in %q", x.cwd)
252 }
253 firstLaunch(ctx, home)
254 }
255 if code, errout := x.installAt(context.Background(), "https://equipo.example", "team1"); code != 0 {
256 t.Fatalf("%d %q", code, errout)
257 }
258 // A home it cannot move into changes nothing.
259 x = newMacRig(t)
260 x.h.chdir = func(string) error { return os.ErrPermission }
261 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 {
262 t.Fatalf("%d %q %v", code, errout, x.calls)
263 }
264 ctx := context.Background()
265 if dir := npmCICommand(ctx, "/n/bin/npm", "/h/.local/lib/equipo-runner/srt", "/h").Dir; dir != "/h/.local/lib/equipo-runner/srt" {
266 t.Fatalf("npm dir %q", dir)
267 }
268 if dir := firstLaunchCommand(ctx, "/h").Dir; dir != "/h" {
269 t.Fatalf("xcodebuild dir %q", dir)
270 }
271 if dir := systemCommand(ctx, "/bin/launchctl", "print").Dir; dir != "/" {
272 t.Fatalf("system tool dir %q", dir)
273 }
274}
275
276// An identity Enrol cannot match is said in words, not as its code, and
277// stands alone.
278func TestInstallMacIdentityInWords(t *testing.T) {
279 x := newMacRig(t)
280 x.h.enrol = func(context.Context, runner.Config, io.Writer) error {
281 return fmt.Errorf("enrol: %w", provider.ErrIdentity)
282 }
283 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
284 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")) {
285 t.Fatalf("%d %q", code, errout)
286 }
287}
288
289// A second install for the same Mac user while one is running is refused
290// and changes nothing (Astra, mac-install-safe): it cannot put its backup
291// back over what the first one installed.
292func TestInstallMacOneAtATime(t *testing.T) {
293 x := installedBefore(t, "https://equipo.example")
294 lock, err := installLock(filepath.Join(x.home, ".local/share/equipo-runner/state"))
295 if err != nil {
296 t.Fatal(err)
297 }
298 defer lock.Close()
299 before := x.snapshot(t)
300 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
301 if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.install.busy")) {
302 t.Fatalf("%d %q", code, errout)
303 }
304 if len(x.calls) != 0 || !x.loaded || x.enrolled != nil || len(x.fetched) != 0 {
305 t.Fatalf("changed something: %v", x.calls)
306 }
307 if after := x.snapshot(t); !mapsEqual(before, after) {
308 t.Fatalf("files changed:\n%v\n%v", before, after)
309 }
310}
311
312// The install command run from the runner installed here copies that
313// runner from where it was moved aside: it installs, and a failure puts
314// it back as it was.
315func TestInstallMacFromTheInstalledRunner(t *testing.T) {
316 for _, fails := range []bool{false, true} {
317 x := installedBefore(t, "https://equipo.example")
318 binary := filepath.Join(x.home, ".local/lib/equipo-runner/equipo-runner")
319 x.h.self = binary
320 before := x.snapshot(t)
321 if fails {
322 x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired }
323 }
324 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
325 if fails {
326 if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.restored")) || !mapsEqual(before, x.snapshot(t)) {
327 t.Fatalf("not put back: %d %q", code, errout)
328 }
329 continue
330 }
331 if code != 0 {
332 t.Fatalf("%d %q", code, errout)
333 }
334 if raw, _ := os.ReadFile(binary); string(raw) != before[".local/lib/equipo-runner/equipo-runner"] {
335 t.Fatalf("installed %q", raw)
336 }
337 }
338}
339
340// A bootout that took the agent out but answered an error (launchctl
341// ended part way) is a stopped runner, not one left running: launchd
342// gets it back when the install does not go ahead. A give-back that
343// fails is said, not passed over.
344func TestInstallMacStopThatTookTheAgentDown(t *testing.T) {
345 x := installedBefore(t, "https://equipo.example")
346 x.bootoutErr, x.bootoutTakesDown = errors.New("Boot-out failed: 5"), true
347 x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired }
348 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
349 if code != 1 || !x.loaded || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.restored")) {
350 t.Fatalf("left down: %d %q %v", code, errout, x.calls)
351 }
352
353 x = newMacRig(t)
354 x.loaded, x.bootstrapErr = true, errors.New("Bootstrap failed: 5")
355 lock, err := runner.LockState(filepath.Join(x.home, ".local/share/equipo-runner/state"))
356 if err != nil {
357 t.Fatal(err)
358 }
359 defer lock.Close()
360 code, _, errout = x.install()
361 if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.still_running")) || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.not_restored")) {
362 t.Fatalf("a failed give-back not said: %d %q", code, errout)
363 }
364}
365
366// expiredEnrolment is a runner enrolled with origin once, its credential
367// now expired: an install for another Equipo may replace it.
368func expiredEnrolment(t *testing.T, state, origin string) {
369 t.Helper()
370 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 {
371 t.Fatal(err)
372 }
373 record := map[string]any{"origin": origin, "label": "Tito Studio", "code": map[string]string{"instance_id": "team1"}}
374 if err := runnerproto.JournalCredentials(filepath.Join(state, "enrolment.json"), record); err != nil {
375 t.Fatal(err)
376 }
377}
378
379// An enrolment that published its credential and then answered an error
380// (the directory sync after the rename failed) is enrolled: the install
381// goes on with the new configuration rather than putting the earlier
382// one back beside the new credential (Astra round 2, mac-install-safe).
383func TestInstallMacEnrolledDespiteAnError(t *testing.T) {
384 x := installedBefore(t, stagingOrigin)
385 state := filepath.Join(x.home, ".local/share/equipo-runner/state")
386 expiredEnrolment(t, state, stagingOrigin)
387 x.h.enrol = func(_ context.Context, cfg runner.Config, _ io.Writer) error {
388 liveEnrolment(t, cfg.StateDir, cfg.Origin, cfg.InstanceID)
389 return errors.New("sync state: input/output error")
390 }
391 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
392 if code != 0 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.installed")) {
393 t.Fatalf("%d %q", code, errout)
394 }
395 if env, _ := runnersetup.ReadEnvFile(filepath.Join(x.home, ".config/equipo-runner/runner.env")); env["EQUIPO_ORIGIN"] != "https://equipo.example" {
396 t.Fatalf("configuration put back beside the new credential: %v", env)
397 }
398}
399
400// A direct enrolment (equipo-runner enrol) waits for no install and
401// never runs beside one: while an install holds the lock it is refused
402// before it enrols, so the install cannot put back over what it added.
403func TestEnrolAloneWhileInstalling(t *testing.T) {
404 state := filepath.Join(t.TempDir(), "state")
405 calls := 0
406 enrol := func(context.Context, runner.Config, io.Writer) error { calls++; return nil }
407 lock, err := installLock(state)
408 if err != nil {
409 t.Fatal(err)
410 }
411 if err := enrolAlone(context.Background(), runner.Config{StateDir: state}, io.Discard, enrol); !errors.Is(err, errInstallBusy) || calls != 0 {
412 t.Fatalf("enrolled during an install: %v %d", err, calls)
413 }
414 lock.Close()
415 if err := enrolAlone(context.Background(), runner.Config{StateDir: state}, io.Discard, enrol); err != nil || calls != 1 {
416 t.Fatalf("not enrolled: %v %d", err, calls)
417 }
418}
419
420// When whether the enrolment published its credential cannot be read
421// (the credential is unreadable after the enrolment's error), nothing
422// is put back beside what may be a new credential: the install stops,
423// saying the earlier runner is not back, and keeps it aside (Astra
424// round 3, mac-install-safe).
425func TestInstallMacEnrolmentUnknown(t *testing.T) {
426 x := installedBefore(t, stagingOrigin)
427 state := filepath.Join(x.home, ".local/share/equipo-runner/state")
428 expiredEnrolment(t, state, stagingOrigin)
429 x.h.enrol = func(_ context.Context, cfg runner.Config, _ io.Writer) error {
430 path := filepath.Join(cfg.StateDir, "credentials.json")
431 if err := os.Remove(path); err != nil {
432 t.Fatal(err)
433 }
434 if err := os.Mkdir(path, 0700); err != nil {
435 t.Fatal(err)
436 }
437 return errors.New("sync state: input/output error")
438 }
439 code, errout := x.installAt(context.Background(), "https://equipo.example", "team1")
440 if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.not_restored")) || strings.Contains(errout, equipo.RunnerSetupCopy("runner.mac.restored")) {
441 t.Fatalf("%d %q", code, errout)
442 }
443 if env, _ := runnersetup.ReadEnvFile(filepath.Join(x.home, ".config/equipo-runner/runner.env")); env["EQUIPO_ORIGIN"] != "https://equipo.example" {
444 t.Fatalf("put back with the enrolment unknown: %v", env)
445 }
446}
447