package runnersetup import ( "context" "crypto/sha256" "encoding/json" "fmt" "os" "path/filepath" "strings" "testing" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/release/renderertest" "amadan.net/oficina/equipo/internal/runner/provider" "golang.org/x/sys/unix" ) // installHome is a home directory on a filesystem that keeps user // extended attributes: the installer marks what it wrote with one. A // tmpfs refuses them before Linux 6.6, so where the test's temporary // directory is one, the home goes under the user's own home instead. func installHome(t *testing.T) string { t.Helper() home := t.TempDir() if unix.Setxattr(home, "user.equipo.test", []byte("1"), 0) == nil { return home } base, err := os.UserHomeDir() if err != nil { t.Fatal(err) } if home, err = os.MkdirTemp(base, "equipo-install-test-"); err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(home) }) return home } func installFixture(t *testing.T) (InstallOptions, installHost, *int) { t.Helper() home := installHome(t) binary := []byte("fixture runner bytes") runnerSum, proxySum := fmt.Sprintf("%x", sha256.Sum256(binary)), fmt.Sprintf("%x", sha256.Sum256([]byte("fixture tool proxy"))) // What a release build records: the tool proxy built beside the runner. built := release.BuildManifest() built.Binaries = append(built.Binaries[:4:4], release.BinaryDigest{Name: "equipo-tool-proxy", Version: built.LauncherVersion, SHA256: proxySum}) // And the renderer archive, whose MANIFEST is the pin linked into the runner. archive, rendererPin := renderertest.Archive(renderertest.Small()) asset := assetOf(archive, rendererPin) m := release.InstallManifest{Version: "fixture-16", Target: "linux/amd64", RunnerSHA256: runnerSum, NamespaceArgs: provider.NamespaceArguments(), Release: built, Targets: map[string]release.InstallTarget{release.TargetLinux: {RunnerSHA256: runnerSum, ToolProxySHA256: proxySum, GitleaksSHA256: runnerSum, RendererSHA256: rendererPin, RendererArchiveSHA256: asset.SHA256, RendererArchiveSize: asset.Size}}} raw, err := json.Marshal(m) if err != nil { t.Fatal(err) } calls := new(int) h := installHost{scannerPin: runnerSum, renderer: asset, fetchRenderer: forgeFetch(t, archive, nil), manifest: m.Release, home: home, goos: "linux", goarch: "amd64", fetch: func(_ context.Context, url string, _ int64) ([]byte, error) { if strings.HasSuffix(url, "install-manifest.json") { return raw, nil } if strings.HasSuffix(url, "/"+release.RendererArchive) { t.Errorf("fetched the renderer from the instance: %s", url) } if strings.HasSuffix(url, "equipo-tool-proxy") { return []byte("fixture tool proxy"), nil } return binary, nil }, preflight: func(context.Context, string, release.InstallManifest) []string { return nil }, service: func(context.Context, string) error { *calls++; return nil }, lingering: func(context.Context) (bool, error) { return false, nil }, serviceAvailable: func(context.Context) bool { return true }} return InstallOptions{Release: m.Version, Root: filepath.Join(home, "runner"), InstanceOrigin: "https://equipo.example", EnableService: true}, h, calls } func TestOnboardingInstallVersioned(t *testing.T) { o, h, calls := installFixture(t) got, err := installUser(context.Background(), o, h) if err != nil || got.Version != o.Release || got.State != "stops_at_logout" || *calls != 1 { t.Fatalf("install: %+v %v calls=%d", got, err, *calls) } b, err := os.ReadFile(got.BinaryPath) if err != nil || string(b) != "fixture runner bytes" { t.Fatal("binary not verified", err) } helper, e := os.ReadFile(filepath.Join(filepath.Dir(got.BinaryPath), "equipo-tool-proxy")) if e != nil || string(helper) != "fixture tool proxy" { t.Fatal("missing verified tool proxy", e) } for _, tc := range []string{"checksum", "helper_checksum", "unrecorded", "version", "os", "arch", "root", "origin", "release", "symlink"} { t.Run(tc, func(t *testing.T) { o, h, calls := installFixture(t) old := h.fetch switch tc { case "checksum", "helper_checksum": h.fetch = func(c context.Context, u string, n int64) ([]byte, error) { b, e := old(c, u, n) if (tc == "checksum" && strings.HasSuffix(u, "/equipo-runner")) || (tc == "helper_checksum" && strings.HasSuffix(u, "/equipo-tool-proxy")) { b = []byte("tampered") } return b, e } case "unrecorded", "version": h.fetch = func(c context.Context, u string, n int64) ([]byte, error) { b, e := old(c, u, n) if strings.HasSuffix(u, ".json") { var m release.InstallManifest _ = json.Unmarshal(b, &m) if tc == "unrecorded" { m.Release.Binaries = m.Release.Binaries[:4] } else { m.Version = "other" } b, _ = json.Marshal(m) } return b, e } case "os": h.goos = "darwin" case "arch": h.goarch = "arm64" case "root": o.Root = filepath.Join(t.TempDir(), "outside-home") case "origin": o.InstanceOrigin = "https://example.test/$(touch nope)" case "release": o.Release = "../../escape" case "symlink": target := t.TempDir() if e := os.Symlink(target, o.Root); e != nil { t.Fatal(e) } } r, e := installUser(context.Background(), o, h) if e == nil || r.State != "unavailable" || len(r.Missing) == 0 || *calls != 0 { t.Fatalf("unsafe install: %+v %v service=%d", r, e, *calls) } }) } o, h, _ = installFixture(t) o.Root = filepath.Join(h.home, "literal $(touch nope) ' directory") if _, err = installUser(context.Background(), o, h); err != nil { t.Fatal("literal path rejected", err) } if _, err = os.Stat(filepath.Join(h.home, "nope")); !os.IsNotExist(err) { t.Fatal("shell interpolation") } } func TestOnboardingContainmentPreflight(t *testing.T) { for _, missing := range []string{"runner.install.bwrap", "runner.install.userns", "runner.install.apparmor", "runner.install.pidfd", "runner.install.namespace"} { t.Run(missing, func(t *testing.T) { o, h, calls := installFixture(t) h.preflight = func(context.Context, string, release.InstallManifest) []string { return []string{missing} } r, e := installUser(context.Background(), o, h) if e == nil || r.State != "unavailable" || len(r.Missing) != 1 || r.Missing[0] != missing || *calls != 0 { t.Fatalf("preflight bypass %+v %v", r, e) } }) } o, h, calls := installFixture(t) h.serviceAvailable = func(context.Context) bool { return false } r, e := installUser(context.Background(), o, h) if e == nil || r.State != "unavailable" || *calls != 0 { t.Fatal("missing user service accepted") } } func TestOnboardingServiceLogout(t *testing.T) { o, h, _ := installFixture(t) r, e := installUser(context.Background(), o, h) if e != nil || r.LingeringEnabled || r.State != "stops_at_logout" { t.Fatalf("logout claim %+v %v", r, e) } h.lingering = func(context.Context) (bool, error) { return true, nil } r, e = installUser(context.Background(), o, h) if e != nil || !r.LingeringEnabled || r.State != "installed" { t.Fatalf("linger observation %+v %v", r, e) } } func TestOnboardingInstallResume(t *testing.T) { o, h, calls := installFixture(t) var scratch string h.preflight = func(_ context.Context, path string, _ release.InstallManifest) []string { scratch = filepath.Dir(path) return nil } o.EnableService = false r, e := installUser(context.Background(), o, h) if e != nil { t.Fatal(e) } sentinel := filepath.Join(o.Root, "unrelated") if e = os.WriteFile(sentinel, []byte("keep"), 0600); e != nil { t.Fatal(e) } o.EnableService = true for range 2 { next, e := installUser(context.Background(), o, h) if e != nil || next.BinaryPath != r.BinaryPath { t.Fatal("retry failed", e) } } if *calls != 1 { t.Fatalf("duplicate service: %d", *calls) } if _, e = os.Stat(sentinel); e != nil { t.Fatal("removed unowned file", e) } if _, e = os.Stat(scratch); !os.IsNotExist(e) { t.Fatal("owned scratch leaked", scratch, e) } t.Run("service retry", func(t *testing.T) { o, h, calls := installFixture(t) h.service = func(context.Context, string) error { *calls++ if *calls == 1 { return os.ErrPermission } return nil } if r, e := installUser(context.Background(), o, h); e == nil || r.State != "unavailable" { t.Fatal("service failure claimed success") } for range 2 { if _, e := installUser(context.Background(), o, h); e != nil { t.Fatal("resume after service failure", e) } } if *calls != 2 { t.Fatal("service retried after success", *calls) } }) } func TestOnboardingContainmentPreflightProbe(t *testing.T) { for _, tc := range []string{"success", "missing", "version", "userns", "apparmor", "pidfd", "namespace"} { t.Run(tc, func(t *testing.T) { calls := 0 h := probeHost{read: func(path string) ([]byte, error) { if tc == "userns" && strings.HasSuffix(path, "unprivileged_userns_clone") { return []byte("0"), nil } if tc == "apparmor" && strings.HasSuffix(path, "apparmor_restrict_unprivileged_userns") { return []byte("1"), nil } return nil, os.ErrNotExist }, version: func(context.Context) (string, error) { if tc == "missing" { return "", os.ErrNotExist } if tc == "version" { return "bubblewrap 0.10.0\n", nil } return "bubblewrap 0.11.0\n", nil }, namespace: func(_ context.Context, _ string, args []string) error { calls++ if fmt.Sprint(args) != fmt.Sprint(provider.NamespaceArguments()) { t.Fatal("wrong release namespace policy") } if tc == "pidfd" { return errPIDFD } if tc == "apparmor" || tc == "namespace" { return os.ErrPermission } return nil }} got := probeContainment(context.Background(), "fixture", release.InstallManifest{NamespaceArgs: provider.NamespaceArguments()}, h) want := map[string]string{"missing": "bwrap", "version": "bwrap", "userns": "userns", "apparmor": "apparmor", "pidfd": "pidfd", "namespace": "namespace"}[tc] if tc == "success" { if len(got) != 0 || calls != 1 { t.Fatal("missing namespace/pidfd probe", got, calls) } } else if len(got) != 1 || got[0] != "runner.install."+want { t.Fatalf("diagnostic %v want %s", got, want) } }) } } func TestOnboardingInstallUpgrade(t *testing.T) { o, h, calls := installFixture(t) first, e := installUser(context.Background(), o, h) if e != nil { t.Fatal(e) } if e = SaveServiceEnvironment(o.Root, []byte("version=1")); e != nil { t.Fatal(e) } oldFetch := h.fetch o.Release = "fixture-17" h.fetch = func(ctx context.Context, url string, n int64) ([]byte, error) { b, e := oldFetch(ctx, url, n) if strings.HasSuffix(url, "install-manifest.json") { var m release.InstallManifest if e = json.Unmarshal(b, &m); e != nil { return nil, e } m.Version = o.Release b, e = json.Marshal(m) } return b, e } next, e := installUser(context.Background(), o, h) if e != nil || *calls != 2 || next.BinaryPath == first.BinaryPath { t.Fatalf("upgrade failed: %+v %v calls=%d", next, e, *calls) } if e = SaveServiceEnvironment(o.Root, []byte("version=2")); e != nil { t.Fatal("environment upgrade", e) } b, _ := os.ReadFile(next.ServicePath) if !strings.Contains(string(b), next.BinaryPath) { t.Fatal("old service binary") } for _, name := range []string{"unowned", "equipo-runner.service"} { path := filepath.Join(o.Root, name) if e = os.WriteFile(path, []byte("person's file"), 0600); e != nil { t.Fatal(e) } if e = writeOwned(path, []byte("overwrite"), 0600); e == nil { t.Fatal("overwrote unowned or edited file", name) } } } func TestOnboardingInstallEmbeddedProxy(t *testing.T) { o, h, calls := installFixture(t) h.manifest.Binaries = []release.BinaryDigest{{Name: "equipo-tool-proxy", Version: h.manifest.LauncherVersion, SHA256: strings.Repeat("b", 64)}} got, e := installUser(context.Background(), o, h) if e == nil || got.State != "unavailable" || *calls != 0 { t.Fatalf("embedded helper mismatch accepted: %+v %v", got, e) } } func TestOnboardingServiceUpgrade(t *testing.T) { root := t.TempDir() systemctl := filepath.Join(root, "systemctl") // The fake service manager leaves an already-running unit alone on enable --now. script := "#!/bin/sh\ncase \"$*\" in\n*restart*) cp \"$TMPDIR/unit-version\" \"$TMPDIR/running-version\" ;;\n*enable*--now*) if [ ! -f \"$TMPDIR/running-version\" ]; then cp \"$TMPDIR/unit-version\" \"$TMPDIR/running-version\"; fi ;;\nesac\n" if e := os.WriteFile(systemctl, []byte(script), 0700); e != nil { t.Fatal(e) } t.Setenv("PATH", root+":"+os.Getenv("PATH")) t.Setenv("TMPDIR", root) for _, version := range []string{"v1", "v2"} { if e := os.WriteFile(filepath.Join(root, "unit-version"), []byte(version), 0600); e != nil { t.Fatal(e) } if e := enableService(context.Background(), filepath.Join(root, "equipo-runner.service")); e != nil { t.Fatal(e) } b, e := os.ReadFile(filepath.Join(root, "running-version")) if e != nil || string(b) != version { t.Fatalf("service kept old release: %q want %q: %v", b, version, e) } } } func TestInstallIncludesVerifiedScanner(t *testing.T) { o, h, _ := installFixture(t) r, err := installUser(context.Background(), o, h) if err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(filepath.Dir(r.BinaryPath), "gitleaks")); err != nil { t.Fatal("scanner not bundled", err) } } func TestInstallScannerDigestRefusesTampering(t *testing.T) { o, h, _ := installFixture(t) fetch := h.fetch h.fetch = func(ctx context.Context, url string, limit int64) ([]byte, error) { if strings.HasSuffix(url, "/gitleaks") { return []byte("wrong scanner"), nil } return fetch(ctx, url, limit) } if _, err := installUser(context.Background(), o, h); err == nil { t.Fatal("changed bundled scanner installed") } } // The programs setup runs (systemctl, loginctl, bwrap) are given their // own working directory, never the folder the installer was started // from, which this user may not read. func TestSetupCommandsHaveTheirOwnDirectory(t *testing.T) { if dir := command(context.Background(), "systemctl", "--user", "show-environment").Dir; dir != "/" { t.Fatalf("dir %q", dir) } } // assetOf is the asset linked into a runner for archive: its tree pin, // digest, size and the tag its digest names. func assetOf(archive []byte, pin string) release.RendererAsset { sum := fmt.Sprintf("%x", sha256.Sum256(archive)) return release.RendererAsset{Pin: pin, SHA256: sum, Size: int64(len(archive)), Tag: "renderer-" + sum[:12]} } // forgeFetch is a fetchRenderer that answers with body, as the forge // would, writing it to a new file in scratch; it records each URL asked // for in urls (when not nil). func forgeFetch(t *testing.T, body []byte, urls *[]string) func(context.Context, string, int64, string) (*os.File, error) { return func(_ context.Context, url string, size int64, scratch string) (*os.File, error) { if urls != nil { *urls = append(*urls, url) } f, err := os.CreateTemp(scratch, "renderer-*.tar.gz") if err != nil { return nil, err } if len(body) > int(size)+1 { body = body[:size+1] } if _, err = f.Write(body); err == nil { _, err = f.Seek(0, 0) } return f, err } }