@rebasepro/rls-check 0.29.0 → 0.29.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/README.md CHANGED
@@ -188,6 +188,10 @@ npx @rebasepro/rls-check [connection-string] [options]
188
188
  addition to anon, authenticated, web_anon and rebase_user.
189
189
  A name that is not in pg_roles is an error, not a no-op.
190
190
  Repeatable or comma-separated.
191
+ --request-role <name> The role a Rebase app on this database runs requests as, in
192
+ place of rebase_user (rls.requestRole). Without it, the roles
193
+ the database recorded in rebase.schema_meta are used, then
194
+ rebase_user. Repeatable or comma-separated.
191
195
  --fail-on <severity> Exit 1 at or above this severity: info, low, medium, high,
192
196
  critical, or none to never fail. Default: high.
193
197
  --only <id> Run only these checks. Repeatable or comma-separated.
@@ -389,7 +393,7 @@ Being clear about this is the point of the tool. It is a **static audit of the c
389
393
  - **It does not execute queries as other roles.** It never connects as `anon`, never sets a JWT claim, and never tries to read a row it should not be able to read. Everything it reports is inferred from what the catalogs say, not observed.
390
394
  - **It cannot prove a policy is correct.** Deciding whether `owner_id = auth.uid()` is the right rule for your application requires knowing your application. `rls-check` can only tell you that certain *shapes* are wrong — a policy that is always true, a view that runs as its owner, a table with RLS switched off.
391
395
  - **A clean report is not a security certification.** It means these fifteen checks found nothing. It does not mean your authorization model is sound, your API layer enforces what it should, or your data is safe.
392
- - **It recognises app roles by name, and yours may not be one of them.** A check calls a table exposed only when a role an untrusted caller can arrive as holds privileges on it and `USAGE` on its schema. Out of the box that means `PUBLIC`, Supabase's `anon` and `authenticated`, PostgREST's `web_anon`, and Rebase's `rebase_user`. If your application connects as `app_user`, `api` or anything else, name it — `--role app_user` — or the checks have nothing to gate on. A scan that finds a write-holding role it cannot account for says so in a `Note` rather than printing a clean report.
396
+ - **It recognises app roles by name, and yours may not be one of them.** A check calls a table exposed only when a role an untrusted caller can arrive as holds privileges on it and `USAGE` on its schema. Out of the box that means `PUBLIC`, Supabase's `anon` and `authenticated`, PostgREST's `web_anon`, and Rebase's request role — `rebase_user`, or the role a Rebase boot recorded in `rebase.schema_meta`, or the one you name with `--request-role`. If your application connects as `app_user`, `api` or anything else, name it — `--role app_user` — or the checks have nothing to gate on. A scan that finds a write-holding role it cannot account for says so in a `Note` rather than printing a clean report.
393
397
  - **It does not model your API layer.** Whether a table is actually reachable depends on PostgREST, your server, or your gateway. Findings say "if this table is exposed over an API" when reachability depends on something outside the database — believe that qualifier.
394
398
  - **It does not see what your connection sees.** Almost every connection string handed to a tool like this belongs to a superuser or a table owner, which RLS cannot constrain. That is what lets it read the true catalog; it also means the findings describe what *other* roles get. The report says so, prominently, every time it applies.
395
399
  - **Heuristic checks produce false positives by design.** Junction-table inference and unqualified-column detection match a shape, not a proof. They are reported in a separate section for exactly that reason.
package/dist/cli.d.ts CHANGED
@@ -30,6 +30,12 @@ export interface ScanOptions {
30
30
  * `anon`, `authenticated`, `web_anon` or `rebase_user`.
31
31
  */
32
32
  roles?: string[];
33
+ /**
34
+ * The role(s) a Rebase app on this database runs requests as, when it is
35
+ * not `rebase_user`. Without it, the roles recorded in
36
+ * `rebase.schema_meta` are used, then `rebase_user`.
37
+ */
38
+ requestRoles?: string[];
33
39
  /** Run only these check ids. */
34
40
  only?: string[];
35
41
  /** Skip these check ids. */
@@ -108,6 +114,8 @@ export interface CliOptions {
108
114
  schemas: string[];
109
115
  /** Extra roles to treat as reachable by an untrusted caller. */
110
116
  roles: string[];
117
+ /** The role(s) a Rebase app runs requests as, in place of `rebase_user`. */
118
+ requestRoles: string[];
111
119
  failOn: Severity | "none";
112
120
  skip: string[];
113
121
  only: string[];
package/dist/index.es.js CHANGED
@@ -1,6 +1,30 @@
1
1
  import { readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { Client } from "pg";
4
+ //#region src/types.ts
5
+ /**
6
+ * The contract between the three layers of `rls-check`:
7
+ *
8
+ * introspect.ts — reads the catalogs into a {@link DbSnapshot}. Talks to Postgres.
9
+ * checks/*.ts — pure functions, snapshot in, {@link Finding}s out. No I/O.
10
+ * report.ts — Findings to text or JSON. No knowledge of Postgres.
11
+ *
12
+ * Checks being pure is the point: every one of them is unit-testable against a
13
+ * hand-written snapshot, so the test suite does not need a live database to
14
+ * cover the interesting cases (it has a Docker-backed suite too, for the
15
+ * introspection layer, which is the only part that can lie).
16
+ */
17
+ /** Ordered least → most severe; the CLI's `--fail-on` compares by index. */
18
+ var SEVERITIES = [
19
+ "info",
20
+ "low",
21
+ "medium",
22
+ "high",
23
+ "critical"
24
+ ];
25
+ /** The role a Rebase app runs every request as when nothing names another (`rls.requestRole`). */
26
+ var DEFAULT_REBASE_REQUEST_ROLE = "rebase_user";
27
+ //#endregion
4
28
  //#region src/checks/sql.ts
5
29
  var isIdentStart = (c) => /[A-Za-z_]/.test(c) || c.charCodeAt(0) > 127;
6
30
  var isIdentBody = (c) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) > 127;
@@ -860,7 +884,7 @@ var anonymousWriteAllowed$1 = {
860
884
  table: policy.table,
861
885
  policy: policy.name
862
886
  },
863
- detail: `Policy "${policy.name}" is a permissive ${policy.command} policy for ${listAnd(grantedTo)}, and the expression that decides ${listAnd(commands)} is a constant truth, so every row satisfies it. ${listAnd(grantedTo)} also ${grantedTo.length > 1 ? "hold" : "holds"} ${listAnd(commands)} on the table, so both the privilege check and the row check pass for a request that carries no credentials.` + (certain ? "" : ` On Rebase every request runs as ${REBASE_REQUEST_ROLE} — a signed-out one too when the API admits it (\`AUTH_REQUIRE=false\`, or \`auth.requireAuth: false\`), and every guest account from anonymous sign-in. The database cannot see that switch, so this is heuristic: with the API gate on and guests off, only signed-in users reach the policy — and they can still ${listAnd(verbs)} any row.`),
887
+ detail: `Policy "${policy.name}" is a permissive ${policy.command} policy for ${listAnd(grantedTo)}, and the expression that decides ${listAnd(commands)} is a constant truth, so every row satisfies it. ${listAnd(grantedTo)} also ${grantedTo.length > 1 ? "hold" : "holds"} ${listAnd(commands)} on the table, so both the privilege check and the row check pass for a request that carries no credentials.` + (certain ? "" : ` On Rebase every request runs as ${listAnd(requestRolesOf(snapshot))} — a signed-out one too when the API admits it (\`AUTH_REQUIRE=false\`, or \`auth.requireAuth: false\`), and every guest account from anonymous sign-in. The database cannot see that switch, so this is heuristic: with the API gate on and guests off, only signed-in users reach the policy — and they can still ${listAnd(verbs)} any row.`),
864
888
  impact: `An unauthenticated caller reaching this database over an API can ${listAnd(verbs)} rows in ${policy.schema}.${policy.table} at will — inserting records attributed to other users, or ${commands.includes("DELETE") ? "deleting the table's contents" : "modifying rows they do not own"}.`,
865
889
  fix: isRebaseManagedPolicy(snapshot, policy) ? managedPolicyFix(policy, "scope the write rule to the caller (an `ownerField`) or restrict it to `roles` — and if anonymous writes are never intended, say so there rather than by revoking the grant, which boot re-makes") : `-- Scope the write to the caller, or take the privilege away entirely:\nALTER POLICY ${qi(policy.name)} ON ${qrel(policy.schema, policy.table)}\n WITH CHECK (user_id = ${uidCall});\n-- and if anonymous writes are never intended:\n` + revokesReaching(snapshot, policy.schema, policy.table, grantedTo, commands).join("\n")
866
890
  }));
@@ -868,8 +892,12 @@ var anonymousWriteAllowed$1 = {
868
892
  return findings;
869
893
  }
870
894
  };
871
- /** The role a Rebase app runs every request as, signed-in or not. */
872
- var REBASE_REQUEST_ROLE = "rebase_user";
895
+ /**
896
+ * The role(s) a Rebase app runs every request as, signed-in or not: what the
897
+ * scan resolved (`--request-role`, the roles recorded in `rebase.schema_meta`),
898
+ * or `rebase_user` for a snapshot that carries none.
899
+ */
900
+ var requestRolesOf = (snapshot) => snapshot.requestRoles && snapshot.requestRoles.length > 0 ? snapshot.requestRoles : [DEFAULT_REBASE_REQUEST_ROLE];
873
901
  /**
874
902
  * Which unauthenticated identities a policy's TO list actually covers.
875
903
  *
@@ -887,7 +915,7 @@ var REBASE_REQUEST_ROLE = "rebase_user";
887
915
  function anonymousIdentities(snapshot, policyRoles) {
888
916
  const present = snapshot.roles.map((r) => r.name);
889
917
  const anonymous = present.filter((name) => ANONYMOUS_ROLES.includes(name.toLowerCase()) && !isPublicRole(name));
890
- const rebaseRequest = snapshot.platform === "rebase" ? present.filter((name) => sameRole(name, REBASE_REQUEST_ROLE)) : [];
918
+ const rebaseRequest = snapshot.platform === "rebase" ? present.filter((name) => requestRolesOf(snapshot).some((role) => sameRole(name, role))) : [];
891
919
  const out = /* @__PURE__ */ new Map();
892
920
  const add = (role, conditional) => {
893
921
  const key = role.toLowerCase();
@@ -1448,28 +1476,6 @@ function restrictiveGate(snapshot, policy) {
1448
1476
  return callers.every((role) => covering.some((gate) => policyAppliesTo(snapshot, gate, role))) ? covering.map((gate) => gate.name) : null;
1449
1477
  }
1450
1478
  //#endregion
1451
- //#region src/types.ts
1452
- /**
1453
- * The contract between the three layers of `rls-check`:
1454
- *
1455
- * introspect.ts — reads the catalogs into a {@link DbSnapshot}. Talks to Postgres.
1456
- * checks/*.ts — pure functions, snapshot in, {@link Finding}s out. No I/O.
1457
- * report.ts — Findings to text or JSON. No knowledge of Postgres.
1458
- *
1459
- * Checks being pure is the point: every one of them is unit-testable against a
1460
- * hand-written snapshot, so the test suite does not need a live database to
1461
- * cover the interesting cases (it has a Docker-backed suite too, for the
1462
- * introspection layer, which is the only part that can lie).
1463
- */
1464
- /** Ordered least → most severe; the CLI's `--fail-on` compares by index. */
1465
- var SEVERITIES = [
1466
- "info",
1467
- "low",
1468
- "medium",
1469
- "high",
1470
- "critical"
1471
- ];
1472
- //#endregion
1473
1479
  //#region src/checks/policy-anonymous-tautology.ts
1474
1480
  var ID$7 = "policy-anonymous-tautology";
1475
1481
  /**
@@ -3157,7 +3163,9 @@ var SCANNED_RELKINDS = [
3157
3163
  *
3158
3164
  * These are recognised *by name*, which is the one place this tool is not
3159
3165
  * framework-agnostic: it knows Supabase's pair, PostgREST's `web_anon` and
3160
- * Rebase's `rebase_user`, and nothing else. Every check gates on a grant to an
3166
+ * Rebase's request role — `rebase_user`, or the role(s) `--request-role` or
3167
+ * `rebase.schema_meta` name (see {@link resolveRequestRoles}), which
3168
+ * {@link exposedRolesFor} adds — and nothing else. Every check gates on a grant to an
3161
3169
  * exposed role, so a database served by `app_user` used to scan clean no
3162
3170
  * matter how open it was.
3163
3171
  *
@@ -3169,9 +3177,34 @@ var SCANNED_RELKINDS = [
3169
3177
  var CANDIDATE_EXPOSED_ROLES = [
3170
3178
  "anon",
3171
3179
  "authenticated",
3172
- "web_anon",
3173
- "rebase_user"
3180
+ "web_anon"
3174
3181
  ];
3182
+ /**
3183
+ * Which roles are this database's Rebase request roles: the ones named with
3184
+ * `--request-role`, else the ones a Rebase boot recorded in
3185
+ * `rebase.schema_meta` (a comma-separated `request_roles` value), else
3186
+ * `rebase_user`.
3187
+ */
3188
+ function resolveRequestRoles(explicit, recorded) {
3189
+ if (explicit && explicit.length > 0) return [...new Set(explicit)];
3190
+ const fromDatabase = (recorded ?? "").split(",").map((r) => r.trim()).filter(Boolean);
3191
+ if (fromDatabase.length > 0) return [...new Set(fromDatabase)];
3192
+ return [DEFAULT_REBASE_REQUEST_ROLE];
3193
+ }
3194
+ /**
3195
+ * The request roles a Rebase boot recorded here, or null. Two reads, because a
3196
+ * table that does not exist cannot be named in the same statement that checks
3197
+ * for it; and the value is read only when the scanning role may, so a scan as
3198
+ * an unprivileged role is not marked degraded for a table it was never meant
3199
+ * to see.
3200
+ */
3201
+ async function readRecordedRequestRoles(db, allSchemas) {
3202
+ if (!allSchemas.includes("rebase")) return null;
3203
+ const [present] = await db.query("recorded request roles", "SELECT has_table_privilege(to_regclass('rebase.schema_meta'), 'SELECT') AS readable");
3204
+ if (present?.readable !== true) return null;
3205
+ const [row] = await db.query("recorded request roles", "SELECT value FROM rebase.schema_meta WHERE key = 'request_roles'");
3206
+ return row?.value ?? null;
3207
+ }
3175
3208
  async function introspect(opts) {
3176
3209
  return (await introspectWithDiagnostics(opts)).snapshot;
3177
3210
  }
@@ -3402,7 +3435,8 @@ async function readSnapshot(client, opts, diagnostics, begin) {
3402
3435
  const allSchemas = (await db.query("schema list", "SELECT nspname FROM pg_namespace ORDER BY nspname")).map((r) => r.nspname);
3403
3436
  const schemas = selectSchemas(allSchemas, opts.schemas, diagnostics);
3404
3437
  const roles = await readRoles(db);
3405
- assertRolesExist(roles, opts.roles, diagnostics);
3438
+ assertRolesExist(roles, [...opts.roles ?? [], ...opts.requestRoles ?? []], diagnostics);
3439
+ const requestRoles = resolveRequestRoles(opts.requestRoles, await readRecordedRequestRoles(db, allSchemas));
3406
3440
  const relations = await readRelations(db, schemas);
3407
3441
  const policies = await readPolicies(db, schemas);
3408
3442
  const grants = await readGrants(db, schemas);
@@ -3413,7 +3447,7 @@ async function readSnapshot(client, opts, diagnostics, begin) {
3413
3447
  const referenced = await readReferencedRelations(db, outOfScopeReferences(relations, views, foreignKeys));
3414
3448
  const scannerIsPrivileged = isPrivileged(currentRole, server, roles, relations);
3415
3449
  const connectingRole = !scannerIsPrivileged && currentRole !== "unknown" ? currentRole : void 0;
3416
- const exposedRoles = exposedRolesFor(roles, opts.roles, connectingRole);
3450
+ const exposedRoles = exposedRolesFor(roles, requestRoles, opts.roles, connectingRole);
3417
3451
  diagnostics.scanningAsExposedRole = connectingRole && exposedRoles.includes(connectingRole) ? connectingRole : null;
3418
3452
  diagnostics.unrecognizedGrantees = unrecognizedGranteesFor(grants, roles, relations, exposedRoles, currentRole);
3419
3453
  return {
@@ -3423,6 +3457,7 @@ async function readSnapshot(client, opts, diagnostics, begin) {
3423
3457
  scannerIsPrivileged,
3424
3458
  schemas,
3425
3459
  exposedRoles,
3460
+ requestRoles,
3426
3461
  platform: detectPlatform(allSchemas, roles),
3427
3462
  relations: [...relations, ...referenced],
3428
3463
  policies,
@@ -3939,10 +3974,11 @@ function detectPlatform(allSchemas, roles) {
3939
3974
  * `connecting` is the role the scan came in as, passed only when it is not
3940
3975
  * privileged — see the call site.
3941
3976
  */
3942
- function exposedRolesFor(roles, explicit, connecting) {
3977
+ function exposedRolesFor(roles, requestRoles, explicit, connecting) {
3943
3978
  const present = new Set(roles.map((r) => r.name));
3944
3979
  const named = [
3945
3980
  ...CANDIDATE_EXPOSED_ROLES,
3981
+ ...requestRoles,
3946
3982
  ...explicit ?? [],
3947
3983
  ...connecting ? [connecting] : []
3948
3984
  ];
@@ -5529,6 +5565,7 @@ async function scanWithSnapshot(options) {
5529
5565
  connectionString: options.connectionString,
5530
5566
  schemas: options.schemas && options.schemas.length > 0 ? options.schemas : void 0,
5531
5567
  roles: options.roles && options.roles.length > 0 ? options.roles : void 0,
5568
+ requestRoles: options.requestRoles && options.requestRoles.length > 0 ? options.requestRoles : void 0,
5532
5569
  statementTimeoutMs: options.statementTimeoutMs ?? DEFAULT_TIMEOUT_MS
5533
5570
  });
5534
5571
  return {
@@ -5616,6 +5653,7 @@ function emptyOptions() {
5616
5653
  html: null,
5617
5654
  schemas: [],
5618
5655
  roles: [],
5656
+ requestRoles: [],
5619
5657
  failOn: DEFAULT_FAIL_ON,
5620
5658
  skip: [],
5621
5659
  only: [],
@@ -5751,6 +5789,15 @@ function parseArgs(argv) {
5751
5789
  options.roles.push(...splitList(value));
5752
5790
  break;
5753
5791
  }
5792
+ case "--request-role": {
5793
+ const value = takeValue();
5794
+ if (value === null) return {
5795
+ ok: false,
5796
+ message: "--request-role needs a role name, e.g. --request-role app_prod_user."
5797
+ };
5798
+ options.requestRoles.push(...splitList(value));
5799
+ break;
5800
+ }
5754
5801
  case "--skip": {
5755
5802
  const value = takeValue();
5756
5803
  if (value === null) return {
@@ -5966,6 +6013,10 @@ Options
5966
6013
  Name the role your application connects as — the checks
5967
6014
  only report a table as exposed when an exposed role can
5968
6015
  reach it. Repeatable or comma-separated.
6016
+ --request-role <name> The role a Rebase app on this database runs requests as, in
6017
+ place of rebase_user (rls.requestRole). Without it, the roles
6018
+ the database recorded in rebase.schema_meta are used, then
6019
+ rebase_user. Repeatable or comma-separated.
5969
6020
  --fail-on <severity> Exit 1 at or above this severity: info, low, medium, high,
5970
6021
  critical, or none to never fail. Default: high.
5971
6022
  --only <id> Run only these checks. Repeatable or comma-separated.
@@ -6123,6 +6174,7 @@ async function runCli(argv, io = defaultIo()) {
6123
6174
  connectionString,
6124
6175
  schemas: options.schemas,
6125
6176
  roles: options.roles,
6177
+ requestRoles: options.requestRoles,
6126
6178
  only: options.only,
6127
6179
  skip: options.skip,
6128
6180
  statementTimeoutMs: options.timeoutMs