package main import ( "bytes" "context" "errors" "fmt" "io" "os" "path/filepath" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/runner" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/rastrillo/rastrillo" ) type linuxRig struct { h linuxInstallHost home, root string installs int enrolled bool cwd string } func newLinuxRig(t *testing.T) *linuxRig { t.Helper() old := rastrillo.BuildVersion rastrillo.BuildVersion = "abc1234" t.Cleanup(func() { rastrillo.BuildVersion = old }) x := &linuxRig{home: t.TempDir()} x.root = filepath.Join(x.home, ".local/share/equipo-runner") x.h = linuxInstallHost{ home: func() (string, error) { return x.home, nil }, chdir: func(dir string) error { x.cwd = dir; return nil }, installable: func() bool { return true }, install: func(_ context.Context, o runnersetup.InstallOptions) (runnersetup.InstallResult, error) { if x.cwd != x.home { t.Errorf("installed from %q", x.cwd) } x.installs++ if err := os.MkdirAll(o.Root, 0700); err != nil { return runnersetup.InstallResult{}, err } if err := os.WriteFile(filepath.Join(o.Root, "equipo-runner.service"), []byte("unit for "+o.InstanceOrigin), 0600); err != nil { return runnersetup.InstallResult{}, err } return runnersetup.InstallResult{BinaryPath: filepath.Join(o.Root, "releases/abc1234/equipo-runner"), State: "installed"}, nil }, config: func(root, origin, instance, _ string, _ func(string) string) (runner.Config, error) { if err := os.WriteFile(filepath.Join(root, "runner.env"), []byte("EQUIPO_ORIGIN="+strconv.Quote(origin)+"\n"), 0600); err != nil { return runner.Config{}, err } return runner.Config{Origin: origin, InstanceID: instance, StateDir: filepath.Join(root, "state")}, nil }, verify: func(runner.Config) error { return nil }, enrol: func(context.Context, runner.Config, io.Writer) error { x.enrolled = true; return nil }, checkEnv: func(string, string, string) error { return nil }, // The installer's own files, except one a person edited. owned: func(path string) bool { raw, _ := os.ReadFile(path) return !strings.Contains(string(raw), "edited by hand") }, } return x } func (x *linuxRig) installWith(ctx context.Context, origin string, input io.Reader) (int, string) { var out, errout bytes.Buffer code := installLinux(ctx, []string{"--release", "abc1234", "--origin", origin, "--instance", "team1"}, input, &out, &errout, func(string) string { return "" }, x.h) return code, errout.String() } // A first install (no root yet) that stops before the enrolment leaves // no unit or environment file behind: nothing would start a runner that // was never added (Astra, mac-install-safe). func TestInstallLinuxFirstFailureLeavesNoConfig(t *testing.T) { x := newLinuxRig(t) x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired } if code, errout := x.install("https://equipo.example", "yes"); code != 1 { t.Fatalf("%d %q", code, errout) } if got := x.files(t); len(got) != 0 { t.Fatalf("left behind %v", got) } } // A unit or environment file someone edited by hand is not moved aside // or replaced: the install stops before changing anything. func TestInstallLinuxKeepsAnEditedFile(t *testing.T) { for _, name := range []string{"runner.env", "equipo-runner.service"} { t.Run(name, func(t *testing.T) { x := newLinuxRig(t) x.before(t, "https://equipo.example") if err := os.WriteFile(filepath.Join(x.root, name), []byte("edited by hand"), 0600); err != nil { t.Fatal(err) } before := x.files(t) code, errout := x.install("https://equipo-next.example", "yes") if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.install.destination")) { t.Fatalf("%d %q", code, errout) } if x.installs != 0 || x.enrolled || !mapsEqual(before, x.files(t)) { t.Fatalf("changed something: %d %v %v", x.installs, x.enrolled, x.files(t)) } }) } } // Ctrl-C at a prompt (the input stays open, no line comes) ends the // install and puts the earlier configuration back at once. func TestInstallLinuxCtrlCAtAPrompt(t *testing.T) { for _, answered := range []string{"", "\n"} { x := newLinuxRig(t) before := x.before(t, "https://equipo.example") r, w := io.Pipe() defer w.Close() installed := make(chan struct{}) install := x.h.install x.h.install = func(ctx context.Context, o runnersetup.InstallOptions) (runnersetup.InstallResult, error) { defer close(installed) return install(ctx, o) } ctx, cancel := context.WithCancel(context.Background()) done := make(chan int) go func() { code, _ := x.installWith(ctx, "https://equipo-next.example", r); done <- code }() <-installed if answered != "" { // The label is answered; Ctrl-C comes at the yes prompt. _, _ = io.WriteString(w, answered) } time.Sleep(50 * time.Millisecond) cancel() select { case code := <-done: if code != 1 { t.Fatalf("exit %d", code) } case <-time.After(5 * time.Second): t.Fatal("Ctrl-C at the prompt did not end the install") } if got := x.files(t); !mapsEqual(before, got) || x.enrolled { t.Fatalf("not put back: %v", got) } } } // A second install of the same runner while one is running is refused // and changes nothing: it cannot put its backup back over the first. func TestInstallLinuxOneAtATime(t *testing.T) { x := newLinuxRig(t) before := x.before(t, "https://equipo.example") lock, err := installLock(filepath.Join(x.root, "state")) if err != nil { t.Fatal(err) } defer lock.Close() code, errout := x.install("https://equipo-next.example", "yes") if code != 1 || !strings.Contains(errout, equipo.RunnerSetupCopy("runner.install.busy")) { t.Fatalf("%d %q", code, errout) } if x.installs != 0 || x.enrolled || !mapsEqual(before, x.files(t)) { t.Fatalf("changed something: %d %v %v", x.installs, x.enrolled, x.files(t)) } } func (x *linuxRig) install(origin, answer string) (int, string) { var out, errout bytes.Buffer code := installLinux(context.Background(), []string{"--release", "abc1234", "--origin", origin, "--instance", "team1"}, strings.NewReader("\n"+answer+"\n"), &out, &errout, func(string) string { return "" }, x.h) return code, errout.String() } // before is a runner installed for origin: its unit and environment file. func (x *linuxRig) before(t *testing.T, origin string) map[string]string { t.Helper() files := map[string]string{"runner.env": "EQUIPO_ORIGIN=" + strconv.Quote(origin) + "\n", "equipo-runner.service": "unit for " + origin} for name, body := range files { if err := os.MkdirAll(x.root, 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(x.root, name), []byte(body), 0600); err != nil { t.Fatal(err) } } return files } func (x *linuxRig) files(t *testing.T) map[string]string { t.Helper() got := map[string]string{} entries, err := os.ReadDir(x.root) if err != nil { t.Fatal(err) } for _, e := range entries { // The install log is the installer's own record. if e.IsDir() || e.Name() == "install.log" { continue } raw, _ := os.ReadFile(filepath.Join(x.root, e.Name())) got[e.Name()] = string(raw) } return got } // The Linux installer asks first too: a runner enrolled with another // Equipo is told so and nothing is installed, written or enrolled. func TestInstallLinuxRefusesAnotherEquipo(t *testing.T) { for name, c := range map[string]struct { unreadable bool want string }{ "another origin": {want: fmt.Sprintf(equipo.RunnerSetupCopy("runner.install.other_instance"), stagingOrigin)}, "credential unreadable": {unreadable: true, want: strings.TrimSuffix(equipo.RunnerSetupCopy("runner.enrol.failed"), "%s")}, } { t.Run(name, func(t *testing.T) { x := newLinuxRig(t) before := x.before(t, stagingOrigin) state := filepath.Join(x.root, "state") liveEnrolment(t, state, stagingOrigin, "team1") if c.unreadable { if err := os.WriteFile(filepath.Join(state, "credentials.json"), []byte("{"), 0600); err != nil { t.Fatal(err) } } code, errout := x.install("https://equipo.example", "yes") if code != 1 || !strings.Contains(errout, c.want) { t.Fatalf("%d %q", code, errout) } if x.installs != 0 || x.enrolled || !mapsEqual(before, x.files(t)) { t.Fatalf("changed something: %d %v %v", x.installs, x.enrolled, x.files(t)) } }) } } // What the installer rewrote before enrolling (the unit and the // environment file) is put back when it stops before the enrolment is // done; an install that enrols keeps the new ones and nothing aside. func TestInstallLinuxPutsBackItsConfig(t *testing.T) { for name, c := range map[string]struct { set func(*linuxRig) answer string }{ "link expired": {set: func(x *linuxRig) { x.h.enrol = func(context.Context, runner.Config, io.Writer) error { return runner.ErrEnrolmentExpired } }, answer: "yes"}, "not confirmed": {set: func(*linuxRig) {}, answer: "no"}, "not the release": {set: func(x *linuxRig) { x.h.verify = func(runner.Config) error { return errScanner } }, answer: "yes"}, } { t.Run(name, func(t *testing.T) { x := newLinuxRig(t) before := x.before(t, "https://equipo.example") c.set(x) if code, errout := x.install("https://equipo-next.example", c.answer); code != 1 { t.Fatalf("%d %q", code, errout) } if got := x.files(t); !mapsEqual(before, got) { t.Fatalf("not put back: %v", got) } if got := len(x.files(t)); got != 2 { t.Fatalf("left behind %v", x.files(t)) } // The unit, the environment file, the install log and the // state directory with its install lock: no backup left. if entries, _ := os.ReadDir(x.root); len(entries) > 4 { t.Fatalf("left behind %v", entries) } }) } x := newLinuxRig(t) x.before(t, "https://equipo.example") if code, errout := x.install("https://equipo-next.example", "yes"); code != 0 || !x.enrolled { t.Fatalf("%d %q", code, errout) } if got := x.files(t); got["runner.env"] != "EQUIPO_ORIGIN=\"https://equipo-next.example\"\n" || got["equipo-runner.service"] != "unit for https://equipo-next.example" { t.Fatalf("new config %v", got) } // The unit, the environment file and the state directory. if entries, _ := os.ReadDir(x.root); len(entries) != 3 { t.Fatalf("left behind %v", entries) } } // As on a Mac: an enrolment that published its credential, then // answered an error, is enrolled and its configuration kept. func TestInstallLinuxEnrolledDespiteAnError(t *testing.T) { x := newLinuxRig(t) x.before(t, stagingOrigin) expiredEnrolment(t, filepath.Join(x.root, "state"), stagingOrigin) x.h.enrol = func(_ context.Context, cfg runner.Config, _ io.Writer) error { liveEnrolment(t, cfg.StateDir, cfg.Origin, cfg.InstanceID) x.enrolled = true return errors.New("sync state: input/output error") } code, errout := x.install("https://equipo.example", "yes") if code != 0 || !x.enrolled { t.Fatalf("%d %q", code, errout) } if got := x.files(t); got["runner.env"] != "EQUIPO_ORIGIN=\"https://equipo.example\"\n" { t.Fatalf("configuration put back beside the new credential: %v", got) } } // As on a Mac: with the enrolment's outcome unreadable, the earlier // configuration is not put back beside what may be a new credential. func TestInstallLinuxEnrolmentUnknown(t *testing.T) { x := newLinuxRig(t) x.before(t, stagingOrigin) expiredEnrolment(t, filepath.Join(x.root, "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") } if code, errout := x.install("https://equipo.example", "yes"); code != 1 { t.Fatalf("%d %q", code, errout) } if got := x.files(t); got["runner.env"] != "EQUIPO_ORIGIN=\"https://equipo.example\"\n" { t.Fatalf("put back with the enrolment unknown: %v", got) } }