fix(auth): use set_config for transaction-scoped RLS context
All checks were successful
ci/woodpecker/push/api Pipeline was successful

This commit is contained in:
2026-02-18 23:23:15 -06:00
parent d2cec04cba
commit 8424a28faa
4 changed files with 63 additions and 10 deletions

View File

@@ -137,13 +137,13 @@ describe("RLS Context Integration", () => {
queries: ["findMany"],
});
// Verify SET LOCAL was called
// Verify transaction-local set_config calls were made
expect(mockTransactionClient.$executeRaw).toHaveBeenCalledWith(
expect.arrayContaining(["SET LOCAL app.current_user_id = ", ""]),
expect.arrayContaining(["SELECT set_config('app.current_user_id', ", ", true)"]),
userId
);
expect(mockTransactionClient.$executeRaw).toHaveBeenCalledWith(
expect.arrayContaining(["SET LOCAL app.current_workspace_id = ", ""]),
expect.arrayContaining(["SELECT set_config('app.current_workspace_id', ", ", true)"]),
workspaceId
);
});

View File

@@ -80,7 +80,7 @@ describe("RlsContextInterceptor", () => {
expect(result).toEqual({ data: "test response" });
expect(mockTransactionClient.$executeRaw).toHaveBeenCalledWith(
expect.arrayContaining(["SET LOCAL app.current_user_id = ", ""]),
expect.arrayContaining(["SELECT set_config('app.current_user_id', ", ", true)"]),
userId
);
});
@@ -111,13 +111,13 @@ describe("RlsContextInterceptor", () => {
// Check that user context was set
expect(mockTransactionClient.$executeRaw).toHaveBeenNthCalledWith(
1,
expect.arrayContaining(["SET LOCAL app.current_user_id = ", ""]),
expect.arrayContaining(["SELECT set_config('app.current_user_id', ", ", true)"]),
userId
);
// Check that workspace context was set
expect(mockTransactionClient.$executeRaw).toHaveBeenNthCalledWith(
2,
expect.arrayContaining(["SET LOCAL app.current_workspace_id = ", ""]),
expect.arrayContaining(["SELECT set_config('app.current_workspace_id', ", ", true)"]),
workspaceId
);
});

View File

@@ -100,12 +100,12 @@ export class RlsContextInterceptor implements NestInterceptor {
this.prisma
.$transaction(
async (tx) => {
// Set user context (always present for authenticated requests)
await tx.$executeRaw`SET LOCAL app.current_user_id = ${userId}`;
// Use set_config(..., true) so values are transaction-local and parameterized safely.
// Direct SET LOCAL with bind parameters produces invalid SQL on PostgreSQL.
await tx.$executeRaw`SELECT set_config('app.current_user_id', ${userId}, true)`;
// Set workspace context (if present)
if (workspaceId) {
await tx.$executeRaw`SET LOCAL app.current_workspace_id = ${workspaceId}`;
await tx.$executeRaw`SELECT set_config('app.current_workspace_id', ${workspaceId}, true)`;
}
// Propagate the transaction client via AsyncLocalStorage