| new file mode 100644 |
| index 000000000..81b08ee47 |
| --- /dev/null |
| +++ b/internal/provision/census_scope_test.go |
| @@ -0,0 +1,503 @@ |
| +package provision |
| + |
| +// The census's scope (C2; Paul's ruling 2 on #280, 2026-10-25, and his go |
| +// on #404, 2026-10-26): the root-read census covers only code root runs. |
| +// Root's entry points come from the systemd units that run as root; the |
| +// units they reach come from J4's reference graph (inputPlatformCallers), |
| +// built for linux, the only platform root runs on, and walked from those |
| +// entry points instead of main.go:main. |
| + |
| +import ( |
| + "fmt" |
| + "go/ast" |
| + "go/token" |
| + "go/types" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "sort" |
| + "strings" |
| + "sync" |
| + |
| + "golang.org/x/tools/go/packages" |
| +) |
| + |
| +// rootDispatcher is a function that picks a verb with a switch on Tag. |
| +// Walking it from root follows everything outside that switch and only the |
| +// case clauses of verbs root runs. Verb is the verb main dispatches to it |
| +// ("" for main itself). |
| +type rootDispatcher struct{ Key, Tag, Verb string } |
| + |
| +var rootDispatchers = []rootDispatcher{ |
| + {Key: "main.go:main", Tag: "cmd"}, |
| + {Key: "system.go:runSystem", Tag: "verb", Verb: "system"}, |
| +} |
| + |
| +// rootBootVerbs are run as root by a box's user_data at first boot (the |
| +// launch template lives in the infra repository, so no unit here names |
| +// them): carlos bootstrap, and on a box a region's group launches, system |
| +// host-env write and system install-channel. |
| +var rootBootVerbs = []string{"bootstrap", "system install-channel", "system host-env"} |
| + |
| +// rootCallbackMethods are the methods the standard library calls by name |
| +// through its own interfaces (fmt, encoding/json, errors, io, sort, net/http, |
| +// database/sql, io/fs). The graph sees no call for them, so a reached type |
| +// reaches these methods of its own. |
| +var rootCallbackMethods = map[string]bool{} |
| + |
| +func init() { |
| + for _, name := range strings.Fields(`Error String GoString Format MarshalJSON UnmarshalJSON MarshalText UnmarshalText MarshalBinary UnmarshalBinary Scan Value Unwrap Is As Len Less Swap Push Pop Read Write Close Seek ReadAt WriteAt WriteTo ReadFrom ReadDir Stat Open ServeHTTP RoundTrip Deadline Done Err LogValue Set Get Flush`) { |
| + rootCallbackMethods[name] = true |
| + } |
| +} |
| + |
| +// rootUnitExec finds the carlos binary and the verb (and sub-verb) it is |
| +// given in a unit's Exec line, inside an inline sh -c script too. |
| +var rootUnitExec = regexp.MustCompile(`/opt/carlos/(?:system/guard/)?carlos(?:\.prev)?\s+([a-z][a-z0-9-]*)(?:\s+([a-z][a-z0-9-]*))?`) |
| + |
| +// rootVerbs is the verb labels root runs, per dispatcher: every verb in an |
| +// Exec line of a unit in internal/host/units with no User= (or User=root) |
| +// and no DynamicUser=, and the boot verbs. A verb that has its own |
| +// dispatcher ("system") needs a sub-verb. |
| +func rootVerbs(root string) (map[string]map[string]bool, error) { |
| + dir := filepath.Join(root, "internal/host/units") |
| + names, err := filepath.Glob(filepath.Join(dir, "*.service")) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(names) == 0 { |
| + return nil, fmt.Errorf("census scope: no units in %s", dir) |
| + } |
| + sort.Strings(names) |
| + var verbs [][2]string |
| + for _, name := range names { |
| + raw, err := os.ReadFile(name) |
| + if err != nil { |
| + return nil, err |
| + } |
| + asRoot := true |
| + var execs []string |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + line = strings.TrimSpace(line) |
| + key, value, _ := strings.Cut(line, "=") |
| + switch { |
| + case key == "User" && strings.TrimSpace(value) != "root" && strings.TrimSpace(value) != "": |
| + asRoot = false |
| + case key == "DynamicUser" && (strings.TrimSpace(value) == "yes" || strings.TrimSpace(value) == "true"): |
| + asRoot = false |
| + case strings.HasPrefix(key, "Exec"): |
| + execs = append(execs, value) |
| + } |
| + } |
| + if !asRoot { |
| + continue |
| + } |
| + for _, line := range execs { |
| + for _, m := range rootUnitExec.FindAllStringSubmatch(line, -1) { |
| + verbs = append(verbs, [2]string{m[1], m[2]}) |
| + } |
| + } |
| + } |
| + for _, v := range rootBootVerbs { |
| + verb, sub, _ := strings.Cut(v, " ") |
| + verbs = append(verbs, [2]string{verb, sub}) |
| + } |
| + out := map[string]map[string]bool{} |
| + add := func(key, label string) { |
| + if out[key] == nil { |
| + out[key] = map[string]bool{} |
| + } |
| + out[key][label] = true |
| + } |
| + for _, v := range verbs { |
| + add(rootDispatchers[0].Key, v[0]) |
| + for _, d := range rootDispatchers[1:] { |
| + if d.Verb != v[0] { |
| + continue |
| + } |
| + if v[1] == "" { |
| + return nil, fmt.Errorf("census scope: a root unit runs %q with no sub-verb", v[0]) |
| + } |
| + add(d.Key, v[1]) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +type refMethod struct{ Name, Key string } |
| + |
| +// refGraph is J4's reference graph for one platform: every declaration |
| +// (keyed as the census keys it, rootReadDeclName) to what it references. |
| +type refGraph struct { |
| + // Edges: identifier uses, interface dispatch to every implementing |
| + // method, json.Unmarshal to UnmarshalJSON, //go:embed to the embedded |
| + // file ("<path>:external"). Every case of every dispatcher. |
| + Edges map[string]map[string]bool |
| + // Cases splits a dispatcher's edges by case label of its verb switch; |
| + // "" holds everything outside that switch's labelled cases. |
| + Cases map[string]map[string]map[string]bool |
| + // Labels is every case label of each dispatcher's verb switch. |
| + Labels map[string]map[string]bool |
| + // Methods: a type's declaration key to its methods. |
| + Methods map[string][]refMethod |
| + // Inits: every init function, and every function a package-level var |
| + // initializer calls, in the packages linked into the binary at root. |
| + Inits []string |
| +} |
| + |
| +func newRefGraph() *refGraph { |
| + return &refGraph{Edges: map[string]map[string]bool{}, Cases: map[string]map[string]map[string]bool{}, Labels: map[string]map[string]bool{}, Methods: map[string][]refMethod{}} |
| +} |
| + |
| +func refAdd(g map[string]map[string]bool, a, b string) { |
| + if a == "" || b == "" || a == b { |
| + return |
| + } |
| + if g[a] == nil { |
| + g[a] = map[string]bool{} |
| + } |
| + g[a][b] = true |
| +} |
| + |
| +// censusGraph loads root's module for one platform and builds its graph. |
| +func censusGraph(root, platform string) (*refGraph, error) { |
| + cfg := &packages.Config{Dir: root, Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports, Env: append(os.Environ(), "GOOS="+platform, "GOARCH=amd64", "CGO_ENABLED=0")} |
| + pkgs, err := packages.Load(cfg, "./...") |
| + if err != nil { |
| + return nil, err |
| + } |
| + if packages.PrintErrors(pkgs) > 0 { |
| + return nil, fmt.Errorf("production package loading failed") |
| + } |
| + type decl struct { |
| + key string |
| + node ast.Decl |
| + pkg *packages.Package |
| + } |
| + var decls []decl |
| + objects := map[types.Object]string{} |
| + methods := map[string][]*types.Func{} |
| + for _, p := range pkgs { |
| + for _, f := range p.Syntax { |
| + file, _ := filepath.Rel(root, p.Fset.Position(f.Pos()).Filename) |
| + file = filepath.ToSlash(file) |
| + grouped := map[string]int{} |
| + for _, d := range f.Decls { |
| + name, ok := rootReadDeclName(d, grouped) |
| + if !ok { |
| + continue |
| + } |
| + key := file + ":" + name |
| + switch d := d.(type) { |
| + case *ast.FuncDecl: |
| + if obj, ok := p.TypesInfo.Defs[d.Name].(*types.Func); ok { |
| + objects[obj] = key |
| + if obj.Type().(*types.Signature).Recv() != nil { |
| + methods[obj.Name()] = append(methods[obj.Name()], obj) |
| + } |
| + } |
| + case *ast.GenDecl: |
| + ast.Inspect(d, func(n ast.Node) bool { |
| + if id, ok := n.(*ast.Ident); ok { |
| + if obj := p.TypesInfo.Defs[id]; obj != nil { |
| + objects[obj] = key |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + decls = append(decls, decl{key, d, p}) |
| + } |
| + } |
| + } |
| + g := newRefGraph() |
| + for _, ms := range methods { |
| + for _, m := range ms { |
| + r := m.Type().(*types.Signature).Recv().Type() |
| + if ptr, ok := r.(*types.Pointer); ok { |
| + r = ptr.Elem() |
| + } |
| + if n, ok := r.(*types.Named); ok { |
| + if tk := objects[n.Origin().Obj()]; tk != "" { |
| + g.Methods[tk] = append(g.Methods[tk], refMethod{m.Name(), objects[m]}) |
| + } |
| + } |
| + } |
| + } |
| + // nodeRefs is one node's references, as J4 has always counted them. |
| + nodeRefs := func(d decl, n ast.Node, add func(string)) { |
| + if call, ok := n.(*ast.CallExpr); ok && len(call.Args) == 2 { |
| + if sel, ok := call.Fun.(*ast.SelectorExpr); ok { |
| + obj := d.pkg.TypesInfo.Uses[sel.Sel] |
| + if obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "encoding/json" && obj.Name() == "Unmarshal" { |
| + for _, method := range inputJSONMethods(d.pkg.TypesInfo.TypeOf(call.Args[1]), map[types.Type]bool{}) { |
| + add(objects[method]) |
| + } |
| + } |
| + } |
| + } |
| + if id, ok := n.(*ast.Ident); ok { |
| + add(objects[d.pkg.TypesInfo.Uses[id]]) |
| + } |
| + if s, ok := n.(*ast.SelectorExpr); ok { |
| + if sel := d.pkg.TypesInfo.Selections[s]; sel != nil { |
| + if iface, ok := sel.Recv().Underlying().(*types.Interface); ok { |
| + if method, ok := sel.Obj().(*types.Func); ok { |
| + for _, candidate := range methods[method.Name()] { |
| + sig := candidate.Type().(*types.Signature) |
| + if types.Implements(sig.Recv().Type(), iface) || types.Implements(types.NewPointer(sig.Recv().Type()), iface) { |
| + add(objects[candidate]) |
| + } |
| + } |
| + } |
| + } |
| + } |
| + } |
| + } |
| + walk := func(d decl, n ast.Node, add func(string)) { |
| + if n == nil { |
| + return |
| + } |
| + ast.Inspect(n, func(n ast.Node) bool { |
| + nodeRefs(d, n, add) |
| + return true |
| + }) |
| + } |
| + tags := map[string]string{} |
| + for _, rd := range rootDispatchers { |
| + tags[rd.Key] = rd.Tag |
| + } |
| + for _, d := range decls { |
| + walk(d, d.node, func(to string) { refAdd(g.Edges, d.key, to) }) |
| + // The embedded unit is an input to the reachable installer declaration. |
| + if gd, ok := d.node.(*ast.GenDecl); ok && gd.Doc != nil { |
| + for _, c := range gd.Doc.List { |
| + if strings.HasPrefix(c.Text, "//go:embed ") { |
| + for _, pattern := range strings.Fields(strings.TrimPrefix(c.Text, "//go:embed ")) { |
| + matches, _ := filepath.Glob(filepath.Join(root, filepath.Dir(strings.Split(d.key, ":")[0]), pattern)) |
| + for _, path := range matches { |
| + rel, _ := filepath.Rel(root, path) |
| + refAdd(g.Edges, d.key, filepath.ToSlash(rel)+":external") |
| + } |
| + } |
| + } |
| + } |
| + } |
| + tag, dispatcher := tags[d.key] |
| + if !dispatcher { |
| + continue |
| + } |
| + cases := map[string]map[string]bool{} |
| + g.Cases[d.key] = cases |
| + g.Labels[d.key] = map[string]bool{} |
| + into := func(label string) func(string) { |
| + return func(to string) { refAdd(cases, label, to) } |
| + } |
| + ast.Inspect(d.node, func(n ast.Node) bool { |
| + sw, ok := n.(*ast.SwitchStmt) |
| + if ok { |
| + id, isIdent := sw.Tag.(*ast.Ident) |
| + ok = isIdent && id.Name == tag |
| + } |
| + if !ok { |
| + nodeRefs(d, n, into("")) |
| + return true |
| + } |
| + walk(d, sw.Init, into("")) |
| + walk(d, sw.Tag, into("")) |
| + for _, s := range sw.Body.List { |
| + cc := s.(*ast.CaseClause) |
| + var labels []string |
| + for _, e := range cc.List { |
| + lit, ok := e.(*ast.BasicLit) |
| + if !ok || lit.Kind != token.STRING { |
| + labels = nil |
| + break |
| + } |
| + labels = append(labels, strings.Trim(lit.Value, "\"`")) |
| + } |
| + if len(labels) == 0 { |
| + labels = []string{""} |
| + } |
| + for _, l := range labels { |
| + if l != "" { |
| + g.Labels[d.key][l] = true |
| + } |
| + for _, e := range cc.List { |
| + walk(d, e, into(l)) |
| + } |
| + for _, st := range cc.Body { |
| + walk(d, st, into(l)) |
| + } |
| + } |
| + } |
| + return false |
| + }) |
| + } |
| + // The packages linked into the binary built from root's own directory. |
| + linked := map[string]bool{} |
| + var link func(p *packages.Package) |
| + link = func(p *packages.Package) { |
| + if linked[p.PkgPath] { |
| + return |
| + } |
| + linked[p.PkgPath] = true |
| + for _, q := range p.Imports { |
| + link(q) |
| + } |
| + } |
| + for _, p := range pkgs { |
| + if p.Name == "main" && len(p.GoFiles) > 0 && filepath.Clean(filepath.Dir(p.GoFiles[0])) == filepath.Clean(root) { |
| + link(p) |
| + } |
| + } |
| + for _, d := range decls { |
| + if !linked[d.pkg.PkgPath] { |
| + continue |
| + } |
| + switch n := d.node.(type) { |
| + case *ast.FuncDecl: |
| + if n.Recv == nil && n.Name.Name == "init" { |
| + g.Inits = append(g.Inits, d.key) |
| + } |
| + case *ast.GenDecl: |
| + if n.Tok != token.VAR { |
| + continue |
| + } |
| + ast.Inspect(n, func(x ast.Node) bool { |
| + call, ok := x.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + var id *ast.Ident |
| + switch f := call.Fun.(type) { |
| + case *ast.Ident: |
| + id = f |
| + case *ast.SelectorExpr: |
| + id = f.Sel |
| + } |
| + if id != nil { |
| + if fn, ok := d.pkg.TypesInfo.Uses[id].(*types.Func); ok && objects[fn] != "" { |
| + g.Inits = append(g.Inits, objects[fn]) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + sort.Strings(g.Inits) |
| + return g, nil |
| +} |
| + |
| +// censusGraphs caches the repository's graphs within one test process, so |
| +// the census and J4 load linux once between them. Fixture trees, which |
| +// tests edit between loads, use censusGraph directly. |
| +var censusGraphs sync.Map |
| + |
| +type censusGraphOnce struct { |
| + once sync.Once |
| + g *refGraph |
| + err error |
| +} |
| + |
| +func censusGraphShared(root, platform string) (*refGraph, error) { |
| + v, _ := censusGraphs.LoadOrStore(root+"\x00"+platform, &censusGraphOnce{}) |
| + c := v.(*censusGraphOnce) |
| + c.once.Do(func() { c.g, c.err = censusGraph(root, platform) }) |
| + return c.g, c.err |
| +} |
| + |
| +// reach walks the graph from start. A dispatcher in allowed is expanded by |
| +// its "" edges and its allowed labels' only; a reached type reaches its |
| +// standard-library callback methods. |
| +func (g *refGraph) reach(start map[string]string, allowed map[string]map[string]bool) map[string]string { |
| + reached := map[string]string{} |
| + var queue []string |
| + push := func(to, from string) { |
| + if to == "" { |
| + return |
| + } |
| + if _, ok := reached[to]; !ok { |
| + reached[to] = from |
| + queue = append(queue, to) |
| + } |
| + } |
| + var seeds []string |
| + for k := range start { |
| + seeds = append(seeds, k) |
| + } |
| + sort.Strings(seeds) |
| + for _, k := range seeds { |
| + push(k, start[k]) |
| + } |
| + for len(queue) > 0 { |
| + from := queue[0] |
| + queue = queue[1:] |
| + var next []string |
| + if labels, ok := allowed[from]; ok && g.Cases[from] != nil { |
| + for to := range g.Cases[from][""] { |
| + next = append(next, to) |
| + } |
| + for l := range labels { |
| + for to := range g.Cases[from][l] { |
| + next = append(next, to) |
| + } |
| + } |
| + } else { |
| + for to := range g.Edges[from] { |
| + next = append(next, to) |
| + } |
| + } |
| + for _, m := range g.Methods[from] { |
| + if rootCallbackMethods[m.Name] { |
| + next = append(next, m.Key) |
| + } |
| + } |
| + sort.Strings(next) |
| + for _, to := range next { |
| + push(to, from) |
| + } |
| + } |
| + return reached |
| +} |
| + |
| +// rootScope is what root runs: every declaration (and embedded file, |
| +// "<path>:external") reached from root's entry points, each with the |
| +// declaration it was reached from. |
| +type rootScope struct { |
| + Reached map[string]string |
| +} |
| + |
| +// rootScopeOf builds root's scope from the tree at root. |
| +func rootScopeOf(root string) (rootScope, error) { |
| + g, err := censusGraph(root, "linux") |
| + if err != nil { |
| + return rootScope{}, err |
| + } |
| + return rootScopeFrom(root, g) |
| +} |
| + |
| +func rootScopeFrom(root string, g *refGraph) (rootScope, error) { |
| + allowed, err := rootVerbs(root) |
| + if err != nil { |
| + return rootScope{}, err |
| + } |
| + for key, labels := range allowed { |
| + for l := range labels { |
| + if !g.Labels[key][l] { |
| + return rootScope{}, fmt.Errorf("census scope: root runs verb %q, but %s has no case for it", l, key) |
| + } |
| + } |
| + } |
| + start := map[string]string{rootDispatchers[0].Key: "root entry point"} |
| + for _, k := range g.Inits { |
| + start[k] = "init in the root binary" |
| + } |
| + return rootScope{Reached: g.reach(start, allowed)}, nil |
| +} |
| + |
| +func sortedStrings(s []string) []string { |
| + out := append([]string(nil), s...) |
| + sort.Strings(out) |
| + return out |
| +} |