greenlitlab 0.6.0 → 0.6.1
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/CHANGELOG.md +13 -0
- package/README.md +4 -2
- package/package.json +1 -1
- package/server.json +2 -2
- package/src/scan-files.mjs +200 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.1
|
|
4
|
+
|
|
5
|
+
- **New check: a read rule that hands out contact details** (`scan:open-profile:<table>`). A Row Level Security policy `for select` (or `for all`) whose condition is `true` (or `1=1`, `(select true)`, `true or …`) on a table whose columns include an email, phone, birth date, home address or ID number is now its own finding: **high** when anyone can read people's details (no role, `public` or `anon`), **medium** when only signed-in users pass (`to authenticated`, or a condition that only asks `auth.uid() is not null`), since anyone can sign up. A read rule covers every column, so a profiles table meant to show a name and an avatar hands out the email next to it. From Priberry's study of public Lovable apps: in 25 of the 32 apps that exposed contact details, the open table was a profiles or users table with a rule like this.
|
|
6
|
+
- **Places, listings and organisations are asked about, not blocked (medium).** When the table's last word is a place, listing or organisation (`stores`, `restaurants`, `venues`, `locations`, `events`, `listings`, `properties`, `jobs`, `vendors`, `clinics`, `hotels`, `offices`, `schools`, `organizations` and the like, singular too), or every contact column is a business's own (`support_`, `business_`, `venue_`, `store_`, `office_`, `company_`, `agent_`, `shop_`, `public_` or `…_public`), the prompt asks whether it is meant to be public: keep it and mark it reviewed if these are a business's details, lock it to the owner if they are people's. `event_attendees`, `company_employees`, `waitlist`, `leads`, `bookings` and `posts.author_email` stay high.
|
|
7
|
+
- **Who can really read is worked out.** A restrictive select (or all) policy with a real condition keeps out the roles it covers (one that only asks whether someone is signed in keeps out anon). `revoke select` (or `all`) on the table from `anon` or `authenticated` removes that role, and a column grant after it (`grant select (id, username) on t to anon`) opens only those columns: the finding names only the contact columns that can be read, and none means no finding. A revoke from `PUBLIC` alone doesn't count, since Supabase grants to `anon` and `authenticated` by name.
|
|
8
|
+
- Columns are read from `create table` and from later `alter table … add column`, `drop column` and `rename column` (and follow the table through `alter table … rename to`, policies included), by the column's own name split into words (`contact_email`, `phoneNumber`, `DateOfBirth`, `contact_number`, `emergency_contact`, `pan_number`, `upi_id`, `license_number`, `mail`). Flags about a detail (`email_verified boolean`, `phone_confirmed_at`, `email_hash`) and links such as `address_id uuid` don't count (`notification_…` and `provider_…` names do when they end in email, phone or address: `notification_email`); nor do a name, username, avatar or city alone.
|
|
9
|
+
- One finding per table, the widest rule winning. Such a table is no longer also listed in the `scan:public-read:*` question. A `for all` rule still gets its `scan:policy-true:<table>:all` finding too, for the writes.
|
|
10
|
+
- Not flagged: a table with Row Level Security off (that is `scan:no-rls`), a restrictive policy on its own, one for `service_role` or a custom role only, a dropped policy or table, and a select policy with no `using` (Postgres lets no row through one on its own). Not seen: SQL inside a `DO` block or built for `EXECUTE` (as for the always-true policy checks; the README says so).
|
|
11
|
+
- The finding lists the columns (`columns`) and its fix prompt says: limit reads to the row's owner (`auth.uid() = id`), or keep the public fields in their own table or a `security_invoker` view and lock the base table.
|
|
12
|
+
- Always-true policy checks also read `(select true)` as true.
|
|
13
|
+
- A table renamed with `alter table … rename to` keeps its policies under the new name.
|
|
14
|
+
- `contactColumn(name, type)` is exported from `src/scan-files.mjs`.
|
|
15
|
+
|
|
3
16
|
## 0.6.0
|
|
4
17
|
|
|
5
18
|
- **The project scan also runs over files held in memory.** `scanFiles(files, opts)` takes a `Map` of path to content and returns the same result as `codeScan(folder)`, with no disk, git or network, so it can run where there is no filesystem. It lives in `src/scan-files.mjs`, the package's main entry, which imports nothing but `node:path` and `node:crypto`. `codeScan` (in `src/scan.mjs`) now reads the folder into that map (`readFolder`) and calls it, so both give the same answer; a parity test runs every scan fixture both ways.
|
package/README.md
CHANGED
|
@@ -45,7 +45,7 @@ The owner-only checks ask for a row count (Supabase), one file or document name
|
|
|
45
45
|
| No DMARC record or a broken SPF record on your own domain | everywhere, custom domains only |
|
|
46
46
|
| Personal columns (email, phone, password…) in tables strangers can read; backend functions listed for review | your own app: `--mine` |
|
|
47
47
|
| Rules that are too loose, tables strangers can change: Supabase's Security Advisor in plain words | `advisor`, with your advisor results |
|
|
48
|
-
| Always-true policies, tables without Row Level Security, unverified payment webhooks, secrets behind a public prefix | `scan`, on your project's files |
|
|
48
|
+
| Always-true policies (and read rules that hand out emails, phones or addresses), tables without Row Level Security, unverified payment webhooks, secrets behind a public prefix | `scan`, on your project's files |
|
|
49
49
|
| Backups, spending limits, a separate test database, outage alerts | `questions`: only you know, never graded |
|
|
50
50
|
|
|
51
51
|
Only what Greenlit confirmed moves the grade. What it couldn't see is said out loud, and what only you know is asked. Greenlit never signs in, never reads your users' data and never writes to your database.
|
|
@@ -67,6 +67,8 @@ npx greenlitlab advisor results.json # Supabase's Security Advisor, in plain wo
|
|
|
67
67
|
|
|
68
68
|
With `--fail-on <level>`, `scan` exits with 1 when it finds anything at that level or above, and with 3 when it couldn't check everything (a file that matters couldn't be read, or too many files). A 3 is never a pass. Otherwise it exits with 0.
|
|
69
69
|
|
|
70
|
+
`scan` reads migrations statement by statement, in order. SQL run inside a `DO $$ … $$` block or built for `EXECUTE` isn't read, so a policy created, dropped or changed that way doesn't count (for the always-true policy checks and the read rules that hand out contact columns alike). Rules changed in the Supabase dashboard never show up in files: check the live app with `--mine`.
|
|
71
|
+
|
|
70
72
|
The last result for each app is kept in `~/.greenlit/sites/` (grade, finding ids and titles only, never keys) so the next run can show what changed.
|
|
71
73
|
|
|
72
74
|
## In Claude, Cursor, VS Code and other agents
|
|
@@ -84,7 +86,7 @@ Then ask your agent to check the app it just deployed and apply the fixes. The `
|
|
|
84
86
|
Greenlit comes from [Priberry](https://priberry.com), the crash-test lab for AI agents. Priberry makes six free, open-source tools:
|
|
85
87
|
|
|
86
88
|
- **[Launch Blockers](https://github.com/priberry-data/launch-blockers)**: the leaks AI-built apps ship, checked in your code. `npx launch-blockers check`
|
|
87
|
-
- **[Rolelock](https://github.com/priberry-data/rolelock)**: can your users raise their own role? Finds two holes in Supabase apps: signed-in users who can raise their own role, and edge functions that use the secret key with an id from the request. `npx rolelock@0.1.
|
|
89
|
+
- **[Rolelock](https://github.com/priberry-data/rolelock)**: can your users raise their own role? Finds two holes in Supabase apps: signed-in users who can raise their own role, and edge functions that use the secret key with an id from the request. `npx rolelock@0.1.1 ./my-app`
|
|
88
90
|
- **Greenlit**: what a stranger can see in your live app. `npx greenlitlab yourapp.com`
|
|
89
91
|
- **[Crumple](https://github.com/priberry-data/crumplelab)**: a crash-test lab for AI coding agents. `npx crumplelab attack`
|
|
90
92
|
- **[Tare](https://github.com/priberry-data/tarelab)**: where your coding agent's tokens go. `npx tarelab`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "greenlitlab",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Is your AI-built app safe to launch? A grade from A to F for apps built with Lovable, Bolt, v0, Replit or Emergent, with a fix prompt for every problem. Checks leaks, open data and launch basics.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/scan-files.mjs",
|
package/server.json
CHANGED
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
"description": "Grade apps built with Lovable, Bolt, v0 or Replit A to F, with a fix prompt for every problem.",
|
|
6
6
|
"websiteUrl": "https://greenlit.priberry.com",
|
|
7
7
|
"repository": { "url": "https://github.com/priberry-data/greenlitlab", "source": "github" },
|
|
8
|
-
"version": "0.6.
|
|
8
|
+
"version": "0.6.1",
|
|
9
9
|
"packages": [
|
|
10
10
|
{
|
|
11
11
|
"registryType": "npm",
|
|
12
12
|
"identifier": "greenlitlab",
|
|
13
|
-
"version": "0.6.
|
|
13
|
+
"version": "0.6.1",
|
|
14
14
|
"transport": { "type": "stdio" },
|
|
15
15
|
"packageArguments": [{ "type": "positional", "value": "mcp" }]
|
|
16
16
|
}
|
package/src/scan-files.mjs
CHANGED
|
@@ -100,6 +100,7 @@ const SQL = {
|
|
|
100
100
|
createTable: new RegExp(String.raw`^\s*create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?${IDENT}`, "i"),
|
|
101
101
|
alterRls: new RegExp(String.raw`^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+(enable|disable)\s+row\s+level\s+security`, "i"),
|
|
102
102
|
rename: new RegExp(String.raw`^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+rename\s+to\s+(${NAME})`, "i"),
|
|
103
|
+
alterTable: new RegExp(String.raw`^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+`, "i"),
|
|
103
104
|
identAtStart: new RegExp(`^${IDENT}`),
|
|
104
105
|
literalRls: new RegExp(String.raw`'\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+enable\s+row\s+level\s+security\s*;?\s*'`, "gi"),
|
|
105
106
|
createPolicy: new RegExp(String.raw`^\s*create\s+policy\s+(${NAME}|"[^"]*")\s+on\s+${IDENT}`, "i"),
|
|
@@ -108,6 +109,7 @@ const SQL = {
|
|
|
108
109
|
dropPolicy: new RegExp(String.raw`^\s*drop\s+policy\s+(?:if\s+exists\s+)?(${NAME}|"[^"]*")\s+on\s+${IDENT}`, "i"),
|
|
109
110
|
createView: new RegExp(String.raw`^\s*create\s+(?:or\s+replace\s+)?(?:materialized\s+)?view\s+(?:if\s+not\s+exists\s+)?${IDENT}`, "i"),
|
|
110
111
|
alterView: new RegExp(String.raw`^\s*alter\s+view\s+(?:if\s+exists\s+)?${IDENT}\s+set\s*\(([^)]*)\)`, "i"),
|
|
112
|
+
grantRevoke: new RegExp(String.raw`^\s*(grant|revoke)\s+(?:grant\s+option\s+for\s+)?([\s\S]+?)\s+on\s+(?:all\s+tables\s+in\s+schema\s+(${NAME})|(?:table\s+)?${IDENT})\s+(?:to|from)\s+([\w\s,"]+)`, "i"),
|
|
111
113
|
revokeTable: new RegExp(String.raw`^\s*revoke\s+[\w\s,]*?\bon\s+(?:table\s+)?${IDENT}\s+from\s+([\w\s,]+)`, "i"),
|
|
112
114
|
revokeHead: /^\s*revoke\s+(?:all|execute)\b/i,
|
|
113
115
|
onFunction: /\bon\s+function\s+/gi,
|
|
@@ -132,7 +134,67 @@ function revokeFunction(s) {
|
|
|
132
134
|
}
|
|
133
135
|
// A column name that says the table holds something about a person.
|
|
134
136
|
const PERSONAL_COLUMN = /\b(e_?mail|phone|mobile|password|passwd|address|street|postcode|zip_?code|birth|dob|ssn|national_id|passport|full_name|first_name|last_name|ip_address|salary|iban|card_number|medical|diagnosis)\b/i;
|
|
135
|
-
|
|
137
|
+
// A column that holds a way to reach or identify one person: email, phone, birth date, home address, an ID number.
|
|
138
|
+
// Judged by the column's own name split into words ("userEmail", "phone_number", "DateOfBirth"), so a table name or a
|
|
139
|
+
// default value never counts. A name, username, avatar or city alone doesn't: apps often show those on purpose.
|
|
140
|
+
// Flags about a contact detail (email_verified boolean, phone_confirmed_at, email_hash) aren't the detail. A few words
|
|
141
|
+
// (notification, provider) are flags only when the name doesn't end in the detail: notification_email is an email.
|
|
142
|
+
const CONTACT_WORD = /^(e_?mails?|emailaddress(es)?|phones?|phonenumbers?|telephones?|tel|cellphones?|whatsapp|msisdn|birth|birthdate|birthday|dob|dateofbirth|address(es)?|addressline\d*|street|streetaddress|postcode|postalcode|zip|zipcode|pincode|ssn|aadhaar|aadhar|passport|passportnumber|cpf|iban|upi)$/;
|
|
143
|
+
const CONTACT_PAIR = /(^|_)(e_mail|cell_phone|cell_number|mobile_(number|no|phone)|contact_(number|no|phone)|emergency_contact|whats_app|date_of_birth|post_code|postal_code|zip_code|pin_code|social_security|national_id|national_insurance|tax_id|id_number|id_card|government_id|drivers?_licen[cs]e|driving_licen[cs]e|licen[cs]e_(number|no)|pan_(number|no|card)|bank_account)(_|$)/;
|
|
144
|
+
const CONTACT_NOT = /(^|_)(verified|confirmed|confirmation|enabled|disabled|opt|optin|optout|opted|visible|visibility|hidden|show|count|sent|at|preferences?|consent|subscribed|template|hash|hashed|domain|status|frequency|bounced|valid|type|ip|wallet|mac|contract|web|url|token|file|archive)(_|$)/;
|
|
145
|
+
const CONTACT_NOT_UNLESS_LAST = /(^|_)(notifications?|notify|provider)(_|$)/;
|
|
146
|
+
const columnWords = (n) => String(n).replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_|_$/g, "").toLowerCase();
|
|
147
|
+
export function contactColumn(name, type = "") {
|
|
148
|
+
if (/^bool/i.test(type)) return false;
|
|
149
|
+
const w = columnWords(name);
|
|
150
|
+
if (!w || CONTACT_NOT.test(w)) return false;
|
|
151
|
+
if (CONTACT_NOT_UNLESS_LAST.test(w) && !/(^|_)(e_?mail|phone|address)$/.test(w)) return false;
|
|
152
|
+
if (/(^|_)id$/.test(w) && !CONTACT_PAIR.test(w) && /^(uuid|int[248]?|integer|bigint|smallint|serial|bigserial)$/i.test(type)) return false; // address_id: a link to a row elsewhere
|
|
153
|
+
return w === "mail" || w === "pan" || /(^|_)mobile$/.test(w) || CONTACT_PAIR.test(w) || w.split("_").some((t) => CONTACT_WORD.test(t));
|
|
154
|
+
}
|
|
155
|
+
// A business's own contact detail, public on purpose: support_email, venue_address, agent_phone, public_email.
|
|
156
|
+
const BUSINESS_COLUMN = (name) => /^(support|business|venue|store|office|company|agent|shop|public)_|_public$/.test(columnWords(name));
|
|
157
|
+
// A table of places, listings or organisations: its address and phone are usually there to be shown. Judged by the
|
|
158
|
+
// table name's last word, so event_attendees and company_employees still hold people.
|
|
159
|
+
const LISTING_TABLE = (name) => /^(stores?|shops?|restaurants?|cafes?|venues?|locations?|places?|business(es)?|compan(y|ies)|organi[sz]ations?|events?|listings?|propert(y|ies)|jobs?|vendors?|suppliers?|clinics?|hospitals?|hotels?|branch(es)?|offices?|schools?|gyms?|salons?)$/.test(columnWords(name).split("_").pop());
|
|
160
|
+
// Column names and types from a CREATE TABLE body ("id uuid, "Email" text not null, constraint …"), or from the
|
|
161
|
+
// actions of an ALTER TABLE (add column, drop column, rename column).
|
|
162
|
+
const COLUMN_SKIP = /^(constraint|primary|unique|foreign|check|exclude|like)$/i;
|
|
163
|
+
function splitTop(body) {
|
|
164
|
+
const parts = [];
|
|
165
|
+
let depth = 0;
|
|
166
|
+
let part = "";
|
|
167
|
+
for (let j = 0; j < body.length; j++) {
|
|
168
|
+
const c = body[j];
|
|
169
|
+
if (c === '"') {
|
|
170
|
+
const end = body.indexOf('"', j + 1);
|
|
171
|
+
const stop = end < 0 ? body.length : end;
|
|
172
|
+
part += body.slice(j, stop + 1);
|
|
173
|
+
j = stop;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
if (c === "(") depth++;
|
|
177
|
+
else if (c === ")") depth--;
|
|
178
|
+
if (c === "," && depth === 0) parts.push(part), (part = "");
|
|
179
|
+
else part += c;
|
|
180
|
+
}
|
|
181
|
+
parts.push(part);
|
|
182
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
183
|
+
}
|
|
184
|
+
const COLUMN_DEF = new RegExp(String.raw`^("(?:[^"]|"")+"|\w+)\s+("(?:[^"]|"")+"|\w+)`);
|
|
185
|
+
function tableColumns(stmt, from) {
|
|
186
|
+
const open = stmt.indexOf("(", from);
|
|
187
|
+
if (open < 0 || /^\s*(as|partition|of)\b/i.test(stmt.slice(from, open))) return [];
|
|
188
|
+
const body = parens(stmt, open);
|
|
189
|
+
if (body == null) return [];
|
|
190
|
+
const cols = [];
|
|
191
|
+
for (const p of splitTop(body)) {
|
|
192
|
+
const m = p.match(COLUMN_DEF);
|
|
193
|
+
if (m && !COLUMN_SKIP.test(m[1])) cols.push({ name: ident(m[1]), type: m[2].replace(/"/g, "").toLowerCase() });
|
|
194
|
+
}
|
|
195
|
+
return cols;
|
|
196
|
+
}
|
|
197
|
+
const SENSITIVE_BUCKET =/(^|[-_])(ids?|identity|identities|kyc|verif\w*|documents?|docs|passports?|licen[cs]es?|selfies?|private|secure|medical|health|invoices?|receipts?|contracts?|statements?|tax|payslips?|resumes?|cvs?|uploads?|attachments?|records?|backups?)([-_]|$)/i;
|
|
136
198
|
|
|
137
199
|
// Comments blanked out, keeping every character's position so line numbers stay right. With `strings`,
|
|
138
200
|
// text inside single quotes is blanked too: it is data or SQL run later, not a statement in this file.
|
|
@@ -228,7 +290,12 @@ const unwrapParens = (p) => {
|
|
|
228
290
|
return s;
|
|
229
291
|
};
|
|
230
292
|
// "true", "1=1", "true or …": a condition that lets everyone through.
|
|
231
|
-
|
|
293
|
+
// "(select true)" too: wrapping a condition in a select (as Supabase advises for auth.uid()) doesn't change it.
|
|
294
|
+
const ALWAYS = (d) => {
|
|
295
|
+
const u = unwrapParens(d);
|
|
296
|
+
const t = /^select\s+/.test(u) ? unwrapParens(u.replace(/^select\s+/, "")) : u;
|
|
297
|
+
return /^(true|'t'|'true'|1\s*=\s*1|true::bool(ean)?|not\s+false)$/.test(t);
|
|
298
|
+
};
|
|
232
299
|
// A condition that only asks "is anyone signed in?": every signed-in user passes.
|
|
233
300
|
const ANY_SIGNED_IN = (d) => /^(\(?\s*(select\s+)?auth\.uid\s*\(\s*\)\s*\)?\s+is\s+not\s+null|\(?\s*(select\s+)?auth\.role\s*\(\s*\)\s*\)?\s*=\s*'authenticated'|\(?\s*(select\s+)?auth\.jwt\s*\(\s*\)\s*\)?\s+is\s+not\s+null|auth\.uid\s*\(\s*\)\s*<>\s*null)$/.test(unwrapParens(d));
|
|
234
301
|
|
|
@@ -457,7 +524,14 @@ export function scanFiles(input, opts = {}) {
|
|
|
457
524
|
const dynamic = new Set(); // tables created before an EXECUTE … enable row level security we can't read
|
|
458
525
|
const publicRead = { everyone: [], "every signed-in user": [] };
|
|
459
526
|
const publicReadSeen = { everyone: new Set(), "every signed-in user": new Set() };
|
|
460
|
-
const policies = new Map(); // "schema.table|name" -> { action, roles, using, check, where, table, schema }
|
|
527
|
+
const policies = new Map(); // "schema.table|name" -> { action, roles, using, check, where, table, schema, restrictive }
|
|
528
|
+
// What the API roles may select from each public table: Supabase grants every table to anon and authenticated, so a
|
|
529
|
+
// table is readable until a revoke says otherwise; a column grant after a revoke opens only those columns.
|
|
530
|
+
const privs = new Map(); // table -> { anon: { table, cols }, authenticated: { table, cols } }
|
|
531
|
+
const privOf = (t) => {
|
|
532
|
+
if (!privs.has(t)) privs.set(t, { anon: { table: true, cols: new Set() }, authenticated: { table: true, cols: new Set() } });
|
|
533
|
+
return privs.get(t);
|
|
534
|
+
};
|
|
461
535
|
const buckets = new Map(); // bucket id -> { public, where }
|
|
462
536
|
const views = new Map(); // view -> { where, invoker, auth, revoked }
|
|
463
537
|
const definers = new Map(); // function -> { where, dynamicSql, revoked }
|
|
@@ -660,7 +734,8 @@ export function scanFiles(input, opts = {}) {
|
|
|
660
734
|
const table = ident(m[2]);
|
|
661
735
|
if (!created.has(table) || created.get(table).dropped) {
|
|
662
736
|
protectedTables.delete(table);
|
|
663
|
-
|
|
737
|
+
privs.delete(table);
|
|
738
|
+
created.set(table, { where: at(i), people: PERSONAL_COLUMN.test(s), columns: tableColumns(s, m[0].length) });
|
|
664
739
|
}
|
|
665
740
|
continue;
|
|
666
741
|
}
|
|
@@ -674,6 +749,34 @@ export function scanFiles(input, opts = {}) {
|
|
|
674
749
|
const [from, to] = [ident(m[2]), ident(m[3])];
|
|
675
750
|
if (created.has(from)) created.set(to, created.get(from)), created.delete(from);
|
|
676
751
|
if (protectedTables.delete(from)) protectedTables.add(to);
|
|
752
|
+
if (privs.has(from)) privs.set(to, privs.get(from)), privs.delete(from);
|
|
753
|
+
// Policies stay on the table under its new name.
|
|
754
|
+
const schema = schemaOf(m[1]);
|
|
755
|
+
for (const [k, pol] of [...policies]) {
|
|
756
|
+
if (pol.schema !== schema || pol.table !== from) continue;
|
|
757
|
+
policies.delete(k);
|
|
758
|
+
policies.set(`${schema}.${to}|${k.slice(k.indexOf("|") + 1)}`, { ...pol, table: to });
|
|
759
|
+
}
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
// Columns added, dropped or renamed later: what a read policy hands out is the table's columns at the end.
|
|
763
|
+
if ((m = s.match(SQL.alterTable))) {
|
|
764
|
+
const info = schemaOf(m[1]) === "public" ? created.get(ident(m[2])) : null;
|
|
765
|
+
if (info) {
|
|
766
|
+
for (const act of splitTop(s.slice(m[0].length))) {
|
|
767
|
+
let a;
|
|
768
|
+
if ((a = act.match(/^add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?("(?:[^"]|"")+"|\w+)\s+("(?:[^"]|"")+"|\w+)/i)) && (/^add\s+column\b/i.test(act) || !COLUMN_SKIP.test(a[1]))) {
|
|
769
|
+
const name = ident(a[1]);
|
|
770
|
+
info.columns = [...info.columns.filter((c) => c.name !== name), { name, type: a[2].replace(/"/g, "").toLowerCase() }];
|
|
771
|
+
} else if ((a = act.match(/^drop\s+(?:column\s+)?(?:if\s+exists\s+)?("(?:[^"]|"")+"|\w+)/i)) && (/^drop\s+column\b/i.test(act) || !/^constraint$/i.test(a[1]))) {
|
|
772
|
+
const name = ident(a[1]);
|
|
773
|
+
info.columns = info.columns.filter((c) => c.name !== name);
|
|
774
|
+
} else if ((a = act.match(/^rename\s+(?:column\s+)?("(?:[^"]|"")+"|\w+)\s+to\s+("(?:[^"]|"")+"|\w+)/i)) && !/^constraint$/i.test(a[1])) {
|
|
775
|
+
const [from, to] = [ident(a[1]), ident(a[2])];
|
|
776
|
+
info.columns = info.columns.map((c) => (c.name === from ? { ...c, name: to } : c));
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
677
780
|
continue;
|
|
678
781
|
}
|
|
679
782
|
if (/^\s*drop\s+table\b/i.test(s)) {
|
|
@@ -685,6 +788,7 @@ export function scanFiles(input, opts = {}) {
|
|
|
685
788
|
if (schema === "public") {
|
|
686
789
|
created.delete(table);
|
|
687
790
|
protectedTables.delete(table);
|
|
791
|
+
privs.delete(table);
|
|
688
792
|
}
|
|
689
793
|
for (const k of [...policies.keys()]) if (k.startsWith(`${schema}.${table}|`)) policies.delete(k);
|
|
690
794
|
}
|
|
@@ -717,10 +821,11 @@ export function scanFiles(input, opts = {}) {
|
|
|
717
821
|
// Policies.
|
|
718
822
|
if ((m = s.match(SQL.createPolicy))) {
|
|
719
823
|
const rest = o.slice(m[0].length);
|
|
720
|
-
|
|
824
|
+
// A restrictive policy narrows access and opens nothing; it is kept only to narrow what a permissive one opens.
|
|
825
|
+
const restrictive = /\bas\s+restrictive\b/i.test(rest);
|
|
721
826
|
const roles = (rest.match(/\bto\s+([\w\s,"]+?)(?=\s+(?:using|with)\b|\s*$)/i) || [, "public"])[1].toLowerCase();
|
|
722
827
|
const action = (rest.match(/\bfor\s+(select|insert|update|delete|all)\b/i) || [, "all"])[1].toLowerCase();
|
|
723
|
-
policies.set(pkey(m[2], m[3], m[1]), { schema: schemaOf(m[2]), table: ident(m[3]), roles, action, using: clause(rest, "using"), check: clause(rest, "with\\s+check"), where: at(i) });
|
|
828
|
+
policies.set(pkey(m[2], m[3], m[1]), { schema: schemaOf(m[2]), table: ident(m[3]), roles, action, using: clause(rest, "using"), check: clause(rest, "with\\s+check"), where: at(i), restrictive });
|
|
724
829
|
continue;
|
|
725
830
|
}
|
|
726
831
|
if ((m = s.match(SQL.alterPolicy))) {
|
|
@@ -772,6 +877,25 @@ export function scanFiles(input, opts = {}) {
|
|
|
772
877
|
if (v && INVOKER.test(m[3])) v.invoker = true;
|
|
773
878
|
continue;
|
|
774
879
|
}
|
|
880
|
+
// Table and column privileges for anon and authenticated. PUBLIC is left out: Supabase grants to anon and
|
|
881
|
+
// authenticated by name, so a revoke from PUBLIC alone doesn't stop them reading.
|
|
882
|
+
if ((m = s.match(SQL.grantRevoke))) {
|
|
883
|
+
const grant = m[1].toLowerCase() === "grant";
|
|
884
|
+
const targets = m[3] != null ? (ident(m[3]) === "public" ? [...created.keys()] : []) : schemaOf(m[4]) === "public" ? [ident(m[5])] : [];
|
|
885
|
+
const roles = m[6].split(",").map((r) => ident(r.trim().split(/\s+/)[0] || "")).filter((r) => r === "anon" || r === "authenticated");
|
|
886
|
+
for (const item of splitTop(m[2])) {
|
|
887
|
+
const pm = item.match(/^(select|all(?:\s+privileges)?)\b\s*(?:\(([\s\S]*)\))?\s*$/i);
|
|
888
|
+
if (!pm) continue;
|
|
889
|
+
const cols = pm[2] != null ? splitTop(pm[2]).map((c) => ident(c.trim())) : null;
|
|
890
|
+
for (const t of targets)
|
|
891
|
+
for (const r of roles) {
|
|
892
|
+
const pr = privOf(t)[r];
|
|
893
|
+
if (cols) for (const c of cols) grant ? pr.cols.add(c) : pr.cols.delete(c);
|
|
894
|
+
else if (grant) pr.table = true;
|
|
895
|
+
else (pr.table = false), pr.cols.clear(); // revoking the table's privilege revokes its column privileges too
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
}
|
|
775
899
|
if ((m = s.match(SQL.revokeTable))) {
|
|
776
900
|
const v = schemaOf(m[1]) === "public" ? views.get(ident(m[2])) : null;
|
|
777
901
|
if (v && /anon|public/i.test(m[3])) v.revoked = true;
|
|
@@ -828,7 +952,17 @@ export function scanFiles(input, opts = {}) {
|
|
|
828
952
|
add({ id: `scan:no-rls:${table}`, severity: maybe ? "medium" : "high", where: info.where, title: maybe ? `Greenlit couldn't see Row Level Security switched on for "${table}"` : `The table "${table}" is created without Row Level Security`, why: `No migration turns Row Level Security on for it.${maybe ? " (A statement built at run time switches it on for some tables, and Greenlit can't tell whether this is one of them.)" : ""} If the app's public key can reach the table, every row is readable. (If you turned it on in the dashboard instead, the live database may be fine: check with npx greenlitlab <your app> --mine.)`, fix: `Add: alter table public.${sqlName(table)} enable row level security; plus a policy for the owner.`, first: null, prompt: `My migrations create the table "${table}" but never enable Row Level Security on it${maybe ? " in a statement I can read" : ""}. Write a new migration that enables it and adds policies so a signed-in user reaches only their own rows (auth.uid() = the owner column; add one if needed). If the table is meant to be public to read, say so and add a read-only policy. Show me the SQL.` });
|
|
829
953
|
}
|
|
830
954
|
|
|
955
|
+
const openProfiles = new Map(); // table -> { everyone, where, contact, signedInCheck }
|
|
956
|
+
// The API roles a policy's TO list reaches (public reaches both).
|
|
957
|
+
const apiRoles = (roles) => {
|
|
958
|
+
const list = roles.split(",").map((r) => r.trim().replace(/"/g, ""));
|
|
959
|
+
const out = new Set();
|
|
960
|
+
if (list.includes("public") || list.includes("anon")) out.add("anon");
|
|
961
|
+
if (list.includes("public") || list.includes("authenticated")) out.add("authenticated");
|
|
962
|
+
return out;
|
|
963
|
+
};
|
|
831
964
|
for (const p of policies.values()) {
|
|
965
|
+
if (p.restrictive) continue; // narrows access, opens nothing
|
|
832
966
|
if (p.schema !== "public" && p.schema !== "storage") continue;
|
|
833
967
|
// The service role skips every rule anyway; a policy for it alone opens nothing.
|
|
834
968
|
if (/service_role/.test(p.roles) && !/anon|authenticated|public/.test(p.roles)) continue;
|
|
@@ -841,6 +975,41 @@ export function scanFiles(input, opts = {}) {
|
|
|
841
975
|
const table = shown(p.schema === "public" ? p.table : `${p.schema}.${p.table}`);
|
|
842
976
|
if (meta)
|
|
843
977
|
add({ id: `scan:policy-user-metadata:${table}`, severity: "high", where: p.where, title: `A rule on "${table}" trusts user_metadata, which users can change themselves`, why: "user_metadata is written by the user (supabase.auth.updateUser), so a rule that checks it can be passed by anyone who edits their own metadata. Supabase's own Security Advisor flags this as an error (lint 0015).", fix: "Check app_metadata (set only by the server) or a column in your own table instead.", first: null, prompt: `A Row Level Security policy on "${table}" checks user_metadata, which every user can change for themselves. Rewrite it to use app_metadata (which only the server can set) or a roles column in my own table that users can't write, as a new migration. Show me the SQL and how roles get assigned.` });
|
|
978
|
+
// A read rule covers every column. On a table with contact columns, a rule that lets anyone (or any account) read
|
|
979
|
+
// every row hands out those columns too: one finding per table, instead of a line in the question below.
|
|
980
|
+
if (p.schema === "public" && (p.action === "select" || p.action === "all") && p.using != null && /\b(anon|public|authenticated)\b/.test(p.roles) && protectedTables.has(p.table)) {
|
|
981
|
+
const reads = disjuncts(p.using);
|
|
982
|
+
const readAll = reads.some(ALWAYS);
|
|
983
|
+
const readSignedIn = !readAll && reads.some(ANY_SIGNED_IN);
|
|
984
|
+
const contactCols = (created.get(p.table)?.columns ?? []).filter((c) => contactColumn(c.name, c.type)).map((c) => c.name);
|
|
985
|
+
if ((readAll || readSignedIn) && contactCols.length) {
|
|
986
|
+
const readers = apiRoles(p.roles);
|
|
987
|
+
if (readSignedIn) readers.delete("anon"); // anon has no auth.uid()
|
|
988
|
+
// A restrictive select (or all) policy with a real condition narrows who gets through: one that only asks
|
|
989
|
+
// whether someone is signed in keeps out anon, any other keeps out every role it covers.
|
|
990
|
+
for (const r of policies.values()) {
|
|
991
|
+
if (!r.restrictive || r.schema !== p.schema || r.table !== p.table || (r.action !== "select" && r.action !== "all") || r.using == null) continue;
|
|
992
|
+
const rd = disjuncts(r.using);
|
|
993
|
+
if (rd.some(ALWAYS)) continue;
|
|
994
|
+
for (const role of apiRoles(r.roles)) if (!rd.some(ANY_SIGNED_IN) || role === "anon") readers.delete(role);
|
|
995
|
+
}
|
|
996
|
+
// Privileges: a revoked table hides every column, a column grant shows only its columns.
|
|
997
|
+
const readable = (role) => {
|
|
998
|
+
const pr = privs.get(p.table)?.[role];
|
|
999
|
+
return !pr || pr.table ? contactCols : contactCols.filter((c) => pr.cols.has(c));
|
|
1000
|
+
};
|
|
1001
|
+
const anonCols = readers.has("anon") ? readable("anon") : [];
|
|
1002
|
+
const authCols = readers.has("authenticated") ? readable("authenticated") : [];
|
|
1003
|
+
const everyone = anonCols.length > 0;
|
|
1004
|
+
const contact = everyone ? anonCols : authCols;
|
|
1005
|
+
if (contact.length) {
|
|
1006
|
+
const seen = openProfiles.get(p.table);
|
|
1007
|
+
if (!seen || (everyone && !seen.everyone)) openProfiles.set(p.table, { everyone, where: p.where, contact, signedInCheck: readSignedIn });
|
|
1008
|
+
}
|
|
1009
|
+
// Handled here, found or not: a table whose contact columns are shut off isn't "read in full" either.
|
|
1010
|
+
if (p.action === "select") continue;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
844
1013
|
if (!always && !anySignedIn) continue;
|
|
845
1014
|
const toAuthed = anySignedIn || (/authenticated/.test(p.roles) && !/anon|public/.test(p.roles));
|
|
846
1015
|
const who = toAuthed ? "every signed-in user" : "everyone";
|
|
@@ -864,8 +1033,32 @@ export function scanFiles(input, opts = {}) {
|
|
|
864
1033
|
add({ id: `scan:policy-true:${table}:${p.action}`, severity: addOnly ? "medium" : "high", where: p.where, title: `A rule lets ${who} ${p.action === "all" ? "read, change and delete" : addOnly ? "add" : p.action} rows in "${table}"`, why: `${anySignedIn ? "The policy's condition only asks whether someone is signed in, so any account passes" : 'The policy\'s condition is simply "true"'}: Row Level Security is on but checks nothing about whose row it is.${addOnly ? " That is right for a contact form, a waitlist or a log, and a problem if anything in the app trusts what is in this table." : ""}`, fix: "Compare auth.uid() with the row's owner column instead.", first: null, prompt: `In my database, a Row Level Security policy on "${table}" for ${p.action} ${anySignedIn ? "only checks that the user is signed in" : "uses the condition true"}, so ${toAuthed ? "any signed-in user" : "anyone"} passes it. ${addOnly ? `Tell me first whether "${table}" is meant to take rows from ${toAuthed ? "any signed-in user" : "strangers"} (a form, a waitlist, a log). If it is, keep it but make sure the new row can't claim to belong to someone else (set the owner column from auth.uid(), never from the request) and can't be flooded. If it isn't, rewrite` : "Rewrite"} it so a user can only ${p.action === "all" ? "reach" : p.action} their own rows (auth.uid() = the owner column; add that column if it's missing). Write this as a new migration, don't edit old ones, and show me the SQL.` });
|
|
865
1034
|
}
|
|
866
1035
|
|
|
1036
|
+
for (const [rawTable, o] of openProfiles) {
|
|
1037
|
+
const table = shown(rawTable);
|
|
1038
|
+
const cols = o.contact.map(shown);
|
|
1039
|
+
const list = cols.length > 4 ? `${cols.slice(0, 4).join(", ")} and ${cols.length - 4} more` : cols.join(", ");
|
|
1040
|
+
const who = o.everyone ? "Anyone on the internet" : "Any signed-in user";
|
|
1041
|
+
// A table of places or listings, or columns that are a business's own (support_email, venue_address), is usually
|
|
1042
|
+
// public on purpose: asked about, not blocked. People's details are blocked.
|
|
1043
|
+
const listing = LISTING_TABLE(rawTable) || o.contact.every(BUSINESS_COLUMN);
|
|
1044
|
+
const lock = `replaces that policy so a user can read only their own row (auth.uid() = id, or the table's owner column). If the app must show other users' public fields, such as a display name or avatar, keep only those columns in a public view or table and lock "${table}" to its owner. A view must be created with security_invoker = true, and then it follows "${table}"'s locked rule, so if other users' names must still show, use a separate public table with only those columns, kept in step by a trigger`;
|
|
1045
|
+
add({
|
|
1046
|
+
id: `scan:open-profile:${table}`,
|
|
1047
|
+
severity: o.everyone && !listing ? "high" : "medium",
|
|
1048
|
+
where: o.where,
|
|
1049
|
+
columns: cols,
|
|
1050
|
+
title: listing ? `${who} can read ${list} in every row of "${table}": check that's meant to be public` : `${who} can read every row of "${table}", including ${list}`,
|
|
1051
|
+
why: `A Row Level Security policy lets ${o.everyone ? "everyone, with no login," : "every signed-in user"} read all of "${table}"${o.signedInCheck ? " (its condition only asks whether someone is signed in)" : ' (its condition is simply "true")'}, and a read rule covers every column in the row: ${list}. ${listing ? "That is right for a business's public details (a shop's address and phone, a job's application email) and a leak if they belong to people." : "A profiles table meant to show a name and an avatar hands out contact details this way."}${o.everyone ? "" : " Only signed-in users pass, but anyone can sign up."}`,
|
|
1052
|
+
fix: listing ? "If these are a business's public details, keep them. If they are people's, limit reads to the row's owner (auth.uid() = id)." : "Limit reads to the row's owner (auth.uid() = id), or keep the public fields (display name, avatar) in their own table or view and lock this table to its owner.",
|
|
1053
|
+
first: null,
|
|
1054
|
+
prompt: listing
|
|
1055
|
+
? `In my database, a Row Level Security policy lets ${o.everyone ? "anyone, with no login," : "any signed-in user"} read every row of "${table}", including ${list}. Is this meant to be public? Tell me what these columns hold and change nothing yet. If they are a business's public details (a shop's address and phone, a job's application email), keep the policy and tell me so, and I'll mark this finding reviewed (with launch-blockers: a line in .launch-blockers-ignore with the reason). If they are people's personal details, write a new migration (don't edit old ones) that ${lock}. Show me the SQL.`
|
|
1056
|
+
: `In my database, a Row Level Security policy lets ${o.everyone ? "anyone, with no login," : "any signed-in user"} read every row of "${table}", and the table holds ${list}. Write a new migration (don't edit old ones) that ${lock}. Tell me which screens read these columns, and show me the SQL.`,
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
|
|
867
1060
|
// Buckets: public ones, judged by what their name says they hold.
|
|
868
|
-
const bucketPolicies = [...policies.values()].filter((p) => p.schema === "storage" && p.table === "objects" && p.action === "select");
|
|
1061
|
+
const bucketPolicies = [...policies.values()].filter((p) => !p.restrictive && p.schema === "storage" && p.table === "objects" && p.action === "select");
|
|
869
1062
|
for (const p of bucketPolicies) {
|
|
870
1063
|
const conds = [p.using].filter(Boolean).join(" ");
|
|
871
1064
|
const id = conds.match(/bucket_id\s*=\s*'([^']+)'/i)?.[1];
|