oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package runnersetup
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/json"
7 "fmt"
8 "os"
9 "path/filepath"
10 "strings"
11 "testing"
12
13 "amadan.net/oficina/equipo/internal/release"
14 "amadan.net/oficina/equipo/internal/release/renderertest"
15 "amadan.net/oficina/equipo/internal/runner/provider"
16 "golang.org/x/sys/unix"
17)
18
19// installHome is a home directory on a filesystem that keeps user
20// extended attributes: the installer marks what it wrote with one. A
21// tmpfs refuses them before Linux 6.6, so where the test's temporary
22// directory is one, the home goes under the user's own home instead.
23func installHome(t *testing.T) string {
24 t.Helper()
25 home := t.TempDir()
26 if unix.Setxattr(home, "user.equipo.test", []byte("1"), 0) == nil {
27 return home
28 }
29 base, err := os.UserHomeDir()
30 if err != nil {
31 t.Fatal(err)
32 }
33 if home, err = os.MkdirTemp(base, "equipo-install-test-"); err != nil {
34 t.Fatal(err)
35 }
36 t.Cleanup(func() { os.RemoveAll(home) })
37 return home
38}
39
40func installFixture(t *testing.T) (InstallOptions, installHost, *int) {
41 t.Helper()
42 home := installHome(t)
43 binary := []byte("fixture runner bytes")
44 runnerSum, proxySum := fmt.Sprintf("%x", sha256.Sum256(binary)), fmt.Sprintf("%x", sha256.Sum256([]byte("fixture tool proxy")))
45 // What a release build records: the tool proxy built beside the runner.
46 built := release.BuildManifest()
47 built.Binaries = append(built.Binaries[:4:4], release.BinaryDigest{Name: "equipo-tool-proxy", Version: built.LauncherVersion, SHA256: proxySum})
48 // And the renderer archive, whose MANIFEST is the pin linked into the runner.
49 archive, rendererPin := renderertest.Archive(renderertest.Small())
50 asset := assetOf(archive, rendererPin)
51 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}}}
52 raw, err := json.Marshal(m)
53 if err != nil {
54 t.Fatal(err)
55 }
56 calls := new(int)
57 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) {
58 if strings.HasSuffix(url, "install-manifest.json") {
59 return raw, nil
60 }
61 if strings.HasSuffix(url, "/"+release.RendererArchive) {
62 t.Errorf("fetched the renderer from the instance: %s", url)
63 }
64 if strings.HasSuffix(url, "equipo-tool-proxy") {
65 return []byte("fixture tool proxy"), nil
66 }
67 return binary, nil
68 }, 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 }}
69 return InstallOptions{Release: m.Version, Root: filepath.Join(home, "runner"), InstanceOrigin: "https://equipo.example", EnableService: true}, h, calls
70}
71func TestOnboardingInstallVersioned(t *testing.T) {
72 o, h, calls := installFixture(t)
73 got, err := installUser(context.Background(), o, h)
74 if err != nil || got.Version != o.Release || got.State != "stops_at_logout" || *calls != 1 {
75 t.Fatalf("install: %+v %v calls=%d", got, err, *calls)
76 }
77 b, err := os.ReadFile(got.BinaryPath)
78 if err != nil || string(b) != "fixture runner bytes" {
79 t.Fatal("binary not verified", err)
80 }
81 helper, e := os.ReadFile(filepath.Join(filepath.Dir(got.BinaryPath), "equipo-tool-proxy"))
82 if e != nil || string(helper) != "fixture tool proxy" {
83 t.Fatal("missing verified tool proxy", e)
84 }
85 for _, tc := range []string{"checksum", "helper_checksum", "unrecorded", "version", "os", "arch", "root", "origin", "release", "symlink"} {
86 t.Run(tc, func(t *testing.T) {
87 o, h, calls := installFixture(t)
88 old := h.fetch
89 switch tc {
90 case "checksum", "helper_checksum":
91 h.fetch = func(c context.Context, u string, n int64) ([]byte, error) {
92 b, e := old(c, u, n)
93 if (tc == "checksum" && strings.HasSuffix(u, "/equipo-runner")) || (tc == "helper_checksum" && strings.HasSuffix(u, "/equipo-tool-proxy")) {
94 b = []byte("tampered")
95 }
96 return b, e
97 }
98 case "unrecorded", "version":
99 h.fetch = func(c context.Context, u string, n int64) ([]byte, error) {
100 b, e := old(c, u, n)
101 if strings.HasSuffix(u, ".json") {
102 var m release.InstallManifest
103 _ = json.Unmarshal(b, &m)
104 if tc == "unrecorded" {
105 m.Release.Binaries = m.Release.Binaries[:4]
106 } else {
107 m.Version = "other"
108 }
109 b, _ = json.Marshal(m)
110 }
111 return b, e
112 }
113 case "os":
114 h.goos = "darwin"
115 case "arch":
116 h.goarch = "arm64"
117 case "root":
118 o.Root = filepath.Join(t.TempDir(), "outside-home")
119 case "origin":
120 o.InstanceOrigin = "https://example.test/$(touch nope)"
121 case "release":
122 o.Release = "../../escape"
123 case "symlink":
124 target := t.TempDir()
125 if e := os.Symlink(target, o.Root); e != nil {
126 t.Fatal(e)
127 }
128 }
129 r, e := installUser(context.Background(), o, h)
130 if e == nil || r.State != "unavailable" || len(r.Missing) == 0 || *calls != 0 {
131 t.Fatalf("unsafe install: %+v %v service=%d", r, e, *calls)
132 }
133 })
134 }
135 o, h, _ = installFixture(t)
136 o.Root = filepath.Join(h.home, "literal $(touch nope) ' directory")
137 if _, err = installUser(context.Background(), o, h); err != nil {
138 t.Fatal("literal path rejected", err)
139 }
140 if _, err = os.Stat(filepath.Join(h.home, "nope")); !os.IsNotExist(err) {
141 t.Fatal("shell interpolation")
142 }
143}
144func TestOnboardingContainmentPreflight(t *testing.T) {
145 for _, missing := range []string{"runner.install.bwrap", "runner.install.userns", "runner.install.apparmor", "runner.install.pidfd", "runner.install.namespace"} {
146 t.Run(missing, func(t *testing.T) {
147 o, h, calls := installFixture(t)
148 h.preflight = func(context.Context, string, release.InstallManifest) []string { return []string{missing} }
149 r, e := installUser(context.Background(), o, h)
150 if e == nil || r.State != "unavailable" || len(r.Missing) != 1 || r.Missing[0] != missing || *calls != 0 {
151 t.Fatalf("preflight bypass %+v %v", r, e)
152 }
153 })
154 }
155 o, h, calls := installFixture(t)
156 h.serviceAvailable = func(context.Context) bool { return false }
157 r, e := installUser(context.Background(), o, h)
158 if e == nil || r.State != "unavailable" || *calls != 0 {
159 t.Fatal("missing user service accepted")
160 }
161}
162func TestOnboardingServiceLogout(t *testing.T) {
163 o, h, _ := installFixture(t)
164 r, e := installUser(context.Background(), o, h)
165 if e != nil || r.LingeringEnabled || r.State != "stops_at_logout" {
166 t.Fatalf("logout claim %+v %v", r, e)
167 }
168 h.lingering = func(context.Context) (bool, error) { return true, nil }
169 r, e = installUser(context.Background(), o, h)
170 if e != nil || !r.LingeringEnabled || r.State != "installed" {
171 t.Fatalf("linger observation %+v %v", r, e)
172 }
173}
174func TestOnboardingInstallResume(t *testing.T) {
175 o, h, calls := installFixture(t)
176 var scratch string
177 h.preflight = func(_ context.Context, path string, _ release.InstallManifest) []string {
178 scratch = filepath.Dir(path)
179 return nil
180 }
181 o.EnableService = false
182 r, e := installUser(context.Background(), o, h)
183 if e != nil {
184 t.Fatal(e)
185 }
186 sentinel := filepath.Join(o.Root, "unrelated")
187 if e = os.WriteFile(sentinel, []byte("keep"), 0600); e != nil {
188 t.Fatal(e)
189 }
190 o.EnableService = true
191 for range 2 {
192 next, e := installUser(context.Background(), o, h)
193 if e != nil || next.BinaryPath != r.BinaryPath {
194 t.Fatal("retry failed", e)
195 }
196 }
197 if *calls != 1 {
198 t.Fatalf("duplicate service: %d", *calls)
199 }
200 if _, e = os.Stat(sentinel); e != nil {
201 t.Fatal("removed unowned file", e)
202 }
203 if _, e = os.Stat(scratch); !os.IsNotExist(e) {
204 t.Fatal("owned scratch leaked", scratch, e)
205 }
206 t.Run("service retry", func(t *testing.T) {
207 o, h, calls := installFixture(t)
208 h.service = func(context.Context, string) error {
209 *calls++
210 if *calls == 1 {
211 return os.ErrPermission
212 }
213 return nil
214 }
215 if r, e := installUser(context.Background(), o, h); e == nil || r.State != "unavailable" {
216 t.Fatal("service failure claimed success")
217 }
218 for range 2 {
219 if _, e := installUser(context.Background(), o, h); e != nil {
220 t.Fatal("resume after service failure", e)
221 }
222 }
223 if *calls != 2 {
224 t.Fatal("service retried after success", *calls)
225 }
226 })
227}
228func TestOnboardingContainmentPreflightProbe(t *testing.T) {
229 for _, tc := range []string{"success", "missing", "version", "userns", "apparmor", "pidfd", "namespace"} {
230 t.Run(tc, func(t *testing.T) {
231 calls := 0
232 h := probeHost{read: func(path string) ([]byte, error) {
233 if tc == "userns" && strings.HasSuffix(path, "unprivileged_userns_clone") {
234 return []byte("0"), nil
235 }
236 if tc == "apparmor" && strings.HasSuffix(path, "apparmor_restrict_unprivileged_userns") {
237 return []byte("1"), nil
238 }
239 return nil, os.ErrNotExist
240 }, version: func(context.Context) (string, error) {
241 if tc == "missing" {
242 return "", os.ErrNotExist
243 }
244 if tc == "version" {
245 return "bubblewrap 0.10.0\n", nil
246 }
247 return "bubblewrap 0.11.0\n", nil
248 }, namespace: func(_ context.Context, _ string, args []string) error {
249 calls++
250 if fmt.Sprint(args) != fmt.Sprint(provider.NamespaceArguments()) {
251 t.Fatal("wrong release namespace policy")
252 }
253 if tc == "pidfd" {
254 return errPIDFD
255 }
256 if tc == "apparmor" || tc == "namespace" {
257 return os.ErrPermission
258 }
259 return nil
260 }}
261 got := probeContainment(context.Background(), "fixture", release.InstallManifest{NamespaceArgs: provider.NamespaceArguments()}, h)
262 want := map[string]string{"missing": "bwrap", "version": "bwrap", "userns": "userns", "apparmor": "apparmor", "pidfd": "pidfd", "namespace": "namespace"}[tc]
263 if tc == "success" {
264 if len(got) != 0 || calls != 1 {
265 t.Fatal("missing namespace/pidfd probe", got, calls)
266 }
267 } else if len(got) != 1 || got[0] != "runner.install."+want {
268 t.Fatalf("diagnostic %v want %s", got, want)
269 }
270 })
271 }
272}
273
274func TestOnboardingInstallUpgrade(t *testing.T) {
275 o, h, calls := installFixture(t)
276 first, e := installUser(context.Background(), o, h)
277 if e != nil {
278 t.Fatal(e)
279 }
280 if e = SaveServiceEnvironment(o.Root, []byte("version=1")); e != nil {
281 t.Fatal(e)
282 }
283 oldFetch := h.fetch
284 o.Release = "fixture-17"
285 h.fetch = func(ctx context.Context, url string, n int64) ([]byte, error) {
286 b, e := oldFetch(ctx, url, n)
287 if strings.HasSuffix(url, "install-manifest.json") {
288 var m release.InstallManifest
289 if e = json.Unmarshal(b, &m); e != nil {
290 return nil, e
291 }
292 m.Version = o.Release
293 b, e = json.Marshal(m)
294 }
295 return b, e
296 }
297 next, e := installUser(context.Background(), o, h)
298 if e != nil || *calls != 2 || next.BinaryPath == first.BinaryPath {
299 t.Fatalf("upgrade failed: %+v %v calls=%d", next, e, *calls)
300 }
301 if e = SaveServiceEnvironment(o.Root, []byte("version=2")); e != nil {
302 t.Fatal("environment upgrade", e)
303 }
304 b, _ := os.ReadFile(next.ServicePath)
305 if !strings.Contains(string(b), next.BinaryPath) {
306 t.Fatal("old service binary")
307 }
308 for _, name := range []string{"unowned", "equipo-runner.service"} {
309 path := filepath.Join(o.Root, name)
310 if e = os.WriteFile(path, []byte("person's file"), 0600); e != nil {
311 t.Fatal(e)
312 }
313 if e = writeOwned(path, []byte("overwrite"), 0600); e == nil {
314 t.Fatal("overwrote unowned or edited file", name)
315 }
316 }
317}
318
319func TestOnboardingInstallEmbeddedProxy(t *testing.T) {
320 o, h, calls := installFixture(t)
321 h.manifest.Binaries = []release.BinaryDigest{{Name: "equipo-tool-proxy", Version: h.manifest.LauncherVersion, SHA256: strings.Repeat("b", 64)}}
322 got, e := installUser(context.Background(), o, h)
323 if e == nil || got.State != "unavailable" || *calls != 0 {
324 t.Fatalf("embedded helper mismatch accepted: %+v %v", got, e)
325 }
326}
327
328func TestOnboardingServiceUpgrade(t *testing.T) {
329 root := t.TempDir()
330 systemctl := filepath.Join(root, "systemctl")
331 // The fake service manager leaves an already-running unit alone on enable --now.
332 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"
333 if e := os.WriteFile(systemctl, []byte(script), 0700); e != nil {
334 t.Fatal(e)
335 }
336 t.Setenv("PATH", root+":"+os.Getenv("PATH"))
337 t.Setenv("TMPDIR", root)
338 for _, version := range []string{"v1", "v2"} {
339 if e := os.WriteFile(filepath.Join(root, "unit-version"), []byte(version), 0600); e != nil {
340 t.Fatal(e)
341 }
342 if e := enableService(context.Background(), filepath.Join(root, "equipo-runner.service")); e != nil {
343 t.Fatal(e)
344 }
345 b, e := os.ReadFile(filepath.Join(root, "running-version"))
346 if e != nil || string(b) != version {
347 t.Fatalf("service kept old release: %q want %q: %v", b, version, e)
348 }
349 }
350}
351
352func TestInstallIncludesVerifiedScanner(t *testing.T) {
353 o, h, _ := installFixture(t)
354 r, err := installUser(context.Background(), o, h)
355 if err != nil {
356 t.Fatal(err)
357 }
358 if _, err := os.Stat(filepath.Join(filepath.Dir(r.BinaryPath), "gitleaks")); err != nil {
359 t.Fatal("scanner not bundled", err)
360 }
361}
362
363func TestInstallScannerDigestRefusesTampering(t *testing.T) {
364 o, h, _ := installFixture(t)
365 fetch := h.fetch
366 h.fetch = func(ctx context.Context, url string, limit int64) ([]byte, error) {
367 if strings.HasSuffix(url, "/gitleaks") {
368 return []byte("wrong scanner"), nil
369 }
370 return fetch(ctx, url, limit)
371 }
372 if _, err := installUser(context.Background(), o, h); err == nil {
373 t.Fatal("changed bundled scanner installed")
374 }
375}
376
377// The programs setup runs (systemctl, loginctl, bwrap) are given their
378// own working directory, never the folder the installer was started
379// from, which this user may not read.
380func TestSetupCommandsHaveTheirOwnDirectory(t *testing.T) {
381 if dir := command(context.Background(), "systemctl", "--user", "show-environment").Dir; dir != "/" {
382 t.Fatalf("dir %q", dir)
383 }
384}
385
386// assetOf is the asset linked into a runner for archive: its tree pin,
387// digest, size and the tag its digest names.
388func assetOf(archive []byte, pin string) release.RendererAsset {
389 sum := fmt.Sprintf("%x", sha256.Sum256(archive))
390 return release.RendererAsset{Pin: pin, SHA256: sum, Size: int64(len(archive)), Tag: "renderer-" + sum[:12]}
391}
392
393// forgeFetch is a fetchRenderer that answers with body, as the forge
394// would, writing it to a new file in scratch; it records each URL asked
395// for in urls (when not nil).
396func forgeFetch(t *testing.T, body []byte, urls *[]string) func(context.Context, string, int64, string) (*os.File, error) {
397 return func(_ context.Context, url string, size int64, scratch string) (*os.File, error) {
398 if urls != nil {
399 *urls = append(*urls, url)
400 }
401 f, err := os.CreateTemp(scratch, "renderer-*.tar.gz")
402 if err != nil {
403 return nil, err
404 }
405 if len(body) > int(size)+1 {
406 body = body[:size+1]
407 }
408 if _, err = f.Write(body); err == nil {
409 _, err = f.Seek(0, 0)
410 }
411 return f, err
412 }
413}
414