diff --git a/README.md b/README.md index 818fdf2..ae90ba3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # check-safety -Static safety checker for the BlockNinja codebase. Walks a target tree, runs 34 invariant +Static safety checker for the BlockNinja codebase. Walks a target tree, runs 39 invariant checks across Go and frontend sources, and exits non-zero on any violation. Lives in the consolidated BlockNinja workspace as a standalone Go module, alongside `cms/`, @@ -46,7 +46,7 @@ line with their findings indented beneath, followed by one tally line. A clean r ``` check-safety /home/alex/src/blockninja/cms -34 checks: 20 ok 14 skip -> OK +39 checks: 20 ok 19 skip -> OK ``` A run with problems: @@ -58,7 +58,7 @@ FAIL 15 1 err.Error() leak(s) to HTTP clients — log via slog.Error() and retur WARN 2e 1 any usage in changed lines (showing 1, --all-any to scan all) web/src/api.ts:12 [go] data: any -34 checks: 29 ok 3 skip 1 warn 1 fail -> FAIL +39 checks: 29 ok 8 skip 1 warn 1 fail -> FAIL ``` Pass `--verbose` to see every check's status. Exit code is `1` on any `FAIL`, `2` on a hard @@ -127,6 +127,48 @@ tool prints in each check header): | 29 | No legacy Go plugins | No `-buildmode=plugin` targets remain after the wasm migration gate is enabled. | | 30 | Render performance | Home-page render p50 remains within the recorded baseline. | | 32 | Schema purity | Every table in `schema.sql` originates from a core migration (31 is retired). | +| 33 | Plugin route access | Plugin HTTP routes are registered through pluginsdk `route` (`Handle` with an access level, or `Form`). Flags `http.NewServeMux`, `Handle`/`HandleFunc` registrations, chi and other router libraries, an `HTTPHandler` that does not return a `route.New` router, and a `route.Public` route whose handler (or a same-package function it calls) reads a table that has `personal_columns`. | +| 34 | Plugin output encoding | HTML built by concatenation, `fmt.Sprintf`/`Fprintf` or builder, buffer and writer writes passes every non-constant string through `html.EscapeString`, `template.HTMLEscapeString`, `url.QueryEscape`/`PathEscape` or a numeric formatter. Parameters, fields and map reads count as untrusted. `html/template` and templ output are not checked. | +| 35 | Plugin public forms | A public POST uses `route.Form` (host-verified captcha plus a per-instance submission limit). Flags `route.Handle` with `route.Public` and a method other than GET or HEAD, and POST handling (`r.Method` compared with POST, `ParseForm`, `PostForm`, `FormValue`) in a function that no `route` registration reaches. | +| 36 | Plugin personal-data logging | Log calls (`log`, `slog` and logger methods, `fmt.Print*`, `fmt.Fprint*` to stdout or stderr, `print`/`println`) do not reference a personal data name as an identifier, a selector field or a key string. | +| 37 | Plugin egress payloads | A function that sends an HTTP request does not reference personal data names or rows read from a table with personal columns, callers do not pass such values to it, and every query or form key with a non-constant value is in the host's `sends` list. | + +### Plugin rules (33 to 37) and severity + +Checks 33 to 37 run only on standalone plugin roots (a directory with `plugin.mod`, or a +`--plugin-dir`); the cms and orchestrator targets report them as SKIP. They read the plugin's +non-test, non-generated Go sources. + +- **Factory-generated plugin** (an `acceptance.json` at the plugin root): every finding is a + FAIL. Nobody reviews this code, so these checks are its gate. Personal data names come from + the spec: every table's `personal_columns` plus every block, route and settings field with + `"personal": true`. Tables with `personal_columns` also mark their sqlc read queries and + generated row types as stored personal data, and `outbound_hosts[].sends` lists the values + each host may receive. +- **First-party plugin** (no `acceptance.json`): every finding is a WARN, so human-reviewed + plugins keep passing. Personal data names default to `email`, `phone`, `address`, + `password` and `date_of_birth`, and the table and `sends` parts are skipped. + +Names match after folding case, `_` and `-`, so `property_address`, `PropertyAddress` and +`"property_address"` are the same name. The analysis is syntactic and best effort: calls are +followed by name within one package, and a query or form key whose value is a literal or a +constant carries no site data and is allowed for any host. + +What the rules accept as declared access or safe output: + +- 33: a ServeMux whose only registrations are `mux.Handle(path, handler)` with both values from + a Connect binding's `Build()` or a handler from `connect.New*Handler` (the host enforces RBAC + method roles on those paths), muxes in + the `Assets` handler that read no stored personal data, and `http.NotFoundHandler()`. +- 34: literals and constants, numeric `fmt` verbs and `strconv` formatters, `.Format` with a + constant layout, the escapers listed above, the pluginsdk `BlockNoteToHTML` renderer and + bluemonday `Sanitize`, range variables over a table written out in the source, and values + built only from those. In a first-party plugin a parameter is also safe when every + same-package call passes a safe value; in a generated plugin parameters are always untrusted. +- 35: in a first-party plugin, a hand-registered handler that calls pluginsdk + `auth.CaptchaVerified` (check 33 still fails such a handler in a generated plugin). + +ADR 0006 records the design. > The canonical numbered list also lives in the comment block at the top of `main.go`; keep > the two in sync when adding or renumbering a check. diff --git a/check_pluginegress.go b/check_pluginegress.go new file mode 100644 index 0000000..d767b37 --- /dev/null +++ b/check_pluginegress.go @@ -0,0 +1,12 @@ +package main + +func init() { + register(Check{ + Seq: 370, + ID: "37", + Title: "Plugin outbound requests send only the values the spec names", + Run: func(ctx *ScanContext, rep *Reporter) { + runPluginRule(ctx, rep, "plugin outbound request payload finding(s)", checkPluginEgress) + }, + }) +} diff --git a/check_pluginforms.go b/check_pluginforms.go new file mode 100644 index 0000000..acdea4e --- /dev/null +++ b/check_pluginforms.go @@ -0,0 +1,12 @@ +package main + +func init() { + register(Check{ + Seq: 350, + ID: "35", + Title: "Public plugin form posts use route.Form", + Run: func(ctx *ScanContext, rep *Reporter) { + runPluginRule(ctx, rep, "plugin form post(s) outside route.Form", checkPluginForms) + }, + }) +} diff --git a/check_pluginhtml.go b/check_pluginhtml.go new file mode 100644 index 0000000..7e95f84 --- /dev/null +++ b/check_pluginhtml.go @@ -0,0 +1,12 @@ +package main + +func init() { + register(Check{ + Seq: 340, + ID: "34", + Title: "Plugin HTML output escapes non-constant strings", + Run: func(ctx *ScanContext, rep *Reporter) { + runPluginRule(ctx, rep, "unescaped value(s) in plugin HTML output", checkPluginHTML) + }, + }) +} diff --git a/check_pluginlogs.go b/check_pluginlogs.go new file mode 100644 index 0000000..c9addde --- /dev/null +++ b/check_pluginlogs.go @@ -0,0 +1,12 @@ +package main + +func init() { + register(Check{ + Seq: 360, + ID: "36", + Title: "Plugin logs carry no personal data", + Run: func(ctx *ScanContext, rep *Reporter) { + runPluginRule(ctx, rep, "plugin log call(s) with personal data", checkPluginLogs) + }, + }) +} diff --git a/check_pluginroutes.go b/check_pluginroutes.go new file mode 100644 index 0000000..eb7c34d --- /dev/null +++ b/check_pluginroutes.go @@ -0,0 +1,12 @@ +package main + +func init() { + register(Check{ + Seq: 330, + ID: "33", + Title: "Plugin HTTP routes declare access through pluginsdk route", + Run: func(ctx *ScanContext, rep *Reporter) { + runPluginRule(ctx, rep, "plugin route(s) without a declared access level or public route(s) reading personal data", checkPluginRoutes) + }, + }) +} diff --git a/docs/adr/0006-plugin-route-output-form-log-and-egress-rules.md b/docs/adr/0006-plugin-route-output-form-log-and-egress-rules.md new file mode 100644 index 0000000..9638d4e --- /dev/null +++ b/docs/adr/0006-plugin-route-output-form-log-and-egress-rules.md @@ -0,0 +1,67 @@ +# Plugin route, output, form, logging and egress rules + +The website factory has a model write a custom CMS plugin for a small +business, and automatic checks are the only gate before it runs on the +customer's site. The WO-088 live runs (orchestrator +`docs/works/WO-088-custom-plugin-generation.md`, concerns 3 to 7) showed +check-safety passing five unsafe patterns: an unauthenticated route returning +stored quote requests, a block writing visitor-submitted rows into HTML +without escaping, a public form taking any POST with no captcha, a log line +carrying an email address, and an outbound request that may carry stored form +data to an approved host. + +Add five checks that run on standalone plugin roots only: + +- 33 `checkPluginRoutes` (`plugin_routes.go`): routes go through pluginsdk + `route` (v0.3.12), which enforces a declared access level at runtime. Own + routers, direct `Handle`/`HandleFunc` registrations and an `HTTPHandler` + that does not return a `route.New` router fail. A `route.Public` route whose + handler, or a same-package function it calls, reads a table with + `personal_columns` fails. +- 34 `checkPluginHTML` (`plugin_html.go`): HTML built by concatenation, + `fmt.Sprintf`/`Fprintf` or writer calls must escape every non-constant + string. Values are traced through locals and same-package function returns; + parameters, fields, map reads and other packages' results are untrusted. +- 35 `checkPluginForms` (`plugin_forms.go`): a public POST must use + `route.Form`, which requires the host-verified captcha and a per-instance + submission limit. +- 36 `checkPluginLogs` (`plugin_logs.go`): log calls must not reference a + personal data name. +- 37 `checkPluginEgress` (`plugin_egress.go`): a function that sends an HTTP + request must not reference personal data or stored personal rows, and every + non-constant query or form key must be in the host's `sends` list. + +The factory writes `acceptance.json` at the plugin root and the plugin cannot +change it, so its presence marks a factory-generated plugin. Findings there +fail; findings in other plugins warn, because first-party plugins are human +reviewed and several mount Connect handlers on a ServeMux that the host guards +with RBAC. Personal data names come from the spec (table `personal_columns` +plus fields marked `personal`); without a spec a short default list applies. + +Rejected: type-checking the plugin with go/packages. It needs the plugin's +module graph inside the build sandbox and slows every run; a syntactic, +name-based analysis catches the WO-088 patterns. Rejected: allowing query +keys by name only. A constant value carries no site data, so keys with literal +or constant values are allowed for any host and only non-constant keys must +appear in `sends`. + +Measured on the first-party plugins, the first version warned on Connect +service muxes, asset muxes, `time.Format` output, `append`-built slices and +helpers that only ever receive constants. The rules now accept Connect +binding and `connect.New*Handler` muxes, asset muxes that read no stored personal data, constant-layout +`Format`, `append`, range variables over source tables, the SDK BlockNote +renderer and bluemonday, and (first-party only) parameters whose every +same-package call passes a safe value and handlers that call +`auth.CaptchaVerified`. The WO-088 fixtures fail under the tuned rules. + +Consequences: + +- Fixtures under `testdata/pluginrules/` reproduce the WO-088 quote and + weather plugins in failing and fixed form; `pluginrules_test.go` covers each + rule and the fail/warn split. +- The cms and orchestrator targets are not plugin roots and report the five + checks as SKIP. +- The analysis is best effort: calls are matched by name within one package + and a value laundered through another package is not traced. + +Keywords: WO-088, acceptance.json, factory, generated plugin, pluginsdk route, route.Form, route.Public, captcha, HTTPHandler, ServeMux, chi, stored XSS, html.EscapeString, output encoding, personal data, personal_columns, slog, logging, egress, outbound_hosts, sends, open-meteo, checks 33 34 35 36 37 diff --git a/main.go b/main.go index 16d8192..885f503 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,14 @@ // 29. No -buildmode=plugin targets in ported plugin repos (disabled until WO-WZ-017) // 30. Home-page render performance stays within its recorded baseline // 32. schema.sql contains only tables created by core migrations (31 retired) +// 33. Plugin HTTP routes are registered through pluginsdk route with a declared access level +// 34. Plugin HTML output escapes every non-constant string +// 35. Public plugin form posts use route.Form (captcha and submission limit) +// 36. Plugin log calls carry no personal data names +// 37. Plugin outbound requests send only the values acceptance.json names for the host +// +// Checks 33 to 37 fail for a factory-generated plugin (acceptance.json at its root) and +// warn for other plugins. package main import ( diff --git a/plugin_egress.go b/plugin_egress.go new file mode 100644 index 0000000..7d26cc9 --- /dev/null +++ b/plugin_egress.go @@ -0,0 +1,234 @@ +package main + +import ( + "fmt" + "go/ast" + "go/token" + "net/url" + "strconv" + "strings" +) + +var outboundHTTPFuncs = map[string]bool{ + "NewRequest": true, "NewRequestWithContext": true, "Get": true, "Post": true, "PostForm": true, "Head": true, +} + +// checkPluginEgress flags outbound requests that carry personal data or +// stored personal rows, and, when the spec names the host, query or form keys +// with non-constant values that the host's sends list does not name. +func checkPluginEgress(src *pluginSource) []pluginRuleFinding { + var out []pluginRuleFinding + add := func(f *pluginFile, n ast.Node, format string, a ...any) { + out = append(out, pluginRuleFinding{file: f.rel, line: src.line(n), msg: fmt.Sprintf(format, a...)}) + } + outbound := map[*pluginPkg]map[string]bool{} + for _, f := range src.files { + for _, decl := range f.ast.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + req := outboundCall(f, fn.Body) + if req == nil { + continue + } + if outbound[f.pkg] == nil { + outbound[f.pkg] = map[string]bool{} + } + outbound[f.pkg][fn.Name.Name] = true + if refs := src.personalRefs(f, fn.Body); len(refs) > 0 { + add(f, req, "outbound request in %s carries personal data (%s)", fn.Name.Name, strings.Join(refs, ", ")) + } + if reads := src.storedPersonalReads(fn.Body); len(reads) > 0 { + add(f, req, "outbound request in %s uses stored personal data from %s", fn.Name.Name, strings.Join(reads, ", ")) + } + if src.spec != nil { + out = append(out, src.egressKeyFindings(f, fn)...) + } + } + } + for _, f := range src.files { + names := outbound[f.pkg] + if len(names) == 0 { + continue + } + ast.Inspect(f.ast, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + var callee string + switch fn := call.Fun.(type) { + case *ast.Ident: + callee = fn.Name + case *ast.SelectorExpr: + if _, _, isPkg := f.pkgSel(fn); !isPkg { + callee = fn.Sel.Name + } + } + if !names[callee] { + return true + } + var refs []string + for _, a := range call.Args { + refs = append(refs, src.personalRefs(f, a)...) + refs = append(refs, src.storedPersonalReads(a)...) + } + if len(refs) > 0 { + add(f, call, "passes personal data (%s) to %s, which makes an outbound request", strings.Join(dedupe(refs), ", "), callee) + } + return true + }) + } + return out +} + +// outboundCall returns the first call in body that sends an HTTP request. +func outboundCall(f *pluginFile, body *ast.BlockStmt) *ast.CallExpr { + var found *ast.CallExpr + ast.Inspect(body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok || found != nil { + return found == nil + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + if p, name, isPkg := f.pkgSel(sel); isPkg { + if p == "net/http" && outboundHTTPFuncs[name] { + found = call + } + return found == nil + } + switch sel.Sel.Name { + case "Do", "RoundTrip": + if len(call.Args) == 1 { + found = call + } + case "Get", "Post", "PostForm", "Head": + if strings.Contains(strings.ToLower(exprText(sel.X)), "client") { + found = call + } + } + return found == nil + }) + return found +} + +// egressKeyFindings checks the query and form keys a function sends against +// the spec's sends list for the hosts named in its URL literals. +func (src *pluginSource) egressKeyFindings(f *pluginFile, fn *ast.FuncDecl) []pluginRuleFinding { + var out []pluginRuleFinding + allowed := map[string]bool{} + var hosts []string + type sentKey struct { + key string + node ast.Node + } + var keys []sentKey + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.BasicLit: + if x.Kind != token.STRING { + return true + } + s, err := strconv.Unquote(x.Value) + if err != nil || !strings.Contains(s, "://") { + return true + } + u, err := url.Parse(s) + if err != nil || u.Hostname() == "" { + return true + } + host := strings.ToLower(u.Hostname()) + sends, ok := src.sends[host] + if !ok { + out = append(out, pluginRuleFinding{file: f.rel, line: src.line(x), msg: fmt.Sprintf("%s calls host %s, which acceptance.json does not list", fn.Name.Name, host)}) + } + hosts = append(hosts, host) + for k := range sends { + allowed[k] = true + } + for _, part := range strings.Split(u.RawQuery, "&") { + k, v, _ := strings.Cut(part, "=") + if k != "" && (v == "" || strings.Contains(v, "%")) { + keys = append(keys, sentKey{k, x}) + } + } + case *ast.CallExpr: + sel, ok := x.Fun.(*ast.SelectorExpr) + if !ok || (sel.Sel.Name != "Set" && sel.Sel.Name != "Add") || len(x.Args) != 2 || strings.Contains(exprText(sel.X), "Header") { + return true + } + if k, ok := stringLit(x.Args[0]); ok && !isConstValue(f, x.Args[1]) { + keys = append(keys, sentKey{k, x}) + } + case *ast.CompositeLit: + if !isURLValuesType(f, x.Type) { + return true + } + for _, el := range x.Elts { + kv, ok := el.(*ast.KeyValueExpr) + if !ok { + continue + } + if k, ok := stringLit(kv.Key); ok && !isConstValue(f, kv.Value) { + keys = append(keys, sentKey{k, kv}) + } + } + } + return true + }) + if len(hosts) == 0 { + return out + } + for _, k := range keys { + if !allowed[normName(k.key)] { + out = append(out, pluginRuleFinding{file: f.rel, line: src.line(k.node), + msg: fmt.Sprintf("%s sends %q to %s, which the spec's sends list does not name", fn.Name.Name, k.key, strings.Join(hosts, ", "))}) + } + } + return out +} + +func stringLit(e ast.Expr) (string, bool) { + lit, ok := e.(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return "", false + } + s, err := strconv.Unquote(lit.Value) + return s, err == nil +} + +func isURLValuesType(f *pluginFile, t ast.Expr) bool { + switch x := t.(type) { + case *ast.SelectorExpr: + p, name, ok := f.pkgSel(x) + return ok && p == "net/url" && name == "Values" + case *ast.MapType: + return exprText(x.Key) == "string" && exprText(x.Value) == "[]string" + } + return false +} + +// isConstValue reports whether a sent value is fixed in the source and so +// carries no data from the site or its visitors. +func isConstValue(f *pluginFile, e ast.Expr) bool { + switch x := e.(type) { + case *ast.BasicLit: + return true + case *ast.Ident: + return f.pkg.consts[x.Name] + case *ast.CompositeLit: + for _, el := range x.Elts { + if !isConstValue(f, el) { + return false + } + } + return true + case *ast.BinaryExpr: + return isConstValue(f, x.X) && isConstValue(f, x.Y) + } + return false +} diff --git a/plugin_forms.go b/plugin_forms.go new file mode 100644 index 0000000..f56cf9b --- /dev/null +++ b/plugin_forms.go @@ -0,0 +1,140 @@ +package main + +import ( + "fmt" + "go/ast" + "go/token" + "strconv" + "strings" +) + +var formReadMethods = map[string]bool{ + "ParseForm": true, "ParseMultipartForm": true, "FormValue": true, "PostFormValue": true, "FormFile": true, +} + +// checkPluginForms enforces that a public POST goes through route.Form, which +// requires the host-verified captcha and a per-instance submission limit. +func checkPluginForms(src *pluginSource) []pluginRuleFinding { + var out []pluginRuleFinding + routeLits := map[ast.Node]bool{} + handlers := map[*pluginPkg][]ast.Node{} + for _, f := range src.files { + for _, reg := range f.routeRegistrations() { + if lit, ok := reg.handler.(*ast.FuncLit); ok { + routeLits[lit] = true + } + handlers[f.pkg] = append(handlers[f.pkg], f.pkg.funcBodies(reg.handler)...) + if reg.access == "public" && !reg.form && !isReadMethod(f, reg.method) { + out = append(out, pluginRuleFinding{file: f.rel, line: src.line(reg.call), + msg: fmt.Sprintf("public route %s %s accepts a non-GET request; serve public posts with route.Form (captcha and rate limit)", shortExpr(reg.method), shortExpr(reg.path))}) + } + } + } + allowed := map[ast.Node]bool{} + for pkg, roots := range handlers { + for _, n := range pkg.reachable(roots) { + allowed[n] = true + } + } + for _, f := range src.files { + for _, decl := range f.ast.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil || allowed[fn] || callsCaptchaVerified(f, fn.Body) { + continue + } + if sig := postSignal(f, fn.Body, routeLits); sig != nil { + out = append(out, pluginRuleFinding{file: f.rel, line: src.line(sig), + msg: fmt.Sprintf("%s handles a form post (%s) outside route.Form; serve public posts with route.Form (captcha and rate limit)", fn.Name.Name, shortExpr(sig))}) + } + } + } + return out +} + +func isReadMethod(f *pluginFile, e ast.Expr) bool { + switch x := e.(type) { + case *ast.BasicLit: + s, err := strconv.Unquote(x.Value) + return err == nil && (strings.EqualFold(s, "GET") || strings.EqualFold(s, "HEAD")) + case *ast.SelectorExpr: + p, name, ok := f.pkgSel(x) + return ok && p == "net/http" && (name == "MethodGet" || name == "MethodHead") + } + return false +} + +func isPostMethod(f *pluginFile, e ast.Expr) bool { + switch x := e.(type) { + case *ast.BasicLit: + s, err := strconv.Unquote(x.Value) + return err == nil && strings.EqualFold(s, "POST") + case *ast.SelectorExpr: + p, name, ok := f.pkgSel(x) + return ok && p == "net/http" && name == "MethodPost" + } + return false +} + +func isMethodField(e ast.Expr) bool { + sel, ok := e.(*ast.SelectorExpr) + return ok && sel.Sel.Name == "Method" +} + +// postSignal returns the first expression in body that handles a form post: +// a comparison of r.Method with POST, a switch case on POST, or a form read. +// Function literals registered as route handlers are skipped. +func postSignal(f *pluginFile, body *ast.BlockStmt, routeLits map[ast.Node]bool) ast.Expr { + var found ast.Expr + ast.Inspect(body, func(n ast.Node) bool { + if found != nil || routeLits[n] { + return false + } + switch x := n.(type) { + case *ast.BinaryExpr: + if (x.Op == token.EQL || x.Op == token.NEQ) && + ((isMethodField(x.X) && isPostMethod(f, x.Y)) || (isMethodField(x.Y) && isPostMethod(f, x.X))) { + found = x + } + case *ast.SwitchStmt: + if x.Tag != nil && isMethodField(x.Tag) { + for _, stmt := range x.Body.List { + for _, e := range stmt.(*ast.CaseClause).List { + if isPostMethod(f, e) { + found = e + } + } + } + } + case *ast.CallExpr: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok && formReadMethods[sel.Sel.Name] { + if _, _, isPkg := f.pkgSel(sel); !isPkg { + found = x + } + } + case *ast.SelectorExpr: + if x.Sel.Name == "PostForm" || x.Sel.Name == "MultipartForm" { + if _, _, isPkg := f.pkgSel(x); !isPkg { + found = x + } + } + } + return found == nil + }) + return found +} + +// callsCaptchaVerified reports whether a hand-registered handler checks the +// host-verified captcha itself. Rule 33 still fails a generated plugin that +// registers it outside route, so this only quiets first-party handlers. +func callsCaptchaVerified(f *pluginFile, body *ast.BlockStmt) bool { + found := false + ast.Inspect(body, func(n ast.Node) bool { + if call, ok := n.(*ast.CallExpr); ok { + if p, name, ok := f.pkgFunc(call); ok && p == pluginSDKImportPrefix+"/auth" && name == "CaptchaVerified" { + found = true + } + } + return !found + }) + return found +} diff --git a/plugin_html.go b/plugin_html.go new file mode 100644 index 0000000..9c08157 --- /dev/null +++ b/plugin_html.go @@ -0,0 +1,621 @@ +package main + +import ( + "fmt" + "go/ast" + "go/token" + "regexp" + "strings" +) + +var htmlTagPattern = regexp.MustCompile(`<[A-Za-z/!]`) + +// htmlChecker finds HTML built by concatenation, fmt formatting or writer +// calls in which a non-constant string reaches the output unescaped. A value +// counts as safe when it is constant, numeric, passed through an escaper, or +// built only from safe values. Parameters, fields, map reads and other +// packages' results count as untrusted. +type htmlChecker struct { + src *pluginSource + f *pluginFile + fn *ast.FuncDecl + params map[paramKey]int // 1 safe, 2 unsafe, 3 in progress + scope *funcScope + visiting map[string]bool + summary map[*ast.FuncDecl]int // 1 safe, 2 unsafe, 3 in progress + reported map[string]bool + out []pluginRuleFinding +} + +func checkPluginHTML(src *pluginSource) []pluginRuleFinding { + var out []pluginRuleFinding + summary := map[*ast.FuncDecl]int{} + params := map[paramKey]int{} + for _, f := range src.files { + for _, decl := range f.ast.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + c := &htmlChecker{src: src, f: f, fn: fn, params: params, scope: newHTMLScope(f, fn), visiting: map[string]bool{}, summary: summary, reported: map[string]bool{}} + c.checkFunc(fn.Body) + out = append(out, c.out...) + } + } + return out +} + +func (c *htmlChecker) report(e ast.Expr) { + f := pluginRuleFinding{file: c.f.rel, line: c.src.line(e), + msg: fmt.Sprintf("%s reaches HTML output unescaped; wrap it in html.EscapeString or use html/template", shortExpr(e))} + key := fmt.Sprintf("%d %s", f.line, f.msg) + if c.reported[key] { + return + } + c.reported[key] = true + c.out = append(c.out, f) +} + +type htmlWrite struct { + call *ast.CallExpr + sink string + operands []ast.Expr + format ast.Expr // Fprintf format, nil otherwise +} + +func (c *htmlChecker) checkFunc(body *ast.BlockStmt) { + var writes []htmlWrite + ast.Inspect(body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.BinaryExpr: + if x.Op == token.ADD { + c.checkConcat(x) + for _, leaf := range concatLeaves(x) { + ast.Inspect(leaf, func(m ast.Node) bool { return c.visitNested(m) }) + } + return false + } + case *ast.AssignStmt: + if x.Tok == token.ADD_ASSIGN && len(x.Lhs) == 1 && len(x.Rhs) == 1 { + if id, ok := x.Lhs[0].(*ast.Ident); ok && c.holdsHTML(id.Name) { + c.checkOperand(x.Rhs[0]) + } + } + case *ast.CallExpr: + if p, name, ok := c.f.pkgFunc(x); ok && p == "fmt" && name == "Sprintf" && len(x.Args) > 0 && isHTMLConst(x.Args[0]) { + c.checkFormatArgs(x.Args[0], x.Args[1:]) + } + if w, ok := c.writeCall(x); ok { + writes = append(writes, w) + } + } + return true + }) + htmlSinks := map[string]bool{} + for _, w := range writes { + if w.format != nil && isHTMLConst(w.format) { + htmlSinks[w.sink] = true + } + for _, op := range w.operands { + if isHTMLConst(op) || c.isHTMLExpr(op) { + htmlSinks[w.sink] = true + } + } + } + for _, w := range writes { + if !htmlSinks[w.sink] { + continue + } + if w.format != nil { + c.checkFormatArgs(w.format, w.operands) + continue + } + for _, op := range w.operands { + c.checkOperand(op) + } + } +} + +// holdsHTML reports whether a local is ever assigned HTML, so appending to it +// with += builds HTML too. +func (c *htmlChecker) holdsHTML(name string) bool { + for _, v := range c.scope.assigns[name] { + if v != nil && (isHTMLConst(v) || c.isHTMLExpr(v)) { + return true + } + } + return false +} + +// visitNested continues the walk inside a concatenation operand so nested +// HTML builders are checked too. +func (c *htmlChecker) visitNested(n ast.Node) bool { + switch x := n.(type) { + case *ast.BinaryExpr: + if x.Op == token.ADD { + c.checkConcat(x) + } + case *ast.CallExpr: + if p, name, ok := c.f.pkgFunc(x); ok && p == "fmt" && name == "Sprintf" && len(x.Args) > 0 && isHTMLConst(x.Args[0]) { + c.checkFormatArgs(x.Args[0], x.Args[1:]) + } + } + return true +} + +func (c *htmlChecker) checkConcat(e *ast.BinaryExpr) { + leaves := concatLeaves(e) + html := false + for _, l := range leaves { + if isHTMLConst(l) { + html = true + } + } + if !html { + return + } + for _, l := range leaves { + c.checkOperand(l) + } +} + +// checkOperand reports an operand of HTML output that is not safe. Operands +// that are themselves HTML builders are checked where they are built. +func (c *htmlChecker) checkOperand(op ast.Expr) { + op = unparen(op) + if c.isHTMLExpr(op) { + return + } + if b, ok := op.(*ast.BinaryExpr); ok && b.Op == token.ADD { + for _, l := range concatLeaves(b) { + c.checkOperand(l) + } + return + } + if !c.safe(op) { + c.report(op) + } +} + +func (c *htmlChecker) checkFormatArgs(format ast.Expr, args []ast.Expr) { + s, ok := stringLit(format) + if !ok { + return + } + verbs := formatVerbs(s) + for i, a := range args { + if verbs != nil && i < len(verbs) && strings.ContainsRune("dbcoOxXUeEfFgGtp", verbs[i]) { + continue + } + c.checkOperand(a) + } +} + +// formatVerbs lists the verb of each argument a format consumes, or nil when +// the format uses explicit argument indexes. +func formatVerbs(s string) []rune { + var verbs []rune + for i := 0; i < len(s); i++ { + if s[i] != '%' { + continue + } + i++ + for i < len(s) && strings.IndexByte("+-# 0123456789.*[]", s[i]) >= 0 { + switch s[i] { + case '[': + return nil + case '*': + verbs = append(verbs, 'd') + } + i++ + } + if i < len(s) && s[i] != '%' { + verbs = append(verbs, rune(s[i])) + } + } + return verbs +} + +// writeCall recognises writes to a builder, buffer or writer. +func (c *htmlChecker) writeCall(call *ast.CallExpr) (htmlWrite, bool) { + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return htmlWrite{}, false + } + if p, name, isPkg := c.f.pkgSel(sel); isPkg { + if len(call.Args) == 0 || isStdStream(c.f, call.Args[0]) { + return htmlWrite{}, false + } + sink := sinkName(call.Args[0]) + switch { + case p == "fmt" && name == "Fprintf" && len(call.Args) >= 2: + return htmlWrite{call: call, sink: sink, format: call.Args[1], operands: call.Args[2:]}, true + case p == "fmt" && (name == "Fprint" || name == "Fprintln"): + return htmlWrite{call: call, sink: sink, operands: call.Args[1:]}, true + case p == "io" && name == "WriteString" && len(call.Args) == 2: + return htmlWrite{call: call, sink: sink, operands: call.Args[1:]}, true + } + return htmlWrite{}, false + } + if (sel.Sel.Name == "WriteString" || sel.Sel.Name == "Write") && len(call.Args) == 1 { + return htmlWrite{call: call, sink: sinkName(sel.X), operands: []ast.Expr{unwrapBytes(call.Args[0])}}, true + } + return htmlWrite{}, false +} + +func isStdStream(f *pluginFile, e ast.Expr) bool { + sel, ok := e.(*ast.SelectorExpr) + if !ok { + return false + } + p, name, isPkg := f.pkgSel(sel) + return isPkg && p == "os" && (name == "Stdout" || name == "Stderr") +} + +func sinkName(e ast.Expr) string { + if u, ok := e.(*ast.UnaryExpr); ok && u.Op == token.AND { + e = u.X + } + return exprText(e) +} + +func unwrapBytes(e ast.Expr) ast.Expr { + if call, ok := e.(*ast.CallExpr); ok && len(call.Args) == 1 { + if at, ok := call.Fun.(*ast.ArrayType); ok && exprText(at.Elt) == "byte" { + return call.Args[0] + } + } + return e +} + +func unparen(e ast.Expr) ast.Expr { + for { + p, ok := e.(*ast.ParenExpr) + if !ok { + return e + } + e = p.X + } +} + +func concatLeaves(e ast.Expr) []ast.Expr { + e = unparen(e) + if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.ADD { + return append(concatLeaves(b.X), concatLeaves(b.Y)...) + } + return []ast.Expr{e} +} + +func isHTMLConst(e ast.Expr) bool { + s, ok := stringLit(unparen(e)) + return ok && htmlTagPattern.MatchString(s) +} + +// isHTMLExpr reports whether e builds HTML itself (a concatenation or Sprintf +// with a tag in a constant), which the checker inspects separately. +func (c *htmlChecker) isHTMLExpr(e ast.Expr) bool { + e = unparen(e) + if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.ADD { + for _, l := range concatLeaves(b) { + if isHTMLConst(l) { + return true + } + } + } + if call, ok := e.(*ast.CallExpr); ok { + if p, name, ok := c.f.pkgFunc(call); ok && p == "fmt" && name == "Sprintf" && len(call.Args) > 0 && isHTMLConst(call.Args[0]) { + return true + } + } + return false +} + +var escaperFuncs = map[string]map[string]bool{ + "html": {"EscapeString": true}, + "html/template": {"HTMLEscapeString": true, "HTMLEscaper": true, "JSEscapeString": true, "URLQueryEscaper": true}, + "text/template": {"HTMLEscapeString": true, "HTMLEscaper": true, "JSEscapeString": true, "URLQueryEscaper": true}, + "net/url": {"QueryEscape": true, "PathEscape": true}, + "github.com/a-h/templ": {"EscapeString": true}, +} + +func (c *htmlChecker) safe(e ast.Expr) bool { + switch x := unparen(e).(type) { + case *ast.BasicLit, *ast.CompositeLit, *ast.FuncLit: + return true + case *ast.UnaryExpr: + return x.Op != token.AND || c.safe(x.X) + case *ast.BinaryExpr: + if x.Op != token.ADD || c.isHTMLExpr(x) { + return true + } + return c.safe(x.X) && c.safe(x.Y) + case *ast.Ident: + return c.safeIdent(x.Name) + case *ast.SliceExpr: + return c.safe(x.X) + case *ast.SelectorExpr: + if id, ok := x.X.(*ast.Ident); ok && c.scope.constRange[id.Name] { + return true + } + _, _, isPkg := c.f.pkgSel(x) + return isPkg + case *ast.CallExpr: + return c.safeCall(x) + } + return false +} + +func (c *htmlChecker) safeIdent(name string) bool { + switch name { + case "nil", "true", "false", "iota": + return true + } + if c.scope.constRange[name] { + return true + } + if c.scope.opaque[name] { + return !c.src.generated && c.paramSafe(name) + } + if xs, ok := c.scope.rangeOf[name]; ok { + if c.visiting[name] { + return true + } + c.visiting[name] = true + defer delete(c.visiting, name) + for _, x := range xs { + if !c.safe(x) { + return false + } + } + return true + } + if values, ok := c.scope.assigns[name]; ok { + if c.visiting[name] { + return true + } + c.visiting[name] = true + defer delete(c.visiting, name) + for _, v := range values { + if v != nil && !c.safe(v) { + return false + } + } + return true + } + if c.f.pkg.consts[name] { + return true + } + if v, ok := c.f.pkg.vars[name]; ok { + return v != nil && c.safe(v) + } + return false +} + +func (c *htmlChecker) safeCall(call *ast.CallExpr) bool { + allArgsSafe := func() bool { + for _, a := range call.Args { + if !c.safe(a) { + return false + } + } + return true + } + switch fn := unparen(call.Fun).(type) { + case *ast.ArrayType, *ast.MapType: + return allArgsSafe() + case *ast.FuncLit: + for _, results := range returnExprs(fn.Body) { + for _, r := range results { + if !c.isHTMLExpr(r) && !c.safe(r) { + return false + } + } + } + return true + case *ast.Ident: + switch fn.Name { + case "len", "cap", "min", "max": + return true + case "string", "append": + return allArgsSafe() + } + if decls := c.f.pkg.funcs[fn.Name]; len(decls) > 0 { + return c.funcReturnsSafe(decls) + } + return false + case *ast.SelectorExpr: + if p, name, isPkg := c.f.pkgSel(fn); isPkg { + switch { + case escaperFuncs[p][name], hasImportPrefix(p, pluginSDKImportPrefix) && trustedHTMLRenderers[name]: + return true + case p == "strconv": + return !strings.HasPrefix(name, "Quote") && !strings.HasPrefix(name, "Unquote") + case p == "fmt" && name == "Sprintf" && len(call.Args) > 0: + if c.isHTMLExpr(call) { + return true + } + verbs := formatVerbs(stringOr(call.Args[0])) + for i, a := range call.Args[1:] { + if verbs != nil && i < len(verbs) && strings.ContainsRune("dbcoOxXUeEfFgGtp", verbs[i]) { + continue + } + if !c.safe(a) { + return false + } + } + return true + case p == "fmt" && (name == "Sprint" || name == "Sprintln"), + p == "strings" && name != "Builder", + p == "html/template" && (name == "HTML" || name == "HTMLAttr" || name == "URL" || name == "CSS" || name == "JS"): + return allArgsSafe() + } + return false + } + if fn.Sel.Name == "String" && len(call.Args) == 0 { + // A builder's String() output is checked where it was written. + return true + } + if fn.Sel.Name == "Format" && len(call.Args) == 1 && isConstValue(c.f, call.Args[0]) { + return true + } + if decls := c.f.pkg.funcs[fn.Sel.Name]; len(decls) > 0 { + return c.funcReturnsSafe(decls) + } + return trustedHTMLRenderers[fn.Sel.Name] + } + return false +} + +// trustedHTMLRenderers are host and library methods that return sanitized +// HTML: the pluginsdk content service's BlockNote renderer and bluemonday. +var trustedHTMLRenderers = map[string]bool{"BlockNoteToHTML": true, "Sanitize": true} + +func stringOr(e ast.Expr) string { + s, _ := stringLit(e) + return s +} + +// funcReturnsSafe reports whether every value the functions return is safe +// or is HTML built (and checked) inside the function. +func (c *htmlChecker) funcReturnsSafe(decls []*ast.FuncDecl) bool { + for _, d := range decls { + switch c.summary[d] { + case 1, 3: + continue + case 2: + return false + } + c.summary[d] = 3 + inner := c.checkerFor(d) + ok := true + for _, results := range returnExprs(d.Body) { + for _, r := range results { + if !inner.isHTMLExpr(r) && !inner.safe(r) { + ok = false + } + } + } + if ok { + c.summary[d] = 1 + } else { + c.summary[d] = 2 + return false + } + } + return true +} + +// newHTMLScope is a funcScope that also marks range variables over a table +// written out in the source, such as a slice of constant structs, as safe. +func newHTMLScope(f *pluginFile, fn ast.Node) *funcScope { + s := newFuncScope(fn) + var constTable func(e ast.Expr, depth int) bool + constTable = func(e ast.Expr, depth int) bool { + if depth > 3 { + return false + } + switch x := e.(type) { + case *ast.CompositeLit: + for _, el := range x.Elts { + if kv, ok := el.(*ast.KeyValueExpr); ok { + el = kv.Value + } + if !isConstValue(f, el) && !constTable(el, depth+1) { + return false + } + } + return true + case *ast.Ident: + values := s.assigns[x.Name] + if len(values) == 0 { + if v, ok := f.pkg.vars[x.Name]; ok && v != nil { + values = []ast.Expr{v} + } + } + for _, v := range values { + if v == nil || !constTable(v, depth+1) { + return false + } + } + return len(values) > 0 + } + return false + } + ast.Inspect(fn, func(n ast.Node) bool { + if r, ok := n.(*ast.RangeStmt); ok && constTable(r.X, 0) { + if id, ok := r.Value.(*ast.Ident); ok { + s.constRange[id.Name] = true + } + } + return true + }) + return s +} + +type paramKey struct { + fn *ast.FuncDecl + index int +} + +func (c *htmlChecker) checkerFor(d *ast.FuncDecl) *htmlChecker { + f := c.src.declFile[d] + return &htmlChecker{src: c.src, f: f, fn: d, params: c.params, scope: newHTMLScope(f, d), visiting: map[string]bool{}, summary: c.summary, reported: map[string]bool{}} +} + +// paramSafe reports whether every same-package call to the current function +// passes a safe value for the named parameter. Generated plugins skip this: +// their parameters always count as untrusted. +func (c *htmlChecker) paramSafe(name string) bool { + if c.fn == nil || c.fn.Type.Params == nil { + return false + } + index, variadic := -1, false + i := 0 + for _, field := range c.fn.Type.Params.List { + for _, n := range field.Names { + if n.Name == name { + index = i + _, variadic = field.Type.(*ast.Ellipsis) + } + i++ + } + if len(field.Names) == 0 { + i++ + } + } + if index < 0 { + return false + } + key := paramKey{c.fn, index} + switch c.params[key] { + case 1, 3: + return true + case 2: + return false + } + c.params[key] = 3 + sites := c.src.callSitesOf(c.fn.Name.Name) + ok := len(sites) > 0 + for _, site := range sites { + args := site.call.Args + if index >= len(args) { + continue + } + args = args[index : index+1] + if variadic { + args = site.call.Args[index:] + } + caller := c.checkerFor(site.decl) + for _, a := range args { + if !caller.isHTMLExpr(a) && !caller.safe(a) { + ok = false + } + } + } + if ok { + c.params[key] = 1 + } else { + c.params[key] = 2 + } + return ok +} diff --git a/plugin_logs.go b/plugin_logs.go new file mode 100644 index 0000000..75f05f6 --- /dev/null +++ b/plugin_logs.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "go/ast" + "strings" +) + +var loggerMethods = map[string]bool{ + "Info": true, "Warn": true, "Error": true, "Debug": true, + "InfoContext": true, "WarnContext": true, "ErrorContext": true, "DebugContext": true, + "Log": true, "LogAttrs": true, "With": true, + "Print": true, "Printf": true, "Println": true, + "Fatal": true, "Fatalf": true, "Fatalln": true, "Panic": true, "Panicf": true, "Panicln": true, +} + +// checkPluginLogs flags log calls whose arguments name personal data. +func checkPluginLogs(src *pluginSource) []pluginRuleFinding { + var out []pluginRuleFinding + for _, f := range src.files { + ast.Inspect(f.ast, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok || !isLogCall(f, call) { + return true + } + var refs []string + for _, a := range call.Args { + refs = append(refs, src.personalRefs(f, a)...) + } + if len(refs) > 0 { + out = append(out, pluginRuleFinding{file: f.rel, line: src.line(call), + msg: fmt.Sprintf("%s logs personal data (%s); log an id or a count", shortExpr(call.Fun), strings.Join(dedupe(refs), ", "))}) + } + return false + }) + } + return out +} + +func isLogCall(f *pluginFile, call *ast.CallExpr) bool { + switch fn := call.Fun.(type) { + case *ast.Ident: + return fn.Name == "print" || fn.Name == "println" + case *ast.SelectorExpr: + if p, name, ok := f.pkgSel(fn); ok { + switch p { + case "log": + return true + case "log/slog": + return !strings.HasPrefix(name, "New") && name != "SetDefault" && name != "SetLogLoggerLevel" + case "fmt": + if strings.HasPrefix(name, "Print") { + return true + } + if strings.HasPrefix(name, "Fprint") && len(call.Args) > 0 { + if w, ok := call.Args[0].(*ast.SelectorExpr); ok { + wp, wn, isPkg := f.pkgSel(w) + return isPkg && wp == "os" && (wn == "Stdout" || wn == "Stderr") + } + } + } + return false + } + return loggerMethods[fn.Sel.Name] && len(call.Args) > 0 + } + return false +} + +func dedupe(xs []string) []string { + seen := map[string]bool{} + for _, x := range xs { + seen[x] = true + } + return sortedKeys(seen) +} diff --git a/plugin_routes.go b/plugin_routes.go new file mode 100644 index 0000000..1a095a0 --- /dev/null +++ b/plugin_routes.go @@ -0,0 +1,313 @@ +package main + +import ( + "fmt" + "go/ast" + "strings" +) + +var pluginRouterLibraries = []string{ + "github.com/go-chi/chi", + "github.com/gorilla/mux", + "github.com/julienschmidt/httprouter", + "github.com/labstack/echo", + "github.com/gin-gonic/gin", +} + +var chiRouteMethods = map[string]bool{ + "Get": true, "Post": true, "Put": true, "Patch": true, "Delete": true, "Head": true, "Options": true, + "Connect": true, "Trace": true, "Method": true, "MethodFunc": true, "Mount": true, "Route": true, +} + +// checkPluginRoutes enforces that a plugin serves HTTP only through pluginsdk +// route, which declares and enforces an access level per route, and that no +// public route reads a table holding personal columns. +func checkPluginRoutes(src *pluginSource) []pluginRuleFinding { + var out []pluginRuleFinding + add := func(f *pluginFile, n ast.Node, format string, a ...any) { + out = append(out, pluginRuleFinding{file: f.rel, line: src.line(n), msg: fmt.Sprintf(format, a...)}) + } + skip := src.accessDeclaredMuxCalls() + for _, f := range src.files { + chiName := "" + for name, p := range f.imports { + if strings.HasPrefix(p, "github.com/go-chi/chi") { + chiName = name + } + } + for _, spec := range f.ast.Imports { + p := strings.Trim(spec.Path.Value, `"`) + for _, lib := range pluginRouterLibraries { + if strings.HasPrefix(p, lib) { + add(f, spec, "imports router library %s; register routes with pluginsdk route.New", p) + } + } + } + ast.Inspect(f.ast, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.CallExpr: + sel, ok := x.Fun.(*ast.SelectorExpr) + if !ok || skip[x] { + return true + } + if p, name, ok := f.pkgSel(sel); ok { + switch { + case p == "net/http" && name == "NewServeMux": + add(f, x, "builds its own http.ServeMux; register routes with pluginsdk route.New") + case p == "net/http" && (name == "Handle" || name == "HandleFunc"): + add(f, x, "registers a handler with http.%s; register routes with pluginsdk route", name) + case strings.HasPrefix(p, "github.com/go-chi/chi") && (name == "NewRouter" || name == "NewMux"): + add(f, x, "builds a chi router; register routes with pluginsdk route.New") + } + return true + } + name := sel.Sel.Name + if (name == "Handle" || name == "HandleFunc") && len(x.Args) == 2 { + add(f, x, "registers %s on %s without an access level; register routes with pluginsdk route", name, shortExpr(sel.X)) + } + if chiName != "" && chiRouteMethods[name] && len(x.Args) == 2 { + add(f, x, "registers chi route %s on %s; register routes with pluginsdk route", name, shortExpr(sel.X)) + } + case *ast.KeyValueExpr: + if key, ok := x.Key.(*ast.Ident); ok && key.Name == "HTTPHandler" && !src.servesRouteRouter(f, x.Value) { + add(f, x, "HTTPHandler returns a handler that does not come from pluginsdk route.New") + } + } + return true + }) + for _, reg := range f.routeRegistrations() { + if reg.access != "public" { + continue + } + for _, n := range f.pkg.reachable(f.pkg.funcBodies(reg.handler)) { + if tables := src.storedPersonalReads(n); len(tables) > 0 { + add(f, reg.call, "public route %s reads personal data from table %s; use route.Admin or route.Visitor", shortExpr(reg.path), strings.Join(tables, ", ")) + break + } + } + } + } + return out +} + +// servesRouteRouter reports whether an HTTPHandler value returns a router +// built by pluginsdk route.New, directly, through a local helper, a local +// variable or a wrapper that takes the router as an argument. +func (src *pluginSource) servesRouteRouter(f *pluginFile, v ast.Expr) bool { + if id, ok := v.(*ast.Ident); ok && id.Name == "nil" { + return true + } + bodies := f.pkg.funcBodies(v) + if len(bodies) == 0 { + return false + } + for _, b := range bodies { + if !src.bodyReturnsRouter(f, b, 0) { + return false + } + } + return true +} + +func (src *pluginSource) bodyReturnsRouter(f *pluginFile, n ast.Node, depth int) bool { + if depth > 4 { + return false + } + var body *ast.BlockStmt + switch x := n.(type) { + case *ast.FuncDecl: + body = x.Body + f = src.declFile[x] + case *ast.FuncLit: + body = x.Body + } + results := returnExprs(body) + if len(results) == 0 { + return false + } + scope := newFuncScope(n) + connect, _ := connectMuxes(f, n) + for _, r := range results { + if len(r) == 0 || !src.isRouteRouter(f, scope, connect, r[0], depth, map[string]bool{}) { + return false + } + } + return true +} + +func (src *pluginSource) isRouteRouter(f *pluginFile, scope *funcScope, connect map[string]bool, e ast.Expr, depth int, visiting map[string]bool) bool { + switch x := e.(type) { + case *ast.ParenExpr: + return src.isRouteRouter(f, scope, connect, x.X, depth, visiting) + case *ast.Ident: + if x.Name == "nil" || connect[x.Name] { + return true + } + values, ok := scope.assigns[x.Name] + if !ok || visiting[x.Name] { + return false + } + visiting[x.Name] = true + for _, v := range values { + if v == nil || !src.isRouteRouter(f, scope, connect, v, depth, visiting) { + return false + } + } + return len(values) > 0 + case *ast.CallExpr: + if p, name, ok := f.pkgFunc(x); ok && ((p == routeImportPath && name == "New") || (p == "net/http" && name == "NotFoundHandler")) { + return true + } + var local []*ast.FuncDecl + switch fn := x.Fun.(type) { + case *ast.Ident: + local = f.pkg.funcs[fn.Name] + case *ast.SelectorExpr: + if _, _, isPkg := f.pkgSel(fn); !isPkg { + local = f.pkg.funcs[fn.Sel.Name] + } + } + if len(local) > 0 { + for _, d := range local { + if !src.bodyReturnsRouter(f, d, depth+1) { + return false + } + } + return true + } + for _, a := range x.Args { + if src.isRouteRouter(f, scope, connect, a, depth, visiting) { + return true + } + } + } + return false +} + +// accessDeclaredMuxCalls lists ServeMux constructions and registrations that +// still declare access: muxes that only mount Connect service bindings (the +// host enforces their RBAC method roles) and muxes inside the Assets handler +// that read no stored personal data. +func (src *pluginSource) accessDeclaredMuxCalls() map[ast.Node]bool { + skip := map[ast.Node]bool{} + assets := map[*pluginPkg][]ast.Node{} + for _, f := range src.files { + for _, decl := range f.ast.Decls { + if fn, ok := decl.(*ast.FuncDecl); ok { + _, calls := connectMuxes(f, fn) + for n := range calls { + skip[n] = true + } + } + } + ast.Inspect(f.ast, func(n ast.Node) bool { + if kv, ok := n.(*ast.KeyValueExpr); ok { + if key, ok := kv.Key.(*ast.Ident); ok && key.Name == "Assets" { + assets[f.pkg] = append(assets[f.pkg], f.pkg.funcBodies(kv.Value)...) + } + } + return true + }) + } + for pkg, roots := range assets { + for _, n := range pkg.reachable(roots) { + if len(src.storedPersonalReads(n)) > 0 { + continue + } + ast.Inspect(n, func(c ast.Node) bool { + if call, ok := c.(*ast.CallExpr); ok { + if sel, ok := call.Fun.(*ast.SelectorExpr); ok { + switch sel.Sel.Name { + case "NewServeMux", "Handle", "HandleFunc": + skip[call] = true + } + } + } + return true + }) + } + } + return skip +} + +func isConnectHandler(f *pluginFile, e ast.Expr) bool { + call, ok := e.(*ast.CallExpr) + if !ok { + return false + } + p, name, ok := f.pkgFunc(call) + return ok && p == "connectrpc.com/connect" && strings.HasPrefix(name, "New") && strings.HasSuffix(name, "Handler") +} + +// connectMuxes returns the ServeMux locals of fn whose every registration is +// mux.Handle(path, handler) with both values from a Connect binding's Build() +// or a handler from connect.New*Handler, plus the construction and +// registration calls of those muxes. +func connectMuxes(f *pluginFile, fn ast.Node) (map[string]bool, map[ast.Node]bool) { + scope := newFuncScope(fn) + fromBuild := func(e ast.Expr) bool { + id, ok := e.(*ast.Ident) + if !ok || len(scope.assigns[id.Name]) == 0 { + return false + } + for _, v := range scope.assigns[id.Name] { + call, ok := v.(*ast.CallExpr) + if !ok { + return false + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "Build" || len(call.Args) != 0 { + return false + } + } + return true + } + created := map[string][]ast.Node{} + for name, values := range scope.assigns { + for _, v := range values { + if call, ok := v.(*ast.CallExpr); ok { + if p, fname, ok := f.pkgFunc(call); ok && p == "net/http" && fname == "NewServeMux" { + created[name] = append(created[name], call) + } + } + } + } + regs := map[string][]*ast.CallExpr{} + ast.Inspect(fn, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Handle" || sel.Sel.Name == "HandleFunc") { + if id, ok := sel.X.(*ast.Ident); ok && created[id.Name] != nil { + regs[id.Name] = append(regs[id.Name], call) + } + } + return true + }) + names := map[string]bool{} + calls := map[ast.Node]bool{} + for name, rs := range regs { + ok := true + for _, r := range rs { + if r.Fun.(*ast.SelectorExpr).Sel.Name != "Handle" || len(r.Args) != 2 { + ok = false + continue + } + if !(fromBuild(r.Args[0]) && fromBuild(r.Args[1])) && !isConnectHandler(f, r.Args[1]) { + ok = false + } + } + if !ok { + continue + } + names[name] = true + for _, r := range rs { + calls[r] = true + } + for _, c := range created[name] { + calls[c] = true + } + } + return names, calls +} diff --git a/pluginrules.go b/pluginrules.go new file mode 100644 index 0000000..76e068d --- /dev/null +++ b/pluginrules.go @@ -0,0 +1,848 @@ +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"` + 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"` + } `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 + // 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{}, + 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 + } + addFields := func(fields []acceptanceField) { + for _, f := range fields { + if f.Personal { + src.personal[normName(f.Name)] = f.Name + } + } + } + s := src.spec.Spec + for _, b := range s.Blocks { + addFields(b.Fields) + } + for _, r := range s.Routes { + addFields(r.Fields) + } + addFields(s.Settings) + for _, t := range s.Tables { + for _, c := range t.PersonalColumns { + src.personal[normName(c)] = c + } + if len(t.PersonalColumns) > 0 { + camel := camelName(t.Name) + src.rowTypes[camel] = t.Name + src.rowTypes[camelName(singularName(t.Name))] = t.Name + } + } + 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 _, t := range src.spec.Spec.Tables { + if len(t.PersonalColumns) == 0 { + continue + } + if regexp.MustCompile(`\b` + regexp.QuoteMeta(strings.ToLower(t.Name)) + `\b`).MatchString(body) { + src.readQueries[m[1]] = t.Name + 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.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{} + 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 + } + } + 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) +} + +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) + } +} diff --git a/pluginrules_test.go b/pluginrules_test.go new file mode 100644 index 0000000..410219e --- /dev/null +++ b/pluginrules_test.go @@ -0,0 +1,328 @@ +package main + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +func pluginRuleFixture(t *testing.T, name string) *pluginSource { + t.Helper() + root, err := filepath.Abs(filepath.Join("testdata", "pluginrules", name)) + if err != nil { + t.Fatal(err) + } + src, err := loadPluginSource(root) + if err != nil { + t.Fatalf("load %s: %v", name, err) + } + return src +} + +// wantFindings asserts that the rule finds exactly the listed file:line +// locations, each with a message containing the given text. +func wantFindings(t *testing.T, got []pluginRuleFinding, want map[string]string) { + t.Helper() + seen := map[string]string{} + for _, f := range got { + seen[f.file+":"+strconv.Itoa(f.line)] = f.msg + } + for loc, text := range want { + msg, ok := seen[loc] + if !ok { + t.Errorf("missing finding at %s (%q); got %v", loc, text, got) + continue + } + if !strings.Contains(msg, text) { + t.Errorf("finding at %s = %q, want it to mention %q", loc, msg, text) + } + } + for loc, msg := range seen { + if _, ok := want[loc]; !ok { + t.Errorf("unexpected finding %s %s", loc, msg) + } + } +} + +func TestPluginRoutesFlagsWO088ServeMux(t *testing.T) { + wantFindings(t, checkPluginRoutes(pluginRuleFixture(t, "quote-fail")), map[string]string{ + "registration.go:20": "HTTPHandler returns a handler that does not come from pluginsdk route.New", + "handler.go:15": "builds its own http.ServeMux", + "handler.go:16": "registers HandleFunc on mux", + "handler.go:17": "registers HandleFunc on mux", + }) +} + +func TestPluginRoutesFlagsPublicRouteReadingPersonalTable(t *testing.T) { + wantFindings(t, checkPluginRoutes(pluginRuleFixture(t, "quote-route-fail")), map[string]string{ + "handler.go:17": "public route \"/requests\" reads personal data from table quote_requests", + }) +} + +func TestPluginHTMLFlagsUnescapedRow(t *testing.T) { + wantFindings(t, checkPluginHTML(pluginRuleFixture(t, "quote-fail")), map[string]string{ + "registration.go:57": "row.Name reaches HTML output unescaped", + }) +} + +func TestPluginFormsFlagsUnguardedPost(t *testing.T) { + wantFindings(t, checkPluginForms(pluginRuleFixture(t, "quote-fail")), map[string]string{ + "handler.go:22": "handleSubmit handles a form post (r.Method != http.MethodPost) outside route.Form", + }) +} + +func TestPluginFormsFlagsPublicHandlePost(t *testing.T) { + wantFindings(t, checkPluginForms(pluginRuleFixture(t, "quote-route-fail")), map[string]string{ + "handler.go:16": "public route http.MethodPost \"/submit\" accepts a non-GET request", + }) +} + +func TestPluginLogsFlagsPersonalData(t *testing.T) { + wantFindings(t, checkPluginLogs(pluginRuleFixture(t, "quote-fail")), map[string]string{ + "handler.go:47": "slog.Info logs personal data (email)", + }) +} + +func TestPluginEgressFlagsStoredPersonalData(t *testing.T) { + got := checkPluginEgress(pluginRuleFixture(t, "weather-fail")) + var msgs []string + for _, f := range got { + msgs = append(msgs, strconv.Itoa(f.line)+" "+f.msg) + } + joined := strings.Join(msgs, "\n") + for _, want := range []string{ + "49 outbound request in fetchForecast carries personal data (address)", + "49 outbound request in fetchForecast uses stored personal data from forecast_signups (LatestForecastSignup)", + "46 fetchForecast sends \"address\" to api.open-meteo.com, which the spec's sends list does not name", + } { + if !strings.Contains(joined, want) { + t.Errorf("missing %q in:\n%s", want, joined) + } + } + if len(got) != 3 { + t.Errorf("want 3 findings, got %d:\n%s", len(got), joined) + } +} + +func TestPluginEgressFlagsPersonalArgumentAtCallSite(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "acceptance.json", `{"name":"x","spec":{"routes":[{"method":"POST","path":"/s","access":"public","fields":[{"name":"email","personal":true}]}],"outbound_hosts":[{"host":"api.example.com","sends":["q"]}]}}`) + writeFile(t, dir, "a.go", `package main + +import "net/http" + +func lookup(q string) error { + _, err := http.Get("https://api.example.com/v1?q=" + q) + return err +} + +func onSubmit(r *http.Request) error { + email := r.FormValue("email") + return lookup(email) +} +`) + src, err := loadPluginSource(dir) + if err != nil { + t.Fatal(err) + } + wantFindings(t, checkPluginEgress(src), map[string]string{ + "a.go:12": "passes personal data (email) to lookup", + }) +} + +func TestPluginRulesPassOnFixedPlugins(t *testing.T) { + rules := map[string]func(*pluginSource) []pluginRuleFinding{ + "routes": checkPluginRoutes, "html": checkPluginHTML, "forms": checkPluginForms, + "logs": checkPluginLogs, "egress": checkPluginEgress, + } + for _, fixture := range []string{"quote-pass", "weather-pass"} { + src := pluginRuleFixture(t, fixture) + for name, rule := range rules { + for _, f := range rule(src) { + t.Errorf("%s %s: unexpected finding %s:%d %s", fixture, name, f.file, f.line, f.msg) + } + } + } +} + +func TestPluginHTMLSafeValues(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "a.go", `package main + +import ( + "fmt" + "html" + "strconv" + "strings" +) + +const cls = "x" + +func label(s string) string { return html.EscapeString(s) } + +func render(name string, n int, items []string) string { + var b strings.Builder + b.WriteString("
" + strconv.Itoa(n) + label(name) + "
") + return b.String() + "%s
", name) + b.String() +} +`) + src, err := loadPluginSource(dir) + if err != nil { + t.Fatal(err) + } + wantFindings(t, checkPluginHTML(src), map[string]string{ + "a.go:28": "it reaches HTML output unescaped", + "a.go:30": "name reaches HTML output unescaped", + }) +} + +func TestPluginRuleSeverityFollowsAcceptanceJSON(t *testing.T) { + generated := t.TempDir() + if err := os.CopyFS(generated, os.DirFS(filepath.Join("testdata", "pluginrules", "quote-fail"))); err != nil { + t.Fatal(err) + } + firstParty := t.TempDir() + if err := os.CopyFS(firstParty, os.DirFS(filepath.Join("testdata", "pluginrules", "quote-fail"))); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(firstParty, "acceptance.json")); err != nil { + t.Fatal(err) + } + notPlugin := t.TempDir() + writeFile(t, notPlugin, "a.go", "package a\n") + + cases := []struct { + name string + root string + status status + exitCode int + }{ + {"generated plugin fails", generated, statusFail, 1}, + {"first-party plugin warns", firstParty, statusWarn, 0}, + {"non-plugin root skips", notPlugin, statusSkip, 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx := &ScanContext{backendTargets: []backendScanTarget{{root: tc.root, display: "p"}}} + rep := &Reporter{} + rep.begin(360, "36", "logs") + runPluginRule(ctx, rep, "plugin log call(s) with personal data", checkPluginLogs) + if rep.current.status != tc.status || rep.exitCode != tc.exitCode { + t.Fatalf("status %v exit %d, want %v exit %d (%v)", rep.current.status, rep.exitCode, tc.status, tc.exitCode, rep.current.findings) + } + }) + } +} + +func TestPluginHTMLParametersStrictOnlyForGeneratedPlugins(t *testing.T) { + code := `package main + +import "fmt" + +func field(id, label string) string { + return fmt.Sprintf("", id, label) +} + +func form() string { + return "Thank you. Your quote request has been received.
")) +} + +// handleList returns every stored quote request to any caller. +func handleList(w http.ResponseWriter, r *http.Request) { + dbtx, ok := current.Pool.(db.DBTX) + if !ok { + http.Error(w, "service unavailable", http.StatusServiceUnavailable) + return + } + rows, err := db.New(dbtx).ListQuoteRequests(r.Context()) + if err != nil { + http.Error(w, "could not load requests", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(rows) +} diff --git a/testdata/pluginrules/quote-fail/plugin.mod b/testdata/pluginrules/quote-fail/plugin.mod new file mode 100644 index 0000000..5972a4f --- /dev/null +++ b/testdata/pluginrules/quote-fail/plugin.mod @@ -0,0 +1,4 @@ +name = "quote-requests-a1a5c0" +version = "1.0.0" +kind = "plugin" +private = true diff --git a/testdata/pluginrules/quote-fail/registration.go b/testdata/pluginrules/quote-fail/registration.go new file mode 100644 index 0000000..5913c08 --- /dev/null +++ b/testdata/pluginrules/quote-fail/registration.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "html" + + "git.dev.alexdunmow.com/block/pluginsdk/blocks" + "git.dev.alexdunmow.com/block/pluginsdk/plugin" + "git.dev.alexdunmow.com/block/pluginsdk/templates" + "git.dev.alexdunmow.com/private/quote-requests-a1a5c0/db" +) + +const pluginName = "quote-requests-a1a5c0" + +// Registration is the plugin entry registration. +var Registration = plugin.PluginRegistration{ + Name: pluginName, + Version: "1.0.0", + Register: register, + HTTPHandler: newHTTPHandler, +} + +var current plugin.CoreServices + +func setServices(deps plugin.CoreServices) { current = deps } + +func register(_ templates.TemplateRegistry, br blocks.BlockRegistry) error { + br.Register(blocks.BlockMeta{Key: "quote_request_form", Title: "Quote request form"}, renderForm) + br.Register(blocks.BlockMeta{Key: "recent_requests", Title: "Recent requests"}, renderRecent) + return nil +} + +func str(content map[string]any, key string) string { + s, _ := content[key].(string) + return html.EscapeString(s) +} + +func renderForm(_ context.Context, content map[string]any) string { + return `Thank you. We received %d characters.
", len(params.RoofIssue)) +} + +func handleList(w http.ResponseWriter, r *http.Request) { + dbtx, ok := current.Pool.(db.DBTX) + if !ok { + http.Error(w, "service unavailable", http.StatusServiceUnavailable) + return + } + rows, err := db.New(dbtx).ListQuoteRequests(r.Context()) + if err != nil { + http.Error(w, "could not load requests", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(rows) +} diff --git a/testdata/pluginrules/quote-pass/plugin.mod b/testdata/pluginrules/quote-pass/plugin.mod new file mode 100644 index 0000000..5972a4f --- /dev/null +++ b/testdata/pluginrules/quote-pass/plugin.mod @@ -0,0 +1,4 @@ +name = "quote-requests-a1a5c0" +version = "1.0.0" +kind = "plugin" +private = true diff --git a/testdata/pluginrules/quote-pass/registration.go b/testdata/pluginrules/quote-pass/registration.go new file mode 100644 index 0000000..8cb7c2d --- /dev/null +++ b/testdata/pluginrules/quote-pass/registration.go @@ -0,0 +1,64 @@ +package main + +import ( + "context" + "html" + + "git.dev.alexdunmow.com/block/pluginsdk/blocks" + "git.dev.alexdunmow.com/block/pluginsdk/plugin" + "git.dev.alexdunmow.com/block/pluginsdk/templates" + "git.dev.alexdunmow.com/private/quote-requests-a1a5c0/db" +) + +const pluginName = "quote-requests-a1a5c0" + +// Registration is the plugin entry registration. +var Registration = plugin.PluginRegistration{ + Name: pluginName, + Version: "1.0.0", + Register: register, + HTTPHandler: newHTTPHandler, +} + +var current plugin.CoreServices + +func setServices(deps plugin.CoreServices) { current = deps } + +func register(_ templates.TemplateRegistry, br blocks.BlockRegistry) error { + br.Register(blocks.BlockMeta{Key: "quote_request_form", Title: "Quote request form"}, renderForm) + br.Register(blocks.BlockMeta{Key: "recent_requests", Title: "Recent requests"}, renderRecent) + return nil +} + +func str(content map[string]any, key string) string { + s, _ := content[key].(string) + return html.EscapeString(s) +} + +func renderForm(_ context.Context, content map[string]any) string { + button := str(content, "button_label") + if button == "" { + button = "Send" + } + return `" + html.EscapeString(note) + "
") + } else { + if town != "" { + b.WriteString("" + html.EscapeString(town) + "
") + } + b.WriteString("