@rebasepro/server-postgres 0.9.1-canary.ff338b5 → 0.10.1-canary.18115ba
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 +21 -0
- package/dist/PostgresBackendDriver.d.ts +18 -0
- package/dist/PostgresBootstrapper.d.ts +7 -1
- package/dist/auth/services.d.ts +93 -54
- package/dist/index.es.js +929 -224
- package/dist/index.es.js.map +1 -1
- package/dist/schema/auth-bootstrap-sql.d.ts +1 -1
- package/dist/schema/auth-schema.d.ts +194 -24
- package/dist/schema/introspect-db-logic.d.ts +0 -5
- package/dist/schema/introspect-db-naming.d.ts +10 -0
- package/dist/security/policy-drift.d.ts +24 -0
- package/dist/security/rls-enforcement.d.ts +2 -2
- package/dist/services/channel-history.d.ts +118 -0
- package/dist/services/realtimeService.d.ts +69 -2
- package/package.json +7 -31
- package/src/PostgresBackendDriver.ts +56 -5
- package/src/PostgresBootstrapper.ts +18 -1
- package/src/auth/ensure-tables.ts +187 -19
- package/src/auth/services.ts +309 -170
- package/src/schema/auth-bootstrap-sql.ts +7 -1
- package/src/schema/auth-schema.ts +53 -15
- package/src/schema/introspect-db-inference.ts +1 -1
- package/src/schema/introspect-db-logic.ts +1 -10
- package/src/schema/introspect-db-naming.ts +15 -0
- package/src/schema/introspect-runtime.ts +1 -1
- package/src/security/policy-drift.test.ts +46 -0
- package/src/security/policy-drift.ts +70 -4
- package/src/security/rls-enforcement.ts +11 -5
- package/src/services/channel-history.ts +343 -0
- package/src/services/realtimeService.ts +198 -10
- package/src/websocket.ts +30 -11
|
@@ -24,8 +24,14 @@
|
|
|
24
24
|
export const AUTH_BOOTSTRAP_SQL = `-- Auth schema + RLS helper functions (required by the policies below)
|
|
25
25
|
CREATE SCHEMA IF NOT EXISTS auth;
|
|
26
26
|
|
|
27
|
+
-- Falls back to the pre-rename \`app.user_id\` so a database that has taken the
|
|
28
|
+
-- new schema but is still served by an older backend keeps resolving the
|
|
29
|
+
-- principal. Drop the COALESCE once no such deployment remains.
|
|
27
30
|
CREATE OR REPLACE FUNCTION auth.uid() RETURNS text AS $$
|
|
28
|
-
SELECT
|
|
31
|
+
SELECT COALESCE(
|
|
32
|
+
NULLIF(current_setting('app.uid', true), ''),
|
|
33
|
+
NULLIF(current_setting('app.user_id', true), '')
|
|
34
|
+
);
|
|
29
35
|
$$ LANGUAGE sql STABLE;
|
|
30
36
|
|
|
31
37
|
CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb AS $$
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { pgSchema, pgTable, varchar, uuid, timestamp, boolean, jsonb, text, unique } from "drizzle-orm/pg-core";
|
|
1
|
+
import { pgSchema, pgTable, varchar, uuid, timestamp, boolean, jsonb, text, unique, index } from "drizzle-orm/pg-core";
|
|
2
2
|
import { relations } from "drizzle-orm";
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -25,24 +25,62 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
25
25
|
isAnonymous: boolean("is_anonymous").default(false).notNull(),
|
|
26
26
|
roles: text("roles").array().default([]).notNull(),
|
|
27
27
|
metadata: jsonb("metadata").$type<Record<string, unknown>>().default({}).notNull(),
|
|
28
|
+
/**
|
|
29
|
+
* Sessions that began before this instant are dead, whatever tokens
|
|
30
|
+
* they still hold. Password resets and admin revocations stamp it.
|
|
31
|
+
*
|
|
32
|
+
* Deleting the user's refresh-token rows (which we also do) is not
|
|
33
|
+
* sufficient on its own: a request already in flight can insert a
|
|
34
|
+
* freshly rotated row microseconds after the delete and survive it.
|
|
35
|
+
* This timestamp cannot be outrun that way — it is checked against
|
|
36
|
+
* `refresh_tokens.session_started_at`, which rotation carries forward.
|
|
37
|
+
*/
|
|
38
|
+
tokensValidAfter: timestamp("tokens_valid_after"),
|
|
28
39
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
29
40
|
updatedAt: timestamp("updated_at").defaultNow().notNull()
|
|
30
41
|
});
|
|
31
42
|
|
|
32
43
|
|
|
33
44
|
/**
|
|
34
|
-
* Refresh tokens for long-lived sessions
|
|
45
|
+
* Refresh tokens for long-lived sessions.
|
|
46
|
+
*
|
|
47
|
+
* A row is one token, not one device. Every token minted from the same
|
|
48
|
+
* sign-in shares a `sessionId`, and rotation ADDS a row rather than
|
|
49
|
+
* replacing one: the superseded token stays on file, flagged `revoked`
|
|
50
|
+
* with a `rotatedAt` stamp. That record is what lets the refresh endpoint
|
|
51
|
+
* tell a client replaying a token it never got an answer for (a response
|
|
52
|
+
* lost to a redeploy, a second tab racing on boot) apart from a stranger
|
|
53
|
+
* presenting a token that was never issued. Deleting the old row on sight
|
|
54
|
+
* — the previous behaviour — made those two cases indistinguishable, and
|
|
55
|
+
* the legitimate one is overwhelmingly the common one.
|
|
56
|
+
*
|
|
57
|
+
* There is deliberately NO unique constraint on (uid, user_agent,
|
|
58
|
+
* ip_address). Keying a session on the IP meant one row per "device",
|
|
59
|
+
* so a second browser profile behind the same NAT silently evicted the
|
|
60
|
+
* first, and a phone changing networks orphaned a row on every hop.
|
|
61
|
+
* User agent and IP are descriptive metadata for the sessions list;
|
|
62
|
+
* `sessionId` is the identity.
|
|
35
63
|
*/
|
|
36
64
|
const refreshTokens = tableCreator("refresh_tokens", {
|
|
37
65
|
id: uuid("id").defaultRandom().primaryKey(),
|
|
38
|
-
|
|
66
|
+
uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
67
|
+
sessionId: uuid("session_id").defaultRandom().notNull(),
|
|
39
68
|
tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
|
|
40
69
|
expiresAt: timestamp("expires_at").notNull(),
|
|
70
|
+
revoked: boolean("revoked").default(false).notNull(),
|
|
71
|
+
rotatedAt: timestamp("rotated_at"),
|
|
72
|
+
/**
|
|
73
|
+
* When the sign-in this token descends from happened — carried across
|
|
74
|
+
* every rotation, unlike `createdAt`. `users.tokensValidAfter` is
|
|
75
|
+
* compared against this, so a revocation cannot be outrun by a token
|
|
76
|
+
* that rotates immediately after it.
|
|
77
|
+
*/
|
|
78
|
+
sessionStartedAt: timestamp("session_started_at").defaultNow().notNull(),
|
|
41
79
|
userAgent: varchar("user_agent", { length: 500 }),
|
|
42
80
|
ipAddress: varchar("ip_address", { length: 45 }),
|
|
43
81
|
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
44
82
|
}, (table) => ({
|
|
45
|
-
|
|
83
|
+
sessionIdx: index("idx_refresh_tokens_session").on(table.sessionId)
|
|
46
84
|
}));
|
|
47
85
|
|
|
48
86
|
/**
|
|
@@ -50,7 +88,7 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
50
88
|
*/
|
|
51
89
|
const passwordResetTokens = tableCreator("password_reset_tokens", {
|
|
52
90
|
id: uuid("id").defaultRandom().primaryKey(),
|
|
53
|
-
|
|
91
|
+
uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
54
92
|
tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
|
|
55
93
|
expiresAt: timestamp("expires_at").notNull(),
|
|
56
94
|
usedAt: timestamp("used_at"),
|
|
@@ -71,7 +109,7 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
71
109
|
*/
|
|
72
110
|
const userIdentities = tableCreator("user_identities", {
|
|
73
111
|
id: uuid("id").defaultRandom().primaryKey(),
|
|
74
|
-
|
|
112
|
+
uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
75
113
|
provider: varchar("provider", { length: 50 }).notNull(), // e.g. 'google', 'linkedin'
|
|
76
114
|
providerId: varchar("provider_id", { length: 255 }).notNull(),
|
|
77
115
|
profileData: jsonb("profile_data"),
|
|
@@ -86,7 +124,7 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
86
124
|
*/
|
|
87
125
|
const mfaFactors = tableCreator("mfa_factors", {
|
|
88
126
|
id: uuid("id").defaultRandom().primaryKey(),
|
|
89
|
-
|
|
127
|
+
uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
90
128
|
factorType: varchar("factor_type", { length: 20 }).notNull(), // 'totp'
|
|
91
129
|
secretEncrypted: varchar("secret_encrypted", { length: 500 }).notNull(),
|
|
92
130
|
friendlyName: varchar("friendly_name", { length: 255 }),
|
|
@@ -112,7 +150,7 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
112
150
|
*/
|
|
113
151
|
const recoveryCodes = tableCreator("recovery_codes", {
|
|
114
152
|
id: uuid("id").defaultRandom().primaryKey(),
|
|
115
|
-
|
|
153
|
+
uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
116
154
|
codeHash: varchar("code_hash", { length: 255 }).notNull(),
|
|
117
155
|
usedAt: timestamp("used_at"),
|
|
118
156
|
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
@@ -123,7 +161,7 @@ export function createAuthSchema(usersSchemaName = "rebase") {
|
|
|
123
161
|
*/
|
|
124
162
|
const magicLinkTokens = tableCreator("magic_link_tokens", {
|
|
125
163
|
id: uuid("id").defaultRandom().primaryKey(),
|
|
126
|
-
|
|
164
|
+
uid: uuid("uid").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
127
165
|
tokenHash: varchar("token_hash", { length: 255 }).notNull().unique(),
|
|
128
166
|
expiresAt: timestamp("expires_at").notNull(),
|
|
129
167
|
usedAt: timestamp("used_at"),
|
|
@@ -171,28 +209,28 @@ export const usersRelations = relations(users, ({ many }) => ({
|
|
|
171
209
|
|
|
172
210
|
export const refreshTokensRelations = relations(refreshTokens, ({ one }) => ({
|
|
173
211
|
user: one(users, {
|
|
174
|
-
fields: [refreshTokens.
|
|
212
|
+
fields: [refreshTokens.uid],
|
|
175
213
|
references: [users.id]
|
|
176
214
|
})
|
|
177
215
|
}));
|
|
178
216
|
|
|
179
217
|
export const passwordResetTokensRelations = relations(passwordResetTokens, ({ one }) => ({
|
|
180
218
|
user: one(users, {
|
|
181
|
-
fields: [passwordResetTokens.
|
|
219
|
+
fields: [passwordResetTokens.uid],
|
|
182
220
|
references: [users.id]
|
|
183
221
|
})
|
|
184
222
|
}));
|
|
185
223
|
|
|
186
224
|
export const userIdentitiesRelations = relations(userIdentities, ({ one }) => ({
|
|
187
225
|
user: one(users, {
|
|
188
|
-
fields: [userIdentities.
|
|
226
|
+
fields: [userIdentities.uid],
|
|
189
227
|
references: [users.id]
|
|
190
228
|
})
|
|
191
229
|
}));
|
|
192
230
|
|
|
193
231
|
export const mfaFactorsRelations = relations(mfaFactors, ({ one, many }) => ({
|
|
194
232
|
user: one(users, {
|
|
195
|
-
fields: [mfaFactors.
|
|
233
|
+
fields: [mfaFactors.uid],
|
|
196
234
|
references: [users.id]
|
|
197
235
|
}),
|
|
198
236
|
challenges: many(mfaChallenges)
|
|
@@ -207,14 +245,14 @@ export const mfaChallengesRelations = relations(mfaChallenges, ({ one }) => ({
|
|
|
207
245
|
|
|
208
246
|
export const recoveryCodesRelations = relations(recoveryCodes, ({ one }) => ({
|
|
209
247
|
user: one(users, {
|
|
210
|
-
fields: [recoveryCodes.
|
|
248
|
+
fields: [recoveryCodes.uid],
|
|
211
249
|
references: [users.id]
|
|
212
250
|
})
|
|
213
251
|
}));
|
|
214
252
|
|
|
215
253
|
export const magicLinkTokensRelations = relations(magicLinkTokens, ({ one }) => ({
|
|
216
254
|
user: one(users, {
|
|
217
|
-
fields: [magicLinkTokens.
|
|
255
|
+
fields: [magicLinkTokens.uid],
|
|
218
256
|
references: [users.id]
|
|
219
257
|
})
|
|
220
258
|
}));
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* and consumed directly by tests.
|
|
8
8
|
*/
|
|
9
9
|
import { inferPropertyFromData } from "./introspect-db-inference";
|
|
10
|
+
import { humanize } from "./introspect-db-naming";
|
|
10
11
|
|
|
11
12
|
// ── Typed interfaces for SQL query results ────────────────────────────
|
|
12
13
|
|
|
@@ -117,16 +118,6 @@ export function singularize(word: string): string {
|
|
|
117
118
|
return word;
|
|
118
119
|
}
|
|
119
120
|
|
|
120
|
-
/**
|
|
121
|
-
* Convert a snake_case name to a human-readable Title Case label.
|
|
122
|
-
* e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
|
|
123
|
-
*/
|
|
124
|
-
export function humanize(snakeName: string): string {
|
|
125
|
-
return snakeName
|
|
126
|
-
.replace(/_/g, " ")
|
|
127
|
-
.replace(/\b\w/g, (c) => c.toUpperCase());
|
|
128
|
-
}
|
|
129
|
-
|
|
130
121
|
/**
|
|
131
122
|
* Convert a snake_case table name to a camelCase + "Collection" variable name.
|
|
132
123
|
* e.g. "company_token" -> "companyTokenCollection"
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Naming helpers shared by the introspection modules. These live apart from
|
|
3
|
+
* `introspect-db-logic.ts` because the inference pass needs them too, and
|
|
4
|
+
* importing them from there would close a cycle back through this module.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Convert a snake_case name to a human-readable Title Case label.
|
|
9
|
+
* e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
|
|
10
|
+
*/
|
|
11
|
+
export function humanize(snakeName: string): string {
|
|
12
|
+
return snakeName
|
|
13
|
+
.replace(/_/g, " ")
|
|
14
|
+
.replace(/\b\w/g, (c) => c.toUpperCase());
|
|
15
|
+
}
|
|
@@ -23,11 +23,11 @@ import {
|
|
|
23
23
|
buildTablesMap,
|
|
24
24
|
buildEnumMap,
|
|
25
25
|
identifyJoinTables,
|
|
26
|
-
humanize,
|
|
27
26
|
singularize,
|
|
28
27
|
mapPgType,
|
|
29
28
|
getIconForTable
|
|
30
29
|
} from "./introspect-db-logic";
|
|
30
|
+
import { humanize } from "./introspect-db-naming";
|
|
31
31
|
|
|
32
32
|
export interface IntrospectedSchema {
|
|
33
33
|
tablesMap: Map<string, TableMeta>;
|
|
@@ -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
|
}
|
|
@@ -59,7 +59,7 @@ export interface ConnectionPosture {
|
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
export interface AuthContext {
|
|
62
|
-
|
|
62
|
+
uid: string;
|
|
63
63
|
/** Raw roles as carried on the user (strings or `{ id }` objects). */
|
|
64
64
|
roles: unknown[];
|
|
65
65
|
}
|
|
@@ -200,7 +200,7 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
|
|
|
200
200
|
* SECURITY: this function is only ever called on the **user** path (the server
|
|
201
201
|
* context uses the base/owner driver and never calls it). The default policies
|
|
202
202
|
* treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
|
|
203
|
-
* is `NULLIF(current_setting('app.
|
|
203
|
+
* is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
|
|
204
204
|
* be read as NULL and silently escalate a user request to server privileges.
|
|
205
205
|
* Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
|
|
206
206
|
* rather than trusting every caller (e.g. realtime subscription auth) to do it.
|
|
@@ -208,15 +208,21 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
|
|
|
208
208
|
* semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
|
|
209
209
|
*/
|
|
210
210
|
export async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {
|
|
211
|
-
const
|
|
211
|
+
const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
|
|
212
212
|
const normalizedRoles = auth.roles.map((r: unknown) =>
|
|
213
213
|
typeof r === "string" ? r : (r as Record<string, unknown>)?.id ?? String(r)
|
|
214
214
|
);
|
|
215
|
+
// `app.user_id` is the pre-rename spelling, still written because policies
|
|
216
|
+
// are data: a database provisioned before the rename holds rules compiled
|
|
217
|
+
// to `current_setting('app.user_id')`, and those predicates would evaluate
|
|
218
|
+
// to NULL — failing open or locking out — if we stopped setting it. Drop
|
|
219
|
+
// the alias only once no live database carries a legacy policy.
|
|
215
220
|
await tx.execute(drizzleSql`
|
|
216
221
|
SELECT
|
|
217
|
-
set_config('app.
|
|
222
|
+
set_config('app.uid', ${uid}, true),
|
|
223
|
+
set_config('app.user_id', ${uid}, true),
|
|
218
224
|
set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
|
|
219
|
-
set_config('app.jwt', ${JSON.stringify({ sub:
|
|
225
|
+
set_config('app.jwt', ${JSON.stringify({ sub: uid, roles: auth.roles })}, true)
|
|
220
226
|
`);
|
|
221
227
|
if (userRole) {
|
|
222
228
|
await tx.execute(drizzleSql.raw(`SET LOCAL ROLE ${quoteIdent(userRole)}`));
|