package main import ( "amadan.net/oficina/equipo/internal/runner/provider/opencode" "amadan.net/oficina/equipo/internal/runner/provider/pi" "context" "encoding/json" "errors" "flag" "fmt" "io" "os" "path/filepath" "strings" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/rastrillo/rastrillo" ) // linuxInstallHost is what installing on Linux touches; tests stand in. type linuxInstallHost struct { home func() (string, error) chdir func(string) error installable func() bool install func(context.Context, runnersetup.InstallOptions) (runnersetup.InstallResult, error) config func(root, origin, instance, version string, getenv func(string) string) (runner.Config, error) verify func(runner.Config) error enrol func(context.Context, runner.Config, io.Writer) error checkEnv func(root, origin, state string) error // owned is whether the installer may replace a file it wrote before // (runnersetup.InstallerOwns): never one edited by hand. owned func(path string) bool } func installRunner(ctx context.Context, args []string, input io.Reader, out, errout io.Writer, getenv func(string) string) int { return installLinux(ctx, args, input, out, errout, getenv, linuxInstallHost{ home: os.UserHomeDir, chdir: os.Chdir, installable: func() bool { return release.BuildManifest().Installable() }, install: runnersetup.InstallUser, config: installConfig, verify: func(cfg runner.Config) error { return verifyInstalled(release.BuildManifest(), cfg) }, enrol: runner.Enrol, checkEnv: runnersetup.CheckServiceEnvironment, owned: runnersetup.InstallerOwns, }) } // installLinux installs a runner under --root (default // ~/.local/share/equipo-runner), from the user's home. A root whose // runner is enrolled with another Equipo is refused before anything is // installed. The unit and the environment file a runner installed before // uses are kept aside until the enrolment is done, and put back if the // install stops before then; the running service is never stopped. func installLinux(ctx context.Context, args []string, input io.Reader, out, errout io.Writer, getenv func(string) string, h linuxInstallHost) int { fail := func(key string) int { fmt.Fprintln(errout, equipo.RunnerSetupCopy(key)); return 1 } flags := flag.NewFlagSet("install", flag.ContinueOnError) flags.SetOutput(io.Discard) home, e := h.home() if e != nil { return fail("runner.install.destination") } instance := flags.String("instance", "", "") version := flags.String("release", "", "") origin := flags.String("origin", "", "") root := flags.String("root", filepath.Join(home, ".local/share/equipo-runner"), "") if flags.Parse(args) != nil || flags.NArg() != 0 || *instance == "" || *version != rastrillo.BuildVersion || !h.installable() { return fail("runner.install.release") } // Everything runs from the user's home, never the folder the // installer was started from (which this user may not read). if h.chdir(home) != nil { return fail("runner.install.destination") } // One install at a time, from this check until it is enrolled or put // back: a second one is refused, not let put back over the first. lock, e := installLock(filepath.Join(*root, "state")) if e != nil { return fail(lockKey(e)) } defer lock.Close() if key, a := enrolledElsewhere(filepath.Join(*root, "state"), *origin, *instance, "runner.install.other_instance"); key != "" { fmt.Fprintf(errout, equipo.RunnerSetupCopy(key)+"\n", a...) return 1 } // The unit and environment file are kept aside until the enrolment // is done; on a new root they do not exist yet, and a failed install // removes what it wrote there. One edited by hand is never replaced. envFile, unit := filepath.Join(*root, "runner.env"), filepath.Join(*root, "equipo-runner.service") if !h.owned(envFile) || !h.owned(unit) { return fail("runner.install.destination") } backup, e := newInstallBackup(*root) if e != nil { return fail("runner.install.destination") } if e = backup.keep(envFile, unit); e != nil { backup.restore() return fail("runner.install.destination") } putBack := func() int { backup.restore() return 1 } abort := func(key string) int { fail(key); return putBack() } result, e := h.install(ctx, runnersetup.InstallOptions{Release: *version, Root: *root, InstanceOrigin: *origin}) if e != nil { for _, key := range result.Missing { fmt.Fprintln(errout, equipo.RunnerSetupCopy(key)) } return putBack() } // Ctrl-C at either prompt ends the install and puts back what was // kept aside, as it does while waiting for the link. lines := newPromptLines(input) label, e := promptMachineLabel(ctx, lines, out, *root, *origin, *instance) if e != nil { return abort("runner.install.unavailable") } fmt.Fprint(out, equipo.RunnerSetupCopy("runner.install.enrol")) confirm, e := lines.read(ctx) if e != nil || strings.TrimSpace(confirm) != "yes" { return abort("runner.install.unavailable") } // Runtime configuration stays explicit. The installer never guesses credential // paths or creates a provider home. Task 17 supplies the local account setup. cfg, e := h.config(*root, *origin, *instance, *version, getenv) if e != nil { return abort("runner.install.config") } if cfg.Origin != *origin || cfg.StateDir != filepath.Join(*root, "state") { return abort("runner.install.config") } // The service starts the installed runner, not this one, and that // runner looks for the scanner beside itself. installed := cfg installed.Executable = result.BinaryPath if result.BinaryPath == "" || h.verify(installed) != nil { return abort("runner.install.release") } cfg.MachineLabel = label report := enrolReport{errout: errout, log: filepath.Join(*root, "install.log")} cfg.EnrolNotify = report.notify // An error after the credential was published (its directory sync) // is still an enrolment: what was kept aside is not put back beside it. before := credentialBefore(cfg.StateDir) if e = h.enrol(ctx, cfg, out); e != nil { enrolled, unknown := enrolOutcome(cfg.StateDir, *origin, *instance, before) switch { case unknown: // Whether it was published cannot be read: nothing is put back // beside what may be a new credential, and what was kept aside // stays where it is. report.failed(e) return 1 case !enrolled: report.failed(e) return putBack() } } // Enrolled: the state now holds the credential this configuration // goes with, so the earlier one is not put back any more. backup.drop() // Use the already configured environment file. Never copy the invoking // process's environment (which may contain credentials) into service metadata. if e = h.checkEnv(*root, cfg.Origin, cfg.StateDir); e != nil { return fail("runner.install.config") } result, e = h.install(ctx, runnersetup.InstallOptions{Release: *version, Root: *root, InstanceOrigin: *origin, EnableService: true}) if e != nil { for _, key := range result.Missing { fmt.Fprintln(errout, equipo.RunnerSetupCopy(key)) } return 1 } fmt.Fprintln(out, equipo.RunnerSetupCopy("runner.install."+result.State)) return 0 } // scannerPin is the gitleaks hash linked into this build; tests replace it. var scannerPin = release.GitleaksSHA256 var errScanner = errors.New("preview_scanner_unverified") // verifyInstalled holds every program this runner starts, at the paths in // its configuration, to the digests of this release: bubblewrap, claude, // codex, its code mode host and the tool proxy built with this runner, // and the preview scanner (gitleaks) beside the runner's executable, where // the runner looks for it, to the hash linked into this build. Without // that scanner every preview fails (preview_scanner). On Linux amd64 the // page renderer beside it, too (verifyRenderer). // The installer runs it before enrolling, and staging and the production // cutover run it (equipo-runner verify-installed) before starting a unit. func verifyInstalled(m release.Manifest, cfg runner.Config) error { if !release.VerifyGitleaks(filepath.Join(filepath.Dir(cfg.Executable), "gitleaks"), scannerPin()) { return errScanner } // The pinned Pi and OpenCode, where this runner has them, are held // to their pins too. if cfg.PiRoot != "" { if err := pi.Verify(cfg.PiRoot); err != nil { return err } } if cfg.OpenCodeRoot != "" { if err := opencode.Verify(cfg.OpenCodeRoot); err != nil { return err } } if err := m.VerifyInstalled(map[string]string{"bwrap": cfg.Bwrap(), "claude": cfg.ClaudePath, "codex": cfg.CodexPath, "codex-code-mode-host": cfg.CodexCodeModeHostPath, "equipo-tool-proxy": cfg.ToolProxy()}); err != nil { return err } // Last, once bubblewrap is the pinned one: on Linux amd64 the page // renderer beside the runner, to its linked pin, and a fixture render. return verifyRenderer(cfg, goos(), goarch()) } func installManifest(args []string, out io.Writer) int { if len(args) != 1 { return 1 } b, e := os.ReadFile(args[0]) if e != nil { return 1 } var m release.InstallManifest if json.Unmarshal(b, &m) != nil || m.Validate(rastrillo.BuildVersion) != nil { return 1 } if json.NewEncoder(out).Encode(m) != nil { return 1 } return 0 } func promptMachineLabel(ctx context.Context, lines *promptLines, out io.Writer, root, origin, instance string) (string, error) { label, e := runner.DefaultMachineLabel(filepath.Join(root, "state"), origin, instance) if e != nil { return "", e } fmt.Fprintf(out, equipo.RunnerSetupCopy("runner.install.label"), label) edited, e := lines.read(ctx) if e != nil { return "", e } if strings.TrimSpace(edited) != "" { label = strings.TrimSpace(edited) } return label, nil }