carlos / platform Public

console: guard test that no JSON view carries a gate hash

TestConsoleJSONNeverCarriesGateHash type-checks internal/console and walks
the static type of every writeJSON, json.Marshal, json.MarshalIndent and
Encoder.Encode body (and of any function forwarding an interface
parameter to one) as encoding/json would, failing where
provision.Record.Gate or registry.Route.Gate is emitted unshadowed. A
negative-control fixture pins the walk; the two store/stamp marshals of a
whole record are named in gsNotResponses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2ebedc9bdb98bb2dc46a96c28dc67c223a631809 parent 3793aa4
1 file changed, +725 −0
  • internal/console/gate_shadow_guard_test.go +725 −0
diff --git a/internal/console/gate_shadow_guard_test.go b/internal/console/gate_shadow_guard_test.go
new file mode 100644
index 000000000..9f4fa6f96
--- /dev/null
+++ b/internal/console/gate_shadow_guard_test.go
@@ -0,0 +1,725 @@
+package console
+
+// TestConsoleJSONNeverCarriesGateHash guards the password gate's one secret:
+// provision.Record.Gate (and registry.Route.Gate, the converged copy) is an
+// app's bcrypt hash and never leaves the console. Every view that carries a
+// record today shadows it with a shallower `json:"gate,omitempty"` field that
+// is always "" (apiRecordView, instanceGetRecord, apiinstances.go). This test
+// makes that a rule for every future view rather than a habit.
+//
+// It type-checks the package once and finds every JSON sink in it, by the
+// callee's types.Func.FullName: writeJSON (its body), json.Marshal,
+// json.MarshalIndent and (*json.Encoder).Encode, plus every function of the
+// package that hands one of its own interface-typed parameters straight to a
+// sink (demoClaimReply, demoOperatorJSON, relayConn.send: a wrapper), found to
+// a fixed point. For each call it takes the static type of the body argument;
+// where that is an interface or holds interfaces (map[string]any), it looks
+// through a composite literal's values, an any(x) conversion and append's
+// arguments, and through a local variable to everything the enclosing
+// function assigns to it or to its elements. It then walks each type as
+// encoding/json would (exported fields; embedded structs promoted, with the
+// shallowest field of a JSON name winning, a tagged one breaking a tie and an
+// untied pair dropping both; pointers, slices, arrays and map values) and
+// fails where a Gate field wins under its own JSON name ("gate" for Record,
+// "Gate" for Route, which has no tag), naming the call site.
+//
+// json.Marshal also builds what the console stores, and a stored record must
+// keep its hash. Those few calls are named in gsNotResponses, by enclosing
+// function and body type; an entry that no longer matches fails.
+//
+// A type with its own MarshalJSON is walked as if it had none: the guard
+// cannot read what the method writes, so it assumes the fields
+// (registry.ColdRows marshals a whole Route that way). Not seen: a value
+// stored in a struct or map field and marshalled elsewhere (systemJob's
+// result), a map filled by a callee (echoCreatedRegion), and a sink reached
+// through a function value. Those still need a reviewer.
+//
+// A negative control type-checks a small in-memory package against the same
+// provision and registry types and must flag exactly its leak* functions.
+
+import (
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "go/types"
+ "path/filepath"
+ "reflect"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+
+ "golang.org/x/tools/go/packages"
+ "golang.org/x/tools/go/types/typeutil"
+)
+
+const (
+ gsProvision = "github.com/carlosframework/platform/internal/provision"
+ gsRegistry = "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestConsoleJSONNeverCarriesGateHash(t *testing.T) {
+ root, err := filepath.Abs(filepath.Join("..", ".."))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg := &packages.Config{Dir: root, Env: sgEnv(),
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax |
+ packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports,
+ }
+ pkgs, err := packages.Load(cfg, "./internal/console")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if packages.PrintErrors(pkgs) > 0 || len(pkgs) != 1 {
+ t.Fatal("loading internal/console failed")
+ }
+ pkg := pkgs[0]
+ deps := gsDeps(pkg.Types)
+ gates := gsGateFields(t, deps)
+
+ res := gsScan(pkg.Fset, pkg.TypesInfo, pkg.Syntax, pkg.Types, gates)
+ t.Logf("%d JSON sink calls checked; %d shadowed Gate fields seen; wrappers: %s",
+ res.calls, res.shadowed, strings.Join(res.wrappers, ", "))
+ used := map[string]bool{}
+ for _, f := range res.findings {
+ if slices.Contains(gsNotResponses[f.fn], f.root) {
+ used[f.fn] = true
+ continue
+ }
+ t.Errorf("%s: JSON body reaches the gate hash as %s; shadow it with a shallower HiddenGate string `json:\"gate,omitempty\"` (apiRecordView)", f.pos, f.path)
+ }
+ for fn := range gsNotResponses {
+ if !used[fn] {
+ t.Errorf("gsNotResponses names %s, which no longer marshals a gate hash; remove the entry", fn)
+ }
+ }
+ // The guard must have seen what it guards: the record views' shadows,
+ // and the sinks it is named for. Zero means it went blind (a field or
+ // sink renamed), not that the package is clean.
+ if res.calls < 100 || res.shadowed == 0 || len(res.wrappers) == 0 {
+ t.Errorf("guard saw %d sink calls, %d shadowed Gate fields, %d wrappers; it no longer finds what it checks", res.calls, res.shadowed, len(res.wrappers))
+ }
+
+ t.Run("negative control", func(t *testing.T) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, "gate_shadow_fixture.go", gsFixtureSrc, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ info := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{},
+ Uses: map[*ast.Ident]types.Object{}, Selections: map[*ast.SelectorExpr]*types.Selection{},
+ Instances: map[*ast.Ident]types.Instance{}}
+ conf := types.Config{Importer: gsImporter(deps)}
+ fix, err := conf.Check("example.com/gateshadowfixture", fset, []*ast.File{file}, info)
+ if err != nil {
+ t.Fatalf("type-check the fixture: %v", err)
+ }
+ res := gsScan(fset, info, []*ast.File{file}, fix, gates)
+ got := map[string]bool{}
+ for _, f := range res.findings {
+ got[f.in] = true
+ }
+ for _, d := range file.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok {
+ continue
+ }
+ name := fd.Name.Name
+ switch want := strings.HasPrefix(name, "leak"); {
+ case want && !got[name]:
+ t.Errorf("fixture %s leaks the gate hash but was not flagged", name)
+ case !want && got[name]:
+ t.Errorf("fixture %s shadows the gate hash but was flagged", name)
+ }
+ }
+ })
+}
+
+// gsFixtureSrc is the negative control. The first two are the plan's; the
+// rest pin each way the scan looks through a body.
+const gsFixtureSrc = `package gateshadowfixture
+
+import (
+ "encoding/json"
+ "io"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type v struct{ provision.Record }
+
+type w struct {
+ provision.Record
+ HiddenGate string ` + "`json:\"gate,omitempty\"`" + `
+}
+
+func leakEmbedded() { _, _ = json.Marshal(v{}) }
+
+func safeShadowed() { _, _ = json.Marshal(w{}) }
+
+// A shadow two levels up still wins.
+func safeShadowedDeeper() { _, _ = json.Marshal(struct{ w }{}) }
+
+// A shadow beside a named field does not reach into it.
+func leakNestedNotShadowed() {
+ _, _ = json.Marshal(struct {
+ Rec provision.Record ` + "`json:\"rec\"`" + `
+ HiddenGate string ` + "`json:\"gate,omitempty\"`" + `
+ }{})
+}
+
+// Route's Gate has no tag: it is emitted as "Gate", and a "gate" shadow
+// does not hide it.
+func leakRoute() {
+ _, _ = json.Marshal(struct {
+ registry.Route
+ HiddenGate string ` + "`json:\"gate,omitempty\"`" + `
+ }{})
+}
+
+func leakPointerSlice() { _, _ = json.MarshalIndent([]*provision.Record{}, "", " ") }
+
+func leakMapValue() { _, _ = json.Marshal(map[string]any{"ok": 1, "rec": map[string]any{"r": v{}}}) }
+
+func safeMapValue() { _, _ = json.Marshal(map[string]any{"rec": []w{}}) }
+
+func leakLocalMap() {
+ var rec provision.Record
+ out := map[string]any{"ok": true}
+ out["rec"] = &rec
+ _ = json.NewEncoder(io.Discard).Encode(out)
+}
+
+func leakConversion() { _, _ = json.Marshal(any(registry.Route{})) }
+
+// A struct literal's field values are its type's fields, already walked;
+// an interface field hides what it holds.
+func safeStructField() { _, _ = json.Marshal(w{Record: provision.Record{}}) }
+
+func leakInterfaceField() { _, _ = json.Marshal(struct{ X any }{X: v{}}) }
+
+func reply(dst io.Writer, body any) { _ = json.NewEncoder(dst).Encode(body) }
+
+func leakWrapper() { reply(io.Discard, map[string]v{}) }
+
+func safeWrapper() { reply(io.Discard, w{}) }
+
+func leakEncoderMethod() {
+ enc := json.NewEncoder(io.Discard)
+ _ = enc.Encode(struct{ R *registry.Route }{})
+}
+`
+
+// gsNotResponses are the json.Marshal calls that must carry the hash because
+// they are not answers: an enclosing function (FullName) and the body types it
+// may marshal whole. Adding one is a ruling; the reason goes beside it.
+var gsNotResponses = map[string][]string{
+ // The record a new lifetime writes to the bucket (Allocation.Body ->
+ // provision.WriteRecord): the bucket is where the hash lives.
+ "(*" + sgConsole + ".Server).createRecordWithLifetimeLocked": {gsProvision + ".Record"},
+ // An in-memory change stamp for the replica placement cache, compared
+ // and never sent.
+ sgConsole + ".replicaStamp": {gsProvision + ".Record"},
+}
+
+// gsGate is a guarded field and the JSON name it is emitted under.
+type gsGate struct {
+ owner string
+ name string
+}
+
+// gsGateFields finds Record.Gate and Route.Gate in the loaded types, so a
+// rename fails here rather than letting the guard go blind.
+func gsGateFields(t *testing.T, deps map[string]*types.Package) map[*types.Var]gsGate {
+ t.Helper()
+ out := map[*types.Var]gsGate{}
+ for _, want := range []struct{ pkg, typ string }{{gsProvision, "Record"}, {gsRegistry, "Route"}} {
+ p := deps[want.pkg]
+ if p == nil {
+ t.Fatalf("%s is not among internal/console's imports", want.pkg)
+ }
+ obj := p.Scope().Lookup(want.typ)
+ if obj == nil {
+ t.Fatalf("%s.%s not found; update the guard", want.pkg, want.typ)
+ }
+ st, ok := obj.Type().Underlying().(*types.Struct)
+ if !ok {
+ t.Fatalf("%s.%s is not a struct", want.pkg, want.typ)
+ }
+ found := false
+ for i := 0; i < st.NumFields(); i++ {
+ if f := st.Field(i); f.Name() == "Gate" {
+ name, _ := gsJSONName(st.Tag(i))
+ if name == "" {
+ name = "Gate"
+ }
+ out[f] = gsGate{owner: want.typ, name: name}
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("%s.%s has no Gate field; update the guard", want.pkg, want.typ)
+ }
+ }
+ return out
+}
+
+// gsDeps is every package internal/console reaches, by path.
+func gsDeps(p *types.Package) map[string]*types.Package {
+ out := map[string]*types.Package{}
+ var walk func(*types.Package)
+ walk = func(p *types.Package) {
+ if out[p.Path()] != nil {
+ return
+ }
+ out[p.Path()] = p
+ for _, q := range p.Imports() {
+ walk(q)
+ }
+ }
+ walk(p)
+ return out
+}
+
+type gsImporter map[string]*types.Package
+
+func (m gsImporter) Import(path string) (*types.Package, error) {
+ if p := m[path]; p != nil {
+ return p, nil
+ }
+ return nil, fmt.Errorf("import %q not loaded", path)
+}
+
+type gsFinding struct {
+ pos token.Position
+ in string // enclosing function's name, "" at package level
+ fn string // its types.Func.FullName
+ root string // the walked type, types.TypeString
+ path string // e.g. apiThing.Record.gate
+}
+
+type gsResult struct {
+ findings []gsFinding
+ calls int
+ shadowed int
+ wrappers []string
+}
+
+// gsScan finds every JSON sink call in files and walks its body's types.
+func gsScan(fset *token.FileSet, info *types.Info, files []*ast.File, pkg *types.Package, gates map[*types.Var]gsGate) gsResult {
+ // sinks: callee FullName -> indexes of the parameters it encodes.
+ sinks := map[string]map[int]bool{
+ "encoding/json.Marshal": {0: true},
+ "encoding/json.MarshalIndent": {0: true},
+ "(*encoding/json.Encoder).Encode": {0: true},
+ }
+ if fn, ok := pkg.Scope().Lookup("writeJSON").(*types.Func); ok {
+ sig := fn.Type().(*types.Signature)
+ for i := 0; i < sig.Params().Len(); i++ {
+ if sig.Params().At(i).Name() == "body" {
+ sinks[fn.FullName()] = map[int]bool{i: true}
+ }
+ }
+ }
+ calleeName := func(call *ast.CallExpr) string {
+ if fn, ok := typeutil.Callee(info, call).(*types.Func); ok {
+ return fn.FullName()
+ }
+ return ""
+ }
+
+ // Wrappers, to a fixed point: a function that passes its own
+ // interface-typed parameter, as is, to a sink's body is a sink.
+ var wrappers []string
+ for changed := true; changed; {
+ changed = false
+ for _, file := range files {
+ for _, d := range file.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ fn, _ := info.Defs[fd.Name].(*types.Func)
+ if fn == nil {
+ continue
+ }
+ params := fn.Type().(*types.Signature).Params()
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ for i := range sinks[calleeName(call)] {
+ if i >= len(call.Args) {
+ continue
+ }
+ id, ok := ast.Unparen(call.Args[i]).(*ast.Ident)
+ if !ok {
+ continue
+ }
+ for j := 0; j < params.Len(); j++ {
+ p := params.At(j)
+ if info.Uses[id] != p || !types.IsInterface(p.Type()) {
+ continue
+ }
+ if sinks[fn.FullName()] == nil {
+ sinks[fn.FullName()] = map[int]bool{}
+ wrappers = append(wrappers, strings.ReplaceAll(fn.FullName(), pkg.Path()+".", ""))
+ }
+ if !sinks[fn.FullName()][j] {
+ sinks[fn.FullName()][j] = true
+ changed = true
+ }
+ }
+ }
+ return true
+ })
+ }
+ }
+ }
+ sort.Strings(wrappers)
+
+ res := gsResult{wrappers: wrappers}
+ w := &gsWalker{gates: gates, memo: map[string][]string{}}
+ check := func(fd *ast.FuncDecl, n ast.Node) {
+ ast.Inspect(n, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ for i := range sinks[calleeName(call)] {
+ if i >= len(call.Args) {
+ continue
+ }
+ res.calls++
+ tr := &gsTracer{info: info, fn: fd, seen: map[types.Object]bool{}}
+ for _, typ := range tr.types(call.Args[i]) {
+ leaks, shadowed := w.walk(typ)
+ res.shadowed += shadowed
+ for _, l := range leaks {
+ f := gsFinding{pos: fset.Position(call.Pos()), root: types.TypeString(typ, nil), path: l}
+ if fd != nil {
+ f.in = fd.Name.Name
+ if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
+ f.fn = fn.FullName()
+ }
+ }
+ res.findings = append(res.findings, f)
+ }
+ }
+ }
+ return true
+ })
+ }
+ for _, file := range files {
+ for _, d := range file.Decls {
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ if fd.Body != nil {
+ check(fd, fd.Body)
+ }
+ continue
+ }
+ check(nil, d)
+ }
+ }
+ return res
+}
+
+// gsTracer finds the static types a sink's body argument can carry.
+type gsTracer struct {
+ info *types.Info
+ fn *ast.FuncDecl
+ seen map[types.Object]bool
+}
+
+func (tr *gsTracer) types(e ast.Expr) []types.Type {
+ e = ast.Unparen(e)
+ out := []types.Type{tr.info.TypeOf(e)}
+ switch x := e.(type) {
+ case *ast.CompositeLit:
+ // A literal's own type is walked above; its values only matter
+ // where the slot they fill is an interface, which hides them.
+ lit := tr.info.TypeOf(x)
+ if lit == nil {
+ break
+ }
+ for i, el := range x.Elts {
+ var key ast.Expr
+ if kv, ok := el.(*ast.KeyValueExpr); ok {
+ key, el = kv.Key, kv.Value
+ }
+ if gsHoldsInterface(tr.slot(lit, key, i)) {
+ out = append(out, tr.types(el)...)
+ }
+ }
+ case *ast.UnaryExpr:
+ if x.Op == token.AND {
+ out = append(out, tr.types(x.X)...)
+ }
+ case *ast.CallExpr:
+ if tv, ok := tr.info.Types[x.Fun]; ok && tv.IsType() && len(x.Args) == 1 {
+ out = append(out, tr.types(x.Args[0])...) // any(x)
+ } else if b, ok := tr.builtin(x); ok && b == "append" {
+ for _, a := range x.Args {
+ out = append(out, tr.types(a)...)
+ }
+ }
+ case *ast.Ident:
+ v, ok := tr.info.Uses[x].(*types.Var)
+ if !ok || v.IsField() || tr.fn == nil || tr.seen[v] || !gsHoldsInterface(v.Type()) {
+ break
+ }
+ tr.seen[v] = true
+ out = append(out, tr.assigned(v)...)
+ }
+ return out
+}
+
+// slot is the type the i'th element of a composite literal of type lit
+// fills: a map's or a list's element type, or a struct's field.
+func (tr *gsTracer) slot(lit types.Type, key ast.Expr, i int) types.Type {
+ switch u := lit.Underlying().(type) {
+ case *types.Map:
+ return u.Elem()
+ case *types.Slice:
+ return u.Elem()
+ case *types.Array:
+ return u.Elem()
+ case *types.Struct:
+ if id, ok := key.(*ast.Ident); ok {
+ if f, ok := tr.info.Uses[id].(*types.Var); ok {
+ return f.Type()
+ }
+ } else if key == nil && i < u.NumFields() {
+ return u.Field(i).Type()
+ }
+ }
+ return types.Typ[types.Invalid]
+}
+
+func (tr *gsTracer) builtin(call *ast.CallExpr) (string, bool) {
+ id, ok := ast.Unparen(call.Fun).(*ast.Ident)
+ if !ok {
+ return "", false
+ }
+ b, ok := tr.info.Uses[id].(*types.Builtin)
+ if !ok {
+ return "", false
+ }
+ return b.Name(), true
+}
+
+// assigned is every type the enclosing function stores in v or in v's
+// elements (v[k] = x).
+func (tr *gsTracer) assigned(v *types.Var) []types.Type {
+ is := func(e ast.Expr) bool {
+ id, ok := ast.Unparen(e).(*ast.Ident)
+ return ok && (tr.info.Uses[id] == v || tr.info.Defs[id] == v)
+ }
+ var out []types.Type
+ ast.Inspect(tr.fn, func(n ast.Node) bool {
+ switch s := n.(type) {
+ case *ast.AssignStmt:
+ if len(s.Lhs) != len(s.Rhs) {
+ break
+ }
+ for i, l := range s.Lhs {
+ if ix, ok := l.(*ast.IndexExpr); ok && is(ix.X) || is(l) {
+ out = append(out, tr.types(s.Rhs[i])...)
+ }
+ }
+ case *ast.ValueSpec:
+ for i, name := range s.Names {
+ if tr.info.Defs[name] == v && i < len(s.Values) {
+ out = append(out, tr.types(s.Values[i])...)
+ }
+ }
+ }
+ return true
+ })
+ return out
+}
+
+// gsHoldsInterface reports whether a value of t can hide another type: an
+// interface, or a map, slice or array of them.
+func gsHoldsInterface(t types.Type) bool {
+ switch u := t.Underlying().(type) {
+ case *types.Interface:
+ return true
+ case *types.Map:
+ return gsHoldsInterface(u.Elem())
+ case *types.Slice:
+ return gsHoldsInterface(u.Elem())
+ case *types.Array:
+ return gsHoldsInterface(u.Elem())
+ }
+ return false
+}
+
+// gsWalker walks a type as encoding/json encodes it.
+type gsWalker struct {
+ gates map[*types.Var]gsGate
+ memo map[string][]string // type -> leak paths; an entry in progress is nil
+ shad int
+}
+
+// walk returns the paths by which t emits a gate field, and how many gate
+// fields a shallower field shadowed on the way.
+func (w *gsWalker) walk(t types.Type) ([]string, int) {
+ w.shad = 0
+ leaks := w.value(t)
+ return leaks, w.shad
+}
+
+func (w *gsWalker) value(t types.Type) []string {
+ if t == nil {
+ return nil
+ }
+ for {
+ p, ok := t.Underlying().(*types.Pointer)
+ if !ok {
+ break
+ }
+ t = p.Elem()
+ }
+ key := types.TypeString(t, nil)
+ if leaks, done := w.memo[key]; done {
+ return leaks
+ }
+ w.memo[key] = nil // a cycle adds nothing new
+ var leaks []string
+ switch u := t.Underlying().(type) {
+ case *types.Struct:
+ label := types.TypeString(t, func(p *types.Package) string { return p.Name() })
+ for _, f := range w.fields(u) {
+ if g, ok := w.gates[f.v]; ok {
+ if f.name == g.name {
+ leaks = append(leaks, label+"."+g.owner+"."+f.name)
+ }
+ continue
+ }
+ for _, l := range w.value(f.v.Type()) {
+ leaks = append(leaks, label+"."+f.name+" -> "+l)
+ }
+ }
+ case *types.Slice:
+ leaks = w.value(u.Elem())
+ case *types.Array:
+ leaks = w.value(u.Elem())
+ case *types.Map:
+ leaks = w.value(u.Elem())
+ }
+ w.memo[key] = leaks
+ return leaks
+}
+
+type gsField struct {
+ name string
+ tagged bool
+ depth int
+ v *types.Var
+}
+
+// fields is encoding/json's typeFields over go/types: the fields a struct
+// emits, after promotion and dominance. A gate field that loses to a
+// shallower or tagged one of its name is counted as shadowed.
+func (w *gsWalker) fields(st *types.Struct) []gsField {
+ type scan struct {
+ st *types.Struct
+ key string
+ depth int
+ }
+ var all []gsField
+ next := []scan{{st: st, key: types.TypeString(st, nil)}}
+ var count, nextCount map[string]int
+ visited := map[string]bool{}
+ for len(next) > 0 {
+ current := next
+ next = nil
+ count, nextCount = nextCount, map[string]int{}
+ for _, s := range current {
+ if visited[s.key] {
+ continue
+ }
+ visited[s.key] = true
+ for i := 0; i < s.st.NumFields(); i++ {
+ sf := s.st.Field(i)
+ ft := sf.Type()
+ if p, ok := ft.(*types.Pointer); ok {
+ ft = p.Elem()
+ }
+ _, isStruct := ft.Underlying().(*types.Struct)
+ if sf.Embedded() {
+ if !sf.Exported() && !isStruct {
+ continue
+ }
+ } else if !sf.Exported() {
+ continue
+ }
+ name, skip := gsJSONName(s.st.Tag(i))
+ if skip {
+ continue
+ }
+ if name != "" || !sf.Embedded() || !isStruct {
+ f := gsField{name: name, tagged: name != "", depth: s.depth, v: sf}
+ if f.name == "" {
+ f.name = sf.Name()
+ }
+ all = append(all, f)
+ if count[s.key] > 1 {
+ all = append(all, f) // embedded twice at this depth: annihilates
+ }
+ continue
+ }
+ key := types.TypeString(ft, nil)
+ nextCount[key]++
+ if nextCount[key] == 1 {
+ next = append(next, scan{st: ft.Underlying().(*types.Struct), key: key, depth: s.depth + 1})
+ }
+ }
+ }
+ }
+ sort.SliceStable(all, func(i, j int) bool {
+ if all[i].name != all[j].name {
+ return all[i].name < all[j].name
+ }
+ if all[i].depth != all[j].depth {
+ return all[i].depth < all[j].depth
+ }
+ return all[i].tagged && !all[j].tagged
+ })
+ var out []gsField
+ for i := 0; i < len(all); {
+ j := i + 1
+ for j < len(all) && all[j].name == all[i].name {
+ j++
+ }
+ group := all[i:j]
+ win := -1
+ if len(group) == 1 || group[0].depth != group[1].depth || group[0].tagged != group[1].tagged {
+ win = 0
+ out = append(out, group[0])
+ }
+ for k, f := range group {
+ if _, ok := w.gates[f.v]; ok && k != win {
+ w.shad++
+ }
+ }
+ i = j
+ }
+ return out
+}
+
+// gsJSONName is a field's json tag name ("" for none) and whether the tag
+// drops the field.
+func gsJSONName(tag string) (string, bool) {
+ v := reflect.StructTag(tag).Get("json")
+ if v == "-" {
+ return "", true
+ }
+ name, _, _ := strings.Cut(v, ",")
+ return name, false
+}