| index 52ebd26e8..f278f89d0 100644 |
| --- a/internal/activator/rootfs_invariants_test.go |
| +++ b/internal/activator/rootfs_invariants_test.go |
| @@ -30,6 +30,7 @@ import ( |
| "go/types" |
| "os" |
| "path/filepath" |
| + "regexp" |
| "slices" |
| "sort" |
| "strings" |
| @@ -46,37 +47,55 @@ import ( |
| |
| // ---- INV-1, structural ------------------------------------------------- |
| |
| -// rootfsBinaryVerbs are the binary unit's verbs a rootfs file never names: |
| -// interface -> its methods. A selection is refused when its method has one |
| -// of these names and either its receiver implements the interface (so an |
| +// rootfsBinaryVerbs are the binary unit's verbs rootfs code never names: |
| +// interface -> its methods. A method selection is refused when its name is |
| +// one of these and either its receiver implements the interface (so an |
| // alias, an embedding or the concrete *instancectl.Client is caught) or |
| // its signature is the verb's (so an anonymous interface holding only the |
| -// verb is caught). A *unitProc's Stop has neither, and passes. |
| +// verb is caught). A func-typed field, variable or parameter with a verb's |
| +// signature is refused too: it can only hold that verb or its double. A |
| +// *unitProc's Stop has neither, and passes. |
| var rootfsBinaryVerbs = map[string][]string{ |
| - "Control": {"Stop", "Cmd", "CmdStatus"}, |
| - "GenControl": {"StopGen"}, |
| + "Control": {"Start", "Seed", "Cmd", "CmdStatus", "Stop", "Reset"}, |
| + "GenControl": {"StartGen", "StartGenExe", "StartSidecarExe", "StopGen"}, |
| "cmdExeStarter": {"CmdExe"}, |
| } |
| |
| -// rootfsRefusedNames are names a rootfs file never refers to, as a call, a |
| -// value or a type: this package's childEnv (the agent's environment) and |
| -// the binary host cgroup's interfaces, and every method named KillHost or |
| -// EmptyHost, whatever its receiver. |
| +// The names rootfs code never refers to, as a call, a value or a type. |
| var ( |
| - rootfsRefusedObjects = []string{"childEnv", "hostKiller", "hostEmptier"} |
| + // rootfsRefusedObjects: this package's childEnv (the agent's |
| + // environment), the binary host cgroup's interfaces and the binary |
| + // unit-name builders (unitNameFor is the runtime-aware one). |
| + rootfsRefusedObjects = []string{"childEnv", "hostKiller", "hostEmptier", "unitName", "runUnitName"} |
| + // rootfsRefusedMethods: every method of these names, whatever its |
| + // receiver. |
| rootfsRefusedMethods = []string{"KillHost", "EmptyHost"} |
| // rootfsRefusedFields: type -> field. ExecBackend's openHostCleanup is |
| // EmptyHost's open of the host cgroup. |
| rootfsRefusedFields = map[string]string{"ExecBackend": "openHostCleanup"} |
| - // rootfsRefusedForeign: import path -> type -> method. The host |
| - // cgroup's open (what a Cgroups field's OpenCleanup reaches). |
| - rootfsRefusedForeign = map[string]map[string]string{ |
| - "github.com/carlosframework/platform/internal/cgroup": {"Manager": "OpenCleanup"}, |
| + // rootfsRefusedForeign: import path -> a package-level object or a |
| + // Type.Method. The host cgroup's opens (what a Cgroups field's |
| + // OpenCleanup and OpenCleanupChild reach) and the binary unit names. |
| + rootfsRefusedForeign = map[string][]string{ |
| + "github.com/carlosframework/platform/internal/cgroup": {"Manager.OpenCleanup", "Manager.OpenCleanupChild"}, |
| + "github.com/carlosframework/platform/internal/instancectl": {"UnitName", "GenUnitName"}, |
| } |
| ) |
| |
| -// isRootfsFile is the files the structural guard reads: every non-test |
| -// rootfs*.go of this package and backend_rootfs.go. |
| +// What the structural guard reads (rootfsScanTargets): every non-test |
| +// rootfs*.go of this package and backend_rootfs.go whole; and in every |
| +// other file each function or method whose name, or whose receiver's type |
| +// name, matches rootfsNamePattern, and each method named like a method of |
| +// one of rootfsSeamInterfaces, on any receiver. The seam interfaces are |
| +// the rootfs backend seams (RootfsControl, and those Plan 3 adds), so |
| +// SplitBackend's forwarding of each (backend_unit.go) is read as soon as |
| +// the seam exists, whatever the forwarder is called. |
| +var ( |
| + rootfsNamePattern = regexp.MustCompile(`(?i)rootfs`) |
| + rootfsSeamInterfaces = []string{"RootfsControl", "rootfsStartable", "rootfsDBPlacer", "ProcessReader", "ReleaseBackend", "RootfsWorkerBackend"} |
| +) |
| + |
| +// isRootfsFile is the files the structural guard reads whole. |
| func isRootfsFile(name string) bool { |
| base := filepath.Base(name) |
| if strings.HasSuffix(base, "_test.go") || !strings.HasSuffix(base, ".go") { |
| @@ -88,13 +107,19 @@ func isRootfsFile(name string) bool { |
| const verbGuardFixtureDir = "testdata/rootfs_verb_guard" |
| |
| // verbGuardFixturePrefix names a fixture inside the loaded package. It does |
| -// not start with "rootfs", so no fixture is read as a real rootfs file. |
| +// not start with "rootfs", and the real scan skips it, so no fixture is |
| +// read as real code. A fixture is judged under its own name: rootfs_*.go is |
| +// read whole, any other only by the function rules. |
| const verbGuardFixturePrefix = "zz_verb_guard_fixture_" |
| |
| +// verbGuardFixtureSeam is the fixture forward.go's seam interface, added to |
| +// rootfsSeamInterfaces for the fixtures only. |
| +const verbGuardFixtureSeam = "verbGuardFixtureSeam" |
| + |
| // loadVerbGuardPackage type-checks this package's non-test files once, |
| // with every fixture of verbGuardFixtureDir laid over it as a file of the |
| -// package (go list's overlay), so a fixture resolves exactly as a real |
| -// rootfs file would. |
| +// package (go list's overlay), so a fixture resolves exactly as real code |
| +// would. |
| var loadVerbGuardPackage = sync.OnceValues(func() (*packages.Package, error) { |
| dir, err := os.Getwd() |
| if err != nil { |
| @@ -130,6 +155,7 @@ var loadVerbGuardPackage = sync.OnceValues(func() (*packages.Package, error) { |
| // verbGuard is the refused objects and verbs, resolved in the loaded |
| // package. |
| type verbGuard struct { |
| + pkg *packages.Package |
| info *types.Info |
| fset *token.FileSet |
| refused map[types.Object]string |
| @@ -144,7 +170,7 @@ type binaryVerb struct { |
| |
| func newVerbGuard(t *testing.T, pkg *packages.Package) *verbGuard { |
| t.Helper() |
| - g := &verbGuard{info: pkg.TypesInfo, fset: pkg.Fset, refused: map[types.Object]string{}} |
| + g := &verbGuard{pkg: pkg, info: pkg.TypesInfo, fset: pkg.Fset, refused: map[types.Object]string{}} |
| scope := pkg.Types.Scope() |
| lookup := func(name string) types.Object { |
| obj := scope.Lookup(name) |
| @@ -163,21 +189,21 @@ func newVerbGuard(t *testing.T, pkg *packages.Package) *verbGuard { |
| } |
| g.refused[obj] = typ + "." + field |
| } |
| - for path, methods := range rootfsRefusedForeign { |
| + for path, names := range rootfsRefusedForeign { |
| imp := pkg.Imports[path] |
| if imp == nil { |
| t.Fatalf("the guard names %s, which this package no longer imports", path) |
| } |
| - for typ, method := range methods { |
| - tn := imp.Types.Scope().Lookup(typ) |
| - if tn == nil { |
| - t.Fatalf("the guard names %s.%s, which no longer exists", path, typ) |
| + for _, name := range names { |
| + typ, method, isMethod := strings.Cut(name, ".") |
| + obj := imp.Types.Scope().Lookup(typ) |
| + if obj != nil && isMethod { |
| + obj, _, _ = types.LookupFieldOrMethod(obj.Type(), true, imp.Types, method) |
| } |
| - obj, _, _ := types.LookupFieldOrMethod(tn.Type(), true, imp.Types, method) |
| if obj == nil { |
| - t.Fatalf("the guard names %s.%s.%s, which no longer exists", path, typ, method) |
| + t.Fatalf("the guard names %s.%s, which no longer exists", path, name) |
| } |
| - g.refused[obj] = imp.Name + "." + typ + "." + method |
| + g.refused[obj] = imp.Name + "." + name |
| } |
| } |
| ifaces := make([]string, 0, len(rootfsBinaryVerbs)) |
| @@ -202,16 +228,102 @@ func newVerbGuard(t *testing.T, pkg *packages.Package) *verbGuard { |
| return g |
| } |
| |
| -// scan judges one file: every selection of a method and every identifier |
| -// it uses, function bodies, closures and package-level values alike. |
| -func (g *verbGuard) scan(f *ast.File) []string { |
| +// scanTarget is one thing the guard reads: a whole file, or one function |
| +// in another file. |
| +type scanTarget struct { |
| + name string // "rootfs.go", or "prepare.go:ExecBackend.writeRootfsLaunchFor" |
| + node ast.Node |
| +} |
| + |
| +// rootfsScanTargets is what the guard reads in the file f, named base, with |
| +// seams the seam interfaces' method names. |
| +func rootfsScanTargets(base string, f *ast.File, seams map[string]bool) []scanTarget { |
| + if isRootfsFile(base) { |
| + return []scanTarget{{name: base, node: f}} |
| + } |
| + var out []scanTarget |
| + for _, decl := range f.Decls { |
| + fd, ok := decl.(*ast.FuncDecl) |
| + if !ok { |
| + continue |
| + } |
| + name, recv := fd.Name.Name, "" |
| + if fd.Recv != nil && len(fd.Recv.List) > 0 { |
| + recv = receiverTypeName(fd.Recv.List[0].Type) |
| + } |
| + if rootfsNamePattern.MatchString(name) || rootfsNamePattern.MatchString(recv) || recv != "" && seams[name] { |
| + if recv != "" { |
| + name = recv + "." + name |
| + } |
| + out = append(out, scanTarget{name: base + ":" + name, node: fd}) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func receiverTypeName(e ast.Expr) string { |
| + switch x := e.(type) { |
| + case *ast.StarExpr: |
| + return receiverTypeName(x.X) |
| + case *ast.IndexExpr: |
| + return receiverTypeName(x.X) |
| + case *ast.IndexListExpr: |
| + return receiverTypeName(x.X) |
| + case *ast.Ident: |
| + return x.Name |
| + } |
| + return "" |
| +} |
| + |
| +// seamMethods is the method names of every seam interface the package |
| +// declares; a seam not declared yet names nothing. |
| +func (g *verbGuard) seamMethods(ifaces []string) map[string]bool { |
| + out := map[string]bool{} |
| + for _, name := range ifaces { |
| + obj := g.pkg.Types.Scope().Lookup(name) |
| + if obj == nil { |
| + continue |
| + } |
| + if iface, ok := obj.Type().Underlying().(*types.Interface); ok { |
| + for i := 0; i < iface.NumMethods(); i++ { |
| + out[iface.Method(i).Name()] = true |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// verbSignature is the binary verb whose signature t has, if any. |
| +func (g *verbGuard) verbSignature(t types.Type) (string, bool) { |
| + sig, ok := t.Underlying().(*types.Signature) |
| + if !ok { |
| + return "", false |
| + } |
| + for _, v := range g.verbs { |
| + if types.Identical(sig, v.method.Type()) { |
| + return v.name, true |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// scan judges one target: every selection of a method or a field and |
| +// every identifier it uses, function bodies, closures and package-level |
| +// values alike. |
| +func (g *verbGuard) scan(node ast.Node) []string { |
| var problems []string |
| at := func(n ast.Node) string { return g.fset.Position(n.Pos()).String() } |
| - ast.Inspect(f, func(n ast.Node) bool { |
| + ast.Inspect(node, func(n ast.Node) bool { |
| switch x := n.(type) { |
| case *ast.SelectorExpr: |
| sel := g.info.Selections[x] |
| - if sel == nil || sel.Kind() == types.FieldVal { |
| + if sel == nil { |
| + return true |
| + } |
| + if sel.Kind() == types.FieldVal { |
| + if verb, ok := g.verbSignature(sel.Type()); ok { |
| + problems = append(problems, at(x)+": a func-typed field with binary verb "+verb+"'s signature in rootfs code") |
| + } |
| return true |
| } |
| fn, ok := sel.Obj().(*types.Func) |
| @@ -220,7 +332,7 @@ func (g *verbGuard) scan(f *ast.File) []string { |
| } |
| for _, v := range g.verbs { |
| if fn.Name() == v.method.Name() && (implements(sel.Recv(), v.iface) || types.Identical(fn.Type(), v.method.Type())) { |
| - problems = append(problems, at(x)+": binary verb "+v.name+" (on "+sel.Recv().String()+") in a rootfs file") |
| + problems = append(problems, at(x)+": binary verb "+v.name+" (on "+sel.Recv().String()+") in rootfs code") |
| } |
| } |
| case *ast.Ident: |
| @@ -229,11 +341,16 @@ func (g *verbGuard) scan(f *ast.File) []string { |
| return true |
| } |
| if name, ok := g.refused[obj]; ok { |
| - problems = append(problems, at(x)+": "+name+" in a rootfs file") |
| + problems = append(problems, at(x)+": "+name+" in rootfs code") |
| } |
| if fn, ok := obj.(*types.Func); ok && slices.Contains(rootfsRefusedMethods, fn.Name()) { |
| if sig, ok := fn.Type().(*types.Signature); ok && sig.Recv() != nil { |
| - problems = append(problems, at(x)+": "+fn.Name()+" (on "+sig.Recv().Type().String()+") in a rootfs file") |
| + problems = append(problems, at(x)+": "+fn.Name()+" (on "+sig.Recv().Type().String()+") in rootfs code") |
| + } |
| + } |
| + if v, ok := obj.(*types.Var); ok && !v.IsField() { |
| + if verb, ok := g.verbSignature(v.Type()); ok { |
| + problems = append(problems, at(x)+": "+v.Name()+", a value with binary verb "+verb+"'s signature, in rootfs code") |
| } |
| } |
| } |
| @@ -253,60 +370,107 @@ func implements(t types.Type, iface *types.Interface) bool { |
| return false |
| } |
| |
| +// verbGuardFixture is what the guard must report on a fixture (substrings |
| +// of its problems), and what it must not: a fixture with neither listed is |
| +// clean. |
| +type verbGuardFixture struct{ want, not []string } |
| + |
| +// verbGuardFixtures: fixture -> its expected result. Rows are only added. |
| +var verbGuardFixtures = map[string]verbGuardFixture{ |
| + "rootfs_clean.go": {}, |
| + "rootfs_direct.go": {want: []string{"binary verb Control.Stop"}}, |
| + "rootfs_methodvalue.go": {want: []string{"binary verb Control.CmdStatus", "binary verb GenControl.StopGen"}}, |
| + "rootfs_alias.go": {want: []string{"binary verb Control.Stop (on github.com/carlosframework/platform/internal/activator.Control)", |
| + "binary verb Control.Cmd (on interface{Cmd"}}, |
| + "rootfs_childenv.go": {want: []string{"childEnv in rootfs code"}}, |
| + "rootfs_killhost.go": {want: []string{"KillHost (on *github.com/carlosframework/platform/internal/activator.SplitBackend)"}}, |
| + "rootfs_others.go": {want: []string{"binary verb cmdExeStarter.CmdExe", "binary verb Control.Stop (on *github.com/carlosframework/platform/internal/instancectl.Client)", |
| + "cgroup.Manager.OpenCleanup in rootfs code", "ExecBackend.openHostCleanup in rootfs code", |
| + "hostEmptier in rootfs code", "hostKiller in rootfs code", "EmptyHost (on github.com/carlosframework/platform/internal/activator.hostEmptier)"}}, |
| + "rootfs_verbs.go": {want: []string{"binary verb Control.Start", "binary verb Control.Seed", "binary verb Control.Reset", |
| + "binary verb GenControl.StartGen ", "binary verb GenControl.StartGenExe", "binary verb GenControl.StartSidecarExe"}}, |
| + "rootfs_unitnames.go": {want: []string{"instancectl.UnitName in rootfs code", "instancectl.GenUnitName in rootfs code", |
| + "unitName in rootfs code", "runUnitName in rootfs code", "cgroup.Manager.OpenCleanupChild in rootfs code"}}, |
| + "rootfs_funcfield.go": {want: []string{"a func-typed field with binary verb Control.Stop's signature", |
| + "stop, a value with binary verb Control.Stop's signature", "start, a value with binary verb GenControl.StartGenExe's signature"}}, |
| + "named.go": {want: []string{"named.go:ExecBackend.verbGuardRestartRootfs: ", "binary verb Control.Stop", "named.go:verbGuardRootfsState.verbGuardRun: ", "binary verb Control.Cmd"}, |
| + not: []string{"binary verb Control.Seed"}}, |
| + "forward.go": {want: []string{"forward.go:SplitBackend.verbGuardForward", "KillHost (on"}, |
| + not: []string{"EmptyHost (on"}}, |
| +} |
| + |
| func TestRootfsFilesNameNoBinaryVerb(t *testing.T) { |
| pkg, err := loadVerbGuardPackage() |
| if err != nil { |
| t.Fatal(err) |
| } |
| g := newVerbGuard(t, pkg) |
| - byName := map[string]*ast.File{} |
| - for _, f := range pkg.Syntax { |
| - byName[filepath.Base(pkg.Fset.Position(f.Package).Filename)] = f |
| - } |
| - var scanned []string |
| - for name, f := range byName { |
| - if !isRootfsFile(name) { |
| - continue |
| - } |
| - scanned = append(scanned, name) |
| - for _, p := range g.scan(f) { |
| - t.Error(p) |
| + scanned := realScanTargets(t, g) |
| + for _, target := range scanned { |
| + for _, p := range g.scan(target.node) { |
| + t.Errorf("%s: %s", target.name, p) |
| } |
| } |
| // rootfs.go is Plan 2's agent start; a guard that reads nothing proves |
| - // nothing. |
| - if !slices.Contains(scanned, "rootfs.go") { |
| - t.Fatalf("the guard read %v, not rootfs.go", scanned) |
| - } |
| - for fixture, want := range map[string][]string{ |
| - "clean.go": nil, |
| - "direct.go": {"binary verb Control.Stop"}, |
| - "methodvalue.go": {"binary verb Control.CmdStatus", "binary verb GenControl.StopGen"}, |
| - "alias.go": {"binary verb Control.Stop (on github.com/carlosframework/platform/internal/activator.Control)", "binary verb Control.Cmd (on interface{Cmd"}, |
| - "childenv.go": {"childEnv in a rootfs file"}, |
| - "killhost.go": {"KillHost (on *github.com/carlosframework/platform/internal/activator.SplitBackend)"}, |
| - "others.go": {"binary verb cmdExeStarter.CmdExe", "binary verb Control.Stop (on *github.com/carlosframework/platform/internal/instancectl.Client)", |
| - "cgroup.Manager.OpenCleanup in a rootfs file", "ExecBackend.openHostCleanup in a rootfs file", |
| - "hostEmptier in a rootfs file", "hostKiller in a rootfs file", "EmptyHost (on github.com/carlosframework/platform/internal/activator.hostEmptier)"}, |
| - } { |
| + // nothing. The floor test holds every target read at Task 1. |
| + if !slices.ContainsFunc(scanned, func(s scanTarget) bool { return s.name == "rootfs.go" }) { |
| + t.Fatalf("the guard did not read rootfs.go") |
| + } |
| + fixtureSeams := g.seamMethods(append(slices.Clone(rootfsSeamInterfaces), verbGuardFixtureSeam)) |
| + files := packageFiles(pkg) |
| + for fixture, want := range verbGuardFixtures { |
| t.Run(fixture, func(t *testing.T) { |
| - f := byName[verbGuardFixturePrefix+fixture] |
| + f := files[verbGuardFixturePrefix+fixture] |
| if f == nil { |
| t.Fatalf("fixture %s was not loaded", fixture) |
| } |
| - got := g.scan(f) |
| - for _, w := range want { |
| + var got []string |
| + for _, target := range rootfsScanTargets(fixture, f, fixtureSeams) { |
| + for _, p := range g.scan(target.node) { |
| + got = append(got, target.name+": "+p) |
| + } |
| + } |
| + for _, w := range want.want { |
| if !slices.ContainsFunc(got, func(p string) bool { return strings.Contains(p, w) }) { |
| t.Errorf("the guard did not report %q; it reported:\n%s", w, strings.Join(got, "\n")) |
| } |
| } |
| - if want == nil && len(got) > 0 { |
| + for _, n := range want.not { |
| + if slices.ContainsFunc(got, func(p string) bool { return strings.Contains(p, n) }) { |
| + t.Errorf("the guard reported %q, which this fixture keeps out of its scope:\n%s", n, strings.Join(got, "\n")) |
| + } |
| + } |
| + if len(want.want) == 0 && len(got) > 0 { |
| t.Errorf("the guard refused a clean source:\n%s", strings.Join(got, "\n")) |
| } |
| }) |
| } |
| } |
| |
| +// packageFiles is the loaded package's files by base name. |
| +func packageFiles(pkg *packages.Package) map[string]*ast.File { |
| + out := map[string]*ast.File{} |
| + for _, f := range pkg.Syntax { |
| + out[filepath.Base(pkg.Fset.Position(f.Package).Filename)] = f |
| + } |
| + return out |
| +} |
| + |
| +// realScanTargets is every target the guard reads in the package's own |
| +// files, fixtures left out, in name order. |
| +func realScanTargets(t *testing.T, g *verbGuard) []scanTarget { |
| + t.Helper() |
| + seams := g.seamMethods(rootfsSeamInterfaces) |
| + var out []scanTarget |
| + for base, f := range packageFiles(g.pkg) { |
| + if !strings.HasPrefix(base, verbGuardFixturePrefix) { |
| + out = append(out, rootfsScanTargets(base, f, seams)...) |
| + } |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].name < out[j].name }) |
| + return out |
| +} |
| + |
| // ---- INV-1, behaviour ---------------------------------------------------- |
| |
| // rootfsProofRig is a production-wired rootfs backend (nestedBackend under |
| @@ -469,36 +633,71 @@ func TestEveryRootfsProofNamesTheRootfsUnit(t *testing.T) { |
| |
| // ---- INV-2 --------------------------------------------------------------- |
| |
| -// The removal guard's allowlists as they stood at Plan 3 Task 1. Plan 3 |
| -// adds no removal owner on root's side; the claims cleanup may take some |
| -// away, so the guard checks each list is a subset of its pin. |
| +// The removal guard (internal/instancectl/rootfs_removal_guard_test.go) as |
| +// it stood at Plan 3 Task 1. Plan 3 adds no removal owner on root's side |
| +// and weakens none of its detection, so: |
| +// - its allowances (removalAllowPins) may shrink, as the claims cleanup |
| +// may shrink them, and never gain an entry; |
| +// - its detectors (removalDetectorPins) may grow and never lose one; |
| +// - its one-look proof is still the function the guard names. |
| +// |
| +// A map entry is its key ("startRootfs"), its key and string value |
| +// ("writeJITDropIn=removeJITDropIn"), or its key and inner key for a map |
| +// of maps ("os.Remove"); a key whose value is false is no entry. |
| var ( |
| - pinnedRootfsRemovalOwners = []string{"startRootfs", "startRootfsCmd", "stopRootfs", "cleanCmdExe", "handleSweep", "sweepGenLeftover"} |
| - pinnedRawRemovalOwners = []string{ |
| - "removeRootfsExe", "removeWorkerFiles", "removeRootfsGenFiles", "removeJITDropIn", |
| - "removeGenFiles", "removeSharedKeyDir", "removeEntry", "removeTree", |
| - "removeCmdExe", "ensureExeAs", "replaceLink", |
| - "writeFileExcl", "BuildProbeImage", "bindControlSocket", |
| - "prepareExecGate", "clearLaunch", |
| + removalAllowPins = map[string][]string{ |
| + "rootfsRemovalOwners": {"startRootfs", "startRootfsCmd", "stopRootfs", "cleanCmdExe", "handleSweep", "sweepGenLeftover"}, |
| + "rootfsProofs": {"removeRootfsUnitFiles", "removeRootfsUnitFilesWith", "removeRootfsUnitFilesOnce"}, |
| + "rootfsRemoverExceptions": {"writeJITDropIn=removeJITDropIn"}, |
| + "preStartCallers": {"startRootfs", "startRootfsCmd"}, |
| + "rawRemovalOwners": { |
| + "removeRootfsExe", "removeWorkerFiles", "removeRootfsGenFiles", "removeJITDropIn", |
| + "removeGenFiles", "removeSharedKeyDir", "removeEntry", "removeTree", |
| + "removeCmdExe", "ensureExeAs", "replaceLink", |
| + "writeFileExcl", "BuildProbeImage", "bindControlSocket", |
| + "prepareExecGate", "clearLaunch", |
| + }, |
| + } |
| + removalDetectorPins = map[string][]string{ |
| + "rootfsRemovers": {"removeRootfsFiles", "removeRootfsExe", "removeWorkerFiles", "removeRootfsGenFiles", "removeJITDropIn"}, |
| + "rawRemovals": {"os.Remove", "os.RemoveAll", "syscall.Unlink", "syscall.Unlinkat", "syscall.Rmdir", |
| + "golang.org/x/sys/unix.Unlink", "golang.org/x/sys/unix.Unlinkat", "golang.org/x/sys/unix.Rmdir", |
| + "github.com/carlosframework/platform/internal/safefile.Remove"}, |
| + "localRawRemovals": {"removeEntry", "removeTree"}, |
| } |
| + // removalConstPins: const -> the value the guard must still hold. |
| + removalConstPins = map[string]string{"onceProof": "removeRootfsUnitFilesOnce"} |
| ) |
| |
| const removalGuardPath = "../instancectl/rootfs_removal_guard_test.go" |
| |
| +// removalGuardFixtures: fixture -> a problem it must report ("" for a |
| +// fixture that must pass). Rows are only added. |
| +var removalGuardFixtures = map[string]string{ |
| + "added.go": `rawRemovalOwners names "x"`, |
| + "owner_added.go": `rootfsRemovalOwners names "x"`, |
| + "proof_added.go": `rootfsProofs names "x"`, |
| + "exception_added.go": `rootfsRemoverExceptions names "removeRootfsGenFiles=removeRootfsFiles"`, |
| + "precaller_added.go": `preStartCallers names "stopRootfs"`, |
| + "remover_dropped.go": `rootfsRemovers lost "removeJITDropIn"`, |
| + "rawremoval_dropped.go": `rawRemovals lost "os.RemoveAll"`, |
| + "rawremoval_false.go": `rawRemovals lost "syscall.Rmdir"`, |
| + "localraw_dropped.go": `localRawRemovals lost "removeTree"`, |
| + "once_changed.go": `onceProof is "removeRootfsUnitFiles"`, |
| + "missing.go": "rootfsRemovalOwners not found", |
| + "shrunk.go": "", |
| +} |
| + |
| func TestRootfsRemovalOwnersUnchanged(t *testing.T) { |
| - for _, p := range removalOwnerProblems(t, removalGuardPath) { |
| + for _, p := range removalGuardProblems(t, removalGuardPath) { |
| t.Error(p) |
| } |
| - for fixture, want := range map[string]string{ |
| - "added.go": `rawRemovalOwners names "x"`, |
| - "shrunk.go": "", |
| - "missing.go": "rootfsRemovalOwners not found", |
| - } { |
| + for fixture, want := range removalGuardFixtures { |
| t.Run(fixture, func(t *testing.T) { |
| - got := removalOwnerProblems(t, filepath.Join("testdata", "rootfs_removal_owners", fixture)) |
| + got := removalGuardProblems(t, filepath.Join("testdata", "rootfs_removal_owners", fixture)) |
| if want == "" { |
| if len(got) > 0 { |
| - t.Errorf("refused a shrunk allowlist:\n%s", strings.Join(got, "\n")) |
| + t.Errorf("refused a guard that only tightened:\n%s", strings.Join(got, "\n")) |
| } |
| return |
| } |
| @@ -509,18 +708,18 @@ func TestRootfsRemovalOwnersUnchanged(t *testing.T) { |
| } |
| } |
| |
| -// removalOwnerProblems parses path and checks the keys of its two |
| -// package-level allowlists against their pins. |
| -func removalOwnerProblems(t *testing.T, path string) []string { |
| +// removalGuardProblems parses path and checks its package-level maps and |
| +// consts against the pins. |
| +func removalGuardProblems(t *testing.T, path string) []string { |
| t.Helper() |
| f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.SkipObjectResolution) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - found := map[string][]string{} |
| + maps, consts := map[string][]string{}, map[string]string{} |
| for _, decl := range f.Decls { |
| gd, ok := decl.(*ast.GenDecl) |
| - if !ok || gd.Tok != token.VAR { |
| + if !ok || gd.Tok != token.VAR && gd.Tok != token.CONST { |
| continue |
| } |
| for _, spec := range gd.Specs { |
| @@ -529,39 +728,82 @@ func removalOwnerProblems(t *testing.T, path string) []string { |
| if i >= len(vs.Values) { |
| continue |
| } |
| - lit, ok := vs.Values[i].(*ast.CompositeLit) |
| - if !ok { |
| - continue |
| - } |
| - keys := []string{} |
| - for _, el := range lit.Elts { |
| - if kv, ok := el.(*ast.KeyValueExpr); ok { |
| - if bl, ok := kv.Key.(*ast.BasicLit); ok && bl.Kind == token.STRING { |
| - keys = append(keys, strings.Trim(bl.Value, `"`)) |
| - } |
| + switch v := vs.Values[i].(type) { |
| + case *ast.CompositeLit: |
| + maps[id.Name] = mapEntries(v) |
| + case *ast.BasicLit: |
| + if v.Kind == token.STRING { |
| + consts[id.Name] = strings.Trim(v.Value, `"`) |
| } |
| } |
| - found[id.Name] = keys |
| } |
| } |
| } |
| var problems []string |
| - for name, pinned := range map[string][]string{"rootfsRemovalOwners": pinnedRootfsRemovalOwners, "rawRemovalOwners": pinnedRawRemovalOwners} { |
| - keys, ok := found[name] |
| + for name, pinned := range removalAllowPins { |
| + entries, ok := maps[name] |
| if !ok { |
| problems = append(problems, path+": "+name+" not found: the guard cannot vouch for an allowlist it cannot read") |
| continue |
| } |
| - for _, k := range keys { |
| - if !slices.Contains(pinned, k) { |
| - problems = append(problems, fmt.Sprintf("%s: %s names %q, which Plan 3 Task 1 did not pin: root gains no removal owner (INV-2)", path, name, k)) |
| + for _, e := range entries { |
| + if !slices.Contains(pinned, e) { |
| + problems = append(problems, fmt.Sprintf("%s: %s names %q, which Plan 3 Task 1 did not pin: root's removal allowances never grow (INV-2)", path, name, e)) |
| } |
| } |
| } |
| + for name, pinned := range removalDetectorPins { |
| + entries, ok := maps[name] |
| + if !ok { |
| + problems = append(problems, path+": "+name+" not found: the guard cannot vouch for a detector it cannot read") |
| + continue |
| + } |
| + for _, e := range pinned { |
| + if !slices.Contains(entries, e) { |
| + problems = append(problems, fmt.Sprintf("%s: %s lost %q: the removal guard's detectors never shrink (INV-2)", path, name, e)) |
| + } |
| + } |
| + } |
| + for name, want := range removalConstPins { |
| + if got, ok := consts[name]; !ok || got != want { |
| + problems = append(problems, fmt.Sprintf("%s: %s is %q, want %q", path, name, got, want)) |
| + } |
| + } |
| sort.Strings(problems) |
| return problems |
| } |
| |
| +// mapEntries is a map literal's entries in removalAllowPins' form. |
| +func mapEntries(lit *ast.CompositeLit) []string { |
| + var out []string |
| + for _, el := range lit.Elts { |
| + kv, ok := el.(*ast.KeyValueExpr) |
| + if !ok { |
| + continue |
| + } |
| + bl, ok := kv.Key.(*ast.BasicLit) |
| + if !ok || bl.Kind != token.STRING { |
| + continue |
| + } |
| + key := strings.Trim(bl.Value, `"`) |
| + switch v := kv.Value.(type) { |
| + case *ast.Ident: |
| + if v.Name == "true" { |
| + out = append(out, key) |
| + } |
| + case *ast.BasicLit: |
| + if v.Kind == token.STRING { |
| + out = append(out, key+"="+strings.Trim(v.Value, `"`)) |
| + } |
| + case *ast.CompositeLit: |
| + for _, inner := range mapEntries(v) { |
| + out = append(out, key+"."+inner) |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| // ---- INV-4 --------------------------------------------------------------- |
| |
| // rootfsRefusals are today's rootfs refusals, each wrapped as the code |
| @@ -623,10 +865,17 @@ var rootfsLaunchRows = map[string]func(t *testing.T) (instancectl.Launch, map[st |
| }, |
| } |
| |
| -// Not parallel: it sets the agent's own PATH and HOME. |
| +// rootfsAgentOnlyEnv is the agent's own environment for the INV-5 test: |
| +// none of it may reach a rootfs launch file, a CARLOS_ name included |
| +// (childEnv drops those, so only a copy of the agent's environment would |
| +// carry it). |
| +var rootfsAgentOnlyEnv = map[string]string{"PATH": "/agent/bin", "HOME": "/agent", "CARLOS_AGENT_ONLY": "box", "AGENT_ONLY": "box"} |
| + |
| +// Not parallel: it sets the agent's own environment. |
| func TestRootfsLaunchFilesCarryOnlyComposedEnv(t *testing.T) { |
| - t.Setenv("PATH", "/agent/bin") |
| - t.Setenv("HOME", "/agent") |
| + for k, v := range rootfsAgentOnlyEnv { |
| + t.Setenv(k, v) |
| + } |
| for process, row := range rootfsLaunchRows { |
| t.Run(process, func(t *testing.T) { |
| l, vars := row(t) |
| @@ -637,7 +886,7 @@ func TestRootfsLaunchFilesCarryOnlyComposedEnv(t *testing.T) { |
| t.Errorf("launch env:\n%s\nwant rootfsLaunchEnv of the composed variables:\n%s", strings.Join(l.Env, "\n"), strings.Join(want, "\n")) |
| } |
| for _, kv := range l.Env { |
| - if strings.HasPrefix(kv, "PATH=") || strings.HasPrefix(kv, "HOME=") { |
| + if k, _, _ := strings.Cut(kv, "="); rootfsAgentOnlyEnv[k] != "" { |
| t.Errorf("the agent's %s reached the launch file", kv) |
| } |
| } |
| @@ -647,23 +896,92 @@ func TestRootfsLaunchFilesCarryOnlyComposedEnv(t *testing.T) { |
| |
| // ---- the tables only grow ---------------------------------------------- |
| |
| -// rootfsInvariantFloor is every row and refused name the guards above had |
| -// at Plan 3 Task 1. A later task adds to the tables and never takes one of |
| -// these away; this floor makes a removal a second, visible edit. |
| -var rootfsInvariantFloor = map[string][]string{ |
| - "rootfsBinaryVerbs": {"Control.Cmd", "Control.CmdStatus", "Control.Stop", "GenControl.StopGen", "cmdExeStarter.CmdExe"}, |
| - "rootfsRefusedObjects": {"childEnv", "hostEmptier", "hostKiller"}, |
| - "rootfsRefusedMethods": {"EmptyHost", "KillHost"}, |
| - "rootfsRefusedFields": {"ExecBackend.openHostCleanup"}, |
| - "rootfsRefusedForeign": {"github.com/carlosframework/platform/internal/cgroup.Manager.OpenCleanup"}, |
| - "rootfsProofHandles": {"rootfs cmdUnit", "web generation unitProc"}, |
| - "rootfsRefusals": {"errBuildStateUnwritten", "errNoRootfsControl", "errRootfsBinaryLaunch", "errRootfsRefused", |
| - "refuseRootfs (a gate's refusal)", "root's 403 (ErrStagedImage)", "root's pre-start refusal (ErrStartRefused, marked)"}, |
| - "rootfsLaunchRows": {"web"}, |
| -} |
| +// What the guards above held at Plan 3 Task 1. A later task adds to the |
| +// tables, scans more code and adds fixtures; it never takes one of these |
| +// away, never changes a fixture's expected result to expect less, and never |
| +// widens a removal allowance. This copy makes any of those a second, |
| +// visible edit. |
| +var ( |
| + rootfsInvariantFloor = map[string][]string{ |
| + "rootfsBinaryVerbs": {"Control.Cmd", "Control.CmdStatus", "Control.Reset", "Control.Seed", "Control.Start", "Control.Stop", |
| + "GenControl.StartGen", "GenControl.StartGenExe", "GenControl.StartSidecarExe", "GenControl.StopGen", "cmdExeStarter.CmdExe"}, |
| + "rootfsRefusedObjects": {"childEnv", "hostEmptier", "hostKiller", "runUnitName", "unitName"}, |
| + "rootfsRefusedMethods": {"EmptyHost", "KillHost"}, |
| + "rootfsRefusedFields": {"ExecBackend.openHostCleanup"}, |
| + "rootfsRefusedForeign": {"github.com/carlosframework/platform/internal/cgroup.Manager.OpenCleanup", |
| + "github.com/carlosframework/platform/internal/cgroup.Manager.OpenCleanupChild", |
| + "github.com/carlosframework/platform/internal/instancectl.GenUnitName", |
| + "github.com/carlosframework/platform/internal/instancectl.UnitName"}, |
| + "rootfsSeamInterfaces": {"ProcessReader", "ReleaseBackend", "RootfsControl", "RootfsWorkerBackend", "rootfsDBPlacer", "rootfsStartable"}, |
| + "rootfsProofHandles": {"rootfs cmdUnit", "web generation unitProc"}, |
| + "rootfsRefusals": {"errBuildStateUnwritten", "errNoRootfsControl", "errRootfsBinaryLaunch", "errRootfsRefused", |
| + "refuseRootfs (a gate's refusal)", "root's 403 (ErrStagedImage)", "root's pre-start refusal (ErrStartRefused, marked)"}, |
| + "rootfsLaunchRows": {"web"}, |
| + "rootfsAgentOnlyEnv": {"AGENT_ONLY", "CARLOS_AGENT_ONLY", "HOME", "PATH"}, |
| + // The structural guard's targets on main at Task 1. |
| + "scanned": {"prepare.go:ExecBackend.writeRootfsLaunchFor", "rootfs.go"}, |
| + } |
| + verbGuardFixturesFloor = map[string]verbGuardFixture{ |
| + "rootfs_clean.go": {}, |
| + "rootfs_direct.go": {want: []string{"binary verb Control.Stop"}}, |
| + "rootfs_methodvalue.go": {want: []string{"binary verb Control.CmdStatus", "binary verb GenControl.StopGen"}}, |
| + "rootfs_alias.go": {want: []string{"binary verb Control.Stop (on github.com/carlosframework/platform/internal/activator.Control)", |
| + "binary verb Control.Cmd (on interface{Cmd"}}, |
| + "rootfs_childenv.go": {want: []string{"childEnv in rootfs code"}}, |
| + "rootfs_killhost.go": {want: []string{"KillHost (on *github.com/carlosframework/platform/internal/activator.SplitBackend)"}}, |
| + "rootfs_others.go": {want: []string{"binary verb cmdExeStarter.CmdExe", "binary verb Control.Stop (on *github.com/carlosframework/platform/internal/instancectl.Client)", |
| + "cgroup.Manager.OpenCleanup in rootfs code", "ExecBackend.openHostCleanup in rootfs code", |
| + "hostEmptier in rootfs code", "hostKiller in rootfs code", "EmptyHost (on github.com/carlosframework/platform/internal/activator.hostEmptier)"}}, |
| + "rootfs_verbs.go": {want: []string{"binary verb Control.Start", "binary verb Control.Seed", "binary verb Control.Reset", |
| + "binary verb GenControl.StartGen ", "binary verb GenControl.StartGenExe", "binary verb GenControl.StartSidecarExe"}}, |
| + "rootfs_unitnames.go": {want: []string{"instancectl.UnitName in rootfs code", "instancectl.GenUnitName in rootfs code", |
| + "unitName in rootfs code", "runUnitName in rootfs code", "cgroup.Manager.OpenCleanupChild in rootfs code"}}, |
| + "rootfs_funcfield.go": {want: []string{"a func-typed field with binary verb Control.Stop's signature", |
| + "stop, a value with binary verb Control.Stop's signature", "start, a value with binary verb GenControl.StartGenExe's signature"}}, |
| + "named.go": {want: []string{"named.go:ExecBackend.verbGuardRestartRootfs: ", "binary verb Control.Stop", "named.go:verbGuardRootfsState.verbGuardRun: ", "binary verb Control.Cmd"}, |
| + not: []string{"binary verb Control.Seed"}}, |
| + "forward.go": {want: []string{"forward.go:SplitBackend.verbGuardForward", "KillHost (on"}, |
| + not: []string{"EmptyHost (on"}}, |
| + } |
| + removalGuardFixturesFloor = map[string]string{ |
| + "added.go": `rawRemovalOwners names "x"`, |
| + "owner_added.go": `rootfsRemovalOwners names "x"`, |
| + "proof_added.go": `rootfsProofs names "x"`, |
| + "exception_added.go": `rootfsRemoverExceptions names "removeRootfsGenFiles=removeRootfsFiles"`, |
| + "precaller_added.go": `preStartCallers names "stopRootfs"`, |
| + "remover_dropped.go": `rootfsRemovers lost "removeJITDropIn"`, |
| + "rawremoval_dropped.go": `rawRemovals lost "os.RemoveAll"`, |
| + "rawremoval_false.go": `rawRemovals lost "syscall.Rmdir"`, |
| + "localraw_dropped.go": `localRawRemovals lost "removeTree"`, |
| + "once_changed.go": `onceProof is "removeRootfsUnitFiles"`, |
| + "missing.go": "rootfsRemovalOwners not found", |
| + "shrunk.go": "", |
| + } |
| + // The removal pins at Task 1: the allowances are a ceiling (a pin may |
| + // lose entries, never gain one), the detectors a floor. |
| + removalAllowCeiling = map[string][]string{ |
| + "rootfsRemovalOwners": {"startRootfs", "startRootfsCmd", "stopRootfs", "cleanCmdExe", "handleSweep", "sweepGenLeftover"}, |
| + "rootfsProofs": {"removeRootfsUnitFiles", "removeRootfsUnitFilesWith", "removeRootfsUnitFilesOnce"}, |
| + "rootfsRemoverExceptions": {"writeJITDropIn=removeJITDropIn"}, |
| + "preStartCallers": {"startRootfs", "startRootfsCmd"}, |
| + "rawRemovalOwners": { |
| + "removeRootfsExe", "removeWorkerFiles", "removeRootfsGenFiles", "removeJITDropIn", |
| + "removeGenFiles", "removeSharedKeyDir", "removeEntry", "removeTree", |
| + "removeCmdExe", "ensureExeAs", "replaceLink", |
| + "writeFileExcl", "BuildProbeImage", "bindControlSocket", |
| + "prepareExecGate", "clearLaunch", |
| + }, |
| + } |
| + removalDetectorFloor = map[string][]string{ |
| + "rootfsRemovers": {"removeRootfsFiles", "removeRootfsExe", "removeWorkerFiles", "removeRootfsGenFiles", "removeJITDropIn"}, |
| + "rawRemovals": {"os.Remove", "os.RemoveAll", "syscall.Unlink", "syscall.Unlinkat", "syscall.Rmdir", |
| + "golang.org/x/sys/unix.Unlink", "golang.org/x/sys/unix.Unlinkat", "golang.org/x/sys/unix.Rmdir", |
| + "github.com/carlosframework/platform/internal/safefile.Remove"}, |
| + "localRawRemovals": {"removeEntry", "removeTree"}, |
| + } |
| +) |
| |
| func TestRootfsInvariantTablesOnlyGrow(t *testing.T) { |
| - t.Parallel() |
| have := map[string][]string{} |
| for iface, methods := range rootfsBinaryVerbs { |
| for _, m := range methods { |
| @@ -675,11 +993,12 @@ func TestRootfsInvariantTablesOnlyGrow(t *testing.T) { |
| for typ, field := range rootfsRefusedFields { |
| have["rootfsRefusedFields"] = append(have["rootfsRefusedFields"], typ+"."+field) |
| } |
| - for path, methods := range rootfsRefusedForeign { |
| - for typ, m := range methods { |
| - have["rootfsRefusedForeign"] = append(have["rootfsRefusedForeign"], path+"."+typ+"."+m) |
| + for path, names := range rootfsRefusedForeign { |
| + for _, n := range names { |
| + have["rootfsRefusedForeign"] = append(have["rootfsRefusedForeign"], path+"."+n) |
| } |
| } |
| + have["rootfsSeamInterfaces"] = rootfsSeamInterfaces |
| for name := range rootfsProofHandles { |
| have["rootfsProofHandles"] = append(have["rootfsProofHandles"], name) |
| } |
| @@ -689,6 +1008,16 @@ func TestRootfsInvariantTablesOnlyGrow(t *testing.T) { |
| for name := range rootfsLaunchRows { |
| have["rootfsLaunchRows"] = append(have["rootfsLaunchRows"], name) |
| } |
| + for name := range rootfsAgentOnlyEnv { |
| + have["rootfsAgentOnlyEnv"] = append(have["rootfsAgentOnlyEnv"], name) |
| + } |
| + pkg, err := loadVerbGuardPackage() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, target := range realScanTargets(t, newVerbGuard(t, pkg)) { |
| + have["scanned"] = append(have["scanned"], target.name) |
| + } |
| for table, floor := range rootfsInvariantFloor { |
| for _, row := range floor { |
| if !slices.Contains(have[table], row) { |
| @@ -696,4 +1025,48 @@ func TestRootfsInvariantTablesOnlyGrow(t *testing.T) { |
| } |
| } |
| } |
| + for fixture, floor := range verbGuardFixturesFloor { |
| + now, ok := verbGuardFixtures[fixture] |
| + switch { |
| + case !ok: |
| + t.Errorf("verb guard fixture %s is gone", fixture) |
| + case len(floor.want) == 0 && len(now.want) > 0: |
| + t.Errorf("verb guard fixture %s was clean and now expects refusals: add a new fixture instead", fixture) |
| + } |
| + for _, w := range floor.want { |
| + if !slices.Contains(now.want, w) { |
| + t.Errorf("verb guard fixture %s no longer expects %q", fixture, w) |
| + } |
| + } |
| + for _, n := range floor.not { |
| + if !slices.Contains(now.not, n) { |
| + t.Errorf("verb guard fixture %s no longer keeps %q out of scope", fixture, n) |
| + } |
| + } |
| + } |
| + for fixture, want := range removalGuardFixturesFloor { |
| + if now, ok := removalGuardFixtures[fixture]; !ok || now != want { |
| + t.Errorf("removal guard fixture %s expects %q, at Task 1 %q", fixture, now, want) |
| + } |
| + } |
| + for name, ceiling := range removalAllowCeiling { |
| + for _, e := range removalAllowPins[name] { |
| + if !slices.Contains(ceiling, e) { |
| + t.Errorf("removalAllowPins[%s] gained %q: root's removal allowances never grow", name, e) |
| + } |
| + } |
| + } |
| + if len(removalAllowPins) < len(removalAllowCeiling) { |
| + t.Errorf("removalAllowPins checks %d maps, Task 1 checked %d", len(removalAllowPins), len(removalAllowCeiling)) |
| + } |
| + for name, floor := range removalDetectorFloor { |
| + for _, e := range floor { |
| + if !slices.Contains(removalDetectorPins[name], e) { |
| + t.Errorf("removalDetectorPins[%s] lost %q: the removal guard's detectors never shrink", name, e) |
| + } |
| + } |
| + } |
| + if removalConstPins["onceProof"] != "removeRootfsUnitFilesOnce" { |
| + t.Errorf("removalConstPins no longer pins onceProof") |
| + } |
| } |