check-safety/pluginrules_test.go
Alex Dunmow 8b8afc044d Classify personal data deterministically and cover site data tables in check 33 (ADR 0007)
A factory spec's personal flags come from Scout. For a factory-generated
plugin, names, sample shapes, visitor form fields and migration columns
now mark personal data too, and the stricter result applies. A public
route that reads a site data table, or personal plugin settings, fails
check 33. frontend.go, plugin_egress.go, plugin_html.go and
plugin_routes.go carry the lint autofixes check 3 applies to this repo.

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

362 lines
11 KiB
Go

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("<ul class=\"" + cls + "\">")
for _, it := range items {
fmt.Fprintf(&b, "<li>%s (%d)</li>", html.EscapeString(it), n)
}
b.WriteString("<p>" + strconv.Itoa(n) + label(name) + "</p>")
return b.String() + "</ul>"
}
func unsafe(name string, items []string) string {
var b strings.Builder
b.WriteString("<ul>")
for _, it := range items {
b.WriteString(it)
}
return fmt.Sprintf("<p>%s</p>", 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("<label for=%q>%s</label>", id, label)
}
func form() string {
return "<form>" + field("email", "Email") + "</form>"
}
`
firstParty := t.TempDir()
writeFile(t, firstParty, "a.go", code)
src, err := loadPluginSource(firstParty)
if err != nil {
t.Fatal(err)
}
wantFindings(t, checkPluginHTML(src), map[string]string{})
generated := t.TempDir()
writeFile(t, generated, "a.go", code)
writeFile(t, generated, "acceptance.json", `{"name":"x","spec":{}}`)
src, err = loadPluginSource(generated)
if err != nil {
t.Fatal(err)
}
wantFindings(t, checkPluginHTML(src), map[string]string{
"a.go:6": "reaches HTML output unescaped",
})
}
func TestPluginRoutesAcceptsConnectBindingsAndAssets(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "a.go", `package main
import (
"net/http"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
)
var Registration = plugin.PluginRegistration{
HTTPHandler: func(deps plugin.CoreServices) http.Handler { return serviceHandler(deps) },
Assets: assetsHandler,
}
func serviceHandler(deps plugin.CoreServices) http.Handler {
reg, err := PluginServiceHandlers(deps)
if err != nil {
return http.NotFoundHandler()
}
mux := http.NewServeMux()
for _, binding := range reg.Services {
path, handler := binding.Build()
mux.Handle(path, handler)
}
return auth.TrustedHeaderMiddleware(mux)
}
func assetsHandler() http.Handler {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(assetFS)))
return mux
}
`)
src, err := loadPluginSource(dir)
if err != nil {
t.Fatal(err)
}
wantFindings(t, checkPluginRoutes(src), map[string]string{})
}
func TestPluginRoutesAcceptsHandBuiltConnectHandlers(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "a.go", `package main
import (
"net/http"
"connectrpc.com/connect"
)
func serviceMux() http.Handler {
mux := http.NewServeMux()
mux.Handle("/svc.v1.S/Echo", connect.NewUnaryHandler("/svc.v1.S/Echo", echo))
return mux
}
`)
src, err := loadPluginSource(dir)
if err != nil {
t.Fatal(err)
}
wantFindings(t, checkPluginRoutes(src), map[string]string{})
}
func TestPluginRoutesFlagsPublicRouteReadingASiteDataTable(t *testing.T) {
wantFindings(t, checkPluginRoutes(pluginRuleFixture(t, "signups-datatable-fail")), map[string]string{
"handler.go:25": "reads personal data from table site data table (ListRows)",
})
}
func TestPluginClassifierOverridesTheSpecsPersonalFlags(t *testing.T) {
src := pluginRuleFixture(t, "classifier-fail")
wantFindings(t, checkPluginLogs(src), map[string]string{
"handler.go:39": "logs personal data (email, notes)",
})
wantFindings(t, checkPluginRoutes(src), map[string]string{
"handler.go:32": "reads personal data from table callers",
})
for name, want := range map[string]string{
"email": "email", "customerEmail": "email", "contact_phone": "phone", "mobile": "phone", "date_of_birth": "birth",
"street_address": "address", "postcode": "address", "first_name": "name", "customer_name": "name", "name": "name",
"town_name": "", "business_name": "", "latitude": "", "heading": "", "roof_type": "", "zipline": "",
} {
if got := personalKind(name); got != want {
t.Errorf("personalKind(%q) = %q, want %q", name, got, want)
}
}
for v, want := range map[string]string{
"jane@example.com": "email", "0412 345 678": "phone", "+61 412 345 678": "phone", "0412345678": "phone",
"1732252800": "", "2026-11-20": "", "-37.5622": "", "Cedar Falls": "",
} {
if got := sampleKind(v); got != want {
t.Errorf("sampleKind(%q) = %q, want %q", v, got, want)
}
}
}