@rebasepro/server-postgres 0.9.1-canary.26fe4b2 → 0.9.1-canary.29ed165

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.
@@ -26,6 +26,14 @@ export interface PolicyRef {
26
26
  hasUsing: boolean;
27
27
  /** Whether a WITH CHECK clause is present at all (not what it says). */
28
28
  hasWithCheck: boolean;
29
+ /**
30
+ * The live clause text, when read from `pg_policies`. Present only for live
31
+ * policies (the expected side is parsed from DDL and does not carry it).
32
+ * Used solely for the insecure-tautology scan, not for divergence — Postgres
33
+ * rewrites this text, so it is not safe to diff against expected.
34
+ */
35
+ qual?: string | null;
36
+ withCheck?: string | null;
29
37
  }
30
38
  export interface PolicyDrift {
31
39
  /** Described by the collections, absent from the database. */
@@ -38,6 +46,22 @@ export interface PolicyDrift {
38
46
  actual: PolicyRef;
39
47
  differences: string[];
40
48
  }[];
49
+ /**
50
+ * A live policy whose expression is the known-permissive tautology
51
+ * `auth.uid() IS NOT NULL` — true for anonymous visitors too, because the
52
+ * user path coerces a blank id to the `'anonymous'` sentinel. This is what
53
+ * `policy.authenticated()` used to compile to, so a database pushed before
54
+ * that fix carries it, and neither the name, roles, command nor clause
55
+ * *presence* differs from the corrected policy — the only thing that changed
56
+ * is the expression text, which this checker otherwise (correctly) ignores.
57
+ * So it is the one drift that hides from every other check here.
58
+ *
59
+ * @see reason a sentence naming the clause and what to do.
60
+ */
61
+ insecure: {
62
+ policy: PolicyRef;
63
+ reason: string;
64
+ }[];
41
65
  }
42
66
  export interface Queryable {
43
67
  query<R>(text: string, values?: unknown[]): Promise<{
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rebasepro/server-postgres",
3
3
  "type": "module",
4
- "version": "0.9.1-canary.26fe4b2",
4
+ "version": "0.9.1-canary.29ed165",
5
5
  "description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
6
6
  "funding": {
7
7
  "url": "https://github.com/sponsors/rebaseco"
@@ -47,11 +47,11 @@
47
47
  "execa": "^9.6.1",
48
48
  "pg": "^8.21.0",
49
49
  "ws": "^8.21.0",
50
- "@rebasepro/codegen": "0.9.1-canary.26fe4b2",
51
- "@rebasepro/common": "0.9.1-canary.26fe4b2",
52
- "@rebasepro/server": "0.9.1-canary.26fe4b2",
53
- "@rebasepro/types": "0.9.1-canary.26fe4b2",
54
- "@rebasepro/utils": "0.9.1-canary.26fe4b2"
50
+ "@rebasepro/common": "0.9.1-canary.29ed165",
51
+ "@rebasepro/server": "0.9.1-canary.29ed165",
52
+ "@rebasepro/codegen": "0.9.1-canary.29ed165",
53
+ "@rebasepro/utils": "0.9.1-canary.29ed165",
54
+ "@rebasepro/types": "0.9.1-canary.29ed165"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@hono/node-server": "^2.0.9",
@@ -123,6 +123,52 @@ describe("checkPolicyDrift", () => {
123
123
  expect(hasDrift(drift)).toBe(false);
124
124
  });
125
125
 
126
+ it("flags the pre-fix permissive tautology that every other check misses", async () => {
127
+ // A database pushed before the `policy.authenticated()` fix carries
128
+ // `auth.uid() IS NOT NULL` — true for anonymous visitors. Its name,
129
+ // roles, command and clause presence all match the corrected policy, so
130
+ // this is the only signal that catches it.
131
+ const cols = [collection("posts")];
132
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
133
+ const live = expected.map((p) => liveRow(p, {
134
+ qual: p.hasUsing ? "(auth.uid() IS NOT NULL)" : null
135
+ }));
136
+
137
+ const drift = await checkPolicyDrift(dbWith(live), cols);
138
+
139
+ expect(drift.insecure.length).toBeGreaterThan(0);
140
+ expect(hasDrift(drift)).toBe(true);
141
+ expect(drift.diverged).toHaveLength(0); // nothing else notices
142
+ expect(formatPolicyDrift(drift)).toContain("anonymous");
143
+ expect(formatPolicyDrift(drift)).toContain("db push");
144
+ });
145
+
146
+ it("clears the corrected expression, in either literal spelling", async () => {
147
+ const cols = [collection("posts")];
148
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
149
+ for (const guard of ["<> 'anonymous'::text", "<> 'anonymous'", "!= 'anonymous'"]) {
150
+ const live = expected.map((p) => liveRow(p, {
151
+ qual: p.hasUsing ? `((auth.uid() IS NOT NULL) AND ((auth.uid())::text ${guard}))` : null
152
+ }));
153
+ const drift = await checkPolicyDrift(dbWith(live), cols);
154
+ expect(drift.insecure).toHaveLength(0);
155
+ }
156
+ });
157
+
158
+ it("also flags the tautology in a WITH CHECK clause", async () => {
159
+ const cols = [collection("posts")];
160
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
161
+ const live = expected.map((p) => liveRow(p, {
162
+ with_check: p.hasWithCheck ? "(auth.uid() IS NOT NULL)" : null
163
+ }));
164
+
165
+ const drift = await checkPolicyDrift(dbWith(live), cols);
166
+
167
+ const flagged = drift.insecure.some((i) => /WITH CHECK/.test(i.reason));
168
+ // Only assert when the fixture actually had a WITH CHECK policy to carry it.
169
+ if (expected.some((p) => p.hasWithCheck)) expect(flagged).toBe(true);
170
+ });
171
+
126
172
  it("parses roles when the driver returns the raw {a,b} text form", async () => {
127
173
  const cols = [collection("tags")];
128
174
  const live = [{ schemaname: "public", tablename: "tags", policyname: "test_policy", roles: "{authenticated,anon}", cmd: "ALL", qual: "true", with_check: null }];
@@ -29,6 +29,14 @@ export interface PolicyRef {
29
29
  hasUsing: boolean;
30
30
  /** Whether a WITH CHECK clause is present at all (not what it says). */
31
31
  hasWithCheck: boolean;
32
+ /**
33
+ * The live clause text, when read from `pg_policies`. Present only for live
34
+ * policies (the expected side is parsed from DDL and does not carry it).
35
+ * Used solely for the insecure-tautology scan, not for divergence — Postgres
36
+ * rewrites this text, so it is not safe to diff against expected.
37
+ */
38
+ qual?: string | null;
39
+ withCheck?: string | null;
32
40
  }
33
41
 
34
42
  export interface PolicyDrift {
@@ -38,6 +46,19 @@ export interface PolicyDrift {
38
46
  orphaned: PolicyRef[];
39
47
  /** Same policy name, different roles or command. */
40
48
  diverged: { expected: PolicyRef; actual: PolicyRef; differences: string[] }[];
49
+ /**
50
+ * A live policy whose expression is the known-permissive tautology
51
+ * `auth.uid() IS NOT NULL` — true for anonymous visitors too, because the
52
+ * user path coerces a blank id to the `'anonymous'` sentinel. This is what
53
+ * `policy.authenticated()` used to compile to, so a database pushed before
54
+ * that fix carries it, and neither the name, roles, command nor clause
55
+ * *presence* differs from the corrected policy — the only thing that changed
56
+ * is the expression text, which this checker otherwise (correctly) ignores.
57
+ * So it is the one drift that hides from every other check here.
58
+ *
59
+ * @see reason a sentence naming the clause and what to do.
60
+ */
61
+ insecure: { policy: PolicyRef; reason: string }[];
41
62
  }
42
63
 
43
64
  export interface Queryable {
@@ -122,10 +143,30 @@ async function readLivePolicies(client: Queryable, schemas: string[]): Promise<P
122
143
  // Presence only. Postgres rewrites the text, but it does not invent or
123
144
  // drop a clause: NULL here means the policy genuinely has none.
124
145
  hasUsing: r.qual != null,
125
- hasWithCheck: r.with_check != null
146
+ hasWithCheck: r.with_check != null,
147
+ qual: r.qual,
148
+ withCheck: r.with_check
126
149
  }));
127
150
  }
128
151
 
152
+ /**
153
+ * The permissive tautology `auth.uid() IS NOT NULL`, without the
154
+ * `<> 'anonymous'` guard that makes it mean "signed in".
155
+ *
156
+ * Whitespace varies with Postgres's rewrite, so match on a collapsed form. The
157
+ * guard clause (`<> 'anonymous'`, in any spelling) is what distinguishes the
158
+ * corrected policy from the stale one, so its presence clears the text.
159
+ */
160
+ function isPermissiveAuthTautology(clause: string | null | undefined): boolean {
161
+ if (!clause) return false;
162
+ const flat = clause.toLowerCase().replace(/\s+/g, " ");
163
+ if (!/auth\.uid\(\)\s*is not null/.test(flat)) return false;
164
+ // The fix appends `AND auth.uid() <> 'anonymous'`; Postgres may store the
165
+ // literal as `'anonymous'::text`. Either spelling means it is the corrected
166
+ // policy, not the tautology.
167
+ return !/<>\s*'anonymous'/.test(flat) && !/!=\s*'anonymous'/.test(flat);
168
+ }
169
+
129
170
  const keyOf = (p: PolicyRef) => `${p.schema}.${p.table}.${p.name}`;
130
171
  const sameRoles = (a: string[], b: string[]) =>
131
172
  a.length === b.length && [...a].sort().join(",") === [...b].sort().join(",");
@@ -154,13 +195,31 @@ export async function checkPolicyDrift(
154
195
  const schemas = [...new Set(expected.map((p) => p.schema))];
155
196
  // Nothing expected means nothing to reconcile against; scanning every
156
197
  // schema would report the whole database as orphaned.
157
- if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [] };
198
+ if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [], insecure: [] };
158
199
 
159
200
  const live = await readLivePolicies(client, schemas);
160
201
  const liveByKey = new Map(live.map((p) => [keyOf(p), p]));
161
202
  const expectedByKey = new Map(expected.map((p) => [keyOf(p), p]));
162
203
 
163
- const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [] };
204
+ const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [], insecure: [] };
205
+
206
+ // Scan every live policy for the permissive tautology. This is deliberately
207
+ // independent of the name-keyed diff below: a database pushed before the
208
+ // `authenticated()` fix matches its expected policy on name, roles, command
209
+ // and clause presence, so nothing else here would flag it.
210
+ for (const p of live) {
211
+ const clause = isPermissiveAuthTautology(p.qual)
212
+ ? "USING"
213
+ : isPermissiveAuthTautology(p.withCheck) ? "WITH CHECK" : null;
214
+ if (clause) {
215
+ drift.insecure.push({
216
+ policy: p,
217
+ reason: `${clause} is \`auth.uid() IS NOT NULL\`, which is true for anonymous ` +
218
+ `visitors too — this grants access to signed-out requests. It predates the ` +
219
+ `\`policy.authenticated()\` fix; re-run \`rebase db push\` to tighten it.`
220
+ });
221
+ }
222
+ }
164
223
 
165
224
  for (const [key, want] of expectedByKey) {
166
225
  const got = liveByKey.get(key);
@@ -249,7 +308,7 @@ export async function dropOrphanedPolicies(
249
308
  }
250
309
 
251
310
  export const hasDrift = (d: PolicyDrift): boolean =>
252
- d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0;
311
+ d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0 || d.insecure.length > 0;
253
312
 
254
313
  /** Human-readable report; empty string when the database matches the config. */
255
314
  export function formatPolicyDrift(drift: PolicyDrift): string {
@@ -273,5 +332,12 @@ export function formatPolicyDrift(drift: PolicyDrift): string {
273
332
  for (const diff of d.differences) lines.push(` ${diff}`);
274
333
  }
275
334
  }
335
+ if (drift.insecure.length > 0) {
336
+ lines.push(" Insecure — a live policy grants access it should not:");
337
+ for (const i of drift.insecure) {
338
+ lines.push(` • ${i.policy.schema}.${i.policy.table} → "${i.policy.name}"`);
339
+ lines.push(` ${i.reason}`);
340
+ }
341
+ }
276
342
  return lines.join("\n");
277
343
  }