oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package checks_test
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "runtime"
11 "strconv"
12 "strings"
13 "testing"
14
15 "amadan.net/oficina/equipo/internal/runner"
16 "amadan.net/oficina/equipo/internal/runner/checks"
17 "amadan.net/oficina/equipo/internal/runner/containment"
18 "amadan.net/oficina/equipo/internal/testci"
19
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/runner/workspace"
22)
23
24type checkHost struct {
25 provider.ProcessHost
26 launches []provider.Launch
27 args [][]string
28}
29
30func (h *checkHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
31 h.launches = append(h.launches, l)
32 h.args = append(h.args, argv)
33 return h.ProcessHost.Start(ctx, l, argv)
34}
35
36func namespaceCheck(t *testing.T, configure ...func(*checks.SandboxConfig)) (*checks.CodexSandbox, string, string, provider.ReadPolicy, *checkHost) {
37 t.Helper()
38 root := t.TempDir()
39 if err := os.Chmod(root, 0700); err != nil {
40 t.Fatal(err)
41 }
42 scratch, work, mods := filepath.Join(root, "ns"), filepath.Join(root, "work"), filepath.Join(root, "modules")
43 for _, p := range []string{scratch, work, mods} {
44 if err := os.Mkdir(p, 0700); err != nil {
45 t.Fatal(err)
46 }
47 }
48 testci.Tools(t, "codex", "bwrap", "python3", "sh")
49 binary, err := exec.LookPath("codex")
50 if err != nil {
51 t.Fatal(err)
52 }
53 goCommand := exec.Command("go", "env", "GOROOT")
54 goCommand.Env = append(os.Environ(), "GOROOT=", "GOTOOLCHAIN="+checks.GoVersion)
55 goOutput, err := goCommand.Output()
56 if err != nil {
57 t.Fatalf("resolve check toolchain: %v", err)
58 }
59 goRoot := strings.TrimSpace(string(goOutput))
60 helper, err := os.Executable()
61 if err != nil {
62 t.Fatal(err)
63 }
64 m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch})
65 if err != nil {
66 t.Fatal(err)
67 }
68 j, err := runner.OpenJournal(context.Background(), filepath.Join(root, "journal.db"))
69 if err != nil {
70 t.Fatal(err)
71 }
72 t.Cleanup(func() { j.Close() })
73 if _, err = j.ReconcileDirect(context.Background(), m); err != nil {
74 t.Fatal(err)
75 }
76 p := filepath.Join(root, "private")
77 protected := workspace.SecurityPaths{RunnerState: p, RunnerConfig: p, Journal: p, Bearer: p, Cleanup: p, ForgeCredential: p, LegacyHome: p, SSH: p, ProviderHomes: []string{p}}
78 host := &checkHost{ProcessHost: runner.NewDirectHost(j, m)}
79 cfg := checks.SandboxConfig{Binary: binary, ScratchRoot: scratch, GoBinary: filepath.Join(goRoot, "bin/go"), GoRoot: goRoot, Protected: protected, Host: host, RunnerBinary: helper, Bwrap: "/usr/bin/bwrap", ModuleCache: mods}
80 for _, apply := range configure {
81 apply(&cfg)
82 }
83 s, err := checks.NewCodexSandbox(context.Background(), cfg)
84 if err != nil {
85 t.Fatal(err)
86 }
87 return s, work, scratch, provider.ReadPolicy{ConfigHash: "checks", DeniedPaths: []string{p}}, host
88}
89
90func TestCheckNamespaceContainment(t *testing.T) {
91 s, work, scratch, policy, _ := namespaceCheck(t)
92 var out, stderr bytes.Buffer
93 code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", `import os,time
94if os.fork()==0:
95 os.setsid()
96 time.sleep(1)
97 open('/workspace/escaped','w').write('bad')
98 os._exit(0)
99print('parent done',flush=True)`}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
100 if err != nil || code != 0 {
101 t.Fatalf("check: %d %v %s", code, err, &stderr)
102 }
103 if !strings.Contains(out.String(), "parent done") {
104 t.Fatal("command did not run")
105 }
106 if _, err := os.Stat(filepath.Join(work, "escaped")); !os.IsNotExist(err) {
107 t.Fatal("detached child escaped")
108 }
109 files, err := os.ReadDir(scratch)
110 if err != nil {
111 t.Fatal(err)
112 }
113 for _, f := range files {
114 if f.IsDir() && strings.HasPrefix(f.Name(), "attempt-") {
115 t.Fatal("attempt scratch survived containment")
116 }
117 }
118}
119
120func TestCheckCacheIsolation(t *testing.T) {
121 s, work, scratch, policy, tracker := namespaceCheck(t)
122 home, err := os.UserHomeDir()
123 if err != nil {
124 t.Fatal(err)
125 }
126 for i := 0; i < 2; i++ {
127 var out, stderr bytes.Buffer
128 code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", `import os
129assert not os.path.exists(os.environ['GOCACHE']+'/prior')
130open(os.environ['GOCACHE']+'/prior','w').write('owned')
131try:
132 open(os.environ['GOMODCACHE']+'/poison','w').write('bad')
133except OSError: pass
134else: raise Exception('module cache writable')
135assert not os.path.exists('` + filepath.Join(home, ".cache/go-build") + `')
136assert os.environ['GOCACHE'].startswith('/tmp/')
137assert os.environ['GOTMPDIR'].startswith('/tmp/')
138print('isolated')`}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
139 if err != nil || code != 0 || !strings.Contains(out.String(), "isolated") {
140 t.Fatalf("cache check %d: %d %v %s %s", i, code, err, &out, &stderr)
141 }
142 }
143 if len(tracker.launches) != 2 || tracker.launches[0].AttemptKey == tracker.launches[1].AttemptKey {
144 t.Fatal("checks shared a namespace identity")
145 }
146 for i, launch := range tracker.launches {
147 args := strings.Join(tracker.args[i], " ")
148 if !strings.Contains(args, `"/opt/go-mod"="read"`) {
149 t.Fatal("module-cache inner write protection missing")
150 }
151 if !strings.Contains(args, `"`+filepath.Join(home, ".cache/go-build")+`"="deny"`) {
152 t.Fatal("host build cache exclusion missing")
153 }
154 for _, mount := range launch.Policy.Mounts {
155 if mount.Source == filepath.Join(home, ".cache/go-build") {
156 t.Fatal("host build cache mounted")
157 }
158 if mount.Target == "/opt/go-mod" && (!mount.ReadOnly || mount.Source != filepath.Join(filepath.Dir(work), "modules")) {
159 t.Fatal("module cache mount changed")
160 }
161 }
162 }
163 files, err := os.ReadDir(scratch)
164 if err != nil {
165 t.Fatal(err)
166 }
167 for _, f := range files {
168 if f.IsDir() && strings.HasPrefix(f.Name(), "attempt-") {
169 t.Fatal("check cache left behind")
170 }
171 }
172}
173
174func TestCheckNamespaceDeniedMountAliases(t *testing.T) {
175 s, work, _, policy, _ := namespaceCheck(t)
176 secret := filepath.Join(filepath.Dir(work), "modules", "private")
177 if err := os.WriteFile(secret, []byte("denied-sentinel"), 0600); err != nil {
178 t.Fatal(err)
179 }
180 policy.DeniedPaths = append(policy.DeniedPaths, secret)
181 var out, stderr bytes.Buffer
182 code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/cat", "/opt/go-mod/private"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
183 if err != nil {
184 t.Fatal(err)
185 }
186 if code == 0 || strings.Contains(out.String(), "denied-sentinel") {
187 t.Fatal("module mount alias bypassed denied path")
188 }
189}
190
191func TestCheckCacheRejectsBroadHome(t *testing.T) {
192 home, err := os.UserHomeDir()
193 if err != nil {
194 t.Fatal(err)
195 }
196 for _, root := range []string{home, "/home", "/", "/tmp"} {
197 _, err = provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: t.TempDir(), Binary: "/usr/bin/true", RunnerBinary: "/usr/bin/true", Bwrap: "/usr/bin/bwrap", GoRoot: t.TempDir(), ModuleCache: root, Argv: []string{"/opt/codex"}})
198 if err == nil {
199 t.Fatalf("broad home accepted as module cache: %s", root)
200 }
201 }
202}
203
204func TestCheckCacheRejectsNamespaceScratch(t *testing.T) {
205 s, work, _, policy, _ := namespaceCheck(t, func(cfg *checks.SandboxConfig) { cfg.ModuleCache = cfg.ScratchRoot })
206 var out, stderr bytes.Buffer
207 if _, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/true"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr); err == nil {
208 t.Fatal("namespace scratch accepted as module cache")
209 }
210}
211
212func TestCheckNamespaceGoRootInsideModuleCache(t *testing.T) {
213 var goRoot string
214 s, work, _, policy, tracker := namespaceCheck(t, func(cfg *checks.SandboxConfig) {
215 goRoot = filepath.Join(cfg.ModuleCache, "golang.org/toolchain@v0.0.1-"+checks.GoVersion+"."+runtime.GOOS+"-"+runtime.GOARCH)
216 if err := os.CopyFS(goRoot, os.DirFS(cfg.GoRoot)); err != nil {
217 t.Fatal(err)
218 }
219 cfg.GoRoot, cfg.GoBinary = goRoot, filepath.Join(goRoot, "bin/go")
220 })
221 home, err := os.UserHomeDir()
222 if err != nil {
223 t.Fatal(err)
224 }
225 script := `import os,subprocess
226assert not os.path.exists(` + strconv.Quote(filepath.Join(home, ".cache/go-build")) + `)
227assert os.environ['GOTOOLCHAIN']=='local'
228assert os.environ['MAKEFLAGS']=='GOTOOLCHAIN=local'
229for path in ['/opt/go/VERSION', '/opt/go-mod/` + filepath.ToSlash(filepath.Join("golang.org", filepath.Base(goRoot))) + `/VERSION']:
230 assert os.path.isfile(path), path
231 try:
232 fd=os.open(path,os.O_WRONLY)
233 except OSError: pass
234 else:
235 os.close(fd)
236 raise Exception('runtime alias writable: '+path)
237assert os.statvfs('/opt/go-mod').f_flag & os.ST_RDONLY
238subprocess.run(['/opt/go/bin/go','test','./...'],check=True)
239print('nested runtime isolated')`
240 for name, data := range map[string]string{"go.mod": "module nestedfixture\n\ngo 1.26.0\n", "nested_test.go": "package nestedfixture\nimport \"testing\"\nfunc TestNested(t *testing.T) {}\n"} {
241 if err := os.WriteFile(filepath.Join(work, name), []byte(data), 0600); err != nil {
242 t.Fatal(err)
243 }
244 }
245 var out, stderr bytes.Buffer
246 code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", script}, Dir: ".", TimeoutSeconds: 120}, work, policy, &out, &stderr)
247 if err != nil || code != 0 || !strings.Contains(out.String(), "nested runtime isolated") {
248 t.Fatalf("nested runtime: code=%d error=%v stdout=%s stderr=%s", code, err, &out, &stderr)
249 }
250 for _, mount := range tracker.launches[0].Policy.Mounts {
251 if !mount.ReadOnly || mount.Source == filepath.Join(home, ".cache/go-build") {
252 t.Fatalf("unsafe mount: %+v", mount)
253 }
254 }
255 policy.DeniedPaths = append(policy.DeniedPaths, filepath.Join(goRoot, "VERSION"))
256 for _, alias := range []string{"/opt/go/VERSION", "/opt/go-mod/" + filepath.ToSlash(filepath.Join("golang.org", filepath.Base(goRoot))) + "/VERSION"} {
257 out.Reset()
258 stderr.Reset()
259 code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/cat", alias}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
260 if err != nil || code == 0 || out.Len() != 0 {
261 t.Fatalf("denied runtime alias %q: code=%d error=%v stdout=%s stderr=%s", alias, code, err, &out, &stderr)
262 }
263 }
264}
265
266func TestCheckCacheRejectsSymlinkPathDiagnostic(t *testing.T) {
267 root := t.TempDir()
268 real := filepath.Join(root, "real")
269 alias := filepath.Join(root, "alias")
270 if err := os.Mkdir(real, 0700); err != nil {
271 t.Fatal(err)
272 }
273 if err := os.Symlink(real, alias); err != nil {
274 t.Fatal(err)
275 }
276 _, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: root, GoRoot: real, ModuleCache: alias, Binary: "/usr/bin/true", RunnerBinary: "/usr/bin/true", Bwrap: "/usr/bin/bwrap"})
277 if !errors.Is(err, provider.ErrPolicy) || !strings.Contains(err.Error(), alias) {
278 t.Fatalf("refused module cache must retain policy class and identify path %q: %v", alias, err)
279 }
280}
281
282func TestCheckNamespaceHostTmp(t *testing.T) {
283 root, err := os.MkdirTemp("/tmp", "equipo-check-")
284 if err != nil {
285 t.Fatal(err)
286 }
287 t.Cleanup(func() { os.RemoveAll(root) })
288 t.Setenv("TMPDIR", root)
289 s, work, _, policy, _ := namespaceCheck(t)
290 policy.DeniedPaths = append(policy.DeniedPaths, filepath.Join(policy.DeniedPaths[0], "config"))
291 var out, stderr bytes.Buffer
292 code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", "import os; assert not os.path.exists(" + strconv.Quote(root) + "); print('check ran')"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
293 if err != nil || code != 0 || !strings.Contains(out.String(), "check ran") {
294 t.Fatalf("host /tmp check: code=%d err=%v stdout=%s stderr=%s", code, err, &out, &stderr)
295 }
296}
297
298func TestCheckNamespaceDeniedHostAliases(t *testing.T) {
299 for _, kind := range []string{"ancestor", "symlink"} {
300 t.Run(kind, func(t *testing.T) {
301 var mods string
302 s, work, _, policy, _ := namespaceCheck(t, func(cfg *checks.SandboxConfig) {
303 cfg.ModuleCache = filepath.Join(cfg.ModuleCache, "nested")
304 if err := os.Mkdir(cfg.ModuleCache, 0700); err != nil {
305 t.Fatal(err)
306 }
307 mods = cfg.ModuleCache
308 })
309 if err := os.WriteFile(filepath.Join(mods, "secret"), []byte("denied-sentinel"), 0600); err != nil {
310 t.Fatal(err)
311 }
312 denied := filepath.Dir(mods)
313 if kind == "symlink" {
314 denied = filepath.Join(filepath.Dir(work), "alias")
315 if err := os.Symlink(filepath.Join(mods, "secret"), denied); err != nil {
316 t.Fatal(err)
317 }
318 }
319 policy.DeniedPaths = append(policy.DeniedPaths, denied)
320 var out, stderr bytes.Buffer
321 code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/cat", "/opt/go-mod/secret"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
322 if err != nil {
323 t.Fatal(err)
324 }
325 if code == 0 || strings.Contains(out.String(), "denied-sentinel") {
326 t.Fatalf("%s deny bypassed: %s", kind, &out)
327 }
328 })
329 }
330}
331