@rebasepro/rls-check 0.31.0-canary.g902a0ce → 0.32.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/dist/index.d.ts CHANGED
@@ -21,6 +21,8 @@ export type { ScanOptions, CliIo, CliOptions, OutputFormat } from "./cli.js";
21
21
  export { introspect } from "./introspect.js";
22
22
  export type { ConnectOptions } from "./introspect.js";
23
23
  export { CHECKS, runChecks } from "./checks/index.js";
24
+ export { findPolicyRecursion } from "./policy-recursion.js";
25
+ export type { PolicyRecursion, PolicyRecursionOptions, RecursionPolicy, RecursionStep, RoleContext } from "./policy-recursion.js";
24
26
  export { renderReport, renderJson, renderCheckCatalog, severityRank, maxSeverity, exceedsThreshold, formatTarget } from "./report.js";
25
27
  export type { RenderOptions } from "./report.js";
26
28
  export { renderAgentReport, findingKey, AGENT_FORMAT_VERSION } from "./report-agent.js";
package/dist/index.es.js CHANGED
@@ -1898,7 +1898,7 @@ function splitTopLevelAnd(expr) {
1898
1898
  if (inQuote) continue;
1899
1899
  if (ch === "(") depth++;
1900
1900
  else if (ch === ")") depth--;
1901
- else if (depth === 0 && s.startsWith("and", i) && isWord(s, i, 3)) {
1901
+ else if (depth === 0 && s.startsWith("and", i) && isWord$1(s, i, 3)) {
1902
1902
  parts.push(s.slice(start, i));
1903
1903
  i += 2;
1904
1904
  start = i + 1;
@@ -1908,7 +1908,7 @@ function splitTopLevelAnd(expr) {
1908
1908
  return parts.length === 1 ? parts : parts.flatMap(splitTopLevelAnd);
1909
1909
  }
1910
1910
  /** `and` as a whole word, not the tail of `brand` or the head of `android`. */
1911
- function isWord(s, at, length) {
1911
+ function isWord$1(s, at, length) {
1912
1912
  const before = at === 0 ? "" : s[at - 1];
1913
1913
  const after = s[at + length] ?? "";
1914
1914
  return !/[a-z0-9_]/.test(before) && !/[a-z0-9_]/.test(after);
@@ -6248,6 +6248,309 @@ async function runCli(argv, io = defaultIo()) {
6248
6248
  }
6249
6249
  }
6250
6250
  //#endregion
6251
- export { AGENT_FORMAT_VERSION, CHECKS, EXIT_ERROR, EXIT_FINDINGS, EXIT_OK, SEVERITIES, escapeHtml, exceedsThreshold, findingKey, formatEndpoint, formatTarget, introspect, maxSeverity, parseConnectionString, redactConnectionString, redactSecrets, remediationFor, renderAgentReport, renderCheckCatalog, renderHtml, renderJson, renderReport, runChecks, runCli, scan, scanWithSnapshot, selectCheckIds, severityRank };
6251
+ //#region src/policy-recursion.ts
6252
+ /** The first word of a parenthesised sub-select. */
6253
+ var SUBQUERY_OPENERS = /* @__PURE__ */ new Set([
6254
+ "select",
6255
+ "with",
6256
+ "values"
6257
+ ]);
6258
+ /** Words that end a FROM list at its own level. */
6259
+ var FROM_LIST_END = /* @__PURE__ */ new Set([
6260
+ "where",
6261
+ "group",
6262
+ "having",
6263
+ "order",
6264
+ "limit",
6265
+ "offset",
6266
+ "union",
6267
+ "intersect",
6268
+ "except",
6269
+ "window",
6270
+ "fetch",
6271
+ "for",
6272
+ "select",
6273
+ "returning"
6274
+ ]);
6275
+ /** Words that may precede a FROM item and are not its name. */
6276
+ var FROM_ITEM_PREFIX = /* @__PURE__ */ new Set(["only", "lateral"]);
6277
+ var isWord = (token, words) => token !== void 0 && token.kind === "ident" && !token.quoted && (typeof words === "string" ? token.value === words : words.has(token.value));
6278
+ var isPunct = (token, value) => token !== void 0 && token.kind === "punct" && token.value === value;
6279
+ /**
6280
+ * The table a FROM item at `start` names, or null when it names none: a
6281
+ * derived table `(SELECT …)` (read as a sub-select of its own) or a function
6282
+ * (`FROM unnest(…)`), which Postgres does not expand.
6283
+ */
6284
+ function fromItem(tokens, start, end) {
6285
+ let j = start;
6286
+ while (j < end && isWord(tokens[j], FROM_ITEM_PREFIX)) j++;
6287
+ const parts = [];
6288
+ while (j < end && tokens[j].kind === "ident") {
6289
+ parts.push(tokens[j]);
6290
+ if (isPunct(tokens[j + 1], ".")) j += 2;
6291
+ else {
6292
+ j++;
6293
+ break;
6294
+ }
6295
+ }
6296
+ if (parts.length === 0) return null;
6297
+ if (j < end && isPunct(tokens[j], "(")) return null;
6298
+ return {
6299
+ schema: parts.length > 1 ? parts[parts.length - 2].value : null,
6300
+ name: parts[parts.length - 1].value
6301
+ };
6302
+ }
6303
+ /** The tables the FROM and JOIN clauses of one sub-select's own level name. */
6304
+ function fromItems(tokens, start, end, level) {
6305
+ const out = [];
6306
+ const take = (at) => {
6307
+ const ref = fromItem(tokens, at, end);
6308
+ if (ref) out.push(ref);
6309
+ };
6310
+ let inFrom = false;
6311
+ for (let j = start; j < end; j++) {
6312
+ const token = tokens[j];
6313
+ if (token.depth !== level) continue;
6314
+ if (isWord(token, "from")) {
6315
+ if (isWord(tokens[j - 1], "distinct")) continue;
6316
+ inFrom = true;
6317
+ take(j + 1);
6318
+ } else if (isWord(token, "join")) {
6319
+ inFrom = true;
6320
+ take(j + 1);
6321
+ } else if (isWord(token, FROM_LIST_END)) inFrom = false;
6322
+ else if (inFrom && isPunct(token, ",")) take(j + 1);
6323
+ }
6324
+ return out;
6325
+ }
6326
+ /** The names `WITH name [(cols)] AS [[NOT] MATERIALIZED] (…)` defines anywhere in the expression. */
6327
+ function cteNames(tokens) {
6328
+ const out = /* @__PURE__ */ new Set();
6329
+ for (let i = 0; i < tokens.length; i++) {
6330
+ if (tokens[i].kind !== "ident") continue;
6331
+ let j = i + 1;
6332
+ if (isPunct(tokens[j], "(")) {
6333
+ const close = matchParen(tokens, j);
6334
+ if (close === -1) continue;
6335
+ j = close + 1;
6336
+ }
6337
+ if (!isWord(tokens[j], "as")) continue;
6338
+ let k = j + 1;
6339
+ if (isWord(tokens[k], "not")) k++;
6340
+ if (isWord(tokens[k], "materialized")) k++;
6341
+ if (isPunct(tokens[k], "(") && isWord(tokens[k + 1], SUBQUERY_OPENERS)) out.add(tokens[i].value);
6342
+ }
6343
+ return out;
6344
+ }
6345
+ /**
6346
+ * Every sub-select in a policy expression: whether there is one, and the
6347
+ * tables they read.
6348
+ *
6349
+ * Sub-selects nest, and each is read at its own level, so `FROM` inside
6350
+ * `extract(year FROM x)` — one level deeper than the sub-select it sits in —
6351
+ * is never a FROM clause.
6352
+ */
6353
+ function readSubLinks(expr) {
6354
+ if (!expr) return {
6355
+ hasSubLink: false,
6356
+ reads: []
6357
+ };
6358
+ const tokens = tokenize(expr);
6359
+ const reads = [];
6360
+ let hasSubLink = false;
6361
+ for (let i = 0; i < tokens.length; i++) {
6362
+ if (!isPunct(tokens[i], "(") || !isWord(tokens[i + 1], SUBQUERY_OPENERS)) continue;
6363
+ hasSubLink = true;
6364
+ const close = matchParen(tokens, i);
6365
+ reads.push(...fromItems(tokens, i + 1, close === -1 ? tokens.length : close, tokens[i].depth + 1));
6366
+ }
6367
+ const ctes = cteNames(tokens);
6368
+ return {
6369
+ hasSubLink,
6370
+ reads: reads.filter((ref) => ref.schema !== null || !ctes.has(ref.name))
6371
+ };
6372
+ }
6373
+ /**
6374
+ * The edges a statement of the policy's own command walks: USING for a read
6375
+ * or a delete, WITH CHECK (or USING standing in for it) for an insert, both
6376
+ * for an update — and both for `ALL`, which an update applies whole.
6377
+ */
6378
+ function startEdges(entry) {
6379
+ switch (entry.policy.command) {
6380
+ case "SELECT":
6381
+ case "DELETE": return entry.usingEdges;
6382
+ case "INSERT": return entry.policy.withCheck != null ? entry.checkEdges : entry.usingEdges;
6383
+ default: return uniqueEdges([...entry.usingEdges, ...entry.checkEdges]);
6384
+ }
6385
+ }
6386
+ /** One edge per table, the certain one when a table is reached both ways. */
6387
+ function uniqueEdges(edges) {
6388
+ const byTable = /* @__PURE__ */ new Map();
6389
+ for (const edge of edges) {
6390
+ const known = byTable.get(edge.to);
6391
+ if (!known || edge.certain && !known.certain) byTable.set(edge.to, edge);
6392
+ }
6393
+ return [...byTable.values()];
6394
+ }
6395
+ /** A NUL cannot appear in a Postgres identifier, so it cannot make two pairs collide. */
6396
+ var keyOf = (schema, table) => `${schema}\u0000${table}`;
6397
+ function splitKey(key) {
6398
+ const at = key.indexOf("\0");
6399
+ return {
6400
+ schema: key.slice(0, at),
6401
+ table: key.slice(at + 1)
6402
+ };
6403
+ }
6404
+ /** The policy tables a reference can mean. */
6405
+ function resolve(ref, schemasByTable, searchPath) {
6406
+ const schemas = schemasByTable.get(ref.name) ?? [];
6407
+ if (ref.schema !== null) return schemas.includes(ref.schema) ? [{
6408
+ to: keyOf(ref.schema, ref.name),
6409
+ certain: true
6410
+ }] : [];
6411
+ const onPath = searchPath.find((schema) => schemas.includes(schema));
6412
+ if (onPath !== void 0) return [{
6413
+ to: keyOf(onPath, ref.name),
6414
+ certain: true
6415
+ }];
6416
+ return schemas.map((schema) => ({
6417
+ to: keyOf(schema, ref.name),
6418
+ certain: false,
6419
+ caveat: `"${ref.name}" is written without a schema and the search path (${searchPath.join(", ")}) has no table of that name: it is ${schema}.${ref.name} only if the policy was created with ${schema} on its search path.`
6420
+ }));
6421
+ }
6422
+ var appliesIn = (policy, roles) => policy.roles.some((role) => role.toLowerCase() === "public" || roles.has(role.toLowerCase()));
6423
+ /**
6424
+ * The shortest way from `first` back to `home` through tables whose SELECT
6425
+ * policies have a sub-select — the tables Postgres walks into — or null.
6426
+ * `certainOnly` keeps to edges whose table is not in doubt.
6427
+ */
6428
+ function loopBack(home, first, expand, certainOnly) {
6429
+ if (certainOnly && !first.certain) return null;
6430
+ const queue = [{
6431
+ key: first.to,
6432
+ via: [],
6433
+ caveats: first.caveat ? [first.caveat] : []
6434
+ }];
6435
+ const seen = /* @__PURE__ */ new Set();
6436
+ for (let next = queue.shift(); next; next = queue.shift()) {
6437
+ const expansion = expand(next.key);
6438
+ if (!expansion.hasSubLink) continue;
6439
+ if (next.key === home) return {
6440
+ via: next.via,
6441
+ caveats: next.caveats
6442
+ };
6443
+ if (seen.has(next.key)) continue;
6444
+ seen.add(next.key);
6445
+ for (const { edge, policy } of expansion.edges) {
6446
+ if (certainOnly && !edge.certain) continue;
6447
+ queue.push({
6448
+ key: edge.to,
6449
+ via: [...next.via, {
6450
+ key: next.key,
6451
+ policy
6452
+ }],
6453
+ caveats: edge.caveat ? [...next.caveats, edge.caveat] : next.caveats
6454
+ });
6455
+ }
6456
+ }
6457
+ return null;
6458
+ }
6459
+ /**
6460
+ * Every policy whose sub-selects lead back to its own table through tables
6461
+ * Postgres walks into — each one a statement the database refuses with 42P17.
6462
+ *
6463
+ * One finding per policy and table it reads, with the shortest loop and every
6464
+ * role context it recurses for. A loop between two other tables that a policy
6465
+ * merely passes through is reported from those tables' own policies, not
6466
+ * again from every policy that reaches it.
6467
+ */
6468
+ function findPolicyRecursion(policies, options = {}) {
6469
+ const searchPath = options.searchPath ?? ["public"];
6470
+ const contexts = options.contexts && options.contexts.length > 0 ? options.contexts : [{
6471
+ name: "PUBLIC",
6472
+ roles: []
6473
+ }];
6474
+ const schemasByTable = /* @__PURE__ */ new Map();
6475
+ for (const policy of policies) {
6476
+ const schemas = schemasByTable.get(policy.table) ?? [];
6477
+ if (!schemas.includes(policy.schema)) schemas.push(policy.schema);
6478
+ schemasByTable.set(policy.table, schemas);
6479
+ }
6480
+ const edgesOf = (refs) => uniqueEdges(refs.flatMap((ref) => resolve(ref, schemasByTable, searchPath)));
6481
+ const parsed = policies.map((policy) => {
6482
+ const using = readSubLinks(policy.using);
6483
+ const check = readSubLinks(policy.withCheck);
6484
+ return {
6485
+ policy,
6486
+ key: keyOf(policy.schema, policy.table),
6487
+ hasSubLink: using.hasSubLink || check.hasSubLink,
6488
+ usingEdges: edgesOf(using.reads),
6489
+ checkEdges: edgesOf(check.reads)
6490
+ };
6491
+ });
6492
+ const byTable = /* @__PURE__ */ new Map();
6493
+ for (const entry of parsed) byTable.set(entry.key, [...byTable.get(entry.key) ?? [], entry]);
6494
+ const found = /* @__PURE__ */ new Map();
6495
+ for (const context of contexts) {
6496
+ const roles = new Set(context.roles.map((role) => role.toLowerCase()));
6497
+ const expansions = /* @__PURE__ */ new Map();
6498
+ const expand = (key) => {
6499
+ const known = expansions.get(key);
6500
+ if (known) return known;
6501
+ const reading = (byTable.get(key) ?? []).filter((entry) => (entry.policy.command === "SELECT" || entry.policy.command === "ALL") && entry.policy.using != null && appliesIn(entry.policy, roles));
6502
+ const expansion = {
6503
+ hasSubLink: reading.some((entry) => entry.hasSubLink),
6504
+ edges: reading.flatMap((entry) => entry.usingEdges.map((edge) => ({
6505
+ edge,
6506
+ policy: entry.policy.name
6507
+ })))
6508
+ };
6509
+ expansions.set(key, expansion);
6510
+ return expansion;
6511
+ };
6512
+ for (const start of parsed) {
6513
+ if (!appliesIn(start.policy, roles)) continue;
6514
+ for (const first of startEdges(start)) {
6515
+ const certain = loopBack(start.key, first, expand, true);
6516
+ const loop = certain ?? loopBack(start.key, first, expand, false);
6517
+ if (!loop) continue;
6518
+ const id = `${start.key}\u0000${start.policy.name}\u0000${first.to}`;
6519
+ const path = [{
6520
+ schema: start.policy.schema,
6521
+ table: start.policy.table,
6522
+ policy: start.policy.name
6523
+ }, ...loop.via.map((step) => ({
6524
+ ...splitKey(step.key),
6525
+ policy: step.policy
6526
+ }))];
6527
+ const known = found.get(id);
6528
+ if (known) {
6529
+ if (!known.contexts.includes(context.name)) known.contexts.push(context.name);
6530
+ if (certain && known.confidence === "heuristic") {
6531
+ known.path = path;
6532
+ known.confidence = "certain";
6533
+ known.caveats = [];
6534
+ }
6535
+ continue;
6536
+ }
6537
+ found.set(id, {
6538
+ schema: start.policy.schema,
6539
+ table: start.policy.table,
6540
+ policy: start.policy.name,
6541
+ command: start.policy.command,
6542
+ reads: splitKey(first.to),
6543
+ path,
6544
+ contexts: [context.name],
6545
+ confidence: certain ? "certain" : "heuristic",
6546
+ caveats: certain ? [] : [...new Set(loop.caveats)]
6547
+ });
6548
+ }
6549
+ }
6550
+ }
6551
+ return [...found.values()].sort((a, b) => a.schema.localeCompare(b.schema) || a.table.localeCompare(b.table) || a.policy.localeCompare(b.policy) || a.reads.schema.localeCompare(b.reads.schema) || a.reads.table.localeCompare(b.reads.table));
6552
+ }
6553
+ //#endregion
6554
+ export { AGENT_FORMAT_VERSION, CHECKS, EXIT_ERROR, EXIT_FINDINGS, EXIT_OK, SEVERITIES, escapeHtml, exceedsThreshold, findPolicyRecursion, findingKey, formatEndpoint, formatTarget, introspect, maxSeverity, parseConnectionString, redactConnectionString, redactSecrets, remediationFor, renderAgentReport, renderCheckCatalog, renderHtml, renderJson, renderReport, runChecks, runCli, scan, scanWithSnapshot, selectCheckIds, severityRank };
6252
6555
 
6253
6556
  //# sourceMappingURL=index.es.js.map