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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +173 -2
- package/bin/rattlecheck.js +12 -0
- package/docs/rules/RC001.md +40 -0
- package/docs/rules/RC002.md +35 -0
- package/docs/rules/RC003.md +25 -0
- package/docs/rules/RC004.md +23 -0
- package/docs/rules/RC005.md +32 -0
- package/docs/rules/RC101.md +31 -0
- package/integrations/AGENTS.md +11 -0
- package/integrations/claude-code/rattlecheck/SKILL.md +42 -0
- package/integrations/cursor/rattlecheck.mdc +13 -0
- package/package.json +45 -4
- package/src/cli.js +158 -0
- package/src/config.js +62 -0
- package/src/live/catalog.js +43 -0
- package/src/live/env.js +102 -0
- package/src/live/ownership.js +72 -0
- package/src/live/probe.js +80 -0
- package/src/live/rc101-anon-readable.js +38 -0
- package/src/mcp/server.js +163 -0
- package/src/model.js +723 -0
- package/src/report/badge-svg.js +26 -0
- package/src/report/card-svg.js +50 -0
- package/src/report/grade.js +26 -0
- package/src/report/sarif.js +44 -0
- package/src/report/terminal.js +105 -0
- package/src/rules/index.js +14 -0
- package/src/rules/supabase/rc001-table-without-rls.js +54 -0
- package/src/rules/supabase/rc002-definer-callable-by-anon.js +37 -0
- package/src/rules/supabase/rc003-definer-search-path.js +33 -0
- package/src/rules/supabase/rc004-invoker-trigger-locked-table.js +49 -0
- package/src/rules/supabase/rc005-permissive-true-policy.js +81 -0
- package/src/scan.js +167 -0
- package/src/sql/ident.js +25 -0
- package/src/sql/signature.js +143 -0
- package/src/sql/statements.js +267 -0
- package/src/version.js +6 -0
package/src/model.js
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
// Replays a Supabase project's migrations, in order, statement by statement,
|
|
2
|
+
// and produces the CURRENT state of every table, policy, function and trigger.
|
|
3
|
+
//
|
|
4
|
+
// Order matters. A REVOKE from March does not protect a function that was
|
|
5
|
+
// dropped and re-created in June (re-creation resets its grants). A policy
|
|
6
|
+
// created and later dropped protects nothing. Checkers that pattern-match
|
|
7
|
+
// files instead of replaying them report holes that were closed and miss holes
|
|
8
|
+
// that were reopened.
|
|
9
|
+
//
|
|
10
|
+
// When the replay can't be sure, it leans toward "reachable". For a security
|
|
11
|
+
// tool a missed hole is worse than a question.
|
|
12
|
+
//
|
|
13
|
+
// This is a static model. It cannot see inside dynamic SQL (EXECUTE format(...))
|
|
14
|
+
// and it does not know what was changed by hand in a dashboard. The live probe
|
|
15
|
+
// exists for the second problem; `defaults: "clean"` in the config exists for
|
|
16
|
+
// projects whose baseline revokes default grants through dynamic SQL.
|
|
17
|
+
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { splitStatements, stripComments, readQualifiedName, readParenGroup, lineIndex, quotedEnd, blankLiterals } from './sql/statements.js';
|
|
21
|
+
import { normaliseArgs, signatureKey } from './sql/signature.js';
|
|
22
|
+
|
|
23
|
+
const PRIVS = ['select', 'insert', 'update', 'delete'];
|
|
24
|
+
const API_ROLES = ['anon', 'authenticated'];
|
|
25
|
+
|
|
26
|
+
/** Find the migrations directory for a project root (or accept a directory of .sql files). */
|
|
27
|
+
export function findMigrationsDir(root) {
|
|
28
|
+
const candidates = [path.join(root, 'supabase', 'migrations'), path.join(root, 'migrations'), root];
|
|
29
|
+
for (const dir of candidates) {
|
|
30
|
+
if (fs.existsSync(dir) && fs.statSync(dir).isDirectory() && fs.readdirSync(dir).some((f) => f.endsWith('.sql'))) {
|
|
31
|
+
return dir;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Exposed schemas from supabase/config.toml ([api] schemas = [...]), falling back to Supabase's default. */
|
|
38
|
+
export function readExposedSchemas(root) {
|
|
39
|
+
const fallback = ['public', 'graphql_public'];
|
|
40
|
+
const tomlPath = path.join(root, 'supabase', 'config.toml');
|
|
41
|
+
if (!fs.existsSync(tomlPath)) return fallback;
|
|
42
|
+
let inApi = false;
|
|
43
|
+
let collecting = null;
|
|
44
|
+
for (const raw of fs.readFileSync(tomlPath, 'utf8').split(/\r?\n/)) {
|
|
45
|
+
const line = raw.replace(/#.*$/, '').trim();
|
|
46
|
+
if (collecting !== null) {
|
|
47
|
+
collecting += ` ${line}`;
|
|
48
|
+
if (line.includes(']')) break;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (/^\[.*\]$/.test(line)) {
|
|
52
|
+
inApi = line === '[api]';
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (inApi) {
|
|
56
|
+
const m = /^schemas\s*=\s*(\[.*)$/.exec(line);
|
|
57
|
+
if (m) {
|
|
58
|
+
collecting = m[1];
|
|
59
|
+
if (m[1].includes(']')) break;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (collecting === null) return fallback;
|
|
64
|
+
const list = [...collecting.matchAll(/"([^"]+)"|'([^']+)'/g)].map((x) => (x[1] || x[2]).toLowerCase());
|
|
65
|
+
return list.length ? list : fallback;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function loadMigrations(dir) {
|
|
69
|
+
return fs
|
|
70
|
+
.readdirSync(dir)
|
|
71
|
+
.filter((f) => f.endsWith('.sql'))
|
|
72
|
+
.sort() // timestamp-prefixed, so this is chronological
|
|
73
|
+
.map((file) => ({ file, sql: fs.readFileSync(path.join(dir, file), 'utf8') }));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Split on top-level commas (not inside parentheses or quotes).
|
|
77
|
+
function splitTopLevel(text) {
|
|
78
|
+
const parts = [];
|
|
79
|
+
let depth = 0;
|
|
80
|
+
let cur = '';
|
|
81
|
+
for (let i = 0; i < text.length; i++) {
|
|
82
|
+
const ch = text[i];
|
|
83
|
+
if (ch === "'" || ch === '"') {
|
|
84
|
+
const end = quotedEnd(text, i);
|
|
85
|
+
cur += text.slice(i, end);
|
|
86
|
+
i = end - 1;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (ch === '(') depth++;
|
|
90
|
+
else if (ch === ')') depth--;
|
|
91
|
+
if (ch === ',' && depth === 0) {
|
|
92
|
+
parts.push(cur);
|
|
93
|
+
cur = '';
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
cur += ch;
|
|
97
|
+
}
|
|
98
|
+
if (cur.trim()) parts.push(cur);
|
|
99
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// GRANT/REVOKE privilege list -> { table, column, usage }. A column list
|
|
103
|
+
// (`SELECT (email)`) grants access to those columns only; revoking it does NOT
|
|
104
|
+
// remove a table-level grant, so the two must be kept apart.
|
|
105
|
+
function parsePrivs(text) {
|
|
106
|
+
const table = new Set();
|
|
107
|
+
const column = new Set();
|
|
108
|
+
let usage = false;
|
|
109
|
+
for (const item of splitTopLevel(text.toLowerCase())) {
|
|
110
|
+
const hasCols = item.includes('(');
|
|
111
|
+
const word = item.replace(/\(.*$/s, '').trim();
|
|
112
|
+
if (/^all(\s+privileges)?$/.test(word)) {
|
|
113
|
+
for (const p of PRIVS) (hasCols ? column : table).add(p);
|
|
114
|
+
usage = true;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (word === 'usage') usage = true;
|
|
118
|
+
if (PRIVS.includes(word)) (hasCols ? column : table).add(word);
|
|
119
|
+
}
|
|
120
|
+
return { table, column, usage };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function rolesIn(text) {
|
|
124
|
+
return {
|
|
125
|
+
public: /\bpublic\b/i.test(text),
|
|
126
|
+
anon: /\banon\b/i.test(text),
|
|
127
|
+
authenticated: /\bauthenticated\b/i.test(text),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Policy roles: absent TO clause means PUBLIC (every role, including anon).
|
|
132
|
+
function parsePolicyRoles(toText) {
|
|
133
|
+
if (!toText) return ['public'];
|
|
134
|
+
return toText
|
|
135
|
+
.split(',')
|
|
136
|
+
.map((r) => r.trim().replace(/"/g, '').toLowerCase())
|
|
137
|
+
.filter(Boolean);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Reads `a, b, "c"` starting at pos. Returns [{schema, name, end}].
|
|
141
|
+
function readNameList(sql, pos) {
|
|
142
|
+
const out = [];
|
|
143
|
+
let p = pos;
|
|
144
|
+
for (;;) {
|
|
145
|
+
const n = readQualifiedName(sql, p);
|
|
146
|
+
if (!n) break;
|
|
147
|
+
out.push(n);
|
|
148
|
+
let j = n.end;
|
|
149
|
+
while (j < sql.length && /\s/.test(sql[j])) j++;
|
|
150
|
+
if (sql[j] !== ',') break;
|
|
151
|
+
p = j + 1;
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Reads `f(uuid), g, public.h(text)` starting at pos. Returns [{n, args}] where
|
|
157
|
+
// args is the raw argument text or null when no list was given.
|
|
158
|
+
function readFunctionList(sql, pos) {
|
|
159
|
+
const out = [];
|
|
160
|
+
let p = pos;
|
|
161
|
+
for (;;) {
|
|
162
|
+
const n = readQualifiedName(sql, p);
|
|
163
|
+
if (!n) break;
|
|
164
|
+
const paren = readParenGroup(sql, n.end);
|
|
165
|
+
out.push({ n, args: paren ? paren.raw : null });
|
|
166
|
+
let j = paren ? paren.end : n.end;
|
|
167
|
+
while (j < sql.length && /\s/.test(sql[j])) j++;
|
|
168
|
+
if (sql[j] !== ',') break;
|
|
169
|
+
p = j + 1;
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Schemas the platform creates, so they exist even though no migration made them.
|
|
175
|
+
const PLATFORM_SCHEMAS = ['public', 'extensions', 'auth', 'storage', 'graphql', 'graphql_public', 'realtime', 'vault', 'net', 'cron', 'pgsodium', 'supabase_functions', 'supabase_migrations'];
|
|
176
|
+
|
|
177
|
+
// The schema unqualified CREATEs land in: the first schema in the path that
|
|
178
|
+
// exists. Returns null for DEFAULT or a path with nothing usable (both mean public).
|
|
179
|
+
function firstSchema(value, exists) {
|
|
180
|
+
if (/^\s*default\s*;?\s*$/i.test(value)) return null;
|
|
181
|
+
for (const part of value.split(',')) {
|
|
182
|
+
let t = part.trim().replace(/;$/, '').trim();
|
|
183
|
+
if (!t || t === "''" || t === '""') continue;
|
|
184
|
+
if (/^'.*'$/.test(t)) {
|
|
185
|
+
const inner = firstSchema(t.slice(1, -1), exists);
|
|
186
|
+
if (inner) return inner;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (/^"\$user"$|^\$user$/i.test(t)) continue;
|
|
190
|
+
if (/^pg_(catalog|temp)$/i.test(t)) continue;
|
|
191
|
+
t = /^".*"$/.test(t) ? t.slice(1, -1) : t.toLowerCase();
|
|
192
|
+
if (exists(t)) return t;
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const SEARCH_PATH_RE = /\bSET\s+"?search_path"?\s*(?:=|TO)\s*([^\n]*)|\bSET\s+"?search_path"?\s+FROM\s+CURRENT\b/i;
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* @param {{file:string, sql:string}[]} migrations
|
|
201
|
+
* @param {{defaults?: string|object, exposedSchemas?: string[], migrationRoles?: string[]}} opts
|
|
202
|
+
*/
|
|
203
|
+
export function buildModel(migrations, opts = {}) {
|
|
204
|
+
// `defaults` is a string for both object kinds, or { functions, tables }.
|
|
205
|
+
const d0 = opts.defaults ?? 'supabase-stock';
|
|
206
|
+
const defaults = typeof d0 === 'string' ? { functions: d0, tables: d0 } : { functions: 'supabase-stock', tables: 'supabase-stock', ...d0 };
|
|
207
|
+
const exposedSchemas = (opts.exposedSchemas ?? ['public', 'graphql_public']).map((s) => s.toLowerCase());
|
|
208
|
+
// ALTER DEFAULT PRIVILEGES only affects objects created by the roles it names.
|
|
209
|
+
// Migrations run as postgres, so FOR ROLE supabase_admin changes nothing here.
|
|
210
|
+
const migrationRoles = (opts.migrationRoles ?? ['postgres']).map((r) => r.toLowerCase());
|
|
211
|
+
|
|
212
|
+
const tables = new Map();
|
|
213
|
+
const functions = new Map();
|
|
214
|
+
const triggers = [];
|
|
215
|
+
const coverage = { files: migrations.length, statements: 0, tablesSeen: 0, functionsSeen: 0, policiesSeen: 0 };
|
|
216
|
+
|
|
217
|
+
// Schema USAGE per role. Without USAGE a role can't reach anything inside the
|
|
218
|
+
// schema. public starts usable by everyone; a schema created in a migration
|
|
219
|
+
// starts closed; a schema never created here (made by the platform) is
|
|
220
|
+
// assumed usable, which is the safe direction.
|
|
221
|
+
const schemaUsage = new Map([['public', { public: true, anon: true, authenticated: true }]]);
|
|
222
|
+
const usageOf = (s) => schemaUsage.get(s) ?? { public: true, anon: true, authenticated: true };
|
|
223
|
+
|
|
224
|
+
// Default privileges decide what a new object is born with. Supabase's stock
|
|
225
|
+
// setup grants ALL on new tables and functions in public to anon and
|
|
226
|
+
// authenticated; Postgres itself grants EXECUTE on every new function to
|
|
227
|
+
// PUBLIC unless that is revoked globally.
|
|
228
|
+
let globalPublicExecRevoked = defaults.functions === 'clean';
|
|
229
|
+
const globalFn = { anon: false, authenticated: false };
|
|
230
|
+
const globalTable = { anon: new Set(), authenticated: new Set() };
|
|
231
|
+
const fnDefaults = new Map(); // schema -> {publicGrant, anon, authenticated}
|
|
232
|
+
const tableDefaults = new Map(); // schema -> {anon:Set, authenticated:Set}
|
|
233
|
+
if (defaults.functions === 'supabase-stock') fnDefaults.set('public', { publicGrant: false, anon: true, authenticated: true });
|
|
234
|
+
if (defaults.tables === 'supabase-stock') tableDefaults.set('public', { anon: new Set(PRIVS), authenticated: new Set(PRIVS) });
|
|
235
|
+
const fnDefaultsFor = (s) => {
|
|
236
|
+
if (!fnDefaults.has(s)) fnDefaults.set(s, { publicGrant: false, anon: false, authenticated: false });
|
|
237
|
+
return fnDefaults.get(s);
|
|
238
|
+
};
|
|
239
|
+
const tableDefaultsFor = (s) => {
|
|
240
|
+
if (!tableDefaults.has(s)) tableDefaults.set(s, { anon: new Set(), authenticated: new Set() });
|
|
241
|
+
return tableDefaults.get(s);
|
|
242
|
+
};
|
|
243
|
+
const fnKeysForName = (schema, name) => {
|
|
244
|
+
const prefix = `${schema}.${name}(`;
|
|
245
|
+
return [...functions.keys()].filter((k) => k.startsWith(prefix));
|
|
246
|
+
};
|
|
247
|
+
const fnKeysFor = ({ n, args }) =>
|
|
248
|
+
args !== null ? [signatureKey(schemaOf(n), n.name, normaliseArgs(args))] : fnKeysForName(schemaOf(n), n.name);
|
|
249
|
+
|
|
250
|
+
// search_path tracking. SET LOCAL and set_config(..., true) last until the
|
|
251
|
+
// transaction ends; a plain SET lasts for the session (one migration file).
|
|
252
|
+
const knownSchemas = new Set(PLATFORM_SCHEMAS);
|
|
253
|
+
const exists = (s) => knownSchemas.has(s);
|
|
254
|
+
let sessionSchema = 'public';
|
|
255
|
+
let localSchema = null;
|
|
256
|
+
const schemaOf = (n) => (n.schema ?? localSchema ?? sessionSchema).toLowerCase();
|
|
257
|
+
const tkey = (n) => `${schemaOf(n)}.${n.name}`;
|
|
258
|
+
|
|
259
|
+
function addTable(n, file, line, kind) {
|
|
260
|
+
const schema = schemaOf(n);
|
|
261
|
+
const td = tableDefaultsFor(schema);
|
|
262
|
+
const k = `${schema}.${n.name}`;
|
|
263
|
+
tables.set(k, {
|
|
264
|
+
key: k,
|
|
265
|
+
schema,
|
|
266
|
+
name: n.name,
|
|
267
|
+
file,
|
|
268
|
+
line,
|
|
269
|
+
kind,
|
|
270
|
+
rls: false,
|
|
271
|
+
privs: {
|
|
272
|
+
anon: new Set([...td.anon, ...globalTable.anon]),
|
|
273
|
+
authenticated: new Set([...td.authenticated, ...globalTable.authenticated]),
|
|
274
|
+
},
|
|
275
|
+
policies: new Map(),
|
|
276
|
+
});
|
|
277
|
+
coverage.tablesSeen++;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
for (const { file, sql: source } of migrations) {
|
|
281
|
+
const lineAt = lineIndex(source);
|
|
282
|
+
sessionSchema = 'public'; // each migration file runs in its own session
|
|
283
|
+
localSchema = null;
|
|
284
|
+
for (const { sql: rawStmt, index } of splitStatements(source)) {
|
|
285
|
+
coverage.statements++;
|
|
286
|
+
const line = lineAt(index);
|
|
287
|
+
const head = stripComments(rawStmt).replace(/^\s+/, '');
|
|
288
|
+
const flat = blankLiterals(head); // for keyword tests that must not see string contents
|
|
289
|
+
|
|
290
|
+
// ── SET search_path (decides where unqualified names land) ───────────
|
|
291
|
+
const sp = /^SET\s+(SESSION\s+|LOCAL\s+)?"?search_path"?\s*(?:=|TO)\s*([\s\S]*)$/i.exec(head);
|
|
292
|
+
if (sp) {
|
|
293
|
+
const s = firstSchema(sp[2], exists) ?? 'public';
|
|
294
|
+
if (/^LOCAL/i.test(sp[1] ?? '')) localSchema = s;
|
|
295
|
+
else sessionSchema = s;
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
const sc = /set_config\(\s*'search_path'\s*,\s*'([^']*)'\s*,\s*(true|false)\s*\)/i.exec(head);
|
|
299
|
+
if (/^SELECT\b/i.test(head) && sc) {
|
|
300
|
+
const s = firstSchema(sc[1], exists) ?? 'public';
|
|
301
|
+
if (sc[2].toLowerCase() === 'true') localSchema = s;
|
|
302
|
+
else sessionSchema = s;
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (/^RESET\s+("?search_path"?|ALL)\b/i.test(head)) {
|
|
306
|
+
sessionSchema = 'public';
|
|
307
|
+
localSchema = null;
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (/^(COMMIT|END|ABORT)\b/i.test(head) || (/^ROLLBACK\b/i.test(head) && !/^ROLLBACK\s+(?:WORK\s+|TRANSACTION\s+)?TO\b/i.test(head))) {
|
|
311
|
+
localSchema = null;
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// ── CREATE SCHEMA ────────────────────────────────────────────────────
|
|
316
|
+
const cs = /^CREATE\s+SCHEMA\s+(IF\s+NOT\s+EXISTS\s+)?/i.exec(head);
|
|
317
|
+
if (cs) {
|
|
318
|
+
const n = readQualifiedName(head, cs[0].length);
|
|
319
|
+
if (!n) continue;
|
|
320
|
+
const name = n.name.toLowerCase();
|
|
321
|
+
// A plain CREATE SCHEMA proves the schema is new, so it starts closed.
|
|
322
|
+
// IF NOT EXISTS proves nothing: it may already exist (made in the
|
|
323
|
+
// dashboard, with USAGE granted there), so leave it as it was.
|
|
324
|
+
if (!cs[1] && !knownSchemas.has(name)) schemaUsage.set(name, { public: false, anon: false, authenticated: false });
|
|
325
|
+
knownSchemas.add(name);
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ── CREATE TABLE (including CREATE TABLE AS) ──────────────────────────
|
|
330
|
+
const ct = /^CREATE\s+(?:(GLOBAL|LOCAL)\s+)?(?:(TEMP|TEMPORARY|UNLOGGED)\s+)?TABLE\s+(IF\s+NOT\s+EXISTS\s+)?/i.exec(head);
|
|
331
|
+
if (ct) {
|
|
332
|
+
if (ct[2] && /^TEMP/i.test(ct[2])) continue;
|
|
333
|
+
const n = readQualifiedName(head, ct[0].length);
|
|
334
|
+
if (!n) continue;
|
|
335
|
+
if (ct[3] && tables.has(tkey(n))) continue;
|
|
336
|
+
// `AS` right after the name (or after a bare column-name list) is CREATE TABLE AS.
|
|
337
|
+
const isCtas = /^\s*(?:\([^()]*\)\s*)?(?:WITH\s*\([^()]*\)\s*)?(?:TABLESPACE\s+\S+\s*)?AS\b/i.test(head.slice(n.end));
|
|
338
|
+
addTable(n, file, line, isCtas ? 'ctas' : 'table');
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// ── SELECT ... INTO new_table (another way to copy a table) ──────────
|
|
343
|
+
if (/^(?:WITH\b|SELECT\b)/i.test(head)) {
|
|
344
|
+
// INSERT INTO / MERGE INTO inside a WITH are writes, not new tables.
|
|
345
|
+
const into = /(?<!\b(?:INSERT|MERGE)\s+)\bINTO\s+(?:(TEMP|TEMPORARY)\s+|UNLOGGED\s+)?(?:TABLE\s+)?/i.exec(flat);
|
|
346
|
+
if (into && !into[1]) {
|
|
347
|
+
const n = readQualifiedName(head, into.index + into[0].length);
|
|
348
|
+
if (n && !/^(strict)$/i.test(n.name)) addTable(n, file, line, 'ctas');
|
|
349
|
+
}
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// ── DROP TABLE ───────────────────────────────────────────────────────
|
|
354
|
+
const dt = /^DROP\s+TABLE\s+(IF\s+EXISTS\s+)?/i.exec(head);
|
|
355
|
+
if (dt) {
|
|
356
|
+
for (const n of readNameList(head, dt[0].length)) tables.delete(tkey(n));
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// ── ALTER TABLE ... RLS / RENAME / SET SCHEMA ────────────────────────
|
|
361
|
+
const at = /^ALTER\s+TABLE\s+(IF\s+EXISTS\s+)?(ONLY\s+)?/i.exec(head);
|
|
362
|
+
if (at) {
|
|
363
|
+
const n = readQualifiedName(head, at[0].length);
|
|
364
|
+
if (!n) continue;
|
|
365
|
+
const k = tkey(n);
|
|
366
|
+
const t = tables.get(k);
|
|
367
|
+
if (!t) continue;
|
|
368
|
+
const rest = head.slice(n.end);
|
|
369
|
+
const restFlat = flat.slice(n.end);
|
|
370
|
+
// Multiple actions can be comma-separated; the last word on RLS wins.
|
|
371
|
+
const rlsActions = [...restFlat.matchAll(/\b(ENABLE|DISABLE)\s+ROW\s+LEVEL\s+SECURITY\b/gi)];
|
|
372
|
+
if (rlsActions.length) t.rls = rlsActions[rlsActions.length - 1][1].toUpperCase() === 'ENABLE';
|
|
373
|
+
const rn = /^\s*RENAME\s+TO\s+/i.exec(rest);
|
|
374
|
+
if (rn) {
|
|
375
|
+
const to = readQualifiedName(rest, rn[0].length);
|
|
376
|
+
if (to) {
|
|
377
|
+
tables.delete(k);
|
|
378
|
+
t.name = to.name;
|
|
379
|
+
t.key = `${t.schema}.${to.name}`;
|
|
380
|
+
tables.set(t.key, t);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
const ss = /^\s*SET\s+SCHEMA\s+/i.exec(rest);
|
|
384
|
+
if (ss) {
|
|
385
|
+
const to = readQualifiedName(rest, ss[0].length);
|
|
386
|
+
if (to) {
|
|
387
|
+
tables.delete(k);
|
|
388
|
+
t.schema = to.name.toLowerCase();
|
|
389
|
+
t.key = `${t.schema}.${t.name}`;
|
|
390
|
+
tables.set(t.key, t);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// ── CREATE / DROP / ALTER POLICY ─────────────────────────────────────
|
|
397
|
+
const policyTarget = (re) => {
|
|
398
|
+
const m = re.exec(head);
|
|
399
|
+
if (!m) return null;
|
|
400
|
+
const pn = readQualifiedName(head, m[0].length);
|
|
401
|
+
if (!pn) return null;
|
|
402
|
+
const on = /^\s*ON\s+/i.exec(head.slice(pn.end));
|
|
403
|
+
if (!on) return null;
|
|
404
|
+
const tn = readQualifiedName(head, pn.end + on[0].length);
|
|
405
|
+
if (!tn) return null;
|
|
406
|
+
return { pn, tn, table: tables.get(tkey(tn)) };
|
|
407
|
+
};
|
|
408
|
+
if (/^CREATE\s+POLICY\s+/i.test(head)) {
|
|
409
|
+
const pt = policyTarget(/^CREATE\s+POLICY\s+/i);
|
|
410
|
+
coverage.policiesSeen++;
|
|
411
|
+
if (pt?.table) pt.table.policies.set(pt.pn.name, { name: pt.pn.name, file, line, ...parsePolicyClauses(head.slice(pt.tn.end)) });
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (/^DROP\s+POLICY\s+/i.test(head)) {
|
|
415
|
+
const pt = policyTarget(/^DROP\s+POLICY\s+(?:IF\s+EXISTS\s+)?/i);
|
|
416
|
+
pt?.table?.policies.delete(pt.pn.name);
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
if (/^ALTER\s+POLICY\s+/i.test(head)) {
|
|
420
|
+
const pt = policyTarget(/^ALTER\s+POLICY\s+/i);
|
|
421
|
+
const p = pt?.table?.policies.get(pt.pn.name);
|
|
422
|
+
if (!p) continue;
|
|
423
|
+
const rest = head.slice(pt.tn.end);
|
|
424
|
+
const rn = /^\s*RENAME\s+TO\s+/i.exec(rest);
|
|
425
|
+
if (rn) {
|
|
426
|
+
const to = readQualifiedName(rest, rn[0].length);
|
|
427
|
+
if (to) {
|
|
428
|
+
pt.table.policies.delete(pt.pn.name);
|
|
429
|
+
p.name = to.name;
|
|
430
|
+
pt.table.policies.set(to.name, p);
|
|
431
|
+
}
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
const upd = parsePolicyClauses(rest);
|
|
435
|
+
if (upd.hasTo) p.roles = upd.roles;
|
|
436
|
+
if (upd.using !== null) p.using = upd.using;
|
|
437
|
+
if (upd.check !== null) p.check = upd.check;
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// ── CREATE [OR REPLACE] FUNCTION ─────────────────────────────────────
|
|
442
|
+
const cf = /^CREATE\s+(OR\s+REPLACE\s+)?FUNCTION\s+/i.exec(head);
|
|
443
|
+
if (cf) {
|
|
444
|
+
const isReplace = Boolean(cf[1]);
|
|
445
|
+
const n = readQualifiedName(head, cf[0].length);
|
|
446
|
+
if (!n) continue;
|
|
447
|
+
const paren = readParenGroup(head, n.end);
|
|
448
|
+
if (!paren) continue;
|
|
449
|
+
const schema = schemaOf(n);
|
|
450
|
+
const argsig = normaliseArgs(paren.raw);
|
|
451
|
+
const k = signatureKey(schema, n.name, argsig);
|
|
452
|
+
const { header, body, trailer } = splitFunctionBody(head.slice(paren.end));
|
|
453
|
+
const attrs = `${header}\n${trailer}`;
|
|
454
|
+
const spm = SEARCH_PATH_RE.exec(attrs);
|
|
455
|
+
const existed = functions.has(k);
|
|
456
|
+
const prev = functions.get(k);
|
|
457
|
+
const d = fnDefaultsFor(schema);
|
|
458
|
+
functions.set(k, {
|
|
459
|
+
key: k,
|
|
460
|
+
schema,
|
|
461
|
+
name: n.name,
|
|
462
|
+
argsig,
|
|
463
|
+
file,
|
|
464
|
+
line,
|
|
465
|
+
body,
|
|
466
|
+
isSecurityDefiner: /\bSECURITY\s+DEFINER\b/i.test(attrs),
|
|
467
|
+
isTrigger: /\bRETURNS\s+"?trigger"?(?!\w)/i.test(header),
|
|
468
|
+
searchPath: spm ? (spm[1] ?? 'FROM CURRENT').trim().replace(/;$/, '') : null,
|
|
469
|
+
// CREATE OR REPLACE on an existing function keeps its grants;
|
|
470
|
+
// a fresh CREATE takes whatever the defaults say right now.
|
|
471
|
+
publicExec: isReplace && existed ? prev.publicExec : !globalPublicExecRevoked || d.publicGrant,
|
|
472
|
+
anonExec: isReplace && existed ? prev.anonExec : d.anon || globalFn.anon,
|
|
473
|
+
authExec: isReplace && existed ? prev.authExec : d.authenticated || globalFn.authenticated,
|
|
474
|
+
});
|
|
475
|
+
coverage.functionsSeen++;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// ── ALTER FUNCTION ───────────────────────────────────────────────────
|
|
480
|
+
const af = /^ALTER\s+FUNCTION\s+/i.exec(head);
|
|
481
|
+
if (af) {
|
|
482
|
+
const [ref] = readFunctionList(head, af[0].length);
|
|
483
|
+
if (!ref) continue;
|
|
484
|
+
const restStart = ref.args !== null ? readParenGroup(head, ref.n.end).end : ref.n.end;
|
|
485
|
+
const rest = head.slice(restStart);
|
|
486
|
+
for (const k of fnKeysFor(ref)) {
|
|
487
|
+
const f = functions.get(k);
|
|
488
|
+
if (!f) continue;
|
|
489
|
+
if (/\bSECURITY\s+DEFINER\b/i.test(rest)) f.isSecurityDefiner = true;
|
|
490
|
+
if (/\bSECURITY\s+INVOKER\b/i.test(rest)) f.isSecurityDefiner = false;
|
|
491
|
+
const spm = SEARCH_PATH_RE.exec(rest);
|
|
492
|
+
if (spm) f.searchPath = (spm[1] ?? 'FROM CURRENT').trim().replace(/;$/, '');
|
|
493
|
+
if (/\bRESET\s+("?search_path"?|ALL)\b/i.test(rest)) f.searchPath = null;
|
|
494
|
+
const oldName = `${f.schema}.${f.name}`;
|
|
495
|
+
const rn = /^\s*RENAME\s+TO\s+/i.exec(rest);
|
|
496
|
+
const ss = /^\s*SET\s+SCHEMA\s+/i.exec(rest);
|
|
497
|
+
if (rn || ss) {
|
|
498
|
+
const to = readQualifiedName(rest, (rn ?? ss)[0].length);
|
|
499
|
+
if (!to) continue;
|
|
500
|
+
functions.delete(k);
|
|
501
|
+
if (rn) f.name = to.name;
|
|
502
|
+
else f.schema = to.name.toLowerCase();
|
|
503
|
+
f.key = signatureKey(f.schema, f.name, f.argsig);
|
|
504
|
+
functions.set(f.key, f);
|
|
505
|
+
for (const tr of triggers) if (tr.fn === oldName) tr.fn = `${f.schema}.${f.name}`;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// ── DROP FUNCTION ────────────────────────────────────────────────────
|
|
512
|
+
const df = /^DROP\s+FUNCTION\s+(IF\s+EXISTS\s+)?/i.exec(head);
|
|
513
|
+
if (df) {
|
|
514
|
+
for (const ref of readFunctionList(head, df[0].length)) for (const k of fnKeysFor(ref)) functions.delete(k);
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// ── CREATE TRIGGER ───────────────────────────────────────────────────
|
|
519
|
+
const tr = /^CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+/i.exec(head);
|
|
520
|
+
if (tr) {
|
|
521
|
+
const on = /\bON\s+/i.exec(head.slice(tr[0].length));
|
|
522
|
+
const exec = /\bEXECUTE\s+(?:FUNCTION|PROCEDURE)\s+/i.exec(head);
|
|
523
|
+
if (!on || !exec) continue;
|
|
524
|
+
const tn = readQualifiedName(head, tr[0].length + on.index + on[0].length);
|
|
525
|
+
const fn = readQualifiedName(head, exec.index + exec[0].length);
|
|
526
|
+
if (tn && fn) triggers.push({ table: tkey(tn), fn: `${schemaOf(fn)}.${fn.name}`, file, line });
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// ── ALTER DEFAULT PRIVILEGES ─────────────────────────────────────────
|
|
531
|
+
if (/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(head)) {
|
|
532
|
+
const forRole = /\bFOR\s+(?:ROLE|USER)\s+([\s\S]*?)\s+(?=IN\s+SCHEMA\b|GRANT\b|REVOKE\b)/i.exec(head);
|
|
533
|
+
if (forRole) {
|
|
534
|
+
const roles = forRole[1].split(',').map((r) => r.trim().replace(/"/g, '').toLowerCase());
|
|
535
|
+
if (!roles.some((r) => migrationRoles.includes(r))) continue;
|
|
536
|
+
}
|
|
537
|
+
if (/\bREVOKE\s+GRANT\s+OPTION\s+FOR\b/i.test(head)) continue;
|
|
538
|
+
const action = /\b(GRANT|REVOKE)\s+([\s\S]*?)\bON\s+(FUNCTIONS|ROUTINES|TABLES)\b/i.exec(head);
|
|
539
|
+
if (!action) continue;
|
|
540
|
+
const isRevoke = action[1].toUpperCase() === 'REVOKE';
|
|
541
|
+
const onTables = action[3].toUpperCase() === 'TABLES';
|
|
542
|
+
const roleText = isRevoke ? (/\bFROM\s+([\s\S]*)$/i.exec(head)?.[1] ?? '') : (/\bTO\s+([\s\S]*)$/i.exec(head)?.[1] ?? '');
|
|
543
|
+
const roles = rolesIn(roleText);
|
|
544
|
+
const privs = parsePrivs(action[2]).table;
|
|
545
|
+
const inSchema = /\bIN\s+SCHEMA\s+/i.exec(head);
|
|
546
|
+
const applyTables = (d) => {
|
|
547
|
+
for (const role of API_ROLES) {
|
|
548
|
+
// GRANT TO PUBLIC reaches every role; REVOKE FROM PUBLIC leaves a role's own grant alone.
|
|
549
|
+
if (isRevoke ? !roles[role] : !roles[role] && !roles.public) continue;
|
|
550
|
+
for (const p of privs) isRevoke ? d[role].delete(p) : d[role].add(p);
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
const execPriv = /\b(EXECUTE|ALL)\b/i.test(action[2]);
|
|
554
|
+
if (!inSchema) {
|
|
555
|
+
if (onTables) applyTables(globalTable);
|
|
556
|
+
else if (execPriv) {
|
|
557
|
+
// Only the global form reaches Postgres's built-in EXECUTE-to-PUBLIC.
|
|
558
|
+
if (roles.public) globalPublicExecRevoked = isRevoke;
|
|
559
|
+
if (roles.anon) globalFn.anon = !isRevoke;
|
|
560
|
+
if (roles.authenticated) globalFn.authenticated = !isRevoke;
|
|
561
|
+
}
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
for (const s of readNameList(head, inSchema.index + inSchema[0].length)) {
|
|
565
|
+
const schema = s.name.toLowerCase();
|
|
566
|
+
if (onTables) applyTables(tableDefaultsFor(schema));
|
|
567
|
+
else if (execPriv) {
|
|
568
|
+
const d = fnDefaultsFor(schema);
|
|
569
|
+
if (roles.public) d.publicGrant = !isRevoke;
|
|
570
|
+
if (roles.anon) d.anon = !isRevoke;
|
|
571
|
+
if (roles.authenticated) d.authenticated = !isRevoke;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// ── GRANT / REVOKE on concrete objects ───────────────────────────────
|
|
578
|
+
const acl = /^(REVOKE|GRANT)\s+/i.exec(head);
|
|
579
|
+
if (!acl) continue;
|
|
580
|
+
// Revoking the grant option leaves the privilege itself in place.
|
|
581
|
+
if (/^REVOKE\s+GRANT\s+OPTION\s+FOR\b/i.test(head)) continue;
|
|
582
|
+
const isRevoke = acl[1].toUpperCase() === 'REVOKE';
|
|
583
|
+
const roleText = isRevoke ? (/\bFROM\s+([\s\S]*)$/i.exec(head)?.[1] ?? '') : (/\bTO\s+([\s\S]*)$/i.exec(head)?.[1] ?? '');
|
|
584
|
+
const roles = rolesIn(roleText);
|
|
585
|
+
if (!roles.public && !roles.anon && !roles.authenticated) continue;
|
|
586
|
+
const onAt = /\bON\b/i.exec(flat);
|
|
587
|
+
const privs = parsePrivs(head.slice(acl[0].length, onAt ? onAt.index : acl[0].length));
|
|
588
|
+
|
|
589
|
+
const onSchema = /\bON\s+SCHEMA\s+/i.exec(head);
|
|
590
|
+
if (onSchema) {
|
|
591
|
+
// Only USAGE decides whether a role can reach objects in a schema.
|
|
592
|
+
// REVOKE CREATE (the standard hardening line) changes nothing here.
|
|
593
|
+
if (!privs.usage) continue;
|
|
594
|
+
for (const s of readNameList(head, onSchema.index + onSchema[0].length)) {
|
|
595
|
+
const name = s.name.toLowerCase();
|
|
596
|
+
const u = { ...usageOf(name) };
|
|
597
|
+
for (const r of ['public', ...API_ROLES]) if (roles[r]) u[r] = !isRevoke;
|
|
598
|
+
schemaUsage.set(name, u);
|
|
599
|
+
}
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const applyFn = (f) => {
|
|
604
|
+
if (roles.public) f.publicExec = !isRevoke;
|
|
605
|
+
if (roles.anon) f.anonExec = !isRevoke;
|
|
606
|
+
if (roles.authenticated) f.authExec = !isRevoke;
|
|
607
|
+
};
|
|
608
|
+
const allFns = /\bON\s+ALL\s+(FUNCTIONS|ROUTINES)\s+IN\s+SCHEMA\s+/i.exec(head);
|
|
609
|
+
if (allFns) {
|
|
610
|
+
const schemas = new Set(readNameList(head, allFns.index + allFns[0].length).map((s) => s.name.toLowerCase()));
|
|
611
|
+
for (const f of functions.values()) if (schemas.has(f.schema)) applyFn(f);
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
const onFn = /\bON\s+(FUNCTION|ROUTINE|PROCEDURE)\s+/i.exec(head);
|
|
615
|
+
if (onFn) {
|
|
616
|
+
for (const ref of readFunctionList(head, onFn.index + onFn[0].length)) {
|
|
617
|
+
for (const k of fnKeysFor(ref)) {
|
|
618
|
+
const f = functions.get(k);
|
|
619
|
+
if (f) applyFn(f);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Table privileges: GRANT/REVOKE <privs> ON [TABLE] a, b | ON ALL TABLES IN SCHEMA s, t
|
|
626
|
+
if (/\bON\s+(?:ALL\s+)?(SEQUENCES?|TYPE|DOMAIN|LANGUAGE|DATABASE|FOREIGN|LARGE|TABLESPACE|PARAMETER)\b/i.test(head)) continue;
|
|
627
|
+
// A REVOKE of a column list doesn't remove a table-level grant; a GRANT of one does give access.
|
|
628
|
+
const effective = isRevoke ? privs.table : new Set([...privs.table, ...privs.column]);
|
|
629
|
+
if (effective.size === 0) continue;
|
|
630
|
+
const applyTable = (t) => {
|
|
631
|
+
for (const role of API_ROLES) {
|
|
632
|
+
if (isRevoke ? !roles[role] : !roles[role] && !roles.public) continue;
|
|
633
|
+
for (const p of effective) isRevoke ? t.privs[role].delete(p) : t.privs[role].add(p);
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
const allTables = /\bON\s+ALL\s+TABLES\s+IN\s+SCHEMA\s+/i.exec(head);
|
|
637
|
+
if (allTables) {
|
|
638
|
+
const schemas = new Set(readNameList(head, allTables.index + allTables[0].length).map((s) => s.name.toLowerCase()));
|
|
639
|
+
for (const t of tables.values()) if (schemas.has(t.schema)) applyTable(t);
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
const onTable = /\bON\s+(?:TABLE\s+)?/i.exec(head);
|
|
643
|
+
if (onTable) {
|
|
644
|
+
for (const n of readNameList(head, onTable.index + onTable[0].length)) {
|
|
645
|
+
const t = tables.get(tkey(n));
|
|
646
|
+
if (t) applyTable(t);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
return { tables, functions, triggers, schemaUsage, exposedSchemas, defaults, coverage };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// Splits what follows a function's argument list into the header (RETURNS,
|
|
656
|
+
// LANGUAGE, SECURITY ...), the body, and the trailer (attributes may follow
|
|
657
|
+
// the body too). Handles $tag$ bodies, 'single-quoted' bodies, and SQL-standard
|
|
658
|
+
// bodies (RETURN ... / BEGIN ATOMIC ... END) that have no quotes at all.
|
|
659
|
+
function splitFunctionBody(after) {
|
|
660
|
+
const m = /\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$|\bAS\s+(?=[Ee]?')/i.exec(after);
|
|
661
|
+
if (!m) return { header: after, body: after, trailer: '' };
|
|
662
|
+
if (m[0].startsWith('$')) {
|
|
663
|
+
const tag = m[0];
|
|
664
|
+
const bStart = m.index + tag.length;
|
|
665
|
+
const bEnd = after.indexOf(tag, bStart);
|
|
666
|
+
return {
|
|
667
|
+
header: after.slice(0, m.index),
|
|
668
|
+
body: after.slice(bStart, bEnd === -1 ? after.length : bEnd),
|
|
669
|
+
trailer: bEnd === -1 ? '' : after.slice(bEnd + tag.length),
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
const q = after.indexOf("'", m.index + m[0].length);
|
|
673
|
+
const end = quotedEnd(after, q);
|
|
674
|
+
return {
|
|
675
|
+
header: after.slice(0, m.index),
|
|
676
|
+
body: after.slice(q + 1, end - 1).replace(/''/g, "'"),
|
|
677
|
+
trailer: after.slice(end),
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// Parses the tail of CREATE/ALTER POLICY after the table name.
|
|
682
|
+
function parsePolicyClauses(rest) {
|
|
683
|
+
// AS / FOR / TO all come before USING and WITH CHECK, so only look there:
|
|
684
|
+
// the word "to" inside a USING expression must not be read as a role list.
|
|
685
|
+
const exprAt = rest.search(/\bUSING\s*\(|\bWITH\s+CHECK\s*\(/i);
|
|
686
|
+
const pre = exprAt === -1 ? rest : rest.slice(0, exprAt);
|
|
687
|
+
const permissive = !/\bAS\s+RESTRICTIVE\b/i.test(pre);
|
|
688
|
+
const cmd = (/\bFOR\s+(ALL|SELECT|INSERT|UPDATE|DELETE)\b/i.exec(pre)?.[1] ?? 'ALL').toUpperCase();
|
|
689
|
+
const to = /\bTO\s+([\s\S]*)$/i.exec(pre);
|
|
690
|
+
const roles = parsePolicyRoles(to ? to[1] : null);
|
|
691
|
+
let using = null;
|
|
692
|
+
let check = null;
|
|
693
|
+
const u = /\bUSING\s*(?=\()/i.exec(rest);
|
|
694
|
+
if (u) using = readParenGroup(rest, u.index + u[0].length)?.raw.trim() ?? null;
|
|
695
|
+
const c = /\bWITH\s+CHECK\s*(?=\()/i.exec(rest);
|
|
696
|
+
if (c) check = readParenGroup(rest, c.index + c[0].length)?.raw.trim() ?? null;
|
|
697
|
+
return { permissive, cmd, roles, hasTo: Boolean(to), using, check };
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function usage(model, schema, role) {
|
|
701
|
+
const u = model.schemaUsage.get(schema) ?? { public: true, anon: true, authenticated: true };
|
|
702
|
+
return u.public || u[role];
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** A table is reachable through the Data API when its schema is exposed and usable, and the role holds a privilege. */
|
|
706
|
+
export function tableExposure(model, t) {
|
|
707
|
+
const exposed = model.exposedSchemas.includes(t.schema);
|
|
708
|
+
return {
|
|
709
|
+
exposed,
|
|
710
|
+
anon: exposed && t.privs.anon.size > 0 && usage(model, t.schema, 'anon'),
|
|
711
|
+
authenticated: exposed && t.privs.authenticated.size > 0 && usage(model, t.schema, 'authenticated'),
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
export function functionReach(model, f) {
|
|
716
|
+
const anonUsage = usage(model, f.schema, 'anon');
|
|
717
|
+
const authUsage = usage(model, f.schema, 'authenticated');
|
|
718
|
+
return {
|
|
719
|
+
public: f.publicExec && anonUsage,
|
|
720
|
+
anon: (f.publicExec || f.anonExec) && anonUsage,
|
|
721
|
+
authenticated: (f.publicExec || f.authExec) && authUsage,
|
|
722
|
+
};
|
|
723
|
+
}
|