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>
This commit is contained in:
parent
bd55930870
commit
8b8afc044d
@ -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
|
||||||
|
|||||||
@ -0,0 +1,51 @@
|
|||||||
|
# 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
|
||||||
@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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})
|
||||||
|
|||||||
@ -5,6 +5,7 @@ import (
|
|||||||
"go/ast"
|
"go/ast"
|
||||||
"go/token"
|
"go/token"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -296,12 +297,10 @@ 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 {
|
||||||
if p, name, ok := c.f.pkgFunc(call); ok && p == "fmt" && name == "Sprintf" && len(call.Args) > 0 && isHTMLConst(call.Args[0]) {
|
if p, name, ok := c.f.pkgFunc(call); ok && p == "fmt" && name == "Sprintf" && len(call.Args) > 0 && isHTMLConst(call.Args[0]) {
|
||||||
return true
|
return true
|
||||||
|
|||||||
@ -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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -88,6 +89,11 @@ 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
|
||||||
// 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,6 +151,8 @@ 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{},
|
||||||
|
|
||||||
|
personalTables: map[string]bool{},
|
||||||
declFile: map[*ast.FuncDecl]*pluginFile{},
|
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 {
|
||||||
@ -220,31 +228,48 @@ 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 {
|
markTable := func(table string, cols []string) {
|
||||||
for _, c := range t.PersonalColumns {
|
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 +304,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 +451,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
|
||||||
@ -461,6 +488,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
|
||||||
}
|
}
|
||||||
|
// Site data tables have fields nobody declares, so in a generated
|
||||||
|
// plugin every read of one counts as personal.
|
||||||
|
if src.generated && siteDataTableReads[sel.Sel.Name] && strings.Contains(shortExpr(sel.X), "DataTables") {
|
||||||
|
seen["site data table ("+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 +511,8 @@ 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}
|
||||||
|
|
||||||
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
161
pluginrules_classify.go
Normal 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:]))
|
||||||
|
}
|
||||||
@ -326,3 +326,36 @@ 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
10
testdata/pluginrules/classifier-fail/acceptance.json
vendored
Normal file
10
testdata/pluginrules/classifier-fail/acceptance.json
vendored
Normal 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": []
|
||||||
|
}}
|
||||||
45
testdata/pluginrules/classifier-fail/handler.go
vendored
Normal file
45
testdata/pluginrules/classifier-fail/handler.go
vendored
Normal 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())
|
||||||
|
}
|
||||||
12
testdata/pluginrules/classifier-fail/migrations/00001_callbacks.sql
vendored
Normal file
12
testdata/pluginrules/classifier-fail/migrations/00001_callbacks.sql
vendored
Normal 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
|
||||||
|
);
|
||||||
4
testdata/pluginrules/classifier-fail/plugin.mod
vendored
Normal file
4
testdata/pluginrules/classifier-fail/plugin.mod
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
name = "callbacks-77c1d0"
|
||||||
|
version = "1.0.0"
|
||||||
|
kind = "plugin"
|
||||||
|
private = true
|
||||||
9
testdata/pluginrules/signups-datatable-fail/acceptance.json
vendored
Normal file
9
testdata/pluginrules/signups-datatable-fail/acceptance.json
vendored
Normal 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": []
|
||||||
|
}}
|
||||||
41
testdata/pluginrules/signups-datatable-fail/handler.go
vendored
Normal file
41
testdata/pluginrules/signups-datatable-fail/handler.go
vendored
Normal 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)
|
||||||
|
}
|
||||||
4
testdata/pluginrules/signups-datatable-fail/plugin.mod
vendored
Normal file
4
testdata/pluginrules/signups-datatable-fail/plugin.mod
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
name = "signups-3f2a10"
|
||||||
|
version = "1.0.0"
|
||||||
|
kind = "plugin"
|
||||||
|
private = true
|
||||||
Loading…
x
Reference in New Issue
Block a user