169 lines
7.1 KiB
TypeScript
169 lines
7.1 KiB
TypeScript
import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
|
export type RlsIdentityContext = {
|
|
tenantId?: string;
|
|
userId?: string;
|
|
portalUserId?: string;
|
|
portalSessionId?: string;
|
|
publicKnowledgeBaseId?: string;
|
|
};
|
|
|
|
type RlsTransaction = object;
|
|
|
|
export type RlsExecutionContext = RlsIdentityContext & {
|
|
platformAnalytics?: true;
|
|
transaction?: RlsTransaction;
|
|
};
|
|
|
|
declare global {
|
|
// The production web process evaluates this module once in the outer Node
|
|
// server bundle and again in the React Router server bundle. The Prisma
|
|
// singleton can be created by either bundle, so both must observe the same
|
|
// request context instead of closing over separate AsyncLocalStorage stores.
|
|
// eslint-disable-next-line no-var
|
|
var __hivegridRlsContext: AsyncLocalStorage<RlsExecutionContext> | undefined;
|
|
}
|
|
|
|
const rlsContext = (globalThis.__hivegridRlsContext ??= new AsyncLocalStorage<RlsExecutionContext>());
|
|
|
|
/**
|
|
* Binds the authenticated database identity to the current async call chain.
|
|
* Prisma operations consume this context and set the matching Postgres GUCs
|
|
* transaction-locally before touching an RLS-protected table.
|
|
*/
|
|
export function runWithRlsContext<T>(context: RlsIdentityContext, callback: () => T): T {
|
|
const current = rlsContext.getStore();
|
|
if (current?.platformAnalytics) {
|
|
throw new Error("Cannot bind an authenticated identity inside the isolated platform analytics RLS context");
|
|
}
|
|
const next = normalizeContext({
|
|
userId: context.userId ?? current?.userId,
|
|
portalUserId: context.portalUserId ?? current?.portalUserId,
|
|
portalSessionId: context.portalSessionId ?? current?.portalSessionId,
|
|
tenantId: context.tenantId ?? current?.tenantId,
|
|
publicKnowledgeBaseId: context.publicKnowledgeBaseId ?? current?.publicKnowledgeBaseId,
|
|
transaction: current?.transaction,
|
|
});
|
|
|
|
if (current?.tenantId && next.tenantId !== current.tenantId) {
|
|
throw new Error("Cannot switch the tenant inside an active RLS context");
|
|
}
|
|
if (current?.userId && next.userId !== current.userId) {
|
|
throw new Error("Cannot switch the user inside an active RLS context");
|
|
}
|
|
if (current?.portalUserId && next.portalUserId !== current.portalUserId) {
|
|
throw new Error("Cannot switch the portal user inside an active RLS context");
|
|
}
|
|
if (current?.portalSessionId && next.portalSessionId !== current.portalSessionId) {
|
|
throw new Error("Cannot switch the portal session inside an active RLS context");
|
|
}
|
|
if (current?.publicKnowledgeBaseId && next.publicKnowledgeBaseId !== current.publicKnowledgeBaseId) {
|
|
throw new Error("Cannot switch the public knowledge base inside an active RLS context");
|
|
}
|
|
|
|
return rlsContext.run(next, callback);
|
|
}
|
|
|
|
/**
|
|
* Binds the separate customer-portal identity. A portal identity can never be
|
|
* combined with or inherited from the core User identity class.
|
|
*/
|
|
export function runWithPortalRlsContext<T>(
|
|
context: { tenantId: string; portalUserId: string; portalSessionId?: string },
|
|
callback: () => T
|
|
): T {
|
|
const current = rlsContext.getStore();
|
|
if (current?.userId || current?.publicKnowledgeBaseId || current?.platformAnalytics) {
|
|
throw new Error("Cannot bind a portal user inside a core or public RLS context");
|
|
}
|
|
return runWithRlsContext(context, callback);
|
|
}
|
|
|
|
/**
|
|
* Runs the anonymous knowledge-base surface without inheriting an authenticated
|
|
* user, tenant, operator privilege, or already-configured transaction.
|
|
*/
|
|
export function runWithIsolatedPublicKnowledgeBaseRlsContext<T>(publicKnowledgeBaseId: string, callback: () => T): T {
|
|
const next = normalizeContext({ publicKnowledgeBaseId });
|
|
return rlsContext.run(next, callback);
|
|
}
|
|
|
|
/**
|
|
* Runs tenantless, anonymous platform analytics without inheriting an
|
|
* authenticated identity, public capability, or configured transaction.
|
|
*/
|
|
export function runWithIsolatedPlatformAnalyticsRlsContext<T>(callback: () => T): T {
|
|
return rlsContext.run(normalizeContext({ platformAnalytics: true }), callback);
|
|
}
|
|
|
|
/**
|
|
* Drops an active tenant/transaction while retaining the already-authenticated
|
|
* user. Cross-tenant account cleanup uses this narrow boundary to re-prove
|
|
* membership independently for every tenant instead of switching a tenant GUC
|
|
* inside an existing tenant transaction.
|
|
*/
|
|
export function runWithIsolatedUserRlsContext<T>(userId: string, callback: () => T): T {
|
|
const current = rlsContext.getStore();
|
|
const normalizedUserId = normalizeIdentifier(userId, "userId");
|
|
if (!normalizedUserId || current?.userId !== normalizedUserId) {
|
|
throw new Error("An existing matching authenticated user context is required before isolating tenant access");
|
|
}
|
|
return rlsContext.run(normalizeContext({ userId: normalizedUserId }), callback);
|
|
}
|
|
|
|
export function runWithRlsTransaction<T>(transaction: RlsTransaction, callback: () => T): T {
|
|
const current = rlsContext.getStore();
|
|
if (!current?.tenantId && !current?.userId && !current?.portalUserId && !current?.publicKnowledgeBaseId && !current?.platformAnalytics) {
|
|
throw new Error("An authenticated RLS identity is required before binding a transaction");
|
|
}
|
|
if (current.transaction && current.transaction !== transaction) {
|
|
throw new Error("Cannot replace an active RLS transaction");
|
|
}
|
|
return rlsContext.run({ ...current, transaction }, callback);
|
|
}
|
|
|
|
export function getRlsExecutionContext(): Readonly<RlsExecutionContext> | null {
|
|
return rlsContext.getStore() ?? null;
|
|
}
|
|
|
|
function normalizeContext(context: RlsExecutionContext): RlsExecutionContext {
|
|
const userId = normalizeIdentifier(context.userId, "userId");
|
|
const portalUserId = normalizeIdentifier(context.portalUserId, "portalUserId");
|
|
const portalSessionId = normalizeIdentifier(context.portalSessionId, "portalSessionId");
|
|
const tenantId = normalizeIdentifier(context.tenantId, "tenantId");
|
|
const publicKnowledgeBaseId = normalizeIdentifier(context.publicKnowledgeBaseId, "publicKnowledgeBaseId");
|
|
if (userId && portalUserId) {
|
|
throw new Error("RLS userId and portalUserId are mutually exclusive");
|
|
}
|
|
if (portalSessionId && !portalUserId) {
|
|
throw new Error("RLS portalSessionId requires portalUserId");
|
|
}
|
|
if (context.platformAnalytics !== undefined && context.platformAnalytics !== true) {
|
|
throw new Error("RLS platformAnalytics must be true when provided");
|
|
}
|
|
return {
|
|
...(userId ? { userId } : {}),
|
|
...(portalUserId ? { portalUserId } : {}),
|
|
...(portalSessionId ? { portalSessionId } : {}),
|
|
...(tenantId ? { tenantId } : {}),
|
|
...(publicKnowledgeBaseId ? { publicKnowledgeBaseId } : {}),
|
|
...(context.platformAnalytics ? { platformAnalytics: true as const } : {}),
|
|
...(context.transaction ? { transaction: context.transaction } : {}),
|
|
};
|
|
}
|
|
|
|
function normalizeIdentifier(
|
|
value: string | undefined,
|
|
name: "tenantId" | "userId" | "portalUserId" | "portalSessionId" | "publicKnowledgeBaseId"
|
|
): string | undefined {
|
|
if (value === undefined) return undefined;
|
|
const normalized = value.trim();
|
|
if (normalized.length === 0) {
|
|
throw new Error(`RLS ${name} must not be empty`);
|
|
}
|
|
if (normalized.length > 191 || normalized.includes("\u0000")) {
|
|
throw new Error(`RLS ${name} is invalid`);
|
|
}
|
|
return normalized;
|
|
}
|