carlos / platform Public

console: guard that no JSON response carries a gate hash

A type-aware test walks every JSON response the console builds
(writeJSON, json.Marshal, Encoder.Encode and their wrappers, helper
returns, locals, custom marshallers) and fails if provision.Record.Gate
or registry.Route.Gate can reach the wire unshadowed. Gate cookies are
keyed from that bcrypt hash, so it must never leave the console. No
leak on main. Also corrects the GO-2026-6859 note in go-toolchain.sh;
the 1.26.10 pin is unchanged.

From the 2026-11-16 security review (discussion 1096). Reviewed by
Astra (round 1, P2s fixed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from sec-gate-shadow-guard into main.
claude agent, operated by paul@keymail.dev c3bd7b3fa4052e0ee833c8fcb06a825f3ec99bac parent 3793aa4
2 files changed, +1,400 −2
  • .amadan/go-toolchain.sh +10 −2
  • internal/console/gate_shadow_guard_test.go +1,390 −0

CI cancelled — superseded by a newer push — run details

diff --git a/.amadan/go-toolchain.sh b/.amadan/go-toolchain.sh
index e2f45b1aa..549fe8de5 100644
--- a/.amadan/go-toolchain.sh
+++ b/.amadan/go-toolchain.sh
@@ -15,8 +15,16 @@
# only switches to a toolchain line NEWER than the local one. GOTOOLCHAIN
# does downgrade. "+auto" still lets a go.mod that needs a newer Go fetch it.
#
-# Re-check when Go ships a fix for the deadlock: move this to that version
-# (it also carries GO-2026-6859), with the early subtests as the witness.
+# Re-check when Go ships a fix for the deadlock: move this to that version,
+# with the early subtests as the witness.
+#
+# GO-2026-6859 is present in 1.26.10. Triggering it needs a request body
+# that exceeds its MaxBytesReader limit, read on another goroutine than the
+# handler's while the handler writes headers, with net/http's own response
+# writer passed to MaxBytesReader; #904 checked every production
+# MaxBytesReader site and found none. Go 1.26.11 contains both the
+# GO-2026-6859 fix and a separate change that deadlocks the edge proxy, and
+# no release yet has the fix without the deadlock.
GOTOOLCHAIN=go1.26.10+auto
export GOTOOLCHAIN
go version
diff --git a/internal/console/gate_shadow_guard_test.go b/internal/console/gate_shadow_guard_test.go
new file mode 100644
index 000000000..a8229571b
--- /dev/null
+++ b/internal/console/gate_shadow_guard_test.go
@@ -0,0 +1,1390 @@
+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 whose sink body can carry one of its own interface-holding
+// parameters (demoClaimReply, relayConn.send, or one that wraps the parameter
+// in a map: a wrapper), found to a fixed point.
+//
+// For each call it takes the static type of the body argument. Where a value
+// can hide another type (an interface, or a map, slice, array, pointer or
+// struct holding one) it follows the value back: a composite literal's
+// values in such slots, any(x), append, a type assertion, a local variable or
+// one of its fields or elements to everything the function assigns there
+// (multi-result and range assignments included), and a call to a function of
+// the package into its return expressions, binding its parameters to the
+// call's arguments. What it cannot follow (a function value, a callee given a
+// map or pointer to fill, a package variable, a struct field read off a
+// parameter, a call outside the package) is an unresolved site, and
+// gsUnresolved pins that inventory: a site appearing or disappearing fails,
+// so a new blind spot is always seen and checked by hand.
+//
+// Each type is then walked as encoding/json walks it (exported fields;
+// embedded structs promoted, the shallowest field of a JSON name winning, a
+// tagged one breaking a tie and an untied pair dropping both; invalid tag
+// names ignored; pointers, slices, arrays and map values), failing where a
+// Gate field wins under its own JSON name ("gate" for Record, "Gate" for
+// Route, which has no tag). A type whose method set, promoted methods
+// included, has MarshalJSON or MarshalText is not encoded field by field, so
+// no shadow protects it: every field it holds, exported or not, is walked,
+// and any Gate reached fails (registry.ColdRows writes its whole Route).
+//
+// 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 negative control type-checks a small in-memory package against the same
+// provision and registry types: exactly its leak* functions must be flagged
+// and exactly its unresolved* functions reported as unresolved.
+
+import (
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "go/types"
+ "path/filepath"
+ "reflect"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+ "unicode"
+
+ "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"
+)
+
+// 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"},
+}
+
+// gsUnresolved is every place a JSON body's value comes from that the guard
+// cannot follow, as "function: kind expression". Each was read by hand and
+// carries no record or route. A new one fails until it is made traceable or
+// read and added; one that disappears fails until removed.
+var gsUnresolved = []string{
+ // stamp is a local func value: nil, or a time formatted RFC 3339.
+ "(*Server).handleAPIAppList: call stamp",
+ // region is filled by echoCreatedRegion inside a closure: region codes,
+ // names, a label, a source and the available list, no record.
+ "(*Server).handleAPICreateApp: handed to maps.Copy",
+ // The job comes from s.systemJobs; its Result is set only by
+ // setResult, whose one caller (apisystemgeoip.go) stores a
+ // geoip.Pointer.
+ "(*Server).handleAPISystemJob: receiver s",
+}
+
+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; %d unresolved sites; wrappers: %s",
+ res.calls, res.shadowed, len(res.open), 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)
+ }
+ }
+ for _, k := range gsSortedKeys(res.open) {
+ if !slices.Contains(gsUnresolved, k) {
+ t.Errorf("%s: the guard cannot follow %q into a JSON body; make it traceable, or read it by hand and add it to gsUnresolved", res.open[k].pos, k)
+ }
+ }
+ for _, k := range gsUnresolved {
+ if _, ok := res.open[k]; !ok {
+ t.Errorf("gsUnresolved lists %q, which the guard no longer finds; remove it", k)
+ }
+ }
+ // 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{}, Implicits: map[ast.Node]types.Object{}}
+ 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)
+ flagged, open := map[string]bool{}, map[string]bool{}
+ for _, f := range res.findings {
+ flagged[f.in] = true
+ }
+ for _, o := range res.open {
+ open[o.in] = true
+ }
+ for _, d := range file.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok {
+ continue
+ }
+ name := fd.Name.Name
+ switch leak := strings.HasPrefix(name, "leak"); {
+ case leak && !flagged[name]:
+ t.Errorf("fixture %s leaks the gate hash but was not flagged", name)
+ case !leak && flagged[name]:
+ t.Errorf("fixture %s shadows the gate hash but was flagged", name)
+ }
+ switch unres := strings.HasPrefix(name, "unresolved"); {
+ case unres && !open[name]:
+ t.Errorf("fixture %s cannot be followed but was not reported unresolved", name)
+ case !unres && open[name]:
+ t.Errorf("fixture %s was reported unresolved", name)
+ }
+ }
+ if t.Failed() {
+ for _, k := range gsSortedKeys(res.open) {
+ t.Logf("unresolved: %s", k)
+ }
+ }
+ })
+}
+
+// gsFixtureSrc is the negative control. Each leak* function must be flagged,
+// each unresolved* one reported unresolved, and nothing else either.
+const gsFixtureSrc = `package gateshadowfixture
+
+import (
+ "encoding/json"
+ "io"
+ "maps"
+ "time"
+
+ "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 }{})
+}
+
+// Returns of the package's own functions, with their parameters bound.
+func answer() map[string]any { return map[string]any{"rec": provision.Record{}} }
+
+func leakHelperReturn() { _, _ = json.Marshal(answer()) }
+
+func wrapIt(x any) map[string]any {
+ out := map[string]any{}
+ out["x"] = x
+ return out
+}
+
+func leakHelperParam() { _, _ = json.Marshal(wrapIt(v{})) }
+
+func safeHelperParam() { _, _ = json.Marshal(wrapIt(w{})) }
+
+func scanReply() (any, error) { return v{}, nil }
+
+func leakMultiResult() {
+ reply, err := scanReply()
+ if err != nil {
+ return
+ }
+ _, _ = json.Marshal(reply)
+}
+
+func named() (out any) {
+ out = &v{}
+ return
+}
+
+func leakNamedResult() { _, _ = json.Marshal(named()) }
+
+// Structs held in locals.
+func leakStructLocal() {
+ resp := struct{ X any }{X: v{}}
+ _, _ = json.Marshal(resp)
+}
+
+func leakStructFieldAssign() {
+ var resp struct{ X any }
+ resp.X = []v{}
+ _, _ = json.Marshal(&resp)
+}
+
+func leakRange() {
+ items := []any{v{}}
+ for _, it := range items {
+ _, _ = json.Marshal(it)
+ }
+}
+
+// A wrapper that wraps its parameter before encoding it.
+func replyData(dst io.Writer, body any) {
+ _ = json.NewEncoder(dst).Encode(map[string]any{"data": body})
+}
+
+func leakWrapperWrapsParam() { replyData(io.Discard, v{}) }
+
+func safeWrapperWrapsParam() { replyData(io.Discard, w{}) }
+
+// A promoted MarshalJSON makes the shadow useless: ColdRows writes its
+// whole Route.
+type coldView struct {
+ registry.ColdRows
+ Route struct{}
+}
+
+func leakPromotedMarshaler() { _, _ = json.Marshal(coldView{}) }
+
+func safeMarshaler() { _, _ = json.Marshal(struct{ At time.Time }{}) }
+
+// Two local types of one name are two types.
+func safeLocalType() {
+ type response struct{ OK bool }
+ _, _ = json.Marshal(response{})
+}
+
+func leakLocalType() {
+ type response struct{ provision.Record }
+ _, _ = json.Marshal(response{})
+}
+
+// An invalid tag name is ignored: A and B keep their Go names, both emitted.
+func leakInvalidTags() {
+ _, _ = json.Marshal(struct {
+ A provision.Record ` + "`json:\"\\t\"`" + `
+ B provision.Record ` + "`json:\"\\t\"`" + `
+ }{})
+}
+
+// A map or receiver a function of the package fills.
+func fill(m map[string]any) { m["rec"] = v{} }
+
+func leakFilledByCallee() {
+ out := make(map[string]any)
+ fill(out)
+ _, _ = json.Marshal(out)
+}
+
+type bag struct{ M map[string]any }
+
+func (b *bag) put(x any) { b.M["x"] = x }
+
+func leakFilledByMethod() {
+ b := bag{M: map[string]any{}}
+ b.put(v{})
+ _, _ = json.Marshal(b)
+}
+
+// What the guard cannot follow.
+func unresolvedCallee() {
+ out := map[string]any{}
+ maps.Copy(out, map[string]any{})
+ _, _ = json.Marshal(out)
+}
+
+func unresolvedFuncValue() {
+ f := func() any { return v{} }
+ _, _ = json.Marshal(f())
+}
+
+var held any
+
+func unresolvedPackageVar() { _, _ = json.Marshal(held) }
+`
+
+// 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)
+}
+
+func gsSortedKeys[V any](m map[string]V) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+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
+}
+
+// gsOpen is one place a body's value comes from that the trace cannot follow.
+type gsOpen struct {
+ pos token.Position
+ in string // the function it is in, by name
+}
+
+type gsResult struct {
+ findings []gsFinding
+ open map[string]gsOpen // by "function: kind expression"
+ calls int
+ shadowed int
+ wrappers []string
+}
+
+// gsScanner holds what one package's scan shares.
+type gsScanner struct {
+ fset *token.FileSet
+ info *types.Info
+ pkg *types.Package
+ decls map[*types.Func]*ast.FuncDecl
+ sinks map[string]map[int]bool // callee FullName -> body parameter indexes
+ hidem typeutil.Map // types.Type -> bool
+}
+
+func (sc *gsScanner) sinkParams(call *ast.CallExpr) map[int]bool {
+ if fn, ok := typeutil.Callee(sc.info, call).(*types.Func); ok {
+ return sc.sinks[fn.Origin().FullName()]
+ }
+ return nil
+}
+
+func (sc *gsScanner) short(fn *types.Func) string {
+ return strings.ReplaceAll(fn.FullName(), sc.pkg.Path()+".", "")
+}
+
+// hides reports whether a value of t can carry a type its static type does
+// not show: an interface, or a pointer, map, slice, array or struct holding
+// one.
+func (sc *gsScanner) hides(t types.Type) bool {
+ if t == nil {
+ return false
+ }
+ if r := sc.hidem.At(t); r != nil {
+ return r.(bool)
+ }
+ sc.hidem.Set(t, false) // a cycle adds nothing
+ h := false
+ switch u := t.Underlying().(type) {
+ case *types.Interface:
+ h = true
+ case *types.Pointer:
+ h = sc.hides(u.Elem())
+ case *types.Slice:
+ h = sc.hides(u.Elem())
+ case *types.Array:
+ h = sc.hides(u.Elem())
+ case *types.Map:
+ h = sc.hides(u.Elem())
+ case *types.Struct:
+ for i := 0; i < u.NumFields() && !h; i++ {
+ f := u.Field(i)
+ h = (f.Exported() || f.Embedded()) && sc.hides(f.Type())
+ }
+ }
+ sc.hidem.Set(t, h)
+ return h
+}
+
+// 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 {
+ sc := &gsScanner{fset: fset, info: info, pkg: pkg, decls: map[*types.Func]*ast.FuncDecl{},
+ sinks: map[string]map[int]bool{
+ "encoding/json.Marshal": {0: true},
+ "encoding/json.MarshalIndent": {0: true},
+ "(*encoding/json.Encoder).Encode": {0: true},
+ }}
+ for _, file := range files {
+ for _, d := range file.Decls {
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
+ sc.decls[fn] = fd
+ }
+ }
+ }
+ }
+ 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" {
+ sc.sinks[fn.FullName()] = map[int]bool{i: true}
+ }
+ }
+ }
+ // eachSink calls visit for every sink body argument in n.
+ eachSink := func(n ast.Node, visit func(arg ast.Expr, call *ast.CallExpr)) {
+ ast.Inspect(n, func(n ast.Node) bool {
+ if call, ok := n.(*ast.CallExpr); ok {
+ for i := range sc.sinkParams(call) {
+ if i < len(call.Args) {
+ visit(call.Args[i], call)
+ }
+ }
+ }
+ return true
+ })
+ }
+
+ // Wrappers, to a fixed point: a function whose sink body can carry its
+ // own parameter is a sink for that parameter.
+ var wrappers []string
+ for changed := true; changed; {
+ changed = false
+ for fn, fd := range sc.decls {
+ if fd.Body == nil {
+ continue
+ }
+ eachSink(fd.Body, func(arg ast.Expr, _ *ast.CallExpr) {
+ tr := sc.trace()
+ tr.types(&gsFrame{decl: fd, fn: fn}, arg)
+ for j := range tr.hits {
+ name := fn.FullName()
+ if sc.sinks[name] == nil {
+ sc.sinks[name] = map[int]bool{}
+ wrappers = append(wrappers, sc.short(fn))
+ }
+ if !sc.sinks[name][j] {
+ sc.sinks[name][j] = true
+ changed = true
+ }
+ }
+ })
+ }
+ }
+ sort.Strings(wrappers)
+
+ res := gsResult{wrappers: wrappers, open: map[string]gsOpen{}}
+ w := &gsWalker{gates: gates}
+ for _, file := range files {
+ for _, d := range file.Decls {
+ frame := &gsFrame{}
+ var n ast.Node = d
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ if fd.Body == nil {
+ continue
+ }
+ fn, _ := info.Defs[fd.Name].(*types.Func)
+ frame, n = &gsFrame{decl: fd, fn: fn}, fd.Body
+ }
+ eachSink(n, func(arg ast.Expr, call *ast.CallExpr) {
+ res.calls++
+ tr := sc.trace()
+ for _, typ := range tr.types(frame, arg) {
+ 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 frame.fn != nil {
+ f.in, f.fn = frame.fn.Name(), frame.fn.FullName()
+ }
+ res.findings = append(res.findings, f)
+ }
+ }
+ for k, o := range tr.open {
+ if _, ok := res.open[k]; !ok {
+ res.open[k] = o
+ }
+ }
+ })
+ }
+ }
+ return res
+}
+
+// gsFrame is one function the trace is in. A frame entered through a call
+// binds the callee's parameters (and receiver) to the call's arguments,
+// read in the caller's frame.
+type gsFrame struct {
+ decl *ast.FuncDecl // nil at package level
+ fn *types.Func
+ caller *gsFrame
+ args map[*types.Var]ast.Expr
+}
+
+// gsTrace follows one sink body argument back to the types it can carry.
+type gsTrace struct {
+ sc *gsScanner
+ followed map[*ast.CallExpr]bool
+ hand map[gsHand]bool
+ seen map[gsSeen]bool
+ hits map[int]bool // the outermost function's parameters reached
+ open map[string]gsOpen
+}
+
+type gsSeen struct {
+ f *gsFrame
+ v *types.Var
+}
+
+func (sc *gsScanner) trace() *gsTrace {
+ return &gsTrace{sc: sc, followed: map[*ast.CallExpr]bool{}, hand: map[gsHand]bool{}, seen: map[gsSeen]bool{},
+ hits: map[int]bool{}, open: map[string]gsOpen{}}
+}
+
+func (tr *gsTrace) unresolved(f *gsFrame, kind string, e ast.Expr) {
+ in, name := "package level", ""
+ if f.fn != nil {
+ in, name = tr.sc.short(f.fn), f.fn.Name()
+ }
+ k := in + ": " + kind + " " + types.ExprString(e)
+ if _, ok := tr.open[k]; !ok {
+ tr.open[k] = gsOpen{pos: tr.sc.fset.Position(e.Pos()), in: name}
+ }
+}
+
+// types is e's static type and, where e can hide others, every type it can
+// carry.
+func (tr *gsTrace) types(f *gsFrame, e ast.Expr) []types.Type {
+ info := tr.sc.info
+ e = ast.Unparen(e)
+ t := info.TypeOf(e)
+ out := []types.Type{t}
+ hides := tr.sc.hides(t)
+ switch x := e.(type) {
+ case *ast.CompositeLit:
+ // Values only matter in slots that hide them.
+ if t == 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 tr.sc.hides(tr.slot(t, key, i)) {
+ out = append(out, tr.types(f, el)...)
+ }
+ }
+ case *ast.UnaryExpr:
+ if x.Op == token.AND {
+ out = append(out, tr.types(f, x.X)...)
+ } else if hides {
+ tr.unresolved(f, "expression", x)
+ }
+ case *ast.CallExpr:
+ if !hides {
+ break
+ }
+ if tv, ok := info.Types[x.Fun]; ok && tv.IsType() {
+ if len(x.Args) == 1 {
+ out = append(out, tr.types(f, x.Args[0])...) // any(x)
+ }
+ break
+ }
+ if b, ok := tr.builtin(x); ok {
+ if b == "make" || b == "new" {
+ break // an empty value: it carries what is assigned to it later
+ }
+ if b != "append" {
+ tr.unresolved(f, "builtin", x)
+ break
+ }
+ for _, a := range x.Args {
+ out = append(out, tr.types(f, a)...)
+ }
+ break
+ }
+ out = append(out, tr.results(f, x, 0)...)
+ case *ast.Ident:
+ if hides {
+ out = append(out, tr.ident(f, x)...)
+ }
+ case *ast.SelectorExpr, *ast.IndexExpr, *ast.StarExpr:
+ if hides {
+ out = append(out, tr.rooted(f, e)...)
+ }
+ case *ast.TypeAssertExpr:
+ if hides {
+ out = append(out, tr.types(f, x.X)...)
+ }
+ case *ast.BasicLit, *ast.FuncLit:
+ default:
+ if hides {
+ tr.unresolved(f, "expression", e)
+ }
+ }
+ 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 *gsTrace) 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.sc.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 *gsTrace) builtin(call *ast.CallExpr) (string, bool) {
+ id, ok := ast.Unparen(call.Fun).(*ast.Ident)
+ if !ok {
+ return "", false
+ }
+ b, ok := tr.sc.info.Uses[id].(*types.Builtin)
+ if !ok {
+ return "", false
+ }
+ return b.Name(), true
+}
+
+// rooted follows a field, element or dereference back to the value it is
+// read from; everything that value can carry covers the part.
+func (tr *gsTrace) rooted(f *gsFrame, e ast.Expr) []types.Type {
+ x := e
+ for {
+ switch y := ast.Unparen(x).(type) {
+ case *ast.SelectorExpr:
+ sel := tr.sc.info.Selections[y]
+ if sel == nil { // a qualified identifier: another package's variable
+ return tr.ident(f, y.Sel)
+ }
+ if sel.Kind() != types.FieldVal {
+ tr.unresolved(f, "method value", e)
+ return nil
+ }
+ x = y.X
+ case *ast.IndexExpr:
+ x = y.X
+ case *ast.StarExpr:
+ x = y.X
+ case *ast.Ident:
+ return tr.ident(f, y)
+ default:
+ return tr.types(f, y)
+ }
+ }
+}
+
+// ident follows a variable: a bound parameter to its argument, the
+// outermost function's parameter to a wrapper hit, and a local to
+// everything assigned to it.
+func (tr *gsTrace) ident(f *gsFrame, id *ast.Ident) []types.Type {
+ v, ok := tr.sc.info.Uses[id].(*types.Var)
+ if !ok {
+ return nil // a constant, function or nil
+ }
+ return tr.variable(f, v, id)
+}
+
+func (tr *gsTrace) variable(f *gsFrame, v *types.Var, id ast.Expr) []types.Type {
+ if v.Pkg() != tr.sc.pkg || v.Parent() == tr.sc.pkg.Scope() {
+ tr.unresolved(f, "package variable", id)
+ return nil
+ }
+ if f.decl == nil {
+ tr.unresolved(f, "variable", id)
+ return nil
+ }
+ k := gsSeen{f, v}
+ if tr.seen[k] {
+ return nil
+ }
+ tr.seen[k] = true
+ var out []types.Type
+ sig := f.fn.Type().(*types.Signature)
+ isParam := false
+ if arg, ok := f.args[v]; ok {
+ isParam = true
+ out = append(out, tr.types(f.caller, arg)...)
+ } else if v == sig.Recv() {
+ tr.unresolved(f, "receiver", id)
+ return nil
+ } else {
+ for j := 0; j < sig.Params().Len(); j++ {
+ if sig.Params().At(j) != v {
+ continue
+ }
+ isParam = true
+ if f.caller == nil {
+ tr.hits[j] = true
+ } else {
+ tr.unresolved(f, "parameter", id)
+ }
+ }
+ for j := 0; j < sig.Results().Len(); j++ {
+ if sig.Results().At(j) == v {
+ isParam = true // a named result, assigned in the body
+ }
+ }
+ }
+ got, defined := tr.assigned(f, v)
+ out = append(out, got...)
+ if !defined && !isParam {
+ tr.unresolved(f, "variable", id)
+ }
+ return out
+}
+
+// gsRootIs reports whether e is v or a field, element or dereference of it.
+func gsRootIs(info *types.Info, e ast.Expr, v *types.Var) bool {
+ for {
+ switch y := ast.Unparen(e).(type) {
+ case *ast.SelectorExpr:
+ if sel := info.Selections[y]; sel == nil || sel.Kind() != types.FieldVal {
+ return false
+ }
+ e = y.X
+ case *ast.IndexExpr:
+ e = y.X
+ case *ast.StarExpr:
+ e = y.X
+ case *ast.Ident:
+ return info.Uses[y] == v || info.Defs[y] == v
+ default:
+ return false
+ }
+ }
+}
+
+// assigned is every type the frame's function stores in v or in a part of
+// it, and whether it defines v. A map or pointer handed to a callee, or a
+// method called on v, may be filled where the trace cannot see: unresolved.
+func (tr *gsTrace) assigned(f *gsFrame, v *types.Var) (out []types.Type, defined bool) {
+ info := tr.sc.info
+ isV := func(e ast.Expr) bool {
+ id, ok := ast.Unparen(e).(*ast.Ident)
+ return ok && (info.Uses[id] == v || info.Defs[id] == v)
+ }
+ ast.Inspect(f.decl, func(n ast.Node) bool {
+ switch s := n.(type) {
+ case *ast.AssignStmt:
+ for i, l := range s.Lhs {
+ if !gsRootIs(info, l, v) {
+ continue
+ }
+ if isV(l) {
+ defined = true
+ }
+ switch {
+ case len(s.Lhs) == len(s.Rhs):
+ out = append(out, tr.types(f, s.Rhs[i])...)
+ case len(s.Rhs) == 1:
+ out = append(out, tr.multi(f, s.Rhs[0], i)...)
+ }
+ }
+ case *ast.ValueSpec:
+ for i, name := range s.Names {
+ if info.Defs[name] != v {
+ continue
+ }
+ defined = true
+ switch {
+ case len(s.Values) == len(s.Names):
+ out = append(out, tr.types(f, s.Values[i])...)
+ case len(s.Values) == 1:
+ out = append(out, tr.multi(f, s.Values[0], i)...)
+ }
+ }
+ case *ast.RangeStmt:
+ if (s.Key != nil && isV(s.Key)) || (s.Value != nil && isV(s.Value)) {
+ defined = true
+ out = append(out, tr.types(f, s.X)...)
+ }
+ case *ast.CallExpr:
+ if tr.sc.sinkParams(s) != nil {
+ break
+ }
+ if _, ok := tr.builtin(s); ok {
+ break
+ }
+ fn, _ := typeutil.Callee(info, s).(*types.Func)
+ var sig *types.Signature
+ if fn != nil {
+ fn = fn.Origin()
+ sig = fn.Type().(*types.Signature)
+ }
+ if sel, ok := ast.Unparen(s.Fun).(*ast.SelectorExpr); ok && isV(sel.X) && !types.IsInterface(v.Type()) {
+ if m := info.Selections[sel]; m != nil && m.Kind() == types.MethodVal {
+ var recv *types.Var
+ if sig != nil {
+ recv = sig.Recv()
+ }
+ out = append(out, tr.handed(f, s, fn, recv, "method call")...)
+ }
+ }
+ for j, a := range s.Args {
+ a = ast.Unparen(a)
+ u, ok := a.(*ast.UnaryExpr)
+ if ok && u.Op == token.AND && gsRootIs(info, u.X, v) || isV(a) && gsMutable(v.Type()) {
+ var param *types.Var
+ if sig != nil && j < sig.Params().Len() && !(sig.Variadic() && j == sig.Params().Len()-1) {
+ param = sig.Params().At(j)
+ }
+ out = append(out, tr.handed(f, s, fn, param, "handed to")...)
+ }
+ }
+ }
+ return true
+ })
+ return out, defined
+}
+
+// gsMutable reports whether a callee given a value of t can change what
+// the caller's value holds.
+func gsMutable(t types.Type) bool {
+ switch t.Underlying().(type) {
+ case *types.Map, *types.Pointer:
+ return true
+ }
+ return false
+}
+
+// multi is the i'th value of a multi-value right-hand side.
+func (tr *gsTrace) multi(f *gsFrame, rhs ast.Expr, i int) []types.Type {
+ switch r := ast.Unparen(rhs).(type) {
+ case *ast.CallExpr:
+ return tr.results(f, r, i)
+ case *ast.IndexExpr: // v, ok := m[k]
+ if i == 0 {
+ return tr.rooted(f, r)
+ }
+ case *ast.TypeAssertExpr: // v, ok := x.(T)
+ if i == 0 {
+ return tr.types(f, r.X)
+ }
+ default:
+ if i == 0 && tr.sc.hides(tr.sc.info.TypeOf(r)) {
+ tr.unresolved(f, "expression", r)
+ }
+ }
+ return nil
+}
+
+// results is what the i'th result of a call can carry: for a function of
+// the package, its return expressions read in a frame that binds its
+// parameters to the call's arguments.
+func (tr *gsTrace) results(f *gsFrame, call *ast.CallExpr, i int) []types.Type {
+ info := tr.sc.info
+ rt := info.TypeOf(call)
+ var out []types.Type
+ if tup, ok := rt.(*types.Tuple); ok {
+ if i >= tup.Len() {
+ return nil
+ }
+ rt = tup.At(i).Type()
+ out = append(out, rt)
+ }
+ if !tr.sc.hides(rt) || tr.followed[call] {
+ return out
+ }
+ tr.followed[call] = true
+ fn, _ := typeutil.Callee(info, call).(*types.Func)
+ if fn != nil {
+ fn = fn.Origin()
+ }
+ g := tr.enter(f, call, fn)
+ if g == nil {
+ tr.unresolved(f, "call", call.Fun)
+ return out
+ }
+ decl := g.decl
+ res := fn.Type().(*types.Signature).Results()
+ ast.Inspect(decl.Body, func(n ast.Node) bool {
+ switch r := n.(type) {
+ case *ast.FuncLit:
+ return false
+ case *ast.ReturnStmt:
+ switch {
+ case len(r.Results) == res.Len():
+ out = append(out, tr.types(g, r.Results[i])...)
+ case len(r.Results) == 1:
+ out = append(out, tr.multi(g, r.Results[0], i)...)
+ case len(r.Results) == 0 && res.At(i).Name() != "":
+ // A bare return: the named result, as assigned.
+ out = append(out, tr.variable(g, res.At(i), decl.Name)...)
+ }
+ }
+ return true
+ })
+ return out
+}
+
+// enter is the frame of a call to fn, a function of the package, with its
+// parameters and receiver bound to the call's arguments; nil when fn has no
+// body here.
+func (tr *gsTrace) enter(f *gsFrame, call *ast.CallExpr, fn *types.Func) *gsFrame {
+ if fn == nil {
+ return nil
+ }
+ decl := tr.sc.decls[fn]
+ if decl == nil || decl.Body == nil {
+ return nil
+ }
+ sig := fn.Type().(*types.Signature)
+ g := &gsFrame{decl: decl, fn: fn, caller: f, args: map[*types.Var]ast.Expr{}}
+ params := sig.Params()
+ if len(call.Args) == params.Len() || sig.Variadic() && len(call.Args) >= params.Len()-1 {
+ for j := 0; j < params.Len() && j < len(call.Args); j++ {
+ if sig.Variadic() && j == params.Len()-1 {
+ break
+ }
+ g.args[params.At(j)] = call.Args[j]
+ }
+ }
+ if recv := sig.Recv(); recv != nil {
+ if sel, ok := ast.Unparen(call.Fun).(*ast.SelectorExpr); ok {
+ g.args[recv] = sel.X
+ }
+ }
+ return g
+}
+
+// handed follows a value the caller handed to fn (as param, or as the
+// receiver) into what fn stores in it. A callee outside the package, a
+// function value or a variadic slot cannot be followed: unresolved.
+func (tr *gsTrace) handed(f *gsFrame, call *ast.CallExpr, fn *types.Func, param *types.Var, kind string) []types.Type {
+ g := tr.enter(f, call, fn)
+ if g == nil || param == nil {
+ tr.unresolved(f, kind, call.Fun)
+ return nil
+ }
+ k := gsHand{call, param}
+ if tr.hand[k] {
+ return nil
+ }
+ tr.hand[k] = true
+ got, _ := tr.assigned(g, param)
+ return got
+}
+
+type gsHand struct {
+ call *ast.CallExpr
+ param *types.Var
+}
+
+// gsWalker walks a type as encoding/json encodes it.
+type gsWalker struct {
+ gates map[*types.Var]gsGate
+ memo typeutil.Map // types.Type -> []string, leak paths; nil while in progress
+ opaque typeutil.Map // the same, for types under a custom marshaller
+ 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 gsDeref(t types.Type) types.Type {
+ for {
+ p, ok := t.Underlying().(*types.Pointer)
+ if !ok {
+ return t
+ }
+ t = p.Elem()
+ }
+}
+
+func gsLabel(t types.Type) string {
+ return types.TypeString(t, func(p *types.Package) string { return p.Name() })
+}
+
+// gsMarshaler reports whether encoding/json hands t, or *t, to its own
+// MarshalJSON or MarshalText, promoted methods included.
+func gsMarshaler(t types.Type) bool {
+ if types.IsInterface(t) {
+ return false
+ }
+ for _, m := range []types.Type{t, types.NewPointer(t)} {
+ ms := types.NewMethodSet(m)
+ if ms.Lookup(nil, "MarshalJSON") != nil || ms.Lookup(nil, "MarshalText") != nil {
+ return true
+ }
+ }
+ return false
+}
+
+func (w *gsWalker) value(t types.Type) []string {
+ if t == nil {
+ return nil
+ }
+ t = gsDeref(t)
+ if r := w.memo.At(t); r != nil {
+ return r.([]string)
+ }
+ w.memo.Set(t, []string(nil)) // a cycle adds nothing new
+ var leaks []string
+ if gsMarshaler(t) {
+ leaks = w.held(t)
+ } else {
+ switch u := t.Underlying().(type) {
+ case *types.Struct:
+ label := gsLabel(t)
+ for _, f := range w.fields(t) {
+ 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.Set(t, leaks)
+ return leaks
+}
+
+// held is every gate field t holds anywhere, exported or not, under any
+// name: what a custom marshaller could write.
+func (w *gsWalker) held(t types.Type) []string {
+ t = gsDeref(t)
+ if r := w.opaque.At(t); r != nil {
+ return r.([]string)
+ }
+ w.opaque.Set(t, []string(nil))
+ var leaks []string
+ switch u := t.Underlying().(type) {
+ case *types.Struct:
+ label := gsLabel(t)
+ for i := 0; i < u.NumFields(); i++ {
+ f := u.Field(i)
+ if g, ok := w.gates[f]; ok {
+ leaks = append(leaks, label+"."+g.owner+".Gate (custom marshaller)")
+ continue
+ }
+ for _, l := range w.held(f.Type()) {
+ leaks = append(leaks, label+"."+f.Name()+" -> "+l)
+ }
+ }
+ case *types.Slice:
+ leaks = w.held(u.Elem())
+ case *types.Array:
+ leaks = w.held(u.Elem())
+ case *types.Map:
+ leaks = append(w.held(u.Key()), w.held(u.Elem())...)
+ }
+ w.opaque.Set(t, leaks)
+ return leaks
+}
+
+type gsField struct {
+ name string
+ tagged bool
+ depth int
+ v *types.Var
+}
+
+func gsCount(m *typeutil.Map, t types.Type) int {
+ if m == nil {
+ return 0
+ }
+ if n := m.At(t); n != nil {
+ return n.(int)
+ }
+ return 0
+}
+
+// fields is encoding/json's typeFields over go/types: the fields a struct
+// type emits, after promotion and dominance, keyed by type identity. A gate
+// field that loses to a shallower or tagged one of its name counts as
+// shadowed.
+func (w *gsWalker) fields(t types.Type) []gsField {
+ type scan struct {
+ typ types.Type
+ depth int
+ }
+ var all []gsField
+ next := []scan{{typ: t}}
+ var count, nextCount *typeutil.Map
+ var visited typeutil.Map
+ for len(next) > 0 {
+ current := next
+ next = nil
+ count, nextCount = nextCount, new(typeutil.Map)
+ for _, s := range current {
+ if visited.At(s.typ) != nil {
+ continue
+ }
+ visited.Set(s.typ, true)
+ st := s.typ.Underlying().(*types.Struct)
+ for i := 0; i < st.NumFields(); i++ {
+ sf := 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(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 gsCount(count, s.typ) > 1 {
+ all = append(all, f) // embedded twice at this depth: annihilates
+ }
+ continue
+ }
+ n := gsCount(nextCount, ft) + 1
+ nextCount.Set(ft, n)
+ if n == 1 {
+ next = append(next, scan{typ: ft, 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 or an invalid one, as
+// encoding/json's isValidTag rules) 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, ",")
+ if !gsValidTag(name) {
+ name = ""
+ }
+ return name, false
+}
+
+// gsValidTag is encoding/json's isValidTag.
+func gsValidTag(s string) bool {
+ if s == "" {
+ return false
+ }
+ for _, c := range s {
+ switch {
+ case strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c):
+ // Backslash and quote chars are reserved, but otherwise any
+ // punctuation chars are allowed in a tag name.
+ case !unicode.IsLetter(c) && !unicode.IsDigit(c):
+ return false
+ }
+ }
+ return true
+}