@rebasepro/common 0.9.0 → 0.9.1-canary.0fce67c

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.
@@ -0,0 +1,353 @@
1
+ import {
2
+ CollectionConfig,
3
+ PolicyExpression,
4
+ PolicyOperand,
5
+ Relation,
6
+ SecurityRule,
7
+ isPostgresCollectionConfig,
8
+ policy
9
+ } from "@rebasepro/types";
10
+ import { getPolicyOperations } from "@rebasepro/utils";
11
+ import { getTableName } from "./relations";
12
+ import { resolveCollectionRelations } from "./relations";
13
+ import { securityRuleToConditions } from "./policy/securityRuleToConditions";
14
+
15
+ /**
16
+ * RLS derivation for many-to-many junction tables.
17
+ *
18
+ * A `through` relation makes the generator create a table nobody declared as a
19
+ * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind
20
+ * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,
21
+ * so with the endpoints locked down, any signed-up user could still read or wipe
22
+ * every edge between them. There is also nowhere in the config to write rules
23
+ * for a junction, so the author could not even fix it by hand.
24
+ *
25
+ * The architecture here is that a junction's security is *derived*, never
26
+ * hand-written:
27
+ *
28
+ * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every
29
+ * collection gets, so the invariant holds again: every table the generator
30
+ * creates is default-deny, and rules only broaden.
31
+ *
32
+ * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint
33
+ * rows are visible — two correlated `EXISTS` subqueries. The subqueries run
34
+ * under the caller's role, so each endpoint's own RLS filters them: junction
35
+ * visibility delegates to the endpoints' policies, whatever they become,
36
+ * with nothing duplicated. A public blog keeps rendering its tags; a private
37
+ * CRM's edges are exactly as hidden as its rows.
38
+ *
39
+ * 3. **Writes follow the owning side's update rules.** Linking or unlinking an
40
+ * edge *is* an edit of the owning row — tagging a post is editing the post —
41
+ * so edge writes inherit the declaring collection's explicit permissive
42
+ * `update` rules, each wrapped in an `EXISTS` against the owning row. Where
43
+ * a rule cannot be embedded faithfully (see below) it is dropped, so the
44
+ * failure mode is always *too locked*, never open. Explicit **restrictive**
45
+ * update rules are inherited as restrictive junction rules; if one of them
46
+ * cannot be embedded, the whole derived write grant for that side is
47
+ * suppressed — granting without the author's gate would be looser than the
48
+ * parent itself.
49
+ *
50
+ * **Embeddability.** A parent rule is embedded by moving its condition inside
51
+ * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.
52
+ * In that scope, `field` operands bind to the parent — which is what the author
53
+ * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind
54
+ * to the RLS row, which is now the junction, not the parent the author wrote
55
+ * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`
56
+ * (equivalent to `field` outside a subquery) is rewritten to `field`; an
57
+ * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies
58
+ * the rule.
59
+ *
60
+ * Injected parent defaults are never inherited — the junction's own baseline
61
+ * already covers the server/admin plane, and an auth collection's restrictive
62
+ * `require_admin_write` gate exists to protect privileged parent *columns*,
63
+ * which an edge write cannot touch. Inheriting it would stop users managing
64
+ * e.g. their own interests through a `users_interests` junction for no gain.
65
+ *
66
+ * Everything flows through the shared naming machinery, so the Studio
67
+ * recognises these policies as generated instead of offering to "import" them.
68
+ */
69
+
70
+ /** One side of a junction: the collection and the FK column pointing at it. */
71
+ export interface JunctionEndpoint {
72
+ collection: CollectionConfig;
73
+ /** Junction column holding this endpoint's key. */
74
+ junctionColumn: string;
75
+ }
76
+
77
+ /** A collection that declares the `through` relation (owns the edge semantics). */
78
+ export interface JunctionDeclaringSide extends JunctionEndpoint {
79
+ relation: Relation;
80
+ }
81
+
82
+ export interface JunctionSpec {
83
+ /** Bare table name (schema stripped). */
84
+ table: string;
85
+ /** Schema the junction is created in — mirrors the CREATE TABLE path. */
86
+ schema: string;
87
+ /** The two endpoints, in [source, target] order of the first declaring relation. */
88
+ endpoints: [JunctionEndpoint, JunctionEndpoint];
89
+ /** Every collection that declares a relation through this table. */
90
+ declaringSides: JunctionDeclaringSide[];
91
+ }
92
+
93
+ // Mirrors auth-default-policies: the server context or an admin.
94
+ const SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(
95
+ policy.serverContext(),
96
+ policy.rolesOverlap(["admin"])
97
+ );
98
+
99
+ /**
100
+ * Walk every collection's resolved relations and aggregate the junction tables
101
+ * they declare. Two collections may declare the same junction from opposite
102
+ * sides (posts→tags and tags→posts through `posts_tags`); both become
103
+ * `declaringSides` of one spec, so derived write grants consider both.
104
+ */
105
+ export function resolveJunctionSpecs(collections: CollectionConfig[]): Map<string, JunctionSpec> {
106
+ const specs = new Map<string, JunctionSpec>();
107
+
108
+ for (const collection of collections) {
109
+ const resolved = resolveCollectionRelations(collection);
110
+ for (const relation of Object.values(resolved)) {
111
+ if (!relation.through) continue;
112
+
113
+ const targetCollection: CollectionConfig | undefined =
114
+ typeof relation.target === "function" ? relation.target() : undefined;
115
+ if (!targetCollection) continue;
116
+
117
+ const rawName = relation.through.table;
118
+ // The CREATE TABLE path strips a schema prefix from the name but
119
+ // still creates in "public"; the policies must target the same
120
+ // table, so mirror that behaviour exactly.
121
+ const table = rawName.includes(".") ? rawName.split(".").pop()! : rawName;
122
+ const schema = "public";
123
+
124
+ const source: JunctionDeclaringSide = {
125
+ collection,
126
+ junctionColumn: relation.through.sourceColumn,
127
+ relation
128
+ };
129
+ const target: JunctionEndpoint = {
130
+ collection: targetCollection,
131
+ junctionColumn: relation.through.targetColumn
132
+ };
133
+
134
+ const existing = specs.get(table);
135
+ if (!existing) {
136
+ specs.set(table, {
137
+ table,
138
+ schema,
139
+ endpoints: [source, target],
140
+ declaringSides: [source]
141
+ });
142
+ } else if (!existing.declaringSides.some(s => s.collection === collection)) {
143
+ existing.declaringSides.push(source);
144
+ }
145
+ }
146
+ }
147
+
148
+ return specs;
149
+ }
150
+
151
+ /**
152
+ * A synthetic CollectionConfig standing in for the junction during policy
153
+ * compilation and naming. Its two FK columns carry explicit `columnName`s so
154
+ * `outerField` operands resolve to the exact columns the CREATE TABLE emitted,
155
+ * whatever their casing.
156
+ */
157
+ export function getJunctionCollectionConfig(spec: JunctionSpec): CollectionConfig {
158
+ const properties: Record<string, unknown> = {};
159
+ for (const endpoint of spec.endpoints) {
160
+ properties[endpoint.junctionColumn] = {
161
+ type: "string",
162
+ columnName: endpoint.junctionColumn
163
+ };
164
+ }
165
+ return {
166
+ slug: spec.table,
167
+ name: spec.table,
168
+ table: spec.table,
169
+ schema: spec.schema,
170
+ properties
171
+ } as unknown as CollectionConfig;
172
+ }
173
+
174
+ /** The property marked as the row id (falls back to `id`). */
175
+ function getIdPropertyName(collection: CollectionConfig): string {
176
+ for (const [name, prop] of Object.entries(collection.properties ?? {})) {
177
+ if (prop && typeof prop === "object" && "isId" in prop && (prop as { isId?: unknown }).isId) {
178
+ return name;
179
+ }
180
+ }
181
+ return "id";
182
+ }
183
+
184
+ /** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */
185
+ function existsEndpoint(endpoint: JunctionEndpoint, extra?: PolicyExpression): PolicyExpression {
186
+ const correlation = policy.compare(
187
+ policy.field(getIdPropertyName(endpoint.collection)),
188
+ "eq",
189
+ policy.outerField(endpoint.junctionColumn)
190
+ );
191
+ return policy.existsIn({
192
+ collection: endpoint.collection.slug,
193
+ where: extra ? policy.and(correlation, extra) : correlation
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Whether a parent-rule expression keeps its meaning when moved inside the
199
+ * junction's `EXISTS` subquery — and the re-scoped copy if it does.
200
+ *
201
+ * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL
202
+ * anywhere (its `{column}` placeholders would bind to the junction), or an
203
+ * `outerField` inside a nested `existsIn` (it would bind to the junction while
204
+ * the author meant the parent, and no operand can express "the middle scope").
205
+ * Top-level `outerField`s are rewritten to `field`, which is what they meant.
206
+ */
207
+ export function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {
208
+ switch (expr.kind) {
209
+ case "raw":
210
+ return null;
211
+ case "and":
212
+ case "or": {
213
+ const parts: PolicyExpression[] = [];
214
+ for (const child of expr.operands) {
215
+ const embedded = embedParentExpression(child, depth);
216
+ if (!embedded) return null;
217
+ parts.push(embedded);
218
+ }
219
+ return expr.kind === "and" ? policy.and(...parts) : policy.or(...parts);
220
+ }
221
+ case "not": {
222
+ const embedded = embedParentExpression(expr.operand, depth);
223
+ return embedded ? policy.not(embedded) : null;
224
+ }
225
+ case "existsIn": {
226
+ const where = embedParentExpression(expr.where, depth + 1);
227
+ return where ? policy.existsIn({ collection: expr.collection, where }) : null;
228
+ }
229
+ case "compare": {
230
+ const left = embedOperand(expr.left, depth);
231
+ const right = embedOperand(expr.right, depth);
232
+ if (!left || !right) return null;
233
+ return { ...expr, left, right };
234
+ }
235
+ default:
236
+ // Leaf expressions with no field references (true, false,
237
+ // serverContext, authenticated, rolesOverlap, rolesContain) are
238
+ // position-independent.
239
+ return expr;
240
+ }
241
+ }
242
+
243
+ /** Re-scope an operand, or return `null` if its binding cannot be preserved. */
244
+ function embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {
245
+ if (operand.kind === "outerField") {
246
+ // Outside a subquery, outerField ≡ field: the author meant their own
247
+ // row, which after embedding is the EXISTS's joined table → field.
248
+ if (depth === 0) return policy.field(operand.name);
249
+ // Inside the author's own existsIn it meant the parent row; after
250
+ // embedding it would bind to the junction. Not expressible.
251
+ return null;
252
+ }
253
+ return operand;
254
+ }
255
+
256
+ /** Does the rule cover the `update` operation? */
257
+ function coversUpdate(rule: SecurityRule): boolean {
258
+ return getPolicyOperations(rule).some(op => op === "update" || op === "all");
259
+ }
260
+
261
+ /**
262
+ * The full derived policy set for a junction table: the locked server/admin
263
+ * baseline, the endpoint-visibility read grant, inherited write grants, and
264
+ * inherited restrictive gates. Returns `[]` when every declaring collection set
265
+ * `disableDefaultPolicies` — the junction is then the author's to police, and
266
+ * stays locked (RLS is still enabled) until they write policies for it.
267
+ */
268
+ export function getJunctionSecurityRules(spec: JunctionSpec): SecurityRule[] {
269
+ if (spec.declaringSides.every(side => side.collection.disableDefaultPolicies)) {
270
+ return [];
271
+ }
272
+
273
+ const rules: SecurityRule[] = [];
274
+
275
+ // 1. Locked baseline — same shape and naming as every collection's.
276
+ rules.push({
277
+ name: `${spec.table}_default_admin_read`,
278
+ operations: ["select"],
279
+ condition: SERVER_OR_ADMIN_EXPR
280
+ });
281
+ rules.push({
282
+ name: `${spec.table}_default_admin_write`,
283
+ operations: ["insert", "update", "delete"],
284
+ condition: SERVER_OR_ADMIN_EXPR,
285
+ check: SERVER_OR_ADMIN_EXPR
286
+ });
287
+
288
+ // 2. Reads follow the endpoints: the edge is visible iff both rows are.
289
+ // The EXISTS subqueries run under the caller's role, so each endpoint's
290
+ // own RLS applies inside them — visibility is delegated, not copied.
291
+ rules.push({
292
+ name: `${spec.table}_default_edge_read`,
293
+ operations: ["select"],
294
+ condition: policy.and(
295
+ existsEndpoint(spec.endpoints[0]),
296
+ existsEndpoint(spec.endpoints[1])
297
+ )
298
+ });
299
+
300
+ // 3. Writes follow the owning side's explicit update rules.
301
+ const writeGrants: PolicyExpression[] = [];
302
+ for (const side of spec.declaringSides) {
303
+ const explicitRules = (isPostgresCollectionConfig(side.collection)
304
+ ? side.collection.securityRules
305
+ : undefined) ?? [];
306
+ const updateRules = explicitRules.filter(coversUpdate);
307
+
308
+ const permissive = updateRules.filter(r => r.mode !== "restrictive");
309
+ const restrictive = updateRules.filter(r => r.mode === "restrictive");
310
+
311
+ // Embed the restrictive gates first: if any of them cannot be carried
312
+ // over, granting writes from this side would be looser than the parent
313
+ // itself allows — so the whole side's grant is suppressed.
314
+ const embeddedGates: PolicyExpression[] = [];
315
+ let gatesEmbeddable = true;
316
+ for (const gate of restrictive) {
317
+ const using = securityRuleToConditions(gate).usingExpr;
318
+ const embedded = using ? embedParentExpression(using) : null;
319
+ if (!embedded) {
320
+ gatesEmbeddable = false;
321
+ break;
322
+ }
323
+ embeddedGates.push(embedded);
324
+ }
325
+ if (!gatesEmbeddable) continue;
326
+
327
+ const grants: PolicyExpression[] = [];
328
+ for (const rule of permissive) {
329
+ const using = securityRuleToConditions(rule).usingExpr;
330
+ const embedded = using ? embedParentExpression(using) : null;
331
+ if (embedded) grants.push(embedded);
332
+ }
333
+ if (grants.length === 0) continue;
334
+
335
+ // "May update the owning row": any permissive grant, AND every gate.
336
+ const condition = embeddedGates.length > 0
337
+ ? policy.and(policy.or(...grants), ...embeddedGates)
338
+ : policy.or(...grants);
339
+
340
+ writeGrants.push(existsEndpoint(side, condition));
341
+ }
342
+
343
+ if (writeGrants.length > 0) {
344
+ rules.push({
345
+ name: `${spec.table}_default_edge_write`,
346
+ operations: ["insert", "update", "delete"],
347
+ condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),
348
+ check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)
349
+ });
350
+ }
351
+
352
+ return rules;
353
+ }
@@ -1,4 +1,4 @@
1
- import { Entity, PolicyCompareOperator, PolicyExpression, PolicyOperand } from "@rebasepro/types";
1
+ import { ANONYMOUS_USER_ID, Entity, PolicyCompareOperator, PolicyExpression, PolicyOperand } from "@rebasepro/types";
2
2
 
3
3
  /**
4
4
  * Result of evaluating a policy client-side. `"unknown"` means the expression
@@ -15,7 +15,14 @@ export type TriState = boolean | "unknown";
15
15
  * being evaluated (or none, for collection-level gating).
16
16
  */
17
17
  export interface PolicyEvalContext {
18
- /** The current user's id, or null/undefined when unauthenticated. */
18
+ /**
19
+ * The current user's id, or null/undefined when no user is signed in.
20
+ *
21
+ * Null here means *anonymous visitor*, not "server context" — a client is
22
+ * never the server context. `authUid` operands therefore resolve to
23
+ * {@link ANONYMOUS_USER_ID} rather than `null`, matching the `auth.uid()`
24
+ * the database would see for the same request.
25
+ */
19
26
  uid?: string | null;
20
27
  /** The current user's application roles. */
21
28
  roles?: string[];
@@ -54,7 +61,12 @@ export function evaluatePolicy(expr: PolicyExpression, ctx: PolicyEvalContext):
54
61
  return expr.roles.every(r => r === "public" || userRoles.includes(r));
55
62
  }
56
63
  case "authenticated":
57
- return ctx.uid != null;
64
+ return ctx.uid != null && ctx.uid !== ANONYMOUS_USER_ID;
65
+ case "serverContext":
66
+ // A client is never the server context. Postgres decides this by
67
+ // `auth.uid() IS NULL`, which a client request can never produce:
68
+ // the driver substitutes ANONYMOUS_USER_ID for a missing id.
69
+ return false;
58
70
  case "existsIn":
59
71
  // A membership subquery cannot be run client-side — server-authoritative.
60
72
  return "unknown";
@@ -92,7 +104,11 @@ function resolveOperand(operand: PolicyOperand, ctx: PolicyEvalContext): Resolve
92
104
  case "literal":
93
105
  return { known: true, value: operand.value };
94
106
  case "authUid":
95
- return { known: true, value: ctx.uid ?? null };
107
+ // The sentinel, not null: `auth.uid()` is never NULL for a request
108
+ // that came from a client, so comparing against null here would
109
+ // disagree with the database on exactly the rules that test for it
110
+ // (e.g. `auth.uid() <> 'anonymous'`).
111
+ return { known: true, value: ctx.uid ?? ANONYMOUS_USER_ID };
96
112
  case "authRoles":
97
113
  return { known: true, value: ctx.roles ?? [] };
98
114
  case "field":
@@ -1,3 +1,4 @@
1
1
  export * from "./securityRuleToConditions";
2
+ export * from "./sqlToPolicy";
2
3
  export * from "./policyToPostgres";
3
4
  export * from "./evaluatePolicy";
@@ -1,4 +1,4 @@
1
- import { CollectionConfig, PolicyExpression, PolicyOperand, PolicyCompareOperator, Property, ExistsInPolicyExpression } from "@rebasepro/types";
1
+ import { ANONYMOUS_USER_ID, CollectionConfig, PolicyExpression, PolicyOperand, PolicyCompareOperator, Property, ExistsInPolicyExpression } from "@rebasepro/types";
2
2
  import { toSnakeCase } from "@rebasepro/utils";
3
3
  import { getTableName } from "../relations";
4
4
 
@@ -68,23 +68,41 @@ function compile(expr: PolicyExpression, scope: CompileScope): string {
68
68
  ? "false"
69
69
  : expr.operands.map(o => `(${compile(o, scope)})`).join(" OR ");
70
70
  case "not":
71
- // Render the common `auth.uid() IS NULL` (unauthenticated) form directly.
72
- if (expr.operand.kind === "authenticated") return "auth.uid() IS NULL";
73
71
  return `NOT (${compile(expr.operand, scope)})`;
74
- case "compare":
75
- return `${operandToSql(expr.left, scope)} ${COMPARE_SQL[expr.op]} ${operandToSql(expr.right, scope)}`;
72
+ case "compare": {
73
+ // `auth.uid()` returns text; cast the column side so uuid / integer
74
+ // id columns compare cleanly instead of failing with
75
+ // "operator does not exist: uuid = text" at CREATE POLICY time.
76
+ const castForAuthUid = (operand: PolicyOperand, sqlText: string, other: PolicyOperand): string =>
77
+ other.kind === "authUid" && (operand.kind === "field" || operand.kind === "outerField")
78
+ ? `(${sqlText})::text`
79
+ : sqlText;
80
+ const leftSql = castForAuthUid(expr.left, operandToSql(expr.left, scope), expr.right);
81
+ const rightSql = castForAuthUid(expr.right, operandToSql(expr.right, scope), expr.left);
82
+ return `${leftSql} ${COMPARE_SQL[expr.op]} ${rightSql}`;
83
+ }
76
84
  case "rolesOverlap":
77
85
  return `string_to_array(auth.roles(), ',') && ${rolesArraySql(expr.roles)}`;
78
86
  case "rolesContain":
79
87
  return `string_to_array(auth.roles(), ',') @> ${rolesArraySql(expr.roles)}`;
80
88
  case "authenticated":
81
- return "auth.uid() IS NOT NULL";
89
+ // `IS NOT NULL` alone is a tautology on the user path: every
90
+ // user-context request sets `app.user_id`, and an anonymous one sets
91
+ // it to the sentinel. Excluding the sentinel is what makes this mean
92
+ // "signed in" rather than "anyone at all".
93
+ return `auth.uid() IS NOT NULL AND auth.uid() <> ${quoteLiteral(ANONYMOUS_USER_ID)}`;
94
+ case "serverContext":
95
+ // Only the built-in server flows leave `app.user_id` unset.
96
+ return "auth.uid() IS NULL";
82
97
  case "existsIn":
83
98
  return compileExistsIn(expr, scope);
84
99
  case "raw":
85
- // Full-power escape hatch: `{column}` references resolve to the bare
86
- // column name (matching the previous raw-SQL behavior).
87
- return expr.sql.replace(/\{(\w+)\}/g, (_, col) => col);
100
+ // Full-power escape hatch: `{column}` denotes a column of the outer
101
+ // RLS row. It must be table-qualified, not bare: raw SQL may open its
102
+ // own subquery over the same table, and there a bare name binds to the
103
+ // inner scope, collapsing `m.x = {x}` into the tautology `m.x = m.x`.
104
+ return expr.sql.replace(/\{(\w+)\}/g, (_, col) =>
105
+ `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);
88
106
  }
89
107
  }
90
108
 
@@ -101,9 +119,7 @@ function compileExistsIn(expr: ExistsInPolicyExpression, scope: CompileScope): s
101
119
 
102
120
  // `outerField` inside the subquery must be qualified with the outer table,
103
121
  // otherwise a bare column name would bind to the joined table instead.
104
- const outerTable = scope.outerCollection ? getTableName(scope.outerCollection) : undefined;
105
- const outerSchema = schemaOf(scope.outerCollection) ?? "public";
106
- const outerPrefix = outerTable ? `"${outerSchema}"."${outerTable}".` : "";
122
+ const outerPrefix = outerQualifier(scope);
107
123
 
108
124
  const innerScope: CompileScope = {
109
125
  fieldCollection: join,
@@ -140,6 +156,16 @@ function operandToSql(operand: PolicyOperand, scope: CompileScope): string {
140
156
  }
141
157
  }
142
158
 
159
+ /**
160
+ * SQL prefix that qualifies a column of the outer RLS row (`"schema"."table".`),
161
+ * or `""` when the collection is unknown.
162
+ */
163
+ function outerQualifier(scope: CompileScope): string {
164
+ const table = scope.outerCollection ? getTableName(scope.outerCollection) : undefined;
165
+ if (!table) return "";
166
+ return `"${schemaOf(scope.outerCollection) ?? "public"}"."${table}".`;
167
+ }
168
+
143
169
  function schemaOf(collection?: CollectionConfig): string | undefined {
144
170
  return (collection as { schema?: string } | undefined)?.schema || undefined;
145
171
  }