carlos / platform Public

Fleet secrets key guard: Sealer fields only in named methods, writes only in NewSealer, and a walk for wholly excluded packages (branch review R1)

The seal-key guard allowed field access in any method with a Sealer
receiver, so a new method could fill a zero sealer from its arguments.
Reads are now allowed only in NewSealer and Sealer's five named methods,
writes only in NewSealer. Two fixtures: a new method that fills a zero
sealer, and Bound rewritten to write a field. The build-constrained pass
now walks every .go file of the module instead of the linux listing's
ignored files, so a package whose every file is for another GOOS is seen;
a darwin-only fixture package pins it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0ca4cc2f1521134182bb34b223b581ee7969ff89 parent e723c94
3 files changed, +224 −61
  • internal/console/sealkey_guard_test.go +192 −61
  • internal/console/testdata/sealguard/ctor/method.go +15 −0
  • internal/console/testdata/sealguard/darwinonly/sealy/sealy.go +17 −0
diff --git a/internal/console/sealkey_guard_test.go b/internal/console/sealkey_guard_test.go
index 120dd6310..66ab63ce1 100644
--- a/internal/console/sealkey_guard_test.go
+++ b/internal/console/sealkey_guard_test.go
@@ -19,12 +19,15 @@ package console
// Each is allowed only inside the functions sealGuardAllowed names for it.
// (appconfig.Sealer).Seal is allowed anywhere: a Sealer comes only from
// NewSealer, so it seals only to a key an allowed caller chose. That rests on
-// three more checks: a composite literal of appconfig.Sealer with any field
+// four more checks: a composite literal of appconfig.Sealer with any field
// set appears only in NewSealer, exactly once (an empty one is the zero
-// Sealer, which refuses every binding and seals nothing); every read or write
-// of one of Sealer's fields, found by identity, is inside NewSealer or one of
-// Sealer's own methods, so no second constructor can fill a zero Sealer field
-// by field; and the struct has no exported field.
+// Sealer, which refuses every binding and seals nothing); every read of one
+// of Sealer's fields, found by identity, is inside NewSealer or one of
+// Sealer's own methods named in sgSealerMethods, so no second constructor,
+// and no new method, can fill a zero Sealer field by field; every write of
+// one is inside NewSealer; and the struct has no exported field. Files no
+// linux build compiles, a package wholly for another GOOS included, are
+// found by a walk of the source tree.
//
// Negative fixtures (testdata/sealguard) are laid over the real packages with
// go list's overlay, so each resolves exactly as real code would, and each
@@ -68,6 +71,18 @@ const (
sgChooseSealKey = "(*" + sgConsole + ".Server).chooseSealKey"
)
+// sgSealerMethods are Sealer's own methods, by types.Func.FullName: with
+// NewSealer, the only functions that may read one of Sealer's fields. A new
+// method is not on the list, so it cannot fill a zero Sealer from its
+// arguments; adding it here is a ruling.
+var sgSealerMethods = []string{
+ "(" + sgAppconfig + ".Sealer).Fingerprint",
+ "(" + sgAppconfig + ".Sealer).Binding",
+ "(" + sgAppconfig + ".Sealer).Bound",
+ "(" + sgAppconfig + ".Sealer).PublicKeyB64",
+ "(" + sgAppconfig + ".Sealer).Seal",
+}
+
// sgTargets is every guarded function, by types.Func.FullName.
var sgTargets = []string{sgSeal, sgSealBound, sgSealUnbound, sgNewSealer, sgSealWith, sgArchiveSeal, sgChooseSealKey}
@@ -186,8 +201,9 @@ func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int)
}
var out []sgFinding
seen := map[string]int{}
- // Sealer's fields, by identity: reading or writing one is building or
- // taking apart a sealer, which only NewSealer and Sealer's own methods
+ // Sealer's fields, by identity: reading one is taking apart a sealer,
+ // which only NewSealer and Sealer's own methods (sgSealerMethods, by
+ // name) may do; writing one is building a sealer, which only NewSealer
// may do. A keyed literal's keys are uses of the fields too.
fields := map[*types.Var]bool{}
for _, pkg := range pkgs {
@@ -202,22 +218,11 @@ func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int)
}
}
}
- fieldsAllowed := func(fn *types.Func) bool {
- if fn == nil {
- return false
- }
- if fn.FullName() == sgNewSealer {
+ fieldsAllowed := func(in string, write bool) bool {
+ if in == sgNewSealer {
return true
}
- recv := fn.Signature().Recv()
- if recv == nil {
- return false
- }
- t := recv.Type()
- if p, ok := t.(*types.Pointer); ok {
- t = p.Elem()
- }
- return sgIsSealer(t)
+ return !write && slices.Contains(sgSealerMethods, in)
}
rel := func(p token.Position) token.Position {
if r, err := filepath.Rel(root, p.Filename); err == nil {
@@ -230,18 +235,21 @@ func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int)
for _, file := range pkg.Syntax {
for _, decl := range file.Decls {
in := ""
- var encl *types.Func
if fd, ok := decl.(*ast.FuncDecl); ok {
if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
- in, encl = fn.FullName(), fn
+ in = fn.FullName()
}
}
+ writes := sgWrites(decl)
ast.Inspect(decl, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.Ident:
if v, ok := info.Uses[n].(*types.Var); ok && fields[v] {
what := "appconfig.Sealer." + v.Name()
- if fieldsAllowed(encl) {
+ if writes[n] {
+ what += " write"
+ }
+ if fieldsAllowed(in, writes[n]) {
seen[in+" -> "+what]++
return true
}
@@ -281,47 +289,131 @@ func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int)
return out, seen
}
-// sgIgnoredFiles names every non-test file a linux build leaves out (build
-// constraints) that the type-checked scan therefore never sees, if it could
-// name a guarded function: it imports appconfig or archive, or it belongs to
-// appconfig, archive or console and mentions a guarded name. A real hit means
-// the guard needs a load under that file's GOOS or tags.
-func sgIgnoredFiles(t *testing.T, root string, pkgs []*packages.Package) []string {
+// sgWrites is every identifier in decl that names something being written:
+// the selector chain of an assignment's or an increment's target, of a
+// range's assigned key and value, and of an operand whose address is taken
+// (through the pointer, a write). For a Sealer field, that is building a
+// sealer.
+func sgWrites(decl ast.Decl) map[*ast.Ident]bool {
+ out := map[*ast.Ident]bool{}
+ var mark func(e ast.Expr)
+ mark = func(e ast.Expr) {
+ switch e := e.(type) {
+ case *ast.Ident:
+ out[e] = true
+ case *ast.SelectorExpr:
+ out[e.Sel] = true
+ mark(e.X)
+ case *ast.IndexExpr:
+ mark(e.X)
+ case *ast.StarExpr:
+ mark(e.X)
+ case *ast.ParenExpr:
+ mark(e.X)
+ }
+ }
+ ast.Inspect(decl, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.AssignStmt:
+ if n.Tok != token.DEFINE {
+ for _, e := range n.Lhs {
+ mark(e)
+ }
+ }
+ case *ast.IncDecStmt:
+ mark(n.X)
+ case *ast.RangeStmt:
+ if n.Tok == token.ASSIGN {
+ if n.Key != nil {
+ mark(n.Key)
+ }
+ if n.Value != nil {
+ mark(n.Value)
+ }
+ }
+ case *ast.UnaryExpr:
+ if n.Op == token.AND {
+ mark(n.X)
+ }
+ }
+ return true
+ })
+ return out
+}
+
+// sgIgnoredFiles names every non-test .go file under root, the module path
+// modPath, that the linux listing does not compile and that could name a
+// guarded function: it imports appconfig or archive, or it belongs to
+// appconfig, archive or console and mentions a guarded name. It walks the
+// source tree as go does (no testdata, vendor, "." or "_" directories, no
+// nested module), so it sees what the listing never returns: a file left out
+// by build constraints, and a package whose every file is for another GOOS
+// or tag, which a linux ./... drops whole. A real hit means the guard needs a
+// load under that file's GOOS or tags.
+func sgIgnoredFiles(t *testing.T, root, modPath string, pkgs []*packages.Package) []string {
t.Helper()
names := []string{"chooseSealKey", "NewSealer", "SealBound", "SealUnbound", "sealWith", "Seal(", "Sealer{"}
- var out []string
+ compiled := map[string]bool{}
for _, pkg := range pkgs {
- for _, path := range pkg.IgnoredFiles {
- if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
- continue
+ for _, path := range pkg.GoFiles {
+ compiled[path] = true
+ }
+ }
+ var out []string
+ err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ if path == root {
+ return nil
}
- src, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
+ name := d.Name()
+ if name == "testdata" || name == "vendor" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
+ return filepath.SkipDir
}
- f, err := parser.ParseFile(token.NewFileSet(), path, src, parser.ImportsOnly)
- if err != nil {
- t.Fatalf("%s: %v", path, err)
+ if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil {
+ return filepath.SkipDir
}
- hit := ""
- for _, imp := range f.Imports {
- if p, _ := strconv.Unquote(imp.Path.Value); p == sgAppconfig || p == sgArchive {
- hit = "imports " + p
- }
+ return nil
+ }
+ if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") || compiled[path] {
+ return nil
+ }
+ src, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ f, err := parser.ParseFile(token.NewFileSet(), path, src, parser.ImportsOnly)
+ if err != nil {
+ return fmt.Errorf("%s: %w", path, err)
+ }
+ hit := ""
+ for _, imp := range f.Imports {
+ if p, _ := strconv.Unquote(imp.Path.Value); p == sgAppconfig || p == sgArchive {
+ hit = "imports " + p
}
- if hit == "" && sgReaches(pkg.PkgPath, nil) {
- for _, name := range names {
- if bytes.Contains(src, []byte(name)) {
- hit = "mentions " + name
- break
- }
+ }
+ r, _ := filepath.Rel(root, path)
+ pkgPath := modPath
+ if dir := filepath.ToSlash(filepath.Dir(r)); dir != "." {
+ pkgPath += "/" + dir
+ }
+ if hit == "" && sgReaches(pkgPath, nil) {
+ for _, name := range names {
+ if bytes.Contains(src, []byte(name)) {
+ hit = "mentions " + name
+ break
}
}
- if hit != "" {
- r, _ := filepath.Rel(root, path)
- out = append(out, r+": "+hit)
- }
}
+ if hit != "" {
+ out = append(out, filepath.ToSlash(r)+": "+hit)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
}
sort.Strings(out)
return out
@@ -360,6 +452,11 @@ func TestOnlySealKeyForBuildsSealers(t *testing.T) {
t.Errorf("the allowlist names %s, which the module no longer declares", in)
}
}
+ for _, m := range sgSealerMethods {
+ if !found[m] {
+ t.Errorf("sgSealerMethods names %s, which the module no longer declares", m)
+ }
+ }
})
t.Run("Sealer has no exported field", func(t *testing.T) {
@@ -403,11 +500,20 @@ func TestOnlySealKeyForBuildsSealers(t *testing.T) {
})
t.Run("build-constrained files", func(t *testing.T) {
- for _, f := range sgIgnoredFiles(t, root, listed) {
+ for _, f := range sgIgnoredFiles(t, root, sgModule, listed) {
t.Errorf("%s, and a linux build leaves it out, so the guard never type-checks it: load it under its own GOOS or tags here", f)
}
})
+ t.Run("a package wholly for another GOOS", func(t *testing.T) {
+ dir := filepath.Join(root, "internal", "console", "testdata", "sealguard", "darwinonly")
+ got := sgIgnoredFiles(t, dir, sgModule+"/internal/console/testdata/sealguard/darwinonly", sgList(t, dir))
+ want := []string{"sealy/sealy.go: imports " + sgAppconfig}
+ if !slices.Equal(got, want) {
+ t.Errorf("a package whose every file is for darwin: the guard named %v, want %v", got, want)
+ }
+ })
+
t.Run("fixtures are named", func(t *testing.T) {
overlay, want := sgFixtures(t, root)
fpkgs := sgLoad(t, root, overlay, []string{sgConsole, sgAppconfig})
@@ -465,7 +571,13 @@ func TestOnlySealKeyForBuildsSealers(t *testing.T) {
// - sealwith: an exported appconfig helper sealing to any key through
// the unexported core, sealWith;
// - choose: chooseSealKey called from a console function that is neither
-// sealKeyFor nor the config PUT's check.
+// sealKeyFor nor the config PUT's check;
+// - method: a new method on Sealer that fills a zero sealer's fields from
+// its arguments;
+// - methodwrite: one of Sealer's named methods (Bound) writing a field.
+//
+// The darwinonly fixture, a package whose every file is for darwin, is
+// walked by its own subtest: it is not laid over anything.
func sgFixtures(t *testing.T, root string) (map[string][]byte, []string) {
t.Helper()
dir := filepath.Join(root, "internal", "console", "testdata", "sealguard")
@@ -486,7 +598,20 @@ func sgFixtures(t *testing.T, root string) (map[string][]byte, []string) {
filepath.Join(appconfigDir, "zz_sealguard_ctor.go"): read("ctor/ctor.go"),
filepath.Join(appconfigDir, "zz_sealguard_fields.go"): read("ctor/fieldassign.go"),
filepath.Join(appconfigDir, "zz_sealguard_sealwith.go"): read("ctor/sealwith.go"),
+ filepath.Join(appconfigDir, "zz_sealguard_method.go"): read("ctor/method.go"),
+ }
+ // methodwrite: one of Sealer's own methods writes a field. Only NewSealer
+ // may; the fixture rewrites Bound in an overlay of the real sealer.go.
+ sealerPath := filepath.Join(appconfigDir, "sealer.go")
+ sealerSrc, err := os.ReadFile(sealerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const boundReal = "func (s Sealer) Bound() bool { return s.bound }"
+ if !bytes.Contains(sealerSrc, []byte(boundReal)) {
+ t.Fatalf("sealer.go no longer declares %q; update the methodwrite fixture", boundReal)
}
+ overlay[sealerPath] = bytes.Replace(sealerSrc, []byte(boundReal), []byte("func (s Sealer) Bound() bool { s.bound = true; return s.bound }"), 1)
// The sealkey fixture's declarations go at the end of the real
// sealkey.go, whose imports they share.
sealkeyPath := filepath.Join(consoleDir, "sealkey.go")
@@ -516,11 +641,17 @@ func sgFixtures(t *testing.T, root string) (map[string][]byte, []string) {
"appconfig.Sealer.pub in " + sgAppconfig + ".sealGuardSealer",
"appconfig.Sealer.binding in " + sgAppconfig + ".sealGuardSealer",
"appconfig.Sealer.bound in " + sgAppconfig + ".sealGuardSealer",
- "appconfig.Sealer.pub in " + sgAppconfig + ".SealGuardFieldSealer",
- "appconfig.Sealer.fp in " + sgAppconfig + ".SealGuardFieldSealer",
- "appconfig.Sealer.binding in " + sgAppconfig + ".SealGuardFieldSealer",
- "appconfig.Sealer.bound in " + sgAppconfig + ".SealGuardFieldSealer",
+ "appconfig.Sealer.pub write in " + sgAppconfig + ".SealGuardFieldSealer",
+ "appconfig.Sealer.fp write in " + sgAppconfig + ".SealGuardFieldSealer",
+ "appconfig.Sealer.binding write in " + sgAppconfig + ".SealGuardFieldSealer",
+ "appconfig.Sealer.bound write in " + sgAppconfig + ".SealGuardFieldSealer",
sgAppconfig + ".sealWith in " + sgAppconfig + ".SealGuardAny",
sgChooseSealKey + " in " + server + ".sealGuardChoose",
+ "appconfig.Sealer.pub in (*" + sgAppconfig + ".Sealer).SealGuardFill",
+ "appconfig.Sealer.pub write in (*" + sgAppconfig + ".Sealer).SealGuardFill",
+ "appconfig.Sealer.fp write in (*" + sgAppconfig + ".Sealer).SealGuardFill",
+ "appconfig.Sealer.binding write in (*" + sgAppconfig + ".Sealer).SealGuardFill",
+ "appconfig.Sealer.bound write in (*" + sgAppconfig + ".Sealer).SealGuardFill",
+ "appconfig.Sealer.bound write in (" + sgAppconfig + ".Sealer).Bound",
}
}
diff --git a/internal/console/testdata/sealguard/ctor/method.go b/internal/console/testdata/sealguard/ctor/method.go
new file mode 100644
index 000000000..d6601b60c
--- /dev/null
+++ b/internal/console/testdata/sealguard/ctor/method.go
@@ -0,0 +1,15 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers, laid over
+// internal/appconfig: a new method on Sealer that fills a zero sealer's
+// fields from its arguments. Every method may touch the receiver it is
+// declared on, so without a named list of Sealer's own methods this would be
+// a second constructor: `var s appconfig.Sealer; s.SealGuardFill(pub, b)`.
+package appconfig
+
+import "crypto/ecdh"
+
+func (s *Sealer) SealGuardFill(pub *ecdh.PublicKey, b Binding) {
+ if s.pub != nil {
+ return
+ }
+ s.pub, s.fp, s.binding, s.bound = pub, KeyFingerprint(pub), b, true
+}
diff --git a/internal/console/testdata/sealguard/darwinonly/sealy/sealy.go b/internal/console/testdata/sealguard/darwinonly/sealy/sealy.go
new file mode 100644
index 000000000..b1c3a3283
--- /dev/null
+++ b/internal/console/testdata/sealguard/darwinonly/sealy/sealy.go
@@ -0,0 +1,17 @@
+//go:build darwin
+
+// A negative fixture of TestOnlySealKeyForBuildsSealers: a package whose
+// every file is for darwin. A linux listing of the module leaves the whole
+// package out, so neither the type-checked scan nor the linux build's
+// ignored files ever see it; the guard's walk of the source tree must.
+package sealy
+
+import (
+ "crypto/ecdh"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+)
+
+func SealAnything(pub *ecdh.PublicKey, b appconfig.Binding) appconfig.Sealer {
+ return appconfig.NewSealer(pub, b, true)
+}