rattlecheck 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +173 -2
  4. package/bin/rattlecheck.js +12 -0
  5. package/docs/rules/RC001.md +40 -0
  6. package/docs/rules/RC002.md +35 -0
  7. package/docs/rules/RC003.md +25 -0
  8. package/docs/rules/RC004.md +23 -0
  9. package/docs/rules/RC005.md +32 -0
  10. package/docs/rules/RC101.md +31 -0
  11. package/integrations/AGENTS.md +11 -0
  12. package/integrations/claude-code/rattlecheck/SKILL.md +42 -0
  13. package/integrations/cursor/rattlecheck.mdc +13 -0
  14. package/package.json +45 -4
  15. package/src/cli.js +158 -0
  16. package/src/config.js +62 -0
  17. package/src/live/catalog.js +43 -0
  18. package/src/live/env.js +102 -0
  19. package/src/live/ownership.js +72 -0
  20. package/src/live/probe.js +80 -0
  21. package/src/live/rc101-anon-readable.js +38 -0
  22. package/src/mcp/server.js +163 -0
  23. package/src/model.js +723 -0
  24. package/src/report/badge-svg.js +26 -0
  25. package/src/report/card-svg.js +50 -0
  26. package/src/report/grade.js +26 -0
  27. package/src/report/sarif.js +44 -0
  28. package/src/report/terminal.js +105 -0
  29. package/src/rules/index.js +14 -0
  30. package/src/rules/supabase/rc001-table-without-rls.js +54 -0
  31. package/src/rules/supabase/rc002-definer-callable-by-anon.js +37 -0
  32. package/src/rules/supabase/rc003-definer-search-path.js +33 -0
  33. package/src/rules/supabase/rc004-invoker-trigger-locked-table.js +49 -0
  34. package/src/rules/supabase/rc005-permissive-true-policy.js +81 -0
  35. package/src/scan.js +167 -0
  36. package/src/sql/ident.js +25 -0
  37. package/src/sql/signature.js +143 -0
  38. package/src/sql/statements.js +267 -0
  39. package/src/version.js +6 -0
@@ -0,0 +1,13 @@
1
+ ---
2
+ description: Check Supabase security with rattlecheck before deploying or after changing migrations
3
+ globs: supabase/migrations/**/*.sql
4
+ alwaysApply: false
5
+ ---
6
+
7
+ When you create or change a file in `supabase/migrations/`, or before a deploy:
8
+
9
+ 1. Run `npx rattlecheck --json` from the project root.
10
+ 2. Put each finding's `fix` SQL into a NEW migration file. Never edit migrations that already ran, and never run SQL against production yourself.
11
+ 3. Run it again until the grade is A.
12
+ 4. If a finding is intentional, ask the user before adding an allow entry with a written reason to `rattlecheck.config.json`.
13
+ 5. Tell the user what you found and fixed using each finding's `plain` text.
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "rattlecheck",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Rattle every door you own. Finds the open doors in your Supabase app before someone else does.",
5
+ "homepage": "https://github.com/chaseakub/rattlecheck#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/chaseakub/rattlecheck.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/chaseakub/rattlecheck/issues"
12
+ },
13
+ "type": "module",
14
+ "bin": {
15
+ "rattlecheck": "bin/rattlecheck.js",
16
+ "rattle": "bin/rattlecheck.js"
17
+ },
18
+ "exports": {
19
+ ".": "./src/scan.js"
20
+ },
21
+ "files": [
22
+ "bin",
23
+ "src",
24
+ "docs",
25
+ "integrations",
26
+ "LICENSE",
27
+ "NOTICE",
28
+ "README.md"
29
+ ],
30
+ "engines": {
31
+ "node": ">=20"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test --test-concurrency=1 \"test/**/*.test.js\""
35
+ },
36
+ "keywords": [
37
+ "supabase",
38
+ "security",
39
+ "rls",
40
+ "row-level-security",
41
+ "postgres",
42
+ "scanner",
43
+ "mcp",
44
+ "sarif"
45
+ ],
46
+ "license": "Apache-2.0"
47
+ }
package/src/cli.js ADDED
@@ -0,0 +1,158 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { scan, ScanError } from './scan.js';
4
+ import { ConfigError } from './config.js';
5
+ import { renderTerminal } from './report/terminal.js';
6
+ import { renderSarif } from './report/sarif.js';
7
+ import { renderBadge } from './report/badge-svg.js';
8
+ import { renderCard } from './report/card-svg.js';
9
+ import { ALL_RULES, getRule } from './rules/index.js';
10
+ import { VERSION } from './version.js';
11
+
12
+ const HELP = `rattlecheck ${VERSION}: rattle every door you own.
13
+
14
+ Usage
15
+ rattlecheck [project-folder] [options]
16
+ rattlecheck rules list every check
17
+ rattlecheck explain <RULE> explain one check, e.g. rattlecheck explain RC002
18
+ rattlecheck mcp run as an MCP server (stdio) for coding agents
19
+
20
+ Options
21
+ --technical file locations, standards, and the exact SQL fix for each finding
22
+ --json machine-readable report (schema rattlecheck.report/v1)
23
+ --sarif SARIF 2.1.0 report, for GitHub code scanning and security tools
24
+ --out <file> write the --json or --sarif report to a file instead of the screen
25
+ --badge [file] write a README badge (default: rattlecheck-badge.svg)
26
+ --card [file] write a 1200x630 share card (default: rattlecheck-card.svg)
27
+ --fix-sql [file] write every suggested fix to one file to review (default: rattlecheck-fixes.sql)
28
+ --live also check your running project, read-only, after proving it's yours
29
+ --config <file> config file (default: rattlecheck.config.json in the project folder)
30
+ --no-color plain text output
31
+ -h, --help show this help
32
+ -v, --version show the version
33
+
34
+ Exit codes
35
+ 0 nothing open 1 open door found 2 usage or config error
36
+ 3 could not parse 4 live check refused (ownership not proven)
37
+
38
+ rattlecheck never changes your database. Fixes are printed for you to review.`;
39
+
40
+ function parseArgs(argv) {
41
+ const opts = { root: null, technical: false, json: false, sarif: false, out: null, badge: null, card: null, fixSql: null, live: false, config: null, color: true };
42
+ const takeOptional = (i, ext, dflt) => {
43
+ const next = argv[i + 1];
44
+ if (next && !next.startsWith('-') && next.toLowerCase().endsWith(ext)) return [next, i + 1];
45
+ return [dflt, i];
46
+ };
47
+ for (let i = 0; i < argv.length; i++) {
48
+ const a = argv[i];
49
+ switch (a) {
50
+ case '--technical': opts.technical = true; break;
51
+ case '--json': opts.json = true; break;
52
+ case '--sarif': opts.sarif = true; break;
53
+ case '--live': opts.live = true; break;
54
+ case '--no-color': opts.color = false; break;
55
+ case '--out': opts.out = argv[++i]; if (!opts.out) throw new ScanError('--out needs a file name'); break;
56
+ case '--config': opts.config = argv[++i]; if (!opts.config) throw new ScanError('--config needs a file name'); break;
57
+ case '--badge': [opts.badge, i] = takeOptional(i, '.svg', 'rattlecheck-badge.svg'); break;
58
+ case '--card': [opts.card, i] = takeOptional(i, '.svg', 'rattlecheck-card.svg'); break;
59
+ case '--fix-sql': [opts.fixSql, i] = takeOptional(i, '.sql', 'rattlecheck-fixes.sql'); break;
60
+ default:
61
+ if (a.startsWith('-')) throw new ScanError(`Unknown option ${a}. Run rattlecheck --help.`);
62
+ if (opts.root) throw new ScanError(`Only one project folder can be checked at a time (got ${opts.root} and ${a}).`);
63
+ opts.root = a;
64
+ }
65
+ }
66
+ if (opts.json && opts.sarif) throw new ScanError('Pick one of --json or --sarif.');
67
+ return opts;
68
+ }
69
+
70
+ function renderFixSql(report) {
71
+ const lines = [
72
+ `-- Suggested fixes from rattlecheck ${report.tool.version}, ${report.generatedAt}`,
73
+ '-- Review every statement. Put the ones you want in a NEW migration file.',
74
+ '-- rattlecheck never runs these for you.',
75
+ '',
76
+ ];
77
+ for (const f of report.findings) {
78
+ lines.push(`-- ${f.rule} [${f.severity}] ${f.name}${f.detail ? ` (${f.detail})` : ''}`);
79
+ lines.push(`-- ${f.plain}`);
80
+ lines.push(f.fix, '');
81
+ }
82
+ if (!report.findings.length) lines.push('-- Nothing to fix.');
83
+ return `${lines.join('\n')}\n`;
84
+ }
85
+
86
+ function explain(rule) {
87
+ return [
88
+ `${rule.id} ${rule.title}`,
89
+ `Severity: ${rule.severity}${rule.live ? ' (live check, runs with --live)' : ''}`,
90
+ '',
91
+ rule.summary,
92
+ '',
93
+ `Standards: ${rule.standards.cwe.join(', ')} | NIST SP 800-53 ${rule.standards.nist80053.join(', ')} | CIS Controls v8 ${rule.standards.cis.join(', ')}`,
94
+ ].join('\n');
95
+ }
96
+
97
+ export async function main(argv, { stdout = process.stdout, stderr = process.stderr, env = process.env } = {}) {
98
+ try {
99
+ if (argv.includes('-h') || argv.includes('--help')) {
100
+ stdout.write(`${HELP}\n`);
101
+ return 0;
102
+ }
103
+ if (argv.includes('-v') || argv.includes('--version')) {
104
+ stdout.write(`${VERSION}\n`);
105
+ return 0;
106
+ }
107
+ if (argv[0] === 'mcp') {
108
+ const { runMcpServer } = await import('./mcp/server.js');
109
+ await runMcpServer();
110
+ return null; // stays running
111
+ }
112
+ if (argv[0] === 'rules') {
113
+ for (const r of ALL_RULES) stdout.write(`${r.id} ${r.severity.padEnd(8)} ${r.title}${r.live ? ' (--live)' : ''}\n`);
114
+ return 0;
115
+ }
116
+ if (argv[0] === 'explain') {
117
+ const rule = getRule(argv[1]);
118
+ if (!rule) throw new ScanError(`No rule called ${argv[1] ?? '(none)'}. Run rattlecheck rules to see them all.`);
119
+ stdout.write(`${explain(rule)}\n`);
120
+ return 0;
121
+ }
122
+
123
+ const opts = parseArgs(argv);
124
+ const root = path.resolve(opts.root ?? '.');
125
+ const report = await scan({ root, live: opts.live, configPath: opts.config, env });
126
+
127
+ const written = [];
128
+ const write = (file, content) => {
129
+ const p = path.resolve(file);
130
+ fs.writeFileSync(p, content);
131
+ const rel = path.relative(process.cwd(), p);
132
+ written.push(rel && !rel.startsWith('..') ? rel : p);
133
+ };
134
+ if (opts.badge) write(opts.badge, renderBadge(report));
135
+ if (opts.card) write(opts.card, renderCard(report));
136
+ if (opts.fixSql) write(opts.fixSql, renderFixSql(report));
137
+
138
+ if (opts.json || opts.sarif) {
139
+ const body = `${JSON.stringify(opts.json ? report : renderSarif(report), null, 2)}\n`;
140
+ if (opts.out) write(opts.out, body);
141
+ else stdout.write(body);
142
+ } else {
143
+ const color = opts.color && !env.NO_COLOR && Boolean(stdout.isTTY);
144
+ stdout.write(renderTerminal(report, { technical: opts.technical, color }));
145
+ }
146
+ for (const w of written) (opts.json || opts.sarif ? stderr : stdout).write(` wrote ${w}\n`);
147
+ if (written.length && !(opts.json || opts.sarif)) stdout.write('\n');
148
+
149
+ if (!report.coverage.ok) return 3;
150
+ return report.counts.critical + report.counts.high > 0 ? 1 : 0;
151
+ } catch (e) {
152
+ if (e instanceof ScanError || e instanceof ConfigError) {
153
+ stderr.write(`rattlecheck: ${e.message}\n`);
154
+ return e.code ?? 2;
155
+ }
156
+ throw e;
157
+ }
158
+ }
package/src/config.js ADDED
@@ -0,0 +1,62 @@
1
+ // rattlecheck.config.json
2
+ //
3
+ // {
4
+ // "defaults": "supabase-stock", // or "clean", or { "functions": "clean", "tables": "supabase-stock" }
5
+ // "exposedSchemas": ["public"], // optional; read from supabase/config.toml otherwise
6
+ // "migrationRoles": ["postgres"], // optional; the roles your migrations run as
7
+ // "allow": [
8
+ // { "rule": "RC005", "object": "public.menu_items", "reason": "Menu is public on the website." }
9
+ // ]
10
+ // }
11
+ //
12
+ // Every allow entry needs a written reason. An exception nobody can explain is
13
+ // a hole nobody owns. Entries that match nothing are reported, because a stale
14
+ // exception silently covers whatever reuses that name next.
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ export class ConfigError extends Error {}
19
+
20
+ const DEFAULT_MODES = new Set(['supabase-stock', 'clean']);
21
+
22
+ export function loadConfig(root, explicitPath) {
23
+ const p = explicitPath ? path.resolve(explicitPath) : path.join(root, 'rattlecheck.config.json');
24
+ if (!fs.existsSync(p)) {
25
+ if (explicitPath) throw new ConfigError(`Config file not found: ${p}`);
26
+ return { path: null, defaults: undefined, exposedSchemas: undefined, migrationRoles: undefined, allow: [] };
27
+ }
28
+ let raw;
29
+ try {
30
+ raw = JSON.parse(fs.readFileSync(p, 'utf8'));
31
+ } catch (e) {
32
+ throw new ConfigError(`${p} is not valid JSON: ${e.message}`);
33
+ }
34
+
35
+ const d = raw.defaults;
36
+ if (d !== undefined) {
37
+ const ok =
38
+ (typeof d === 'string' && DEFAULT_MODES.has(d)) ||
39
+ (d && typeof d === 'object' && Object.entries(d).every(([k, v]) => ['functions', 'tables'].includes(k) && DEFAULT_MODES.has(v)));
40
+ if (!ok) throw new ConfigError(`"defaults" must be "supabase-stock", "clean", or { "functions": ..., "tables": ... }`);
41
+ }
42
+ if (raw.exposedSchemas !== undefined && !(Array.isArray(raw.exposedSchemas) && raw.exposedSchemas.every((s) => typeof s === 'string'))) {
43
+ throw new ConfigError('"exposedSchemas" must be an array of schema names');
44
+ }
45
+
46
+ const allow = raw.allow ?? [];
47
+ if (!Array.isArray(allow)) throw new ConfigError('"allow" must be an array');
48
+ allow.forEach((a, i) => {
49
+ if (!a || typeof a.rule !== 'string' || typeof a.object !== 'string') {
50
+ throw new ConfigError(`allow[${i}] needs "rule" (like "RC002") and "object" (like "public.my_function(uuid)")`);
51
+ }
52
+ if (typeof a.reason !== 'string' || a.reason.trim().length < 10) {
53
+ throw new ConfigError(`allow[${i}] (${a.rule} ${a.object}) needs a "reason" that explains why this is safe`);
54
+ }
55
+ });
56
+
57
+ if (raw.migrationRoles !== undefined && !(Array.isArray(raw.migrationRoles) && raw.migrationRoles.length && raw.migrationRoles.every((s) => typeof s === 'string'))) {
58
+ throw new ConfigError('"migrationRoles" must be a non-empty array of role names (the roles your migrations run as)');
59
+ }
60
+
61
+ return { path: p, defaults: d, exposedSchemas: raw.exposedSchemas, migrationRoles: raw.migrationRoles, allow };
62
+ }
@@ -0,0 +1,43 @@
1
+ // The full list of tables and views the live check has to ask about.
2
+ //
3
+ // Migrations alone are not enough: anything created in the dashboard, by a
4
+ // script, or by hand (a quick backup copy, say) never appears in them, and
5
+ // those are exactly the objects most likely to be left open. A live check
6
+ // that only asks about tables it already knows reports "0 open" over the
7
+ // tables it never saw.
8
+ //
9
+ // With an access token, rattlecheck reads the object names from the project's
10
+ // catalog through Supabase's READ-ONLY query endpoint. Names only, no rows.
11
+ // It never falls back to the general query endpoint, which can write.
12
+ function sqlLiteral(s) {
13
+ return `'${String(s).replace(/'/g, "''")}'`;
14
+ }
15
+
16
+ export async function listExposedObjects({ ref, accessToken, schemas, fetchImpl = globalThis.fetch, userAgent }) {
17
+ if (!ref || !accessToken) return { ok: false, names: [], reason: 'needs an access token for a hosted project' };
18
+ const query =
19
+ 'select n.nspname as schema, c.relname as name, c.relkind as kind ' +
20
+ 'from pg_catalog.pg_class c join pg_catalog.pg_namespace n on n.oid = c.relnamespace ' +
21
+ `where n.nspname = any (array[${schemas.map(sqlLiteral).join(', ')}]::text[]) ` +
22
+ "and c.relkind in ('r', 'p', 'v', 'm', 'f') order by 1, 2";
23
+ try {
24
+ const res = await fetchImpl(`https://api.supabase.com/v1/projects/${ref}/database/query/read-only`, {
25
+ method: 'POST',
26
+ redirect: 'manual',
27
+ headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json', 'User-Agent': userAgent },
28
+ body: JSON.stringify({ query }),
29
+ });
30
+ if (res.status !== 200 && res.status !== 201) {
31
+ await res.body?.cancel?.();
32
+ return { ok: false, names: [], reason: `the read-only catalog query was refused (HTTP ${res.status})` };
33
+ }
34
+ const rows = await res.json();
35
+ if (!Array.isArray(rows)) return { ok: false, names: [], reason: 'the catalog query returned something unexpected' };
36
+ const names = rows
37
+ .filter((r) => typeof r.schema === 'string' && typeof r.name === 'string')
38
+ .map((r) => `${r.schema}.${r.name}`);
39
+ return { ok: true, names, views: rows.filter((r) => r.kind === 'v' || r.kind === 'm').length };
40
+ } catch (e) {
41
+ return { ok: false, names: [], reason: `could not reach the Management API (${e.message})` };
42
+ }
43
+ }
@@ -0,0 +1,102 @@
1
+ // Reads the project's own connection settings. Values are kept in memory only
2
+ // and are never printed, logged, or returned in a report.
3
+ //
4
+ // The URL and the keys always come from ONE source: either the process
5
+ // environment (if it names a project URL at all) or the project's env files.
6
+ // Mixing them would let a repo's .env supply the URL while your shell supplies
7
+ // the keys, and your keys would go wherever that repo pointed them.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ const ENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local'];
12
+ const URL_RE = /^(?:[A-Z]+_)*SUPABASE_URL$/;
13
+
14
+ export function parseEnvFile(text) {
15
+ const out = {};
16
+ for (const raw of text.split(/\r?\n/)) {
17
+ const line = raw.trim();
18
+ if (!line || line.startsWith('#')) continue;
19
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
20
+ if (!m) continue;
21
+ let v = m[2].trim();
22
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
23
+ else v = v.replace(/\s+#.*$/, '');
24
+ out[m[1]] = v;
25
+ }
26
+ return out;
27
+ }
28
+
29
+ function pick(vars, re) {
30
+ const k = Object.keys(vars).find((name) => re.test(name) && vars[name]);
31
+ return k ? vars[k] : null;
32
+ }
33
+
34
+ /** Collect URL and keys from one source, plus the access token from the process environment only. */
35
+ export function readProjectEnv(root, processEnv = process.env) {
36
+ const proc = Object.fromEntries(Object.entries(processEnv).filter(([k]) => /SUPABASE/.test(k)));
37
+ let vars;
38
+ let source;
39
+ if (Object.keys(proc).some((k) => URL_RE.test(k) && proc[k])) {
40
+ vars = proc;
41
+ source = 'environment';
42
+ } else {
43
+ vars = {};
44
+ for (const f of ENV_FILES) {
45
+ const p = path.join(root, f);
46
+ if (fs.existsSync(p)) Object.assign(vars, parseEnvFile(fs.readFileSync(p, 'utf8')));
47
+ }
48
+ source = 'env files';
49
+ }
50
+ return {
51
+ source,
52
+ url: pick(vars, URL_RE),
53
+ anonKey: pick(vars, /SUPABASE_(?:ANON|PUBLISHABLE)\w*KEY$/),
54
+ serviceKey: pick(vars, /SUPABASE_(?:SERVICE_ROLE|SECRET)\w*KEY$/),
55
+ accessToken: processEnv.SUPABASE_ACCESS_TOKEN || null,
56
+ };
57
+ }
58
+
59
+ /** Legacy keys are JWTs and go in both headers; new sb_ keys go in apikey only. */
60
+ export function authHeaders(key) {
61
+ return key.startsWith('eyJ') ? { apikey: key, Authorization: `Bearer ${key}` } : { apikey: key };
62
+ }
63
+
64
+ /**
65
+ * The only places rattlecheck will send a key: a hosted project at
66
+ * https://<ref>.supabase.co (or .in), or a local Supabase on localhost.
67
+ */
68
+ export function checkTarget(url) {
69
+ let u;
70
+ try {
71
+ u = new URL(String(url).trim());
72
+ } catch {
73
+ return { ok: false, reason: 'the project URL is not a valid URL' };
74
+ }
75
+ const bare = u.pathname === '/' && !u.search && !u.hash && !u.username && !u.password;
76
+ const hosted = /^([a-z0-9]{20})\.supabase\.(?:co|in)$/i.exec(u.hostname);
77
+ if (hosted && u.protocol === 'https:' && !u.port && bare) {
78
+ return { ok: true, base: `https://${u.hostname.toLowerCase()}`, ref: hosted[1].toLowerCase(), local: false };
79
+ }
80
+ const isLoopback = ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
81
+ if (isLoopback && (u.protocol === 'http:' || u.protocol === 'https:') && bare) {
82
+ return { ok: true, base: `${u.protocol}//${u.host}`, ref: null, local: true };
83
+ }
84
+ return {
85
+ ok: false,
86
+ reason: 'rattlecheck only sends your keys to https://<project-ref>.supabase.co or to a local Supabase on localhost. Set SUPABASE_URL to that address (custom domains aren\'t supported yet)',
87
+ };
88
+ }
89
+
90
+ /** True when a key in the public slot is actually a secret one. */
91
+ export function looksSecret(key) {
92
+ if (key.startsWith('sb_secret_')) return true;
93
+ if (key.startsWith('eyJ')) {
94
+ try {
95
+ const payload = JSON.parse(Buffer.from(key.split('.')[1], 'base64url').toString('utf8'));
96
+ return payload.role === 'service_role';
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+ return false;
102
+ }
@@ -0,0 +1,72 @@
1
+ // Live checks only run against a project the person running rattlecheck can
2
+ // prove they control. This is the line between a tool that checks your own
3
+ // doors and a tool that tries other people's. It is not optional and there is
4
+ // no flag to skip it.
5
+ //
6
+ // Proof is one of:
7
+ // 1. A Supabase access token (from `supabase login`) that can see the
8
+ // project through the Management API.
9
+ // 2. The project's own service key, accepted by the project's admin API.
10
+ // Only the owner has it. It is used for this one request and nothing else.
11
+ //
12
+ // No request follows a redirect. Otherwise a server could pass the proof
13
+ // itself and then forward every probe somewhere else.
14
+ import { authHeaders, checkTarget } from './env.js';
15
+
16
+ // An id no real user has. The admin API answers "user not found" to a service
17
+ // key and "not allowed" to anything else, and no user data comes back either way.
18
+ const NOBODY = '00000000-0000-0000-0000-000000000000';
19
+
20
+ async function smallText(res) {
21
+ try {
22
+ const t = await res.text();
23
+ return t.slice(0, 4096);
24
+ } catch {
25
+ return '';
26
+ }
27
+ }
28
+
29
+ export function projectRefFromUrl(url) {
30
+ const t = checkTarget(url);
31
+ return t.ok && !t.local ? t.ref : null;
32
+ }
33
+
34
+ export async function proveOwnership({ url, accessToken, serviceKey, fetchImpl = globalThis.fetch, userAgent }) {
35
+ const target = checkTarget(url);
36
+ if (!target.ok) return { ok: false, method: null, ref: null, reason: target.reason };
37
+ const attempts = [];
38
+
39
+ if (accessToken && target.ref) {
40
+ try {
41
+ const res = await fetchImpl(`https://api.supabase.com/v1/projects/${target.ref}`, {
42
+ headers: { Authorization: `Bearer ${accessToken}`, 'User-Agent': userAgent },
43
+ redirect: 'manual',
44
+ });
45
+ await res.body?.cancel?.();
46
+ if (res.status === 200) return { ok: true, method: 'access-token', ref: target.ref, base: target.base };
47
+ attempts.push(`access token was not accepted for project ${target.ref} (HTTP ${res.status})`);
48
+ } catch (e) {
49
+ attempts.push(`could not reach the Supabase Management API (${e.message})`);
50
+ }
51
+ }
52
+
53
+ if (serviceKey) {
54
+ try {
55
+ const res = await fetchImpl(`${target.base}/auth/v1/admin/users/${NOBODY}`, {
56
+ headers: { ...authHeaders(serviceKey), 'User-Agent': userAgent },
57
+ redirect: 'manual',
58
+ });
59
+ const body = await smallText(res);
60
+ if (res.status === 404 && /user_not_found|user not found/i.test(body)) {
61
+ return { ok: true, method: 'service-key', ref: target.ref, base: target.base };
62
+ }
63
+ attempts.push(`service key was not accepted by this project (HTTP ${res.status})`);
64
+ } catch (e) {
65
+ attempts.push(`could not reach the project (${e.message})`);
66
+ }
67
+ }
68
+
69
+ if (!accessToken && !serviceKey) attempts.push('no SUPABASE_ACCESS_TOKEN or service key found');
70
+ else if (accessToken && !target.ref && !serviceKey) attempts.push('an access token can only prove ownership of a hosted <ref>.supabase.co project');
71
+ return { ok: false, method: null, ref: target.ref, reason: attempts.join('; ') };
72
+ }
@@ -0,0 +1,80 @@
1
+ // The attacker's view: ask the live project, with only the public key, how
2
+ // many rows of each table it will hand over.
3
+ //
4
+ // Read-only by construction. Every table request is a HEAD with
5
+ // Prefer: count=exact, so the server returns a row count and no row data. The
6
+ // one GET asks the API for its list of tables (names only, no rows). Nothing is
7
+ // written, no row is downloaded, nothing is stored. Count=exact makes Postgres
8
+ // count the rows, which can take a moment on very large tables.
9
+ //
10
+ // A zero is reported as "locked or empty", never as "locked". From outside,
11
+ // an empty table and a table row-level security filters to nothing look the
12
+ // same, and claiming otherwise would be reporting an instrument we can't trust.
13
+ import { authHeaders, checkTarget } from './env.js';
14
+
15
+ // PostgREST's own table list. It only lists what the asking role can reach,
16
+ // which makes it complete for the public key's point of view, when the
17
+ // project serves it at all (many no longer do to the public key).
18
+ async function discoverPublicTables(base, headers, fetchImpl) {
19
+ try {
20
+ const res = await fetchImpl(`${base}/rest/v1/`, { headers: { ...headers, Accept: 'application/openapi+json' }, redirect: 'manual' });
21
+ if (res.status !== 200) {
22
+ await res.body?.cancel?.();
23
+ return { ok: false, names: [] };
24
+ }
25
+ const spec = await res.json();
26
+ if (!spec || typeof spec.paths !== 'object') return { ok: false, names: [] };
27
+ const names = Object.keys(spec.paths)
28
+ .filter((p) => p !== '/' && !p.startsWith('/rpc/'))
29
+ .map((p) => `public.${p.slice(1)}`);
30
+ return { ok: true, names };
31
+ } catch {
32
+ return { ok: false, names: [] };
33
+ }
34
+ }
35
+
36
+ function parseCount(contentRange) {
37
+ const m = /\/(\d+|\*)\s*$/.exec(contentRange ?? '');
38
+ return m && m[1] !== '*' ? Number(m[1]) : null;
39
+ }
40
+
41
+ export async function probeTables({ url, anonKey, tables, fetchImpl = globalThis.fetch, userAgent, concurrency = 4 }) {
42
+ // Defense in depth: the caller already proved ownership of this exact base.
43
+ const target = checkTarget(url);
44
+ if (!target.ok) throw new Error(target.reason);
45
+ const base = target.base;
46
+ const headers = { ...authHeaders(anonKey), 'User-Agent': userAgent };
47
+ const apiList = await discoverPublicTables(base, headers, fetchImpl);
48
+ const all = [...new Set([...tables, ...apiList.names])].sort();
49
+
50
+ const results = [];
51
+ let next = 0;
52
+ async function worker() {
53
+ while (next < all.length) {
54
+ const name = all[next++];
55
+ const [schema, table] = name.split('.');
56
+ try {
57
+ const res = await fetchImpl(`${base}/rest/v1/${encodeURIComponent(table)}?select=*`, {
58
+ method: 'HEAD',
59
+ headers: { ...headers, Prefer: 'count=exact', 'Accept-Profile': schema },
60
+ redirect: 'manual',
61
+ });
62
+ const count = parseCount(res.headers.get('content-range'));
63
+ if (res.status === 200 || res.status === 206) {
64
+ results.push({ table: name, status: res.status, state: count > 0 ? 'open' : 'locked-or-empty', count });
65
+ } else if (res.status === 401 || res.status === 403) {
66
+ results.push({ table: name, status: res.status, state: 'locked', count: null });
67
+ } else if (res.status === 404 || res.status === 406) {
68
+ results.push({ table: name, status: res.status, state: 'not-exposed', count: null });
69
+ } else {
70
+ results.push({ table: name, status: res.status, state: 'error', count: null });
71
+ }
72
+ } catch (e) {
73
+ results.push({ table: name, status: 0, state: 'error', count: null, error: e.message });
74
+ }
75
+ }
76
+ }
77
+ await Promise.all(Array.from({ length: Math.min(concurrency, all.length) }, worker));
78
+ results.sort((a, b) => a.table.localeCompare(b.table));
79
+ return { results, apiList };
80
+ }
@@ -0,0 +1,38 @@
1
+ import { qualified } from '../sql/ident.js';
2
+
3
+ export default {
4
+ id: 'RC101',
5
+ target: 'supabase',
6
+ live: true,
7
+ severity: 'critical',
8
+ title: 'Live table hands rows to the public key',
9
+ summary:
10
+ 'Checked against the running project, not the migration files. A table that returns rows to the anon key is readable by anyone who opens your website and copies the key out of its code. This also catches changes made in the dashboard that never made it into a migration.',
11
+ standards: { cwe: ['CWE-200', 'CWE-284'], nist80053: ['AC-3', 'AC-6'], cis: ['3.3'] },
12
+
13
+ check(probe, model) {
14
+ const checked = [];
15
+ const findings = [];
16
+ for (const r of probe.results) {
17
+ checked.push(`table:${r.table}`);
18
+ if (r.state !== 'open') continue;
19
+ const [schema, name] = r.table.split('.');
20
+ const staticT = model?.tables.get(r.table);
21
+ const drift = staticT && staticT.rls
22
+ ? ' Your migrations turn row-level security on for this table, so either a policy lets the public read it, or the live database was changed outside your migrations.'
23
+ : '';
24
+ findings.push({
25
+ object: `table:${r.table}`,
26
+ name: r.table,
27
+ file: staticT?.file ?? null,
28
+ line: staticT?.line ?? null,
29
+ severity: 'critical',
30
+ message: `Live: ${r.table} returned a count of ${r.count} rows to the anon key.${drift}`,
31
+ plain: `Right now, anyone on the internet can read ${r.count.toLocaleString('en-US')} rows from the "${name}" table. rattlecheck confirmed this by asking your live project with only your public key. It did not read or keep any of the data.${drift}`,
32
+ todo: 'Lock this table today. If the data is meant to be public, mark it as allowed in rattlecheck.config.json with a reason.',
33
+ fix: `alter table ${qualified(schema, name)} enable row level security;\n-- Then review the policies on ${qualified(schema, name)} and remove any that let anon read rows it shouldn't.`,
34
+ });
35
+ }
36
+ return { checked, findings };
37
+ },
38
+ };