//go:build linux package containment import ( "amadan.net/oficina/equipo/internal/release" "context" "crypto/sha256" "encoding/json" "fmt" "go/ast" "go/parser" "go/token" "os" "path/filepath" "strconv" "strings" "testing" ) func TestNamespaceExecutableIsRunningRunner(t *testing.T) { m, _ := fixture(t) cfg := m.cfg cfg.RunnerBinary = "/usr/bin/true" if _, err := New(cfg); err == nil { t.Fatal("unrelated executable accepted as namespace helper") } self, err := os.Executable() if err != nil { t.Fatal(err) } cfg.RunnerBinary = self if _, err = New(cfg); err != nil { t.Fatal(err) } } func TestNamespaceHelperProtocol(t *testing.T) { if validReadiness(readiness{PID: 1, Protocol: 0}) { t.Fatal("old helper protocol accepted") } if validReadiness(readiness{PID: 1, Protocol: 999}) { t.Fatal("unknown helper protocol accepted") } } func TestSourceNamespaceVersionTracksImplementation(t *testing.T) { raw, err := os.ReadFile("linux.go") if err != nil { t.Fatal(err) } source := string(raw) start := strings.Index(source, "func NamespaceMain(") end := strings.Index(source[start:], "\nfunc namespaceArgs(") digest := fmt.Sprintf("%x", sha256.Sum256([]byte(source[start:start+end]))) known := map[string]string{"direct-v3": "c7c0bd0688732bb654c3efed8855e9745c85d246b3dcd62a62cec9f4b91162b6"} if known[LauncherVersion] != digest || release.BuildManifest().LauncherVersion != LauncherVersion || HelperProtocol != 3 { t.Fatalf("NamespaceMain or helper protocol changed; bump LauncherVersion and record its implementation: %s", digest) } } // A test binary can run outside the source tree, in a VM with only the // binary, so it skips '^TestSource'. Every function in the package's test // files that opens a relative path literal must therefore be a TestSource // test, or that run would fail on a missing file. func TestSourceTestsAreNamed(t *testing.T) { 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" if got := relativeOpens(t, "planted_test.go", []byte(planted)); strings.Join(got, ",") != "planted_test.go:5 TestC,planted_test.go:6 helper" { t.Fatalf("the check misreads a planted file: %q", got) } names, err := filepath.Glob("*_test.go") if err != nil || len(names) < 2 { t.Fatalf("no test files to check: %v %v", names, err) } var bad []string for _, name := range names { raw, err := os.ReadFile(name) if err != nil { t.Fatal(err) } bad = append(bad, relativeOpens(t, name, raw)...) } if len(bad) > 0 { t.Fatalf("tests outside the TestSource prefix open relative paths: %s", strings.Join(bad, ", ")) } } // relativeOpens lists the functions, other than TestSource tests, that pass // a relative string literal (directly or as the first part of a Join) to a // call that opens or inspects a path. func relativeOpens(t *testing.T, name string, src []byte) []string { t.Helper() fset := token.NewFileSet() file, err := parser.ParseFile(fset, name, src, 0) if err != nil { t.Fatal(err) } pkgs := map[string]string{} for _, imp := range file.Imports { p := strings.Trim(imp.Path.Value, `"`) local := p[strings.LastIndex(p, "/")+1:] if imp.Name != nil { local = imp.Name.Name } pkgs[local] = p } 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} callee := func(e ast.Expr) string { if sel, ok := e.(*ast.SelectorExpr); ok { if id, ok := sel.X.(*ast.Ident); ok { return pkgs[id.Name] + "." + sel.Sel.Name } } return "" } var relative func(ast.Expr) bool relative = func(e ast.Expr) bool { switch v := e.(type) { case *ast.BasicLit: s, err := strconv.Unquote(v.Value) return v.Kind == token.STRING && err == nil && !filepath.IsAbs(s) case *ast.CallExpr: c := callee(v.Fun) return (c == "path/filepath.Join" || c == "path.Join") && len(v.Args) > 0 && relative(v.Args[0]) } return false } var bad []string for _, decl := range file.Decls { fn, ok := decl.(*ast.FuncDecl) if !ok || fn.Body == nil || strings.HasPrefix(fn.Name.Name, "TestSource") { continue } ast.Inspect(fn.Body, func(n ast.Node) bool { if call, ok := n.(*ast.CallExpr); ok && opens[callee(call.Fun)] && len(call.Args) > 0 && relative(call.Args[0]) { bad = append(bad, fmt.Sprintf("%s:%d %s", name, fset.Position(call.Pos()).Line, fn.Name.Name)) } return true }) } return bad } func TestBwrapRunsPinnedDescriptor(t *testing.T) { m, l := fixture(t) path := filepath.Join(t.TempDir(), "bwrap") raw, err := os.ReadFile(m.cfg.Binary) if err != nil { t.Fatal(err) } if err = os.WriteFile(path, raw, 0700); err != nil { t.Fatal(err) } cfg := m.cfg cfg.Binary = path m, err = New(cfg) if err != nil { t.Fatal(err) } p, err := m.StartRecorded(context.Background(), l, []string{"/usr/bin/true"}, func(_ context.Context, r Record) error { if r.HostPID == 0 { replacement := path + ".new" if e := os.WriteFile(replacement, []byte("#!/bin/sh\nexit 99\n"), 0700); e != nil { return e } return os.Rename(replacement, path) } return nil }) if err != nil { t.Fatal("executed replaced bwrap path", err) } defer p.Stdin().Close() defer p.Stdout().Close() defer p.Stderr().Close() if _, err = p.Wait(context.Background()); err != nil { t.Fatal(err) } } func TestNamespaceStartupFailureWaitsForInit(t *testing.T) { m, l := fixture(t) called := false m.waitExit = func(ctx context.Context, fd int) error { called = true if err := waitPID(ctx, fd); err != nil { return err } return errIdentity } var record Record _, err := m.StartRecorded(context.Background(), l, []string{"/usr/bin/true"}, func(_ context.Context, r Record) error { record = r if r.HostPID != 0 { return errStartup } return nil }) if err == nil { t.Fatal("failed admission accepted") } if !called { t.Fatal("PID 1 exit never observed on failed admission") } raw, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, record.ID+".exit.json")) if err != nil { t.Fatal(err) } var proof Proof if err = json.Unmarshal(raw, &proof); err != nil { t.Fatal(err) } if proof.Verified { t.Fatal("failed exit observation fabricated proof") } }