@rebasepro/rls-check 0.25.1 → 0.27.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/README.md CHANGED
@@ -16,7 +16,7 @@ It also takes the connection string as an argument, but prefer not to: npm echoe
16
16
 
17
17
  It works against Supabase, Neon, RDS, Cloud SQL, Postgres in a container on your laptop, or anything else that speaks the wire protocol. It knows nothing about your framework and asks nothing of your codebase.
18
18
 
19
- **It is read-only.** It sets two options for its own session, `statement_timeout` and `default_transaction_read_only = on`, and then issues `SELECT`s against the system catalogs (`pg_class` and its ACLs, `pg_policies`, `pg_proc`, `pg_roles` …) and nothing else. It writes nothing, changes nothing beyond its own session, and sends nothing anywhere. There is no telemetry, no upload, and no network access beyond the connection you give it.
19
+ **It is read-only.** It runs inside one `BEGIN READ ONLY` transaction with a `SET LOCAL statement_timeout`, and issues `SELECT`s against the system catalogs (`pg_class` and its ACLs, `pg_policies`, `pg_proc`, `pg_roles` …) and nothing else. It writes nothing, sets nothing for the session (a shared or pooled session is left as it was found), and sends nothing anywhere. There is no telemetry, no upload, and no network access beyond the connection you give it.
20
20
 
21
21
  ---
22
22
 
@@ -177,6 +177,10 @@ DATABASE_URL="postgresql://..." npx @rebasepro/rls-check [options]
177
177
  npx @rebasepro/rls-check [connection-string] [options]
178
178
 
179
179
  --json Machine-readable ScanResult on stdout, and nothing else.
180
+ --format <name> text (default), json (the same as --json) or agent: one JSON
181
+ document for a coding agent, where every finding carries the
182
+ failing table and policy, the SQL that fixes it and the
183
+ equivalent Rebase securityRules. See "Agent output" below.
180
184
  --html <path> Also write a self-contained HTML report to <path>. One file,
181
185
  no network requests, safe to attach to a ticket.
182
186
  --schema <name> Restrict the scan to a schema. Repeatable or comma-separated.
@@ -331,6 +335,53 @@ Findings are sorted worst-first and then by schema, object and id, so two scans
331
335
 
332
336
  `exposedRoles` and `diagnostics` are part of the contract, not decoration. A check that calls a table exposed does so only when one of the exposed roles can reach it, and `diagnostics.degraded` is how a consumer tells "nothing was wrong" from "the scan could not look" — `findings: []` without both is half an answer.
333
337
 
338
+ ## Agent output
339
+
340
+ `--format agent` is for a coding agent that runs `npx @rebasepro/rls-check` against the database it is building and then fixes what it finds. It writes one JSON document to stdout and nothing else; the exit code is the same as for any other format.
341
+
342
+ ```bash
343
+ DATABASE_URL="postgresql://..." npx @rebasepro/rls-check --format agent
344
+ ```
345
+
346
+ Every finding names the check id (one of the fifteen `--list-checks` prints) and the failing object, and carries a `remediation` built for that check id:
347
+
348
+ ```jsonc
349
+ {
350
+ "key": "rls-disabled:public.todos", // stable across runs
351
+ "checkId": "rls-disabled",
352
+ "severity": "critical",
353
+ "confidence": "certain",
354
+ "failsRun": true, // at or above --fail-on
355
+ "target": { "schema": "public", "table": "todos", "policy": null, "view": null, "routine": null, "column": null },
356
+ "title": "public.todos has row-level security disabled and is granted to anon",
357
+ "detail": "…", "impact": "…", "docs": "https://rebase.pro/docs/rls-check#rls-disabled",
358
+ "remediation": {
359
+ "summary": "Enable row-level security on public.todos and add a policy that limits every row to its owner.",
360
+ "apply": "sql",
361
+ "sql": "ALTER TABLE \"public\".\"todos\" ENABLE ROW LEVEL SECURITY;\nCREATE POLICY \"todos_owner\" ON \"public\".\"todos\"\n FOR ALL\n USING (\"user_id\" = auth.uid())\n WITH CHECK (\"user_id\" = auth.uid());",
362
+ "placeholders": [],
363
+ "alternatives": [{ "summary": "If API callers should not reach this table at all, revoke their privileges instead.", "sql": "REVOKE SELECT, INSERT ON \"public\".\"todos\" FROM \"anon\";" }],
364
+ "caveats": ["With row-level security on, every role that neither owns the table nor holds BYPASSRLS sees only the rows a policy admits — …"],
365
+ "rebase": {
366
+ "applicable": true,
367
+ "securityRules": "[\n { operation: \"all\", ownerField: \"user_id\" }\n]",
368
+ "snippet": "defineCollection({\n // …name, slug, properties and the rest stay as they are…\n table: \"todos\",\n securityRules: [ … ]\n});",
369
+ "note": "Rebase enables row-level security on every collection's table and compiles each rule into a policy … `ownerField` compiles to `<column>::text = rebase.uid()` …"
370
+ }
371
+ }
372
+ }
373
+ ```
374
+
375
+ What the fields promise:
376
+
377
+ - **`apply`** says where the fix belongs. `sql`: run `remediation.sql` as a migration. `rebase-config`: the policy is compiled by Rebase from a collection's `securityRules` and re-made on every boot, so `sql` is `null` and the rule in `rebase.snippet` is what to change. `manual`: no statement can be written without a decision only a person can make, and `summary` names it.
378
+ - **`sql`** is statements only — no comments to interpret — and is written per check: the table's own owner column (compared as uuid or text, whichever its type allows), the grants that actually reach the exposed roles, the policy's own expression with only the flagged clause rewritten. Applying it clears the finding it is attached to; the test suite holds every check to that against a real PostgreSQL.
379
+ - **`placeholders`** lists the tokens the catalog cannot fill — `<owner_column>` on a table with no column that looks like an owner, `<app_role>` for the role your application connects as. Replace them before running `sql`.
380
+ - **`alternatives`** are fixes for a different intent ("nobody should reach this table at all"), not a second step.
381
+ - **`rebase`** is the same fix as `defineCollection({ securityRules: [...] })`. The rules are type-checked against `SecurityRule` from `@rebasepro/types` in this package's tests. Where `securityRules` cannot express the fix — grants, views, functions, `FORCE` — `applicable` is `false`, the rules are `null`, and `note` says what Rebase does instead.
382
+
383
+ Around the findings, the document carries the verdict (`exitCode`, `reason`, `failOn`), `complete` (false when a catalogue read or a check failed), `notes` (the same caveats the text report prints, such as a role to name with `--role`), `diagnostics` and `howToApply`, a paragraph an agent can read as instructions. Every key is always present, with `null` for an absent object, and `formatVersion` changes only when a key is renamed or removed. `--json` is unchanged.
384
+
334
385
  ## What this tool does not do
335
386
 
336
387
  Being clear about this is the point of the tool. It is a **static audit of the catalog**, not a penetration test.
@@ -360,7 +411,7 @@ if (exceedsThreshold(result.findings, "high")) {
360
411
  }
361
412
  ```
362
413
 
363
- `introspect()`, `runChecks()`, `renderReport()` and `renderJson()` are exported too, if you would rather assemble the pipeline yourself. The checks are pure functions of a `DbSnapshot`, so they are straightforward to test against a schema you construct by hand.
414
+ `scanWithSnapshot()` returns the snapshot beside the result, which is what `renderAgentReport()` and `remediationFor()` need. `introspect()`, `runChecks()`, `renderReport()` and `renderJson()` are exported too, if you would rather assemble the pipeline yourself. The checks are pure functions of a `DbSnapshot`, so they are straightforward to test against a schema you construct by hand.
364
415
 
365
416
  ## Requirements
366
417
 
@@ -14,3 +14,10 @@ import type { Check } from "../types.js";
14
14
  * impact line says so rather than claiming a working escalation.
15
15
  */
16
16
  export declare const securityDefinerMutableSearchPath: Check;
17
+ /**
18
+ * A `DO` block that pins `search_path` on every overload of `schema.name`.
19
+ *
20
+ * Exported for the agent output, which prints the same statement as its
21
+ * runnable SQL.
22
+ */
23
+ export declare function pinSearchPathSql(schema: string, name: string): string;
@@ -1,4 +1,4 @@
1
- import type { Check } from "../types.js";
1
+ import type { Check, DbPolicy, DbSnapshot } from "../types.js";
2
2
  /**
3
3
  * A bare column reference inside a policy subquery that resolves to the *inner*
4
4
  * relation when the outer row was meant.
@@ -41,3 +41,34 @@ import type { Check } from "../types.js";
41
41
  * comparison somebody meant.
42
42
  */
43
43
  export declare const unqualifiedColumnInSubquery: Check;
44
+ export interface Ambiguity {
45
+ /**
46
+ * `bare`: the unqualified name is in the text (never, from a live catalog).
47
+ * `self`: the stored text compares an inner column with itself, which is
48
+ * what Postgres keeps of a bare name that bound to the inner relation.
49
+ */
50
+ kind: "bare" | "self";
51
+ /** The bare name as written. */
52
+ column: string;
53
+ /** The relation Postgres binds it to, as `schema.name` for prose. */
54
+ inner: string;
55
+ /** The same relation, for SQL. */
56
+ innerRelation: {
57
+ schema: string;
58
+ name: string;
59
+ };
60
+ /** What it is compared against, for the report. */
61
+ comparedTo: string;
62
+ /** The comparison operator, for a `self` hit — `=` admits, `<>` denies. */
63
+ operator?: string;
64
+ }
65
+ /**
66
+ * Every ambiguity this check reports on one policy, with the clause it sits in.
67
+ *
68
+ * The same scan `run` makes, exposed so the agent output can rewrite the exact
69
+ * comparison a finding names rather than restate a generic template.
70
+ */
71
+ export declare function policyAmbiguities(snapshot: DbSnapshot, policy: DbPolicy): {
72
+ clause: "USING" | "WITH CHECK";
73
+ hit: Ambiguity;
74
+ }[];
@@ -84,6 +84,17 @@ export declare function policiesFor(snapshot: DbSnapshot, schema: string, table:
84
84
  export declare const hasColumn: (r: DbRelation, name: string) => boolean;
85
85
  /** `≈ 12,000 rows` — only ever used to convey blast radius, never severity. */
86
86
  export declare function rowsPhrase(rel: DbRelation | undefined): string;
87
+ /**
88
+ * A quoted identifier that is one printable token wherever a fix puts it.
89
+ *
90
+ * Every name here comes out of the catalog, which means out of whoever could
91
+ * create a table, a role or a policy, and every fix is printed to be pasted
92
+ * into psql. Doubling `"` keeps a name inside its quotes; a name with a line
93
+ * break in it is written as a Unicode-escape identifier (`U&"a\000Ab"`), which
94
+ * names the same object and has no line break to escape a comment with.
95
+ */
96
+ /** Column names that usually hold the id of the row's owner, most likely first. */
97
+ export declare const OWNER_COLUMNS: string[];
87
98
  /**
88
99
  * The column a printed fix should scope rows by, when the table has one that
89
100
  * looks like the owner's id. Fixes named `user_id` on every table, and a table
package/dist/cli.d.ts CHANGED
@@ -46,6 +46,25 @@ export interface ScanOptions {
46
46
  * and this has an integration test.
47
47
  */
48
48
  export declare function scan(options: ScanOptions): Promise<ScanResult>;
49
+ /**
50
+ * {@link scan}, also handing back the snapshot the findings were computed from.
51
+ *
52
+ * `--format agent` needs it: a remediation names the owner column, the grants
53
+ * to revoke and the policy expression to rewrite, and the result carries none
54
+ * of those.
55
+ */
56
+ export declare function scanWithSnapshot(options: ScanOptions): Promise<{
57
+ result: ScanResult;
58
+ snapshot: DbSnapshot;
59
+ }>;
60
+ /**
61
+ * The half of {@link scan} after introspection: run the checks over a snapshot
62
+ * and assemble the result. Pure, and exported so the wiring below is tested
63
+ * without a database — the unit suite passed with it removed.
64
+ *
65
+ * `diagnostics` is extended in place with any check that crashed.
66
+ */
67
+ export declare function scanSnapshot(snapshot: DbSnapshot, diagnostics: ScanResult["diagnostics"], options: Pick<ScanOptions, "connectionString" | "only" | "skip" | "now">): ScanResult;
49
68
  /**
50
69
  * The check ids `runChecks` will actually execute for these options.
51
70
  *
@@ -65,8 +84,18 @@ export declare function buildScanResult(snapshot: DbSnapshot, findings: Finding[
65
84
  scannedAt: string;
66
85
  diagnostics: ScanResult["diagnostics"];
67
86
  }): ScanResult;
87
+ /**
88
+ * What stdout carries. `text` is the report for a person; `json` is the
89
+ * {@link ScanResult} contract; `agent` is one JSON document with a remediation —
90
+ * SQL and the Rebase `securityRules` equivalent — on every finding, for a
91
+ * coding agent to apply.
92
+ */
93
+ export declare const OUTPUT_FORMATS: readonly ["text", "json", "agent"];
94
+ export type OutputFormat = (typeof OUTPUT_FORMATS)[number];
68
95
  export interface CliOptions {
69
96
  connectionString: string | null;
97
+ format: OutputFormat;
98
+ /** `format === "json"`, kept for callers that read it. */
70
99
  json: boolean;
71
100
  /**
72
101
  * `--html <path>`: also write a self-contained HTML report there.
package/dist/index.d.ts CHANGED
@@ -16,13 +16,17 @@
16
16
  * at production databases by people who have never heard of us, and the install
17
17
  * has to be something they can read in full before they run it.
18
18
  */
19
- export { runCli, scan, selectCheckIds, EXIT_OK, EXIT_FINDINGS, EXIT_ERROR } from "./cli.js";
20
- export type { ScanOptions, CliIo, CliOptions } from "./cli.js";
19
+ export { runCli, scan, scanWithSnapshot, selectCheckIds, EXIT_OK, EXIT_FINDINGS, EXIT_ERROR } from "./cli.js";
20
+ 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
24
  export { renderReport, renderJson, renderCheckCatalog, severityRank, maxSeverity, exceedsThreshold, formatTarget } from "./report.js";
25
25
  export type { RenderOptions } from "./report.js";
26
+ export { renderAgentReport, findingKey, AGENT_FORMAT_VERSION } from "./report-agent.js";
27
+ export type { AgentFinding, AgentReport, AgentRenderOptions } from "./report-agent.js";
28
+ export { remediationFor } from "./remediation.js";
29
+ export type { Remediation, RemediationApply, Placeholder, AlternativeFix, RebaseEquivalent } from "./remediation.js";
26
30
  export { renderHtml, escapeHtml } from "./report-html.js";
27
31
  export type { HtmlRenderOptions } from "./report-html.js";
28
32
  export { redactConnectionString, redactSecrets, parseConnectionString, formatEndpoint } from "./redact.js";