carlos / platform Public

rootfs apps plan 3: Task 1 review fixes, wider and grow-only invariant guards

- INV-1: refuse also Control.Start, Seed and Reset, GenControl.StartGen,
  StartGenExe and StartSidecarExe, the binary unit-name builders
  (instancectl.UnitName, GenUnitName, unitName, runUnitName) and
  cgroup.Manager.OpenCleanupChild; refuse a func-typed field, variable
  or parameter with a binary verb's signature; read, besides the rootfs
  files, every function whose name or receiver type matches rootfs in
  any file (prepare.go's writeRootfsLaunchFor on main) and every method
  named like a method of a rootfs seam interface, so SplitBackend's
  forwarders in backend_unit.go are read. New fixtures for each.
- INV-2: every allowance map of the removal guard may only shrink, every
  detector map may only grow, and onceProof is pinned; a fixture per
  rejection.
- The floor now holds the scanned targets, every fixture with its
  expected result, and the removal pins.
- Inventory: whole camel-case word matching (releaseOp no longer matches
  releaseOptions; WorkerReportedVersion leaves the baseline), local func
  literals and local types are declarations, and the unused shared-seam
  allowance is gone.
- INV-5: agent-only variables, CARLOS_AGENT_ONLY included, must not reach
  the launch file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 40c7e25ae144c13b4205e8a176211baabf20637b parent 057ee3a
27 files changed, +831 −178
  • internal/activator/rootfs_invariants_test.go +502 −129
  • internal/activator/testdata/rootfs_removal_owners/added.go +1 −2
  • internal/activator/testdata/rootfs_removal_owners/exception_added.go +7 −0
  • internal/activator/testdata/rootfs_removal_owners/localraw_dropped.go +4 −0
  • internal/activator/testdata/rootfs_removal_owners/missing.go +3 −11
  • internal/activator/testdata/rootfs_removal_owners/once_changed.go +4 −0
  • internal/activator/testdata/rootfs_removal_owners/owner_added.go +4 −0
  • internal/activator/testdata/rootfs_removal_owners/precaller_added.go +4 −0
  • internal/activator/testdata/rootfs_removal_owners/proof_added.go +4 −0
  • internal/activator/testdata/rootfs_removal_owners/rawremoval_dropped.go +9 −0
  • internal/activator/testdata/rootfs_removal_owners/rawremoval_false.go +9 −0
  • internal/activator/testdata/rootfs_removal_owners/remover_dropped.go +7 −0
  • internal/activator/testdata/rootfs_removal_owners/shrunk.go +23 −3
  • internal/activator/testdata/rootfs_verb_guard/forward.go +26 −0
  • internal/activator/testdata/rootfs_verb_guard/named.go +29 −0
  • internal/activator/testdata/rootfs_verb_guard/{alias.go => rootfs_alias.go} +0 −0
  • internal/activator/testdata/rootfs_verb_guard/{childenv.go => rootfs_childenv.go} +0 −0
  • internal/activator/testdata/rootfs_verb_guard/{clean.go => rootfs_clean.go} +0 −0
  • internal/activator/testdata/rootfs_verb_guard/{direct.go => rootfs_direct.go} +0 −0
  • internal/activator/testdata/rootfs_verb_guard/rootfs_funcfield.go +27 −0
  • internal/activator/testdata/rootfs_verb_guard/{killhost.go => rootfs_killhost.go} +0 −0
  • internal/activator/testdata/rootfs_verb_guard/{methodvalue.go => rootfs_methodvalue.go} +0 −0
  • internal/activator/testdata/rootfs_verb_guard/{others.go => rootfs_others.go} +0 −0
  • internal/activator/testdata/rootfs_verb_guard/rootfs_unitnames.go +20 −0
  • internal/activator/testdata/rootfs_verb_guard/rootfs_verbs.go +36 −0
  • plan3_groups_test.go +95 −26
  • testdata/plan3_inventory/added.go +17 −7

CI passed — run details

diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go
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")
+ }
}
diff --git a/internal/activator/testdata/rootfs_removal_owners/added.go b/internal/activator/testdata/rootfs_removal_owners/added.go
index 64fe0c816..81e03aab3 100644
--- a/internal/activator/testdata/rootfs_removal_owners/added.go
+++ b/internal/activator/testdata/rootfs_removal_owners/added.go
@@ -1,5 +1,4 @@
-// The removal guard's two allowlists as instancectl pins them, with one
-// raw removal owner added: TestRootfsRemovalOwnersUnchanged refuses "x".
+// The removal guard's raw removal owners with one added: refused ("x").
package instancectl
var (
diff --git a/internal/activator/testdata/rootfs_removal_owners/exception_added.go b/internal/activator/testdata/rootfs_removal_owners/exception_added.go
new file mode 100644
index 000000000..44e155429
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/exception_added.go
@@ -0,0 +1,7 @@
+// A remover exception added: refused.
+package instancectl
+
+var rootfsRemoverExceptions = map[string]string{
+ "writeJITDropIn": "removeJITDropIn",
+ "removeRootfsGenFiles": "removeRootfsFiles",
+}
diff --git a/internal/activator/testdata/rootfs_removal_owners/localraw_dropped.go b/internal/activator/testdata/rootfs_removal_owners/localraw_dropped.go
new file mode 100644
index 000000000..c04a220b0
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/localraw_dropped.go
@@ -0,0 +1,4 @@
+// A local raw removal no longer detected: refused.
+package instancectl
+
+var localRawRemovals = map[string]bool{"removeEntry": true}
diff --git a/internal/activator/testdata/rootfs_removal_owners/missing.go b/internal/activator/testdata/rootfs_removal_owners/missing.go
index 46ae406c8..83ce523ee 100644
--- a/internal/activator/testdata/rootfs_removal_owners/missing.go
+++ b/internal/activator/testdata/rootfs_removal_owners/missing.go
@@ -1,13 +1,5 @@
-// rootfsRemovalOwners renamed away: TestRootfsRemovalOwnersUnchanged
-// refuses a file in which it cannot find a pinned allowlist, rather than
-// passing over nothing.
+// rootfsRemovalOwners renamed away: refused, since the guard cannot vouch
+// for an allowlist it cannot read.
package instancectl
-var (
- removalOwners = map[string]bool{
- "startRootfs": true,
- }
- rawRemovalOwners = map[string]bool{
- "removeRootfsExe": true,
- }
-)
+var removalOwners = map[string]bool{"startRootfs": true}
diff --git a/internal/activator/testdata/rootfs_removal_owners/once_changed.go b/internal/activator/testdata/rootfs_removal_owners/once_changed.go
new file mode 100644
index 000000000..812d6d812
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/once_changed.go
@@ -0,0 +1,4 @@
+// The one-look proof renamed in the guard: refused.
+package instancectl
+
+const onceProof = "removeRootfsUnitFiles"
diff --git a/internal/activator/testdata/rootfs_removal_owners/owner_added.go b/internal/activator/testdata/rootfs_removal_owners/owner_added.go
new file mode 100644
index 000000000..1689b8943
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/owner_added.go
@@ -0,0 +1,4 @@
+// A removal owner added: refused.
+package instancectl
+
+var rootfsRemovalOwners = map[string]bool{"startRootfs": true, "x": true}
diff --git a/internal/activator/testdata/rootfs_removal_owners/precaller_added.go b/internal/activator/testdata/rootfs_removal_owners/precaller_added.go
new file mode 100644
index 000000000..6941affca
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/precaller_added.go
@@ -0,0 +1,4 @@
+// A pre-start caller of the one-look proof added: refused.
+package instancectl
+
+var preStartCallers = map[string]bool{"startRootfs": true, "startRootfsCmd": true, "stopRootfs": true}
diff --git a/internal/activator/testdata/rootfs_removal_owners/proof_added.go b/internal/activator/testdata/rootfs_removal_owners/proof_added.go
new file mode 100644
index 000000000..0b1c64f1d
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/proof_added.go
@@ -0,0 +1,4 @@
+// A proof function added: refused.
+package instancectl
+
+var rootfsProofs = map[string]bool{"removeRootfsUnitFiles": true, "x": true}
diff --git a/internal/activator/testdata/rootfs_removal_owners/rawremoval_dropped.go b/internal/activator/testdata/rootfs_removal_owners/rawremoval_dropped.go
new file mode 100644
index 000000000..1d5d6cef7
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/rawremoval_dropped.go
@@ -0,0 +1,9 @@
+// A raw removal no longer detected: refused.
+package instancectl
+
+var rawRemovals = map[string]map[string]bool{
+ "os": {"Remove": true},
+ "syscall": {"Unlink": true, "Unlinkat": true, "Rmdir": true},
+ "golang.org/x/sys/unix": {"Unlink": true, "Unlinkat": true, "Rmdir": true},
+ "github.com/carlosframework/platform/internal/safefile": {"Remove": true},
+}
diff --git a/internal/activator/testdata/rootfs_removal_owners/rawremoval_false.go b/internal/activator/testdata/rootfs_removal_owners/rawremoval_false.go
new file mode 100644
index 000000000..a7254d5d1
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/rawremoval_false.go
@@ -0,0 +1,9 @@
+// A raw removal switched off by a false value: refused as lost.
+package instancectl
+
+var rawRemovals = map[string]map[string]bool{
+ "os": {"Remove": true, "RemoveAll": true},
+ "syscall": {"Unlink": true, "Unlinkat": true, "Rmdir": false},
+ "golang.org/x/sys/unix": {"Unlink": true, "Unlinkat": true, "Rmdir": true},
+ "github.com/carlosframework/platform/internal/safefile": {"Remove": true},
+}
diff --git a/internal/activator/testdata/rootfs_removal_owners/remover_dropped.go b/internal/activator/testdata/rootfs_removal_owners/remover_dropped.go
new file mode 100644
index 000000000..9fd70a605
--- /dev/null
+++ b/internal/activator/testdata/rootfs_removal_owners/remover_dropped.go
@@ -0,0 +1,7 @@
+// A rootfs remover no longer tracked: refused.
+package instancectl
+
+var rootfsRemovers = map[string]bool{
+ "removeRootfsFiles": true, "removeRootfsExe": true, "removeWorkerFiles": true,
+ "removeRootfsGenFiles": true,
+}
diff --git a/internal/activator/testdata/rootfs_removal_owners/shrunk.go b/internal/activator/testdata/rootfs_removal_owners/shrunk.go
index 4a130b06f..59bd550ee 100644
--- a/internal/activator/testdata/rootfs_removal_owners/shrunk.go
+++ b/internal/activator/testdata/rootfs_removal_owners/shrunk.go
@@ -1,16 +1,36 @@
-// The removal guard's two allowlists with entries taken out, as the claims
-// cleanup may leave them: TestRootfsRemovalOwnersUnchanged accepts it.
+// The removal guard after a change that only tightened it, as the claims
+// cleanup may leave it: allowances taken away, a detector added, the
+// one-look proof unchanged. TestRootfsRemovalOwnersUnchanged accepts it.
package instancectl
var (
+ rootfsRemovers = map[string]bool{
+ "removeRootfsFiles": true, "removeRootfsExe": true, "removeWorkerFiles": true,
+ "removeRootfsGenFiles": true, "removeJITDropIn": true, "removeNewThing": true,
+ }
+ rootfsProofs = map[string]bool{
+ "removeRootfsUnitFiles": true, "removeRootfsUnitFilesOnce": true,
+ }
rootfsRemovalOwners = map[string]bool{
"startRootfs": true, "startRootfsCmd": true, "stopRootfs": true, "cleanCmdExe": true,
"handleSweep": true, "sweepGenLeftover": true,
}
- rawRemovalOwners = map[string]bool{
+ rootfsRemoverExceptions = map[string]string{}
+ preStartCallers = map[string]bool{"startRootfs": true, "startRootfsCmd": true}
+ rawRemovalOwners = map[string]bool{
"removeRootfsExe": true, "removeWorkerFiles": true, "removeRootfsGenFiles": true, "removeJITDropIn": true,
"removeGenFiles": true, "removeSharedKeyDir": true, "removeEntry": true, "removeTree": true,
"removeCmdExe": true, "ensureExeAs": true, "replaceLink": true,
"writeFileExcl": true, "BuildProbeImage": true, "bindControlSocket": true,
+ "x": false,
}
+ rawRemovals = map[string]map[string]bool{
+ "os": {"Remove": true, "RemoveAll": true, "Truncate": true},
+ "syscall": {"Unlink": true, "Unlinkat": true, "Rmdir": true},
+ "golang.org/x/sys/unix": {"Unlink": true, "Unlinkat": true, "Rmdir": true},
+ "github.com/carlosframework/platform/internal/safefile": {"Remove": true},
+ }
+ localRawRemovals = map[string]bool{"removeEntry": true, "removeTree": true}
)
+
+const onceProof = "removeRootfsUnitFilesOnce"
diff --git a/internal/activator/testdata/rootfs_verb_guard/forward.go b/internal/activator/testdata/rootfs_verb_guard/forward.go
new file mode 100644
index 000000000..763c2eb50
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/forward.go
@@ -0,0 +1,26 @@
+// A seam's SplitBackend forwarder, named like nothing rootfs: the guard
+// reads every method named like a method of a seam interface
+// (verbGuardFixtureSeam stands in for Plan 3's rootfs seams), so
+// verbGuardForward's KillHost is refused, while verbGuardOther, no seam's
+// method, is out of scope (its EmptyHost is not reported).
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type verbGuardFixtureSeam interface {
+ verbGuardForward(ctx context.Context, rt registry.Route) error
+}
+
+var _ verbGuardFixtureSeam = (*SplitBackend)(nil)
+
+func (b *SplitBackend) verbGuardForward(ctx context.Context, rt registry.Route) error {
+ return b.KillHost(ctx, rt)
+}
+
+func (b *SplitBackend) verbGuardOther(ctx context.Context, rt registry.Route) error {
+ return b.EmptyHost(ctx, rt)
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/named.go b/internal/activator/testdata/rootfs_verb_guard/named.go
new file mode 100644
index 000000000..6231d4c84
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/named.go
@@ -0,0 +1,29 @@
+// Outside the rootfs files the guard reads each function whose name, or
+// whose receiver's type name, matches rootfs: verbGuardRestartRootfs and
+// the method of verbGuardRootfsState are refused, while
+// verbGuardBinaryHelper, a binary helper, is out of scope (its Seed is not
+// reported).
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardRestartRootfs(ctx context.Context, rt registry.Route) error {
+ return b.Control.Stop(ctx, rt.Host, instancectl.RoleRun)
+}
+
+type verbGuardRootfsState struct{ b *ExecBackend }
+
+func (s verbGuardRootfsState) verbGuardRun(ctx context.Context, rt registry.Route) error {
+ _, err := s.b.Control.Cmd(ctx, rt.Host, 0)
+ return err
+}
+
+func (b *ExecBackend) verbGuardBinaryHelper(ctx context.Context, rt registry.Route) error {
+ _, err := b.Control.Seed(ctx, rt.Host, 0)
+ return err
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/alias.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_alias.go
similarity index 100%
rename from internal/activator/testdata/rootfs_verb_guard/alias.go
rename to internal/activator/testdata/rootfs_verb_guard/rootfs_alias.go
diff --git a/internal/activator/testdata/rootfs_verb_guard/childenv.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_childenv.go
similarity index 100%
rename from internal/activator/testdata/rootfs_verb_guard/childenv.go
rename to internal/activator/testdata/rootfs_verb_guard/rootfs_childenv.go
diff --git a/internal/activator/testdata/rootfs_verb_guard/clean.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_clean.go
similarity index 100%
rename from internal/activator/testdata/rootfs_verb_guard/clean.go
rename to internal/activator/testdata/rootfs_verb_guard/rootfs_clean.go
diff --git a/internal/activator/testdata/rootfs_verb_guard/direct.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_direct.go
similarity index 100%
rename from internal/activator/testdata/rootfs_verb_guard/direct.go
rename to internal/activator/testdata/rootfs_verb_guard/rootfs_direct.go
diff --git a/internal/activator/testdata/rootfs_verb_guard/rootfs_funcfield.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_funcfield.go
new file mode 100644
index 000000000..cdaf97dd6
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/rootfs_funcfield.go
@@ -0,0 +1,27 @@
+// A binary verb held in a func-typed field, a local variable and a
+// parameter: refused by the verb's signature wherever the value came from.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type verbGuardStopper struct {
+ stopFn func(ctx context.Context, host string, role instancectl.Role) error
+}
+
+func verbGuardFuncField(ctx context.Context, rt registry.Route, s verbGuardStopper,
+ start func(context.Context, string, uint64, int64, instancectl.StagedExe) (string, error)) error {
+ if err := s.stopFn(ctx, rt.Host, instancectl.RoleRun); err != nil {
+ return err
+ }
+ stop := s.stopFn
+ if err := stop(ctx, rt.Host, instancectl.RoleRun); err != nil {
+ return err
+ }
+ _, err := start(ctx, rt.Host, 7, 0, instancectl.StagedExe{})
+ return err
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/killhost.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_killhost.go
similarity index 100%
rename from internal/activator/testdata/rootfs_verb_guard/killhost.go
rename to internal/activator/testdata/rootfs_verb_guard/rootfs_killhost.go
diff --git a/internal/activator/testdata/rootfs_verb_guard/methodvalue.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_methodvalue.go
similarity index 100%
rename from internal/activator/testdata/rootfs_verb_guard/methodvalue.go
rename to internal/activator/testdata/rootfs_verb_guard/rootfs_methodvalue.go
diff --git a/internal/activator/testdata/rootfs_verb_guard/others.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_others.go
similarity index 100%
rename from internal/activator/testdata/rootfs_verb_guard/others.go
rename to internal/activator/testdata/rootfs_verb_guard/rootfs_others.go
diff --git a/internal/activator/testdata/rootfs_verb_guard/rootfs_unitnames.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_unitnames.go
new file mode 100644
index 000000000..521bc108e
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/rootfs_unitnames.go
@@ -0,0 +1,20 @@
+// The binary unit-name builders, instancectl's and this package's, and
+// the host cgroup's child open: each names a unit or a group a rootfs row
+// never runs in.
+package activator
+
+import (
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardUnitNames(rt registry.Route) error {
+ _ = instancectl.UnitName(instancectl.RoleRun, rt.Host)
+ _ = instancectl.GenUnitName(rt.Host, 7)
+ if _, err := unitName(instancectl.RoleRun, rt.Host, 7); err != nil {
+ return err
+ }
+ _ = runUnitName(rt.Host, 7)
+ _, err := b.Cgroups.OpenCleanupChild(rt.Host, "g7")
+ return err
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/rootfs_verbs.go b/internal/activator/testdata/rootfs_verb_guard/rootfs_verbs.go
new file mode 100644
index 000000000..6f8f74ada
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/rootfs_verbs.go
@@ -0,0 +1,36 @@
+// The rest of the binary unit's verbs: Control's Start, Seed and Reset,
+// and GenControl's StartGen, StartGenExe and StartSidecarExe, as calls and
+// method expressions.
+package activator
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (b *ExecBackend) verbGuardVerbs(ctx context.Context, rt registry.Route) error {
+ if _, err := b.Control.Start(ctx, rt.Host, instancectl.RoleRun, 0); err != nil {
+ return err
+ }
+ if _, err := b.Control.Seed(ctx, rt.Host, 0); err != nil {
+ return err
+ }
+ if err := b.Control.Reset(ctx, rt.Host, instancectl.RoleRun); err != nil {
+ return err
+ }
+ gc, err := b.genControl()
+ if err != nil {
+ return err
+ }
+ if _, err := gc.StartGen(ctx, rt.Host, 7, 0); err != nil {
+ return err
+ }
+ exe := GenControl.StartGenExe
+ if _, err := exe(gc, ctx, rt.Host, 7, 0, instancectl.StagedExe{}); err != nil {
+ return err
+ }
+ _, err = gc.StartSidecarExe(ctx, rt.Host, 0, instancectl.StagedExe{})
+ return err
+}
diff --git a/plan3_groups_test.go b/plan3_groups_test.go
index 64982509c..2f50113c8 100644
--- a/plan3_groups_test.go
+++ b/plan3_groups_test.go
@@ -7,7 +7,6 @@ import (
"go/parser"
"go/token"
"path/filepath"
- "regexp"
"slices"
"sort"
"strings"
@@ -25,7 +24,7 @@ import (
// built, and no row of a group not started is;
// - TestPlan3MachineryInventory: no name declared in internal/activator
// matches the release or the worker inventory unless that group has
-// started, beyond the two pinned allowances.
+// started, beyond the pinned baseline.
//
// Group A is the base group: Task 1 is its first task, so it counts as
// started from here on and is never listed in plan3GroupsStarted. The
@@ -49,29 +48,69 @@ var (
)
// The release and the worker machinery, by declared name (plan Task 1).
+// A word matches a name case-insensitively as whole camel-case words:
+// it starts the name or at an upper-case letter (or after an underscore or
+// a digit), and ends the name or before an upper-case letter, an
+// underscore or a digit, with an optional plural "s". So releaseOp matches
+// releaseOp, releaseOps and reapReleaseOpsLocked, and not releaseOptions;
+// WorkerReport matches WorkerReport and not WorkerReportedVersion.
var (
- plan3ReleaseInventory = regexp.MustCompile(`(?i)release(Op|Due|Timeout|Passed|BeforeSwap|Env|Backend)|runRelease|classifyRelease|leaseWatch|ReleaseError|errRelease|wakeCeiling|StartRelease`)
- plan3WorkerInventory = regexp.MustCompile(`(?i)rootfsWorker|RootfsWorker|LaunchRootfsWorker|workerGate|workerWakeGate|startRootfsWorkers|stopRootfsWorkers|handOverRootfsWorkers|WorkerReport|prepareWorker|writeRootfsWorkerLaunch|rootfsUnitFor`)
+ plan3ReleaseInventory = []string{"releaseOp", "releaseDue", "releaseTimeout", "releasePassed", "releaseBeforeSwap",
+ "releaseEnv", "releaseBackend", "runRelease", "classifyRelease", "leaseWatch", "ReleaseError", "errRelease",
+ "wakeCeiling", "StartRelease"}
+ plan3WorkerInventory = []string{"rootfsWorker", "LaunchRootfsWorker", "workerGate", "workerWakeGate", "startRootfsWorkers",
+ "stopRootfsWorkers", "handOverRootfsWorkers", "WorkerReport", "prepareWorker", "writeRootfsWorkerLaunch", "rootfsUnitFor"}
)
// plan3MachineryBaseline is every declaration in internal/activator's
// non-test files that matched either inventory on main at a912a342, read
-// once at Task 1: Plan 2's worker verb on RootfsControl and the binary
-// sidecar worker's WorkerReportedVersion, whose name happens to match.
-// Keyed by kind and owner, so the same name declared anywhere else is
-// judged afresh.
+// once at Task 1: Plan 2's worker verb on RootfsControl. Keyed by kind and
+// owner, so the same name declared anywhere else is judged afresh.
var plan3MachineryBaseline = map[string]bool{
"method RootfsControl.StartRootfsWorker": true, // control.go: Plan 2's worker verb
- "method Service.WorkerReportedVersion": true, // workerbuild.go: the binary sidecar worker's build
}
-// plan3SharedSeams are Group A's own seams: names that look like release or
-// worker machinery but belong to A (plan Task 1), so A's tasks may declare
-// them before either group starts.
-var plan3SharedSeams = map[string]bool{
- "Processes": true, "ProcessReader": true, "rootfsProcessesHook": true, "superviseRootfsLocked": true,
- "startCmdUnit": true, "stagedImageOf": true, "stagedIdentityOf": true, "rootfsCmdVars": true,
- "residentFailure": true,
+// plan3Match is the inventory word name matches, or "".
+func plan3Match(words []string, name string) string {
+ upper := func(c byte) bool { return c >= 'A' && c <= 'Z' }
+ edge := func(i int) bool {
+ return i == len(name) || upper(name[i]) || name[i] == '_' || name[i] >= '0' && name[i] <= '9'
+ }
+ for _, w := range words {
+ for i := 0; i+len(w) <= len(name); i++ {
+ if !strings.EqualFold(name[i:i+len(w)], w) {
+ continue
+ }
+ if i > 0 && !upper(name[i]) && name[i-1] != '_' && !(name[i-1] >= '0' && name[i-1] <= '9') {
+ continue
+ }
+ j := i + len(w)
+ if j < len(name) && name[j] == 's' && edge(j+1) {
+ j++
+ }
+ if edge(j) {
+ return w
+ }
+ }
+ }
+ return ""
+}
+
+func TestPlan3InventoryMatchesWholeWords(t *testing.T) {
+ for name, want := range map[string]string{
+ "releaseOp": "releaseOp", "releaseOps": "releaseOp", "reapReleaseOpsLocked": "releaseOp", "releaseOpFor": "releaseOp",
+ "releaseOptions": "", "releaseOpts": "", "errReleaseLeaseLost": "errRelease", "ReleaseError": "ReleaseError",
+ "rerunRelease": "", "runRelease2": "runRelease", "rootfsWorkerVars": "rootfsWorker", "RootfsWorkerGone": "rootfsWorker",
+ "startRootfsWorkers": "rootfsWorker", "WorkerReport": "WorkerReport", "WorkerReportedVersion": "", "rootfsUnitForRole": "rootfsUnitFor",
+ } {
+ got := plan3Match(plan3ReleaseInventory, name)
+ if got == "" {
+ got = plan3Match(plan3WorkerInventory, name)
+ }
+ if got != want {
+ t.Errorf("%s matched %q, want %q", name, got, want)
+ }
+ }
}
func plan3IDs(ns ...int) []string {
@@ -173,14 +212,15 @@ func TestPlan3MachineryInventory(t *testing.T) {
}
}
-// The fixture declares a release name, a worker name and the baseline's
-// StartRootfsWorker on another owner beside a shared seam and a binary
-// name: the inventory must refuse exactly the first three.
+// The fixture's comment lists what the inventory must refuse and what it
+// must pass: exactly the five refusals below.
func TestPlan3MachineryInventoryFixture(t *testing.T) {
problems, _ := plan3InventoryProblems(t, []string{filepath.Join("testdata", "plan3_inventory", "added.go")})
want := []string{"func runRelease: release machinery before group R has started",
"type rootfsWorkerState: worker machinery before group W has started",
- "method Service.StartRootfsWorker: worker machinery before group W has started"}
+ "method Service.StartRootfsWorker: worker machinery before group W has started",
+ "local func Service.wake.runReleaseStep: release machinery before group R has started",
+ "local type Service.wake.releaseOpRecord: release machinery before group R has started"}
if len(problems) != len(want) {
t.Fatalf("the inventory reported %d problems, want %d:\n%s", len(problems), len(want), strings.Join(problems, "\n"))
}
@@ -208,14 +248,11 @@ func plan3InventoryProblems(t *testing.T, sources []string) (problems []string,
seen[key] = true
continue
}
- if plan3SharedSeams[d.name] {
- continue
- }
at := fset.Position(d.pos).String() + ": " + key + ": "
- if plan3ReleaseInventory.MatchString(d.name) && !plan3GroupStarted("R") {
+ if plan3Match(plan3ReleaseInventory, d.name) != "" && !plan3GroupStarted("R") {
problems = append(problems, at+"release machinery before group R has started")
}
- if plan3WorkerInventory.MatchString(d.name) && !plan3GroupStarted("W") {
+ if plan3Match(plan3WorkerInventory, d.name) != "" && !plan3GroupStarted("W") {
problems = append(problems, at+"worker machinery before group W has started")
}
}
@@ -231,7 +268,9 @@ type plan3Decl struct {
// plan3Declarations is every package-level name f declares: functions,
// methods, types, vars and consts, and the struct fields and interface
-// methods of its types, each field or method with its owner.
+// methods of its types, each field or method with its owner; and inside
+// each function body, every local type and every local name bound to a
+// func literal (runRelease := func...), owned by the function.
func plan3Declarations(f *ast.File) []plan3Decl {
var out []plan3Decl
add := func(kind, owner string, id *ast.Ident) {
@@ -263,14 +302,44 @@ func plan3Declarations(f *ast.File) []plan3Decl {
return true
})
}
+ isFuncLit := func(e ast.Expr) bool { _, ok := e.(*ast.FuncLit); return ok }
+ locals := func(owner string, body *ast.BlockStmt) {
+ ast.Inspect(body, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.AssignStmt:
+ if len(x.Lhs) == len(x.Rhs) {
+ for i, l := range x.Lhs {
+ if id, ok := l.(*ast.Ident); ok && isFuncLit(x.Rhs[i]) {
+ add("local func", owner, id)
+ }
+ }
+ }
+ case *ast.TypeSpec:
+ add("local type", owner, x.Name)
+ members(owner+"."+x.Name.Name, x.Type)
+ case *ast.ValueSpec:
+ for i, id := range x.Names {
+ if i < len(x.Values) && isFuncLit(x.Values[i]) {
+ add("local func", owner, id)
+ }
+ }
+ }
+ return true
+ })
+ }
for _, decl := range f.Decls {
switch d := decl.(type) {
case *ast.FuncDecl:
+ owner := d.Name.Name
if d.Recv != nil && len(d.Recv.List) > 0 {
+ owner = receiverName(d.Recv.List[0].Type) + "." + d.Name.Name
add("method", receiverName(d.Recv.List[0].Type), d.Name)
} else {
add("func", "", d.Name)
}
+ if d.Body != nil {
+ locals(owner, d.Body)
+ }
case *ast.GenDecl:
for _, spec := range d.Specs {
switch sp := spec.(type) {
diff --git a/testdata/plan3_inventory/added.go b/testdata/plan3_inventory/added.go
index 48a26b669..9f224ea78 100644
--- a/testdata/plan3_inventory/added.go
+++ b/testdata/plan3_inventory/added.go
@@ -1,8 +1,10 @@
-// The inventory's fixture (plan3_groups_test.go): a release name and a
-// worker name, which it refuses before their groups start; the baseline's
-// StartRootfsWorker declared on another owner, which the baseline does not
-// cover; and a shared seam of group A and a binary name that matches
-// neither inventory, which pass.
+// The inventory's fixture (plan3_groups_test.go). Refused before their
+// groups start: a release name, a worker name, the baseline's
+// StartRootfsWorker declared on another owner (the baseline does not
+// cover it), a local func literal and a local type inside a function. Not
+// refused: names that only contain an inventory word inside a longer word
+// (releaseOptions, WorkerReportedVersion), a seam of group A and a binary
+// name.
package activator
type Service struct{}
@@ -13,8 +15,16 @@ type rootfsWorkerState struct{}
func (s *Service) StartRootfsWorker() {}
-func startCmdUnit() {}
+func (s *Service) wake() {
+ runReleaseStep := func() {}
+ type releaseOpRecord struct{}
+ _ = runReleaseStep
+}
+
+type releaseOptions struct{}
-func (s *Service) residentFailure(error) bool { return false }
+func (s *Service) WorkerReportedVersion() {}
+
+func startCmdUnit() {}
func releaseBuild() {}