@rebasepro/server-postgres 0.0.1-canary.fc811d7 → 0.9.1-canary.09aaf62

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.
Files changed (57) hide show
  1. package/dist/PostgresBackendDriver.d.ts +25 -2
  2. package/dist/PostgresBootstrapper.d.ts +10 -0
  3. package/dist/auth/services.d.ts +16 -0
  4. package/dist/collections/buildRegistry.d.ts +27 -0
  5. package/dist/connection.d.ts +21 -0
  6. package/dist/data-transformer.d.ts +9 -2
  7. package/dist/index.es.js +2005 -2583
  8. package/dist/index.es.js.map +1 -1
  9. package/dist/module-dir.d.ts +1 -0
  10. package/dist/schema/doctor.d.ts +1 -1
  11. package/dist/security/policy-drift.d.ts +46 -5
  12. package/dist/security/rls-enforcement.d.ts +27 -2
  13. package/dist/services/FetchService.d.ts +4 -24
  14. package/dist/services/PersistService.d.ts +27 -1
  15. package/dist/services/RelationService.d.ts +34 -1
  16. package/dist/services/collection-helpers.d.ts +79 -14
  17. package/dist/services/dataService.d.ts +3 -1
  18. package/dist/services/index.d.ts +1 -1
  19. package/dist/services/realtimeService.d.ts +7 -0
  20. package/dist/services/row-pipeline.d.ts +63 -0
  21. package/package.json +15 -17
  22. package/src/PostgresBackendDriver.ts +127 -13
  23. package/src/PostgresBootstrapper.ts +68 -26
  24. package/src/auth/ensure-tables.ts +73 -11
  25. package/src/auth/services.ts +49 -19
  26. package/src/cli-helpers.ts +2 -20
  27. package/src/cli.ts +60 -0
  28. package/src/collections/buildRegistry.ts +59 -0
  29. package/src/connection.ts +61 -1
  30. package/src/data-transformer.ts +11 -9
  31. package/src/databasePoolManager.ts +2 -0
  32. package/src/module-dir.ts +7 -0
  33. package/src/schema/doctor-cli.ts +5 -1
  34. package/src/schema/doctor.ts +45 -20
  35. package/src/schema/generate-drizzle-schema-logic.ts +24 -29
  36. package/src/schema/generate-postgres-ddl-logic.ts +76 -28
  37. package/src/schema/introspect-db.ts +19 -2
  38. package/src/security/anonymous-grants.test.ts +71 -0
  39. package/src/security/policy-drift.test.ts +153 -14
  40. package/src/security/policy-drift.ts +128 -10
  41. package/src/security/rls-enforcement.ts +64 -3
  42. package/src/services/BranchService.ts +42 -10
  43. package/src/services/FetchService.ts +65 -270
  44. package/src/services/PersistService.ts +130 -14
  45. package/src/services/RelationService.ts +153 -94
  46. package/src/services/collection-helpers.ts +164 -47
  47. package/src/services/dataService.ts +3 -2
  48. package/src/services/index.ts +1 -0
  49. package/src/services/realtimeService.ts +40 -19
  50. package/src/services/row-pipeline.ts +239 -0
  51. package/src/utils/drizzle-conditions.ts +13 -0
  52. package/src/websocket.ts +4 -1
  53. package/dist/chunk-DSJWtz9O.js +0 -40
  54. package/dist/schema/auth-default-policies.d.ts +0 -10
  55. package/dist/src-Eh-CZosp.js +0 -595
  56. package/dist/src-Eh-CZosp.js.map +0 -1
  57. package/src/schema/auth-default-policies.ts +0 -125
@@ -25,6 +25,10 @@ export interface PolicyRef {
25
25
  roles: string[];
26
26
  /** SELECT / INSERT / UPDATE / DELETE / ALL. */
27
27
  command: string;
28
+ /** Whether a USING clause is present at all (not what it says). */
29
+ hasUsing: boolean;
30
+ /** Whether a WITH CHECK clause is present at all (not what it says). */
31
+ hasWithCheck: boolean;
28
32
  }
29
33
 
30
34
  export interface PolicyDrift {
@@ -40,18 +44,57 @@ export interface Queryable {
40
44
  query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;
41
45
  }
42
46
 
43
- const CREATE_POLICY = /CREATE POLICY "([^"]+)" ON "([^"]+)"\."([^"]+)"\s+AS (\w+)\s+FOR (\w+)\s+TO ([^\n]+?)(?:\s+USING|\s+WITH CHECK|;)/gi;
47
+ // The trailing group captures whichever clause follows the TO list, which is
48
+ // what tells us the clause is present.
49
+ const CREATE_POLICY = /CREATE POLICY "([^"]+)" ON "([^"]+)"\."([^"]+)"\s+AS (\w+)\s+FOR (\w+)\s+TO ([^\n]+?)(\s+USING\s*\(|\s+WITH CHECK\s*\(|;)/gi;
50
+
51
+ const WITH_CHECK_NEXT = /^\s+WITH CHECK\s*\(/i;
52
+
53
+ /**
54
+ * Index just past the `)` closing a clause whose `(` ends at `open`.
55
+ *
56
+ * Needed because a policy expression nests parens and can contain a quoted
57
+ * literal holding either character, so "find the next `)`" would stop early and
58
+ * miss the `WITH CHECK` that follows.
59
+ */
60
+ function clauseEnd(ddl: string, open: number): number {
61
+ let depth = 1;
62
+ let inQuote = false;
63
+ for (let i = open; i < ddl.length; i++) {
64
+ const c = ddl[i];
65
+ if (inQuote) {
66
+ // '' is an escaped quote inside a string, not a close.
67
+ if (c === "'") {
68
+ if (ddl[i + 1] === "'") i++;
69
+ else inQuote = false;
70
+ }
71
+ continue;
72
+ }
73
+ if (c === "'") inQuote = true;
74
+ else if (c === "(") depth++;
75
+ else if (c === ")" && --depth === 0) return i + 1;
76
+ }
77
+ return ddl.length;
78
+ }
44
79
 
45
80
  /** Parse the generated DDL rather than rebuilding the shape by hand. */
46
81
  export function parseExpectedPolicies(ddl: string): PolicyRef[] {
47
82
  const found: PolicyRef[] = [];
48
83
  for (const m of ddl.matchAll(CREATE_POLICY)) {
49
- const [, name, schema, table, , command, rolesRaw] = m;
84
+ const [, name, schema, table, , command, rolesRaw, clause] = m;
50
85
  const roles = rolesRaw
51
86
  .split(",")
52
87
  .map((r) => r.trim().replace(/^"|"$/g, ""))
53
88
  .filter(Boolean);
54
- found.push({ schema, table, name, roles, command: command.toUpperCase() });
89
+
90
+ // The generator emits USING before WITH CHECK, so what follows the TO
91
+ // list settles USING; WITH CHECK is then whatever follows that clause.
92
+ const hasUsing = /USING/i.test(clause);
93
+ const hasWithCheck = hasUsing
94
+ ? WITH_CHECK_NEXT.test(ddl.slice(clauseEnd(ddl, m.index + m[0].length)))
95
+ : /WITH CHECK/i.test(clause);
96
+
97
+ found.push({ schema, table, name, roles, command: command.toUpperCase(), hasUsing, hasWithCheck });
55
98
  }
56
99
  return found;
57
100
  }
@@ -59,8 +102,9 @@ export function parseExpectedPolicies(ddl: string): PolicyRef[] {
59
102
  async function readLivePolicies(client: Queryable, schemas: string[]): Promise<PolicyRef[]> {
60
103
  const { rows } = await client.query<{
61
104
  schemaname: string; tablename: string; policyname: string; roles: string[] | string; cmd: string;
105
+ qual: string | null; with_check: string | null;
62
106
  }>(
63
- `SELECT schemaname, tablename, policyname, roles, cmd
107
+ `SELECT schemaname, tablename, policyname, roles, cmd, qual, with_check
64
108
  FROM pg_policies
65
109
  WHERE schemaname = ANY($1)`,
66
110
  [schemas]
@@ -74,7 +118,11 @@ async function readLivePolicies(client: Queryable, schemas: string[]): Promise<P
74
118
  roles: Array.isArray(r.roles)
75
119
  ? r.roles
76
120
  : String(r.roles ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean),
77
- command: (r.cmd ?? "ALL").toUpperCase()
121
+ command: (r.cmd ?? "ALL").toUpperCase(),
122
+ // Presence only. Postgres rewrites the text, but it does not invent or
123
+ // drop a clause: NULL here means the policy genuinely has none.
124
+ hasUsing: r.qual != null,
125
+ hasWithCheck: r.with_check != null
78
126
  }));
79
127
  }
80
128
 
@@ -85,11 +133,18 @@ const sameRoles = (a: string[], b: string[]) =>
85
133
  /**
86
134
  * Diff expected against live.
87
135
  *
88
- * Compares names, roles and command only — all exact values. Policy
89
- * *expressions* are deliberately not compared: Postgres rewrites `qual`/
90
- * `with_check` when storing them (parenthesising, casting, schema-qualifying),
91
- * so text comparison reports drift that does not exist, and a check that cries
92
- * wolf gets ignored. Roles alone catch the failure this exists for.
136
+ * Compares names, roles, command, and whether each clause exists — all exact
137
+ * values. Policy expression *text* is deliberately not compared: Postgres
138
+ * rewrites `qual`/`with_check` when storing them (parenthesising, casting,
139
+ * schema-qualifying), so text comparison reports drift that does not exist, and
140
+ * a check that cries wolf gets ignored.
141
+ *
142
+ * Presence is not text, though. A NULL `qual` is not a rewrite of an
143
+ * expression, it is the absence of one, and absence has no false-positive risk:
144
+ * either the generator emitted a clause or it did not. That distinction is worth
145
+ * the extra comparison — a production database was found with a SELECT policy
146
+ * whose `qual` was NULL, matching on every field this checked and denying 100%
147
+ * of reads. The same blindness would hide a policy that fails open.
93
148
  */
94
149
  export async function checkPolicyDrift(
95
150
  client: Queryable,
@@ -120,6 +175,13 @@ export async function checkPolicyDrift(
120
175
  if (want.command !== got.command) {
121
176
  differences.push(`command: expected ${want.command}, database has ${got.command}`);
122
177
  }
178
+ for (const clause of ["USING", "WITH CHECK"] as const) {
179
+ const key = clause === "USING" ? "hasUsing" : "hasWithCheck";
180
+ if (want[key] === got[key]) continue;
181
+ differences.push(want[key]
182
+ ? `${clause}: expected an expression, database has none — this policy matches no rows`
183
+ : `${clause}: expected none, database has an expression`);
184
+ }
123
185
  if (differences.length > 0) drift.diverged.push({ expected: want, actual: got, differences });
124
186
  }
125
187
 
@@ -130,6 +192,62 @@ export async function checkPolicyDrift(
130
192
  return drift;
131
193
  }
132
194
 
195
+ /**
196
+ * Does this name look like one the generator produced for this table?
197
+ *
198
+ * Unnamed rules compile to `<table>_<op>_<sha1[0:7]>` (plus `_<idx>` when one
199
+ * rule spans several operations), and the hash covers the rule's semantics — so
200
+ * *editing* a rule renames its policy. The policy under the old name is left
201
+ * behind by `db push`, which only DROPs the names it is about to CREATE, and
202
+ * Postgres ORs PERMISSIVE policies together: a superseded `USING (true)` keeps
203
+ * granting everything no matter how tight its replacement is.
204
+ *
205
+ * Matching the shape is what makes dropping them safe. A hand-written policy
206
+ * would have to collide with a 7-hex digest to be mistaken for generated one;
207
+ * a policy named anything else is left alone and merely reported, because a
208
+ * custom name is indistinguishable from one someone wrote in SQL on purpose.
209
+ */
210
+ export function isGeneratedPolicyName(name: string, table: string): boolean {
211
+ return new RegExp(`^${table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}_(select|insert|update|delete|all)_[0-9a-f]{7}(_\\d+)?$`)
212
+ .test(name);
213
+ }
214
+
215
+ export interface OrphanCleanup {
216
+ /** Superseded generated policies that were dropped. */
217
+ dropped: PolicyRef[];
218
+ /** Orphans left in place because their names are not generator-shaped. */
219
+ kept: PolicyRef[];
220
+ }
221
+
222
+ /**
223
+ * Drop the policies an earlier push superseded but never removed.
224
+ *
225
+ * Only touches tables the collections describe — a table with no expected
226
+ * policy is not ours to reconcile, and scanning by schema alone would sweep up
227
+ * policies belonging to something else sharing the database.
228
+ */
229
+ export async function dropOrphanedPolicies(
230
+ client: Queryable,
231
+ drift: PolicyDrift,
232
+ collections: CollectionConfig[]
233
+ ): Promise<OrphanCleanup> {
234
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));
235
+ const managed = new Set(expected.map((p) => `${p.schema}.${p.table}`));
236
+
237
+ const cleanup: OrphanCleanup = { dropped: [], kept: [] };
238
+ for (const p of drift.orphaned) {
239
+ if (!managed.has(`${p.schema}.${p.table}`) || !isGeneratedPolicyName(p.name, p.table)) {
240
+ cleanup.kept.push(p);
241
+ continue;
242
+ }
243
+ // Identifiers are quoted, and the name came from pg_policies rather than
244
+ // from user input, so it is already a valid identifier.
245
+ await client.query(`DROP POLICY IF EXISTS "${p.name}" ON "${p.schema}"."${p.table}"`);
246
+ cleanup.dropped.push(p);
247
+ }
248
+ return cleanup;
249
+ }
250
+
133
251
  export const hasDrift = (d: PolicyDrift): boolean =>
134
252
  d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0;
135
253
 
@@ -1,4 +1,6 @@
1
1
  import { sql as drizzleSql, SQL } from "drizzle-orm";
2
+ import { ANONYMOUS_USER_ID, PolicyExpression, SecurityRule } from "@rebasepro/types";
3
+ import { AnonymousGrantRisk, findAnonymousGrants, securityRuleToConditions } from "@rebasepro/common";
2
4
  import { logger } from "@rebasepro/server";
3
5
 
4
6
  /**
@@ -200,11 +202,13 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
200
202
  * treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
201
203
  * is `NULLIF(current_setting('app.user_id'), '')` — so an EMPTY user id would
202
204
  * be read as NULL and silently escalate a user request to server privileges.
203
- * Coerce empty/blank ids to a sentinel here, at the single chokepoint, rather
204
- * than trusting every caller (e.g. realtime subscription auth) to do it.
205
+ * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
206
+ * rather than trusting every caller (e.g. realtime subscription auth) to do it.
207
+ * That sentinel is exported from `@rebasepro/types` because it leaks into rule
208
+ * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
205
209
  */
206
210
  export async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {
207
- const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : "anonymous";
211
+ const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : ANONYMOUS_USER_ID;
208
212
  const normalizedRoles = auth.roles.map((r: unknown) =>
209
213
  typeof r === "string" ? r : (r as Record<string, unknown>)?.id ?? String(r)
210
214
  );
@@ -226,6 +230,63 @@ const FOREIGN_CONVENTION_ROLES: Record<string, string> = {
226
230
  service_role: "Supabase"
227
231
  };
228
232
 
233
+ /**
234
+ * Warn about rules that read as "signed-in users only" but admit anonymous
235
+ * callers — `auth.uid() IS NOT NULL`, or a comparison against another
236
+ * platform's magic user id such as `'anon'`.
237
+ *
238
+ * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
239
+ * of the same habit. A foreign `pgRoles` value makes a policy unreachable and
240
+ * the table reads empty — loud, and that guard throws. These do the opposite:
241
+ * the rule compiles to a grant, and nothing looks wrong until the data is
242
+ * already public.
243
+ *
244
+ * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
245
+ * serving traffic today: refusing to boot would take an app offline to report a
246
+ * problem it already has, and on the read path it would take it offline
247
+ * *because* its data was exposed. Rewriting the author's SQL is not an option
248
+ * either — this is the escape hatch whose whole promise is that it means what it
249
+ * says. So: say so, loudly, and leave the rule alone.
250
+ */
251
+ export function warnOnAnonymousGrants(
252
+ collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]
253
+ ): void {
254
+ // Grouped by the mistake, not by the rule: one habit typically repeats
255
+ // across every collection an author wrote, and a per-rule list would repeat
256
+ // the same paragraph dozens of times and get skimmed.
257
+ const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();
258
+
259
+ for (const collection of collections) {
260
+ for (const rule of collection.securityRules ?? []) {
261
+ const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
262
+ const risks = [usingExpr, withCheckExpr]
263
+ .filter((e): e is PolicyExpression => e !== null)
264
+ .flatMap(findAnonymousGrants);
265
+
266
+ for (const risk of risks) {
267
+ const key = `${risk.pattern}:${risk.detail}`;
268
+ const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
269
+ const entry = byRisk.get(key) ?? { risk, sites: [] };
270
+ if (!entry.sites.includes(site)) entry.sites.push(site);
271
+ byRisk.set(key, entry);
272
+ }
273
+ }
274
+ }
275
+
276
+ if (byRisk.size === 0) return;
277
+
278
+ const problems = [...byRisk.values()].map(({ risk, sites }) =>
279
+ ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`
280
+ );
281
+
282
+ logger.warn(
283
+ `Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +
284
+ `client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +
285
+ `true for everyone:\n\n` +
286
+ problems.join("\n\n") + "\n"
287
+ );
288
+ }
289
+
229
290
  /**
230
291
  * Reject `pgRoles` that this server can never satisfy.
231
292
  *
@@ -11,10 +11,45 @@ import { sql } from "drizzle-orm";
11
11
  import { BranchInfo } from "@rebasepro/types";
12
12
  import { DrizzleClient } from "../interfaces";
13
13
  import { DatabasePoolManager } from "../databasePoolManager";
14
+ import { extractPgError, extractCauseMessage } from "../utils/pg-error-utils";
14
15
 
15
16
  /** Internal prefix applied to branch database names to avoid collisions. */
16
17
  const BRANCH_DB_PREFIX = "rb_";
17
18
 
19
+ /** `duplicate_database` — the target database name is already taken. */
20
+ const PG_DUPLICATE_DATABASE = "42P04";
21
+
22
+ /** `object_in_use` — the database still has connections attached. */
23
+ const PG_OBJECT_IN_USE = "55006";
24
+
25
+ /**
26
+ * Describe a failed branch DDL statement in terms a user can act on.
27
+ *
28
+ * Drizzle reports failures as `Failed query: <sql> params:` and hides the real
29
+ * PostgreSQL error in the `cause` chain, so matching on `err.message` never sees
30
+ * the actual problem. Match on the PG error code instead — it survives wrapping
31
+ * and, unlike the message text, is not locale-dependent.
32
+ */
33
+ function describeBranchDdlError(err: unknown, fallbackContext: string): Error {
34
+ const pgError = extractPgError(err);
35
+
36
+ if (pgError?.code === PG_DUPLICATE_DATABASE) {
37
+ return new Error(`Database "${fallbackContext}" already exists on the server. Choose a different branch name.`);
38
+ }
39
+ if (pgError?.code === PG_OBJECT_IN_USE) {
40
+ return new Error(
41
+ `Cannot complete the operation: the database "${fallbackContext}" has active connections. ` +
42
+ "Close other clients or connections and try again."
43
+ );
44
+ }
45
+
46
+ // Unknown failure: surface the real PG message rather than the Drizzle
47
+ // wrapper, which would otherwise show the raw SQL and no reason at all.
48
+ const detail = pgError?.message ?? extractCauseMessage(err);
49
+ if (detail) return new Error(detail);
50
+ return err instanceof Error ? err : new Error(String(err));
51
+ }
52
+
18
53
  /** Fully-qualified metadata table in the rebase schema. */
19
54
  const BRANCHES_TABLE = "rebase.branches";
20
55
 
@@ -109,18 +144,15 @@ export class BranchService {
109
144
  sql.raw(`CREATE DATABASE "${safeDbName}" TEMPLATE "${safeSourceDb}"`)
110
145
  );
111
146
  } catch (err) {
112
- const msg = err instanceof Error ? err.message : String(err);
113
- if (msg.includes("already exists")) {
114
- throw new Error(`Database "${dbName}" already exists on the server. Choose a different branch name.`);
115
- }
116
- // If template fails due to active connections, provide a helpful error
117
- if (msg.includes("being accessed by other users")) {
147
+ const pgError = extractPgError(err);
148
+ if (pgError?.code === PG_OBJECT_IN_USE) {
149
+ // The template not the new database is the one still in use.
118
150
  throw new Error(
119
151
  `Cannot create branch: the source database "${sourceDb}" has active connections. ` +
120
152
  "Close other clients or connections and try again."
121
153
  );
122
154
  }
123
- throw err;
155
+ throw describeBranchDdlError(err, dbName);
124
156
  }
125
157
 
126
158
  // Record metadata in the default database
@@ -166,14 +198,14 @@ export class BranchService {
166
198
  try {
167
199
  await this.db.execute(sql.raw(`DROP DATABASE "${safeDbName}"`));
168
200
  } catch (err) {
169
- const msg = err instanceof Error ? err.message : String(err);
170
- if (msg.includes("being accessed by other users")) {
201
+ const pgError = extractPgError(err);
202
+ if (pgError?.code === PG_OBJECT_IN_USE) {
171
203
  throw new Error(
172
204
  `Cannot delete branch "${sanitizedName}": the database has active connections. ` +
173
205
  "Close other clients and try again."
174
206
  );
175
207
  }
176
- throw err;
208
+ throw describeBranchDdlError(err, dbName);
177
209
  }
178
210
 
179
211
  // Remove metadata