check-safety/README.md
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

13 KiB

check-safety

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/, orchestrator/, core/, the plugins, and the sites. It is intentionally standalone — no imports from sibling repos except two vendored packages (see Vendored packages).

Run

# Scan CMS (default target)
make run

# Scan a different repo
make run TARGET=../orchestrator

# Direct invocation — first positional arg is the target dir (default ".")
go run . ../sites/bidbuddy
go run . ~/src/blockninja/cms

If you run it against the top of the consolidated BlockNinja repo, it prints a hint to pass --plugin-dir <path> (or run inside the plugin directory) so plugin-specific checks fire.

CLI flags

Flag Meaning
<target-dir> (positional) Repo/subtree to scan. Defaults to .. If it contains plugin.mod, it is auto-registered as a plugin root so plugin checks run.
--orchestrator Scan the orchestrator backend only (resolved from the discovered consolidated workspace), regardless of the positional target.
--plugin-dir <path> [more…] Register one or more plugin roots (dirs with plugin.mod). Alias: --plugin-dirs. Consumes args until the next --flag.
--plugin-pages <dir> [more…] Register frontend source dirs directly as plugin page targets (for the frontend checks). Consumes args until the next --flag.
--verbose / -v Print every check (including OK/SKIP), not just failures and warnings.
--all-any The any-usage check (2e) defaults to only the unstaged working-tree diff (newly introduced any); --all-any scans every source file instead.

The CLI contract (check-safety <target-dir> [--flags]) is stable — the CMS Makefile safety-check / install-safety-checker targets shell into this directory and depend on it.

Output

Output is concise by design (it is usually fed back into an agent's context). Passing and skipped checks print nothing; only FAIL/WARN/ERR checks print a <STATUS> <id> <summary> line with their findings indented beneath, followed by one tally line. A clean run is two lines:

check-safety /home/alex/src/blockninja/cms
39 checks: 20 ok 19 skip -> OK

A run with problems:

check-safety /home/alex/src/blockninja/cms
FAIL 15 1 err.Error() leak(s) to HTTP clients — log via slog.Error() and return a user-friendly message
  internal/service/handler.go:27 http.Error(w, err.Error(), ...) — leaks internal error
WARN 2e 1 any usage in changed lines (showing 1, --all-any to scan all)
  web/src/api.ts:12 [go] data: any

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 ERR, 0 otherwise (warnings do not fail the run).

Install globally

make install   # go install . → $GOPATH/bin/check-safety
check-safety ~/src/blockninja/cms

Test

make test         # go test -count=1 ./... (some tests shell out to npm/tsc/golangci-lint and skip if absent)
make test-short   # go test -short — skip the slow ones
make test-update  # regenerate the golden snapshots after intentional output changes
make tidy         # go mod tidy
make build        # go build -o check-safety .
make clean        # remove the built binary

golden_test.go is a characterisation snapshot test: it runs the whole binary against the fixtures under testdata/golden/ and diffs stdout + exit code. If you intentionally change a check's output, run make test-update and commit the regenerated fixture.

What it checks

Checks self-register via init() and run in Seq order. The full set (the ID is what the tool prints in each check header):

ID Check What it enforces
1 Secret env var reads Secret env vars (JWT_SECRET, VAULT_*, encryption keys, …) are read only inside config.Load() (config/config.go) or _test.go files.
2 RBAC registration Every RPC method is registered in the RBAC interceptor. Internal / plugin-managed services (e.g. ManagementService, Symposium's WikiService) are exempted.
2b Plugin proto ownership Plugins own their proto/RBAC definitions correctly (no poaching of core proto packages).
2c Plugin SDK boundaries Standalone plugins build against the published block/pluginsdk SDK (a coexisting block/core require is allowed) — verified via imports, go.mod, and version.
2d sqlc UUID overrides sqlc UUID overrides in standalone plugins and cmd configs must use github.com/google/uuid.
2e any usage Warns on any usage in Go and TypeScript (capped at 120 printed warnings).
2f Codegen freshness sqlc compile and buf generate must succeed for every scanned root that defines them (generated code is up to date).
3 Go lint Go code compiles and passes go fix, golangci-lint --fix, go vet, and the strict lint checks.
3b Orchestrator tests Orchestrator backend tests must pass when checking the core BlockNinja repo.
4 Frontend lint Frontend code is auto-formatted, lint-clean, and typecheck-clean.
5 ConnectRPC hooks Frontend uses the generated ConnectRPC hooks — no hand-crafted API clients.
6 No hardcoded colors No hardcoded colors in the frontend — use theme tokens.
7 Tab state in URL No useState for tab state in route files — use URL ?tab= params.
8 API subpath imports Import @block-ninja/api from subpaths only, never the package root.
9 pnpm only No npm/yarn lockfiles — pnpm is the only package manager.
10 Button automation Interactive buttons carry the required automation attributes.
10b No eslint-disable No eslint-disable-next-line comments (fix the lint, don't suppress it).
10disc Plugin discovery Plugin frontend pages are discoverable by the loader.
11 No placeholder code No placeholder / stub code — only shipped features.
12 No reinvented utils No reinvented utilities — use the shared helpers.
13 RPC error handling RPC query/mutation error handling is present and correct.
14 No raw SQL No raw SQL outside sqlc / Bob.
15 No leaked errors No err.Error() leaked to HTTP clients.
16 Directory structure Services and handlers live in their correct directories.
17 No TODO markers No TODO markers in production code.
18 Plugin segmentation Plugin segmentation is respected (safety-rules.yml).
19 Auth precedence Bearer token takes precedence over cookies in the auth middleware.
20 Tailwind v4 Tailwind v4 configuration is correct (PostCSS plugin, CSS directives, @config).
21 Preset validation Plugin presets.json type-safe-unmarshals against theme.Theme.
22 HTML sanitization No hand-rolled HTML sanitization — use bluemonday.
28 Admin toolbar Public page handlers inject the admin toolbar data.
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 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.
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. 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 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.

How it stays in sync with CMS

internal/helpers/deferlog.go and internal/theme/*.go are vendored copies from CMS (cms/backend/internal/{helpers,theme}/). Go's internal/ rule blocks direct imports across modules, so they are copied in rather than imported. When CMS changes the theme schema or LogDeferredError, re-copy them — that drift is precisely what the preset-validation check (21) surfaces.

blockNinjaRepoRoot() and orchestratorRepoRoot() discover the consolidated workspace by walking upward from the current directory, executable, and compiled source location. The historical ~/src/blockninja layout remains a last-resort fallback for installed binaries.

Adding a new check

  1. Add a check_<name>.go file with a runCheck<Name> func and an init() that calls register(Check{Seq, ID, Title, Run}).
  2. Add the rule logic in a <rule>.go file, plus a <rule>_test.go for unit coverage.
  3. Pick a Seq value that slots it into the desired run order.
  4. Update the numbered comment block at the top of main.go and the table above.
  5. If the output is deterministic, add a fixture under testdata/golden/<case>/ and run make test-update to regenerate the snapshot.