oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package containment
4
5import (
6 "amadan.net/oficina/equipo/internal/release"
7 "context"
8 "crypto/sha256"
9 "encoding/json"
10 "fmt"
11 "go/ast"
12 "go/parser"
13 "go/token"
14 "os"
15 "path/filepath"
16 "strconv"
17 "strings"
18 "testing"
19)
20
21func TestNamespaceExecutableIsRunningRunner(t *testing.T) {
22 m, _ := fixture(t)
23 cfg := m.cfg
24 cfg.RunnerBinary = "/usr/bin/true"
25 if _, err := New(cfg); err == nil {
26 t.Fatal("unrelated executable accepted as namespace helper")
27 }
28 self, err := os.Executable()
29 if err != nil {
30 t.Fatal(err)
31 }
32 cfg.RunnerBinary = self
33 if _, err = New(cfg); err != nil {
34 t.Fatal(err)
35 }
36}
37func TestNamespaceHelperProtocol(t *testing.T) {
38 if validReadiness(readiness{PID: 1, Protocol: 0}) {
39 t.Fatal("old helper protocol accepted")
40 }
41 if validReadiness(readiness{PID: 1, Protocol: 999}) {
42 t.Fatal("unknown helper protocol accepted")
43 }
44}
45
46func TestSourceNamespaceVersionTracksImplementation(t *testing.T) {
47 raw, err := os.ReadFile("linux.go")
48 if err != nil {
49 t.Fatal(err)
50 }
51 source := string(raw)
52 start := strings.Index(source, "func NamespaceMain(")
53 end := strings.Index(source[start:], "\nfunc namespaceArgs(")
54 digest := fmt.Sprintf("%x", sha256.Sum256([]byte(source[start:start+end])))
55 known := map[string]string{"direct-v3": "c7c0bd0688732bb654c3efed8855e9745c85d246b3dcd62a62cec9f4b91162b6"}
56 if known[LauncherVersion] != digest || release.BuildManifest().LauncherVersion != LauncherVersion || HelperProtocol != 3 {
57 t.Fatalf("NamespaceMain or helper protocol changed; bump LauncherVersion and record its implementation: %s", digest)
58 }
59}
60
61// A test binary can run outside the source tree, in a VM with only the
62// binary, so it skips '^TestSource'. Every function in the package's test
63// files that opens a relative path literal must therefore be a TestSource
64// test, or that run would fail on a missing file.
65func TestSourceTestsAreNamed(t *testing.T) {
66 planted := "package p\nimport (\"os\"; fp \"path/filepath\")\nfunc TestA() { os.ReadFile(\"/abs\"); os.ReadFile(dir) }\nfunc TestSourceB() { os.ReadFile(\"x.go\") }\nfunc TestC() { os.Stat(fp.Join(\"..\", \"x.json\")) }\nfunc helper() { os.Open(\"y\") }\n"
67 if got := relativeOpens(t, "planted_test.go", []byte(planted)); strings.Join(got, ",") != "planted_test.go:5 TestC,planted_test.go:6 helper" {
68 t.Fatalf("the check misreads a planted file: %q", got)
69 }
70 names, err := filepath.Glob("*_test.go")
71 if err != nil || len(names) < 2 {
72 t.Fatalf("no test files to check: %v %v", names, err)
73 }
74 var bad []string
75 for _, name := range names {
76 raw, err := os.ReadFile(name)
77 if err != nil {
78 t.Fatal(err)
79 }
80 bad = append(bad, relativeOpens(t, name, raw)...)
81 }
82 if len(bad) > 0 {
83 t.Fatalf("tests outside the TestSource prefix open relative paths: %s", strings.Join(bad, ", "))
84 }
85}
86
87// relativeOpens lists the functions, other than TestSource tests, that pass
88// a relative string literal (directly or as the first part of a Join) to a
89// call that opens or inspects a path.
90func relativeOpens(t *testing.T, name string, src []byte) []string {
91 t.Helper()
92 fset := token.NewFileSet()
93 file, err := parser.ParseFile(fset, name, src, 0)
94 if err != nil {
95 t.Fatal(err)
96 }
97 pkgs := map[string]string{}
98 for _, imp := range file.Imports {
99 p := strings.Trim(imp.Path.Value, `"`)
100 local := p[strings.LastIndex(p, "/")+1:]
101 if imp.Name != nil {
102 local = imp.Name.Name
103 }
104 pkgs[local] = p
105 }
106 opens := map[string]bool{"os.ReadFile": true, "os.Open": true, "os.OpenFile": true, "os.Stat": true, "os.Lstat": true, "os.ReadDir": true, "os.DirFS": true, "path/filepath.Glob": true}
107 callee := func(e ast.Expr) string {
108 if sel, ok := e.(*ast.SelectorExpr); ok {
109 if id, ok := sel.X.(*ast.Ident); ok {
110 return pkgs[id.Name] + "." + sel.Sel.Name
111 }
112 }
113 return ""
114 }
115 var relative func(ast.Expr) bool
116 relative = func(e ast.Expr) bool {
117 switch v := e.(type) {
118 case *ast.BasicLit:
119 s, err := strconv.Unquote(v.Value)
120 return v.Kind == token.STRING && err == nil && !filepath.IsAbs(s)
121 case *ast.CallExpr:
122 c := callee(v.Fun)
123 return (c == "path/filepath.Join" || c == "path.Join") && len(v.Args) > 0 && relative(v.Args[0])
124 }
125 return false
126 }
127 var bad []string
128 for _, decl := range file.Decls {
129 fn, ok := decl.(*ast.FuncDecl)
130 if !ok || fn.Body == nil || strings.HasPrefix(fn.Name.Name, "TestSource") {
131 continue
132 }
133 ast.Inspect(fn.Body, func(n ast.Node) bool {
134 if call, ok := n.(*ast.CallExpr); ok && opens[callee(call.Fun)] && len(call.Args) > 0 && relative(call.Args[0]) {
135 bad = append(bad, fmt.Sprintf("%s:%d %s", name, fset.Position(call.Pos()).Line, fn.Name.Name))
136 }
137 return true
138 })
139 }
140 return bad
141}
142
143func TestBwrapRunsPinnedDescriptor(t *testing.T) {
144 m, l := fixture(t)
145 path := filepath.Join(t.TempDir(), "bwrap")
146 raw, err := os.ReadFile(m.cfg.Binary)
147 if err != nil {
148 t.Fatal(err)
149 }
150 if err = os.WriteFile(path, raw, 0700); err != nil {
151 t.Fatal(err)
152 }
153 cfg := m.cfg
154 cfg.Binary = path
155 m, err = New(cfg)
156 if err != nil {
157 t.Fatal(err)
158 }
159 p, err := m.StartRecorded(context.Background(), l, []string{"/usr/bin/true"}, func(_ context.Context, r Record) error {
160 if r.HostPID == 0 {
161 replacement := path + ".new"
162 if e := os.WriteFile(replacement, []byte("#!/bin/sh\nexit 99\n"), 0700); e != nil {
163 return e
164 }
165 return os.Rename(replacement, path)
166 }
167 return nil
168 })
169 if err != nil {
170 t.Fatal("executed replaced bwrap path", err)
171 }
172 defer p.Stdin().Close()
173 defer p.Stdout().Close()
174 defer p.Stderr().Close()
175 if _, err = p.Wait(context.Background()); err != nil {
176 t.Fatal(err)
177 }
178}
179
180func TestNamespaceStartupFailureWaitsForInit(t *testing.T) {
181 m, l := fixture(t)
182 called := false
183 m.waitExit = func(ctx context.Context, fd int) error {
184 called = true
185 if err := waitPID(ctx, fd); err != nil {
186 return err
187 }
188 return errIdentity
189 }
190 var record Record
191 _, err := m.StartRecorded(context.Background(), l, []string{"/usr/bin/true"}, func(_ context.Context, r Record) error {
192 record = r
193 if r.HostPID != 0 {
194 return errStartup
195 }
196 return nil
197 })
198 if err == nil {
199 t.Fatal("failed admission accepted")
200 }
201 if !called {
202 t.Fatal("PID 1 exit never observed on failed admission")
203 }
204 raw, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, record.ID+".exit.json"))
205 if err != nil {
206 t.Fatal(err)
207 }
208 var proof Proof
209 if err = json.Unmarshal(raw, &proof); err != nil {
210 t.Fatal(err)
211 }
212 if proof.Verified {
213 t.Fatal("failed exit observation fabricated proof")
214 }
215}
216