check-safety/pluginrules.go
Alex Dunmow 945ca508e0 Judge site data table reads by the fields the spec declares (ADR 0007 amendment)
With data_tables in acceptance.json, a public route over a site data
table fails check 33 only when the table read holds a personal field by
the spec or the classifier. The table is resolved from a literal
GetTableByKey key; an unresolved read falls back to any declared table
being personal. Without data_tables every read stays personal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:48:11 +08:00

942 lines
24 KiB
Go

package main
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
)
// The plugin rules (checks 33 to 37) read a plugin's Go sources and, for a
// factory-generated plugin, its factory-written acceptance.json. A plugin with
// acceptance.json has no human reviewer, so its findings fail the run; a
// first-party plugin's findings are warnings.
const routeImportPath = pluginSDKImportPrefix + "/route"
// defaultPersonalNames apply when a plugin has no acceptance.json.
var defaultPersonalNames = []string{"email", "phone", "address", "password", "date_of_birth"}
type acceptanceField struct {
Name string `json:"name"`
Sample string `json:"sample"`
Personal bool `json:"personal"`
}
type acceptanceSpec struct {
Name string `json:"name"`
Spec struct {
Blocks []struct {
Key string `json:"key"`
Fields []acceptanceField `json:"fields"`
} `json:"blocks"`
Tables []struct {
Name string `json:"name"`
Columns []string `json:"columns"`
PersonalColumns []string `json:"personal_columns"`
} `json:"tables"`
Routes []struct {
Method string `json:"method"`
Path string `json:"path"`
Access string `json:"access"`
Fields []acceptanceField `json:"fields"`
} `json:"routes"`
OutboundHosts []struct {
Host string `json:"host"`
Sends []string `json:"sends"`
} `json:"outbound_hosts"`
Settings []acceptanceField `json:"settings"`
DataTables []struct {
Key string `json:"key"`
Fields []acceptanceField `json:"fields"`
} `json:"data_tables"`
} `json:"spec"`
}
type pluginRuleFinding struct {
file string
line int
msg string
}
type pluginFile struct {
rel string
ast *ast.File
pkg *pluginPkg
imports map[string]string // local name -> import path
}
type pluginPkg struct {
funcs map[string][]*ast.FuncDecl // functions and methods by name
consts map[string]bool
vars map[string]ast.Expr
}
type pluginSource struct {
root string
generated bool
spec *acceptanceSpec
fset *token.FileSet
files []*pluginFile
// personal maps a normalised personal data name to its spelling in the spec.
personal map[string]string
// readQueries maps a sqlc query name that reads a personal table to the table.
readQueries map[string]string
// rowTypes maps a generated row type name of a personal table to the table.
rowTypes map[string]string
// personalTables names the tables holding a personal column, by the spec
// or by the classifier.
personalTables map[string]bool
// personalSettings is true when a plugin setting holds personal data.
personalSettings bool
// personalDataTables maps each site data table the spec declares to
// whether it holds a personal field; nil when the spec declares none.
personalDataTables map[string]bool
// sends maps an outbound host to the normalised names the spec lets it receive.
sends map[string]map[string]bool
// declFile maps each function declaration to the file that holds it.
declFile map[*ast.FuncDecl]*pluginFile
callSites map[string][]callSite
}
type callSite struct {
call *ast.CallExpr
decl *ast.FuncDecl
}
// callSitesOf lists the calls, by function or method name, made inside the
// plugin's function declarations.
func (src *pluginSource) callSitesOf(name string) []callSite {
if src.callSites == nil {
src.callSites = map[string][]callSite{}
for _, f := range src.files {
for _, decl := range f.ast.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok || fn.Body == nil {
continue
}
ast.Inspect(fn.Body, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
switch x := call.Fun.(type) {
case *ast.Ident:
src.callSites[x.Name] = append(src.callSites[x.Name], callSite{call, fn})
case *ast.SelectorExpr:
if _, _, isPkg := f.pkgSel(x); !isPkg {
src.callSites[x.Sel.Name] = append(src.callSites[x.Sel.Name], callSite{call, fn})
}
}
return true
})
}
}
}
return src.callSites[name]
}
var pluginSourceCache = map[string]*pluginSource{}
func loadPluginSource(root string) (*pluginSource, error) {
if src, ok := pluginSourceCache[root]; ok {
return src, nil
}
src := &pluginSource{
root: root,
fset: token.NewFileSet(),
personal: map[string]string{},
readQueries: map[string]string{},
rowTypes: map[string]string{},
sends: map[string]map[string]bool{},
personalTables: map[string]bool{},
declFile: map[*ast.FuncDecl]*pluginFile{},
}
if data, err := os.ReadFile(filepath.Join(root, "acceptance.json")); err == nil {
var spec acceptanceSpec
if err := json.Unmarshal(data, &spec); err != nil {
return nil, fmt.Errorf("acceptance.json: %w", err)
}
src.generated = true
src.spec = &spec
}
src.indexSpec()
pkgs := map[string]*pluginPkg{}
var sqlLiterals []string
err := filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
name := d.Name()
if p != root && (strings.HasPrefix(name, ".") || name == "vendor" || name == "node_modules" || name == "testdata") {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
return nil
}
f, perr := parser.ParseFile(src.fset, p, nil, parser.ParseComments|parser.SkipObjectResolution)
if perr != nil {
return nil
}
ast.Inspect(f, func(n ast.Node) bool {
if lit, ok := n.(*ast.BasicLit); ok && lit.Kind == token.STRING && strings.Contains(lit.Value, "-- name: ") {
if s, uerr := strconv.Unquote(lit.Value); uerr == nil {
sqlLiterals = append(sqlLiterals, s)
}
}
return true
})
if ast.IsGenerated(f) {
return nil
}
dir := filepath.Dir(p)
pkg := pkgs[dir]
if pkg == nil {
pkg = &pluginPkg{funcs: map[string][]*ast.FuncDecl{}, consts: map[string]bool{}, vars: map[string]ast.Expr{}}
pkgs[dir] = pkg
}
pkg.add(f)
rel, _ := filepath.Rel(root, p)
pf := &pluginFile{rel: filepath.ToSlash(rel), ast: f, pkg: pkg, imports: fileImports(f)}
src.files = append(src.files, pf)
for _, decl := range f.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
src.declFile[fn] = pf
}
}
return nil
})
if err != nil {
return nil, err
}
src.indexQueries(sqlLiterals)
pluginSourceCache[root] = src
return src, nil
}
func (src *pluginSource) indexSpec() {
if src.spec == nil {
for _, n := range defaultPersonalNames {
src.personal[normName(n)] = n
}
return
}
// A field is personal when the spec says so or the classifier does: by its
// name, its sample's shape, or because a visitor types it into a form.
addFields := func(fields []acceptanceField, visitorForm bool) bool {
found := false
for _, f := range fields {
if f.Personal || visitorForm || personalKind(f.Name) != "" || sampleKind(f.Sample) != "" {
src.personal[normName(f.Name)] = f.Name
found = true
}
}
return found
}
s := src.spec.Spec
for _, b := range s.Blocks {
addFields(b.Fields, false)
}
for _, r := range s.Routes {
addFields(r.Fields, strings.EqualFold(r.Method, "POST") && (r.Access == "public" || r.Access == "visitor"))
}
src.personalSettings = addFields(s.Settings, false)
if len(s.DataTables) > 0 {
src.personalDataTables = map[string]bool{}
for _, dt := range s.DataTables {
src.personalDataTables[dt.Key] = addFields(dt.Fields, false)
}
}
markTable := func(table string, cols []string) {
for _, c := range cols {
src.personal[normName(c)] = c
}
if len(cols) > 0 {
src.personalTables[table] = true
src.rowTypes[camelName(table)] = table
src.rowTypes[camelName(singularName(table))] = table
}
}
for _, t := range s.Tables {
cols := append([]string(nil), t.PersonalColumns...)
for _, c := range t.Columns {
if _, named := src.personal[normName(c)]; named || personalKind(c) != "" {
cols = append(cols, c)
}
}
markTable(t.Name, cols)
}
for table, cols := range migrationColumns(src.root) {
markTable(table, cols)
}
for _, h := range s.OutboundHosts {
names := map[string]bool{}
for _, n := range h.Sends {
names[normName(n)] = true
}
src.sends[strings.ToLower(h.Host)] = names
}
}
var sqlcNamePattern = regexp.MustCompile(`--\s*name:\s*(\w+)`)
// indexQueries finds the sqlc queries that read a personal table, so a call
// to the generated method can be traced back to the table.
func (src *pluginSource) indexQueries(literals []string) {
if src.spec == nil {
return
}
for _, sql := range literals {
m := sqlcNamePattern.FindStringSubmatch(sql)
if m == nil {
continue
}
body := strings.ToLower(sql[len(m[0]):])
fields := strings.Fields(body)
for len(fields) > 0 && strings.HasPrefix(fields[0], ":") {
fields = fields[1:]
}
reads := strings.Contains(body, "returning")
if len(fields) > 0 && (fields[0] == "select" || fields[0] == "with") {
reads = true
}
if !reads {
continue
}
for _, table := range sortedKeys(src.personalTables) {
if regexp.MustCompile(`\b` + regexp.QuoteMeta(strings.ToLower(table)) + `\b`).MatchString(body) {
src.readQueries[m[1]] = table
break
}
}
}
}
func (p *pluginPkg) add(f *ast.File) {
for _, decl := range f.Decls {
switch d := decl.(type) {
case *ast.FuncDecl:
p.funcs[d.Name.Name] = append(p.funcs[d.Name.Name], d)
case *ast.GenDecl:
for _, spec := range d.Specs {
vs, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
for i, n := range vs.Names {
if d.Tok == token.CONST {
p.consts[n.Name] = true
} else if i < len(vs.Values) {
p.vars[n.Name] = vs.Values[i]
} else {
p.vars[n.Name] = nil
}
}
}
}
}
}
func fileImports(f *ast.File) map[string]string {
out := map[string]string{}
for _, spec := range f.Imports {
p, err := strconv.Unquote(spec.Path.Value)
if err != nil {
continue
}
name := ""
if spec.Name != nil {
name = spec.Name.Name
} else {
name = defaultImportName(p)
}
if name == "_" || name == "." {
continue
}
out[name] = p
}
return out
}
var majorVersionSuffix = regexp.MustCompile(`^v[0-9]+$`)
func defaultImportName(p string) string {
base := path.Base(p)
if majorVersionSuffix.MatchString(base) {
base = path.Base(path.Dir(p))
}
if i := strings.Index(base, ".v"); i > 0 {
base = base[:i]
}
return strings.ReplaceAll(base, "-", "_")
}
// pkgFunc reports the import path and function name of a call like http.Get.
func (f *pluginFile) pkgFunc(call *ast.CallExpr) (string, string, bool) {
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return "", "", false
}
return f.pkgSel(sel)
}
func (f *pluginFile) pkgSel(sel *ast.SelectorExpr) (string, string, bool) {
id, ok := sel.X.(*ast.Ident)
if !ok {
return "", "", false
}
p, ok := f.imports[id.Name]
if !ok {
return "", "", false
}
return p, sel.Sel.Name, true
}
func (f *pluginFile) isImportName(name string) bool {
_, ok := f.imports[name]
return ok
}
func (src *pluginSource) line(n ast.Node) int { return src.fset.Position(n.Pos()).Line }
// normName folds snake_case, kebab-case and CamelCase spellings to one key.
func normName(s string) string {
var b strings.Builder
for _, r := range s {
if r == '_' || r == '-' || r == ' ' {
continue
}
b.WriteRune(unicode.ToLower(r))
}
return b.String()
}
func camelName(snake string) string {
var b strings.Builder
for part := range strings.SplitSeq(snake, "_") {
if part == "" {
continue
}
b.WriteString(strings.ToUpper(part[:1]) + part[1:])
}
return b.String()
}
// singularName mirrors sqlc's row type naming for the common plurals.
// shortcut: plain suffix rules, upgrade to an inflection table if a spec table
// name trips them.
func singularName(s string) string {
switch {
case strings.HasSuffix(s, "ies"):
return strings.TrimSuffix(s, "ies") + "y"
case strings.HasSuffix(s, "sses"), strings.HasSuffix(s, "ches"), strings.HasSuffix(s, "shes"), strings.HasSuffix(s, "xes"):
return strings.TrimSuffix(s, "es")
case strings.HasSuffix(s, "s") && !strings.HasSuffix(s, "ss"):
return strings.TrimSuffix(s, "s")
}
return s
}
var keyLikeString = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_.-]*$`)
// personalRefs lists the personal data names an expression mentions through
// an identifier, a selector field or a key-like string literal.
func (src *pluginSource) personalRefs(f *pluginFile, n ast.Node) []string {
seen := map[string]bool{}
check := func(s string) {
if name, ok := src.personal[normName(s)]; ok {
seen[name] = true
}
}
ast.Inspect(n, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.CallExpr:
// A length carries no personal data.
if id, ok := x.Fun.(*ast.Ident); ok && id.Name == "len" {
return false
}
case *ast.SelectorExpr:
if id, ok := x.X.(*ast.Ident); ok && f.isImportName(id.Name) {
return false
}
check(x.Sel.Name)
case *ast.Ident:
if !f.isImportName(x.Name) {
check(x.Name)
}
case *ast.BasicLit:
if x.Kind == token.STRING {
if s, err := strconv.Unquote(x.Value); err == nil && keyLikeString.MatchString(s) {
check(s)
}
}
}
return true
})
return sortedKeys(seen)
}
// storedPersonalReads lists the personal tables an expression reads through a
// sqlc query or the table's generated row type.
func (src *pluginSource) storedPersonalReads(n ast.Node) []string {
seen := map[string]bool{}
scope := n
ast.Inspect(n, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.CallExpr:
if sel, ok := x.Fun.(*ast.SelectorExpr); ok {
if t, ok := src.readQueries[sel.Sel.Name]; ok {
seen[t+" ("+sel.Sel.Name+")"] = true
}
if src.generated && siteDataTableReads[sel.Sel.Name] && strings.Contains(shortExpr(sel.X), "DataTables") {
if label, personal := src.dataTableReadPersonal(scope); personal {
seen["site data table "+label+"("+sel.Sel.Name+")"] = true
}
}
if src.personalSettings && sel.Sel.Name == "GetPluginSettings" {
seen["plugin settings ("+sel.Sel.Name+")"] = true
}
}
case *ast.SelectorExpr:
if t, ok := src.rowTypes[x.Sel.Name]; ok {
seen[t+" ("+x.Sel.Name+")"] = true
}
case *ast.Ident:
if t, ok := src.rowTypes[x.Name]; ok {
seen[t+" ("+x.Name+")"] = true
}
}
return true
})
return sortedKeys(seen)
}
var siteDataTableReads = map[string]bool{"ListRows": true, "GetRow": true, "FindRowByField": true}
// dataTableReadPersonal decides whether a site data table read inside n reads
// personal data. Without data_tables in the spec every read is personal. With
// them, the tables n names by a literal GetTableByKey key decide; a read whose
// table cannot be resolved is personal when any declared table is.
func (src *pluginSource) dataTableReadPersonal(n ast.Node) (string, bool) {
if src.personalDataTables == nil {
return "", true
}
var keys []string
ast.Inspect(n, func(c ast.Node) bool {
call, ok := c.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || sel.Sel.Name != "GetTableByKey" || len(call.Args) != 2 {
return true
}
if lit, ok := call.Args[1].(*ast.BasicLit); ok && lit.Kind == token.STRING {
if k, err := strconv.Unquote(lit.Value); err == nil {
keys = append(keys, k)
}
}
return true
})
if len(keys) == 0 {
for k, personal := range src.personalDataTables {
if personal {
return k + " ", true
}
}
return "", false
}
for _, k := range keys {
personal, declared := src.personalDataTables[k]
if personal || !declared {
return k + " ", true
}
}
return "", false
}
func sortedKeys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
// funcScope records, by name, every value a function assigns to its locals.
// Parameters, receivers and range variables are opaque: their values come from
// the caller or a collection and count as untrusted.
type funcScope struct {
assigns map[string][]ast.Expr
opaque map[string]bool
// rangeOf maps a range value variable to the collections it ranges over.
rangeOf map[string][]ast.Expr
// constRange holds range variables over a table of constants (set by the
// HTML rule).
constRange map[string]bool
}
func newFuncScope(n ast.Node) *funcScope {
s := &funcScope{assigns: map[string][]ast.Expr{}, opaque: map[string]bool{}, rangeOf: map[string][]ast.Expr{}, constRange: map[string]bool{}}
addFields := func(fl *ast.FieldList) {
if fl == nil {
return
}
for _, field := range fl.List {
for _, name := range field.Names {
s.opaque[name.Name] = true
}
}
}
addAssign := func(lhs ast.Expr, rhs ast.Expr) {
if id, ok := lhs.(*ast.Ident); ok && id.Name != "_" {
s.assigns[id.Name] = append(s.assigns[id.Name], rhs)
}
}
ast.Inspect(n, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
addFields(x.Recv)
addFields(x.Type.Params)
if x.Type.Results != nil {
for _, field := range x.Type.Results.List {
for _, name := range field.Names {
s.assigns[name.Name] = append(s.assigns[name.Name], nil)
}
}
}
case *ast.FuncLit:
addFields(x.Type.Params)
case *ast.AssignStmt:
for i, lhs := range x.Lhs {
switch {
case len(x.Lhs) == len(x.Rhs):
addAssign(lhs, x.Rhs[i])
case len(x.Rhs) == 1:
addAssign(lhs, x.Rhs[0])
}
}
case *ast.ValueSpec:
for i, name := range x.Names {
if i < len(x.Values) {
addAssign(name, x.Values[i])
} else if len(x.Values) == 1 {
addAssign(name, x.Values[0])
} else {
addAssign(name, nil)
}
}
case *ast.RangeStmt:
if id, ok := x.Key.(*ast.Ident); ok {
s.opaque[id.Name] = true
}
if id, ok := x.Value.(*ast.Ident); ok {
s.rangeOf[id.Name] = append(s.rangeOf[id.Name], x.X)
}
case *ast.TypeSwitchStmt:
if as, ok := x.Assign.(*ast.AssignStmt); ok {
for _, lhs := range as.Lhs {
if id, ok := lhs.(*ast.Ident); ok {
s.opaque[id.Name] = true
}
}
}
}
return true
})
return s
}
// returnExprs lists the values a function body returns, skipping nested
// function literals.
func returnExprs(body *ast.BlockStmt) [][]ast.Expr {
var out [][]ast.Expr
if body == nil {
return nil
}
ast.Inspect(body, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncLit:
return false
case *ast.ReturnStmt:
out = append(out, x.Results)
}
return true
})
return out
}
// funcBodies resolves a handler expression to the function bodies it names in
// the same package: a function literal, a function or a method value.
func (p *pluginPkg) funcBodies(h ast.Expr) []ast.Node {
switch x := h.(type) {
case *ast.FuncLit:
return []ast.Node{x}
case *ast.Ident:
return declNodes(p.funcs[x.Name])
case *ast.SelectorExpr:
return declNodes(p.funcs[x.Sel.Name])
case *ast.ParenExpr:
return p.funcBodies(x.X)
case *ast.CallExpr:
// A conversion such as http.HandlerFunc(fn) or a wrapper call names
// its handler as an argument.
var out []ast.Node
for _, a := range x.Args {
out = append(out, p.funcBodies(a)...)
}
return out
}
return nil
}
func declNodes(decls []*ast.FuncDecl) []ast.Node {
out := make([]ast.Node, 0, len(decls))
for _, d := range decls {
out = append(out, d)
}
return out
}
// reachable returns the given bodies plus every same-package function they
// name, matched by name (methods included), so a handler's helpers count.
func (p *pluginPkg) reachable(roots []ast.Node) []ast.Node {
seen := map[ast.Node]bool{}
queue := append([]ast.Node(nil), roots...)
var out []ast.Node
for len(queue) > 0 {
n := queue[0]
queue = queue[1:]
if seen[n] {
continue
}
seen[n] = true
out = append(out, n)
ast.Inspect(n, func(c ast.Node) bool {
var name string
switch x := c.(type) {
case *ast.Ident:
name = x.Name
case *ast.SelectorExpr:
name = x.Sel.Name
}
for _, d := range p.funcs[name] {
if !seen[d] {
queue = append(queue, d)
}
}
return true
})
}
return out
}
// routeRegistration is one call on a pluginsdk route.Router.
type routeRegistration struct {
call *ast.CallExpr
form bool
method ast.Expr
path ast.Expr
access string // public, visitor, admin, or empty when not a route constant
handler ast.Expr
}
// routeRegistrations finds r.Handle(method, path, route.X, h) and
// r.Form(path, h) calls in a file that imports pluginsdk route.
func (f *pluginFile) routeRegistrations() []routeRegistration {
routeName := ""
for name, p := range f.imports {
if p == routeImportPath {
routeName = name
}
}
if routeName == "" {
return nil
}
var out []routeRegistration
ast.Inspect(f.ast, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
switch {
case sel.Sel.Name == "Handle" && len(call.Args) == 4:
reg := routeRegistration{call: call, method: call.Args[0], path: call.Args[1], handler: call.Args[3]}
if a, ok := call.Args[2].(*ast.SelectorExpr); ok {
if id, ok := a.X.(*ast.Ident); ok && id.Name == routeName {
reg.access = strings.ToLower(a.Sel.Name)
}
}
out = append(out, reg)
case sel.Sel.Name == "Form" && len(call.Args) == 2:
out = append(out, routeRegistration{call: call, form: true, path: call.Args[0], access: "public", handler: call.Args[1]})
}
return true
})
return out
}
func shortExpr(e ast.Expr) string {
s := exprText(e)
if len(s) > 60 {
s = s[:57] + "..."
}
return s
}
func exprText(e ast.Expr) string {
var b strings.Builder
writeExpr(&b, e)
return b.String()
}
func writeExpr(b *strings.Builder, e ast.Expr) {
switch x := e.(type) {
case *ast.Ident:
b.WriteString(x.Name)
case *ast.BasicLit:
b.WriteString(x.Value)
case *ast.SelectorExpr:
writeExpr(b, x.X)
b.WriteString("." + x.Sel.Name)
case *ast.StarExpr:
b.WriteString("*")
writeExpr(b, x.X)
case *ast.UnaryExpr:
b.WriteString(x.Op.String())
writeExpr(b, x.X)
case *ast.ParenExpr:
b.WriteString("(")
writeExpr(b, x.X)
b.WriteString(")")
case *ast.BinaryExpr:
writeExpr(b, x.X)
b.WriteString(" " + x.Op.String() + " ")
writeExpr(b, x.Y)
case *ast.IndexExpr:
writeExpr(b, x.X)
b.WriteString("[")
writeExpr(b, x.Index)
b.WriteString("]")
case *ast.TypeAssertExpr:
writeExpr(b, x.X)
b.WriteString(".(")
if x.Type != nil {
writeExpr(b, x.Type)
} else {
b.WriteString("type")
}
b.WriteString(")")
case *ast.CallExpr:
writeExpr(b, x.Fun)
b.WriteString("(")
for i, a := range x.Args {
if i > 0 {
b.WriteString(", ")
}
writeExpr(b, a)
}
b.WriteString(")")
case *ast.ArrayType:
b.WriteString("[]")
writeExpr(b, x.Elt)
case *ast.FuncLit:
b.WriteString("func literal")
case *ast.CompositeLit:
if x.Type != nil {
writeExpr(b, x.Type)
}
b.WriteString("{...}")
default:
b.WriteString("expression")
}
}
type pluginRuleTarget struct {
root string
label string
}
// pluginRuleTargets lists the standalone plugin roots of a scan. The cms and
// orchestrator roots are not plugin roots, so the plugin rules skip them.
func pluginRuleTargets(ctx *ScanContext) []pluginRuleTarget {
var out []pluginRuleTarget
seen := map[string]bool{}
add := func(root, label string) {
if seen[root] || !shouldCheckStandalonePluginImports(root) {
return
}
seen[root] = true
out = append(out, pluginRuleTarget{root: root, label: label})
}
for _, t := range ctx.backendTargets {
add(t.root, t.displayOrRoot())
}
for _, t := range ctx.pluginTargets {
add(t.root, t.display)
}
return out
}
// runPluginRule runs one plugin rule over every plugin target. Findings in a
// plugin with acceptance.json fail; findings in other plugins warn.
func runPluginRule(ctx *ScanContext, rep *Reporter, what string, rule func(*pluginSource) []pluginRuleFinding) {
var failed, warned, scanned int
for _, t := range pluginRuleTargets(ctx) {
src, err := loadPluginSource(t.root)
if err != nil {
rep.Fatal("%s: %v", t.label, err)
}
if len(src.files) == 0 {
continue
}
scanned++
findings := rule(src)
sort.SliceStable(findings, func(i, j int) bool {
if findings[i].file != findings[j].file {
return findings[i].file < findings[j].file
}
return findings[i].line < findings[j].line
})
for _, f := range findings {
rep.Findingf("%s:%d %s", prefixDisplayPath(t.label, f.file), f.line, f.msg)
}
if src.generated {
failed += len(findings)
} else {
warned += len(findings)
}
}
switch {
case scanned == 0:
rep.Skip("no plugin Go sources scanned")
case failed == 0 && warned == 0:
rep.OK("no %s", what)
}
if warned > 0 {
rep.Warn("%d %s in first-party plugin code (warning: no acceptance.json)", warned, what)
}
if failed > 0 {
rep.Fail("%d %s in a factory-generated plugin", failed, what)
}
}