Compare commits

..

2 Commits

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:48:11 +08:00
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
22 changed files with 628 additions and 30 deletions

View File

@ -127,7 +127,7 @@ tool prints in each check header):
| 29 | No legacy Go plugins | No `-buildmode=plugin` targets remain after the wasm migration gate is enabled. | | 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. | | 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). | | 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`. | | 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 holds a personal column. In a factory-generated plugin a read of a site data table (`DataTables.ListRows`, `GetRow`, `FindRowByField`) counts as personal, and so does `GetPluginSettings` when a setting is personal. |
| 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. | | 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. | | 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. | | 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. |
@ -142,7 +142,12 @@ non-test, non-generated Go sources.
- **Factory-generated plugin** (an `acceptance.json` at the plugin root): every finding is a - **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 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 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 `"personal": true`. A deterministic classifier (`pluginrules_classify.go`, ADR 0007) adds to
them, and the stricter result applies: a name whose words mean email, phone, name, address,
date of birth or an identifier, a sample shaped like an email address or phone number, every
field of a public or visitor POST route (free text a visitor types), and the columns of
`migrations/*.sql` tables that are personal by name or by type (`inet`, `cidr`). A table with
any such column is personal. 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 generated row types as stored personal data, and `outbound_hosts[].sends` lists the values
each host may receive. each host may receive.
- **First-party plugin** (no `acceptance.json`): every finding is a WARN, so human-reviewed - **First-party plugin** (no `acceptance.json`): every finding is a WARN, so human-reviewed

View File

@ -0,0 +1,68 @@
# Personal data is classified deterministically, and public routes cover site data tables
Builds on ADR 0006. Orchestrator WO-100 (gaps 5, 6 and 7 of WO-097).
Checks 33, 36 and 37 took personal data names from the factory spec alone. Scout writes the
spec, so a spec that marked `email` as not personal turned the log and egress rules off for it,
a `notes` column that stores visitors' phone numbers was never personal, and a public route that
listed a site data table was not flagged because only the plugin's own tables were traced.
Decision: for a factory-generated plugin (an `acceptance.json` at the root), a deterministic
classifier runs over the spec and the generated schema and the stricter result applies.
- A name is personal when the spec says so or its words do: email, phone and its synonyms
(mobile, tel, cell, fax, sms), birth or dob, address and its parts (street, postcode, zip,
postal), identifiers (ip, ssn, passport, password, licence, medicare), and person names
(`name`, first, last, full, given, family, or an owner word such as customer, client, contact,
guest or visitor before `name`). `town_name` and `business_name` are not personal.
- A field whose sample looks like an email address or a phone number is personal. A run of
digits counts as a phone number only with a leading 0 or +, or with separators, so timestamps
and amounts do not.
- Every field of a public or visitor POST route is personal: it is free text a visitor types.
A table column with the same name is personal, which covers the `notes` example.
- `migrations/*.sql` CREATE TABLE columns that are personal by name, or typed `inet` or `cidr`,
make their table personal, including tables the spec never listed.
- In a generated plugin a public route that reads a site data table (`DataTables.ListRows`,
`GetRow`, `FindRowByField`) fails check 33, because a site data table's fields are not in the
spec and the check cannot prove they hold no personal data. `GetPluginSettings` counts as a
personal read when a setting is personal.
- A value passed through `len()` carries no personal data, so logging a length is allowed.
The CMS host runs the same name rules at runtime for factory-built plugins (cms ADR 0233,
`plugin/factory_guard.go` `personalKind`), where it also classifies values by shape. The two
copies are small and must stay aligned; check-safety stays standalone and imports nothing from
the CMS.
Rejected: sharing the classifier through a pluginsdk package. The CMS go.mod would have to move
to an unreleased pluginsdk version, and check-safety imports no sibling module.
Consequences:
- `pluginrules_classify.go` (`personalKind`, `sampleKind`, `migrationColumns`); `indexSpec`,
`indexQueries` and `storedPersonalReads` in `pluginrules.go` use the classified set
(`personalTables`, `personalSettings`).
- Fixtures `testdata/pluginrules/signups-datatable-fail` (a `route.Public` GET listing the
`signups` data table) and `classifier-fail` (a spec that marks `email` and `notes` not personal,
and a migration table `callers` with `mobile` and an `inet` column). Tests
`TestPluginRoutesFlagsPublicRouteReadingASiteDataTable` and
`TestPluginClassifierOverridesTheSpecsPersonalFlags`.
- First-party plugins keep the default name list and warnings only.
Keywords: personal data classifier, deterministic classifier, personalKind, sampleKind, migrationColumns, personalTables, personalSettings, site data table, DataTables, ListRows, GetRow, FindRowByField, GetPluginSettings, check 33, check 36, check 37, visitor form, free text, inet, cidr, notes column, WO-100, gap 5, gap 6, gap 7, acceptance.json
## Amendment 2026-11-22: declared site data tables
Since orchestrator WO-099 the spec declares the site data tables a plugin reads (`data_tables[]`
with `key` and `fields[]`), and the rule above refused the events plugin's public `/events.ics`
feed. When the spec has `data_tables`, a site data table read counts as personal only when the
table it reads has a field marked `personal` or one the classifier calls personal (by name or
sample shape), so a public route over an `events` table passes and one over a table with an
`email` field fails even when the spec marks it not personal. The table is resolved from the
literal key of a `GetTableByKey` call in the same function; a read whose table cannot be resolved
statically counts as personal when any declared table is, and a literal key the spec does not
declare counts as personal. Without `data_tables` in the spec the earlier rule stands: every read
is personal. Fixtures `events-datatable-pass` and `subscribers-datatable-fail`, test
`TestPluginRoutesJudgeSiteDataTablesByTheirDeclaredFields`. Declared data table fields also join
the personal names the log and egress rules use.
Keywords: data_tables, declared site data table, dataTableReadPersonal, personalDataTables, GetTableByKey, events.ics, events-datatable-pass, subscribers-datatable-fail

View File

@ -348,11 +348,11 @@ func literalFetchTarget(line string) (string, bool) {
} }
call := line[match[0]:] call := line[match[0]:]
open := strings.IndexByte(call, '(') _, after, ok := strings.Cut(call, "(")
if open < 0 { if !ok {
return "", false return "", false
} }
rest := strings.TrimLeft(call[open+1:], " \t") rest := strings.TrimLeft(after, " \t")
if len(rest) < 2 || (rest[0] != '\'' && rest[0] != '"' && rest[0] != '`') { if len(rest) < 2 || (rest[0] != '\'' && rest[0] != '"' && rest[0] != '`') {
return "", false return "", false
} }

View File

@ -150,7 +150,7 @@ func (src *pluginSource) egressKeyFindings(f *pluginFile, fn *ast.FuncDecl) []pl
for k := range sends { for k := range sends {
allowed[k] = true allowed[k] = true
} }
for _, part := range strings.Split(u.RawQuery, "&") { for part := range strings.SplitSeq(u.RawQuery, "&") {
k, v, _ := strings.Cut(part, "=") k, v, _ := strings.Cut(part, "=")
if k != "" && (v == "" || strings.Contains(v, "%")) { if k != "" && (v == "" || strings.Contains(v, "%")) {
keys = append(keys, sentKey{k, x}) keys = append(keys, sentKey{k, x})

View File

@ -5,6 +5,7 @@ import (
"go/ast" "go/ast"
"go/token" "go/token"
"regexp" "regexp"
"slices"
"strings" "strings"
) )
@ -296,10 +297,8 @@ func isHTMLConst(e ast.Expr) bool {
func (c *htmlChecker) isHTMLExpr(e ast.Expr) bool { func (c *htmlChecker) isHTMLExpr(e ast.Expr) bool {
e = unparen(e) e = unparen(e)
if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.ADD { if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.ADD {
for _, l := range concatLeaves(b) { if slices.ContainsFunc(concatLeaves(b), isHTMLConst) {
if isHTMLConst(l) { return true
return true
}
} }
} }
if call, ok := e.(*ast.CallExpr); ok { if call, ok := e.(*ast.CallExpr); ok {

View File

@ -294,7 +294,7 @@ func connectMuxes(f *pluginFile, fn ast.Node) (map[string]bool, map[ast.Node]boo
ok = false ok = false
continue continue
} }
if !(fromBuild(r.Args[0]) && fromBuild(r.Args[1])) && !isConnectHandler(f, r.Args[1]) { if (!fromBuild(r.Args[0]) || !fromBuild(r.Args[1])) && !isConnectHandler(f, r.Args[1]) {
ok = false ok = false
} }
} }

View File

@ -28,6 +28,7 @@ var defaultPersonalNames = []string{"email", "phone", "address", "password", "da
type acceptanceField struct { type acceptanceField struct {
Name string `json:"name"` Name string `json:"name"`
Sample string `json:"sample"`
Personal bool `json:"personal"` Personal bool `json:"personal"`
} }
@ -53,7 +54,11 @@ type acceptanceSpec struct {
Host string `json:"host"` Host string `json:"host"`
Sends []string `json:"sends"` Sends []string `json:"sends"`
} `json:"outbound_hosts"` } `json:"outbound_hosts"`
Settings []acceptanceField `json:"settings"` Settings []acceptanceField `json:"settings"`
DataTables []struct {
Key string `json:"key"`
Fields []acceptanceField `json:"fields"`
} `json:"data_tables"`
} `json:"spec"` } `json:"spec"`
} }
@ -88,6 +93,14 @@ type pluginSource struct {
readQueries map[string]string readQueries map[string]string
// rowTypes maps a generated row type name of a personal table to the table. // rowTypes maps a generated row type name of a personal table to the table.
rowTypes map[string]string rowTypes map[string]string
// personalTables names the tables holding a personal column, by the spec
// or by the classifier.
personalTables map[string]bool
// personalSettings is true when a plugin setting holds personal data.
personalSettings bool
// personalDataTables maps each site data table the spec declares to
// whether it holds a personal field; nil when the spec declares none.
personalDataTables map[string]bool
// sends maps an outbound host to the normalised names the spec lets it receive. // sends maps an outbound host to the normalised names the spec lets it receive.
sends map[string]map[string]bool sends map[string]map[string]bool
// declFile maps each function declaration to the file that holds it. // declFile maps each function declaration to the file that holds it.
@ -145,7 +158,9 @@ func loadPluginSource(root string) (*pluginSource, error) {
readQueries: map[string]string{}, readQueries: map[string]string{},
rowTypes: map[string]string{}, rowTypes: map[string]string{},
sends: map[string]map[string]bool{}, sends: map[string]map[string]bool{},
declFile: map[*ast.FuncDecl]*pluginFile{},
personalTables: map[string]bool{},
declFile: map[*ast.FuncDecl]*pluginFile{},
} }
if data, err := os.ReadFile(filepath.Join(root, "acceptance.json")); err == nil { if data, err := os.ReadFile(filepath.Join(root, "acceptance.json")); err == nil {
var spec acceptanceSpec var spec acceptanceSpec
@ -220,31 +235,54 @@ func (src *pluginSource) indexSpec() {
} }
return return
} }
addFields := func(fields []acceptanceField) { // A field is personal when the spec says so or the classifier does: by its
// name, its sample's shape, or because a visitor types it into a form.
addFields := func(fields []acceptanceField, visitorForm bool) bool {
found := false
for _, f := range fields { for _, f := range fields {
if f.Personal { if f.Personal || visitorForm || personalKind(f.Name) != "" || sampleKind(f.Sample) != "" {
src.personal[normName(f.Name)] = f.Name src.personal[normName(f.Name)] = f.Name
found = true
} }
} }
return found
} }
s := src.spec.Spec s := src.spec.Spec
for _, b := range s.Blocks { for _, b := range s.Blocks {
addFields(b.Fields) addFields(b.Fields, false)
} }
for _, r := range s.Routes { for _, r := range s.Routes {
addFields(r.Fields) addFields(r.Fields, strings.EqualFold(r.Method, "POST") && (r.Access == "public" || r.Access == "visitor"))
} }
addFields(s.Settings) src.personalSettings = addFields(s.Settings, false)
for _, t := range s.Tables { if len(s.DataTables) > 0 {
for _, c := range t.PersonalColumns { src.personalDataTables = map[string]bool{}
for _, dt := range s.DataTables {
src.personalDataTables[dt.Key] = addFields(dt.Fields, false)
}
}
markTable := func(table string, cols []string) {
for _, c := range cols {
src.personal[normName(c)] = c src.personal[normName(c)] = c
} }
if len(t.PersonalColumns) > 0 { if len(cols) > 0 {
camel := camelName(t.Name) src.personalTables[table] = true
src.rowTypes[camel] = t.Name src.rowTypes[camelName(table)] = table
src.rowTypes[camelName(singularName(t.Name))] = t.Name src.rowTypes[camelName(singularName(table))] = table
} }
} }
for _, t := range s.Tables {
cols := append([]string(nil), t.PersonalColumns...)
for _, c := range t.Columns {
if _, named := src.personal[normName(c)]; named || personalKind(c) != "" {
cols = append(cols, c)
}
}
markTable(t.Name, cols)
}
for table, cols := range migrationColumns(src.root) {
markTable(table, cols)
}
for _, h := range s.OutboundHosts { for _, h := range s.OutboundHosts {
names := map[string]bool{} names := map[string]bool{}
for _, n := range h.Sends { for _, n := range h.Sends {
@ -279,12 +317,9 @@ func (src *pluginSource) indexQueries(literals []string) {
if !reads { if !reads {
continue continue
} }
for _, t := range src.spec.Spec.Tables { for _, table := range sortedKeys(src.personalTables) {
if len(t.PersonalColumns) == 0 { if regexp.MustCompile(`\b` + regexp.QuoteMeta(strings.ToLower(table)) + `\b`).MatchString(body) {
continue src.readQueries[m[1]] = table
}
if regexp.MustCompile(`\b` + regexp.QuoteMeta(strings.ToLower(t.Name)) + `\b`).MatchString(body) {
src.readQueries[m[1]] = t.Name
break break
} }
} }
@ -429,6 +464,11 @@ func (src *pluginSource) personalRefs(f *pluginFile, n ast.Node) []string {
} }
ast.Inspect(n, func(n ast.Node) bool { ast.Inspect(n, func(n ast.Node) bool {
switch x := n.(type) { switch x := n.(type) {
case *ast.CallExpr:
// A length carries no personal data.
if id, ok := x.Fun.(*ast.Ident); ok && id.Name == "len" {
return false
}
case *ast.SelectorExpr: case *ast.SelectorExpr:
if id, ok := x.X.(*ast.Ident); ok && f.isImportName(id.Name) { if id, ok := x.X.(*ast.Ident); ok && f.isImportName(id.Name) {
return false return false
@ -454,6 +494,7 @@ func (src *pluginSource) personalRefs(f *pluginFile, n ast.Node) []string {
// sqlc query or the table's generated row type. // sqlc query or the table's generated row type.
func (src *pluginSource) storedPersonalReads(n ast.Node) []string { func (src *pluginSource) storedPersonalReads(n ast.Node) []string {
seen := map[string]bool{} seen := map[string]bool{}
scope := n
ast.Inspect(n, func(n ast.Node) bool { ast.Inspect(n, func(n ast.Node) bool {
switch x := n.(type) { switch x := n.(type) {
case *ast.CallExpr: case *ast.CallExpr:
@ -461,6 +502,14 @@ func (src *pluginSource) storedPersonalReads(n ast.Node) []string {
if t, ok := src.readQueries[sel.Sel.Name]; ok { if t, ok := src.readQueries[sel.Sel.Name]; ok {
seen[t+" ("+sel.Sel.Name+")"] = true seen[t+" ("+sel.Sel.Name+")"] = true
} }
if src.generated && siteDataTableReads[sel.Sel.Name] && strings.Contains(shortExpr(sel.X), "DataTables") {
if label, personal := src.dataTableReadPersonal(scope); personal {
seen["site data table "+label+"("+sel.Sel.Name+")"] = true
}
}
if src.personalSettings && sel.Sel.Name == "GetPluginSettings" {
seen["plugin settings ("+sel.Sel.Name+")"] = true
}
} }
case *ast.SelectorExpr: case *ast.SelectorExpr:
if t, ok := src.rowTypes[x.Sel.Name]; ok { if t, ok := src.rowTypes[x.Sel.Name]; ok {
@ -476,6 +525,50 @@ func (src *pluginSource) storedPersonalReads(n ast.Node) []string {
return sortedKeys(seen) return sortedKeys(seen)
} }
var siteDataTableReads = map[string]bool{"ListRows": true, "GetRow": true, "FindRowByField": true}
// dataTableReadPersonal decides whether a site data table read inside n reads
// personal data. Without data_tables in the spec every read is personal. With
// them, the tables n names by a literal GetTableByKey key decide; a read whose
// table cannot be resolved is personal when any declared table is.
func (src *pluginSource) dataTableReadPersonal(n ast.Node) (string, bool) {
if src.personalDataTables == nil {
return "", true
}
var keys []string
ast.Inspect(n, func(c ast.Node) bool {
call, ok := c.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || sel.Sel.Name != "GetTableByKey" || len(call.Args) != 2 {
return true
}
if lit, ok := call.Args[1].(*ast.BasicLit); ok && lit.Kind == token.STRING {
if k, err := strconv.Unquote(lit.Value); err == nil {
keys = append(keys, k)
}
}
return true
})
if len(keys) == 0 {
for k, personal := range src.personalDataTables {
if personal {
return k + " ", true
}
}
return "", false
}
for _, k := range keys {
personal, declared := src.personalDataTables[k]
if personal || !declared {
return k + " ", true
}
}
return "", false
}
func sortedKeys(m map[string]bool) []string { func sortedKeys(m map[string]bool) []string {
out := make([]string, 0, len(m)) out := make([]string, 0, len(m))
for k := range m { for k := range m {

161
pluginrules_classify.go Normal file
View File

@ -0,0 +1,161 @@
package main
import (
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"unicode"
)
// The deterministic personal data classifier (ADR 0007). The spec's personal
// flags come from a model, so for a factory-generated plugin a name is also
// personal when its words, its sample value's shape, its column type or its
// place in a visitor form say so, and the stricter result applies. The CMS
// host runs the same name rules at runtime (cms backend/plugin/factory_guard.go
// personalKind); keep the two aligned.
// personalKind classifies a field or column name: email, phone, birth,
// address, secret or name, or "" when the name says nothing personal.
func personalKind(name string) string {
tokens := nameTokens(name)
has := func(t string) bool {
return slices.Contains(tokens, t)
}
switch {
case has("email") || has("e") && has("mail") || len(tokens) == 1 && tokens[0] == "mail":
return "email"
case has("phone") || has("mobile") || has("tel") || has("telephone") || has("cell") || has("fax") || has("whatsapp") || has("sms"):
return "phone"
case has("birth") || has("dob") || has("birthday") || has("birthdate"):
return "birth"
case has("address") && !has("email") || has("street") || has("postcode") || has("zip") || has("postal"):
return "address"
case has("ip") || has("ssn") || has("passport") || has("password") || has("medicare") || has("licence") || has("license"):
return "secret"
case has("name"):
if len(tokens) == 1 || has("first") || has("last") || has("full") || has("given") || has("family") || has("middle") || has("sur") {
return "name"
}
if slices.ContainsFunc([]string{"customer", "client", "contact", "person", "your", "guest", "visitor", "attendee", "member", "user", "student", "parent", "child", "patient", "owner", "sender", "recipient", "buyer", "requester", "applicant"}, has) {
return "name"
}
case has("surname") || has("firstname") || has("lastname") || has("fullname"):
return "name"
}
return ""
}
func nameTokens(name string) []string {
var out []string
var cur []rune
flush := func() {
if len(cur) > 0 {
out = append(out, strings.ToLower(string(cur)))
cur = cur[:0]
}
}
runes := []rune(name)
for i, r := range runes {
switch {
case r == '_' || r == '-' || r == ' ' || r == '.':
flush()
case unicode.IsUpper(r) && i > 0 && unicode.IsLower(runes[i-1]):
flush()
cur = append(cur, r)
default:
cur = append(cur, r)
}
}
flush()
return out
}
var (
classifyEmail = regexp.MustCompile(`(?i)^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$`)
classifyPhone = regexp.MustCompile(`^\+?[0-9 ()./-]{7,22}$`)
classifyDate = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}`)
)
// sampleKind recognises an email address or phone number by its shape.
func sampleKind(v string) string {
v = strings.TrimSpace(v)
if classifyEmail.MatchString(v) {
return "email"
}
if !classifyPhone.MatchString(v) || classifyDate.MatchString(v) {
return ""
}
digits := 0
for _, r := range v {
if r >= '0' && r <= '9' {
digits++
}
}
if digits < 8 || digits > 15 || strings.Contains(v, ".") && !strings.ContainsAny(v, " -()") {
return ""
}
if digits == len(v) && !strings.HasPrefix(v, "0") {
return ""
}
return "phone"
}
var (
createTablePattern = regexp.MustCompile(`(?is)create\s+table\s+(?:if\s+not\s+exists\s+)?([\w."]+)\s*\((.*?)\)\s*;`)
personalColumnType = regexp.MustCompile(`(?i)^(inet|cidr)\b`)
)
// migrationColumns reads CREATE TABLE statements in the plugin's migrations
// and returns, per table, the columns that are personal by name or type.
func migrationColumns(root string) map[string][]string {
out := map[string][]string{}
files, _ := filepath.Glob(filepath.Join(root, "migrations", "*.sql"))
for _, path := range files {
raw, err := os.ReadFile(path)
if err != nil {
continue
}
for _, m := range createTablePattern.FindAllStringSubmatch(string(raw), -1) {
table := strings.Trim(m[1], `"`)
if i := strings.LastIndex(table, "."); i >= 0 {
table = strings.Trim(table[i+1:], `"`)
}
for _, def := range splitColumnDefs(m[2]) {
fields := strings.Fields(def)
if len(fields) < 2 {
continue
}
col := strings.Trim(fields[0], `"`)
switch strings.ToLower(col) {
case "primary", "unique", "constraint", "foreign", "check", "exclude":
continue
}
if personalKind(col) != "" || personalColumnType.MatchString(fields[1]) {
out[table] = append(out[table], col)
}
}
}
}
return out
}
func splitColumnDefs(body string) []string {
var out []string
depth, start := 0, 0
for i, r := range body {
switch r {
case '(':
depth++
case ')':
depth--
case ',':
if depth == 0 {
out = append(out, strings.TrimSpace(body[start:i]))
start = i + 1
}
}
}
return append(out, strings.TrimSpace(body[start:]))
}

View File

@ -326,3 +326,45 @@ func serviceMux() http.Handler {
} }
wantFindings(t, checkPluginRoutes(src), map[string]string{}) 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)
}
}
}
func TestPluginRoutesJudgeSiteDataTablesByTheirDeclaredFields(t *testing.T) {
if got := checkPluginRoutes(pluginRuleFixture(t, "events-datatable-pass")); len(got) != 0 {
t.Fatalf("a public route over the events data table must pass: %v", got)
}
wantFindings(t, checkPluginRoutes(pluginRuleFixture(t, "subscribers-datatable-fail")), map[string]string{
"handler.go:25": "reads personal data from table site data table subscribers (ListRows)",
})
}

View File

@ -0,0 +1,10 @@
{"version": 1, "name": "callbacks-77c1d0",
"spec": {
"title": "Call-back requests",
"blocks": [{"key": "callback_form", "source": "fields", "fields": [{"name": "heading", "sample": "Ask us to call you", "personal": false}]}],
"tables": [{"name": "callbacks", "columns": ["id", "email", "notes"], "personal_columns": []}],
"routes": [{"method": "POST", "path": "/request", "access": "public", "fields": [{"name": "email", "sample": "jo@example.com", "personal": false}, {"name": "notes", "sample": "please call 0400 123 456", "personal": false}]},
{"method": "GET", "path": "/recent", "access": "public", "fields": []}],
"outbound_hosts": [],
"settings": []
}}

View File

@ -0,0 +1,45 @@
package main
import (
"encoding/json"
"log/slog"
"net/http"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"git.dev.alexdunmow.com/block/pluginsdk/route"
)
const pluginName = "callbacks-77c1d0"
// Registration is the plugin entry registration.
var Registration = plugin.PluginRegistration{
Name: pluginName,
Version: "1.0.0",
HTTPHandler: newHTTPHandler,
}
const listRecent = `-- name: ListRecentCallers :many
SELECT id, mobile FROM callers ORDER BY id LIMIT 20
`
type Queries struct{}
func (Queries) ListRecentCallers() []string { return nil }
func newHTTPHandler(deps plugin.CoreServices) http.Handler {
r := route.New(pluginName)
r.Form("/request", handleRequest)
r.Handle(http.MethodGet, "/recent", route.Public, handleRecent)
return r
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
email := r.PostFormValue("email")
notes := r.PostFormValue("notes")
slog.Info("call-back requested", "email", email, "notes", notes)
w.WriteHeader(http.StatusNoContent)
}
func handleRecent(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(Queries{}.ListRecentCallers())
}

View File

@ -0,0 +1,12 @@
-- +goose Up
CREATE TABLE callbacks (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
email text NOT NULL,
notes text NOT NULL DEFAULT ''
);
CREATE TABLE callers (
id uuid PRIMARY KEY,
mobile text NOT NULL,
seen_from inet
);

View File

@ -0,0 +1,4 @@
name = "callbacks-77c1d0"
version = "1.0.0"
kind = "plugin"
private = true

View File

@ -0,0 +1,7 @@
{"version": 1, "name": "upcoming-events-5d1e22",
"spec": {
"blocks": [{"key": "upcoming_events", "source": "data_table:events", "fields": []}],
"data_tables": [{"key": "events", "fields": [{"name": "title", "sample": "Roof safety open day", "personal": false}, {"name": "starts_at", "sample": "2026-12-05T10:00", "personal": false}, {"name": "location", "sample": "The yard, Ballarat", "personal": false}]}],
"routes": [{"method": "GET", "path": "/events.ics", "access": "public", "fields": []}],
"outbound_hosts": [], "settings": []
}}

View File

@ -0,0 +1,41 @@
package main
import (
"encoding/json"
"net/http"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"git.dev.alexdunmow.com/block/pluginsdk/route"
)
const pluginName = "upcoming-events-5d1e22"
// Registration is the plugin entry registration.
var Registration = plugin.PluginRegistration{
Name: pluginName,
Version: "1.0.0",
HTTPHandler: newHTTPHandler,
}
var current plugin.CoreServices
func newHTTPHandler(deps plugin.CoreServices) http.Handler {
current = deps
r := route.New(pluginName)
r.Handle(http.MethodGet, "/events.ics", route.Public, handleList)
return r
}
func handleList(w http.ResponseWriter, r *http.Request) {
table, err := current.DataTables.GetTableByKey(r.Context(), "events")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
rows, err := current.DataTables.ListRows(r.Context(), table.ID, 100, 0)
if err != nil {
http.Error(w, "could not load rows", http.StatusInternalServerError)
return
}
_ = json.NewEncoder(w).Encode(rows)
}

View File

@ -0,0 +1,4 @@
name = "upcoming-events-5d1e22"
version = "1.0.0"
kind = "plugin"
private = true

View File

@ -0,0 +1,9 @@
{"version": 1, "name": "signups-3f2a10",
"spec": {
"title": "Workshop sign-ups",
"blocks": [{"key": "signups", "source": "data_table:signups", "fields": []}],
"tables": [],
"routes": [{"method": "GET", "path": "/signups", "access": "public", "fields": []}],
"outbound_hosts": [],
"settings": []
}}

View File

@ -0,0 +1,41 @@
package main
import (
"encoding/json"
"net/http"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"git.dev.alexdunmow.com/block/pluginsdk/route"
)
const pluginName = "signups-3f2a10"
// Registration is the plugin entry registration.
var Registration = plugin.PluginRegistration{
Name: pluginName,
Version: "1.0.0",
HTTPHandler: newHTTPHandler,
}
var current plugin.CoreServices
func newHTTPHandler(deps plugin.CoreServices) http.Handler {
current = deps
r := route.New(pluginName)
r.Handle(http.MethodGet, "/signups", route.Public, handleSignups)
return r
}
func handleSignups(w http.ResponseWriter, r *http.Request) {
table, err := current.DataTables.GetTableByKey(r.Context(), "signups")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
rows, err := current.DataTables.ListRows(r.Context(), table.ID, 100, 0)
if err != nil {
http.Error(w, "could not load sign-ups", http.StatusInternalServerError)
return
}
_ = json.NewEncoder(w).Encode(rows)
}

View File

@ -0,0 +1,4 @@
name = "signups-3f2a10"
version = "1.0.0"
kind = "plugin"
private = true

View File

@ -0,0 +1,8 @@
{"version": 1, "name": "newsletter-9a0b11",
"spec": {
"blocks": [{"key": "subscribers", "source": "data_table:subscribers", "fields": []}],
"data_tables": [{"key": "events", "fields": [{"name": "title", "sample": "Open day", "personal": false}]},
{"key": "subscribers", "fields": [{"name": "email", "sample": "jo@example.com", "personal": false}, {"name": "joined", "sample": "2026-11-01", "personal": false}]}],
"routes": [{"method": "GET", "path": "/subscribers", "access": "public", "fields": []}],
"outbound_hosts": [], "settings": []
}}

View File

@ -0,0 +1,41 @@
package main
import (
"encoding/json"
"net/http"
"git.dev.alexdunmow.com/block/pluginsdk/plugin"
"git.dev.alexdunmow.com/block/pluginsdk/route"
)
const pluginName = "newsletter-9a0b11"
// Registration is the plugin entry registration.
var Registration = plugin.PluginRegistration{
Name: pluginName,
Version: "1.0.0",
HTTPHandler: newHTTPHandler,
}
var current plugin.CoreServices
func newHTTPHandler(deps plugin.CoreServices) http.Handler {
current = deps
r := route.New(pluginName)
r.Handle(http.MethodGet, "/subscribers", route.Public, handleList)
return r
}
func handleList(w http.ResponseWriter, r *http.Request) {
table, err := current.DataTables.GetTableByKey(r.Context(), "subscribers")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
rows, err := current.DataTables.ListRows(r.Context(), table.ID, 100, 0)
if err != nil {
http.Error(w, "could not load rows", http.StatusInternalServerError)
return
}
_ = json.NewEncoder(w).Encode(rows)
}

View File

@ -0,0 +1,4 @@
name = "newsletter-9a0b11"
version = "1.0.0"
kind = "plugin"
private = true