@rebasepro/server-postgres 0.9.1-canary.ed943fa → 0.9.1-canary.f0ac103
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.es.js +3 -22
- package/dist/index.es.js.map +1 -1
- package/dist/schema/doctor.d.ts +1 -1
- package/dist/security/policy-drift.d.ts +0 -30
- package/package.json +6 -7
- package/src/cli.ts +0 -60
- package/src/schema/doctor.ts +20 -45
- package/src/security/policy-drift.test.ts +1 -106
- package/src/security/policy-drift.ts +0 -56
- package/src/services/row-pipeline.ts +3 -27
package/dist/schema/doctor.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { CollectionConfig, Property } from "@rebasepro/types";
|
|
|
2
2
|
export type IssueSeverity = "error" | "warning" | "info";
|
|
3
3
|
export interface DoctorIssue {
|
|
4
4
|
severity: IssueSeverity;
|
|
5
|
-
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale"
|
|
5
|
+
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale";
|
|
6
6
|
table?: string;
|
|
7
7
|
column?: string;
|
|
8
8
|
expected?: string;
|
|
@@ -63,36 +63,6 @@ export declare function parseExpectedPolicies(ddl: string): PolicyRef[];
|
|
|
63
63
|
* of reads. The same blindness would hide a policy that fails open.
|
|
64
64
|
*/
|
|
65
65
|
export declare function checkPolicyDrift(client: Queryable, collections: CollectionConfig[]): Promise<PolicyDrift>;
|
|
66
|
-
/**
|
|
67
|
-
* Does this name look like one the generator produced for this table?
|
|
68
|
-
*
|
|
69
|
-
* Unnamed rules compile to `<table>_<op>_<sha1[0:7]>` (plus `_<idx>` when one
|
|
70
|
-
* rule spans several operations), and the hash covers the rule's semantics — so
|
|
71
|
-
* *editing* a rule renames its policy. The policy under the old name is left
|
|
72
|
-
* behind by `db push`, which only DROPs the names it is about to CREATE, and
|
|
73
|
-
* Postgres ORs PERMISSIVE policies together: a superseded `USING (true)` keeps
|
|
74
|
-
* granting everything no matter how tight its replacement is.
|
|
75
|
-
*
|
|
76
|
-
* Matching the shape is what makes dropping them safe. A hand-written policy
|
|
77
|
-
* would have to collide with a 7-hex digest to be mistaken for generated one;
|
|
78
|
-
* a policy named anything else is left alone and merely reported, because a
|
|
79
|
-
* custom name is indistinguishable from one someone wrote in SQL on purpose.
|
|
80
|
-
*/
|
|
81
|
-
export declare function isGeneratedPolicyName(name: string, table: string): boolean;
|
|
82
|
-
export interface OrphanCleanup {
|
|
83
|
-
/** Superseded generated policies that were dropped. */
|
|
84
|
-
dropped: PolicyRef[];
|
|
85
|
-
/** Orphans left in place because their names are not generator-shaped. */
|
|
86
|
-
kept: PolicyRef[];
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Drop the policies an earlier push superseded but never removed.
|
|
90
|
-
*
|
|
91
|
-
* Only touches tables the collections describe — a table with no expected
|
|
92
|
-
* policy is not ours to reconcile, and scanning by schema alone would sweep up
|
|
93
|
-
* policies belonging to something else sharing the database.
|
|
94
|
-
*/
|
|
95
|
-
export declare function dropOrphanedPolicies(client: Queryable, drift: PolicyDrift, collections: CollectionConfig[]): Promise<OrphanCleanup>;
|
|
96
66
|
export declare const hasDrift: (d: PolicyDrift) => boolean;
|
|
97
67
|
/** Human-readable report; empty string when the database matches the config. */
|
|
98
68
|
export declare function formatPolicyDrift(drift: PolicyDrift): string;
|
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.
|
|
4
|
+
"version": "0.9.1-canary.f0ac103",
|
|
5
5
|
"description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
|
|
6
6
|
"funding": {
|
|
7
7
|
"url": "https://github.com/sponsors/rebaseco"
|
|
@@ -71,15 +71,14 @@
|
|
|
71
71
|
"execa": "^9.6.1",
|
|
72
72
|
"pg": "^8.21.0",
|
|
73
73
|
"ws": "^8.21.0",
|
|
74
|
-
"@rebasepro/codegen": "0.9.1-canary.
|
|
75
|
-
"@rebasepro/
|
|
76
|
-
"@rebasepro/
|
|
77
|
-
"@rebasepro/utils": "0.9.1-canary.
|
|
78
|
-
"@rebasepro/
|
|
74
|
+
"@rebasepro/codegen": "0.9.1-canary.f0ac103",
|
|
75
|
+
"@rebasepro/common": "0.9.1-canary.f0ac103",
|
|
76
|
+
"@rebasepro/types": "0.9.1-canary.f0ac103",
|
|
77
|
+
"@rebasepro/utils": "0.9.1-canary.f0ac103",
|
|
78
|
+
"@rebasepro/server": "0.9.1-canary.f0ac103"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@hono/node-server": "^2.0.9",
|
|
82
|
-
"@jest/globals": "^30.4.1",
|
|
83
82
|
"@types/jest": "^30.0.0",
|
|
84
83
|
"@types/node": "^25.9.3",
|
|
85
84
|
"@types/pg": "^8.20.0",
|
package/src/cli.ts
CHANGED
|
@@ -176,7 +176,6 @@ async function dbCommand(subcommand: string, rawArgs: string[]): Promise<void> {
|
|
|
176
176
|
|
|
177
177
|
if (databaseUrl) {
|
|
178
178
|
await applyPolicies(databaseUrl);
|
|
179
|
-
await reconcilePolicies(databaseUrl, collectionsPath);
|
|
180
179
|
await ensureRlsUserRole(databaseUrl);
|
|
181
180
|
} else {
|
|
182
181
|
logger.warn(chalk.yellow(" ⚠️ DATABASE_URL not found in environment, skipping RLS policies application."));
|
|
@@ -270,65 +269,6 @@ async function applyPolicies(databaseUrl: string): Promise<void> {
|
|
|
270
269
|
}
|
|
271
270
|
}
|
|
272
271
|
|
|
273
|
-
/**
|
|
274
|
-
* Remove the policies an earlier push superseded but never dropped.
|
|
275
|
-
*
|
|
276
|
-
* `policies.sql` only DROPs the names it is about to CREATE, and a rule's
|
|
277
|
-
* generated name contains a hash of its own semantics — so editing a rule
|
|
278
|
-
* writes a *new* policy and abandons the old one. Postgres ORs PERMISSIVE
|
|
279
|
-
* policies together, which makes an abandoned grant outrank every tightening
|
|
280
|
-
* that replaced it, and push reported success the whole time.
|
|
281
|
-
*
|
|
282
|
-
* Runs after `applyPolicies` so the current policies are already in place: the
|
|
283
|
-
* drift check then sees exactly the set that should survive, and anything else
|
|
284
|
-
* on a managed table is by definition left over.
|
|
285
|
-
*/
|
|
286
|
-
async function reconcilePolicies(databaseUrl: string, collectionsPath: string): Promise<void> {
|
|
287
|
-
try {
|
|
288
|
-
const { checkPolicyDrift, dropOrphanedPolicies, formatPolicyDrift, hasDrift } =
|
|
289
|
-
await import("./security/policy-drift");
|
|
290
|
-
const { loadCollections } = await import("./schema/doctor");
|
|
291
|
-
|
|
292
|
-
const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
|
|
293
|
-
const { Client } = await import("pg");
|
|
294
|
-
const client = new Client({ connectionString: databaseUrl });
|
|
295
|
-
await client.connect();
|
|
296
|
-
try {
|
|
297
|
-
const drift = await checkPolicyDrift(client as never, collections);
|
|
298
|
-
const { dropped, kept } = await dropOrphanedPolicies(client as never, drift, collections);
|
|
299
|
-
|
|
300
|
-
for (const p of dropped) {
|
|
301
|
-
logger.info(chalk.gray(` ✓ Dropped superseded policy "${p.name}" on ${p.schema}.${p.table}`));
|
|
302
|
-
}
|
|
303
|
-
if (dropped.length > 0) {
|
|
304
|
-
logger.info(chalk.green(` ✓ Removed ${dropped.length} superseded RLS ${dropped.length === 1 ? "policy" : "policies"}.`));
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
// Custom-named orphans are indistinguishable from policies someone
|
|
308
|
-
// wrote in SQL deliberately, so they are reported, never dropped.
|
|
309
|
-
if (kept.length > 0) {
|
|
310
|
-
logger.warn(chalk.yellow(" ⚠️ Policies in the database that no collection describes:"));
|
|
311
|
-
for (const p of kept) {
|
|
312
|
-
logger.warn(chalk.yellow(` • ${p.schema}.${p.table} → "${p.name}" (${p.command} TO ${p.roles.join(", ")})`));
|
|
313
|
-
}
|
|
314
|
-
logger.warn(chalk.yellow(" These still grant access. Drop them by hand if they are stale."));
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// Missing/diverged are not push's to fix, but staying silent about
|
|
318
|
-
// them is how a database ends up not matching its config.
|
|
319
|
-
const remaining = { ...drift, orphaned: kept };
|
|
320
|
-
if (hasDrift(remaining) && (remaining.missing.length > 0 || remaining.diverged.length > 0)) {
|
|
321
|
-
logger.warn(chalk.yellow(" ⚠️ RLS policies do not match your collections:"));
|
|
322
|
-
logger.warn(formatPolicyDrift({ ...remaining, orphaned: [] }));
|
|
323
|
-
}
|
|
324
|
-
} finally {
|
|
325
|
-
await client.end();
|
|
326
|
-
}
|
|
327
|
-
} catch (err) {
|
|
328
|
-
logger.warn(chalk.yellow(` ⚠️ Could not reconcile RLS policies: ${err instanceof Error ? err.message : String(err)}`));
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
272
|
async function branchCommand(rawArgs: string[]): Promise<void> {
|
|
333
273
|
const branchAction = rawArgs[2]; // create, list, delete, info
|
|
334
274
|
|
package/src/schema/doctor.ts
CHANGED
|
@@ -37,7 +37,7 @@ export type IssueSeverity = "error" | "warning" | "info";
|
|
|
37
37
|
|
|
38
38
|
export interface DoctorIssue {
|
|
39
39
|
severity: IssueSeverity;
|
|
40
|
-
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale"
|
|
40
|
+
category: "missing_table" | "missing_column" | "type_mismatch" | "missing_constraint" | "schema_stale" | "missing_enum" | "enum_value_mismatch" | "missing_foreign_key" | "sdk_stale";
|
|
41
41
|
table?: string;
|
|
42
42
|
column?: string;
|
|
43
43
|
expected?: string;
|
|
@@ -61,29 +61,19 @@ export function getExpectedColumnType(prop: Property): string | null {
|
|
|
61
61
|
const sp = prop as StringProperty;
|
|
62
62
|
if (sp.enum) return "USER-DEFINED"; // pgEnum → USER-DEFINED in information_schema
|
|
63
63
|
if ("isId" in sp && sp.isId === "uuid") return "uuid";
|
|
64
|
-
if (sp.columnType === "
|
|
65
|
-
// A markdown/multiline string compiles to `text`, not varchar — the
|
|
66
|
-
// generator treats those UI hints as column-type signals, so the
|
|
67
|
-
// expectation here must too or every such column reads as drift.
|
|
68
|
-
if (sp.columnType === "text" || sp.ui?.markdown || sp.ui?.multiline) return "text";
|
|
64
|
+
if (sp.columnType === "text") return "text";
|
|
69
65
|
if (sp.columnType === "char") return "character";
|
|
70
66
|
return "character varying";
|
|
71
67
|
}
|
|
72
68
|
case "number": {
|
|
73
69
|
const np = prop as NumberProperty;
|
|
74
|
-
if (np.columnType)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
serial: "integer",
|
|
82
|
-
bigserial: "bigint",
|
|
83
|
-
smallserial: "smallint"
|
|
84
|
-
};
|
|
85
|
-
return serialWidths[np.columnType] ?? np.columnType;
|
|
86
|
-
}
|
|
70
|
+
if (np.columnType === "double precision") return "double precision";
|
|
71
|
+
if (np.columnType === "real") return "real";
|
|
72
|
+
if (np.columnType === "bigint") return "bigint";
|
|
73
|
+
if (np.columnType === "serial") return "integer"; // serial is integer under the hood
|
|
74
|
+
if (np.columnType === "bigserial") return "bigint";
|
|
75
|
+
if (np.columnType === "integer") return "integer";
|
|
76
|
+
if (np.columnType === "numeric") return "numeric";
|
|
87
77
|
if (np.validation?.integer || ("isId" in np && np.isId)) return "integer";
|
|
88
78
|
return "numeric";
|
|
89
79
|
}
|
|
@@ -211,18 +201,15 @@ export async function checkCollectionsVsSdk(
|
|
|
211
201
|
): Promise<{ passed: boolean; issues: DoctorIssue[] }> {
|
|
212
202
|
const issues: DoctorIssue[] = [];
|
|
213
203
|
|
|
214
|
-
//
|
|
215
|
-
// you choose to. A project that never generated one isn't drifting, so report
|
|
216
|
-
// it as information rather than a warning; otherwise `doctor` can never come
|
|
217
|
-
// back clean on a fresh project and users learn to ignore its output.
|
|
204
|
+
// Check if SDK file exists
|
|
218
205
|
if (!fs.existsSync(sdkFilePath)) {
|
|
219
206
|
issues.push({
|
|
220
|
-
severity: "
|
|
221
|
-
category: "
|
|
222
|
-
message:
|
|
223
|
-
fix: "Run `rebase generate-sdk`
|
|
207
|
+
severity: "warning",
|
|
208
|
+
category: "sdk_stale",
|
|
209
|
+
message: `Generated SDK typedefs file does not exist at "${sdkFilePath}".`,
|
|
210
|
+
fix: "Run `rebase generate-sdk`"
|
|
224
211
|
});
|
|
225
|
-
return { passed:
|
|
212
|
+
return { passed: false,
|
|
226
213
|
issues };
|
|
227
214
|
}
|
|
228
215
|
|
|
@@ -644,15 +631,11 @@ export function renderReport(report: DoctorReport): void {
|
|
|
644
631
|
}
|
|
645
632
|
|
|
646
633
|
function renderPhase(label: string, passed: boolean, issues: DoctorIssue[]): void {
|
|
647
|
-
|
|
648
|
-
const warnCount = issues.filter((i) => i.severity === "warning").length;
|
|
649
|
-
const infoIssues = issues.filter((i) => i.severity === "info");
|
|
650
|
-
|
|
651
|
-
// Informational notes don't make a phase unhealthy, so key the header off
|
|
652
|
-
// real problems rather than `passed` alone.
|
|
653
|
-
if (errorCount === 0 && warnCount === 0) {
|
|
634
|
+
if (passed) {
|
|
654
635
|
logger.info(` ${chalk.green("✅")} ${label}: ${chalk.green("In sync")}`);
|
|
655
636
|
} else {
|
|
637
|
+
const errorCount = issues.filter((i) => i.severity === "error").length;
|
|
638
|
+
const warnCount = issues.filter((i) => i.severity === "warning").length;
|
|
656
639
|
const parts: string[] = [];
|
|
657
640
|
if (errorCount > 0) parts.push(`${errorCount} error${errorCount > 1 ? "s" : ""}`);
|
|
658
641
|
if (warnCount > 0) parts.push(`${warnCount} warning${warnCount > 1 ? "s" : ""}`);
|
|
@@ -660,14 +643,7 @@ function renderPhase(label: string, passed: boolean, issues: DoctorIssue[]): voi
|
|
|
660
643
|
}
|
|
661
644
|
logger.info("");
|
|
662
645
|
|
|
663
|
-
|
|
664
|
-
for (const issue of infoIssues) {
|
|
665
|
-
const fixPart = issue.fix ? chalk.gray(` — ${issue.fix}`) : "";
|
|
666
|
-
logger.info(` ${chalk.gray("ℹ")} ${chalk.gray(issue.message)}${fixPart}`);
|
|
667
|
-
logger.info("");
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
for (const issue of issues.filter((i) => i.severity !== "info")) {
|
|
646
|
+
for (const issue of issues) {
|
|
671
647
|
const severityIcon = issue.severity === "error" ? chalk.red("✗") : chalk.yellow("⚠");
|
|
672
648
|
const categoryLabel = formatCategory(issue.category);
|
|
673
649
|
logger.info(` ${chalk.gray("┌─")} ${severityIcon} ${chalk.bold(categoryLabel)} ${chalk.gray("─".repeat(Math.max(0, 42 - categoryLabel.length)))}`);
|
|
@@ -698,8 +674,7 @@ function formatCategory(cat: DoctorIssue["category"]): string {
|
|
|
698
674
|
missing_enum: "Missing Enum",
|
|
699
675
|
enum_value_mismatch: "Enum Value Mismatch",
|
|
700
676
|
missing_foreign_key: "Missing Foreign Key",
|
|
701
|
-
sdk_stale: "Stale SDK Types"
|
|
702
|
-
sdk_not_generated: "SDK Types Not Generated"
|
|
677
|
+
sdk_stale: "Stale SDK Types"
|
|
703
678
|
};
|
|
704
679
|
return labels[cat];
|
|
705
680
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { describe, expect, it } from "@jest/globals";
|
|
2
2
|
import type { CollectionConfig } from "@rebasepro/types";
|
|
3
3
|
|
|
4
|
-
import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift,
|
|
4
|
+
import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift, type PolicyRef, type Queryable } from "./policy-drift";
|
|
5
5
|
import { generatePostgresPoliciesDdl } from "../schema/generate-postgres-ddl-logic";
|
|
6
6
|
|
|
7
7
|
function collection(slug: string): CollectionConfig {
|
|
@@ -154,108 +154,3 @@ describe("checkPolicyDrift", () => {
|
|
|
154
154
|
expect(drift.missing.length).toBeGreaterThan(0);
|
|
155
155
|
});
|
|
156
156
|
});
|
|
157
|
-
|
|
158
|
-
describe("isGeneratedPolicyName", () => {
|
|
159
|
-
it("recognises the generator's own shape", () => {
|
|
160
|
-
expect(isGeneratedPolicyName("documents_insert_a1b2c3d", "documents")).toBe(true);
|
|
161
|
-
// One rule spanning several operations appends the operation index.
|
|
162
|
-
expect(isGeneratedPolicyName("documents_update_a1b2c3d_1", "documents")).toBe(true);
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
it("does not claim names a human could have written", () => {
|
|
166
|
-
expect(isGeneratedPolicyName("owner_access", "documents")).toBe(false);
|
|
167
|
-
expect(isGeneratedPolicyName("documents_default_admin_read", "documents")).toBe(false);
|
|
168
|
-
// Right shape, wrong table — belongs to something else.
|
|
169
|
-
expect(isGeneratedPolicyName("teams_insert_a1b2c3d", "documents")).toBe(false);
|
|
170
|
-
// A digest is 7 lowercase hex characters, nothing else.
|
|
171
|
-
expect(isGeneratedPolicyName("documents_insert_notahex", "documents")).toBe(false);
|
|
172
|
-
expect(isGeneratedPolicyName("documents_grant_a1b2c3d", "documents")).toBe(false);
|
|
173
|
-
});
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
describe("dropOrphanedPolicies", () => {
|
|
177
|
-
/** Records the DDL issued so the test can assert on what was dropped. */
|
|
178
|
-
function recordingDb(rows: Record<string, unknown>[]) {
|
|
179
|
-
const executed: string[] = [];
|
|
180
|
-
const db: Queryable = {
|
|
181
|
-
query: async (text: string) => {
|
|
182
|
-
if (!/^SELECT/i.test(text)) executed.push(text);
|
|
183
|
-
return { rows: rows as never[] };
|
|
184
|
-
}
|
|
185
|
-
};
|
|
186
|
-
return { db, executed };
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
it("drops the policy a rule edit superseded", async () => {
|
|
190
|
-
// The reported failure: tightening a rule renames its policy, and the
|
|
191
|
-
// permissive original stays live and keeps ORing itself back in.
|
|
192
|
-
const cols = [collection("documents")];
|
|
193
|
-
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
194
|
-
const stale = {
|
|
195
|
-
schemaname: "public", tablename: "documents", policyname: "documents_insert_dead1ee",
|
|
196
|
-
roles: ["public"], cmd: "INSERT", qual: null, with_check: "true"
|
|
197
|
-
};
|
|
198
|
-
const live = [...expected.map((p) => liveRow(p)), stale];
|
|
199
|
-
|
|
200
|
-
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
201
|
-
const { db, executed } = recordingDb(live);
|
|
202
|
-
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
203
|
-
|
|
204
|
-
expect(dropped).toHaveLength(1);
|
|
205
|
-
expect(dropped[0].name).toBe("documents_insert_dead1ee");
|
|
206
|
-
expect(kept).toHaveLength(0);
|
|
207
|
-
expect(executed).toEqual([
|
|
208
|
-
'DROP POLICY IF EXISTS "documents_insert_dead1ee" ON "public"."documents"'
|
|
209
|
-
]);
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
it("leaves a hand-written policy alone and reports it instead", async () => {
|
|
213
|
-
const cols = [collection("documents")];
|
|
214
|
-
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
215
|
-
const live = [
|
|
216
|
-
...expected.map((p) => liveRow(p)),
|
|
217
|
-
{ schemaname: "public", tablename: "documents", policyname: "ops_break_glass", roles: ["public"], cmd: "ALL", qual: "true", with_check: null }
|
|
218
|
-
];
|
|
219
|
-
|
|
220
|
-
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
221
|
-
const { db, executed } = recordingDb(live);
|
|
222
|
-
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
223
|
-
|
|
224
|
-
expect(dropped).toHaveLength(0);
|
|
225
|
-
expect(kept.map((p) => p.name)).toEqual(["ops_break_glass"]);
|
|
226
|
-
expect(executed).toEqual([]);
|
|
227
|
-
});
|
|
228
|
-
|
|
229
|
-
it("never touches a table the collections do not describe", async () => {
|
|
230
|
-
// Another application sharing the schema owns this table; a
|
|
231
|
-
// generator-shaped name there is coincidence, not our leftover.
|
|
232
|
-
const cols = [collection("documents")];
|
|
233
|
-
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
234
|
-
const live = [
|
|
235
|
-
...expected.map((p) => liveRow(p)),
|
|
236
|
-
{ schemaname: "public", tablename: "legacy", policyname: "legacy_select_a1b2c3d", roles: ["public"], cmd: "SELECT", qual: "true", with_check: null }
|
|
237
|
-
];
|
|
238
|
-
|
|
239
|
-
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
240
|
-
const { db, executed } = recordingDb(live);
|
|
241
|
-
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
242
|
-
|
|
243
|
-
expect(dropped).toHaveLength(0);
|
|
244
|
-
expect(kept.map((p) => p.name)).toEqual(["legacy_select_a1b2c3d"]);
|
|
245
|
-
expect(executed).toEqual([]);
|
|
246
|
-
});
|
|
247
|
-
|
|
248
|
-
it("does nothing when the database already matches", async () => {
|
|
249
|
-
const cols = [collection("documents")];
|
|
250
|
-
const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
|
|
251
|
-
const live = expected.map((p) => liveRow(p));
|
|
252
|
-
|
|
253
|
-
const drift = await checkPolicyDrift(dbWith(live), cols);
|
|
254
|
-
const { db, executed } = recordingDb(live);
|
|
255
|
-
const { dropped, kept } = await dropOrphanedPolicies(db, drift, cols);
|
|
256
|
-
|
|
257
|
-
expect(dropped).toHaveLength(0);
|
|
258
|
-
expect(kept).toHaveLength(0);
|
|
259
|
-
expect(executed).toEqual([]);
|
|
260
|
-
});
|
|
261
|
-
});
|
|
@@ -192,62 +192,6 @@ export async function checkPolicyDrift(
|
|
|
192
192
|
return drift;
|
|
193
193
|
}
|
|
194
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
|
-
|
|
251
195
|
export const hasDrift = (d: PolicyDrift): boolean =>
|
|
252
196
|
d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0;
|
|
253
197
|
|
|
@@ -91,30 +91,6 @@ function coerceDeclaredNumbers(
|
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
/** Render one target row in the requested style. */
|
|
94
|
-
/**
|
|
95
|
-
* Drop every column the collection marked `excludeFromApi`.
|
|
96
|
-
*
|
|
97
|
-
* Password hashes and verification tokens have to be readable server-side but
|
|
98
|
-
* must never reach a client — and "never" has to mean every exit from this
|
|
99
|
-
* pipeline, including relation targets, or a secret leaks through whichever
|
|
100
|
-
* path was overlooked. Keyed by both the property name and its column name,
|
|
101
|
-
* since a row can arrive keyed either way depending on the caller.
|
|
102
|
-
*/
|
|
103
|
-
function stripExcluded(
|
|
104
|
-
row: Record<string, unknown>,
|
|
105
|
-
collection: CollectionConfig
|
|
106
|
-
): Record<string, unknown> {
|
|
107
|
-
const properties = collection.properties as Record<string, Property> | undefined;
|
|
108
|
-
if (!properties) return row;
|
|
109
|
-
|
|
110
|
-
for (const [key, property] of Object.entries(properties)) {
|
|
111
|
-
if (!property?.excludeFromApi) continue;
|
|
112
|
-
delete row[key];
|
|
113
|
-
if (property.columnName) delete row[property.columnName];
|
|
114
|
-
}
|
|
115
|
-
return row;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
94
|
function renderTarget(
|
|
119
95
|
targetRow: Record<string, unknown>,
|
|
120
96
|
targetCollection: CollectionConfig,
|
|
@@ -124,7 +100,7 @@ function renderTarget(
|
|
|
124
100
|
if (style === "inline") {
|
|
125
101
|
// The target's columns, and only those: its address is the consumer's
|
|
126
102
|
// to derive, and merging one in overwrites a real `id` column.
|
|
127
|
-
return
|
|
103
|
+
return coerceDeclaredNumbers({ ...targetRow }, targetCollection);
|
|
128
104
|
}
|
|
129
105
|
|
|
130
106
|
const address = relationTargetAddress(targetRow, targetCollection, registry);
|
|
@@ -192,7 +168,7 @@ export function toCmsRow(
|
|
|
192
168
|
}
|
|
193
169
|
}
|
|
194
170
|
|
|
195
|
-
return
|
|
171
|
+
return normalized;
|
|
196
172
|
}
|
|
197
173
|
|
|
198
174
|
/**
|
|
@@ -235,5 +211,5 @@ export function toRestRow(
|
|
|
235
211
|
}
|
|
236
212
|
}
|
|
237
213
|
|
|
238
|
-
return
|
|
214
|
+
return flat;
|
|
239
215
|
}
|