Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+3
@@ -43,6 +43,9 @@ describeIfDb("Apps-Engine RLS tenant isolation gate proof (DataConnection, AppSy
|
||||
await admin.connect();
|
||||
|
||||
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8"));
|
||||
// Production credentials are intentionally not part of the rollout SQL.
|
||||
// Set a disposable password only inside this throwaway integration database.
|
||||
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
|
||||
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/apps-engine-isolation.sql"), "utf8"));
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repoRoot = path.resolve(process.cwd());
|
||||
const rlsDirectory = path.join(repoRoot, "prisma", "rls");
|
||||
|
||||
function executableSql(relativePath: string): string {
|
||||
return readFileSync(path.join(rlsDirectory, relativePath), "utf8").replace(/--.*$/gm, "");
|
||||
}
|
||||
|
||||
describe("RLS rollout artifacts", () => {
|
||||
it("never provisions a reusable database password from repository SQL", () => {
|
||||
const violations = readdirSync(rlsDirectory)
|
||||
.filter((file) => file.endsWith(".sql"))
|
||||
.filter((file) => /\b(?:CREATE|ALTER)\s+(?:ROLE|USER)\b[^;]*\bPASSWORD\b/is.test(executableSql(file)));
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the canonical transaction-local tenant context name in every isolation policy", () => {
|
||||
const isolationFiles = readdirSync(rlsDirectory).filter((file) => file.endsWith("-isolation.sql"));
|
||||
const violations = isolationFiles.filter((file) => {
|
||||
const sql = executableSql(file);
|
||||
return !sql.includes("app.tenant_id") || sql.includes("app.current_tenant_id");
|
||||
});
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps global automation templates read-only for the tenant runtime role", () => {
|
||||
const sql = executableSql("automation-isolation.sql");
|
||||
const selectPolicy = /CREATE POLICY "tenant_isolation_automation_template_select"[\s\S]*?;/i.exec(sql)?.[0];
|
||||
const mutablePolicies = [...sql.matchAll(/CREATE POLICY "tenant_isolation_automation_template_(?:insert|update|delete)"[\s\S]*?;/gi)].map(
|
||||
(match) => match[0],
|
||||
);
|
||||
|
||||
expect(selectPolicy).toContain('"tenantId" IS NULL OR');
|
||||
expect(mutablePolicies).toHaveLength(3);
|
||||
for (const policy of mutablePolicies) {
|
||||
expect(policy).toContain("current_setting('app.tenant_id', true)");
|
||||
expect(policy).not.toContain('"tenantId" IS NULL');
|
||||
}
|
||||
});
|
||||
});
|
||||
+3
@@ -52,6 +52,9 @@ describeIfDb("Email-inbox RLS tenant isolation gate proof (EmailIntegrationMailb
|
||||
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
|
||||
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(baseSql);
|
||||
// Production credentials are intentionally not part of the rollout SQL.
|
||||
// Set a disposable password only inside this throwaway integration database.
|
||||
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
|
||||
// 2) Email-inbox RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs
|
||||
// on the four VA-P23 tables (the deferred P5 activation artifact).
|
||||
const emailInboxRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/email-inbox-isolation.sql"), "utf8");
|
||||
|
||||
+3
@@ -53,6 +53,9 @@ describeIfDb("File RLS tenant isolation gate proof (File, FileEntityLink)", () =
|
||||
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
|
||||
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(baseSql);
|
||||
// Production credentials are intentionally not part of the rollout SQL.
|
||||
// Set a disposable password only inside this throwaway integration database.
|
||||
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
|
||||
// 2) File RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
|
||||
// four Files tables (the deferred P5 activation artifact, applied here).
|
||||
const fileRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/file-isolation.sql"), "utf8");
|
||||
|
||||
+85
-1
@@ -14,7 +14,7 @@ const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..
|
||||
// AK-P17a — HR RLS GATE PROOF. Companion to the task/file/tenant isolation tests:
|
||||
// proves that once the HR RLS block (prisma/rls/hr-isolation.sql) is applied, the
|
||||
// restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is confined to its own
|
||||
// tenant's HR rows (here: HrEmployeeProfile + EmployeePasswordSafeEntry), sees
|
||||
// tenant's HR rows (including all three password-safe tables), sees
|
||||
// nothing without a tenant context, and is blocked by WITH CHECK from writing
|
||||
// cross-tenant rows. This is what makes the P5 activation a pure switch: the
|
||||
// wrapped hr*Service helpers already set the GUC, so flipping RLS on cannot break
|
||||
@@ -53,6 +53,9 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
|
||||
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(baseSql);
|
||||
// Production credentials are intentionally not part of the rollout SQL.
|
||||
// Set a disposable password only inside this throwaway integration database.
|
||||
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
|
||||
// 2) HR RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the HR
|
||||
// tables (the deferred P5 activation artifact, applied here).
|
||||
const hrRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/hr-isolation.sql"), "utf8");
|
||||
@@ -74,6 +77,18 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
('rls_entryA',now(),'rls_tenantA','rls_vaultA','Entry A'),
|
||||
('rls_entryB',now(),'rls_tenantB','rls_vaultB','Entry B')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "EmployeePasswordSafeAccess"(id,"updatedAt","tenantId","vaultId","userId","permissionLevel","grantedByUserId") VALUES
|
||||
('rls_accessA',now(),'rls_tenantA','rls_vaultA','rls_userA','admin','rls_userA'),
|
||||
('rls_accessB',now(),'rls_tenantB','rls_vaultB','rls_userB','admin','rls_userB')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "HrAnnouncement"(id,"updatedAt","tenantId","authorUserId",title,body,"audienceKind","audienceRef") VALUES
|
||||
('rls_announcementA',now(),'rls_tenantA','rls_userA','Team A','Body A','team','team-A'),
|
||||
('rls_announcementB',now(),'rls_tenantB','rls_userB','Team B','Body B','team','team-B')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
await admin.query(`INSERT INTO "HrSurvey"(id,"updatedAt","tenantId","authorUserId",title,"audienceKind","audienceRef") VALUES
|
||||
('rls_surveyA',now(),'rls_tenantA','rls_userA','Survey A','location','location-A'),
|
||||
('rls_surveyB',now(),'rls_tenantB','rls_userB','Survey B','location','location-B')
|
||||
ON CONFLICT (id) DO NOTHING`);
|
||||
|
||||
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
|
||||
await app.connect();
|
||||
@@ -112,6 +127,23 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it("isolates audience-targeted announcements and surveys before object gates run", async () => {
|
||||
const visible = await underTenant("rls_tenantA", async () => {
|
||||
const announcements = (
|
||||
await app.query(`SELECT id FROM "HrAnnouncement" ORDER BY id`)
|
||||
).rows.map((row) => row.id);
|
||||
const surveys = (await app.query(`SELECT id FROM "HrSurvey" ORDER BY id`)).rows.map(
|
||||
(row) => row.id,
|
||||
);
|
||||
return { announcements, surveys };
|
||||
});
|
||||
|
||||
expect(visible).toEqual({
|
||||
announcements: ["rls_announcementA"],
|
||||
surveys: ["rls_surveyA"],
|
||||
});
|
||||
});
|
||||
|
||||
it("sees no HR rows at all when no tenant context is set", async () => {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "HrEmployeeProfile"`)).rows[0].c;
|
||||
expect(count).toBe(0);
|
||||
@@ -131,4 +163,56 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
|
||||
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "EmployeePasswordSafeEntry" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
|
||||
expect(crossCount).toBe(0);
|
||||
});
|
||||
|
||||
it("forces RLS on vault, entry and access rows for the restricted app role", async () => {
|
||||
const { rows } = await admin.query(`
|
||||
SELECT relname, relrowsecurity, relforcerowsecurity
|
||||
FROM pg_class
|
||||
WHERE relnamespace = 'public'::regnamespace
|
||||
AND relname IN ('EmployeePasswordSafeAccess', 'EmployeePasswordSafeEntry', 'EmployeePasswordSafeVault')
|
||||
ORDER BY relname
|
||||
`);
|
||||
expect(rows).toHaveLength(3);
|
||||
expect(rows.every((row) => row.relrowsecurity && row.relforcerowsecurity)).toBe(true);
|
||||
});
|
||||
|
||||
it("isolates vault grants and blocks cross-tenant IDOR writes", async () => {
|
||||
const visible = await underTenant("rls_tenantA", async () => {
|
||||
const vaults = (await app.query(`SELECT id FROM "EmployeePasswordSafeVault" ORDER BY id`)).rows.map((row) => row.id);
|
||||
const access = (await app.query(`SELECT id FROM "EmployeePasswordSafeAccess" ORDER BY id`)).rows.map((row) => row.id);
|
||||
return { vaults, access };
|
||||
});
|
||||
expect(visible).toEqual({ vaults: ["rls_vaultA"], access: ["rls_accessA"] });
|
||||
|
||||
await expect(
|
||||
underTenant("rls_tenantA", () =>
|
||||
app.query(`INSERT INTO "EmployeePasswordSafeAccess"(id,"updatedAt","tenantId","vaultId","userId","permissionLevel","grantedByUserId")
|
||||
VALUES ('rls_accessX',now(),'rls_tenantB','rls_vaultB','rls_userA','read','rls_userA')`)
|
||||
)
|
||||
).rejects.toThrow(/row-level security/i);
|
||||
});
|
||||
|
||||
it("returns no vault, entry or access metadata without a bound tenant", async () => {
|
||||
for (const table of ["EmployeePasswordSafeVault", "EmployeePasswordSafeEntry", "EmployeePasswordSafeAccess"]) {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "${table}"`)).rows[0].c;
|
||||
expect(count, table).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("forces RLS and returns no audience metadata without a bound tenant", async () => {
|
||||
for (const table of ["HrAnnouncement", "HrSurvey"]) {
|
||||
const count = (await app.query(`SELECT count(*)::int AS c FROM "${table}"`)).rows[0].c;
|
||||
expect(count, table).toBe(0);
|
||||
}
|
||||
|
||||
const { rows } = await admin.query(`
|
||||
SELECT relname, relrowsecurity, relforcerowsecurity
|
||||
FROM pg_class
|
||||
WHERE relnamespace = 'public'::regnamespace
|
||||
AND relname IN ('HrAnnouncement', 'HrSurvey')
|
||||
ORDER BY relname
|
||||
`);
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows.every((row) => row.relrowsecurity && row.relforcerowsecurity)).toBe(true);
|
||||
});
|
||||
});
|
||||
+3
@@ -53,6 +53,9 @@ describeIfDb("Task RLS tenant isolation gate proof (Task, TaskWatcher, EntityLin
|
||||
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
|
||||
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(baseSql);
|
||||
// Production credentials are intentionally not part of the rollout SQL.
|
||||
// Set a disposable password only inside this throwaway integration database.
|
||||
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
|
||||
// 2) Task RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
|
||||
// three Task tables (the deferred P5 activation artifact, applied here).
|
||||
const taskRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/task-isolation.sql"), "utf8");
|
||||
|
||||
+3
@@ -39,6 +39,9 @@ describeIfDb("RLS tenant isolation gate proof (TenantUser)", () => {
|
||||
// 1) RLS-Mechanik + restricted Rolle + Policy aus dem committeten SQL anwenden (idempotent).
|
||||
const rlsSql = fs.readFileSync(path.resolve(process.cwd(), "prisma/rls/tenant-isolation.sql"), "utf8");
|
||||
await admin.query(rlsSql);
|
||||
// Production credentials are intentionally not part of the rollout SQL.
|
||||
// Set a disposable password only inside this throwaway integration database.
|
||||
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
|
||||
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
|
||||
|
||||
// 2) Zwei Tenants + User + Memberships seeden (als Superuser -> bypasst RLS).
|
||||
|
||||
+7
-4
@@ -1,4 +1,5 @@
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
@@ -18,8 +19,10 @@ export async function withTenantRLS<T>(tenantId: string, callback: (tx: TenantRl
|
||||
if (!tenantId) {
|
||||
throw new Error("withTenantRLS requires a non-empty tenantId");
|
||||
}
|
||||
return db.$transaction(async (tx: TenantRlsClient) => {
|
||||
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
|
||||
return callback(tx);
|
||||
});
|
||||
return runWithRlsContext({ tenantId }, () =>
|
||||
db.$transaction(async (tx: TenantRlsClient) => {
|
||||
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
|
||||
return callback(tx);
|
||||
}),
|
||||
);
|
||||
}
|
||||
+70
-74
@@ -1,33 +1,35 @@
|
||||
import { adminGetAllLegacyTenantSummaries } from "@hivegrid/db/accounts.server";
|
||||
import {
|
||||
createLegacyApiKeyLog,
|
||||
createLegacyApiKey,
|
||||
countLegacyApiKeyLogsForKey,
|
||||
deleteLegacyApiKey,
|
||||
adminFindLegacyApiKeyById,
|
||||
findFirstLegacyActiveApiKey,
|
||||
findLegacyApiKeyByAlias,
|
||||
findLegacyApiKeyById,
|
||||
findLegacyApiKeyByKey,
|
||||
getAllLegacyApiKeys,
|
||||
findRedactedLegacyApiKeyByAlias,
|
||||
findRedactedLegacyApiKeyById,
|
||||
getRedactedLegacyApiKeysForTenant,
|
||||
rotateLegacyApiKey,
|
||||
getLegacyApiKeyLogsForKey,
|
||||
getLegacyApiKeysForTenant,
|
||||
type LegacyApiKeyLogWithDetails,
|
||||
type LegacyRedactedApiKeyWithDetails,
|
||||
type LegacyApiKeySimple,
|
||||
type LegacyApiKeyWithDetails,
|
||||
updateLegacyApiKey,
|
||||
} from "@hivegrid/db/api-keys.server";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { db } from "../db.server";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
||||
import { cachified, clearCacheKey } from "../cache.server";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
|
||||
import { invalidateApiKeySnapshot, loadCachedApiKeySnapshot } from "../api/api-key-auth-cache.server";
|
||||
|
||||
export type ApiKeyWithDetails = LegacyApiKeyWithDetails;
|
||||
export type RedactedApiKeyWithDetails = Omit<LegacyApiKeyWithDetails, "key">;
|
||||
export type RedactedApiKeyWithDetails = LegacyRedactedApiKeyWithDetails;
|
||||
|
||||
export function redactApiKeyForDisplay(apiKey: LegacyApiKeyWithDetails): RedactedApiKeyWithDetails {
|
||||
const redactedApiKey = { ...apiKey };
|
||||
@@ -40,13 +42,11 @@ export function redactApiKeysForDisplay(apiKeys: LegacyApiKeyWithDetails[]): Red
|
||||
}
|
||||
|
||||
export type ApiKeyLogWithDetails = LegacyApiKeyLogWithDetails;
|
||||
export type ApiKeyLogSimple = { apiKeyId: string | null; status: number | null };
|
||||
|
||||
export type ApiKeySimple = LegacyApiKeySimple;
|
||||
|
||||
export async function getAllApiKeys(): Promise<RedactedApiKeyWithDetails[]> {
|
||||
const apiKeys = await getAllLegacyApiKeys();
|
||||
return redactApiKeysForDisplay(apiKeys);
|
||||
const groups = await mapAdminTenants((tenantId) => getRedactedLegacyApiKeysForTenant(tenantId));
|
||||
return groups.flat().sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
|
||||
}
|
||||
|
||||
export async function getAllApiKeyLogs(
|
||||
@@ -82,27 +82,6 @@ export async function getAllApiKeyLogs(
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAllApiKeyLogsSimple(tenantId?: string): Promise<ApiKeyLogSimple[]> {
|
||||
let where: any = {};
|
||||
if (tenantId) {
|
||||
where = {
|
||||
apiKey: {
|
||||
tenantId,
|
||||
},
|
||||
};
|
||||
}
|
||||
return await db.apiKeyLog.findMany({
|
||||
where,
|
||||
select: {
|
||||
apiKeyId: true,
|
||||
status: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantApiKeyLogs(
|
||||
tenantId: string,
|
||||
pagination: { page: number; pageSize: number },
|
||||
@@ -131,60 +110,40 @@ export async function getTenantApiKeyLogs(
|
||||
}
|
||||
|
||||
export async function getApiKeys(tenantId: string): Promise<RedactedApiKeyWithDetails[]> {
|
||||
const apiKeys = await getLegacyApiKeysForTenant(tenantId);
|
||||
return redactApiKeysForDisplay(apiKeys);
|
||||
return runWithRlsContext({ tenantId }, () => getRedactedLegacyApiKeysForTenant(tenantId));
|
||||
}
|
||||
|
||||
export async function adminGetApiKeyById(id: string): Promise<RedactedApiKeyWithDetails | null> {
|
||||
const apiKey = await adminFindLegacyApiKeyById(id);
|
||||
return apiKey ? redactApiKeyForDisplay(apiKey) : null;
|
||||
return findAdminApiKeyById(id);
|
||||
}
|
||||
|
||||
export async function getTenantApiKeyById(id: string, tenantId: string): Promise<RedactedApiKeyWithDetails | null> {
|
||||
const apiKey = await findLegacyApiKeyById({ id, tenantId });
|
||||
return apiKey ? redactApiKeyForDisplay(apiKey) : null;
|
||||
}
|
||||
|
||||
export async function adminGetApiKeyByIdWithSecret(id: string): Promise<ApiKeyWithDetails | null> {
|
||||
return adminFindLegacyApiKeyById(id);
|
||||
}
|
||||
|
||||
export async function getTenantApiKeyByIdWithSecret(id: string, tenantId: string): Promise<ApiKeyWithDetails | null> {
|
||||
return findLegacyApiKeyById({ id, tenantId });
|
||||
return runWithRlsContext({ tenantId }, () => findRedactedLegacyApiKeyById({ id, tenantId }));
|
||||
}
|
||||
|
||||
export async function getApiKey(key: string): Promise<ApiKeySimple | null> {
|
||||
return await cachified({
|
||||
key: getApiKeyLookupCacheKey(key),
|
||||
ttl: 1000 * 60 * 60,
|
||||
getFreshValue: () => findLegacyApiKeyByKey(key),
|
||||
});
|
||||
return loadCachedApiKeySnapshot(getApiKeyLookupCacheKey(key), () => findLegacyApiKeyByKey(key));
|
||||
}
|
||||
|
||||
export async function getApiKeyByAlias(tenantId: string, alias: string): Promise<ApiKeyWithDetails | null> {
|
||||
return findLegacyApiKeyByAlias(tenantId, alias);
|
||||
export async function getApiKeyByAlias(tenantId: string, alias: string): Promise<RedactedApiKeyWithDetails | null> {
|
||||
return runWithRlsContext({ tenantId }, () => findRedactedLegacyApiKeyByAlias(tenantId, alias));
|
||||
}
|
||||
|
||||
export async function getApiKeyLogs(id: string, tenantId: string): Promise<ApiKeyLogWithDetails[]> {
|
||||
return getLegacyApiKeyLogsForKey({ id, tenantId });
|
||||
return runWithRlsContext({ tenantId }, () => getLegacyApiKeyLogsForKey({ id, tenantId }));
|
||||
}
|
||||
|
||||
export async function countApiKeyLogsForKey(id: string, tenantId: string): Promise<number> {
|
||||
return countLegacyApiKeyLogsForKey({ id, tenantId });
|
||||
return runWithRlsContext({ tenantId }, () => countLegacyApiKeyLogsForKey({ id, tenantId }));
|
||||
}
|
||||
|
||||
export async function getFirstApiKey(tenantId: string | null) {
|
||||
return findFirstLegacyActiveApiKey(tenantId);
|
||||
if (!tenantId) return null;
|
||||
return runWithRlsContext({ tenantId }, () => findFirstLegacyActiveApiKey(tenantId));
|
||||
}
|
||||
|
||||
export async function createApiKey(data: {
|
||||
tenantId: string;
|
||||
createdByUserId: string;
|
||||
alias: string;
|
||||
expires: Date | null;
|
||||
active: boolean;
|
||||
}) {
|
||||
return createLegacyApiKey(data, undefined, getApiKeyHashSecret());
|
||||
export async function createApiKey(data: { tenantId: string; createdByUserId: string; alias: string; expires: Date | null; active: boolean }) {
|
||||
return runWithRlsContext({ tenantId: data.tenantId }, () => createLegacyApiKey(data, undefined, getApiKeyHashSecret()));
|
||||
}
|
||||
|
||||
export async function createApiKeyLog(
|
||||
@@ -207,7 +166,7 @@ export async function createApiKeyLog(
|
||||
status: data.status,
|
||||
alias: data.alias,
|
||||
tenantName: data.tenantName,
|
||||
ip: getClientIPAddress(request.headers)?.toString() ?? "",
|
||||
ip: getTrustedClientIpOrNull(request) ?? "",
|
||||
method: request.method,
|
||||
params: serializeApiLogSearchParams(request),
|
||||
});
|
||||
@@ -222,36 +181,73 @@ export async function updateApiKey(
|
||||
active: boolean;
|
||||
}
|
||||
) {
|
||||
const apiKey = await updateLegacyApiKey(id, data);
|
||||
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
|
||||
const apiKey = await runWithRlsContext({ tenantId: data.tenantId }, () => updateLegacyApiKey(id, data));
|
||||
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(apiKey.key));
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
export async function rotateApiKey(id: string, tenantId: string) {
|
||||
const previousApiKey = await findLegacyApiKeyById({ id, tenantId });
|
||||
const previousApiKey = await runWithRlsContext({ tenantId }, () => findLegacyApiKeyById({ id, tenantId }));
|
||||
if (!previousApiKey) {
|
||||
throw new Error(`API key ${id} not found`);
|
||||
}
|
||||
const apiKey = await rotateLegacyApiKey({ id, tenantId: previousApiKey.tenantId }, undefined, getApiKeyHashSecret());
|
||||
const apiKey = await runWithRlsContext({ tenantId }, () => rotateLegacyApiKey({ id, tenantId: previousApiKey.tenantId }, undefined, getApiKeyHashSecret()));
|
||||
|
||||
if (previousApiKey?.key) {
|
||||
clearCacheKey(getApiKeyLookupCacheKey(previousApiKey.key));
|
||||
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(previousApiKey.key));
|
||||
}
|
||||
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
|
||||
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(apiKey.key));
|
||||
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
export async function deleteApiKey(id: string, tenantId: string) {
|
||||
const previousApiKey = await findLegacyApiKeyById({ id, tenantId });
|
||||
const previousApiKey = await runWithRlsContext({ tenantId }, () => findLegacyApiKeyById({ id, tenantId }));
|
||||
if (!previousApiKey) {
|
||||
throw new Error(`API key ${id} not found`);
|
||||
}
|
||||
const apiKey = await deleteLegacyApiKey({ id, tenantId: previousApiKey.tenantId });
|
||||
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
|
||||
const apiKey = await runWithRlsContext({ tenantId }, () => deleteLegacyApiKey({ id, tenantId: previousApiKey.tenantId }));
|
||||
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(apiKey.key));
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
function getApiKeyHashSecret() {
|
||||
return loadRequiredWebConfig().jwtSecret;
|
||||
}
|
||||
|
||||
async function findAdminApiKeyById(id: string): Promise<RedactedApiKeyWithDetails | null> {
|
||||
const normalizedId = id.trim();
|
||||
if (!normalizedId) return null;
|
||||
|
||||
const matches = (await mapAdminTenants((tenantId) => findRedactedLegacyApiKeyById({ id: normalizedId, tenantId }))).filter(
|
||||
(item): item is RedactedApiKeyWithDetails => item !== null
|
||||
);
|
||||
if (matches.length > 1) {
|
||||
throw new Error(`API key ${normalizedId} resolved to more than one tenant`);
|
||||
}
|
||||
return matches[0] ?? null;
|
||||
}
|
||||
|
||||
async function mapAdminTenants<T>(operation: (tenantId: string) => Promise<T>): Promise<T[]> {
|
||||
const context = getRlsExecutionContext();
|
||||
if (!context?.userId || context.tenantId) {
|
||||
throw new Error("Admin API key access requires an unscoped authenticated operator context");
|
||||
}
|
||||
|
||||
const tenants = await adminGetAllLegacyTenantSummaries();
|
||||
return mapWithConcurrency(tenants, 8, ({ id }) => runWithRlsContext({ tenantId: id }, () => operation(id)));
|
||||
}
|
||||
|
||||
async function mapWithConcurrency<T, U>(items: readonly T[], concurrency: number, operation: (item: T) => Promise<U>): Promise<U[]> {
|
||||
const results = new Array<U>(items.length);
|
||||
let cursor = 0;
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(concurrency, items.length) }, async () => {
|
||||
while (cursor < items.length) {
|
||||
const index = cursor++;
|
||||
results[index] = await operation(items[index]!);
|
||||
}
|
||||
})
|
||||
);
|
||||
return results;
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import type { AppConfiguration as AppConfigurationRow } from "@hivegrid/db/prisma-browser";
|
||||
import { createTwoTierCache, type CacheSerializer, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
|
||||
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const log = createScopedLogger("app-configuration-cache");
|
||||
|
||||
export const APP_CONFIGURATION_CACHE_TTL_SECONDS = 30;
|
||||
const APP_CONFIGURATION_CACHE_KEY = "global";
|
||||
|
||||
type SerializedAppConfiguration = Omit<AppConfigurationRow, "updatedAt"> & { updatedAt: string };
|
||||
|
||||
const appConfigurationSerializer: CacheSerializer<AppConfigurationRow> = {
|
||||
serialize(value) {
|
||||
return JSON.stringify({ ...value, updatedAt: value.updatedAt.toISOString() } satisfies SerializedAppConfiguration);
|
||||
},
|
||||
deserialize(raw) {
|
||||
const value = JSON.parse(raw) as SerializedAppConfiguration;
|
||||
return { ...value, updatedAt: new Date(value.updatedAt) };
|
||||
},
|
||||
};
|
||||
|
||||
function pubsubEnabledFromEnv(): boolean {
|
||||
const raw = process.env.CACHE_INVALIDATION_ENABLED;
|
||||
if (raw === undefined || raw === null || raw === "") return true;
|
||||
return raw.toLowerCase() !== "false" && raw !== "0";
|
||||
}
|
||||
|
||||
export function createAppConfigurationCache(store: SharedStore, options: { now?: () => number } = {}): TwoTierCache<AppConfigurationRow> {
|
||||
return createTwoTierCache<AppConfigurationRow>({
|
||||
store,
|
||||
namespace: "app-configuration",
|
||||
ttlSeconds: APP_CONFIGURATION_CACHE_TTL_SECONDS,
|
||||
l1MaxEntries: 1,
|
||||
l1Now: options.now,
|
||||
serializer: appConfigurationSerializer,
|
||||
pubsubEnabled: pubsubEnabledFromEnv(),
|
||||
logger: {
|
||||
warn: (obj, msg) => log.warn(obj, msg),
|
||||
info: (obj, msg) => log.info(obj, msg),
|
||||
error: (obj, msg) => log.error(obj, msg),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let cacheSingleton: TwoTierCache<AppConfigurationRow> | null = null;
|
||||
let subscribeDisposer: (() => Promise<void>) | null = null;
|
||||
|
||||
function getAppConfigurationCache(): TwoTierCache<AppConfigurationRow> {
|
||||
cacheSingleton ??= createAppConfigurationCache(getSharedStore());
|
||||
return cacheSingleton;
|
||||
}
|
||||
|
||||
export async function loadCachedAppConfiguration(getFreshValue: () => Promise<AppConfigurationRow | null>): Promise<AppConfigurationRow | null> {
|
||||
const cache = getAppConfigurationCache();
|
||||
try {
|
||||
const cached = await cache.get(APP_CONFIGURATION_CACHE_KEY);
|
||||
if (cached !== null) return cached;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "app-configuration-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"App configuration cache read failed; falling back to the database."
|
||||
);
|
||||
}
|
||||
|
||||
const fresh = await getFreshValue();
|
||||
if (fresh !== null) {
|
||||
try {
|
||||
await cache.set(APP_CONFIGURATION_CACHE_KEY, fresh);
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "app-configuration-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"App configuration cache write failed; continuing with the database result."
|
||||
);
|
||||
}
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/** Fail closed because this row controls auth policy and injected scripts. */
|
||||
export async function invalidateAppConfigurationCache(): Promise<void> {
|
||||
clearCacheKey("appConfiguration");
|
||||
const cache = getAppConfigurationCache();
|
||||
cache.deleteLocal(APP_CONFIGURATION_CACHE_KEY);
|
||||
await cache.l2.invalidate(APP_CONFIGURATION_CACHE_KEY);
|
||||
}
|
||||
|
||||
export async function subscribeAppConfigurationCache(): Promise<() => Promise<void>> {
|
||||
if (subscribeDisposer) return subscribeDisposer;
|
||||
subscribeDisposer = await getAppConfigurationCache().subscribe();
|
||||
log.info({ namespace: "app-configuration" }, "App configuration cache subscriber started.");
|
||||
return subscribeDisposer;
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export function __resetAppConfigurationCacheForTests(): void {
|
||||
cacheSingleton = null;
|
||||
subscribeDisposer = null;
|
||||
}
|
||||
+7
@@ -28,4 +28,11 @@ describe("appConfiguration web config adoption", () => {
|
||||
expect(source).toContain("simpleAnalytics: false");
|
||||
expect(source).toContain("ipLookup: false");
|
||||
});
|
||||
|
||||
test("fails safe to email verification for a fresh deployment while preserving persisted overrides", () => {
|
||||
expect(source).toContain("auth: {\n // A deployment without a persisted AppConfiguration");
|
||||
expect(source).toContain("requireEmailVerification: true");
|
||||
expect(source).toContain("conf.auth.requireEmailVerification = appConfiguration?.authRequireEmailVerification");
|
||||
expect(source).toContain("authRequireEmailVerification: conf.auth.requireEmailVerification");
|
||||
});
|
||||
});
|
||||
+12
-15
@@ -3,12 +3,12 @@ import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPublicAuthProviders } from "../auth/authProviders.server";
|
||||
import { cachified, clearCacheKey } from "../cache.server";
|
||||
import { db } from "../db.server";
|
||||
import { defaultTheme } from "../theme/defaultThemes";
|
||||
import { getBaseURL, getDomainName } from "../url.server";
|
||||
import { PortalConfiguration, getAppPortalConfiguration } from "./appPortalConfiguration.db.server";
|
||||
import { getWidgetsConfiguration, WidgetsConfiguration } from "./appWidgetsConfiguration.db.server";
|
||||
import { invalidateAppConfigurationCache, loadCachedAppConfiguration } from "./app-configuration-cache.server";
|
||||
|
||||
export type AppConfiguration = {
|
||||
app: {
|
||||
@@ -19,7 +19,6 @@ export type AppConfiguration = {
|
||||
company?: { name: string; address: string };
|
||||
features: {
|
||||
tenantHome: "/:tenant/" | "/";
|
||||
tenantTypes: boolean;
|
||||
tenantApiKeys?: boolean;
|
||||
tenantEntityCustomization?: boolean;
|
||||
crm: boolean;
|
||||
@@ -126,7 +125,6 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
|
||||
tenantApiKeys: true,
|
||||
tenantEntityCustomization: false,
|
||||
crm: false,
|
||||
tenantTypes: false,
|
||||
tenantWorkflows: false,
|
||||
tenantEmailMarketing: false,
|
||||
tenantFeedback: true,
|
||||
@@ -134,7 +132,10 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
|
||||
},
|
||||
email: defaultEmailConfig,
|
||||
auth: {
|
||||
requireEmailVerification: false,
|
||||
// A deployment without a persisted AppConfiguration must not silently
|
||||
// skip ownership proof for a public email address. Explicitly configured
|
||||
// rows still override this launch-safe default below.
|
||||
requireEmailVerification: true,
|
||||
requireOrganization: false,
|
||||
requireName: false,
|
||||
slug: { require: false, type: "username" },
|
||||
@@ -202,11 +203,7 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
|
||||
scripts: { head: null, body: null },
|
||||
};
|
||||
|
||||
const appConfiguration = await cachified({
|
||||
key: `appConfiguration`,
|
||||
ttl: 1000 * 60 * 60 * 24, // 1 day
|
||||
getFreshValue: async () => db.appConfiguration.findFirst(),
|
||||
});
|
||||
const appConfiguration = await loadCachedAppConfiguration(() => db.appConfiguration.findFirst());
|
||||
if (!appConfiguration) {
|
||||
return conf;
|
||||
}
|
||||
@@ -284,8 +281,8 @@ export async function getOrCreateAppConfiguration({ request }: { request: Reques
|
||||
brandingFavicon: conf.branding.favicon,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`appConfiguration`);
|
||||
.then(async (item) => {
|
||||
await invalidateAppConfigurationCache();
|
||||
return item;
|
||||
});
|
||||
}
|
||||
@@ -308,15 +305,15 @@ export async function updateAppConfiguration(data: Prisma.AppConfigurationUpdate
|
||||
.updateMany({
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`appConfiguration`);
|
||||
.then(async (item) => {
|
||||
await invalidateAppConfigurationCache();
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAppConfiguration() {
|
||||
return await db.appConfiguration.deleteMany({ where: {} }).then((item) => {
|
||||
clearCacheKey(`appConfiguration`);
|
||||
return await db.appConfiguration.deleteMany({ where: {} }).then(async (item) => {
|
||||
await invalidateAppConfigurationCache();
|
||||
return item;
|
||||
});
|
||||
}
|
||||
-15
@@ -8,12 +8,6 @@ export type PortalConfiguration = {
|
||||
forTenants: boolean;
|
||||
pricing: boolean;
|
||||
analytics: boolean;
|
||||
domains?: {
|
||||
enabled: boolean;
|
||||
provider: "fly";
|
||||
portalAppId: string;
|
||||
records?: { A: string; AAAA: string };
|
||||
};
|
||||
metadata: Array<JsonPropertyDto> | undefined;
|
||||
pages: Array<PortalPageConfigDto>;
|
||||
};
|
||||
@@ -80,15 +74,6 @@ export function getAppPortalConfiguration({ t }: { t: TFunction }): PortalConfig
|
||||
forTenants: true,
|
||||
pricing: true,
|
||||
analytics: true,
|
||||
domains: {
|
||||
enabled: true,
|
||||
provider: "fly",
|
||||
portalAppId: "app-portal",
|
||||
records: {
|
||||
A: "66.241.125.25",
|
||||
AAAA: "2a09:8280:1::31:5dc2:0",
|
||||
},
|
||||
},
|
||||
metadata: [],
|
||||
pages: [
|
||||
{
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ export type WidgetsConfiguration = {
|
||||
metadata: Array<JsonPropertyDto> | undefined;
|
||||
};
|
||||
|
||||
export function getWidgetsConfiguration({ t }: { t: TFunction }): WidgetsConfiguration {
|
||||
export function getWidgetsConfiguration({ t: _t }: { t: TFunction }): WidgetsConfiguration {
|
||||
const conf: WidgetsConfiguration = {
|
||||
enabled: false,
|
||||
metadata: [
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@hivegrid/db/pretenant-security.server", () => ({
|
||||
addBlacklistCapability: vi.fn(),
|
||||
findBlacklistCapability: vi.fn(),
|
||||
recordBlacklistAttemptCapability: vi.fn(),
|
||||
}));
|
||||
vi.mock("../db.server", () => ({
|
||||
db: {
|
||||
blacklist: {
|
||||
create: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("../logger.server", () => ({
|
||||
createScopedLogger: vi.fn(() => ({ info: vi.fn() })),
|
||||
}));
|
||||
|
||||
import { addBlacklistCapability, findBlacklistCapability, recordBlacklistAttemptCapability } from "@hivegrid/db/pretenant-security.server";
|
||||
import { db } from "../db.server";
|
||||
import { addBlacklistAttempt, addToBlacklist, findInBlacklist } from "./blacklist.db.server";
|
||||
|
||||
const blacklistItem = {
|
||||
id: "blacklist_1",
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
type: "email",
|
||||
value: "blocked@example.test",
|
||||
active: true,
|
||||
registerAttempts: 2,
|
||||
};
|
||||
const addCapabilityMock = vi.mocked(addBlacklistCapability);
|
||||
const findCapabilityMock = vi.mocked(findBlacklistCapability);
|
||||
const recordAttemptMock = vi.mocked(recordBlacklistAttemptCapability);
|
||||
const directTableMock = vi.mocked(db.blacklist, true);
|
||||
|
||||
describe("blacklist db helpers", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("uses the exact-match capability instead of a direct table read", async () => {
|
||||
findCapabilityMock.mockResolvedValueOnce(blacklistItem);
|
||||
|
||||
await expect(findInBlacklist("email", "blocked@example.test")).resolves.toEqual(blacklistItem);
|
||||
|
||||
expect(findCapabilityMock).toHaveBeenCalledWith("email", "blocked@example.test");
|
||||
expect(directTableMock.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("records attempts atomically through the capability", async () => {
|
||||
recordAttemptMock.mockResolvedValueOnce({ ...blacklistItem, registerAttempts: 3 });
|
||||
|
||||
await expect(addBlacklistAttempt(blacklistItem)).resolves.toMatchObject({ registerAttempts: 3 });
|
||||
|
||||
expect(recordAttemptMock).toHaveBeenCalledWith(blacklistItem);
|
||||
expect(directTableMock.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates runtime blacklist entries through the capability", async () => {
|
||||
addCapabilityMock.mockResolvedValueOnce(blacklistItem);
|
||||
|
||||
await expect(addToBlacklist({ type: "email", value: "blocked@example.test" })).resolves.toEqual(blacklistItem);
|
||||
|
||||
expect(addCapabilityMock).toHaveBeenCalledWith({ type: "email", value: "blocked@example.test" });
|
||||
expect(directTableMock.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+6
-23
@@ -1,4 +1,5 @@
|
||||
import { Blacklist } from "@hivegrid/db/prisma-browser";
|
||||
import { addBlacklistCapability, findBlacklistCapability, recordBlacklistAttemptCapability } from "@hivegrid/db/pretenant-security.server";
|
||||
import type { Blacklist } from "@hivegrid/db/prisma-browser";
|
||||
import Constants from "~/application/Constants";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
@@ -30,34 +31,16 @@ export async function getBlacklist(
|
||||
}
|
||||
|
||||
export async function findInBlacklist(type: string, value: string): Promise<Blacklist | null> {
|
||||
return await db.blacklist.findFirst({
|
||||
where: {
|
||||
type,
|
||||
value,
|
||||
},
|
||||
});
|
||||
return await findBlacklistCapability(type, value);
|
||||
}
|
||||
|
||||
export async function addBlacklistAttempt(item: Blacklist) {
|
||||
blacklistLogger.info(
|
||||
{ type: item.type, value: item.value, registerAttempts: item.registerAttempts + 1 },
|
||||
`[BLACKLISTED ${item.type.toUpperCase()}]`
|
||||
);
|
||||
return await db.blacklist.updateMany({
|
||||
where: {
|
||||
type: item.type,
|
||||
value: item.value,
|
||||
},
|
||||
data: {
|
||||
registerAttempts: item.registerAttempts + 1,
|
||||
},
|
||||
});
|
||||
blacklistLogger.info({ type: item.type, value: item.value, registerAttempts: item.registerAttempts + 1 }, `[BLACKLISTED ${item.type.toUpperCase()}]`);
|
||||
return await recordBlacklistAttemptCapability(item);
|
||||
}
|
||||
|
||||
export async function addToBlacklist(data: { type: string; value: string }) {
|
||||
return await db.blacklist.create({
|
||||
data,
|
||||
});
|
||||
return await addBlacklistCapability(data);
|
||||
}
|
||||
|
||||
export async function deleteFromBlacklist(where: { type: string; value: string }) {
|
||||
|
||||
+30
-1
@@ -7,16 +7,19 @@ vi.mock("../db.server", () => {
|
||||
log: {
|
||||
groupBy: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { db } from "../db.server";
|
||||
import { getLastUserLogsByUserIds } from "./logs.db.server";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
import { createLogLogin, getLastUserLogsByUserIds } from "./logs.db.server";
|
||||
|
||||
const groupBy = db.log.groupBy as unknown as ReturnType<typeof vi.fn>;
|
||||
const findMany = db.log.findMany as unknown as ReturnType<typeof vi.fn>;
|
||||
const create = db.log.create as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
describe("getLastUserLogsByUserIds", () => {
|
||||
beforeEach(() => {
|
||||
@@ -55,6 +58,12 @@ describe("getLastUserLogsByUserIds", () => {
|
||||
where: { userId: { in: userIds } },
|
||||
_max: { createdAt: true },
|
||||
});
|
||||
expect(findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
OR: Object.entries(newest).map(([userId, createdAt]) => ({ userId, createdAt })),
|
||||
},
|
||||
select: { id: true, userId: true, action: true, createdAt: true },
|
||||
});
|
||||
expect(result.get("u1")).toMatchObject({ id: "log-u1", userId: "u1" });
|
||||
expect(result.get("u3")).toMatchObject({ id: "log-u3" });
|
||||
expect(result.size).toBe(3);
|
||||
@@ -70,3 +79,23 @@ describe("getLastUserLogsByUserIds", () => {
|
||||
expect(result.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("identity-owned authentication logs", () => {
|
||||
it("creates a pre-tenant login log inside the user's RLS context", async () => {
|
||||
create.mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1" });
|
||||
return {};
|
||||
});
|
||||
|
||||
await createLogLogin(new Request("https://app.example.test/login"), { id: "user_1" } as never);
|
||||
|
||||
expect(create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
userId: "user_1",
|
||||
url: "",
|
||||
action: "Login",
|
||||
details: "",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import { db } from "../db.server";
|
||||
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
||||
import { getUserInfo } from "../session.server";
|
||||
import { UserWithoutPassword } from "./users.db.server";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
export type LogWithDetails = Log & {
|
||||
user: UserWithoutPassword | null;
|
||||
@@ -13,6 +14,8 @@ export type LogWithDetails = Log & {
|
||||
tenant?: Tenant | null;
|
||||
};
|
||||
|
||||
export type AdminUserLastActivity = Pick<Log, "id" | "userId" | "action" | "createdAt">;
|
||||
|
||||
const include = {
|
||||
user: true,
|
||||
tenant: true,
|
||||
@@ -74,75 +77,87 @@ export async function getLogs(
|
||||
|
||||
export async function createLog(request: Request, tenantId: string | null, action: string, details: string) {
|
||||
const userInfo = await getUserInfo(request);
|
||||
await db.log.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
url: new URL(request.url).pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
});
|
||||
await withLogRlsContext(userInfo.userId, tenantId, () =>
|
||||
db.log.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
url: new URL(request.url).pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function createManualLog(userId: string, tenantId: string | null, pathname: string, action: string, details: string) {
|
||||
await db.log.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId,
|
||||
url: pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
});
|
||||
await withLogRlsContext(userId, tenantId, () =>
|
||||
db.log.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId,
|
||||
url: pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function createLogLogin(request: Request, user: UserWithoutPassword) {
|
||||
// eslint-disable-next-line no-console
|
||||
// console.log({ clientIpAddress: getClientIPAddress(request.headers) });
|
||||
|
||||
await db.log.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
url: "",
|
||||
action: DefaultLogActions.Login,
|
||||
details: "",
|
||||
},
|
||||
});
|
||||
await withLogRlsContext(user.id, null, () =>
|
||||
db.log.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
url: "",
|
||||
action: DefaultLogActions.Login,
|
||||
details: "",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function createLogLogout(request: Request, userId: string) {
|
||||
await db.log.create({
|
||||
data: {
|
||||
userId,
|
||||
url: "",
|
||||
action: DefaultLogActions.Logout,
|
||||
details: "",
|
||||
},
|
||||
});
|
||||
await withLogRlsContext(userId, null, () =>
|
||||
db.log.create({
|
||||
data: {
|
||||
userId,
|
||||
url: "",
|
||||
action: DefaultLogActions.Logout,
|
||||
details: "",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function createAdminLog(request: Request, action: string, details: string) {
|
||||
const userInfo = await getUserInfo(request);
|
||||
await db.log.create({
|
||||
data: {
|
||||
userId: userInfo.userId,
|
||||
url: new URL(request.url).pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
});
|
||||
await withLogRlsContext(userInfo.userId, null, () =>
|
||||
db.log.create({
|
||||
data: {
|
||||
userId: userInfo.userId,
|
||||
url: new URL(request.url).pathname,
|
||||
action,
|
||||
details,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getLastUserLog(userId: string): Promise<Log | null> {
|
||||
return await db.log.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
return await withLogRlsContext(userId, null, () =>
|
||||
db.log.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,7 +165,7 @@ export async function getLastUserLog(userId: string): Promise<Log | null> {
|
||||
* constant number of queries (1 groupBy + 1 findMany), avoiding the N+1
|
||||
* pattern of calling `getLastUserLog` per user.
|
||||
*/
|
||||
export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<string, Log>> {
|
||||
export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<string, AdminUserLastActivity>> {
|
||||
if (userIds.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
@@ -167,8 +182,9 @@ export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<s
|
||||
}
|
||||
const logs = await db.log.findMany({
|
||||
where: { OR: filters },
|
||||
select: { id: true, userId: true, action: true, createdAt: true },
|
||||
});
|
||||
const byUserId = new Map<string, Log>();
|
||||
const byUserId = new Map<string, AdminUserLastActivity>();
|
||||
for (const log of logs) {
|
||||
const existing = byUserId.get(log.userId ?? "");
|
||||
if (!log.userId) continue;
|
||||
@@ -178,3 +194,17 @@ export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<s
|
||||
}
|
||||
return byUserId;
|
||||
}
|
||||
|
||||
function withLogRlsContext<T>(userId: string | undefined, tenantId: string | null, operation: () => T): T {
|
||||
const current = getRlsExecutionContext();
|
||||
if (current?.userId || current?.tenantId) {
|
||||
return operation();
|
||||
}
|
||||
return runWithRlsContext(
|
||||
{
|
||||
...(userId ? { userId } : {}),
|
||||
...(tenantId ? { tenantId } : {}),
|
||||
},
|
||||
operation,
|
||||
);
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
// @vitest-environment node
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
|
||||
|
||||
const { clearCacheKey, getSharedStore, logError, logInfo, logWarn } = vi.hoisted(() => ({
|
||||
clearCacheKey: vi.fn(),
|
||||
getSharedStore: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logInfo: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/shared-store.server", () => ({ getSharedStore }));
|
||||
vi.mock("~/utils/cache.server", () => ({ clearCacheKey }));
|
||||
vi.mock("~/utils/logger.server", () => ({
|
||||
createScopedLogger: () => ({ error: logError, info: logInfo, warn: logWarn }),
|
||||
}));
|
||||
|
||||
import {
|
||||
__resetPermissionCacheForTests,
|
||||
cachePermissionNames,
|
||||
createPermissionCache,
|
||||
getCachedPermissionNames,
|
||||
getPermissionCache,
|
||||
invalidateUserPermissionCache,
|
||||
invalidateUserPermissionCacheScopes,
|
||||
subscribePermissionCache,
|
||||
} from "./permission-cache.server";
|
||||
|
||||
const disposers: Array<() => Promise<void>> = [];
|
||||
const originalCacheInvalidationEnabled = process.env.CACHE_INVALIDATION_ENABLED;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
__resetPermissionCacheForTests();
|
||||
delete process.env.CACHE_INVALIDATION_ENABLED;
|
||||
getSharedStore.mockReturnValue(createSharedStore({ namespace: "permission-singleton-test", adapter: new MemoryAdapter() }));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(disposers.splice(0).map((dispose) => dispose()));
|
||||
__resetPermissionCacheForTests();
|
||||
if (originalCacheInvalidationEnabled === undefined) delete process.env.CACHE_INVALIDATION_ENABLED;
|
||||
else process.env.CACHE_INVALIDATION_ENABLED = originalCacheInvalidationEnabled;
|
||||
});
|
||||
|
||||
describe("permission authorization cache", () => {
|
||||
it("revokes a cached grant on a second replica through shared-store pub/sub", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
const replicaA = createPermissionCache(createSharedStore({ namespace: "permission-replica-test", adapter }));
|
||||
const replicaB = createPermissionCache(createSharedStore({ namespace: "permission-replica-test", adapter }));
|
||||
disposers.push(await replicaA.subscribe(), await replicaB.subscribe());
|
||||
|
||||
const key = "user_1:tenant_1";
|
||||
await replicaA.set(key, ["settings.members.delete"]);
|
||||
expect(await replicaB.get(key)).toEqual(["settings.members.delete"]);
|
||||
expect(replicaB.l1.get(key)).toEqual(["settings.members.delete"]);
|
||||
|
||||
replicaA.deleteLocal(key);
|
||||
await replicaA.l2.invalidate(key);
|
||||
|
||||
expect(replicaB.l1.get(key)).toBeUndefined();
|
||||
expect(await replicaB.get(key)).toBeNull();
|
||||
});
|
||||
|
||||
it("memoizes the process cache and stores defensive permission snapshots", async () => {
|
||||
const first = getPermissionCache();
|
||||
expect(getPermissionCache()).toBe(first);
|
||||
expect(getSharedStore).toHaveBeenCalledTimes(1);
|
||||
|
||||
const names = ["settings.members.read"];
|
||||
await expect(cachePermissionNames("user_1", "tenant_1", names)).resolves.toBe(true);
|
||||
names.push("settings.members.delete");
|
||||
const cached = await getCachedPermissionNames("user_1", "tenant_1");
|
||||
expect(cached).toEqual(["settings.members.read"]);
|
||||
cached?.push("mutated.by.caller");
|
||||
await expect(getCachedPermissionNames("user_1", "tenant_1")).resolves.toEqual(["settings.members.read"]);
|
||||
await expect(getCachedPermissionNames("missing", null)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to the database when cache reads or writes fail", async () => {
|
||||
const cache = getPermissionCache();
|
||||
vi.spyOn(cache, "get").mockRejectedValueOnce(new TypeError("read unavailable")).mockRejectedValueOnce("unknown read failure");
|
||||
vi.spyOn(cache, "set").mockRejectedValueOnce(new RangeError("write unavailable")).mockRejectedValueOnce("unknown write failure");
|
||||
|
||||
await expect(getCachedPermissionNames("user_1", "tenant_1")).resolves.toBeNull();
|
||||
await expect(getCachedPermissionNames("user_1", null)).resolves.toBeNull();
|
||||
await expect(cachePermissionNames("user_1", "tenant_1", ["projects.read"])).resolves.toBe(false);
|
||||
await expect(cachePermissionNames("user_1", null, ["admin.read"])).resolves.toBe(false);
|
||||
expect(logWarn).toHaveBeenCalledTimes(4);
|
||||
expect(logWarn.mock.calls.map(([context]) => context)).toEqual([
|
||||
expect.objectContaining({ op: "permission-cache.read", err: { name: "TypeError" } }),
|
||||
expect.objectContaining({ op: "permission-cache.read", err: { name: "Error" } }),
|
||||
expect.objectContaining({ op: "permission-cache.write", err: { name: "RangeError" } }),
|
||||
expect.objectContaining({ op: "permission-cache.write", err: { name: "Error" } }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("invalidates one scope locally, in L2, and through the legacy cache", async () => {
|
||||
const cache = getPermissionCache();
|
||||
await cache.set("user_1:tenant_1", ["projects.read"]);
|
||||
const invalidate = vi.spyOn(cache.l2, "invalidate");
|
||||
|
||||
await invalidateUserPermissionCache("user_1", "tenant_1");
|
||||
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
expect(cache.l1.get("user_1:tenant_1")).toBeUndefined();
|
||||
expect(invalidate).toHaveBeenCalledWith("user_1:tenant_1");
|
||||
});
|
||||
|
||||
it("propagates single-scope invalidation failures", async () => {
|
||||
const cache = getPermissionCache();
|
||||
vi.spyOn(cache.l2, "invalidate").mockRejectedValueOnce(new TypeError("publish unavailable")).mockRejectedValueOnce("publish secret");
|
||||
|
||||
await expect(invalidateUserPermissionCache("user_1", null)).rejects.toThrow("publish unavailable");
|
||||
await expect(invalidateUserPermissionCache("user_1", null)).rejects.toBe("publish secret");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
expect(logError.mock.calls.map(([context]) => context)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ op: "permission-cache.invalidate", err: { name: "TypeError" } }),
|
||||
expect.objectContaining({ op: "permission-cache.invalidate", err: { name: "Error" } }),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it("deduplicates batch scopes, deletes L2 snapshots, and broadcasts one wildcard", async () => {
|
||||
const cache = getPermissionCache();
|
||||
await cache.set("user_1:tenant_1", ["projects.read"]);
|
||||
await cache.set("user_2:__admin__", ["admin.read"]);
|
||||
const remove = vi.spyOn(cache.l2, "delete");
|
||||
const invalidate = vi.spyOn(cache.l2, "invalidate");
|
||||
|
||||
await invalidateUserPermissionCacheScopes([
|
||||
{ userId: "user_1", tenantId: "tenant_1" },
|
||||
{ userId: "user_1", tenantId: "tenant_1" },
|
||||
{ userId: "user_2", tenantId: null },
|
||||
]);
|
||||
|
||||
expect(remove).toHaveBeenCalledTimes(2);
|
||||
expect(remove).toHaveBeenCalledWith("user_1:tenant_1");
|
||||
expect(remove).toHaveBeenCalledWith("user_2:__admin__");
|
||||
expect(invalidate).toHaveBeenCalledWith("*");
|
||||
expect(clearCacheKey.mock.calls).toEqual(expect.arrayContaining([["userRoles:user_1:tenant_1"], ["userRoles:user_2:null"]]));
|
||||
expect(cache.l1.get("user_1:tenant_1")).toBeUndefined();
|
||||
expect(cache.l1.get("user_2:__admin__")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("handles empty and single-scope batches without wildcard invalidation", async () => {
|
||||
const cache = getPermissionCache();
|
||||
const invalidate = vi.spyOn(cache.l2, "invalidate");
|
||||
|
||||
await invalidateUserPermissionCacheScopes([]);
|
||||
expect(invalidate).not.toHaveBeenCalled();
|
||||
await invalidateUserPermissionCacheScopes([{ userId: "user_1", tenantId: null }]);
|
||||
expect(invalidate).toHaveBeenCalledWith("user_1:__admin__");
|
||||
expect(invalidate).not.toHaveBeenCalledWith("*");
|
||||
});
|
||||
|
||||
it("propagates batch invalidation failures without hiding stale-peer risk", async () => {
|
||||
const cache = getPermissionCache();
|
||||
const remove = vi.spyOn(cache.l2, "delete").mockRejectedValueOnce("delete unavailable");
|
||||
const scopes = [
|
||||
{ userId: "user_1", tenantId: "tenant_1" },
|
||||
{ userId: "user_2", tenantId: "tenant_1" },
|
||||
];
|
||||
|
||||
await expect(invalidateUserPermissionCacheScopes(scopes)).rejects.toBe("delete unavailable");
|
||||
remove.mockRejectedValueOnce(new TypeError("delete failed"));
|
||||
await expect(invalidateUserPermissionCacheScopes(scopes)).rejects.toThrow("delete failed");
|
||||
expect(logError.mock.calls.map(([context]) => context)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ op: "permission-cache.invalidate-many", err: { name: "Error" } }),
|
||||
expect.objectContaining({ op: "permission-cache.invalidate-many", err: { name: "TypeError" } }),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it("reuses the singleton subscriber and honours explicit pubsub disable values", async () => {
|
||||
process.env.CACHE_INVALIDATION_ENABLED = "false";
|
||||
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-false", adapter: new MemoryAdapter() }));
|
||||
process.env.CACHE_INVALIDATION_ENABLED = "0";
|
||||
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-zero", adapter: new MemoryAdapter() }));
|
||||
process.env.CACHE_INVALIDATION_ENABLED = "TRUE";
|
||||
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-true", adapter: new MemoryAdapter() }));
|
||||
process.env.CACHE_INVALIDATION_ENABLED = "";
|
||||
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-default", adapter: new MemoryAdapter() }));
|
||||
|
||||
const cache = getPermissionCache();
|
||||
const subscribe = vi.spyOn(cache, "subscribe");
|
||||
const first = await subscribePermissionCache();
|
||||
disposers.push(first);
|
||||
await expect(subscribePermissionCache()).resolves.toBe(first);
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(logInfo).toHaveBeenCalledWith({ namespace: "user-permissions" }, "Permission cache subscriber started.");
|
||||
});
|
||||
});
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import { createTwoTierCache, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
|
||||
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const log = createScopedLogger("permission-cache");
|
||||
|
||||
// Pub/sub is the primary revocation path. The short TTL is the safety net for
|
||||
// a replica that was disconnected while an invalidation was published.
|
||||
const AUTHORIZATION_CACHE_TTL_SECONDS = 30;
|
||||
const ADMIN_SCOPE_KEY = "__admin__";
|
||||
|
||||
export type PermissionCache = TwoTierCache<string[]>;
|
||||
|
||||
let cacheSingleton: PermissionCache | null = null;
|
||||
let subscribeDisposer: (() => Promise<void>) | null = null;
|
||||
|
||||
function permissionCacheKey(userId: string, tenantId: string | null): string {
|
||||
return `${userId}:${tenantId ?? ADMIN_SCOPE_KEY}`;
|
||||
}
|
||||
|
||||
function legacyPermissionCacheKey(userId: string, tenantId: string | null): string {
|
||||
return `userRoles:${userId}:${tenantId}`;
|
||||
}
|
||||
|
||||
function pubsubEnabledFromEnv(): boolean {
|
||||
const raw = process.env.CACHE_INVALIDATION_ENABLED;
|
||||
if (raw === undefined || raw === null || raw === "") return true;
|
||||
return raw.toLowerCase() !== "false" && raw !== "0";
|
||||
}
|
||||
|
||||
export function createPermissionCache(store: SharedStore): PermissionCache {
|
||||
return createTwoTierCache<string[]>({
|
||||
store,
|
||||
namespace: "user-permissions",
|
||||
ttlSeconds: AUTHORIZATION_CACHE_TTL_SECONDS,
|
||||
pubsubEnabled: pubsubEnabledFromEnv(),
|
||||
logger: {
|
||||
warn: (obj, msg) => log.warn(obj, msg),
|
||||
info: (obj, msg) => log.info(obj, msg),
|
||||
error: (obj, msg) => log.error(obj, msg),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function getPermissionCache(): PermissionCache {
|
||||
if (!cacheSingleton) {
|
||||
cacheSingleton = createPermissionCache(getSharedStore());
|
||||
}
|
||||
return cacheSingleton;
|
||||
}
|
||||
|
||||
export async function getCachedPermissionNames(userId: string, tenantId: string | null): Promise<string[] | null> {
|
||||
try {
|
||||
const cached = await getPermissionCache().get(permissionCacheKey(userId, tenantId));
|
||||
return cached === null ? null : [...cached];
|
||||
} catch (error) {
|
||||
// Cache availability must not become an authorization availability
|
||||
// dependency. The caller falls back to the authoritative database.
|
||||
log.warn(
|
||||
{ op: "permission-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Permission cache read failed; falling back to the database."
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function cachePermissionNames(userId: string, tenantId: string | null, permissionNames: readonly string[]): Promise<boolean> {
|
||||
try {
|
||||
await getPermissionCache().set(permissionCacheKey(userId, tenantId), [...permissionNames]);
|
||||
return true;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "permission-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Permission cache write failed; continuing with the database result."
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidates one authorization scope locally, in shared L2, and on every
|
||||
* subscribed web replica. Publish errors propagate: callers changing roles
|
||||
* must not report success while peer replicas could still hold a stale grant.
|
||||
*/
|
||||
export async function invalidateUserPermissionCache(userId: string, tenantId: string | null): Promise<void> {
|
||||
const key = permissionCacheKey(userId, tenantId);
|
||||
clearCacheKey(legacyPermissionCacheKey(userId, tenantId));
|
||||
const cache = getPermissionCache();
|
||||
cache.deleteLocal(key);
|
||||
try {
|
||||
await cache.l2.invalidate(key);
|
||||
} catch (error) {
|
||||
log.error(
|
||||
{ op: "permission-cache.invalidate", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Permission cache invalidation could not be published."
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function invalidateUserPermissionCacheScopes(scopes: readonly { userId: string; tenantId: string | null }[]): Promise<void> {
|
||||
const unique = [...new Map(scopes.map((scope) => [permissionCacheKey(scope.userId, scope.tenantId), scope])).values()];
|
||||
if (unique.length === 0) return;
|
||||
if (unique.length === 1) {
|
||||
const scope = unique[0]!;
|
||||
await invalidateUserPermissionCache(scope.userId, scope.tenantId);
|
||||
return;
|
||||
}
|
||||
const cache = getPermissionCache();
|
||||
const keys = unique.map((scope) => permissionCacheKey(scope.userId, scope.tenantId));
|
||||
unique.forEach((scope) => {
|
||||
clearCacheKey(legacyPermissionCacheKey(scope.userId, scope.tenantId));
|
||||
cache.deleteLocal(permissionCacheKey(scope.userId, scope.tenantId));
|
||||
});
|
||||
try {
|
||||
// Delete every affected shared snapshot, then use one wildcard broadcast
|
||||
// to flush peer L1s. This avoids one PUBLISH per user on large roles.
|
||||
await Promise.all(keys.map((key) => cache.l2.delete(key)));
|
||||
await cache.l2.invalidate("*");
|
||||
} catch (error) {
|
||||
log.error(
|
||||
{ op: "permission-cache.invalidate-many", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Permission cache invalidation batch could not be published."
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function subscribePermissionCache(): Promise<() => Promise<void>> {
|
||||
if (subscribeDisposer) return subscribeDisposer;
|
||||
subscribeDisposer = await getPermissionCache().subscribe();
|
||||
log.info({ namespace: "user-permissions" }, "Permission cache subscriber started.");
|
||||
return subscribeDisposer;
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export function __resetPermissionCacheForTests(): void {
|
||||
cacheSingleton = null;
|
||||
subscribeDisposer = null;
|
||||
}
|
||||
+23
-19
@@ -12,17 +12,24 @@ vi.mock("../../db.server", () => ({
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
rolePermission: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("./roles.db.server", () => ({ getAllRolesNames: vi.fn(), getRoleByName: vi.fn() }));
|
||||
vi.mock("./rolePermissions.db.server", () => ({ createRolePermission: vi.fn(), getAllRolePermissions: vi.fn() }));
|
||||
vi.mock("./rolePermissions.db.server", () => ({
|
||||
createRolePermission: vi.fn(),
|
||||
getAllRolePermissions: vi.fn(),
|
||||
invalidateRoleAssignmentScopes: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: { getFiltersCondition: vi.fn() } }));
|
||||
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { db } from "../../db.server";
|
||||
import { createRolePermission, getAllRolePermissions } from "./rolePermissions.db.server";
|
||||
import { createRolePermission, getAllRolePermissions, invalidateRoleAssignmentScopes } from "./rolePermissions.db.server";
|
||||
import { getRoleByName } from "./roles.db.server";
|
||||
import {
|
||||
createPermissions,
|
||||
@@ -40,8 +47,9 @@ import {
|
||||
describe("permission persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) =>
|
||||
options.getFreshValue()) as never);
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
|
||||
vi.mocked(db.rolePermission.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(invalidateRoleAssignmentScopes).mockResolvedValue();
|
||||
});
|
||||
|
||||
it("lists permissions with filters, role filters, and type constraints", async () => {
|
||||
@@ -75,19 +83,10 @@ describe("permission persistence", () => {
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
expect(db.permission.findUnique).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ where: { id: "permission_1" } })
|
||||
);
|
||||
expect(db.permission.findUnique).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ where: { name: "admin.users.view" } })
|
||||
);
|
||||
expect(db.permission.findUnique).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { id: "permission_1" } }));
|
||||
expect(db.permission.findUnique).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { name: "admin.users.view" } }));
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "permission:admin.users.view" }));
|
||||
expect(db.permission.findMany).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ where: { name: { in: ["admin.users.view", "admin.users.edit"] } } })
|
||||
);
|
||||
expect(db.permission.findMany).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { name: { in: ["admin.users.view", "admin.users.edit"] } } }));
|
||||
});
|
||||
|
||||
it("calculates the next permission order with and without a type filter", async () => {
|
||||
@@ -158,12 +157,15 @@ describe("permission persistence", () => {
|
||||
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
|
||||
vi.mocked(getRoleByName).mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["Missing"] }])
|
||||
).rejects.toThrow("Role required: Missing");
|
||||
await expect(createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["Missing"] }])).rejects.toThrow(
|
||||
"Role required: Missing"
|
||||
);
|
||||
});
|
||||
|
||||
it("updates and deletes permissions while clearing the permission cache", async () => {
|
||||
vi.mocked(db.rolePermission.findMany)
|
||||
.mockResolvedValueOnce([{ roleId: "role_admin" }] as never)
|
||||
.mockResolvedValueOnce([{ roleId: "role_member" }] as never);
|
||||
vi.mocked(db.permission.update).mockResolvedValueOnce({ id: "permission_1", name: "admin.users.view" } as never);
|
||||
vi.mocked(db.permission.delete).mockResolvedValueOnce({ id: "permission_1", name: "admin.users.delete" } as never);
|
||||
|
||||
@@ -172,5 +174,7 @@ describe("permission persistence", () => {
|
||||
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.view");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.delete");
|
||||
expect(invalidateRoleAssignmentScopes).toHaveBeenNthCalledWith(1, ["role_admin"]);
|
||||
expect(invalidateRoleAssignmentScopes).toHaveBeenNthCalledWith(2, ["role_member"]);
|
||||
});
|
||||
});
|
||||
+12
-22
@@ -1,7 +1,7 @@
|
||||
import { db } from "../../db.server";
|
||||
import { Permission, Role, RolePermission } from "@hivegrid/db/prisma-browser";
|
||||
import { getRoleByName } from "./roles.db.server";
|
||||
import { createRolePermission, getAllRolePermissions } from "./rolePermissions.db.server";
|
||||
import { createRolePermission, getAllRolePermissions, invalidateRoleAssignmentScopes } from "./rolePermissions.db.server";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
@@ -131,10 +131,7 @@ export async function getNextPermissionsOrder(type?: string): Promise<number> {
|
||||
);
|
||||
}
|
||||
|
||||
export async function createPermissions(
|
||||
permissions: { inRoles: string[]; name: string; description: string; type: string }[],
|
||||
fromOrder: number = 0
|
||||
) {
|
||||
export async function createPermissions(permissions: { inRoles: string[]; name: string; description: string; type: string }[], fromOrder: number = 0) {
|
||||
const allRolePermissions = await getAllRolePermissions();
|
||||
const allPermissions = await getAllPermissions();
|
||||
const permissionByName = new Map<string, { id: string; name: string }>(allPermissions.map((permission) => [permission.name, permission]));
|
||||
@@ -196,24 +193,17 @@ export async function updatePermission(
|
||||
order?: number;
|
||||
}
|
||||
) {
|
||||
return await db.permission
|
||||
.update({
|
||||
where: { id },
|
||||
data,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`permission:${item.name}`);
|
||||
return item;
|
||||
});
|
||||
const links = await db.rolePermission.findMany({ where: { permissionId: id }, select: { roleId: true } });
|
||||
const item = await db.permission.update({ where: { id }, data });
|
||||
clearCacheKey(`permission:${item.name}`);
|
||||
await invalidateRoleAssignmentScopes(links.map((link) => link.roleId));
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function deletePermission(id: string) {
|
||||
return await db.permission
|
||||
.delete({
|
||||
where: { id },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`permission:${item.name}`);
|
||||
return item;
|
||||
});
|
||||
const links = await db.rolePermission.findMany({ where: { permissionId: id }, select: { roleId: true } });
|
||||
const item = await db.permission.delete({ where: { id } });
|
||||
clearCacheKey(`permission:${item.name}`);
|
||||
await invalidateRoleAssignmentScopes(links.map((link) => link.roleId));
|
||||
return item;
|
||||
}
|
||||
+29
-19
@@ -16,18 +16,20 @@ vi.mock("../../db.server", () => ({
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
userRole: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/cache.server", () => ({ clearCacheKey: vi.fn() }));
|
||||
vi.mock("../tenants.db.server", () => ({ adminGetAllTenants: vi.fn() }));
|
||||
vi.mock("../users.db.server", () => ({ adminGetAllUsersNames: vi.fn() }));
|
||||
vi.mock("./permission-cache.server", () => ({ invalidateUserPermissionCacheScopes: vi.fn() }));
|
||||
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { adminGetAllTenants } from "../tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "../users.db.server";
|
||||
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
|
||||
import { db } from "../../db.server";
|
||||
import {
|
||||
createRolePermission,
|
||||
@@ -47,8 +49,9 @@ describe("role permission persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.$transaction.mockImplementation(async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock));
|
||||
vi.mocked(adminGetAllTenants).mockResolvedValue([]);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([]);
|
||||
dbMock.userRole.findMany.mockResolvedValue([] as never);
|
||||
dbMock.rolePermission.findMany.mockResolvedValue([] as never);
|
||||
vi.mocked(invalidateUserPermissionCacheScopes).mockResolvedValue();
|
||||
});
|
||||
|
||||
it("sets role permissions inside one awaited transaction before clearing caches", async () => {
|
||||
@@ -74,9 +77,7 @@ describe("role permission persistence", () => {
|
||||
|
||||
it("reads and creates role-permission links without duplicating existing links", async () => {
|
||||
dbMock.rolePermission.findMany.mockResolvedValueOnce([{ id: "rp_1" }] as never);
|
||||
dbMock.rolePermission.findFirst
|
||||
.mockResolvedValueOnce({ id: "rp_existing" } as never)
|
||||
.mockResolvedValueOnce(null);
|
||||
dbMock.rolePermission.findFirst.mockResolvedValueOnce({ id: "rp_existing" } as never).mockResolvedValueOnce(null);
|
||||
dbMock.rolePermission.create.mockResolvedValueOnce({ id: "rp_created" } as never);
|
||||
|
||||
await expect(getAllRolePermissions()).resolves.toEqual([{ id: "rp_1" }]);
|
||||
@@ -96,24 +97,24 @@ describe("role permission persistence", () => {
|
||||
expect(dbMock.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears app role user caches across tenants and user-role lookup caches", async () => {
|
||||
it("invalidates exactly the assigned users across replicas after an app-role permission change", async () => {
|
||||
findRoleByIdMock.mockResolvedValue({ id: "role_1", name: "Member", type: "app" } as never);
|
||||
findPermissionsMock.mockResolvedValue([]);
|
||||
vi.mocked(adminGetAllTenants).mockResolvedValue([
|
||||
{ id: "tenant_1", users: [{ userId: "user_1" }, { userId: "user_2" }] },
|
||||
{ id: "tenant_2", users: [{ userId: "user_3" }] },
|
||||
dbMock.userRole.findMany.mockResolvedValue([
|
||||
{ userId: "user_1", tenantId: "tenant_1" },
|
||||
{ userId: "user_2", tenantId: "tenant_1" },
|
||||
{ userId: "user_3", tenantId: "tenant_2" },
|
||||
] as never);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([{ id: "user_1" }, { id: "user_4" }] as never);
|
||||
|
||||
await setRolePermissions("role_1", []);
|
||||
|
||||
expect(dbMock.rolePermission.createMany).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("roles:app");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_2:tenant_1");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_3:tenant_2");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRole:user_1:Member");
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRole:user_4:Member");
|
||||
expect(invalidateUserPermissionCacheScopes).toHaveBeenCalledWith([
|
||||
{ userId: "user_1", tenantId: "tenant_1" },
|
||||
{ userId: "user_2", tenantId: "tenant_1" },
|
||||
{ userId: "user_3", tenantId: "tenant_2" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("sets permission roles inside one awaited transaction", async () => {
|
||||
@@ -146,6 +147,7 @@ describe("role permission persistence", () => {
|
||||
|
||||
it("deletes role-permission links by composite keys or id", async () => {
|
||||
dbMock.rolePermission.deleteMany.mockResolvedValueOnce({ count: 1 } as never);
|
||||
dbMock.rolePermission.findUnique.mockResolvedValueOnce({ roleId: "role_2" } as never);
|
||||
dbMock.rolePermission.delete.mockResolvedValueOnce({ id: "rp_1" } as never);
|
||||
|
||||
await expect(deleteRolePermission("role_1", "permission_1")).resolves.toEqual({ count: 1 });
|
||||
@@ -153,5 +155,13 @@ describe("role permission persistence", () => {
|
||||
|
||||
expect(dbMock.rolePermission.deleteMany).toHaveBeenCalledWith({ where: { roleId: "role_1", permissionId: "permission_1" } });
|
||||
expect(dbMock.rolePermission.delete).toHaveBeenCalledWith({ where: { id: "rp_1" } });
|
||||
expect(dbMock.userRole.findMany).toHaveBeenCalledWith({
|
||||
where: { roleId: { in: ["role_1"] } },
|
||||
select: { userId: true, tenantId: true },
|
||||
});
|
||||
expect(dbMock.userRole.findMany).toHaveBeenCalledWith({
|
||||
where: { roleId: { in: ["role_2"] } },
|
||||
select: { userId: true, tenantId: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
+27
-21
@@ -1,10 +1,15 @@
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { db } from "../../db.server";
|
||||
import { adminGetAllTenants } from "../tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "../users.db.server";
|
||||
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
|
||||
|
||||
const rolePermissionsLogger = createScopedLogger("db.rolePermissions");
|
||||
export async function invalidateRoleAssignmentScopes(roleIds: readonly string[]): Promise<void> {
|
||||
if (roleIds.length === 0) return;
|
||||
const assignments = await db.userRole.findMany({
|
||||
where: { roleId: { in: [...new Set(roleIds)] } },
|
||||
select: { userId: true, tenantId: true },
|
||||
});
|
||||
await invalidateUserPermissionCacheScopes(assignments);
|
||||
}
|
||||
|
||||
export async function getAllRolePermissions() {
|
||||
return await db.rolePermission.findMany({
|
||||
@@ -24,9 +29,11 @@ export async function createRolePermission(data: { roleId: string; permissionId:
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return await db.rolePermission.create({
|
||||
const created = await db.rolePermission.create({
|
||||
data,
|
||||
});
|
||||
await invalidateRoleAssignmentScopes([data.roleId]);
|
||||
return created;
|
||||
}
|
||||
|
||||
export async function setRolePermissions(roleId: string, permissionNames: string[]) {
|
||||
@@ -59,20 +66,7 @@ export async function setRolePermissions(roleId: string, permissionNames: string
|
||||
});
|
||||
|
||||
clearCacheKey(`roles:${role.type}`);
|
||||
if (role.type === "app") {
|
||||
const allTenants = await adminGetAllTenants();
|
||||
rolePermissionsLogger.info({ tenantCount: allTenants.length }, "Clearing user roles cache");
|
||||
for (const tenant of allTenants) {
|
||||
for (const user of tenant.users) {
|
||||
clearCacheKey(`userRoles:${user.userId}:${tenant.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allUsers = await adminGetAllUsersNames();
|
||||
for (const user of allUsers) {
|
||||
clearCacheKey(`userRole:${user.id}:${role.name}`);
|
||||
}
|
||||
await invalidateRoleAssignmentScopes([roleId]);
|
||||
}
|
||||
|
||||
export async function setPermissionRoles(permissionId: string, roleNames: string[]) {
|
||||
@@ -83,6 +77,10 @@ export async function setPermissionRoles(permissionId: string, roleNames: string
|
||||
select: { id: true },
|
||||
})
|
||||
: [];
|
||||
const previousLinks = await db.rolePermission.findMany({
|
||||
where: { permissionId },
|
||||
select: { roleId: true },
|
||||
});
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.rolePermission.deleteMany({
|
||||
@@ -98,16 +96,24 @@ export async function setPermissionRoles(permissionId: string, roleNames: string
|
||||
});
|
||||
}
|
||||
});
|
||||
await invalidateRoleAssignmentScopes([...previousLinks.map((link) => link.roleId), ...roles.map((role) => role.id)]);
|
||||
}
|
||||
|
||||
export async function deleteRolePermission(roleId: string, permissionId: string) {
|
||||
return await db.rolePermission.deleteMany({
|
||||
const result = await db.rolePermission.deleteMany({
|
||||
where: { roleId, permissionId },
|
||||
});
|
||||
await invalidateRoleAssignmentScopes([roleId]);
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteRolePermissionById(id: string) {
|
||||
return await db.rolePermission.delete({
|
||||
const existing = await db.rolePermission.findUnique({ where: { id }, select: { roleId: true } });
|
||||
const result = await db.rolePermission.delete({
|
||||
where: { id },
|
||||
});
|
||||
if (existing) {
|
||||
await invalidateRoleAssignmentScopes([existing.roleId]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
+26
-7
@@ -12,14 +12,19 @@ vi.mock("../../db.server", () => ({
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
userRole: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
|
||||
vi.mock("./permission-cache.server", () => ({ invalidateUserPermissionCacheScopes: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: { getFiltersCondition: vi.fn() } }));
|
||||
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { db } from "../../db.server";
|
||||
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
|
||||
import {
|
||||
createRole,
|
||||
deleteRole,
|
||||
@@ -34,6 +39,7 @@ import {
|
||||
getRolesByName,
|
||||
getTenantAppRoleByName,
|
||||
getTenantAssignableAppRole,
|
||||
getTenantAssignableAppRoles,
|
||||
getTenantMutableAppRole,
|
||||
updateRole,
|
||||
} from "./roles.db.server";
|
||||
@@ -43,8 +49,9 @@ const dbMock = vi.mocked(db);
|
||||
describe("role persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) =>
|
||||
options.getFreshValue()) as never);
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(invalidateUserPermissionCacheScopes).mockResolvedValue();
|
||||
});
|
||||
|
||||
it("lists global roles with permissions and supports type filtering", async () => {
|
||||
@@ -94,11 +101,7 @@ describe("role persistence", () => {
|
||||
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue({ name: { contains: "editor" } } as never);
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
await getAllRolesWithUsers(
|
||||
"app",
|
||||
{ properties: [{ name: "permissionId", value: "permission_1" }] } as never,
|
||||
"tenant_1"
|
||||
);
|
||||
await getAllRolesWithUsers("app", { properties: [{ name: "permissionId", value: "permission_1" }] } as never, "tenant_1");
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -178,6 +181,20 @@ describe("role persistence", () => {
|
||||
expect(dbMock.role.findFirst).toHaveBeenNthCalledWith(4, expect.objectContaining({ where: { name: "Support", tenantId: "tenant_1", type: "app" } }));
|
||||
});
|
||||
|
||||
it("lists shared defaults and tenant-owned roles that the tenant may assign", async () => {
|
||||
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([{ id: "role_1" }] as never);
|
||||
|
||||
await expect(getTenantAssignableAppRoles("tenant_1")).resolves.toEqual([{ id: "role_1" }]);
|
||||
|
||||
expect(dbMock.role.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
type: "app",
|
||||
OR: [{ isDefault: true, tenantId: null }, { tenantId: "tenant_1" }],
|
||||
},
|
||||
orderBy: [{ type: "asc" }, { order: "asc" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("calculates next role order for global and tenant-scoped roles", async () => {
|
||||
vi.mocked(dbMock.role.aggregate)
|
||||
.mockResolvedValueOnce({ _max: { order: 4 } } as never)
|
||||
@@ -202,6 +219,7 @@ describe("role persistence", () => {
|
||||
vi.mocked(dbMock.role.create).mockResolvedValueOnce({ id: "role_1", type: "app" } as never);
|
||||
vi.mocked(dbMock.role.update).mockResolvedValueOnce({ id: "role_1", type: "admin" } as never);
|
||||
vi.mocked(dbMock.role.delete).mockResolvedValueOnce({ id: "role_1", type: "app" } as never);
|
||||
vi.mocked(dbMock.userRole.findMany).mockResolvedValueOnce([{ userId: "user_1", tenantId: "tenant_1" }] as never);
|
||||
|
||||
await createRole({
|
||||
order: 1,
|
||||
@@ -234,5 +252,6 @@ describe("role persistence", () => {
|
||||
expect(clearCacheKey).toHaveBeenNthCalledWith(1, "roles:app");
|
||||
expect(clearCacheKey).toHaveBeenNthCalledWith(2, "roles:admin");
|
||||
expect(clearCacheKey).toHaveBeenNthCalledWith(3, "roles:app");
|
||||
expect(invalidateUserPermissionCacheScopes).toHaveBeenCalledWith([{ userId: "user_1", tenantId: "tenant_1" }]);
|
||||
});
|
||||
});
|
||||
+9
-8
@@ -5,6 +5,7 @@ import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { UserSimple } from "../users.db.server";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
|
||||
|
||||
export type RoleWithPermissions = Role & {
|
||||
permissions: (RolePermission & { permission: Permission })[];
|
||||
@@ -318,12 +319,12 @@ export async function updateRole(id: string, data: { name: string; description:
|
||||
}
|
||||
|
||||
export async function deleteRole(id: string) {
|
||||
return await db.role
|
||||
.delete({
|
||||
where: { id },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`roles:${item.type}`);
|
||||
return item;
|
||||
});
|
||||
const assignments = await db.userRole.findMany({
|
||||
where: { roleId: id },
|
||||
select: { userId: true, tenantId: true },
|
||||
});
|
||||
const item = await db.role.delete({ where: { id } });
|
||||
clearCacheKey(`roles:${item.type}`);
|
||||
await invalidateUserPermissionCacheScopes(assignments);
|
||||
return item;
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
userRole: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
tenantUser: {
|
||||
findUnique: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { db } from "../../db.server";
|
||||
import { getTenantSeatCounts, getUserEffectiveSeatType } from "./seatType.db.server";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
const dbMock = vi.mocked(db, true);
|
||||
|
||||
describe("getUserEffectiveSeatType", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.tenantUser.findUnique.mockResolvedValue(null as never);
|
||||
});
|
||||
|
||||
it("derives office when the user holds at least one office role", async () => {
|
||||
dbMock.userRole.findMany.mockResolvedValue([{ role: { seatCategory: "field" } }, { role: { seatCategory: "office" } }] as never);
|
||||
|
||||
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("office");
|
||||
expect(dbMock.userRole.findMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user-1", tenantId: "tenant-1" },
|
||||
select: { role: { select: { seatCategory: true } } },
|
||||
});
|
||||
});
|
||||
|
||||
it("derives field when every role is a field role", async () => {
|
||||
dbMock.userRole.findMany.mockResolvedValue([{ role: { seatCategory: "field" } }] as never);
|
||||
|
||||
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("field");
|
||||
});
|
||||
|
||||
it("derives field when the user holds no roles in the tenant", async () => {
|
||||
dbMock.userRole.findMany.mockResolvedValue([] as never);
|
||||
|
||||
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("field");
|
||||
});
|
||||
|
||||
it("prefers the TenantUser.seatType admin override over the role-derived seat", async () => {
|
||||
dbMock.userRole.findMany.mockResolvedValue([{ role: { seatCategory: "office" } }] as never);
|
||||
dbMock.tenantUser.findUnique.mockResolvedValue({ seatType: "field" } as never);
|
||||
|
||||
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("field");
|
||||
expect(dbMock.tenantUser.findUnique).toHaveBeenCalledWith({
|
||||
where: { tenantId_userId: { tenantId: "tenant-1", userId: "user-1" } },
|
||||
select: { seatType: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTenantSeatCounts", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("queries only ACTIVE members with their tenant roles (no N+1)", async () => {
|
||||
dbMock.tenantUser.findMany.mockResolvedValue([] as never);
|
||||
|
||||
await getTenantSeatCounts("tenant-1");
|
||||
|
||||
expect(dbMock.tenantUser.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(dbMock.tenantUser.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant-1", status: TenantUserStatus.ACTIVE },
|
||||
select: {
|
||||
seatType: true,
|
||||
user: { select: { roles: { where: { tenantId: "tenant-1" }, select: { role: { select: { seatCategory: true } } } } } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("buckets members by effective seat type: any office role => office, else field", async () => {
|
||||
dbMock.tenantUser.findMany.mockResolvedValue([
|
||||
// office (has an office role)
|
||||
{ seatType: null, user: { roles: [{ role: { seatCategory: "office" } }, { role: { seatCategory: "field" } }] } },
|
||||
// field (only field roles)
|
||||
{ seatType: null, user: { roles: [{ role: { seatCategory: "field" } }] } },
|
||||
// field (no roles at all)
|
||||
{ seatType: null, user: { roles: [] } },
|
||||
] as never);
|
||||
|
||||
await expect(getTenantSeatCounts("tenant-1")).resolves.toEqual({ office: 1, field: 2 });
|
||||
});
|
||||
|
||||
it("honours the TenantUser.seatType admin override over the role-derived seat", async () => {
|
||||
dbMock.tenantUser.findMany.mockResolvedValue([
|
||||
// office role but overridden to field
|
||||
{ seatType: "field", user: { roles: [{ role: { seatCategory: "office" } }] } },
|
||||
// field role but overridden to office
|
||||
{ seatType: "office", user: { roles: [{ role: { seatCategory: "field" } }] } },
|
||||
] as never);
|
||||
|
||||
await expect(getTenantSeatCounts("tenant-1")).resolves.toEqual({ office: 1, field: 1 });
|
||||
});
|
||||
|
||||
it("returns zero counts when the tenant has no active members", async () => {
|
||||
dbMock.tenantUser.findMany.mockResolvedValue([] as never);
|
||||
await expect(getTenantSeatCounts("tenant-1")).resolves.toEqual({ office: 0, field: 0 });
|
||||
});
|
||||
});
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import type { SeatType } from "@hivegrid/db/prisma-browser";
|
||||
import { deriveSeatType } from "@hivegrid/entitlements";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { db } from "../../db.server";
|
||||
|
||||
/**
|
||||
* Effective seat type of a single member in a tenant (Fundament C).
|
||||
*
|
||||
* Loads the tenant roles the user holds via the UserRole -> Role path (reading
|
||||
* `Role.seatCategory`) plus the `TenantUser.seatType` admin override, then applies
|
||||
* the shared `deriveSeatType` rule. Two batched queries, run in parallel — no N+1.
|
||||
*/
|
||||
export async function getUserEffectiveSeatType(userId: string, tenantId: string): Promise<SeatType> {
|
||||
const [userRoles, tenantUser] = await Promise.all([
|
||||
db.userRole.findMany({
|
||||
where: { userId, tenantId },
|
||||
select: { role: { select: { seatCategory: true } } },
|
||||
}),
|
||||
db.tenantUser.findUnique({
|
||||
where: { tenantId_userId: { tenantId, userId } },
|
||||
select: { seatType: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return deriveSeatType({
|
||||
roleSeatCategories: userRoles.map((userRole) => userRole.role.seatCategory),
|
||||
override: tenantUser?.seatType ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
/** Count of the tenant's active seats per effective seat category (Fundament E). */
|
||||
export interface TenantSeatCounts {
|
||||
readonly office: number;
|
||||
readonly field: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the ACTIVE members of a tenant by their effective seat type (Fundament E).
|
||||
*
|
||||
* One batched `findMany` loads every active member together with the roles they
|
||||
* hold in the tenant (for `Role.seatCategory`) plus the `TenantUser.seatType`
|
||||
* admin override, then the shared `deriveSeatType` rule buckets each member —
|
||||
* no N+1. Only `TenantUserStatus.ACTIVE` members count toward billed seats.
|
||||
*/
|
||||
export async function getTenantSeatCounts(tenantId: string): Promise<TenantSeatCounts> {
|
||||
const members = await db.tenantUser.findMany({
|
||||
where: { tenantId, status: TenantUserStatus.ACTIVE },
|
||||
select: {
|
||||
seatType: true,
|
||||
user: {
|
||||
select: {
|
||||
roles: {
|
||||
where: { tenantId },
|
||||
select: { role: { select: { seatCategory: true } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const counts = { office: 0, field: 0 };
|
||||
for (const member of members) {
|
||||
const seat = deriveSeatType({
|
||||
roleSeatCategories: member.user.roles.map((userRole) => userRole.role.seatCategory),
|
||||
override: member.seatType,
|
||||
});
|
||||
counts[seat] += 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
+185
-23
@@ -1,47 +1,98 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
syncGroupChats: vi.fn(),
|
||||
syncProjectChats: vi.fn(),
|
||||
lockGroups: vi.fn(),
|
||||
logActivity: vi.fn(),
|
||||
publishAudit: vi.fn(),
|
||||
withTenantRLS: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
group: { findFirst: vi.fn(), create: vi.fn(), deleteMany: vi.fn() },
|
||||
tenantUser: { findMany: vi.fn() },
|
||||
groupUser: {
|
||||
create: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
teamChatGroupSource: { deleteMany: vi.fn() },
|
||||
projektMitglied: { findMany: vi.fn(), updateMany: vi.fn() },
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/chat/group-sync.server", () => ({
|
||||
syncPermissionGroupChatsIfEnabledWithTx: (...args: unknown[]) => mocks.syncGroupChats(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/chat/project-sync.server", () => ({
|
||||
syncProjectChannelsForPermissionGroupWithTx: (...args: unknown[]) => mocks.syncProjectChats(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/chat/sync-locks.server", () => ({
|
||||
lockPermissionGroupsWithTx: (...args: unknown[]) => mocks.lockGroups(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/activity", () => ({
|
||||
logActivity: (...args: unknown[]) => mocks.logActivity(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAudit(...args),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (...args: unknown[]) => mocks.withTenantRLS(...args),
|
||||
}));
|
||||
|
||||
import { db } from "../../db.server";
|
||||
import { createUserGroup, createUserGroups, deleteGroupUsers, deleteUserGroup, replaceGroupUsers } from "./userGroups.db.server";
|
||||
import {
|
||||
addGroupUsersAndSync,
|
||||
createPermissionGroupWithUsers,
|
||||
deletePermissionGroupAndSync,
|
||||
removeGroupUsersAndSync,
|
||||
replaceGroupUsers,
|
||||
} from "./userGroups.db.server";
|
||||
|
||||
const dbMock = vi.mocked(db);
|
||||
const syncContext = { actorUserId: "user_actor", requestId: "request_group_change" } as const;
|
||||
|
||||
describe("user group persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(dbMock.$transaction).mockImplementation((async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock)) as never);
|
||||
vi.mocked(dbMock.group.findFirst).mockResolvedValue({ id: "group_1", name: "Dispatch" } as never);
|
||||
vi.mocked(dbMock.tenantUser.findMany).mockImplementation(
|
||||
(async (args: { where: { userId: { in: string[] } } }) => args.where.userId.in.map((userId) => ({ userId }))) as never
|
||||
);
|
||||
mocks.withTenantRLS.mockImplementation((_tenantId: string, callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock));
|
||||
mocks.syncGroupChats.mockResolvedValue({ changedChatIds: [], addedUserIds: [], removedUserIds: [] });
|
||||
mocks.syncProjectChats.mockResolvedValue([]);
|
||||
mocks.lockGroups.mockResolvedValue(["group_1"]);
|
||||
mocks.logActivity.mockResolvedValue(undefined);
|
||||
mocks.publishAudit.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("creates and deletes single group memberships", async () => {
|
||||
vi.mocked(dbMock.groupUser.create).mockResolvedValueOnce({ id: "group_user_1" } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
|
||||
await expect(createUserGroup("user_1", "group_1")).resolves.toEqual({ id: "group_user_1" });
|
||||
await expect(deleteUserGroup("user_1", "group_1")).resolves.toEqual({ count: 1 });
|
||||
await expect(deleteGroupUsers("group_1", "tenant_1")).resolves.toEqual({ count: 2 });
|
||||
|
||||
expect(dbMock.groupUser.create).toHaveBeenCalledWith({ data: { userId: "user_1", groupId: "group_1" } });
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenNthCalledWith(1, { where: { userId: "user_1", groupId: "group_1" } });
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenNthCalledWith(2, { where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
|
||||
});
|
||||
|
||||
it("bulk-creates deduplicated group memberships with database duplicate protection", async () => {
|
||||
it("creates a permission group and deduplicated memberships inside tenant RLS", async () => {
|
||||
vi.mocked(dbMock.group.create).mockResolvedValueOnce({ id: "group_1" } as never);
|
||||
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
|
||||
await expect(createUserGroups("group_1", ["user_1", "user_2", "user_1"])).resolves.toEqual({ count: 2 });
|
||||
await expect(
|
||||
createPermissionGroupWithUsers(
|
||||
"tenant_1",
|
||||
{ createdByUserId: "user_actor", name: "Dispatch", description: "Dispatch team", color: 2 },
|
||||
["user_1", "user_2", "user_1"]
|
||||
)
|
||||
).resolves.toEqual({ id: "group_1" });
|
||||
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
|
||||
expect(dbMock.group.create).toHaveBeenCalledWith({
|
||||
data: { tenantId: "tenant_1", createdByUserId: "user_actor", name: "Dispatch", description: "Dispatch team", color: 2 },
|
||||
});
|
||||
expect(dbMock.groupUser.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ userId: "user_1", groupId: "group_1" },
|
||||
@@ -51,19 +102,75 @@ describe("user group persistence", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("skips bulk membership writes when no users are selected", async () => {
|
||||
await expect(createUserGroups("group_1", [])).resolves.toEqual({ count: 0 });
|
||||
it("creates a permission group without a membership write when no users are selected", async () => {
|
||||
vi.mocked(dbMock.group.create).mockResolvedValueOnce({ id: "group_1" } as never);
|
||||
await expect(
|
||||
createPermissionGroupWithUsers(
|
||||
"tenant_1",
|
||||
{ createdByUserId: "user_actor", name: "Empty", description: "", color: 0 },
|
||||
[]
|
||||
)
|
||||
).resolves.toEqual({ id: "group_1" });
|
||||
|
||||
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("revokes group-derived chat access and archives project history before deleting the group", async () => {
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
vi.mocked(dbMock.teamChatGroupSource.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
vi.mocked(dbMock.projektMitglied.findMany).mockResolvedValueOnce([
|
||||
{ id: "membership_1", projektId: "project_1", rolle: "monteur" },
|
||||
{ id: "membership_2", projektId: "project_1", rolle: "beobachter" },
|
||||
] as never);
|
||||
vi.mocked(dbMock.projektMitglied.updateMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
vi.mocked(dbMock.group.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
|
||||
await expect(deletePermissionGroupAndSync("group_1", "tenant_1", syncContext)).resolves.toEqual({ count: 1 });
|
||||
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
|
||||
expect(mocks.syncGroupChats).toHaveBeenCalledWith(
|
||||
dbMock,
|
||||
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
|
||||
);
|
||||
expect(mocks.syncProjectChats).toHaveBeenCalledWith(
|
||||
dbMock,
|
||||
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
|
||||
);
|
||||
expect(dbMock.teamChatGroupSource.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", groupId: "group_1" } });
|
||||
expect(dbMock.projektMitglied.updateMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", groupId: "group_1", archivedAt: null },
|
||||
data: { archivedAt: expect.any(Date) },
|
||||
});
|
||||
expect(mocks.logActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_actor",
|
||||
activityType: "project_member_removed",
|
||||
subjectId: "project_1",
|
||||
summaryText: "activity.runtime.permissions.groupProjectMembershipArchived",
|
||||
metadata: expect.objectContaining({ groupId: "group_1", membershipIds: ["membership_1", "membership_2"] }),
|
||||
}),
|
||||
{ client: dbMock }
|
||||
);
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
dbMock,
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
actorId: "user_actor",
|
||||
action: "permissions.group.deleted",
|
||||
targetId: "group_1",
|
||||
})
|
||||
);
|
||||
expect(dbMock.group.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", id: "group_1" } });
|
||||
});
|
||||
|
||||
it("replaces group memberships inside one transaction", async () => {
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
|
||||
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
|
||||
await expect(replaceGroupUsers("group_1", "tenant_1", ["user_1", "user_2", "user_1"])).resolves.toEqual({ count: 2 });
|
||||
await expect(replaceGroupUsers("group_1", "tenant_1", ["user_1", "user_2", "user_1"], syncContext)).resolves.toEqual({ count: 2 });
|
||||
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
|
||||
expect(dbMock.groupUser.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
@@ -72,15 +179,70 @@ describe("user group persistence", () => {
|
||||
],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
expect(mocks.syncGroupChats).toHaveBeenCalledWith(
|
||||
dbMock,
|
||||
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
|
||||
);
|
||||
expect(mocks.syncProjectChats).toHaveBeenCalledWith(
|
||||
dbMock,
|
||||
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed before replacing a group with a user outside the active tenant membership", async () => {
|
||||
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValueOnce([{ userId: "user_1" }] as never);
|
||||
|
||||
await expect(replaceGroupUsers("group_1", "tenant_1", ["user_1", "foreign_user"], syncContext)).rejects.toThrow(
|
||||
"outside the active tenant membership"
|
||||
);
|
||||
|
||||
expect(dbMock.groupUser.deleteMany).not.toHaveBeenCalled();
|
||||
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
|
||||
expect(mocks.syncGroupChats).not.toHaveBeenCalled();
|
||||
expect(mocks.syncProjectChats).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("replaces group memberships with an empty set without bulk insert", async () => {
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
|
||||
|
||||
await expect(replaceGroupUsers("group_1", "tenant_1", [])).resolves.toEqual({ count: 0 });
|
||||
await expect(replaceGroupUsers("group_1", "tenant_1", [], syncContext)).resolves.toEqual({ count: 0 });
|
||||
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
|
||||
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
|
||||
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
|
||||
expect(mocks.syncGroupChats).toHaveBeenCalledOnce();
|
||||
expect(mocks.syncProjectChats).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("syncs dependent group and project chats after additive and subtractive membership changes", async () => {
|
||||
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
|
||||
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
|
||||
await expect(addGroupUsersAndSync("group_1", "tenant_1", ["user_1", "user_2"], syncContext)).resolves.toEqual({ count: 2 });
|
||||
await expect(removeGroupUsersAndSync("group_1", "tenant_1", ["user_2"], syncContext)).resolves.toEqual({ count: 1 });
|
||||
|
||||
expect(mocks.syncGroupChats).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.syncProjectChats).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.lockGroups).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("returns without opening an RLS transaction when additive or subtractive inputs are empty", async () => {
|
||||
await expect(addGroupUsersAndSync("group_1", "tenant_1", [], syncContext)).resolves.toEqual({ count: 0 });
|
||||
await expect(removeGroupUsersAndSync("group_1", "tenant_1", [], syncContext)).resolves.toEqual({ count: 0 });
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
expect(mocks.lockGroups).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the permission group does not belong to the tenant", async () => {
|
||||
vi.mocked(dbMock.group.findFirst).mockResolvedValueOnce(null);
|
||||
|
||||
await expect(addGroupUsersAndSync("foreign_group", "tenant_1", ["user_1"], syncContext)).rejects.toThrow(
|
||||
"Permission group is not available in the tenant"
|
||||
);
|
||||
|
||||
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
|
||||
expect(mocks.syncGroupChats).not.toHaveBeenCalled();
|
||||
expect(mocks.syncProjectChats).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+226
-45
@@ -1,64 +1,245 @@
|
||||
import { db } from "~/utils/db.server";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { syncPermissionGroupChatsIfEnabledWithTx } from "@hivegrid/chat/group-sync.server";
|
||||
import { syncProjectChannelsForPermissionGroupWithTx } from "@hivegrid/chat/project-sync.server";
|
||||
import { lockPermissionGroupsWithTx } from "@hivegrid/chat/sync-locks.server";
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
|
||||
import { withTenantScope } from "@hivegrid/foundation";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
export async function createUserGroup(userId: string, groupId: string) {
|
||||
return await db.groupUser.create({
|
||||
data: {
|
||||
userId,
|
||||
groupId,
|
||||
},
|
||||
export type GroupMembershipSyncContext = Readonly<{
|
||||
actorUserId: string;
|
||||
requestId: string;
|
||||
}>;
|
||||
|
||||
export type PermissionGroupCreateInput = Readonly<{
|
||||
createdByUserId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
color: number;
|
||||
}>;
|
||||
|
||||
async function syncGroupMembershipDependents(
|
||||
tx: DbTransactionClient,
|
||||
tenantId: string,
|
||||
groupId: string,
|
||||
context: GroupMembershipSyncContext
|
||||
): Promise<void> {
|
||||
await syncPermissionGroupChatsIfEnabledWithTx(tx, {
|
||||
tenantId,
|
||||
groupId,
|
||||
actorUserId: context.actorUserId,
|
||||
requestId: `${context.requestId}:group-chats`,
|
||||
});
|
||||
await syncProjectChannelsForPermissionGroupWithTx(tx, {
|
||||
tenantId,
|
||||
groupId,
|
||||
actorUserId: context.actorUserId,
|
||||
requestId: `${context.requestId}:project-chats`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUserGroups(groupId: string, userIds: string[]) {
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
if (uniqueUserIds.length === 0) {
|
||||
return { count: 0 };
|
||||
async function requireTenantGroup(
|
||||
tx: DbTransactionClient,
|
||||
tenantId: string,
|
||||
groupId: string
|
||||
): Promise<Readonly<{ id: string; name: string }>> {
|
||||
const group = await tx.group.findFirst({
|
||||
where: withTenantScope(tenantId, { id: groupId }),
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!group) throw new Error("Permission group is not available in the tenant");
|
||||
return group;
|
||||
}
|
||||
|
||||
async function requireActiveTenantUsers(tx: DbTransactionClient, tenantId: string, userIds: readonly string[]): Promise<void> {
|
||||
if (userIds.length === 0) return;
|
||||
const expectedUserIds = [...userIds].sort();
|
||||
const memberships = await tx.tenantUser.findMany({
|
||||
where: withTenantScope(tenantId, {
|
||||
userId: { in: expectedUserIds },
|
||||
status: 2,
|
||||
user: { active: true, pendingDeletion: false, pseudonymized: false },
|
||||
}),
|
||||
select: { userId: true },
|
||||
orderBy: { userId: "asc" },
|
||||
});
|
||||
const activeUserIds = memberships.map((membership) => membership.userId).sort();
|
||||
if (activeUserIds.length !== expectedUserIds.length || activeUserIds.some((userId, index) => userId !== expectedUserIds[index])) {
|
||||
throw new Error("Permission group contains a user outside the active tenant membership");
|
||||
}
|
||||
return await db.groupUser.createMany({
|
||||
data: uniqueUserIds.map((userId) => ({
|
||||
userId,
|
||||
groupId,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteUserGroup(userId: string, groupId: string) {
|
||||
return await db.groupUser.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
groupId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function replaceGroupUsers(groupId: string, tenantId: string, userIds: string[]) {
|
||||
export async function createPermissionGroupWithUsers(
|
||||
tenantId: string,
|
||||
input: PermissionGroupCreateInput,
|
||||
userIds: string[]
|
||||
) {
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
return await db.$transaction(async (tx) => {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await requireActiveTenantUsers(tx, tenantId, uniqueUserIds);
|
||||
const group = await tx.group.create({
|
||||
data: withTenantScope(tenantId, input),
|
||||
});
|
||||
if (uniqueUserIds.length > 0) {
|
||||
await tx.groupUser.createMany({
|
||||
data: uniqueUserIds.map((userId) => ({ userId, groupId: group.id })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
return group;
|
||||
});
|
||||
}
|
||||
|
||||
export async function addGroupUsersAndSync(
|
||||
groupId: string,
|
||||
tenantId: string,
|
||||
userIds: string[],
|
||||
context: GroupMembershipSyncContext
|
||||
) {
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
if (uniqueUserIds.length === 0) return { count: 0 };
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
|
||||
await requireTenantGroup(tx, tenantId, groupId);
|
||||
await requireActiveTenantUsers(tx, tenantId, uniqueUserIds);
|
||||
const result = await tx.groupUser.createMany({
|
||||
data: uniqueUserIds.map((userId) => ({ userId, groupId })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
if (result.count > 0) await syncGroupMembershipDependents(tx, tenantId, groupId, context);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeGroupUsersAndSync(
|
||||
groupId: string,
|
||||
tenantId: string,
|
||||
userIds: string[],
|
||||
context: GroupMembershipSyncContext
|
||||
) {
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
if (uniqueUserIds.length === 0) return { count: 0 };
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
|
||||
await requireTenantGroup(tx, tenantId, groupId);
|
||||
const result = await tx.groupUser.deleteMany({ where: { groupId, userId: { in: uniqueUserIds } } });
|
||||
if (result.count > 0) await syncGroupMembershipDependents(tx, tenantId, groupId, context);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
export async function replaceGroupUsers(
|
||||
groupId: string,
|
||||
tenantId: string,
|
||||
userIds: string[],
|
||||
context: GroupMembershipSyncContext
|
||||
) {
|
||||
const uniqueUserIds = [...new Set(userIds)];
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
|
||||
await requireTenantGroup(tx, tenantId, groupId);
|
||||
await requireActiveTenantUsers(tx, tenantId, uniqueUserIds);
|
||||
await tx.groupUser.deleteMany({
|
||||
where: {
|
||||
groupId,
|
||||
group: { tenantId },
|
||||
},
|
||||
});
|
||||
if (uniqueUserIds.length === 0) {
|
||||
return { count: 0 };
|
||||
}
|
||||
return await tx.groupUser.createMany({
|
||||
data: uniqueUserIds.map((userId) => ({
|
||||
userId,
|
||||
groupId,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
const result =
|
||||
uniqueUserIds.length === 0
|
||||
? { count: 0 }
|
||||
: await tx.groupUser.createMany({
|
||||
data: uniqueUserIds.map((userId) => ({ userId, groupId })),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
await syncGroupMembershipDependents(tx, tenantId, groupId, context);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteGroupUsers(groupId: string, tenantId: string) {
|
||||
return await db.groupUser.deleteMany({
|
||||
where: {
|
||||
groupId,
|
||||
group: { tenantId },
|
||||
},
|
||||
export async function deletePermissionGroupAndSync(
|
||||
groupId: string,
|
||||
tenantId: string,
|
||||
context: GroupMembershipSyncContext
|
||||
) {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
|
||||
const group = await requireTenantGroup(tx, tenantId, groupId);
|
||||
const projectMemberships = await tx.projektMitglied.findMany({
|
||||
where: withTenantScope(tenantId, { groupId, archivedAt: null }),
|
||||
select: { id: true, projektId: true, rolle: true },
|
||||
orderBy: [{ projektId: "asc" }, { id: "asc" }],
|
||||
});
|
||||
|
||||
// Empty the source first so both chat reconcilers revoke group-derived
|
||||
// access while the Group row is still available to their tenant checks.
|
||||
await tx.groupUser.deleteMany({ where: { groupId, group: { tenantId } } });
|
||||
await syncGroupMembershipDependents(tx, tenantId, groupId, context);
|
||||
|
||||
// Chat source rows describe live configuration and become invalid with the
|
||||
// group. Project-member rows are business history, so archive rather than
|
||||
// hard-delete them and retain the bare group id as the historical source.
|
||||
await tx.teamChatGroupSource.deleteMany({ where: withTenantScope(tenantId, { groupId }) });
|
||||
const archivedAt = new Date();
|
||||
if (projectMemberships.length > 0) {
|
||||
await tx.projektMitglied.updateMany({
|
||||
where: withTenantScope(tenantId, { groupId, archivedAt: null }),
|
||||
data: { archivedAt },
|
||||
});
|
||||
for (const [projectId, memberships] of groupProjectMemberships(projectMemberships)) {
|
||||
await logActivity(
|
||||
{
|
||||
tenantId,
|
||||
actorUserId: context.actorUserId,
|
||||
actorKind: "user",
|
||||
activityType: "project_member_removed",
|
||||
subjectType: "project",
|
||||
subjectId: projectId,
|
||||
summaryText: "activity.runtime.permissions.groupProjectMembershipArchived",
|
||||
metadata: {
|
||||
groupId,
|
||||
groupName: group.name,
|
||||
membershipIds: memberships.map(({ id }) => id),
|
||||
roles: [...new Set(memberships.map(({ rolle }) => rolle))].sort(),
|
||||
archivedAt: archivedAt.toISOString(),
|
||||
reason: "permission_group_deleted",
|
||||
},
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId,
|
||||
actorId: context.actorUserId,
|
||||
actorType: "user",
|
||||
action: "permissions.group.deleted",
|
||||
targetType: "Group",
|
||||
targetId: groupId,
|
||||
requestId: context.requestId,
|
||||
sourceModule: "permissions",
|
||||
dataSensitivity: "internal",
|
||||
metadata: {
|
||||
groupName: group.name,
|
||||
archivedProjectMembershipIds: projectMemberships.map(({ id }) => id),
|
||||
affectedProjectIds: [...new Set(projectMemberships.map(({ projektId }) => projektId))].sort(),
|
||||
},
|
||||
summaryText: "Eine Berechtigungsgruppe wurde gelöscht; Projektzuordnungen bleiben archiviert erhalten.",
|
||||
});
|
||||
|
||||
return tx.group.deleteMany({ where: withTenantScope(tenantId, { id: groupId }) });
|
||||
});
|
||||
}
|
||||
|
||||
function groupProjectMemberships<T extends Readonly<{ projektId: string }>>(rows: readonly T[]): ReadonlyMap<string, readonly T[]> {
|
||||
const grouped = new Map<string, T[]>();
|
||||
for (const row of rows) {
|
||||
const memberships = grouped.get(row.projektId) ?? [];
|
||||
memberships.push(row);
|
||||
grouped.set(row.projektId, memberships);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
// @vitest-environment node
|
||||
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
addGroupUsersAndSync,
|
||||
deletePermissionGroupAndSync,
|
||||
removeGroupUsersAndSync,
|
||||
} from "./userGroups.db.server";
|
||||
|
||||
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
|
||||
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
|
||||
|
||||
const TENANT_A = "chat_group_sync_rls_tenant_a";
|
||||
const TENANT_B = "chat_group_sync_rls_tenant_b";
|
||||
const ACTOR_A = "chat_group_sync_rls_actor_a";
|
||||
const MEMBER_A = "chat_group_sync_rls_member_a";
|
||||
const ACTOR_B = "chat_group_sync_rls_actor_b";
|
||||
const MEMBER_B = "chat_group_sync_rls_member_b";
|
||||
const GROUP_A = "chat_group_sync_rls_group_a";
|
||||
const GROUP_B = "chat_group_sync_rls_group_b";
|
||||
const CHAT_A = "chat_group_sync_rls_chat_a";
|
||||
const CHAT_B = "chat_group_sync_rls_chat_b";
|
||||
const PROJECT_A = "chat_group_sync_rls_project_a";
|
||||
const PROJECT_B = "chat_group_sync_rls_project_b";
|
||||
|
||||
describeIfDatabase("permission-group chat sync with the restricted app role", () => {
|
||||
const admin = createDbClient({ connectionString: ADMIN_URL });
|
||||
const app = getWriteDbClient();
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanupFixtures(admin);
|
||||
await admin.user.createMany({
|
||||
data: [
|
||||
{ id: ACTOR_A, email: "chat-group-sync-actor-a@example.test", firstName: "Actor", lastName: "A", active: true },
|
||||
{ id: MEMBER_A, email: "chat-group-sync-member-a@example.test", firstName: "Member", lastName: "A", active: true },
|
||||
{ id: ACTOR_B, email: "chat-group-sync-actor-b@example.test", firstName: "Actor", lastName: "B", active: true },
|
||||
{ id: MEMBER_B, email: "chat-group-sync-member-b@example.test", firstName: "Member", lastName: "B", active: true },
|
||||
],
|
||||
});
|
||||
await admin.tenant.createMany({
|
||||
data: [
|
||||
{ id: TENANT_A, slug: TENANT_A, name: "Group sync RLS tenant A", active: true },
|
||||
{ id: TENANT_B, slug: TENANT_B, name: "Group sync RLS tenant B", active: true },
|
||||
],
|
||||
});
|
||||
await admin.tenantUser.createMany({
|
||||
data: [
|
||||
{ id: `${TENANT_A}_actor`, tenantId: TENANT_A, userId: ACTOR_A, type: 0, joined: 1, status: 2 },
|
||||
{ id: `${TENANT_A}_member`, tenantId: TENANT_A, userId: MEMBER_A, type: 0, joined: 1, status: 2 },
|
||||
{ id: `${TENANT_B}_actor`, tenantId: TENANT_B, userId: ACTOR_B, type: 0, joined: 1, status: 2 },
|
||||
{ id: `${TENANT_B}_member`, tenantId: TENANT_B, userId: MEMBER_B, type: 0, joined: 1, status: 2 },
|
||||
],
|
||||
});
|
||||
await admin.group.createMany({
|
||||
data: [
|
||||
{ id: GROUP_A, tenantId: TENANT_A, createdByUserId: ACTOR_A, name: "Tenant A Dispatch", description: "A", color: 1 },
|
||||
{ id: GROUP_B, tenantId: TENANT_B, createdByUserId: ACTOR_B, name: "Tenant B Dispatch", description: "B", color: 2 },
|
||||
],
|
||||
});
|
||||
await admin.groupUser.create({ data: { id: `${GROUP_B}_member`, groupId: GROUP_B, userId: MEMBER_B } });
|
||||
await admin.teamChat.createMany({
|
||||
data: [
|
||||
{ id: CHAT_A, tenantId: TENANT_A, createdByUserId: ACTOR_A, kind: "group", name: "A", isPrivate: true, eventStreamId: `${CHAT_A}_stream` },
|
||||
{ id: CHAT_B, tenantId: TENANT_B, createdByUserId: ACTOR_B, kind: "group", name: "B", isPrivate: true, eventStreamId: `${CHAT_B}_stream` },
|
||||
],
|
||||
});
|
||||
await admin.teamChatGroupSource.createMany({
|
||||
data: [
|
||||
{ id: `${CHAT_A}_source`, tenantId: TENANT_A, chatId: CHAT_A, groupId: GROUP_A, syncEnabled: true },
|
||||
{ id: `${CHAT_B}_source`, tenantId: TENANT_B, chatId: CHAT_B, groupId: GROUP_B, syncEnabled: true },
|
||||
],
|
||||
});
|
||||
await admin.teamChatMember.createMany({
|
||||
data: [
|
||||
{ id: `${CHAT_A}_actor`, tenantId: TENANT_A, chatId: CHAT_A, userId: ACTOR_A, roleInChat: "admin", notificationPref: "all_messages", isManualMember: true, manualRoleInChat: "admin" },
|
||||
{ id: `${CHAT_B}_actor`, tenantId: TENANT_B, chatId: CHAT_B, userId: ACTOR_B, roleInChat: "admin", notificationPref: "all_messages", isManualMember: true, manualRoleInChat: "admin" },
|
||||
{ id: `${CHAT_B}_member`, tenantId: TENANT_B, chatId: CHAT_B, userId: MEMBER_B, notificationPref: "all_messages", isManualMember: false, isGroupManaged: true },
|
||||
],
|
||||
});
|
||||
await createProjectFixtures(admin);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanupFixtures(admin);
|
||||
await Promise.all([admin.$disconnect(), app.$disconnect()]);
|
||||
});
|
||||
|
||||
it("adds, removes, and deletes only tenant-A group sources while preserving project history", async () => {
|
||||
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
|
||||
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
|
||||
const rlsState = await app.$queryRaw<Array<{ tableName: string; enabled: boolean; forced: boolean }>>`
|
||||
SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced
|
||||
FROM pg_catalog.pg_class
|
||||
WHERE relnamespace = 'public'::regnamespace
|
||||
AND relname IN ('Group', 'GroupUser', 'ProjektMitglied', 'TeamChat', 'TeamChatGroupSource', 'TeamChatMember')
|
||||
ORDER BY relname ASC
|
||||
`;
|
||||
expect(rlsState).toHaveLength(6);
|
||||
expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true);
|
||||
await expect(app.group.findMany({ where: { id: GROUP_A }, select: { id: true } })).resolves.toEqual([]);
|
||||
|
||||
await addGroupUsersAndSync(GROUP_A, TENANT_A, [MEMBER_A], { actorUserId: ACTOR_A, requestId: "group-rls-add-a" });
|
||||
await expect(admin.teamChatMember.findUnique({ where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } } })).resolves.toMatchObject({
|
||||
isGroupManaged: true,
|
||||
leftAt: null,
|
||||
});
|
||||
|
||||
await removeGroupUsersAndSync(GROUP_A, TENANT_A, [MEMBER_A], { actorUserId: ACTOR_A, requestId: "group-rls-remove-a" });
|
||||
await expect(admin.teamChatMember.findUnique({ where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } } })).resolves.toMatchObject({
|
||||
isGroupManaged: false,
|
||||
leftAt: expect.any(Date),
|
||||
});
|
||||
|
||||
await addGroupUsersAndSync(GROUP_A, TENANT_A, [MEMBER_A], { actorUserId: ACTOR_A, requestId: "group-rls-readd-a" });
|
||||
await deletePermissionGroupAndSync(GROUP_A, TENANT_A, { actorUserId: ACTOR_A, requestId: "group-rls-delete-a" });
|
||||
|
||||
await expect(admin.group.findUnique({ where: { id: GROUP_A } })).resolves.toBeNull();
|
||||
await expect(admin.teamChatGroupSource.count({ where: { tenantId: TENANT_A, groupId: GROUP_A } })).resolves.toBe(0);
|
||||
await expect(admin.projektMitglied.findUnique({ where: { id: `${PROJECT_A}_group_member` } })).resolves.toMatchObject({
|
||||
groupId: GROUP_A,
|
||||
archivedAt: expect.any(Date),
|
||||
});
|
||||
await expect(admin.activity.count({ where: { tenantId: TENANT_A, subjectType: "project", subjectId: PROJECT_A, activityType: "project_member_removed" } })).resolves.toBeGreaterThan(0);
|
||||
await expect(admin.outboxEvent.count({ where: { tenantId: TENANT_A } })).resolves.toBeGreaterThan(0);
|
||||
|
||||
await expect(admin.group.findUnique({ where: { id: GROUP_B } })).resolves.toMatchObject({ tenantId: TENANT_B });
|
||||
await expect(admin.groupUser.findUnique({ where: { group_user_membership_key: { groupId: GROUP_B, userId: MEMBER_B } } })).resolves.not.toBeNull();
|
||||
await expect(admin.teamChatGroupSource.findUnique({ where: { chatId_groupId: { chatId: CHAT_B, groupId: GROUP_B } } })).resolves.toMatchObject({ tenantId: TENANT_B, syncEnabled: true });
|
||||
await expect(admin.teamChatMember.findUnique({ where: { chatId_userId: { chatId: CHAT_B, userId: MEMBER_B } } })).resolves.toMatchObject({ isGroupManaged: true, leftAt: null });
|
||||
await expect(admin.projektMitglied.findUnique({ where: { id: `${PROJECT_B}_group_member` } })).resolves.toMatchObject({ archivedAt: null });
|
||||
});
|
||||
});
|
||||
|
||||
async function createProjectFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
|
||||
await admin.pipeline.createMany({
|
||||
data: [
|
||||
{ id: `${PROJECT_A}_pipeline`, tenantId: TENANT_A, createdByUserId: ACTOR_A, name: "A Pipeline", typHint: "auftrag" },
|
||||
{ id: `${PROJECT_B}_pipeline`, tenantId: TENANT_B, createdByUserId: ACTOR_B, name: "B Pipeline", typHint: "auftrag" },
|
||||
],
|
||||
});
|
||||
await admin.pipelineStage.createMany({
|
||||
data: [
|
||||
{ id: `${PROJECT_A}_stage`, tenantId: TENANT_A, pipelineId: `${PROJECT_A}_pipeline`, name: "A Active", stageKind: "offen" },
|
||||
{ id: `${PROJECT_B}_stage`, tenantId: TENANT_B, pipelineId: `${PROJECT_B}_pipeline`, name: "B Active", stageKind: "offen" },
|
||||
],
|
||||
});
|
||||
await admin.projekt.createMany({
|
||||
data: [
|
||||
{ id: PROJECT_A, tenantId: TENANT_A, createdByUserId: ACTOR_A, projektNummer: "RLS-A", projektname: "RLS A", pipelineId: `${PROJECT_A}_pipeline`, stageId: `${PROJECT_A}_stage` },
|
||||
{ id: PROJECT_B, tenantId: TENANT_B, createdByUserId: ACTOR_B, projektNummer: "RLS-B", projektname: "RLS B", pipelineId: `${PROJECT_B}_pipeline`, stageId: `${PROJECT_B}_stage` },
|
||||
],
|
||||
});
|
||||
await admin.projektMitglied.createMany({
|
||||
data: [
|
||||
{ id: `${PROJECT_A}_group_member`, tenantId: TENANT_A, projektId: PROJECT_A, groupId: GROUP_A, rolle: "monteur", createdByUserId: ACTOR_A },
|
||||
{ id: `${PROJECT_B}_group_member`, tenantId: TENANT_B, projektId: PROJECT_B, groupId: GROUP_B, rolle: "monteur", createdByUserId: ACTOR_B },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async function cleanupFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
|
||||
const tenantIds = [TENANT_A, TENANT_B];
|
||||
await admin.teamChatMember.updateMany({ where: { tenantId: { in: tenantIds } }, data: { lastReadMessageId: null, lastReadAt: null } });
|
||||
await admin.teamChatEvent.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.teamChatMessage.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.teamChatMember.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.teamChatGroupSource.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.teamChat.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.activity.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.outboxEvent.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.projektMitglied.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.projekt.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.pipelineStage.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.pipeline.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.groupUser.deleteMany({ where: { groupId: { in: [GROUP_A, GROUP_B] } } });
|
||||
await admin.group.deleteMany({ where: { id: { in: [GROUP_A, GROUP_B] } } });
|
||||
await admin.tenantUser.deleteMany({ where: { tenantId: { in: tenantIds } } });
|
||||
await admin.tenant.deleteMany({ where: { id: { in: tenantIds } } });
|
||||
await admin.user.deleteMany({ where: { id: { in: [ACTOR_A, MEMBER_A, ACTOR_B, MEMBER_B] } } });
|
||||
}
|
||||
+77
-16
@@ -2,6 +2,13 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
|
||||
const permissionCacheMock = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
set: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
invalidateScopes: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../db.server", () => ({
|
||||
db: {
|
||||
permission: {
|
||||
@@ -22,11 +29,25 @@ vi.mock("../../db.server", () => ({
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/cache.server", () => ({
|
||||
cachified: vi.fn((options: { getFreshValue: () => unknown }) => options.getFreshValue()),
|
||||
clearCacheKey: vi.fn(),
|
||||
}));
|
||||
vi.mock("./permission-cache.server", async () => {
|
||||
const { clearCacheKey } = await import("~/utils/cache.server");
|
||||
permissionCacheMock.invalidate.mockImplementation(async (userId: string, tenantId: string | null) => {
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
});
|
||||
permissionCacheMock.invalidateScopes.mockImplementation(async (scopes: Array<{ userId: string; tenantId: string | null }>) => {
|
||||
for (const scope of scopes) await permissionCacheMock.invalidate(scope.userId, scope.tenantId);
|
||||
});
|
||||
return {
|
||||
getCachedPermissionNames: permissionCacheMock.get,
|
||||
cachePermissionNames: permissionCacheMock.set,
|
||||
invalidateUserPermissionCache: permissionCacheMock.invalidate,
|
||||
invalidateUserPermissionCacheScopes: permissionCacheMock.invalidateScopes,
|
||||
};
|
||||
});
|
||||
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { db } from "../../db.server";
|
||||
import {
|
||||
countUserPermission,
|
||||
@@ -44,6 +65,7 @@ import {
|
||||
getUserRoleInTenant,
|
||||
getUserRoles,
|
||||
getUsersRolesInTenant,
|
||||
reconcileAdminUserRoleByName,
|
||||
userHasPermission,
|
||||
} from "./userRoles.db.server";
|
||||
|
||||
@@ -52,7 +74,8 @@ const dbMock = vi.mocked(db);
|
||||
describe("user role persistence", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
|
||||
permissionCacheMock.get.mockResolvedValue(null);
|
||||
permissionCacheMock.set.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
it("queries user-role relationships with tenant and admin scope", async () => {
|
||||
@@ -71,7 +94,7 @@ describe("user role persistence", () => {
|
||||
where: { userId: "user_1", role: { name: "Admin" }, tenantId: "tenant_1" },
|
||||
});
|
||||
expect(dbMock.userRole.findFirst).toHaveBeenNthCalledWith(3, {
|
||||
where: { userId: "user_1", role: { name: "SuperAdmin" }, tenantId: null },
|
||||
where: { userId: "user_1", role: { name: "SuperAdmin", type: "admin" }, tenantId: null },
|
||||
});
|
||||
expect(dbMock.userRole.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -99,12 +122,8 @@ describe("user role persistence", () => {
|
||||
|
||||
await expect(getPermissionsByUser("user_1", "tenant_1")).resolves.toEqual(["members.read", "settings.update"]);
|
||||
|
||||
expect(cachified).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
key: "userRoles:user_1:tenant_1",
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
})
|
||||
);
|
||||
expect(permissionCacheMock.get).toHaveBeenCalledWith("user_1", "tenant_1");
|
||||
expect(permissionCacheMock.set).toHaveBeenCalledWith("user_1", "tenant_1", ["members.read", "settings.update"]);
|
||||
});
|
||||
|
||||
it("checks permission membership through the cached user-role expansion", async () => {
|
||||
@@ -129,10 +148,29 @@ describe("user role persistence", () => {
|
||||
await expect(userHasPermission("user_1", "tenant_1", "members.read")).resolves.toBe(true);
|
||||
await expect(userHasPermission("user_1", "tenant_1", "settings.update")).resolves.toBe(false);
|
||||
|
||||
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "userRoles:user_1:tenant_1" }));
|
||||
expect(permissionCacheMock.get).toHaveBeenCalledWith("user_1", "tenant_1");
|
||||
expect(dbMock.permission.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not repopulate a stale grant when revocation races a cache miss", async () => {
|
||||
permissionCacheMock.set.mockResolvedValue(true);
|
||||
vi.mocked(dbMock.userRole.findMany)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
role: {
|
||||
name: "Admin",
|
||||
permissions: [{ permission: { name: "members.delete" } }],
|
||||
},
|
||||
},
|
||||
] as never)
|
||||
.mockResolvedValueOnce([] as never);
|
||||
|
||||
await expect(getPermissionsByUser("user_1", "tenant_1")).resolves.toEqual([]);
|
||||
|
||||
expect(permissionCacheMock.invalidate).toHaveBeenCalledWith("user_1", "tenant_1");
|
||||
expect(permissionCacheMock.set).toHaveBeenLastCalledWith("user_1", "tenant_1", []);
|
||||
});
|
||||
|
||||
it("returns the first matching permission name or null", async () => {
|
||||
vi.mocked(dbMock.userRole.findMany)
|
||||
.mockResolvedValueOnce([
|
||||
@@ -273,7 +311,9 @@ describe("user role persistence", () => {
|
||||
});
|
||||
|
||||
it("returns the concurrently-created user role when the unique assignment index wins the race", async () => {
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null).mockResolvedValueOnce({ id: "ur_concurrent" } as never);
|
||||
vi.mocked(dbMock.userRole.findFirst)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce({ id: "ur_concurrent" } as never);
|
||||
vi.mocked(dbMock.userRole.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }) as never);
|
||||
|
||||
await expect(createUserRole("user_1", "role_admin", null)).resolves.toEqual({ id: "ur_concurrent" });
|
||||
@@ -301,22 +341,22 @@ describe("user role persistence", () => {
|
||||
await expect(createUserRole("user_1", "role_1", null)).rejects.toBe(error);
|
||||
});
|
||||
|
||||
it("does not grant an admin role by name when no matching admin role exists", async () => {
|
||||
it("fails closed when a required admin role is not configured", async () => {
|
||||
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce(null);
|
||||
|
||||
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
|
||||
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).rejects.toThrow("Required admin role is not configured");
|
||||
|
||||
expect(dbMock.role.findFirst).toHaveBeenCalledWith({
|
||||
where: { name: "SuperAdmin", type: "admin" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.userRole.create).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
|
||||
it("grants a matching admin role by name with admin scope and invalidates the role cache", async () => {
|
||||
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce({ id: "role_super_admin" } as never);
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null);
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(dbMock.userRole.create).mockResolvedValueOnce({ id: "ur_admin" } as never);
|
||||
|
||||
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
|
||||
@@ -327,6 +367,27 @@ describe("user role persistence", () => {
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
|
||||
it("revokes SuperAdmin on an SSO staff downgrade and invalidates the role cache", async () => {
|
||||
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce({ id: "role_super_admin" } as never);
|
||||
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
|
||||
|
||||
await expect(reconcileAdminUserRoleByName("user_1", "SuperAdmin", false)).resolves.toBe("revoked");
|
||||
|
||||
expect(dbMock.userRole.deleteMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user_1", roleId: "role_super_admin", tenantId: null },
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
|
||||
it("keeps staff reconciliation safe when the SuperAdmin role is not configured", async () => {
|
||||
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce(null);
|
||||
|
||||
await expect(reconcileAdminUserRoleByName("user_1", "SuperAdmin", false)).resolves.toBe("unchanged");
|
||||
|
||||
expect(dbMock.userRole.deleteMany).not.toHaveBeenCalled();
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
|
||||
});
|
||||
|
||||
it("creates, bulk-creates, and deletes user roles while clearing tenant-specific caches", async () => {
|
||||
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null);
|
||||
vi.mocked(dbMock.userRole.create).mockResolvedValueOnce({ id: "ur_1" } as never);
|
||||
|
||||
+88
-51
@@ -1,7 +1,7 @@
|
||||
import { Permission, Role, RolePermission, UserRole } from "@hivegrid/db/prisma-browser";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { db } from "../../db.server";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
import { cachePermissionNames, getCachedPermissionNames, invalidateUserPermissionCache, invalidateUserPermissionCacheScopes } from "./permission-cache.server";
|
||||
|
||||
export type UserRoleWithPermission = UserRole & {
|
||||
role: Role & { permissions: (RolePermission & { permission: Permission })[] };
|
||||
@@ -21,8 +21,8 @@ function getUserRoleAssignmentKey(assignment: UserRoleAssignment): string {
|
||||
return `${assignment.userId}:${assignment.roleId}:${normalizeTenantId(assignment.tenantId)}`;
|
||||
}
|
||||
|
||||
function clearUserRoleCache(userId: string, tenantId: string | null): void {
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
async function clearUserRoleCache(userId: string, tenantId: string | null): Promise<void> {
|
||||
await invalidateUserPermissionCache(userId, tenantId);
|
||||
}
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
@@ -57,6 +57,7 @@ export async function getUserRoleInAdmin(userId: string, roleName: string) {
|
||||
userId,
|
||||
role: {
|
||||
name: roleName,
|
||||
type: "admin",
|
||||
},
|
||||
tenantId: null,
|
||||
},
|
||||
@@ -89,33 +90,42 @@ export async function getUserRoles(userId: string, tenantId?: string | null): Pr
|
||||
}
|
||||
|
||||
export async function getPermissionsByUser(userId: string, tenantId: string | null): Promise<string[]> {
|
||||
const userRoles = await cachified({
|
||||
key: `userRoles:${userId}:${tenantId}`,
|
||||
ttl: 1000 * 60 * 60 * 24,
|
||||
getFreshValue: () =>
|
||||
db.userRole.findMany({
|
||||
where: { userId, tenantId },
|
||||
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
|
||||
}),
|
||||
});
|
||||
const roles: string[] = [];
|
||||
const names: string[] = [];
|
||||
userRoles.forEach((userRoles) => {
|
||||
if (!roles.includes(userRoles.role.name)) {
|
||||
roles.push(userRoles.role.name);
|
||||
}
|
||||
userRoles.role.permissions.forEach((permission) => {
|
||||
if (!names.includes(permission.permission.name)) {
|
||||
names.push(permission.permission.name);
|
||||
}
|
||||
const cached = await getCachedPermissionNames(userId, tenantId);
|
||||
if (cached !== null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const readPermissionNames = async (): Promise<string[]> => {
|
||||
const userRoles = await db.userRole.findMany({
|
||||
where: { userId, tenantId },
|
||||
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
|
||||
});
|
||||
});
|
||||
// console.log({
|
||||
// userId,
|
||||
// tenantId,
|
||||
// roles,
|
||||
// permissions: names,
|
||||
// });
|
||||
const names: string[] = [];
|
||||
userRoles.forEach((userRole) => {
|
||||
userRole.role.permissions.forEach((permission) => {
|
||||
if (!names.includes(permission.permission.name)) {
|
||||
names.push(permission.permission.name);
|
||||
}
|
||||
});
|
||||
});
|
||||
return names;
|
||||
};
|
||||
|
||||
const names = await readPermissionNames();
|
||||
const cachedSuccessfully = await cachePermissionNames(userId, tenantId, names);
|
||||
if (!cachedSuccessfully) {
|
||||
return names;
|
||||
}
|
||||
|
||||
// Close the cache-aside race: a revocation can commit and publish between
|
||||
// the database read and cache write. Re-read after populating; a later
|
||||
// revocation necessarily publishes after our write and purges it normally.
|
||||
const confirmedNames = await readPermissionNames();
|
||||
if (confirmedNames.length !== names.length || confirmedNames.some((name) => !names.includes(name))) {
|
||||
await invalidateUserPermissionCache(userId, tenantId);
|
||||
await cachePermissionNames(userId, tenantId, confirmedNames);
|
||||
return confirmedNames;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
@@ -235,7 +245,7 @@ export async function ensureTenantUserAppRoles({
|
||||
missingRoles.map((role) => ({ id: role.id, tenantId }))
|
||||
);
|
||||
} else {
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
await clearUserRoleCache(userId, tenantId);
|
||||
}
|
||||
|
||||
return { created: missingRoles.length, roleCount: roles.length };
|
||||
@@ -254,7 +264,7 @@ export async function createUserRole(userId: string, roleId: string, tenantId: s
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
await clearUserRoleCache(userId, tenantId);
|
||||
return item;
|
||||
} catch (error) {
|
||||
if (!isUniqueConstraintError(error)) {
|
||||
@@ -272,18 +282,44 @@ export async function createUserRole(userId: string, roleId: string, tenantId: s
|
||||
* Grants an admin-scoped RBAC role (e.g. "SuperAdmin") to a user by role name,
|
||||
* idempotently. Used by the Admin-SSO callback to wire the JIT-provisioned
|
||||
* `super_admin` identity to its concrete permission set. `createUserRole`
|
||||
* invalidates the `userRoles:<userId>:null` cache, so the granted permissions
|
||||
* are visible on the very next request — independent of the cache TTL.
|
||||
* publishes through the shared permission cache, so every replica observes
|
||||
* the grant or revocation on the next request.
|
||||
*/
|
||||
export async function ensureAdminUserRoleByName(userId: string, roleName: string): Promise<void> {
|
||||
await reconcileAdminUserRoleByName(userId, roleName, true);
|
||||
}
|
||||
|
||||
export type AdminRoleReconciliationResult = "granted" | "revoked" | "unchanged";
|
||||
|
||||
export async function reconcileAdminUserRoleByName(userId: string, roleName: string, shouldHaveRole: boolean): Promise<AdminRoleReconciliationResult> {
|
||||
const role = await db.role.findFirst({
|
||||
where: { name: roleName, type: "admin" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!role) {
|
||||
return;
|
||||
await clearUserRoleCache(userId, null);
|
||||
if (shouldHaveRole) {
|
||||
throw new Error(`Required admin role is not configured: ${roleName}`);
|
||||
}
|
||||
return "unchanged";
|
||||
}
|
||||
await createUserRole(userId, role.id, null);
|
||||
|
||||
if (shouldHaveRole) {
|
||||
const existing = await getUserRole(userId, role.id, null);
|
||||
if (existing) {
|
||||
await clearUserRoleCache(userId, null);
|
||||
return "unchanged";
|
||||
}
|
||||
await createUserRole(userId, role.id, null);
|
||||
await clearUserRoleCache(userId, null);
|
||||
return "granted";
|
||||
}
|
||||
|
||||
const revoked = await db.userRole.deleteMany({
|
||||
where: { userId, roleId: role.id, tenantId: null },
|
||||
});
|
||||
await clearUserRoleCache(userId, null);
|
||||
return revoked.count > 0 ? "revoked" : "unchanged";
|
||||
}
|
||||
|
||||
export async function createUserRoles(userId: string, roles: { id: string; tenantId: string | null }[]) {
|
||||
@@ -336,29 +372,28 @@ export async function createUserRoleAssignments(assignments: UserRoleAssignment[
|
||||
})
|
||||
: { count: 0 };
|
||||
|
||||
cacheScopes.forEach((scope) => {
|
||||
clearUserRoleCache(scope.userId, scope.tenantId);
|
||||
});
|
||||
await invalidateUserPermissionCacheScopes(cacheScopes.map((scope) => ({ userId: scope.userId, tenantId: scope.tenantId })));
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteUserRole(userId: string, roleId: string, tenantId: string | null = null) {
|
||||
return await db.userRole
|
||||
.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
roleId,
|
||||
tenantId,
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(`userRoles:${userId}:${tenantId}`);
|
||||
return item;
|
||||
});
|
||||
const item = await db.userRole.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
roleId,
|
||||
tenantId,
|
||||
},
|
||||
});
|
||||
await clearUserRoleCache(userId, tenantId);
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function deleteAllUserRoles(userId: string, type: string) {
|
||||
return await db.userRole.deleteMany({
|
||||
const assignments = await db.userRole.findMany({
|
||||
where: { userId, role: { type } },
|
||||
select: { tenantId: true },
|
||||
});
|
||||
const result = await db.userRole.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
@@ -366,4 +401,6 @@ export async function deleteAllUserRoles(userId: string, type: string) {
|
||||
},
|
||||
},
|
||||
});
|
||||
await invalidateUserPermissionCacheScopes(assignments.map((assignment) => ({ userId, tenantId: assignment.tenantId })));
|
||||
return result;
|
||||
}
|
||||
+196
-66
@@ -1,40 +1,174 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../db.server", () => ({
|
||||
db: {
|
||||
registration: {
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
vi.mock("@hivegrid/db/pretenant-security.server", () => ({
|
||||
createRegistrationCapability: vi.fn(),
|
||||
findRegistrationBillingPreferenceCapability: vi.fn(),
|
||||
findRegistrationByTokenCapability: vi.fn(),
|
||||
findRegistrationSummaryByEmail: vi.fn(),
|
||||
rotateRegistrationVerificationCapability: vi.fn(),
|
||||
updateRegistrationCapability: vi.fn(),
|
||||
}));
|
||||
|
||||
import { db } from "../db.server";
|
||||
import { createRegistration, getRegistrationByEmail, getRegistrationByToken, updateRegistration } from "./registration.db.server";
|
||||
import {
|
||||
createRegistrationCapability,
|
||||
findRegistrationBillingPreferenceCapability,
|
||||
findRegistrationByTokenCapability,
|
||||
findRegistrationSummaryByEmail,
|
||||
rotateRegistrationVerificationCapability,
|
||||
updateRegistrationCapability,
|
||||
} from "@hivegrid/db/pretenant-security.server";
|
||||
import {
|
||||
createRegistration,
|
||||
getRegistrationBillingPreference,
|
||||
getRegistrationByEmail,
|
||||
getRegistrationByToken,
|
||||
getRegistrationVerificationStateByToken,
|
||||
getRegistrationVerificationViewByToken,
|
||||
REGISTRATION_VERIFICATION_TTL_MS,
|
||||
rotateRegistrationVerification,
|
||||
updateRegistration,
|
||||
} from "./registration.db.server";
|
||||
|
||||
const registrationMock = vi.mocked(db.registration, true);
|
||||
const createCapabilityMock = vi.mocked(createRegistrationCapability);
|
||||
const findBillingPreferenceMock = vi.mocked(findRegistrationBillingPreferenceCapability);
|
||||
const findByEmailMock = vi.mocked(findRegistrationSummaryByEmail);
|
||||
const findByTokenMock = vi.mocked(findRegistrationByTokenCapability);
|
||||
const updateCapabilityMock = vi.mocked(updateRegistrationCapability);
|
||||
const rotateCapabilityMock = vi.mocked(rotateRegistrationVerificationCapability);
|
||||
|
||||
describe("registration db helpers", () => {
|
||||
const createdAt = new Date("2026-07-15T08:00:00.000Z");
|
||||
const verificationToken = "0123456789abcdef0123456789abcdef01234567";
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("looks up pending registrations by email and token", async () => {
|
||||
registrationMock.findFirst.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
|
||||
registrationMock.findUnique.mockResolvedValueOnce({ id: "registration_2" } as Awaited<ReturnType<typeof getRegistrationByToken>>);
|
||||
it("uses narrow pre-tenant capabilities for email and token lookups", async () => {
|
||||
findByEmailMock.mockResolvedValueOnce({ id: "registration_1", createdTenantId: null });
|
||||
findByTokenMock.mockResolvedValueOnce({ id: "registration_2", createdAt } as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
|
||||
|
||||
await expect(getRegistrationByEmail("ada@example.test")).resolves.toMatchObject({ id: "registration_1" });
|
||||
await expect(getRegistrationByToken("token_1")).resolves.toMatchObject({ id: "registration_2" });
|
||||
await expect(getRegistrationByEmail("ada@example.test")).resolves.toEqual({
|
||||
id: "registration_1",
|
||||
createdTenantId: null,
|
||||
});
|
||||
await expect(getRegistrationByToken(verificationToken, new Date(createdAt.getTime() + 1))).resolves.toMatchObject({ id: "registration_2" });
|
||||
|
||||
expect(registrationMock.findFirst).toHaveBeenCalledWith({ where: { email: "ada@example.test" } });
|
||||
expect(registrationMock.findUnique).toHaveBeenCalledWith({ where: { token: "token_1" } });
|
||||
expect(findByEmailMock).toHaveBeenCalledWith("ada@example.test");
|
||||
expect(findByTokenMock).toHaveBeenCalledWith(verificationToken);
|
||||
});
|
||||
|
||||
it("persists lead conversion context on new registrations", async () => {
|
||||
registrationMock.create.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
|
||||
it("delegates the consumed registration preference to the tenant-member capability", async () => {
|
||||
findBillingPreferenceMock.mockResolvedValueOnce({
|
||||
selectedSubscriptionPriceId: "price_swarm",
|
||||
selectedOfficeSeatQuantity: 5,
|
||||
selectedFieldSeatQuantity: 15,
|
||||
});
|
||||
|
||||
await expect(getRegistrationBillingPreference("tenant_1", "user_1")).resolves.toEqual({
|
||||
selectedSubscriptionPriceId: "price_swarm",
|
||||
selectedOfficeSeatQuantity: 5,
|
||||
selectedFieldSeatQuantity: 15,
|
||||
});
|
||||
expect(findBillingPreferenceMock).toHaveBeenCalledWith("tenant_1", "user_1");
|
||||
});
|
||||
|
||||
it("projects only verification-page fields from the token capability", async () => {
|
||||
findByTokenMock.mockResolvedValueOnce({
|
||||
email: "ada@example.test",
|
||||
createdTenantId: null,
|
||||
firstName: "Ada",
|
||||
id: "registration_1",
|
||||
createdAt,
|
||||
} as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
|
||||
|
||||
await expect(getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + 1))).resolves.toEqual({
|
||||
status: "pending",
|
||||
email: "ada@example.test",
|
||||
creationRequestKey: expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),
|
||||
});
|
||||
expect(findByTokenMock).toHaveBeenCalledWith(verificationToken);
|
||||
});
|
||||
|
||||
it("keeps the projected bootstrap key stable when a resend rotates the token", async () => {
|
||||
const rotatedToken = "f".repeat(40);
|
||||
findByTokenMock.mockResolvedValue({
|
||||
email: "ada@example.test",
|
||||
createdTenantId: null,
|
||||
firstName: "Ada",
|
||||
id: "registration_1",
|
||||
createdAt,
|
||||
} as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
|
||||
|
||||
const beforeResend = await getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + 1));
|
||||
const afterResend = await getRegistrationVerificationViewByToken(rotatedToken, new Date(createdAt.getTime() + 2));
|
||||
|
||||
expect(beforeResend).toMatchObject({ status: "pending" });
|
||||
expect(afterResend).toMatchObject({ status: "pending" });
|
||||
if (beforeResend.status !== "pending" || afterResend.status !== "pending") throw new Error("Expected pending registration views");
|
||||
expect(afterResend.creationRequestKey).toBe(beforeResend.creationRequestKey);
|
||||
expect(findByTokenMock).toHaveBeenNthCalledWith(1, verificationToken);
|
||||
expect(findByTokenMock).toHaveBeenNthCalledWith(2, rotatedToken);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["39 characters", "a".repeat(39)],
|
||||
["41 characters", "a".repeat(41)],
|
||||
["non-hex", `${"a".repeat(39)}g`],
|
||||
["oversized", "a".repeat(2048)],
|
||||
])("rejects %s before the SECURITY-DEFINER token lookup", async (_label, invalidToken) => {
|
||||
await expect(getRegistrationByToken(invalidToken)).resolves.toBeNull();
|
||||
expect(findByTokenMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([verificationToken, "ABCDEF0123456789ABCDEF0123456789ABCDEF01"])("accepts a valid legacy/new 40-hex token: %s", async (validToken) => {
|
||||
findByTokenMock.mockResolvedValueOnce({ id: "registration_2", createdAt } as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
|
||||
|
||||
await expect(getRegistrationByToken(validToken, new Date(createdAt.getTime() + 1))).resolves.toMatchObject({ id: "registration_2" });
|
||||
expect(findByTokenMock).toHaveBeenCalledWith(validToken);
|
||||
});
|
||||
|
||||
it("accepts verification at 23:59:59.999 and rejects it exactly at the 24h boundary for loader and action helpers", async () => {
|
||||
const registration = { id: "registration_1", email: "ada@example.test", createdAt, createdTenantId: null } as Awaited<
|
||||
ReturnType<typeof findRegistrationByTokenCapability>
|
||||
>;
|
||||
findByTokenMock.mockResolvedValue(registration);
|
||||
|
||||
await expect(getRegistrationByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS - 1))).resolves.toMatchObject({
|
||||
id: "registration_1",
|
||||
});
|
||||
await expect(getRegistrationByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS))).resolves.toBeNull();
|
||||
await expect(
|
||||
getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS - 1))
|
||||
).resolves.toMatchObject({ email: "ada@example.test" });
|
||||
await expect(getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS))).resolves.toEqual({
|
||||
status: "expired",
|
||||
});
|
||||
});
|
||||
|
||||
it("distinguishes expired, consumed, and invalid links without exposing registration PII", async () => {
|
||||
findByTokenMock
|
||||
.mockResolvedValueOnce({ id: "registration_expired", email: "expired@example.test", createdAt, createdTenantId: null } as Awaited<
|
||||
ReturnType<typeof findRegistrationByTokenCapability>
|
||||
>)
|
||||
.mockResolvedValueOnce({ id: "registration_used", email: "used@example.test", createdAt, createdTenantId: "tenant_1" } as Awaited<
|
||||
ReturnType<typeof findRegistrationByTokenCapability>
|
||||
>)
|
||||
.mockResolvedValueOnce(null);
|
||||
const afterTtl = new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS);
|
||||
|
||||
const expired = await getRegistrationVerificationStateByToken(verificationToken, afterTtl);
|
||||
const used = await getRegistrationVerificationStateByToken(verificationToken, afterTtl);
|
||||
const invalidView = await getRegistrationVerificationViewByToken(verificationToken, afterTtl);
|
||||
|
||||
expect(expired.status).toBe("expired");
|
||||
expect(used.status).toBe("used");
|
||||
expect(invalidView).toEqual({ status: "invalid" });
|
||||
expect(JSON.stringify(invalidView)).not.toContain("example.test");
|
||||
});
|
||||
|
||||
it("persists lead conversion context through the create capability", async () => {
|
||||
createCapabilityMock.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
|
||||
|
||||
await createRegistration({
|
||||
email: "ada@example.test",
|
||||
@@ -43,6 +177,8 @@ describe("registration db helpers", () => {
|
||||
token: "registration-token",
|
||||
company: "Analytical Engines",
|
||||
selectedSubscriptionPriceId: "price_1",
|
||||
selectedOfficeSeatQuantity: 4,
|
||||
selectedFieldSeatQuantity: 8,
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
@@ -50,25 +186,25 @@ describe("registration db helpers", () => {
|
||||
slug: "ada",
|
||||
});
|
||||
|
||||
expect(registrationMock.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
token: "registration-token",
|
||||
company: "Analytical Engines",
|
||||
selectedSubscriptionPriceId: "price_1",
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
ipAddress: "127.0.0.1",
|
||||
slug: "ada",
|
||||
},
|
||||
expect(createCapabilityMock).toHaveBeenCalledWith({
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
token: "registration-token",
|
||||
company: "Analytical Engines",
|
||||
selectedSubscriptionPriceId: "price_1",
|
||||
selectedOfficeSeatQuantity: 4,
|
||||
selectedFieldSeatQuantity: 8,
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
ipAddress: "127.0.0.1",
|
||||
slug: "ada",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears missing lead conversion fields to null when creating registrations", async () => {
|
||||
registrationMock.create.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
|
||||
createCapabilityMock.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
|
||||
|
||||
await createRegistration({
|
||||
email: "ada@example.test",
|
||||
@@ -77,47 +213,41 @@ describe("registration db helpers", () => {
|
||||
token: "registration-token",
|
||||
company: null,
|
||||
selectedSubscriptionPriceId: null,
|
||||
selectedOfficeSeatQuantity: null,
|
||||
selectedFieldSeatQuantity: null,
|
||||
ipAddress: null,
|
||||
slug: null,
|
||||
});
|
||||
|
||||
expect(registrationMock.create).toHaveBeenCalledWith(
|
||||
expect(createCapabilityMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
leadConversionLeadId: null,
|
||||
leadConversionToken: null,
|
||||
leadConversionPlanId: null,
|
||||
}),
|
||||
leadConversionLeadId: null,
|
||||
leadConversionToken: null,
|
||||
leadConversionPlanId: null,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("updates lead conversion context and created tenant id together", async () => {
|
||||
registrationMock.update.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof updateRegistration>>);
|
||||
it("binds tenant consumption to the expected token and rejects stale capabilities", async () => {
|
||||
updateCapabilityMock.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
||||
|
||||
await updateRegistration("registration_1", {
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
company: "Analytical Engines",
|
||||
createdTenantId: "tenant_1",
|
||||
token: "new-token",
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
});
|
||||
await expect(updateRegistration("registration_1", { expectedToken: "token_1" }, { createdTenantId: "tenant_1" })).resolves.toBe(true);
|
||||
await expect(updateRegistration("registration_1", { expectedToken: "stale-token" }, { createdTenantId: "tenant_1" })).rejects.toThrow(
|
||||
"Registration update capability was rejected"
|
||||
);
|
||||
});
|
||||
|
||||
expect(registrationMock.update).toHaveBeenCalledWith({
|
||||
where: { id: "registration_1" },
|
||||
data: {
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
company: "Analytical Engines",
|
||||
createdTenantId: "tenant_1",
|
||||
token: "new-token",
|
||||
leadConversionLeadId: "lead_1",
|
||||
leadConversionToken: "signed-lead-token",
|
||||
leadConversionPlanId: "plan_pro",
|
||||
},
|
||||
it("rotates a resend only through the previous-token capability", async () => {
|
||||
rotateCapabilityMock.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
||||
|
||||
await expect(rotateRegistrationVerification("registration_1", "old-token", verificationToken)).resolves.toBe(true);
|
||||
await expect(rotateRegistrationVerification("registration_1", "stale-token", verificationToken)).rejects.toThrow(
|
||||
"Registration verification rotation capability was rejected"
|
||||
);
|
||||
expect(rotateCapabilityMock).toHaveBeenNthCalledWith(1, {
|
||||
id: "registration_1",
|
||||
expectedToken: "old-token",
|
||||
token: verificationToken,
|
||||
});
|
||||
});
|
||||
});
|
||||
+90
-52
@@ -1,19 +1,67 @@
|
||||
import { db } from "../db.server";
|
||||
import {
|
||||
createRegistrationCapability,
|
||||
findRegistrationBillingPreferenceCapability,
|
||||
findRegistrationByTokenCapability,
|
||||
findRegistrationSummaryByEmail,
|
||||
rotateRegistrationVerificationCapability,
|
||||
updateRegistrationCapability,
|
||||
} from "@hivegrid/db/pretenant-security.server";
|
||||
import { deriveVerificationCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
|
||||
|
||||
export async function getRegistrationByEmail(email: string) {
|
||||
return await db.registration.findFirst({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
export const REGISTRATION_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const REGISTRATION_VERIFICATION_TOKEN_PATTERN = /^[a-f0-9]{40}$/iu;
|
||||
type RegistrationRecord = NonNullable<Awaited<ReturnType<typeof findRegistrationByTokenCapability>>>;
|
||||
|
||||
export type RegistrationVerificationState =
|
||||
| { status: "invalid" }
|
||||
| { status: "expired"; registration: RegistrationRecord }
|
||||
| { status: "used"; registration: RegistrationRecord }
|
||||
| { status: "pending"; registration: RegistrationRecord };
|
||||
|
||||
export class RegistrationVerificationRotationConflictError extends Error {
|
||||
constructor() {
|
||||
super("Registration verification rotation capability was rejected");
|
||||
this.name = "RegistrationVerificationRotationConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRegistrationByToken(token: string) {
|
||||
return await db.registration.findUnique({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
});
|
||||
export async function getRegistrationByEmail(email: string) {
|
||||
return await findRegistrationSummaryByEmail(email);
|
||||
}
|
||||
|
||||
export async function getRegistrationBillingPreference(tenantId: string, userId: string) {
|
||||
return await findRegistrationBillingPreferenceCapability(tenantId, userId);
|
||||
}
|
||||
|
||||
export async function getRegistrationByToken(token: string, now = new Date()) {
|
||||
const state = await getRegistrationVerificationStateByToken(token, now);
|
||||
return state.status === "pending" || state.status === "used" ? state.registration : null;
|
||||
}
|
||||
|
||||
export async function getRegistrationVerificationStateByToken(token: string, now = new Date()): Promise<RegistrationVerificationState> {
|
||||
if (!REGISTRATION_VERIFICATION_TOKEN_PATTERN.test(token)) return { status: "invalid" };
|
||||
const registration = await findRegistrationByTokenCapability(token);
|
||||
if (!registration) return { status: "invalid" };
|
||||
if (registration.createdTenantId) return { status: "used", registration };
|
||||
if (!isRegistrationVerificationFresh(registration.createdAt, now)) return { status: "expired", registration };
|
||||
return { status: "pending", registration };
|
||||
}
|
||||
|
||||
/** Minimal projection for the public verification page. */
|
||||
export async function getRegistrationVerificationViewByToken(token: string, now = new Date()) {
|
||||
const state = await getRegistrationVerificationStateByToken(token, now);
|
||||
if (state.status !== "pending") return { status: state.status } as const;
|
||||
return {
|
||||
status: "pending" as const,
|
||||
email: state.registration.email,
|
||||
creationRequestKey: deriveVerificationCreationRequestKey(state.registration.id),
|
||||
};
|
||||
}
|
||||
|
||||
export function isRegistrationVerificationFresh(createdAt: Date | string, now = new Date()): boolean {
|
||||
const createdAtMs = new Date(createdAt).getTime();
|
||||
const nowMs = now.getTime();
|
||||
return Number.isFinite(createdAtMs) && nowMs >= createdAtMs && nowMs - createdAtMs < REGISTRATION_VERIFICATION_TTL_MS;
|
||||
}
|
||||
|
||||
export async function createRegistration(data: {
|
||||
@@ -23,53 +71,43 @@ export async function createRegistration(data: {
|
||||
token: string;
|
||||
company: string | null;
|
||||
selectedSubscriptionPriceId: string | null;
|
||||
selectedOfficeSeatQuantity: number | null;
|
||||
selectedFieldSeatQuantity: number | null;
|
||||
leadConversionLeadId?: string | null;
|
||||
leadConversionToken?: string | null;
|
||||
leadConversionPlanId?: string | null;
|
||||
ipAddress: string | null;
|
||||
slug: string | null;
|
||||
}) {
|
||||
return await db.registration.create({
|
||||
data: {
|
||||
email: data.email,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
token: data.token,
|
||||
company: data.company,
|
||||
selectedSubscriptionPriceId: data.selectedSubscriptionPriceId,
|
||||
leadConversionLeadId: data.leadConversionLeadId ?? null,
|
||||
leadConversionToken: data.leadConversionToken ?? null,
|
||||
leadConversionPlanId: data.leadConversionPlanId ?? null,
|
||||
ipAddress: data.ipAddress,
|
||||
slug: data.slug,
|
||||
},
|
||||
return await createRegistrationCapability({
|
||||
email: data.email,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
token: data.token,
|
||||
company: data.company,
|
||||
selectedSubscriptionPriceId: data.selectedSubscriptionPriceId,
|
||||
selectedOfficeSeatQuantity: data.selectedOfficeSeatQuantity,
|
||||
selectedFieldSeatQuantity: data.selectedFieldSeatQuantity,
|
||||
leadConversionLeadId: data.leadConversionLeadId ?? null,
|
||||
leadConversionToken: data.leadConversionToken ?? null,
|
||||
leadConversionPlanId: data.leadConversionPlanId ?? null,
|
||||
ipAddress: data.ipAddress,
|
||||
slug: data.slug,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateRegistration(
|
||||
id: string,
|
||||
data: {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
company?: string | null;
|
||||
createdTenantId?: string | null;
|
||||
token?: string;
|
||||
leadConversionLeadId?: string | null;
|
||||
leadConversionToken?: string | null;
|
||||
leadConversionPlanId?: string | null;
|
||||
export async function rotateRegistrationVerification(id: string, expectedToken: string, token: string) {
|
||||
const updated = await rotateRegistrationVerificationCapability({ id, expectedToken, token });
|
||||
if (!updated) {
|
||||
throw new RegistrationVerificationRotationConflictError();
|
||||
}
|
||||
) {
|
||||
return await db.registration.update({
|
||||
where: { id },
|
||||
data: {
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
company: data.company,
|
||||
createdTenantId: data.createdTenantId,
|
||||
token: data.token,
|
||||
leadConversionLeadId: data.leadConversionLeadId,
|
||||
leadConversionToken: data.leadConversionToken,
|
||||
leadConversionPlanId: data.leadConversionPlanId,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function updateRegistration(id: string, capability: { expectedToken: string }, data: { createdTenantId: string }) {
|
||||
const updated = await updateRegistrationCapability({ id, expectedToken: capability.expectedToken, patch: data });
|
||||
if (!updated) {
|
||||
throw new Error("Registration update capability was rejected");
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
|
||||
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createApiKeyAuthCache, API_KEY_AUTH_CACHE_TTL_SECONDS } from "~/utils/api/api-key-auth-cache.server";
|
||||
import { createAppConfigurationCache } from "./app-configuration-cache.server";
|
||||
import { createTenantSecurityCache, TENANT_SNAPSHOT_SAFETY_TTL_SECONDS } from "./tenant-cache.server";
|
||||
import { createUserSnapshotCache, USER_SNAPSHOT_CACHE_TTL_SECONDS } from "./user-snapshot-cache.server";
|
||||
import type { UserWithoutPassword } from "./users.db.server";
|
||||
|
||||
const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
function stores(now: () => number = () => Date.now()) {
|
||||
const adapter = new MemoryAdapter({ now });
|
||||
return {
|
||||
first: createSharedStore({ namespace: "security-cache-test", adapter }),
|
||||
second: createSharedStore({ namespace: "security-cache-test", adapter }),
|
||||
};
|
||||
}
|
||||
|
||||
function apiKeySnapshot(): LegacyApiKeySimple {
|
||||
return {
|
||||
id: "api-key-1",
|
||||
alias: "Automation",
|
||||
expires: new Date("2030-01-01T00:00:00.000Z"),
|
||||
tenantId: "tenant-1",
|
||||
createdByUserId: "user-1",
|
||||
active: true,
|
||||
scopes: ["workflow:read"],
|
||||
tenant: { id: "tenant-1", name: "Acme", slug: "acme", deactivatedReason: null },
|
||||
};
|
||||
}
|
||||
|
||||
function userSnapshot(isAdmin = true): UserWithoutPassword {
|
||||
return {
|
||||
id: "user-1",
|
||||
email: "admin@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Admin",
|
||||
avatar: null,
|
||||
phone: null,
|
||||
admin: isAdmin
|
||||
? {
|
||||
userId: "user-1",
|
||||
ssoProvider: "authentik",
|
||||
ssoSubjectId: "subject-1",
|
||||
ssoGroups: ["hivegrid-admin"],
|
||||
lastSsoLoginAt: new Date("2026-07-12T10:00:00.000Z"),
|
||||
}
|
||||
: null,
|
||||
defaultTenantId: "tenant-1",
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
locale: "de",
|
||||
lightOrDarkMode: "light",
|
||||
};
|
||||
}
|
||||
|
||||
describe("cross-replica security snapshot caches", () => {
|
||||
it("never stores a plaintext API key and invalidates a peer replica immediately", async () => {
|
||||
const { first, second } = stores();
|
||||
const firstCache = createApiKeyAuthCache(first);
|
||||
const secondCache = createApiKeyAuthCache(second);
|
||||
const disposeSecond = await secondCache.subscribe();
|
||||
const rawApiKey = "hg_live_this_is_the_plaintext_credential";
|
||||
const lookupKey = `apiKeyHash:${"a".repeat(64)}`;
|
||||
|
||||
await firstCache.set(lookupKey, apiKeySnapshot());
|
||||
expect((await secondCache.get(lookupKey))?.expires).toEqual(new Date("2030-01-01T00:00:00.000Z"));
|
||||
|
||||
const stored = await first.get(`cache:api-key-auth:${lookupKey}`);
|
||||
expect(stored).not.toContain(rawApiKey);
|
||||
expect(stored).not.toContain("hg_live_");
|
||||
|
||||
firstCache.deleteLocal(lookupKey);
|
||||
await firstCache.l2.invalidate(lookupKey);
|
||||
await tick();
|
||||
expect(secondCache.l1.get(lookupKey)).toBeUndefined();
|
||||
expect(await secondCache.get(lookupKey)).toBeNull();
|
||||
|
||||
await disposeSecond();
|
||||
});
|
||||
|
||||
it("expires an API-key L1 snapshot after a missed invalidation", async () => {
|
||||
let now = 1_000;
|
||||
const { first, second } = stores(() => now);
|
||||
const firstCache = createApiKeyAuthCache(first, { now: () => now });
|
||||
const disconnectedReplica = createApiKeyAuthCache(second, { now: () => now });
|
||||
const lookupKey = `apiKeyHash:${"b".repeat(64)}`;
|
||||
|
||||
await firstCache.set(lookupKey, apiKeySnapshot());
|
||||
expect(await disconnectedReplica.get(lookupKey)).not.toBeNull();
|
||||
await firstCache.l2.delete(lookupKey);
|
||||
|
||||
now += API_KEY_AUTH_CACHE_TTL_SECONDS * 1_000 + 1;
|
||||
expect(await disconnectedReplica.get(lookupKey)).toBeNull();
|
||||
});
|
||||
|
||||
it("revokes a cached admin snapshot on a peer and bounds missed events", async () => {
|
||||
let now = 10_000;
|
||||
const { first, second } = stores(() => now);
|
||||
const firstCache = createUserSnapshotCache(first, { now: () => now });
|
||||
const secondCache = createUserSnapshotCache(second, { now: () => now });
|
||||
const disposeSecond = await secondCache.subscribe();
|
||||
|
||||
await firstCache.set("user-1", userSnapshot());
|
||||
expect((await secondCache.get("user-1"))?.admin).not.toBeNull();
|
||||
await firstCache.l2.invalidate("user-1");
|
||||
await tick();
|
||||
expect(secondCache.l1.get("user-1")).toBeUndefined();
|
||||
|
||||
await firstCache.set("user-1", userSnapshot());
|
||||
expect(await secondCache.get("user-1")).not.toBeNull();
|
||||
await disposeSecond();
|
||||
await firstCache.l2.delete("user-1");
|
||||
now += USER_SNAPSHOT_CACHE_TTL_SECONDS * 1_000 + 1;
|
||||
expect(await secondCache.get("user-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("invalidates tenant deactivation snapshots across replicas with a short fallback TTL", async () => {
|
||||
let now = 20_000;
|
||||
const { first, second } = stores(() => now);
|
||||
const firstCache = createTenantSecurityCache(first, { now: () => now });
|
||||
const secondCache = createTenantSecurityCache(second, { now: () => now });
|
||||
const disposeSecond = await secondCache.subscribe();
|
||||
const snapshot = { id: "tenant-1", name: "Acme", slug: "acme", deactivatedReason: null };
|
||||
|
||||
await firstCache.set("tenant-1", snapshot);
|
||||
expect(await secondCache.get("tenant-1")).toEqual(snapshot);
|
||||
await firstCache.l2.invalidate("tenant-1");
|
||||
await tick();
|
||||
expect(secondCache.l1.get("tenant-1")).toBeUndefined();
|
||||
|
||||
await firstCache.set("tenant-1", snapshot);
|
||||
expect(await secondCache.get("tenant-1")).toEqual(snapshot);
|
||||
await disposeSecond();
|
||||
await firstCache.l2.delete("tenant-1");
|
||||
now += TENANT_SNAPSHOT_SAFETY_TTL_SECONDS * 1_000 + 1;
|
||||
expect(await secondCache.get("tenant-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("invalidates auth policy and custom-script configuration across replicas", async () => {
|
||||
const { first, second } = stores();
|
||||
const firstCache = createAppConfigurationCache(first);
|
||||
const secondCache = createAppConfigurationCache(second);
|
||||
const disposeSecond = await secondCache.subscribe();
|
||||
const snapshot = {
|
||||
id: "configuration-1",
|
||||
updatedAt: new Date("2026-07-12T10:00:00.000Z"),
|
||||
authRequireEmailVerification: true,
|
||||
headScripts: null,
|
||||
bodyScripts: null,
|
||||
} as never;
|
||||
|
||||
await firstCache.set("global", snapshot);
|
||||
expect((await secondCache.get("global"))?.updatedAt).toEqual(new Date("2026-07-12T10:00:00.000Z"));
|
||||
await firstCache.l2.invalidate("global");
|
||||
await tick();
|
||||
expect(secondCache.l1.get("global")).toBeUndefined();
|
||||
|
||||
await disposeSecond();
|
||||
});
|
||||
});
|
||||
+216
-6
@@ -3,9 +3,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
type SeedService = typeof import("./SeedService").default;
|
||||
|
||||
const dbMock = {
|
||||
$queryRaw: vi.fn(async () => [{ marked: true }]),
|
||||
user: {
|
||||
findUnique: vi.fn(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}` })),
|
||||
findUnique: vi.fn(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}`, active: true })),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(async ({ where, data }: { where: { id: string }; data: { active: boolean } }) => ({ id: where.id, active: data.active })),
|
||||
},
|
||||
adminUser: {
|
||||
findUnique: vi.fn(async () => ({ userId: "admin-id" })),
|
||||
@@ -95,12 +97,37 @@ const dbMock = {
|
||||
app: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
automationTemplate: {
|
||||
findFirst: vi.fn(async () => null),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
bookingPage: {
|
||||
upsert: vi.fn(async ({ create }: { create: { slug: string; tenantId: string } }) => ({ id: `booking-page-${create.tenantId}-${create.slug}` })),
|
||||
},
|
||||
bookingPageProvider: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
availabilityRule: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
availabilityException: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
appointment: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
calendarEvent: {
|
||||
upsert: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const hashMock = vi.fn(async () => "hashed-password");
|
||||
const genSaltMock = vi.fn(async () => "generated-salt");
|
||||
const seedRolesAndPermissionsMock = vi.fn();
|
||||
const seedStandardEntitlementsMock = vi.fn();
|
||||
const seedStagingDomainDemoMock = vi.fn();
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
const loggerInfo = vi.fn();
|
||||
@@ -123,6 +150,7 @@ vi.mock("@hivegrid/db/seed.server", async () => {
|
||||
vi.mock("~/utils/services/emailService", () => ({ getAvailableTenantInboundAddress: vi.fn(async () => "seed@example.test") }));
|
||||
vi.mock("~/utils/services/rolesAndPermissionsService", () => ({ seedRolesAndPermissions: seedRolesAndPermissionsMock }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
|
||||
vi.mock("./stagingDomainDemoSeed.server", () => ({ seedStagingDomainDemo: seedStagingDomainDemoMock }));
|
||||
|
||||
async function loadSeedService(): Promise<SeedService> {
|
||||
vi.resetModules();
|
||||
@@ -133,11 +161,21 @@ async function loadSeedService(): Promise<SeedService> {
|
||||
describe("SeedService", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.user.findUnique.mockImplementation(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}`, active: true }));
|
||||
dbMock.user.update.mockImplementation(async ({ where, data }: { where: { id: string }; data: { active: boolean } }) => ({ id: where.id, active: data.active }));
|
||||
process.env = { ...originalEnv };
|
||||
delete process.env.SEED_ADMIN_EMAIL;
|
||||
delete process.env.SEED_ADMIN_PASSWORD;
|
||||
delete process.env.SEED_DEMO_DATA;
|
||||
delete process.env.ALLOW_STAGING_DEMO_SEED;
|
||||
delete process.env.SEED_DEMO_PRO_MANAGED;
|
||||
delete process.env.LOCAL_DEV_CREDENTIALS;
|
||||
// These unit cases exercise explicit seed environments. The dedicated
|
||||
// local-credential contract suite covers the fail-closed CI branch.
|
||||
delete process.env.CI;
|
||||
delete process.env.SENTRY_ENVIRONMENT;
|
||||
delete process.env.RLS_RUNTIME_MODE;
|
||||
delete process.env.ADMIN_APP_HOST;
|
||||
process.env.NODE_ENV = "test";
|
||||
});
|
||||
|
||||
@@ -189,6 +227,87 @@ describe("SeedService", () => {
|
||||
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("safe-production-password");
|
||||
});
|
||||
|
||||
it("keeps the existing seed override path when the canonical local launcher flag is absent", async () => {
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-development-password";
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "owner@example.com" } });
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
|
||||
expect(hashMock).toHaveBeenCalledWith("safe-development-password", "generated-salt");
|
||||
expect(dbMock.user.update).not.toHaveBeenCalled();
|
||||
expect(dbMock.$queryRaw).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("restores canonical seed credentials only through the verified local launcher contract", async () => {
|
||||
process.env.NODE_ENV = "development";
|
||||
process.env.LOCAL_DEV_CREDENTIALS = "1";
|
||||
process.env.DATABASE_URL = "postgresql://local:local@127.0.0.1:5432/hivegrid";
|
||||
process.env.ADMIN_APP_HOST = "admin.localhost:3000";
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
|
||||
dbMock.user.findUnique.mockResolvedValueOnce({ id: "local-admin", active: false } as never);
|
||||
dbMock.user.update.mockResolvedValueOnce({ id: "local-admin", active: true } as never);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "owner@example.com" } });
|
||||
expect(hashMock).toHaveBeenCalledWith("password", "generated-salt");
|
||||
expect(dbMock.$queryRaw).toHaveBeenCalledOnce();
|
||||
expect(dbMock.user.update).toHaveBeenCalledWith({
|
||||
where: { id: "local-admin" },
|
||||
data: { passwordHash: "hashed-password", active: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("fails before seed work when the local launcher flag targets a remote database", async () => {
|
||||
process.env.NODE_ENV = "development";
|
||||
process.env.LOCAL_DEV_CREDENTIALS = "1";
|
||||
process.env.DATABASE_URL = "postgresql://app:secret@staging-db:5432/hivegrid";
|
||||
process.env.ADMIN_APP_HOST = "admin.localhost:3000";
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await expect(SeedService.seed()).rejects.toThrow("loopback PostgreSQL");
|
||||
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
|
||||
expect(dbMock.user.create).not.toHaveBeenCalled();
|
||||
expect(hashMock).not.toHaveBeenCalled();
|
||||
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
|
||||
expect(dbMock.$queryRaw).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails before seed work when a loopback database lacks the disposable-local marker", async () => {
|
||||
process.env.NODE_ENV = "development";
|
||||
process.env.LOCAL_DEV_CREDENTIALS = "1";
|
||||
process.env.DATABASE_URL = "postgresql://local:local@127.0.0.1:5432/hivegrid";
|
||||
process.env.ADMIN_APP_HOST = "admin.localhost:3000";
|
||||
dbMock.$queryRaw.mockResolvedValueOnce([{ marked: false }]);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await expect(SeedService.seed()).rejects.toThrow("database marked as disposable local development data");
|
||||
|
||||
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
|
||||
expect(dbMock.user.create).not.toHaveBeenCalled();
|
||||
expect(hashMock).not.toHaveBeenCalled();
|
||||
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates seed-managed users as active", async () => {
|
||||
dbMock.user.findUnique.mockResolvedValueOnce(null as never);
|
||||
dbMock.user.create.mockResolvedValueOnce({ id: "new-admin", active: true } as never);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ active: true }),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects blank admin credential overrides in production before DB writes", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
process.env.SEED_ADMIN_EMAIL = "";
|
||||
@@ -220,7 +339,7 @@ describe("SeedService", () => {
|
||||
|
||||
it("skips local demo users and tenants unless explicitly enabled", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
@@ -237,7 +356,7 @@ describe("SeedService", () => {
|
||||
it("seeds local demo users and tenants only when explicitly enabled outside production", async () => {
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
@@ -268,12 +387,87 @@ describe("SeedService", () => {
|
||||
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.knowledgeBase.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.supportTicket.upsert).toHaveBeenCalledTimes(6);
|
||||
expect(seedStagingDomainDemoMock).toHaveBeenCalledOnce();
|
||||
expect(seedStagingDomainDemoMock).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-demo-business-crm",
|
||||
ownerUserId: "user-john.doe@company.com",
|
||||
});
|
||||
// AK-P16a/b: booking + calendar demo data per demo tenant (2 pages, 2
|
||||
// providers each, Mo-Fr rules x 2 providers, 2 exceptions, 4 appointments,
|
||||
// 3 internal mirrors + 1 external event; the cancelled appointment clears
|
||||
// its mirror instead).
|
||||
expect(dbMock.bookingPage.upsert).toHaveBeenCalledTimes(6);
|
||||
expect(dbMock.bookingPageProvider.upsert).toHaveBeenCalledTimes(12);
|
||||
expect(dbMock.availabilityRule.upsert).toHaveBeenCalledTimes(30);
|
||||
expect(dbMock.availabilityException.upsert).toHaveBeenCalledTimes(6);
|
||||
expect(dbMock.appointment.upsert).toHaveBeenCalledTimes(12);
|
||||
expect(dbMock.calendarEvent.upsert).toHaveBeenCalledTimes(12);
|
||||
expect(dbMock.calendarEvent.deleteMany).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.bookingPage.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { tenantId_slug: { tenantId: "tenant-demo-starter-crm", slug: "beratungstermin" } },
|
||||
create: expect.objectContaining({ isDemoData: true, isPublished: true }),
|
||||
}),
|
||||
);
|
||||
expect(dbMock.appointment.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: "seed-demo-starter-crm-appt-cancelled-consult" },
|
||||
create: expect.objectContaining({ status: "cancelled", isDemoData: true, internalCalendarEventId: null }),
|
||||
}),
|
||||
);
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "seed.createDemoUsers", count: 2 }),
|
||||
"Creating CRM SaaS demo users with tenants",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the managed demo-pro tenant outside the legacy boot demo seed", async () => {
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
process.env.SEED_DEMO_PRO_MANAGED = "true";
|
||||
const SeedService = await loadSeedService();
|
||||
vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-business-crm" } });
|
||||
expect(dbMock.tenant.findUnique).not.toHaveBeenCalledWith(expect.objectContaining({ where: { slug: "demo-pro-crm" } }));
|
||||
expect(dbMock.tenantUser.create).toHaveBeenCalledTimes(6);
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_starter" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).not.toHaveBeenCalledWith({
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_pro" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { billingProviderId: "hivegrid_entitlement_plan_business" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(dbMock.tenantSubscriptionProduct.create).toHaveBeenCalledTimes(2);
|
||||
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(2);
|
||||
expect(dbMock.knowledgeBase.upsert).toHaveBeenCalledTimes(2);
|
||||
expect(dbMock.supportTicket.upsert).toHaveBeenCalledTimes(4);
|
||||
expect(dbMock.bookingPage.upsert).toHaveBeenCalledTimes(4);
|
||||
expect(dbMock.bookingPageProvider.upsert).toHaveBeenCalledTimes(8);
|
||||
expect(dbMock.availabilityRule.upsert).toHaveBeenCalledTimes(20);
|
||||
expect(dbMock.availabilityException.upsert).toHaveBeenCalledTimes(4);
|
||||
expect(dbMock.appointment.upsert).toHaveBeenCalledTimes(8);
|
||||
expect(dbMock.calendarEvent.upsert).toHaveBeenCalledTimes(8);
|
||||
expect(dbMock.calendarEvent.deleteMany).toHaveBeenCalledTimes(2);
|
||||
expect(seedStagingDomainDemoMock).toHaveBeenCalledOnce();
|
||||
expect(seedStagingDomainDemoMock).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-demo-business-crm",
|
||||
ownerUserId: "user-john.doe@company.com",
|
||||
});
|
||||
expect(seedRolesAndPermissionsMock).toHaveBeenCalledWith({
|
||||
adminEmail: "admin@email.com",
|
||||
diagnostics: expect.any(Function),
|
||||
excludedTenantSlugs: ["demo-pro-crm"],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not reassign a demo tenant plan after self-service checkout", async () => {
|
||||
process.env.SEED_DEMO_DATA = "true";
|
||||
dbMock.tenant.findUnique.mockImplementation(async ({ where, include }: { where: { slug: string }; include?: unknown }) => ({
|
||||
@@ -329,14 +523,28 @@ describe("SeedService", () => {
|
||||
process.env.ALLOW_STAGING_DEMO_SEED = "true";
|
||||
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
|
||||
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
const SeedService = await loadSeedService();
|
||||
|
||||
dbMock.user.findUnique
|
||||
.mockResolvedValueOnce({ id: "admin-user", active: true } as never)
|
||||
.mockResolvedValueOnce({ id: "demo-user-1", active: false } as never)
|
||||
.mockResolvedValueOnce({ id: "demo-user-2", active: false } as never);
|
||||
|
||||
await SeedService.seed();
|
||||
|
||||
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
|
||||
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
|
||||
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalled();
|
||||
expect(dbMock.user.update).toHaveBeenCalledTimes(2);
|
||||
expect(dbMock.user.update).toHaveBeenCalledWith({
|
||||
where: { id: "demo-user-1" },
|
||||
data: { active: true },
|
||||
});
|
||||
expect(dbMock.user.update).toHaveBeenCalledWith({
|
||||
where: { id: "demo-user-2" },
|
||||
data: { active: true },
|
||||
});
|
||||
expect(loggerInfo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "db-seed", phase: "start", nodeEnv: "staging-demo" }),
|
||||
"DB seed event",
|
||||
@@ -371,6 +579,8 @@ describe("SeedService", () => {
|
||||
expect(seedStandardEntitlementsMock).toHaveBeenCalledOnce();
|
||||
expect(seedStandardEntitlementsMock).toHaveBeenCalledWith({
|
||||
client: dbMock,
|
||||
includeCustomerPortalCommercialProducts: true,
|
||||
includeEmailMarketingCommercialProducts: true,
|
||||
diagnostics: expect.any(Function),
|
||||
});
|
||||
expect(calls).toEqual(["roles", "entitlements"]);
|
||||
@@ -415,7 +625,7 @@ describe("SeedService", () => {
|
||||
|
||||
it("logs redacted roles and permissions seed diagnostics from the helper", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
seedRolesAndPermissionsMock.mockImplementation(async ({ diagnostics }) => {
|
||||
await diagnostics?.({
|
||||
phase: "success",
|
||||
@@ -453,7 +663,7 @@ describe("SeedService", () => {
|
||||
|
||||
it("logs redacted entitlements seed diagnostics from the helper", async () => {
|
||||
const SeedService = await loadSeedService();
|
||||
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
vi.spyOn(console, "log").mockImplementation(() => undefined);
|
||||
seedStandardEntitlementsMock.mockImplementation(async ({ diagnostics }) => {
|
||||
await diagnostics?.({
|
||||
phase: "failure",
|
||||
|
||||
+347
-11
@@ -12,6 +12,15 @@ import { seedRolesAndPermissions, type RolesAndPermissionsSeedDiagnosticEvent }
|
||||
import { db } from "~/utils/db.server";
|
||||
import { seedShkCustomFieldTemplate } from "~/utils/integrations/crm/customFieldService.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import {
|
||||
assertLocalCredentialsDatabaseMarker,
|
||||
assertLocalCredentialsEnvironment,
|
||||
} from "./localCredentialsEnvironment.server";
|
||||
import { seedStagingDomainDemo } from "./stagingDomainDemoSeed.server";
|
||||
import {
|
||||
automationTemplateCatalog,
|
||||
automationTemplateFlowData,
|
||||
} from "~/services/automation/automation.registry";
|
||||
|
||||
const seedLogger = createScopedLogger("seed");
|
||||
|
||||
@@ -32,6 +41,7 @@ const localDemoSeedUsers = [
|
||||
lastName: "Doe",
|
||||
email: "john.doe@company.com",
|
||||
password: "password",
|
||||
reactivateExisting: true,
|
||||
},
|
||||
{
|
||||
userType: "app" as const,
|
||||
@@ -39,6 +49,7 @@ const localDemoSeedUsers = [
|
||||
lastName: "Davis",
|
||||
email: "luna.davis@company.com",
|
||||
password: "password",
|
||||
reactivateExisting: true,
|
||||
},
|
||||
];
|
||||
const demoCrmTenants = [
|
||||
@@ -46,6 +57,7 @@ const demoCrmTenants = [
|
||||
{ slug: "demo-pro-crm", name: "Demo Pro CRM", planId: entitlementPlanIds.pro },
|
||||
{ slug: "demo-business-crm", name: "Demo Business CRM", planId: entitlementPlanIds.business },
|
||||
] as const;
|
||||
const managedDemoProTenantSlug = "demo-pro-crm";
|
||||
const demoTenantRoleSeeds = [
|
||||
{
|
||||
name: "CRM Manager",
|
||||
@@ -68,7 +80,94 @@ const demoSupportTicketSubjects = {
|
||||
const demoSupportTicketPlanGatesMessage =
|
||||
"Use this ticket to confirm blueprint, plan, tenant override, and tenant-owned role access in the seeded workspace.";
|
||||
|
||||
function getAdminSeedUser() {
|
||||
// AK-P16a/AK-P16b: booking + calendar demo data for the demo tenants so
|
||||
// /bookings, /bookings/pages, /availability and /calendar are populated out of
|
||||
// the box. The rich local demo seed (scripts/seed-hivegrid-demo.ts) refuses to
|
||||
// run with NODE_ENV=production, so the staging demo path lives here.
|
||||
// Deterministic `seed-<tenant>-*` ids keep every upsert idempotent across
|
||||
// SEED_ON_BOOT runs; day offsets are re-resolved on each run so "upcoming"
|
||||
// appointments stay upcoming.
|
||||
const demoBookingTimezone = "Europe/Berlin";
|
||||
const demoBookingPageSeeds = [
|
||||
{
|
||||
slug: "beratungstermin",
|
||||
title: "Beratungstermin", // demo seed copy
|
||||
description: "Kostenloses Erstgespräch für neue Anfragen (Demo).",
|
||||
durationMinutes: 30,
|
||||
isPublished: true,
|
||||
},
|
||||
{
|
||||
slug: "vor-ort-termin",
|
||||
title: "Vor-Ort-Termin", // demo seed copy
|
||||
description: "Termin beim Endkunden vor Ort (Demo, unveröffentlicht).",
|
||||
durationMinutes: 60,
|
||||
isPublished: false,
|
||||
},
|
||||
] as const;
|
||||
const demoAppointmentSeeds = [
|
||||
{
|
||||
key: "upcoming-consult",
|
||||
pageSlug: "beratungstermin",
|
||||
providerIndex: 0,
|
||||
dayOffset: 2,
|
||||
startHour: 10,
|
||||
status: "scheduled",
|
||||
intakeAnswers: { vorname: "Sabine", nachname: "Wagner", email: "sabine.wagner@example.test", anliegen: "Bad-Sanierung besprechen." },
|
||||
},
|
||||
{
|
||||
key: "upcoming-onsite",
|
||||
pageSlug: "vor-ort-termin",
|
||||
providerIndex: 1,
|
||||
dayOffset: 5,
|
||||
startHour: 8,
|
||||
status: "scheduled",
|
||||
intakeAnswers: { vorname: "Thomas", nachname: "Schneider", email: "thomas.schneider@example.test", anliegen: "Heizungstausch vor Ort ansehen." },
|
||||
},
|
||||
{
|
||||
key: "past-held",
|
||||
pageSlug: "beratungstermin",
|
||||
providerIndex: 0,
|
||||
dayOffset: -3,
|
||||
startHour: 14,
|
||||
status: "held",
|
||||
intakeAnswers: { vorname: "Birgit", nachname: "Sommer", email: "birgit.sommer@example.test", anliegen: "Jahreswartung planen." },
|
||||
},
|
||||
{
|
||||
key: "cancelled-consult",
|
||||
pageSlug: "beratungstermin",
|
||||
providerIndex: 1,
|
||||
dayOffset: -1,
|
||||
startHour: 9,
|
||||
status: "cancelled",
|
||||
intakeAnswers: { vorname: "Peter", nachname: "Krause", email: "peter.krause@example.test", anliegen: "Terminanfrage (storniert)." },
|
||||
},
|
||||
] as const;
|
||||
const demoAvailabilityWeekdays = ["monday", "tuesday", "wednesday", "thursday", "friday"] as const;
|
||||
const demoAvailabilityExceptionSeeds = [
|
||||
{ key: "day-off", providerIndex: 0, dayOffset: 7, kind: "unavailable", startTime: null, endTime: null, reason: "Urlaubstag (Demo)" },
|
||||
{ key: "short-day", providerIndex: 1, dayOffset: 3, kind: "custom_window", startTime: "10:00", endTime: "14:00", reason: "Verkürzter Tag (Demo)" },
|
||||
] as const;
|
||||
|
||||
async function useCanonicalLocalCredentials() {
|
||||
if (process.env.LOCAL_DEV_CREDENTIALS !== "1") {
|
||||
return false;
|
||||
}
|
||||
|
||||
assertLocalCredentialsEnvironment(process.env);
|
||||
await assertLocalCredentialsDatabaseMarker(db);
|
||||
return true;
|
||||
}
|
||||
|
||||
function getAdminSeedUser(canonicalLocalCredentials: boolean) {
|
||||
if (canonicalLocalCredentials) {
|
||||
return {
|
||||
email: DEFAULT_ADMIN_EMAIL,
|
||||
password: DEFAULT_ADMIN_PASSWORD,
|
||||
firstName: "Admin",
|
||||
lastName: "User",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
email: process.env.SEED_ADMIN_EMAIL ?? DEFAULT_ADMIN_EMAIL,
|
||||
password: process.env.SEED_ADMIN_PASSWORD ?? DEFAULT_ADMIN_PASSWORD,
|
||||
@@ -78,8 +177,10 @@ function getAdminSeedUser() {
|
||||
}
|
||||
|
||||
async function seed() {
|
||||
const adminUser = getAdminSeedUser();
|
||||
const canonicalLocalCredentials = await useCanonicalLocalCredentials();
|
||||
const adminUser = getAdminSeedUser(canonicalLocalCredentials);
|
||||
const shouldSeedDemoData = shouldSeedCrmDemoData();
|
||||
const bootSeedDemoCrmTenants = getBootSeedDemoCrmTenants();
|
||||
const seedCredentials = shouldSeedDemoData
|
||||
? [
|
||||
{ label: "admin", email: adminUser.email, password: adminUser.password },
|
||||
@@ -94,16 +195,16 @@ async function seed() {
|
||||
seedCredentials,
|
||||
diagnostics: logDbSeedDiagnostic,
|
||||
seed: async () => {
|
||||
const admin = await createUser({ userType: "admin", ...adminUser });
|
||||
const admin = await createUser({ userType: "admin", canonicalLocalCredentials, ...adminUser });
|
||||
let demoUsers: Awaited<ReturnType<typeof createUser>>[] = [];
|
||||
|
||||
if (shouldSeedDemoData) {
|
||||
seedLogger.info({ op: "seed.createDemoUsers", count: localDemoSeedUsers.length }, "Creating CRM SaaS demo users with tenants");
|
||||
demoUsers = await Promise.all(localDemoSeedUsers.map((user) => createUser(user)));
|
||||
demoUsers = await Promise.all(localDemoSeedUsers.map((user) => createUser({ ...user, canonicalLocalCredentials })));
|
||||
const [user1, user2] = demoUsers;
|
||||
|
||||
await Promise.all(
|
||||
demoCrmTenants.map((tenant, index) =>
|
||||
bootSeedDemoCrmTenants.map((tenant, index) =>
|
||||
createTenant(tenant.slug, tenant.name, [
|
||||
{ ...admin, type: TenantUserType.ADMIN },
|
||||
{ ...user1, type: index === 0 ? TenantUserType.ADMIN : TenantUserType.OWNER },
|
||||
@@ -117,25 +218,40 @@ async function seed() {
|
||||
await seedRolesAndPermissions({
|
||||
adminEmail: adminUser.email,
|
||||
diagnostics: logRolesAndPermissionsSeedDiagnostic,
|
||||
...(process.env.SEED_DEMO_PRO_MANAGED === "true" ? { excludedTenantSlugs: [managedDemoProTenantSlug] } : {}),
|
||||
});
|
||||
|
||||
await seedStandardEntitlements({
|
||||
client: db,
|
||||
includeCustomerPortalCommercialProducts: true,
|
||||
includeEmailMarketingCommercialProducts: true,
|
||||
diagnostics: logEntitlementsSeedDiagnostic,
|
||||
});
|
||||
|
||||
// R-P5: global App definition table from the code catalog (idempotent by
|
||||
// unique key; the tenant runtime keeps reading INTEGRATION_CATALOG).
|
||||
await seedIntegrationCatalog();
|
||||
await seedAutomationTemplateCatalog();
|
||||
|
||||
if (shouldSeedDemoData) {
|
||||
await Promise.all(demoCrmTenants.map((tenant) => assignTenantPlan(tenant.slug, tenant.planId)));
|
||||
await Promise.all(demoCrmTenants.map((tenant) => seedDemoProductCoreTenant(tenant.slug, tenant.planId, demoUsers)));
|
||||
await Promise.all(bootSeedDemoCrmTenants.map((tenant) => assignTenantPlan(tenant.slug, tenant.planId)));
|
||||
await Promise.all(bootSeedDemoCrmTenants.map((tenant) => seedDemoProductCoreTenant(tenant.slug, tenant.planId, demoUsers)));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function getBootSeedDemoCrmTenants() {
|
||||
if (process.env.SEED_DEMO_PRO_MANAGED !== "true") {
|
||||
return demoCrmTenants;
|
||||
}
|
||||
|
||||
// The comprehensive staging seed owns every tenant-scoped row in demo-pro-crm.
|
||||
// Excluding it here keeps later web boots from reintroducing legacy members,
|
||||
// plans, bookings, projects, or other product-core fixtures.
|
||||
return demoCrmTenants.filter((tenant) => tenant.slug !== managedDemoProTenantSlug);
|
||||
}
|
||||
|
||||
/** Upsert the code catalog into the global `App` table (R-P5, no RLS/tenant). */
|
||||
async function seedIntegrationCatalog() {
|
||||
const plan = buildCatalogSeedPlan();
|
||||
@@ -148,6 +264,38 @@ async function seedIntegrationCatalog() {
|
||||
seedLogger.info({ op: "seed.integrationCatalog", count: plan.length }, "Upserted integration catalog into App table");
|
||||
}
|
||||
|
||||
/** Seed global templates through the privileged deployment seed, never a tenant request. */
|
||||
async function seedAutomationTemplateCatalog() {
|
||||
for (const template of automationTemplateCatalog) {
|
||||
const flowData = JSON.parse(JSON.stringify(automationTemplateFlowData(template))) as object;
|
||||
// Matching the old key-shaped name too heals rows that were seeded before
|
||||
// display text replaced the translation key.
|
||||
const existing = await db.automationTemplate.findFirst({
|
||||
where: { tenantId: null, name: { in: [template.defaultName, template.nameKey] }, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
const data = {
|
||||
name: template.defaultName,
|
||||
description: template.defaultDescription,
|
||||
category: template.category,
|
||||
flowData,
|
||||
isPublished: true,
|
||||
isDemoData: true,
|
||||
};
|
||||
if (existing) {
|
||||
await db.automationTemplate.update({ where: { id: existing.id }, data });
|
||||
} else {
|
||||
await db.automationTemplate.create({
|
||||
data: { tenantId: null, ...data },
|
||||
});
|
||||
}
|
||||
}
|
||||
seedLogger.info(
|
||||
{ op: "seed.automationTemplateCatalog", count: automationTemplateCatalog.length },
|
||||
"Upserted global automation template catalog",
|
||||
);
|
||||
}
|
||||
|
||||
function shouldSeedCrmDemoData() {
|
||||
if (process.env.SEED_DEMO_DATA !== "true") {
|
||||
return false;
|
||||
@@ -229,12 +377,16 @@ async function createUser({
|
||||
email,
|
||||
password,
|
||||
userType,
|
||||
reactivateExisting = false,
|
||||
canonicalLocalCredentials = false,
|
||||
}: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
userType: "admin" | "app";
|
||||
reactivateExisting?: boolean;
|
||||
canonicalLocalCredentials?: boolean;
|
||||
}) {
|
||||
// Never log raw `email` (PII) and never log `password` (secret).
|
||||
// Use email fingerprint hash so operators can still correlate seed events.
|
||||
@@ -248,7 +400,24 @@ async function createUser({
|
||||
where: { email },
|
||||
});
|
||||
if (user) {
|
||||
const isAdmin = await db.adminUser.findUnique({ where: { userId: user.id } });
|
||||
if (canonicalLocalCredentials) {
|
||||
user = await db.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
passwordHash,
|
||||
...(userType === "admin" || reactivateExisting ? { active: true } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
// Only explicitly managed demo identities opt into reactivation. Existing
|
||||
// admin or customer accounts may have been disabled intentionally.
|
||||
if (!canonicalLocalCredentials && reactivateExisting && user.active === false) {
|
||||
user = await db.user.update({
|
||||
where: { id: user.id },
|
||||
data: { active: true },
|
||||
});
|
||||
}
|
||||
const isAdmin = await db.adminUser.findUnique({ where: { id: user.id } });
|
||||
if (!isAdmin && userType === "admin") {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
throw new Error("Production seed refused to promote an existing non-admin user. Choose a new SEED_ADMIN_EMAIL or bootstrap the admin user explicitly.");
|
||||
@@ -257,7 +426,15 @@ async function createUser({
|
||||
{ op: "seed.promoteUserToAdmin", emailFingerprint: emailFingerprint(email) },
|
||||
"User already exists; promoting to admin",
|
||||
);
|
||||
await db.adminUser.create({ data: { userId: user.id } });
|
||||
await db.adminUser.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
status: "active",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
seedLogger.info(
|
||||
{ op: "seed.userExists", userType, emailFingerprint: emailFingerprint(email) },
|
||||
@@ -274,11 +451,18 @@ async function createUser({
|
||||
firstName,
|
||||
lastName,
|
||||
phone: "",
|
||||
active: true,
|
||||
},
|
||||
});
|
||||
if (userType === "admin") {
|
||||
await db.adminUser.create({
|
||||
data: { userId: user.id },
|
||||
data: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
status: "active",
|
||||
},
|
||||
});
|
||||
}
|
||||
return user;
|
||||
@@ -426,10 +610,162 @@ async function seedDemoProductCoreTenant(tenantSlug: string, planId: Entitlement
|
||||
// data (`isDemoData = true`) instead of the legacy entity-builder CRM
|
||||
// entities. The template is intentionally empty until the Geerkens
|
||||
// workshop (E3), so this is currently an idempotent no-op.
|
||||
seedShkCustomFieldTemplate({ tenantId: tenant.id }),
|
||||
seedShkCustomFieldTemplate({ tenantId: tenant.id, isDemoData: true }),
|
||||
planId === entitlementPlanIds.business && demoUsers[0]
|
||||
? seedStagingDomainDemo({ tenantId: tenant.id, ownerUserId: demoUsers[0].id })
|
||||
: Promise.resolve(),
|
||||
seedDemoTenantBookingData(tenant.id, tenant.slug, demoUsers),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Local wall-clock date `dayOffset` days from now (mirrors the local demo seed). */
|
||||
function demoBookingDate(dayOffset: number, hour: number, minute = 0): Date {
|
||||
const value = new Date();
|
||||
value.setDate(value.getDate() + dayOffset);
|
||||
value.setHours(hour, minute, 0, 0);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Calendar-date-only value at UTC midnight (AvailabilityException stores `@db.Date`). */
|
||||
function demoBookingDateOnlyUtc(dayOffset: number): Date {
|
||||
const value = new Date();
|
||||
value.setDate(value.getDate() + dayOffset);
|
||||
return new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()));
|
||||
}
|
||||
|
||||
async function seedDemoTenantBookingData(tenantId: string, tenantSlug: string, demoUsers: { id: string }[]) {
|
||||
const providers = demoUsers.slice(0, 2);
|
||||
if (providers.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Booking pages + provider assignments (unique per tenantId+slug).
|
||||
const pageBySlug = new Map<string, { id: string; durationMinutes: number }>();
|
||||
for (const page of demoBookingPageSeeds) {
|
||||
const data = {
|
||||
title: page.title,
|
||||
description: page.description,
|
||||
durationMinutes: page.durationMinutes,
|
||||
confirmationEmailSubject: `Terminbestätigung: ${page.title}`,
|
||||
confirmationEmailBody: "Vielen Dank für deine Buchung. Die Termindetails findest du im Kalenderanhang (.ics).",
|
||||
isPublished: page.isPublished,
|
||||
isDemoData: true,
|
||||
createdByUserId: providers[0].id,
|
||||
};
|
||||
const row = await db.bookingPage.upsert({
|
||||
where: { tenantId_slug: { tenantId, slug: page.slug } },
|
||||
create: { tenantId, slug: page.slug, ...data },
|
||||
update: data,
|
||||
select: { id: true },
|
||||
});
|
||||
pageBySlug.set(page.slug, { id: row.id, durationMinutes: page.durationMinutes });
|
||||
|
||||
for (const [index, provider] of providers.entries()) {
|
||||
await db.bookingPageProvider.upsert({
|
||||
where: { bookingPageId_providerUserId: { bookingPageId: row.id, providerUserId: provider.id } },
|
||||
create: { tenantId, bookingPageId: row.id, providerUserId: provider.id, displayOrder: index, isActive: true },
|
||||
update: { displayOrder: index, isActive: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Weekly Mo–Fr availability per provider so the public slot engine and the
|
||||
// /availability editor have data. AvailabilityRule has no natural unique key,
|
||||
// so deterministic ids keep the upserts idempotent.
|
||||
for (const [providerIndex, provider] of providers.entries()) {
|
||||
for (const day of demoAvailabilityWeekdays) {
|
||||
const id = `seed-${tenantSlug}-avail-${providerIndex}-${day}`;
|
||||
const data = { tenantId, providerUserId: provider.id, dayOfWeek: day, startTime: "09:00", endTime: "17:00", timezone: demoBookingTimezone };
|
||||
await db.availabilityRule.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
}
|
||||
}
|
||||
|
||||
for (const exception of demoAvailabilityExceptionSeeds) {
|
||||
const provider = providers[exception.providerIndex % providers.length];
|
||||
const id = `seed-${tenantSlug}-exception-${exception.key}`;
|
||||
const data = {
|
||||
tenantId,
|
||||
providerUserId: provider.id,
|
||||
date: demoBookingDateOnlyUtc(exception.dayOffset),
|
||||
kind: exception.kind,
|
||||
startTime: exception.startTime,
|
||||
endTime: exception.endTime,
|
||||
reason: exception.reason,
|
||||
timezone: demoBookingTimezone,
|
||||
};
|
||||
await db.availabilityException.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
}
|
||||
|
||||
// Appointments across the list tabs (upcoming/past/cancelled) + a local
|
||||
// CalendarEvent mirror per active appointment so /calendar shows sources
|
||||
// (mirrors what BookingSubmitService does on a real booking).
|
||||
for (const appointment of demoAppointmentSeeds) {
|
||||
const page = pageBySlug.get(appointment.pageSlug);
|
||||
const provider = providers[appointment.providerIndex % providers.length];
|
||||
if (!page) {
|
||||
continue;
|
||||
}
|
||||
const appointmentId = `seed-${tenantSlug}-appt-${appointment.key}`;
|
||||
const calendarEventId = `seed-${tenantSlug}-cal-${appointment.key}`;
|
||||
const startAt = demoBookingDate(appointment.dayOffset, appointment.startHour);
|
||||
const endAt = new Date(startAt.getTime() + page.durationMinutes * 60_000);
|
||||
const cancelled = appointment.status === "cancelled";
|
||||
|
||||
if (cancelled) {
|
||||
// Real cancels remove the availability-blocking mirror — keep parity.
|
||||
await db.calendarEvent.deleteMany({ where: { id: calendarEventId } });
|
||||
} else {
|
||||
const eventData = {
|
||||
tenantId,
|
||||
userId: provider.id,
|
||||
source: "hivegrid_internal" as const,
|
||||
title: `${demoBookingPageSeeds.find((p) => p.slug === appointment.pageSlug)?.title ?? "Buchung"} (Demo)`,
|
||||
startsAt: startAt,
|
||||
endsAt: endAt,
|
||||
timeZone: demoBookingTimezone,
|
||||
isBusyForAvailability: true,
|
||||
internalEntityLink: { type: "appointment", id: appointmentId },
|
||||
isDemoData: true,
|
||||
};
|
||||
await db.calendarEvent.upsert({ where: { id: calendarEventId }, create: { id: calendarEventId, ...eventData }, update: eventData });
|
||||
}
|
||||
|
||||
const data = {
|
||||
tenantId,
|
||||
bookingPageId: page.id,
|
||||
providerUserId: provider.id,
|
||||
startAt,
|
||||
endAt,
|
||||
timezone: demoBookingTimezone,
|
||||
status: appointment.status,
|
||||
intakeAnswers: { ...appointment.intakeAnswers },
|
||||
internalCalendarEventId: cancelled ? null : calendarEventId,
|
||||
cancelledAt: cancelled ? demoBookingDate(appointment.dayOffset - 1, 12) : null,
|
||||
cancelledByKind: cancelled ? ("customer" as const) : null,
|
||||
cancellationReason: cancelled ? "Vom Endkunden storniert (Demo)." : null,
|
||||
isDemoData: true,
|
||||
};
|
||||
await db.appointment.upsert({ where: { id: appointmentId }, create: { id: appointmentId, ...data }, update: data });
|
||||
}
|
||||
|
||||
// One external busy block per tenant so the calendar grid shows both source
|
||||
// markers (internal + external) without a live Google connection.
|
||||
const externalEventId = `seed-${tenantSlug}-cal-external`;
|
||||
const externalStartsAt = demoBookingDate(1, 12);
|
||||
const externalData = {
|
||||
tenantId,
|
||||
userId: providers[0].id,
|
||||
source: "external_synced" as const,
|
||||
title: "Externer Termin (Demo)",
|
||||
startsAt: externalStartsAt,
|
||||
endsAt: new Date(externalStartsAt.getTime() + 90 * 60_000),
|
||||
timeZone: demoBookingTimezone,
|
||||
isBusyForAvailability: true,
|
||||
isDemoData: true,
|
||||
};
|
||||
await db.calendarEvent.upsert({ where: { id: externalEventId }, create: { id: externalEventId, ...externalData }, update: externalData });
|
||||
}
|
||||
|
||||
async function seedDemoTenantProductConfiguration(tenantId: string, planId: EntitlementPlanId) {
|
||||
await db.tenantProductConfiguration.upsert({
|
||||
where: { tenantId },
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { LOCAL_ADMIN_EMAIL, LOCAL_ADMIN_PASSWORD, ensureLocalCredentials, type LocalCredentialsClient } from "./localCredentials.server";
|
||||
import { assertLocalCredentialsEnvironment } from "./localCredentialsEnvironment.server";
|
||||
|
||||
const localEnv = {
|
||||
LOCAL_DEV_CREDENTIALS: "1",
|
||||
NODE_ENV: "development",
|
||||
DATABASE_URL: "postgresql://local:local@127.0.0.1:55432/hivegrid_local",
|
||||
ADMIN_APP_HOST: "admin.localhost:3000",
|
||||
};
|
||||
|
||||
describe("assertLocalCredentialsEnvironment", () => {
|
||||
it("accepts only the canonical local launcher with a loopback PostgreSQL database", () => {
|
||||
expect(assertLocalCredentialsEnvironment(localEnv).hostname).toBe("127.0.0.1");
|
||||
expect(assertLocalCredentialsEnvironment({ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid" }).hostname).toBe("localhost");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ ...localEnv, LOCAL_DEV_CREDENTIALS: undefined }, "canonical local launcher"],
|
||||
[{ ...localEnv, NODE_ENV: "production" }, "NODE_ENV=development"],
|
||||
[{ ...localEnv, CI: "true" }, "disabled in CI"],
|
||||
[{ ...localEnv, SENTRY_ENVIRONMENT: "staging" }, "deployed Sentry environments"],
|
||||
[{ ...localEnv, SENTRY_ENVIRONMENT: "canary" }, "deployed Sentry environments"],
|
||||
[{ ...localEnv, SENTRY_ENVIRONMENT: "preview" }, "deployed Sentry environments"],
|
||||
[{ ...localEnv, SENTRY_ENVIRONMENT: "prod" }, "deployed Sentry environments"],
|
||||
[{ ...localEnv, RLS_RUNTIME_MODE: "required" }, "RLS runtime mode"],
|
||||
[{ ...localEnv, ADMIN_APP_HOST: undefined }, "admin.localhost"],
|
||||
[{ ...localEnv, ADMIN_APP_HOST: "admin.hivegrid.de" }, "admin.localhost"],
|
||||
[{ ...localEnv, ADMIN_APP_HOST: "admin.localhost.evil" }, "admin.localhost"],
|
||||
[{ ...localEnv, DATABASE_URL: "postgresql://app:secret@staging-db:5432/hivegrid" }, "loopback PostgreSQL"],
|
||||
[{ ...localEnv, DATABASE_URL: "not-a-url" }, "valid DATABASE_URL"],
|
||||
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?host=remote-db" }, "connection query parameters"],
|
||||
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?HOSTADDR=203.0.113.10" }, "connection query parameters"],
|
||||
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?host=%2Fvar%2Frun%2Fpostgresql" }, "connection query parameters"],
|
||||
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?SeRvIcE=production" }, "connection query parameters"],
|
||||
])("rejects unsafe environment %#", (env, message) => {
|
||||
expect(() => assertLocalCredentialsEnvironment(env)).toThrow(message);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ensureLocalCredentials", () => {
|
||||
it("upserts the canonical platform admin and normalizes every password-backed local identity", async () => {
|
||||
const transaction = {
|
||||
user: {
|
||||
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 51 }),
|
||||
},
|
||||
portalUser: {
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 3 }),
|
||||
},
|
||||
adminUser: {
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 2 }),
|
||||
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
|
||||
},
|
||||
adminRole: {
|
||||
findUnique: vi.fn().mockResolvedValue({ id: "super-admin-role" }),
|
||||
},
|
||||
adminUserRole: {
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 2 }),
|
||||
create: vi.fn().mockResolvedValue({ id: "admin-user-role" }),
|
||||
},
|
||||
};
|
||||
const client = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ marked: true }]),
|
||||
$transaction: vi.fn(async (callback) => callback(transaction as never)),
|
||||
} as unknown as LocalCredentialsClient;
|
||||
const hashPassword = vi.fn().mockResolvedValue("argon2-hash");
|
||||
const syncPermissions = vi.fn().mockResolvedValue(undefined);
|
||||
const syncAdminPermissions = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
await expect(ensureLocalCredentials({ client, env: localEnv, hashPassword, syncPermissions, syncAdminPermissions })).resolves.toEqual({
|
||||
adminUserId: "admin-user",
|
||||
normalizedPasswordIdentityCount: 54,
|
||||
});
|
||||
|
||||
expect(client.$queryRaw).toHaveBeenCalledOnce();
|
||||
expect(hashPassword).toHaveBeenCalledWith(LOCAL_ADMIN_PASSWORD);
|
||||
expect(syncPermissions).toHaveBeenCalledOnce();
|
||||
expect(syncAdminPermissions).toHaveBeenCalledOnce();
|
||||
expect(transaction.user.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { email: LOCAL_ADMIN_EMAIL },
|
||||
create: expect.objectContaining({ email: LOCAL_ADMIN_EMAIL, passwordHash: "argon2-hash", active: true }),
|
||||
update: expect.objectContaining({ passwordHash: "argon2-hash", active: true, totpEnabledAt: null }),
|
||||
})
|
||||
);
|
||||
expect(transaction.adminUser.updateMany).toHaveBeenCalledWith({
|
||||
where: { email: { not: LOCAL_ADMIN_EMAIL }, status: "active" },
|
||||
data: expect.objectContaining({ status: "disabled" }),
|
||||
});
|
||||
expect(transaction.adminUser.upsert).toHaveBeenCalledWith({
|
||||
where: { email: LOCAL_ADMIN_EMAIL },
|
||||
create: expect.objectContaining({ id: "admin-user", email: LOCAL_ADMIN_EMAIL, status: "active" }),
|
||||
update: expect.objectContaining({ status: "active", disabledAt: null, disabledReason: null }),
|
||||
select: { id: true },
|
||||
});
|
||||
expect(transaction.adminRole.findUnique).toHaveBeenCalledWith({
|
||||
where: { systemKey: "super_admin" },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(transaction.adminUserRole.deleteMany).toHaveBeenCalledWith({
|
||||
where: { adminUserId: "admin-user" },
|
||||
});
|
||||
expect(transaction.adminUserRole.create).toHaveBeenCalledWith({
|
||||
data: { adminUserId: "admin-user", adminRoleId: "super-admin-role", grantedByAdminUserId: "admin-user" },
|
||||
});
|
||||
expect(transaction.user.updateMany).toHaveBeenCalledWith({
|
||||
where: { passwordHash: { not: null } },
|
||||
data: { passwordHash: "argon2-hash" },
|
||||
});
|
||||
expect(transaction.portalUser.updateMany).toHaveBeenCalledWith({
|
||||
where: { passwordHash: { not: null } },
|
||||
data: { passwordHash: "argon2-hash" },
|
||||
});
|
||||
});
|
||||
|
||||
it("fails before hashing or opening a transaction outside the local contract", async () => {
|
||||
const client = { $queryRaw: vi.fn(), $transaction: vi.fn() } as unknown as LocalCredentialsClient;
|
||||
const hashPassword = vi.fn();
|
||||
const syncPermissions = vi.fn();
|
||||
|
||||
await expect(
|
||||
ensureLocalCredentials({
|
||||
client,
|
||||
env: { ...localEnv, DATABASE_URL: "postgresql://app:secret@staging-db:5432/hivegrid" },
|
||||
hashPassword,
|
||||
syncPermissions,
|
||||
})
|
||||
).rejects.toThrow("loopback PostgreSQL");
|
||||
expect(hashPassword).not.toHaveBeenCalled();
|
||||
expect(syncPermissions).not.toHaveBeenCalled();
|
||||
expect(client.$queryRaw).not.toHaveBeenCalled();
|
||||
expect(client.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails before hashing, permission sync, or writes when the database lacks the disposable-local marker", async () => {
|
||||
const client = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ marked: false }]),
|
||||
$transaction: vi.fn(),
|
||||
} as unknown as LocalCredentialsClient;
|
||||
const hashPassword = vi.fn();
|
||||
const syncPermissions = vi.fn();
|
||||
|
||||
await expect(ensureLocalCredentials({ client, env: localEnv, hashPassword, syncPermissions })).rejects.toThrow(
|
||||
"database marked as disposable local development data"
|
||||
);
|
||||
expect(hashPassword).not.toHaveBeenCalled();
|
||||
expect(syncPermissions).not.toHaveBeenCalled();
|
||||
expect(client.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the canonical admin role is unavailable after permission sync", async () => {
|
||||
const transaction = {
|
||||
user: {
|
||||
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
portalUser: { updateMany: vi.fn() },
|
||||
adminUser: { updateMany: vi.fn(), upsert: vi.fn().mockResolvedValue({ id: "admin-user" }) },
|
||||
adminRole: { findUnique: vi.fn().mockResolvedValue(null) },
|
||||
adminUserRole: { deleteMany: vi.fn(), create: vi.fn() },
|
||||
};
|
||||
const client = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ marked: true }]),
|
||||
$transaction: vi.fn(async (callback) => callback(transaction as never)),
|
||||
} as unknown as LocalCredentialsClient;
|
||||
|
||||
await expect(
|
||||
ensureLocalCredentials({
|
||||
client,
|
||||
env: localEnv,
|
||||
hashPassword: vi.fn().mockResolvedValue("argon2-hash"),
|
||||
syncPermissions: vi.fn().mockResolvedValue(undefined),
|
||||
syncAdminPermissions: vi.fn().mockResolvedValue(undefined),
|
||||
})
|
||||
).rejects.toThrow("canonical SuperAdmin role");
|
||||
expect(transaction.adminUserRole.deleteMany).not.toHaveBeenCalled();
|
||||
expect(transaction.adminUserRole.create).not.toHaveBeenCalled();
|
||||
expect(transaction.user.updateMany).not.toHaveBeenCalled();
|
||||
expect(transaction.portalUser.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps exactly one canonical SuperAdmin assignment across repeated local starts", async () => {
|
||||
const transaction = {
|
||||
user: {
|
||||
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
|
||||
},
|
||||
portalUser: { updateMany: vi.fn().mockResolvedValue({ count: 0 }) },
|
||||
adminUser: {
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
|
||||
},
|
||||
adminRole: { findUnique: vi.fn().mockResolvedValue({ id: "super-admin-role" }) },
|
||||
adminUserRole: {
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
|
||||
create: vi.fn().mockResolvedValue({ id: "admin-user-role" }),
|
||||
},
|
||||
};
|
||||
const client = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ marked: true }]),
|
||||
$transaction: vi.fn(async (callback) => callback(transaction as never)),
|
||||
} as unknown as LocalCredentialsClient;
|
||||
const options = {
|
||||
client,
|
||||
env: localEnv,
|
||||
hashPassword: vi.fn().mockResolvedValue("argon2-hash"),
|
||||
syncPermissions: vi.fn().mockResolvedValue(undefined),
|
||||
syncAdminPermissions: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
await ensureLocalCredentials(options);
|
||||
await ensureLocalCredentials(options);
|
||||
|
||||
expect(transaction.adminUserRole.deleteMany).toHaveBeenCalledTimes(2);
|
||||
expect(transaction.adminUserRole.create).toHaveBeenCalledTimes(2);
|
||||
expect(transaction.adminUserRole.create).toHaveBeenLastCalledWith({
|
||||
data: { adminUserId: "admin-user", adminRoleId: "super-admin-role", grantedByAdminUserId: "admin-user" },
|
||||
});
|
||||
});
|
||||
});
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import { syncDefaultRolesAndPermissions } from "@hivegrid/db/permissions-seed.server";
|
||||
import { syncAdminRoleCatalog } from "@hivegrid/db/admin-rbac.server";
|
||||
import argon2 from "argon2";
|
||||
import {
|
||||
assertLocalCredentialsDatabaseMarker,
|
||||
assertLocalCredentialsEnvironment,
|
||||
type LocalCredentialsEnvironment,
|
||||
} from "./localCredentialsEnvironment.server";
|
||||
|
||||
export const LOCAL_ADMIN_EMAIL = "admin@email.com";
|
||||
export const LOCAL_ADMIN_PASSWORD = "password";
|
||||
|
||||
export type LocalCredentialsClient = Pick<DbClient, "$queryRaw" | "$transaction">;
|
||||
|
||||
export type LocalCredentialsResult = {
|
||||
adminUserId: string;
|
||||
normalizedPasswordIdentityCount: number;
|
||||
};
|
||||
|
||||
export async function ensureLocalCredentials({
|
||||
client,
|
||||
env = process.env,
|
||||
hashPassword = hashLocalPassword,
|
||||
syncPermissions = async () => {
|
||||
await syncDefaultRolesAndPermissions({ client: client as DbClient });
|
||||
},
|
||||
syncAdminPermissions = async () => {
|
||||
await syncAdminRoleCatalog(client as DbClient);
|
||||
},
|
||||
}: {
|
||||
client: LocalCredentialsClient;
|
||||
env?: LocalCredentialsEnvironment;
|
||||
hashPassword?: (password: string) => Promise<string>;
|
||||
syncPermissions?: () => Promise<void>;
|
||||
syncAdminPermissions?: () => Promise<void>;
|
||||
}): Promise<LocalCredentialsResult> {
|
||||
assertLocalCredentialsEnvironment(env);
|
||||
await assertLocalCredentialsDatabaseMarker(client);
|
||||
const passwordHash = await hashPassword(LOCAL_ADMIN_PASSWORD);
|
||||
await syncPermissions();
|
||||
await syncAdminPermissions();
|
||||
|
||||
return client.$transaction(async (transaction) => {
|
||||
const admin = await transaction.user.upsert({
|
||||
where: { email: LOCAL_ADMIN_EMAIL },
|
||||
create: {
|
||||
email: LOCAL_ADMIN_EMAIL,
|
||||
passwordHash,
|
||||
firstName: "Admin",
|
||||
lastName: "User",
|
||||
avatar: "",
|
||||
phone: "",
|
||||
active: true,
|
||||
},
|
||||
update: {
|
||||
passwordHash,
|
||||
active: true,
|
||||
pendingDeletion: false,
|
||||
scheduledDeletionAt: null,
|
||||
deletionRequestedAt: null,
|
||||
pseudonymized: false,
|
||||
pseudonymizedAt: null,
|
||||
deletionRequestId: null,
|
||||
totpSecretEncrypted: null,
|
||||
totpPendingSecretEncrypted: null,
|
||||
totpEnabledAt: null,
|
||||
totpPendingCreatedAt: null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
await transaction.adminUser.updateMany({
|
||||
where: { email: { not: LOCAL_ADMIN_EMAIL }, status: "active" },
|
||||
data: {
|
||||
status: "disabled",
|
||||
disabledAt: new Date(),
|
||||
disabledReason: "Local canonical admin normalization",
|
||||
},
|
||||
});
|
||||
const adminIdentity = await transaction.adminUser.upsert({
|
||||
where: { email: LOCAL_ADMIN_EMAIL },
|
||||
create: {
|
||||
id: admin.id,
|
||||
email: LOCAL_ADMIN_EMAIL,
|
||||
firstName: "Admin",
|
||||
lastName: "User",
|
||||
status: "active",
|
||||
authentikGroups: [],
|
||||
},
|
||||
update: {
|
||||
firstName: "Admin",
|
||||
lastName: "User",
|
||||
status: "active",
|
||||
disabledAt: null,
|
||||
disabledReason: null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const adminRole = await transaction.adminRole.findUnique({
|
||||
where: { systemKey: "super_admin" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!adminRole) {
|
||||
throw new Error("Local credential setup could not resolve the canonical SuperAdmin role.");
|
||||
}
|
||||
|
||||
// Delete and recreate so this remains idempotent even after `prisma db push`,
|
||||
// where migration-only partial unique indexes may not exist yet.
|
||||
await transaction.adminUserRole.deleteMany({
|
||||
where: { adminUserId: adminIdentity.id },
|
||||
});
|
||||
await transaction.adminUserRole.create({
|
||||
data: { adminUserId: adminIdentity.id, adminRoleId: adminRole.id, grantedByAdminUserId: adminIdentity.id },
|
||||
});
|
||||
|
||||
const normalizedUsers = await transaction.user.updateMany({
|
||||
where: { passwordHash: { not: null } },
|
||||
data: { passwordHash },
|
||||
});
|
||||
const normalizedPortalUsers = await transaction.portalUser.updateMany({
|
||||
where: { passwordHash: { not: null } },
|
||||
data: { passwordHash },
|
||||
});
|
||||
|
||||
return {
|
||||
adminUserId: adminIdentity.id,
|
||||
normalizedPasswordIdentityCount: normalizedUsers.count + normalizedPortalUsers.count,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function hashLocalPassword(password: string): Promise<string> {
|
||||
return argon2.hash(password, {
|
||||
type: argon2.argon2id,
|
||||
memoryCost: 19_456,
|
||||
timeCost: 2,
|
||||
parallelism: 1,
|
||||
});
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
export type LocalCredentialsEnvironment = {
|
||||
ADMIN_APP_HOST?: string;
|
||||
CI?: string;
|
||||
DATABASE_URL?: string;
|
||||
LOCAL_DEV_CREDENTIALS?: string;
|
||||
NODE_ENV?: string;
|
||||
RLS_RUNTIME_MODE?: string;
|
||||
SENTRY_ENVIRONMENT?: string;
|
||||
};
|
||||
|
||||
const LOCAL_DATABASE_HOSTS = new Set(["127.0.0.1", "[::1]", "localhost"]);
|
||||
const LOCAL_ADMIN_HOST_PATTERN = /^admin\.localhost(?::\d+)?$/i;
|
||||
const LOCAL_DATABASE_MARKER = "app.local_dev_credentials";
|
||||
const LOCAL_DATABASE_MARKER_VALUE = "enabled";
|
||||
|
||||
/**
|
||||
* Local credential normalization requires independent process, URL, and
|
||||
* database-side proof. A loopback SSH tunnel must never be sufficient.
|
||||
*/
|
||||
export function assertLocalCredentialsEnvironment(env: LocalCredentialsEnvironment = process.env): URL {
|
||||
if (env.LOCAL_DEV_CREDENTIALS !== "1") {
|
||||
throw new Error("Local credential normalization requires the canonical local launcher.");
|
||||
}
|
||||
if (env.NODE_ENV !== "development") {
|
||||
throw new Error("Local credential normalization requires NODE_ENV=development.");
|
||||
}
|
||||
if (env.CI?.trim()) {
|
||||
throw new Error("Local credential normalization is disabled in CI.");
|
||||
}
|
||||
if (env.SENTRY_ENVIRONMENT?.trim()) {
|
||||
throw new Error("Local credential normalization is disabled for deployed Sentry environments.");
|
||||
}
|
||||
if (env.RLS_RUNTIME_MODE?.trim().toLowerCase() === "required") {
|
||||
throw new Error("Local credential normalization is disabled when RLS runtime mode is required.");
|
||||
}
|
||||
if (!LOCAL_ADMIN_HOST_PATTERN.test(env.ADMIN_APP_HOST?.trim() ?? "")) {
|
||||
throw new Error("Local credential normalization requires the admin.localhost host.");
|
||||
}
|
||||
|
||||
let databaseUrl: URL;
|
||||
try {
|
||||
databaseUrl = new URL(env.DATABASE_URL ?? "");
|
||||
} catch {
|
||||
throw new Error("Local credential normalization requires a valid DATABASE_URL.");
|
||||
}
|
||||
|
||||
// node-postgres accepts query parameters that can override the URI host.
|
||||
if (databaseUrl.search !== "") {
|
||||
throw new Error("Local credential normalization does not allow PostgreSQL connection query parameters.");
|
||||
}
|
||||
if (!new Set(["postgres:", "postgresql:"]).has(databaseUrl.protocol) || !LOCAL_DATABASE_HOSTS.has(databaseUrl.hostname)) {
|
||||
throw new Error("Local credential normalization requires a loopback PostgreSQL database.");
|
||||
}
|
||||
|
||||
return databaseUrl;
|
||||
}
|
||||
|
||||
export async function assertLocalCredentialsDatabaseMarker(client: Pick<DbClient, "$queryRaw">): Promise<void> {
|
||||
const markerRows = await client.$queryRaw<Array<{ marked: boolean }>>`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM pg_catalog.pg_db_role_setting AS setting
|
||||
JOIN pg_catalog.pg_database AS database
|
||||
ON database.oid = setting.setdatabase
|
||||
WHERE database.datname = current_database()
|
||||
AND setting.setrole = 0
|
||||
AND ${`${LOCAL_DATABASE_MARKER}=${LOCAL_DATABASE_MARKER_VALUE}`} = ANY(setting.setconfig)
|
||||
) AS marked
|
||||
`;
|
||||
if (markerRows[0]?.marked !== true) {
|
||||
throw new Error(
|
||||
"Local credential normalization requires a database marked as disposable local development data. Run pnpm dev:services:mark-local only for the repository's local Postgres container."
|
||||
);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dbMock = vi.hoisted(() => ({
|
||||
pipeline: { upsert: vi.fn() },
|
||||
pipelineStage: { upsert: vi.fn() },
|
||||
pipelineAccess: { upsert: vi.fn() },
|
||||
pipelineFieldConfig: { upsert: vi.fn() },
|
||||
pipelineFieldVisibility: { upsert: vi.fn() },
|
||||
lostReason: { upsert: vi.fn() },
|
||||
projekt: { upsert: vi.fn() },
|
||||
automationRule: { upsert: vi.fn() },
|
||||
automationRuleStep: { upsert: vi.fn(), deleteMany: vi.fn() },
|
||||
task: { upsert: vi.fn() },
|
||||
automationExecution: { upsert: vi.fn() },
|
||||
automationStepExecution: { upsert: vi.fn() },
|
||||
automationTemplate: { upsert: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
|
||||
|
||||
import { seedStagingDomainDemo } from "./stagingDomainDemoSeed.server";
|
||||
|
||||
describe("seedStagingDomainDemo", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("upserts a reviewable P8 and P12 staging showcase", async () => {
|
||||
await seedStagingDomainDemo({ tenantId: "tenant-business", ownerUserId: "user-owner" });
|
||||
|
||||
expect(dbMock.pipeline.upsert).toHaveBeenCalledTimes(2);
|
||||
expect(dbMock.pipelineStage.upsert).toHaveBeenCalledTimes(10);
|
||||
expect(dbMock.lostReason.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.projekt.upsert).toHaveBeenCalledTimes(7);
|
||||
expect(dbMock.automationRule.upsert).toHaveBeenCalledOnce();
|
||||
expect(dbMock.automationRuleStep.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(dbMock.automationTemplate.upsert).toHaveBeenCalledOnce();
|
||||
|
||||
expect(dbMock.projekt.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ tenantId: "tenant-business", projektname: "Heizungstausch Schneider", isDemoData: true }),
|
||||
}),
|
||||
);
|
||||
expect(dbMock.automationRule.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ tenantId: "tenant-business", enabled: true, isDemoData: true }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("seeds an executable 24h reverse example with a real demo task output", async () => {
|
||||
await seedStagingDomainDemo({ tenantId: "tenant-business", ownerUserId: "user-owner" });
|
||||
|
||||
expect(dbMock.task.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ id: "staging-demo-automation-task", source: "automation" }),
|
||||
update: expect.objectContaining({ archivedAt: null }),
|
||||
}),
|
||||
);
|
||||
expect(dbMock.automationExecution.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
id: "staging-demo-automation-execution-success",
|
||||
status: "success",
|
||||
reverseWindowExpiresAt: expect.any(Date),
|
||||
isDemoData: true,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
stepKey: "create-task",
|
||||
output: expect.objectContaining({ taskId: "staging-demo-automation-task" }),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
stepKey: "notify-office",
|
||||
output: expect.objectContaining({
|
||||
recipients: [
|
||||
expect.objectContaining({ email: "buero@demo-pro.example" }),
|
||||
expect.objectContaining({ email: "einsatzleitung@demo-pro.example" }),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("removes UI-rewritten rule steps before upserting so the (ruleId, stepKey) unique cannot collide", async () => {
|
||||
await seedStagingDomainDemo({ tenantId: "tenant-business", ownerUserId: "user-owner" });
|
||||
|
||||
expect(dbMock.automationRuleStep.deleteMany).toHaveBeenCalledExactlyOnceWith({
|
||||
where: {
|
||||
ruleId: "staging-demo-automation-lead-follow-up",
|
||||
id: {
|
||||
notIn: [
|
||||
"staging-demo-automation-step-trigger",
|
||||
"staging-demo-automation-step-create-task",
|
||||
"staging-demo-automation-step-notify-office",
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const deleteOrder = dbMock.automationRuleStep.deleteMany.mock.invocationCallOrder[0];
|
||||
const firstUpsertOrder = dbMock.automationRuleStep.upsert.mock.invocationCallOrder[0];
|
||||
expect(deleteOrder).toBeLessThan(firstUpsertOrder);
|
||||
|
||||
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({ ruleStepId: "staging-demo-automation-step-create-task" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
type StagingDomainDemoSeedInput = {
|
||||
tenantId: string;
|
||||
ownerUserId: string;
|
||||
};
|
||||
|
||||
const salesPipelineId = "staging-demo-pipeline-sales";
|
||||
const orderPipelineId = "staging-demo-pipeline-orders";
|
||||
const lostReasonBudgetId = "staging-demo-lost-reason-budget";
|
||||
const automationRuleId = "staging-demo-automation-lead-follow-up";
|
||||
const automationTaskId = "staging-demo-automation-task";
|
||||
const automationExecutionId = "staging-demo-automation-execution-success";
|
||||
const automationRuleDescription = "Erstellt eine Rückruf-Aufgabe und informiert das Büro über neue Website-Anfragen.";
|
||||
const automationTaskTitle = "Rückruf Familie Klein zur Wärmepumpe";
|
||||
const automationTemplateDescription = "Informiert die Projektleitung vor einer nahenden Deadline.";
|
||||
|
||||
const salesStages = [
|
||||
{ key: "new", name: "Neu", stageKind: "offen", winProbability: 10, color: "#64748b" },
|
||||
{ key: "qualified", name: "Qualifiziert", stageKind: "offen", winProbability: 35, color: "#0ea5e9" },
|
||||
{ key: "proposal", name: "Angebot", stageKind: "offen", winProbability: 70, color: "#8b5cf6" },
|
||||
{ key: "won", name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#22c55e" },
|
||||
{ key: "lost", name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#ef4444" },
|
||||
] as const;
|
||||
|
||||
const orderStages = [
|
||||
{ key: "planning", name: "Planung", stageKind: "offen", winProbability: 100, color: "#64748b" },
|
||||
{ key: "installation", name: "Montage", stageKind: "offen", winProbability: 100, color: "#0ea5e9" },
|
||||
{ key: "acceptance", name: "Abnahme", stageKind: "offen", winProbability: 100, color: "#f59e0b" },
|
||||
{ key: "done", name: "Abgeschlossen", stageKind: "gewonnen", winProbability: 100, color: "#22c55e" },
|
||||
{ key: "cancelled", name: "Storniert", stageKind: "verloren", winProbability: 0, color: "#ef4444" },
|
||||
] as const;
|
||||
|
||||
function stageId(pipeline: "sales" | "orders", key: string): string {
|
||||
return `staging-demo-stage-${pipeline}-${key}`;
|
||||
}
|
||||
|
||||
function daysFromNow(days: number, hour = 12): Date {
|
||||
const date = new Date();
|
||||
date.setHours(hour, 0, 0, 0);
|
||||
date.setDate(date.getDate() + days);
|
||||
return date;
|
||||
}
|
||||
|
||||
async function seedPipelinesAndProjects(input: StagingDomainDemoSeedInput): Promise<void> {
|
||||
const pipelines = [
|
||||
{ id: salesPipelineId, name: "Sales-Pipeline", typHint: "sales", position: 0, isDefault: true, stages: salesStages, key: "sales" },
|
||||
{ id: orderPipelineId, name: "Auftragsabwicklung", typHint: "auftrag", position: 10, isDefault: false, stages: orderStages, key: "orders" },
|
||||
] as const;
|
||||
|
||||
for (const pipeline of pipelines) {
|
||||
await db.pipeline.upsert({
|
||||
where: { id: pipeline.id },
|
||||
create: {
|
||||
id: pipeline.id,
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.ownerUserId,
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
position: pipeline.position,
|
||||
isDefault: pipeline.isDefault,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
position: pipeline.position,
|
||||
isDefault: pipeline.isDefault,
|
||||
isDemoData: true,
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
for (const [position, stage] of pipeline.stages.entries()) {
|
||||
const id = stageId(pipeline.key, stage.key);
|
||||
await db.pipelineStage.upsert({
|
||||
where: { id },
|
||||
create: {
|
||||
id,
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: pipeline.id,
|
||||
name: stage.name,
|
||||
stageKind: stage.stageKind,
|
||||
winProbability: stage.winProbability,
|
||||
color: stage.color,
|
||||
position,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
pipelineId: pipeline.id,
|
||||
name: stage.name,
|
||||
stageKind: stage.stageKind,
|
||||
winProbability: stage.winProbability,
|
||||
color: stage.color,
|
||||
position,
|
||||
isDemoData: true,
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await db.pipelineAccess.upsert({
|
||||
where: { id: "staging-demo-pipeline-access-owner" },
|
||||
create: {
|
||||
id: "staging-demo-pipeline-access-owner",
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: salesPipelineId,
|
||||
principalType: "user",
|
||||
principalId: input.ownerUserId,
|
||||
kannSehen: true,
|
||||
kannBearbeiten: true,
|
||||
},
|
||||
update: { principalId: input.ownerUserId, kannSehen: true, kannBearbeiten: true },
|
||||
});
|
||||
|
||||
const valueFieldConfigId = "staging-demo-pipeline-field-potential-value";
|
||||
await db.pipelineFieldConfig.upsert({
|
||||
where: { id: valueFieldConfigId },
|
||||
create: {
|
||||
id: valueFieldConfigId,
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: salesPipelineId,
|
||||
fieldKey: "potenziellerAuftragswert",
|
||||
sichtbar: true,
|
||||
pflicht: false,
|
||||
reihenfolge: 10,
|
||||
},
|
||||
update: { sichtbar: true, pflicht: false, reihenfolge: 10 },
|
||||
});
|
||||
await db.pipelineFieldVisibility.upsert({
|
||||
where: { id: "staging-demo-pipeline-field-visibility-owner" },
|
||||
create: {
|
||||
id: "staging-demo-pipeline-field-visibility-owner",
|
||||
tenantId: input.tenantId,
|
||||
fieldConfigId: valueFieldConfigId,
|
||||
principalType: "user",
|
||||
principalId: input.ownerUserId,
|
||||
kannSehen: true,
|
||||
kannBearbeiten: true,
|
||||
},
|
||||
update: { principalId: input.ownerUserId, kannSehen: true, kannBearbeiten: true },
|
||||
});
|
||||
|
||||
const lostReasons = [
|
||||
{ id: lostReasonBudgetId, name: "Budget nicht freigegeben", position: 0 },
|
||||
{ id: "staging-demo-lost-reason-timing", name: "Zeitpunkt passt nicht", position: 10 },
|
||||
{ id: "staging-demo-lost-reason-competitor", name: "Wettbewerber gewählt", position: 20 },
|
||||
];
|
||||
for (const reason of lostReasons) {
|
||||
await db.lostReason.upsert({
|
||||
where: { id: reason.id },
|
||||
create: { ...reason, tenantId: input.tenantId, isDemoData: true },
|
||||
update: { name: reason.name, position: reason.position, isDemoData: true, archivedAt: null },
|
||||
});
|
||||
}
|
||||
|
||||
const projects = [
|
||||
{ id: "staging-demo-project-heat-pump", number: "HG-2026-0042", name: "Wärmepumpe Familie Klein", stage: stageId("sales", "new"), value: 28500, priority: "hoch", deadline: daysFromNow(14), won: false, lost: false, order: false },
|
||||
{ id: "staging-demo-project-bathroom", number: "HG-2026-0043", name: "Badsanierung Wagner", stage: stageId("sales", "qualified"), value: 42000, priority: "normal", deadline: daysFromNow(30), won: false, lost: false, order: false },
|
||||
{ id: "staging-demo-project-heating", number: "HG-2026-0044", name: "Heizungstausch Schneider", stage: stageId("sales", "proposal"), value: 19750, priority: "dringend", deadline: daysFromNow(-3), won: false, lost: false, order: false },
|
||||
{ id: "staging-demo-project-housing", number: "HG-2026-0045", name: "Sanierung Wohnanlage Müller", stage: stageId("sales", "won"), value: 138000, priority: "hoch", deadline: daysFromNow(60), won: true, lost: false, order: false },
|
||||
{ id: "staging-demo-project-maintenance", number: "HG-2026-0046", name: "Wartungsvertrag Bäckerei Sonnenschein", stage: stageId("sales", "lost"), value: 7800, priority: "niedrig", deadline: daysFromNow(7), won: false, lost: true, order: false },
|
||||
{ id: "staging-demo-project-installation", number: "HG-2026-0047", name: "Montage Wärmepumpe Klein", stage: stageId("orders", "installation"), value: 28500, priority: "hoch", deadline: daysFromNow(10), won: false, lost: false, order: true },
|
||||
{ id: "staging-demo-project-acceptance", number: "HG-2026-0048", name: "Abnahme Badsanierung Wagner", stage: stageId("orders", "acceptance"), value: 42000, priority: "normal", deadline: daysFromNow(2), won: false, lost: false, order: true },
|
||||
] as const;
|
||||
|
||||
for (const project of projects) {
|
||||
const pipelineId = project.order ? orderPipelineId : salesPipelineId;
|
||||
const data = {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.ownerUserId,
|
||||
projektNummer: project.number,
|
||||
projektname: project.name,
|
||||
beschreibung: "Staging-Demodatensatz für die visuelle Prüfung der Projekt- und Pipeline-Oberflächen.",
|
||||
projekttyp: project.order ? "Auftrag" : "Verkaufschance",
|
||||
prioritaet: project.priority,
|
||||
pipelineId,
|
||||
stageId: project.stage,
|
||||
potenziellerAuftragswert: project.order ? null : project.value,
|
||||
auftragsvolumen: project.order ? project.value : null,
|
||||
startDatum: daysFromNow(-14),
|
||||
deadline: project.deadline,
|
||||
zustaendigePersonId: input.ownerUserId,
|
||||
wonAt: project.won ? daysFromNow(-5) : null,
|
||||
lostAt: project.lost ? daysFromNow(-2) : null,
|
||||
lostReasonId: project.lost ? lostReasonBudgetId : null,
|
||||
isDemoData: true,
|
||||
archivedAt: null,
|
||||
};
|
||||
await db.projekt.upsert({ where: { id: project.id }, create: { id: project.id, ...data }, update: data });
|
||||
}
|
||||
}
|
||||
|
||||
async function seedAutomation(input: StagingDomainDemoSeedInput): Promise<void> {
|
||||
const steps = [
|
||||
{ key: "trigger", kind: "trigger", nodeType: "forms.submitted", parents: [], position: { x: 120, y: 160 }, summary: "automation.steps.triggerFormSubmitted" },
|
||||
{ key: "create-task", kind: "action", nodeType: "task.create", parents: ["trigger"], position: { x: 440, y: 160 }, summary: "automation.steps.createBackofficeTask" },
|
||||
{ key: "notify-office", kind: "action", nodeType: "notification.send", parents: ["create-task"], position: { x: 760, y: 160 }, summary: "automation.steps.notifyOffice" },
|
||||
] as const;
|
||||
const flowData = {
|
||||
triggerKey: "forms.submitted",
|
||||
steps: steps.map((step, sortOrder) => ({
|
||||
stepKey: step.key,
|
||||
kind: step.kind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parents,
|
||||
config: {},
|
||||
position: step.position,
|
||||
sortOrder,
|
||||
summaryKey: step.summary,
|
||||
})),
|
||||
history: { past: [], future: [] },
|
||||
};
|
||||
|
||||
await db.automationRule.upsert({
|
||||
where: { id: automationRuleId },
|
||||
create: {
|
||||
id: automationRuleId,
|
||||
tenantId: input.tenantId,
|
||||
name: "Angebotsanfragen automatisch nachfassen",
|
||||
description: automationRuleDescription,
|
||||
status: "active",
|
||||
enabled: true,
|
||||
createdVia: "staging-demo-seed",
|
||||
triggerKey: "forms.submitted",
|
||||
flowData,
|
||||
createdByUserId: input.ownerUserId,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: { description: automationRuleDescription, status: "active", enabled: true, flowData, isDemoData: true, archivedAt: null },
|
||||
});
|
||||
|
||||
// Saving the rule in the UI rewrites its steps with generated cuid ids. Those
|
||||
// rows collide with the fixed-id upserts below on the (ruleId, stepKey) unique,
|
||||
// crashing the seed on boot. Remove them first; executions keep working via
|
||||
// the SetNull relation and are re-linked below.
|
||||
await db.automationRuleStep.deleteMany({
|
||||
where: {
|
||||
ruleId: automationRuleId,
|
||||
id: { notIn: steps.map((step) => `staging-demo-automation-step-${step.key}`) },
|
||||
},
|
||||
});
|
||||
|
||||
for (const [sortOrder, step] of steps.entries()) {
|
||||
const id = `staging-demo-automation-step-${step.key}`;
|
||||
await db.automationRuleStep.upsert({
|
||||
where: { id },
|
||||
create: {
|
||||
id,
|
||||
tenantId: input.tenantId,
|
||||
ruleId: automationRuleId,
|
||||
stepKey: step.key,
|
||||
stepKind: step.kind,
|
||||
nodeType: step.nodeType,
|
||||
config: {},
|
||||
parentStepIds: [...step.parents],
|
||||
position: step.position,
|
||||
sortOrder,
|
||||
summaryText: step.summary,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: { stepKind: step.kind, nodeType: step.nodeType, config: {}, parentStepIds: [...step.parents], position: step.position, sortOrder, summaryText: step.summary, isDemoData: true },
|
||||
});
|
||||
}
|
||||
|
||||
await db.task.upsert({
|
||||
where: { id: automationTaskId },
|
||||
create: {
|
||||
id: automationTaskId,
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.ownerUserId,
|
||||
title: automationTaskTitle,
|
||||
description: "Von der Staging-Demo-Automation angelegte Aufgabe.",
|
||||
status: "open",
|
||||
priority: "high",
|
||||
deadline: daysFromNow(2),
|
||||
assignedToUserId: input.ownerUserId,
|
||||
source: "automation",
|
||||
sourceRef: automationExecutionId,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: { status: "open", priority: "high", deadline: daysFromNow(2), assignedToUserId: input.ownerUserId, assignedToGroupId: null, archivedAt: null, isDemoData: true },
|
||||
});
|
||||
|
||||
const startedAt = new Date(Date.now() - 45 * 60_000);
|
||||
const endedAt = new Date(startedAt.getTime() + 38_000);
|
||||
await db.automationExecution.upsert({
|
||||
where: { id: automationExecutionId },
|
||||
create: {
|
||||
id: automationExecutionId,
|
||||
tenantId: input.tenantId,
|
||||
ruleId: automationRuleId,
|
||||
triggerKey: "forms.submitted",
|
||||
triggerPayload: { form: "Angebotsanfrage", contact: "Familie Klein", source: "staging-demo" },
|
||||
status: "success",
|
||||
dryRun: false,
|
||||
idempotencyKey: "staging-demo:lead-follow-up:success",
|
||||
reverseWindowExpiresAt: daysFromNow(1),
|
||||
summaryText: "Angebotsanfrage Familie Klein erfolgreich verarbeitet",
|
||||
queuedAt: startedAt,
|
||||
startedAt,
|
||||
endedAt,
|
||||
durationMs: 38_000,
|
||||
createdByUserId: input.ownerUserId,
|
||||
isDemoData: true,
|
||||
createdAt: startedAt,
|
||||
},
|
||||
update: { status: "success", reverseWindowExpiresAt: daysFromNow(1), summaryText: "Angebotsanfrage Familie Klein erfolgreich verarbeitet", errorText: null, queuedAt: startedAt, startedAt, endedAt, durationMs: 38_000, isDemoData: true, createdAt: startedAt },
|
||||
});
|
||||
|
||||
const executionOutputs = {
|
||||
trigger: { form: "Angebotsanfrage", contact: "Familie Klein", topic: "Wärmepumpe" },
|
||||
"create-task": { taskId: automationTaskId, createdTaskId: automationTaskId, title: automationTaskTitle },
|
||||
"notify-office": {
|
||||
recipient: "Büro",
|
||||
deliveryStatus: "delivered",
|
||||
// Reverse-window recipients contract: send-type steps persist who was
|
||||
// reached so the 24h reverse plan can show the (non-retractable) list.
|
||||
recipients: [
|
||||
{ name: "Sandra Vogel", email: "buero@demo-pro.example" },
|
||||
{ name: "Peter Klein", email: "einsatzleitung@demo-pro.example" },
|
||||
],
|
||||
},
|
||||
} as const;
|
||||
for (const [sortOrder, step] of steps.entries()) {
|
||||
const id = `staging-demo-automation-step-execution-${step.key}`;
|
||||
await db.automationStepExecution.upsert({
|
||||
where: { id },
|
||||
create: {
|
||||
id,
|
||||
tenantId: input.tenantId,
|
||||
executionId: automationExecutionId,
|
||||
ruleStepId: `staging-demo-automation-step-${step.key}`,
|
||||
stepKey: step.key,
|
||||
stepKind: step.kind,
|
||||
nodeType: step.nodeType,
|
||||
status: "success",
|
||||
input: sortOrder === 0 ? { source: "Website-Formular" } : { previousStep: step.parents[0] ?? null },
|
||||
output: executionOutputs[step.key],
|
||||
summaryText: step.summary,
|
||||
startedAt: new Date(startedAt.getTime() + sortOrder * 10_000),
|
||||
endedAt: new Date(startedAt.getTime() + (sortOrder + 1) * 10_000),
|
||||
durationMs: 10_000,
|
||||
sortOrder,
|
||||
},
|
||||
update: { status: "success", output: executionOutputs[step.key], summaryText: step.summary, errorText: null, sortOrder, ruleStepId: `staging-demo-automation-step-${step.key}` },
|
||||
});
|
||||
}
|
||||
|
||||
await db.automationTemplate.upsert({
|
||||
where: { id: "staging-demo-automation-template-project-deadline" },
|
||||
create: {
|
||||
id: "staging-demo-automation-template-project-deadline",
|
||||
tenantId: input.tenantId,
|
||||
name: "Projekt-Deadline erinnern",
|
||||
description: automationTemplateDescription,
|
||||
category: "projects",
|
||||
flowData: {
|
||||
triggerKey: "projects.deadline_soon",
|
||||
steps: [
|
||||
{ stepKey: "trigger", kind: "trigger", nodeType: "projects.deadline_soon", parentStepIds: [], summaryKey: "automation.steps.triggerProjectDeadline" },
|
||||
{ stepKey: "notify", kind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], summaryKey: "automation.steps.notifyProjectLead" },
|
||||
],
|
||||
},
|
||||
isPublished: true,
|
||||
createdByUserId: input.ownerUserId,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: { description: automationTemplateDescription, isPublished: true, isDemoData: true, archivedAt: null },
|
||||
});
|
||||
}
|
||||
|
||||
export async function seedStagingDomainDemo(input: StagingDomainDemoSeedInput): Promise<void> {
|
||||
await seedPipelinesAndProjects(input);
|
||||
await seedAutomation(input);
|
||||
}
|
||||
+1
@@ -11,6 +11,7 @@ export {
|
||||
deleteSubscriptionUsageBasedTier,
|
||||
getAllSubscriptionFeatures,
|
||||
getAllSubscriptionProducts,
|
||||
getAllSubscriptionProductsStrict,
|
||||
getAllSubscriptionProductsWithTenants,
|
||||
getSubscriptionPrice,
|
||||
getSubscriptionPriceByBillingProviderId,
|
||||
|
||||
+17
@@ -35,6 +35,7 @@ import {
|
||||
cancelTenantSubscriptionProduct as persistCancel,
|
||||
updateTenantSubscriptionProduct as persistUpdate,
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
import type { TenantBillingClient } from "@hivegrid/db/subscriptions.server";
|
||||
|
||||
const mocks = getMocks();
|
||||
|
||||
@@ -51,6 +52,22 @@ describe("tenantSubscriptionProducts db wrapper — cross-replica cache invalida
|
||||
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant-a");
|
||||
});
|
||||
|
||||
it("can defer cache invalidation until the caller's transaction has committed", async () => {
|
||||
mocks.clearTenantSubscriptionCache.mockClear();
|
||||
vi.mocked(persistAdd).mockClear();
|
||||
vi.mocked(persistAdd).mockResolvedValueOnce({
|
||||
tenantSubscription: { tenantId: "tenant-a" },
|
||||
} as Awaited<ReturnType<typeof persistAdd>>);
|
||||
|
||||
const transactionClient = {} as TenantBillingClient;
|
||||
const input = {} as Parameters<typeof addTenantSubscriptionProduct>[0];
|
||||
|
||||
await addTenantSubscriptionProduct(input, { invalidateCache: false, client: transactionClient });
|
||||
|
||||
expect(persistAdd).toHaveBeenCalledWith(input, transactionClient);
|
||||
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updateTenantSubscriptionProduct publishes a cross-replica invalidation for the tenant", async () => {
|
||||
mocks.clearTenantSubscriptionCache.mockClear();
|
||||
vi.mocked(persistUpdate).mockResolvedValueOnce({
|
||||
|
||||
+9
-3
@@ -5,6 +5,7 @@ import {
|
||||
type TenantSubscriptionProductCreateInput,
|
||||
type TenantSubscriptionProductUpdateInput,
|
||||
type TenantSubscriptionProductCancelInput,
|
||||
type TenantBillingClient,
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
||||
|
||||
@@ -19,11 +20,16 @@ export {
|
||||
type TenantSubscriptionProductWithTenant,
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
|
||||
export async function addTenantSubscriptionProduct(data: TenantSubscriptionProductCreateInput) {
|
||||
const item = await persistTenantSubscriptionProduct(data);
|
||||
export async function addTenantSubscriptionProduct(
|
||||
data: TenantSubscriptionProductCreateInput,
|
||||
options: { invalidateCache?: boolean; client?: TenantBillingClient } = {}
|
||||
) {
|
||||
const item = await persistTenantSubscriptionProduct(data, options.client);
|
||||
// Cross-replica purge: clearTenantSubscriptionCache publishes on the
|
||||
// subscription pub/sub channel so peer web replicas drop their L1 too.
|
||||
clearTenantSubscriptionCache(item.tenantSubscription.tenantId);
|
||||
if (options.invalidateCache !== false) {
|
||||
clearTenantSubscriptionCache(item.tenantSubscription.tenantId);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
|
||||
+61
-23
@@ -1,8 +1,15 @@
|
||||
import { createTwoTierCache, type TwoTierCache } from "@hivegrid/shared-store";
|
||||
import { createTwoTierCache, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
export type TenantSecuritySnapshot = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
deactivatedReason: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Tenant cache (two-tier). The existing in-process `cachified` LRU in
|
||||
* `tenants.db.server.ts` stays the L1 read path; this module owns the
|
||||
@@ -15,9 +22,9 @@ import { createScopedLogger } from "~/utils/logger.server";
|
||||
*/
|
||||
const log = createScopedLogger("tenant-cache");
|
||||
|
||||
const TTL_SECONDS_DEFAULT = 5 * 60;
|
||||
export const TENANT_SNAPSHOT_SAFETY_TTL_SECONDS = 30;
|
||||
|
||||
let cacheSingleton: TwoTierCache<{ id: string } | null> | null = null;
|
||||
let cacheSingleton: TwoTierCache<TenantSecuritySnapshot> | null = null;
|
||||
let subscribeDisposer: (() => Promise<void>) | null = null;
|
||||
|
||||
function pubsubEnabledFromEnv(): boolean {
|
||||
@@ -26,39 +33,70 @@ function pubsubEnabledFromEnv(): boolean {
|
||||
return raw.toLowerCase() !== "false" && raw !== "0";
|
||||
}
|
||||
|
||||
function ttlSecondsFromEnv(): number {
|
||||
const raw = process.env.CACHE_L1_TTL_SECONDS;
|
||||
if (!raw) return TTL_SECONDS_DEFAULT;
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) return TTL_SECONDS_DEFAULT;
|
||||
return Math.floor(parsed);
|
||||
}
|
||||
|
||||
export function getTenantCache(): TwoTierCache<{ id: string } | null> {
|
||||
if (cacheSingleton) return cacheSingleton;
|
||||
cacheSingleton = createTwoTierCache<{ id: string } | null>({
|
||||
store: getSharedStore(),
|
||||
export function createTenantSecurityCache(store: SharedStore, options: { now?: () => number } = {}): TwoTierCache<TenantSecuritySnapshot> {
|
||||
return createTwoTierCache<TenantSecuritySnapshot>({
|
||||
store,
|
||||
namespace: "tenant",
|
||||
ttlSeconds: ttlSecondsFromEnv(),
|
||||
ttlSeconds: TENANT_SNAPSHOT_SAFETY_TTL_SECONDS,
|
||||
l1Now: options.now,
|
||||
pubsubEnabled: pubsubEnabledFromEnv(),
|
||||
logger: { warn: (obj, msg) => log.warn(obj, msg), error: (obj, msg) => log.error(obj, msg) },
|
||||
});
|
||||
}
|
||||
|
||||
export function getTenantCache(): TwoTierCache<TenantSecuritySnapshot> {
|
||||
if (cacheSingleton) return cacheSingleton;
|
||||
cacheSingleton = createTenantSecurityCache(getSharedStore());
|
||||
return cacheSingleton;
|
||||
}
|
||||
|
||||
export async function loadTenantSecuritySnapshot(
|
||||
identifier: string,
|
||||
getFreshValue: () => Promise<TenantSecuritySnapshot | null>
|
||||
): Promise<TenantSecuritySnapshot | null> {
|
||||
const cache = getTenantCache();
|
||||
try {
|
||||
const cached = await cache.get(identifier);
|
||||
if (cached !== null) return cached;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "tenant-security-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Tenant security cache read failed; falling back to the database."
|
||||
);
|
||||
}
|
||||
const fresh = await getFreshValue();
|
||||
if (fresh !== null) {
|
||||
try {
|
||||
await cache.set(identifier, fresh);
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "tenant-security-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Tenant security cache write failed; continuing with the database result."
|
||||
);
|
||||
}
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish a tenant-invalidation. Call after any tenant mutation in the
|
||||
* web app (settings update, logo upload, member add/remove). The local
|
||||
* cachified entries are also cleared as a defence-in-depth in case the
|
||||
* caller forgot to call clearCacheKey().
|
||||
*/
|
||||
export async function publishTenantInvalidation(tenantId: string): Promise<void> {
|
||||
clearCacheKey(`tenant:${tenantId}`);
|
||||
clearCacheKey(`tenantSimple:${tenantId}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${tenantId}`);
|
||||
await getTenantCache().invalidate(tenantId).catch(() => {
|
||||
/* logged inside helper */
|
||||
});
|
||||
export async function publishTenantInvalidation(...identifiers: string[]): Promise<void> {
|
||||
const uniqueIdentifiers = [...new Set(identifiers.filter((identifier) => identifier.length > 0))];
|
||||
const cache = getTenantCache();
|
||||
for (const identifier of uniqueIdentifiers) {
|
||||
clearCacheKey(`tenant:${identifier}`);
|
||||
clearCacheKey(`tenantSimple:${identifier}`);
|
||||
clearCacheKey(`tenantIdOrSlug:${identifier}`);
|
||||
cache.deleteLocal(identifier);
|
||||
}
|
||||
// Tenant deactivation and slug changes are authorization/routing changes.
|
||||
// Propagate failures so the mutating request cannot report success while a
|
||||
// peer replica may still serve an old snapshot.
|
||||
await Promise.all(uniqueIdentifiers.map((identifier) => cache.l2.invalidate(identifier)));
|
||||
}
|
||||
|
||||
export async function subscribeTenantCache(): Promise<() => Promise<void>> {
|
||||
|
||||
+848
-138
File diff suppressed because it is too large.
Load diff
+608
-212
File diff suppressed because it is too large.
Load diff
-43
@@ -1,43 +0,0 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tenantTypeFindMany: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
tenantType: {
|
||||
findMany: mocks.tenantTypeFindMany,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { getTenantTypeOptions } from "./tenantTypes.db.server";
|
||||
|
||||
describe("tenant type db helpers", () => {
|
||||
beforeEach(() => {
|
||||
mocks.tenantTypeFindMany.mockReset();
|
||||
mocks.tenantTypeFindMany.mockResolvedValue([
|
||||
{ id: "type_1", title: "Workspace" },
|
||||
{ id: "type_2", title: "Customer" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads lightweight tenant type options for account forms", async () => {
|
||||
await expect(getTenantTypeOptions()).resolves.toEqual([
|
||||
{ id: "type_1", title: "Workspace" },
|
||||
{ id: "type_2", title: "Customer" },
|
||||
]);
|
||||
|
||||
expect(mocks.tenantTypeFindMany).toHaveBeenCalledWith({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
import { Prisma, SubscriptionProduct, TenantType } from "@hivegrid/db/prisma-browser";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { cachified, clearCacheKey } from "~/utils/cache.server";
|
||||
|
||||
export type TenantTypeWithDetails = TenantType & {
|
||||
subscriptionProducts: SubscriptionProduct[];
|
||||
_count: { tenants: number };
|
||||
};
|
||||
const includeDetails = {
|
||||
subscriptionProducts: true,
|
||||
_count: { select: { tenants: true } },
|
||||
};
|
||||
|
||||
// TenantTypes are a quasi-static, non-tenant-scoped table read on every authenticated app pageview
|
||||
// (loadAppData). The cache is invalidated on every tenant-type mutation below. NOTE: the embedded
|
||||
// `_count.tenants` also changes when tenants are created/deleted (outside this module's scope), so a
|
||||
// short TTL is used to keep that count from drifting more than a few minutes on the app overview.
|
||||
const TENANT_TYPES_CACHE_KEY = "tenantTypes:all";
|
||||
const TENANT_TYPES_CACHE_TTL = 1000 * 60 * 5; // 5min — bounded staleness for the embedded tenant count
|
||||
|
||||
export async function getAllTenantTypes(): Promise<TenantTypeWithDetails[]> {
|
||||
return await cachified({
|
||||
key: TENANT_TYPES_CACHE_KEY,
|
||||
ttl: TENANT_TYPES_CACHE_TTL,
|
||||
getFreshValue: () =>
|
||||
db.tenantType.findMany({
|
||||
include: {
|
||||
subscriptionProducts: true,
|
||||
_count: { select: { tenants: true } },
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantTypeOptions(): Promise<Array<Pick<TenantType, "id" | "title">>> {
|
||||
return await db.tenantType.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getDefaultTenantTypes() {
|
||||
return await db.tenantType.findMany({
|
||||
where: { isDefault: true },
|
||||
orderBy: {
|
||||
createdAt: "asc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantType(id: string): Promise<TenantTypeWithDetails | null> {
|
||||
return await db.tenantType.findUnique({
|
||||
where: { id: id },
|
||||
include: includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantTypeByTitle(title: string): Promise<TenantTypeWithDetails | null> {
|
||||
return await db.tenantType.findUnique({
|
||||
where: { title },
|
||||
include: includeDetails,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createTenantType(data: {
|
||||
title: string;
|
||||
titlePlural: string;
|
||||
description: string | null;
|
||||
isDefault?: boolean;
|
||||
subscriptionProducts: string[];
|
||||
}) {
|
||||
return await db.tenantType
|
||||
.create({
|
||||
data: {
|
||||
title: data.title,
|
||||
titlePlural: data.titlePlural,
|
||||
description: data.description,
|
||||
isDefault: data.isDefault,
|
||||
subscriptionProducts: {
|
||||
connect: data.subscriptionProducts.map((id) => ({ id })),
|
||||
},
|
||||
},
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(TENANT_TYPES_CACHE_KEY);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenantType(
|
||||
id: string,
|
||||
data: {
|
||||
title?: string;
|
||||
titlePlural?: string;
|
||||
description?: string | null;
|
||||
isDefault?: boolean;
|
||||
subscriptionProducts?: string[];
|
||||
}
|
||||
) {
|
||||
const update: Prisma.TenantTypeUncheckedUpdateInput = {
|
||||
title: data.title,
|
||||
titlePlural: data.titlePlural,
|
||||
description: data.description,
|
||||
isDefault: data.isDefault,
|
||||
};
|
||||
if (data.subscriptionProducts) {
|
||||
update.subscriptionProducts = {
|
||||
set: data.subscriptionProducts.map((id) => ({ id })),
|
||||
};
|
||||
}
|
||||
return await db.tenantType
|
||||
.update({
|
||||
where: { id: id },
|
||||
data: update,
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(TENANT_TYPES_CACHE_KEY);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteTenantType(id: string) {
|
||||
return await db.tenantType
|
||||
.delete({
|
||||
where: { id: id },
|
||||
})
|
||||
.then((item) => {
|
||||
clearCacheKey(TENANT_TYPES_CACHE_KEY);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import { createTwoTierCache, type CacheSerializer, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
|
||||
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import type { UserWithoutPassword } from "./users.db.server";
|
||||
|
||||
const log = createScopedLogger("user-snapshot-cache");
|
||||
|
||||
export const USER_SNAPSHOT_CACHE_TTL_SECONDS = 30;
|
||||
|
||||
type SerializedUserSnapshot = Omit<UserWithoutPassword, "createdAt"> & {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const userSerializer: CacheSerializer<UserWithoutPassword> = {
|
||||
serialize(value) {
|
||||
const serialized: SerializedUserSnapshot = {
|
||||
...value,
|
||||
createdAt: value.createdAt.toISOString(),
|
||||
};
|
||||
return JSON.stringify(serialized);
|
||||
},
|
||||
deserialize(raw) {
|
||||
const value = JSON.parse(raw) as SerializedUserSnapshot;
|
||||
return {
|
||||
...value,
|
||||
createdAt: new Date(value.createdAt),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
function pubsubEnabledFromEnv(): boolean {
|
||||
const raw = process.env.CACHE_INVALIDATION_ENABLED;
|
||||
if (raw === undefined || raw === null || raw === "") return true;
|
||||
return raw.toLowerCase() !== "false" && raw !== "0";
|
||||
}
|
||||
|
||||
export function createUserSnapshotCache(store: SharedStore, options: { now?: () => number } = {}): TwoTierCache<UserWithoutPassword> {
|
||||
return createTwoTierCache<UserWithoutPassword>({
|
||||
store,
|
||||
namespace: "user-snapshot",
|
||||
ttlSeconds: USER_SNAPSHOT_CACHE_TTL_SECONDS,
|
||||
l1MaxEntries: 10_000,
|
||||
l1Now: options.now,
|
||||
serializer: userSerializer,
|
||||
pubsubEnabled: pubsubEnabledFromEnv(),
|
||||
logger: {
|
||||
warn: (obj, msg) => log.warn(obj, msg),
|
||||
info: (obj, msg) => log.info(obj, msg),
|
||||
error: (obj, msg) => log.error(obj, msg),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let cacheSingleton: TwoTierCache<UserWithoutPassword> | null = null;
|
||||
let subscribeDisposer: (() => Promise<void>) | null = null;
|
||||
|
||||
export function getUserSnapshotCache(): TwoTierCache<UserWithoutPassword> {
|
||||
cacheSingleton ??= createUserSnapshotCache(getSharedStore());
|
||||
return cacheSingleton;
|
||||
}
|
||||
|
||||
export async function loadCachedUserSnapshot(userId: string, getFreshValue: () => Promise<UserWithoutPassword | null>): Promise<UserWithoutPassword | null> {
|
||||
const cache = getUserSnapshotCache();
|
||||
try {
|
||||
const cached = await cache.get(userId);
|
||||
if (cached !== null) return cached;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "user-snapshot-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"User snapshot cache read failed; falling back to the database."
|
||||
);
|
||||
}
|
||||
|
||||
const fresh = await getFreshValue();
|
||||
if (fresh !== null) {
|
||||
try {
|
||||
await cache.set(userId, fresh);
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "user-snapshot-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"User snapshot cache write failed; continuing with the database result."
|
||||
);
|
||||
}
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/** Fail closed because this snapshot contains the operator-admin relation. */
|
||||
export async function invalidateUserSnapshot(userId: string): Promise<void> {
|
||||
clearCacheKey(`user:${userId}`);
|
||||
const cache = getUserSnapshotCache();
|
||||
cache.deleteLocal(userId);
|
||||
await cache.l2.invalidate(userId);
|
||||
}
|
||||
|
||||
export async function subscribeUserSnapshotCache(): Promise<() => Promise<void>> {
|
||||
if (subscribeDisposer) return subscribeDisposer;
|
||||
subscribeDisposer = await getUserSnapshotCache().subscribe();
|
||||
log.info({ namespace: "user-snapshot" }, "User snapshot cache subscriber started.");
|
||||
return subscribeDisposer;
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export function __resetUserSnapshotCacheForTests(): void {
|
||||
cacheSingleton = null;
|
||||
subscribeDisposer = null;
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
const dbMock = vi.hoisted(() => ({
|
||||
adminUser: { findMany: vi.fn(), findUnique: vi.fn() },
|
||||
user: { findMany: vi.fn(), count: vi.fn(), findUnique: vi.fn(), create: vi.fn() },
|
||||
tenant: { findMany: vi.fn() },
|
||||
tenantUser: { findMany: vi.fn() },
|
||||
userRole: { findMany: vi.fn() },
|
||||
log: { findMany: vi.fn() },
|
||||
$transaction: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
|
||||
vi.mock("~/utils/auth/passwordHasher.server", () => ({ hashPassword: vi.fn() }));
|
||||
vi.mock("~/modules/plugins/services/.server/pluginHookPublisher", () => ({ emitPluginHookFireAndForget: vi.fn() }));
|
||||
vi.mock("./user-snapshot-cache.server", () => ({ invalidateUserSnapshot: vi.fn(), loadCachedUserSnapshot: vi.fn() }));
|
||||
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({ resolveUserEmailRlsIdentity: vi.fn() }));
|
||||
|
||||
import { emitPluginHookFireAndForget } from "~/modules/plugins/services/.server/pluginHookPublisher";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { resolveUserEmailRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
|
||||
import { adminGetAllUsers, emitUserCreatedHook, getUserByEmail, register } from "./users.db.server";
|
||||
|
||||
const userRoots = [
|
||||
{
|
||||
id: "user_1",
|
||||
email: "one@example.test",
|
||||
firstName: "One",
|
||||
lastName: "User",
|
||||
avatar: null,
|
||||
phone: null,
|
||||
admin: { userId: "user_1" },
|
||||
defaultTenantId: "tenant_1",
|
||||
createdAt: new Date("2026-07-14T08:00:00.000Z"),
|
||||
locale: "de",
|
||||
lightOrDarkMode: null,
|
||||
},
|
||||
{
|
||||
id: "user_2",
|
||||
email: "two@example.test",
|
||||
firstName: "Two",
|
||||
lastName: "User",
|
||||
avatar: null,
|
||||
phone: null,
|
||||
admin: null,
|
||||
defaultTenantId: "tenant_2",
|
||||
createdAt: new Date("2026-07-14T09:00:00.000Z"),
|
||||
locale: "de",
|
||||
lightOrDarkMode: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("admin user RLS hydration", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMock.user.findMany.mockResolvedValue(userRoots);
|
||||
dbMock.user.count.mockResolvedValue(2);
|
||||
dbMock.adminUser.findMany.mockResolvedValue([{ id: "user_1" }]);
|
||||
dbMock.$transaction.mockImplementation(async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock));
|
||||
vi.mocked(hashPassword).mockResolvedValue("password-hash");
|
||||
vi.mocked(resolveUserEmailRlsIdentity).mockResolvedValue({ resourceId: "resolved_user", userId: "resolved_user" });
|
||||
dbMock.tenant.findMany.mockResolvedValue([{ id: "tenant_1" }, { id: "tenant_2" }]);
|
||||
dbMock.userRole.findMany.mockImplementation(async (args) => {
|
||||
const tenantId = getRlsExecutionContext()?.tenantId;
|
||||
if (args.where.tenantId === null) {
|
||||
expect(tenantId).toBeUndefined();
|
||||
return [{ id: "global_role_1", userId: "user_1", roleId: "admin_role", tenantId: null, role: { id: "admin_role", type: "admin" } }];
|
||||
}
|
||||
expect(args.where.tenantId).toBe(tenantId);
|
||||
return [
|
||||
{
|
||||
id: `tenant_role_${tenantId}`,
|
||||
userId: tenantId === "tenant_1" ? "user_1" : "user_2",
|
||||
roleId: `app_role_${tenantId}`,
|
||||
tenantId,
|
||||
role: { id: `app_role_${tenantId}`, type: "app" },
|
||||
},
|
||||
];
|
||||
});
|
||||
dbMock.tenantUser.findMany.mockImplementation(async (args) => {
|
||||
const tenantId = getRlsExecutionContext()?.tenantId;
|
||||
expect(args.where.tenantId).toBe(tenantId);
|
||||
const userId = tenantId === "tenant_1" ? "user_1" : "user_2";
|
||||
return [{ id: `membership_${tenantId}`, userId, tenantId, tenant: { id: tenantId, name: tenantId } }];
|
||||
});
|
||||
});
|
||||
|
||||
it("hydrates each membership and tenant role only inside its exact tenant context", async () => {
|
||||
const result = await runWithRlsContext({ userId: "operator_1" }, () => adminGetAllUsers());
|
||||
|
||||
expect(dbMock.tenant.findMany).toHaveBeenCalledWith({ select: { id: true }, orderBy: { id: "asc" } });
|
||||
expect(dbMock.tenantUser.findMany).toHaveBeenCalledTimes(2);
|
||||
expect(result.items[0]?.tenants.map(({ tenantId }) => tenantId)).toEqual(["tenant_1"]);
|
||||
expect(result.items[0]?.roles.map(({ tenantId }) => tenantId)).toEqual([null, "tenant_1"]);
|
||||
expect(result.items[1]?.tenants.map(({ tenantId }) => tenantId)).toEqual(["tenant_2"]);
|
||||
expect(result.items[1]?.roles.map(({ tenantId }) => tenantId)).toEqual(["tenant_2"]);
|
||||
expect(dbMock.$transaction).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("resolves a tenant filter through TenantUser without a cross-tenant relation include", async () => {
|
||||
dbMock.tenantUser.findMany.mockImplementationOnce(async (args) => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId: "tenant_2" });
|
||||
expect(args).toEqual({ where: { tenantId: "tenant_2" }, select: { userId: true } });
|
||||
return [{ userId: "user_2" }];
|
||||
});
|
||||
|
||||
await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
adminGetAllUsers({
|
||||
query: null,
|
||||
properties: [{ name: "tenantId", title: "Tenant", manual: true, value: "tenant_2" }],
|
||||
})
|
||||
);
|
||||
|
||||
expect(dbMock.user.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { AND: [{}, { id: { in: ["user_2"] } }] },
|
||||
select: expect.objectContaining({ id: true }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("binds the created user and target tenant when emitting a post-commit hook without context", async () => {
|
||||
vi.mocked(emitPluginHookFireAndForget).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_3", tenantId: "tenant_3" });
|
||||
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
|
||||
});
|
||||
|
||||
await emitUserCreatedHook({
|
||||
id: "user_3",
|
||||
email: "three@example.test",
|
||||
locale: "de",
|
||||
defaultTenantId: "tenant_3",
|
||||
createdAt: new Date("2026-07-15T10:00:00.000Z"),
|
||||
});
|
||||
|
||||
expect(emitPluginHookFireAndForget).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps the authenticated actor but isolates a previous tenant transaction for the post-commit hook", async () => {
|
||||
const oldTransaction = {};
|
||||
vi.mocked(emitPluginHookFireAndForget).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId: "tenant_3" });
|
||||
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
|
||||
});
|
||||
|
||||
await runWithRlsContext({ userId: "operator_1", tenantId: "tenant_old" }, () =>
|
||||
runWithRlsTransaction(oldTransaction, async () => {
|
||||
await emitUserCreatedHook({
|
||||
id: "user_3",
|
||||
email: "three@example.test",
|
||||
locale: "de",
|
||||
defaultTenantId: "tenant_3",
|
||||
createdAt: new Date("2026-07-15T10:00:00.000Z"),
|
||||
});
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId: "tenant_old", transaction: oldTransaction });
|
||||
})
|
||||
);
|
||||
|
||||
expect(emitPluginHookFireAndForget).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("can defer the user-created hook until an invitation owner claim succeeds", async () => {
|
||||
const createdAt = new Date("2026-07-15T11:00:00.000Z");
|
||||
dbMock.user.create.mockResolvedValueOnce({
|
||||
id: "user_invited",
|
||||
email: "invited@example.test",
|
||||
defaultTenantId: null,
|
||||
locale: "de",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
await expect(
|
||||
register({
|
||||
email: "invited@example.test",
|
||||
password: "password",
|
||||
firstName: "Invite",
|
||||
lastName: "Owner",
|
||||
locale: "de",
|
||||
request: new Request("https://app.example.test/invitation/token"),
|
||||
emitCreatedHook: false,
|
||||
})
|
||||
).resolves.toMatchObject({ id: "user_invited", createdAt });
|
||||
|
||||
expect(emitPluginHookFireAndForget).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("loads an email identity by the fail-closed resolver id instead of the caller casing", async () => {
|
||||
const resolvedUser = { id: "resolved_user", email: "mixed@example.test", tenants: [], admin: null };
|
||||
dbMock.user.findUnique.mockImplementationOnce(async (args) => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "resolved_user" });
|
||||
expect(args.where).toEqual({ id: "resolved_user" });
|
||||
expect(args.where).not.toHaveProperty("email");
|
||||
return resolvedUser;
|
||||
});
|
||||
|
||||
await expect(getUserByEmail(" Mixed@Example.Test ")).resolves.toEqual(resolvedUser);
|
||||
|
||||
expect(resolveUserEmailRlsIdentity).toHaveBeenCalledWith(" Mixed@Example.Test ");
|
||||
});
|
||||
|
||||
it("normalizes persisted and returned registration email", async () => {
|
||||
dbMock.user.create.mockImplementationOnce(async ({ data }) => ({
|
||||
...data,
|
||||
createdAt: new Date("2026-07-15T12:00:00.000Z"),
|
||||
}));
|
||||
|
||||
const result = await register({
|
||||
email: " New.Owner@Example.Test ",
|
||||
password: "password",
|
||||
firstName: "New",
|
||||
lastName: "Owner",
|
||||
request: new Request("https://app.example.test/register"),
|
||||
emitCreatedHook: false,
|
||||
});
|
||||
|
||||
expect(dbMock.user.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ email: "new.owner@example.test" }),
|
||||
});
|
||||
expect(result.email).toBe("new.owner@example.test");
|
||||
});
|
||||
});
|
||||
+10
-1
@@ -28,8 +28,17 @@ describe("users db wrapper", () => {
|
||||
});
|
||||
|
||||
test("parallelizes admin user pagination queries", () => {
|
||||
expect(source).toContain("const [items, totalItems] = await Promise.all([");
|
||||
expect(source).toContain("const [userRoots, totalItems] = await Promise.all([");
|
||||
expect(source).toContain("db.user.findMany({");
|
||||
expect(source).toContain("db.user.count({\n where,\n }),");
|
||||
expect(source).toContain("const items = await hydrateAdminUserDetails(userRoots);");
|
||||
});
|
||||
|
||||
test("consumes password-reset state with one conditional update", () => {
|
||||
expect(source).toContain("export async function consumePasswordResetTokenAndUpdatePassword");
|
||||
expect(source).toContain("verifyToken: expectedVerifyToken");
|
||||
expect(source).toContain("equals: expectedVerifyTokenCreatedAt");
|
||||
expect(source).toContain("gt: minimumVerifyTokenCreatedAt");
|
||||
expect(source).toContain("if (result.count !== 1)");
|
||||
});
|
||||
});
|
||||
+496
-254
File diff suppressed because it is too large.
Load diff
@@ -24,11 +24,8 @@ vi.mock("../cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }
|
||||
const testDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const usersSource = readFileSync(path.join(testDir, "users.db.server.ts"), "utf8");
|
||||
const schemaSource = readFileSync(path.join(testDir, "../../../../../prisma/schema/accounts.prisma"), "utf8");
|
||||
const migrationSource = readFileSync(path.join(testDir, "../../../../../prisma/migrations/20260508130000_user_totp_mfa/migration.sql"), "utf8");
|
||||
const recoveryCodesMigrationSource = readFileSync(
|
||||
path.join(testDir, "../../../../../prisma/migrations/20260508133000_user_mfa_recovery_codes/migration.sql"),
|
||||
"utf8"
|
||||
);
|
||||
const baselineSource = readFileSync(path.join(testDir, "../../../../../prisma/migrations/00000000000000_hivegrid_baseline/migration.sql"), "utf8");
|
||||
const userTableSource = baselineSource.match(/CREATE TABLE public\."User" \([\s\S]*?\n\);/)?.[0] ?? "";
|
||||
|
||||
describe("user TOTP MFA storage contract", () => {
|
||||
beforeEach(() => {
|
||||
@@ -38,28 +35,30 @@ describe("user TOTP MFA storage contract", () => {
|
||||
mockFindUnique.mockReset();
|
||||
});
|
||||
|
||||
test("schema and migration define nullable encrypted TOTP state without defaults", () => {
|
||||
test("schema and baseline define nullable encrypted TOTP state without defaults", () => {
|
||||
expect(schemaSource).toContain("totpSecretEncrypted String?");
|
||||
expect(schemaSource).toContain("totpPendingSecretEncrypted String?");
|
||||
expect(schemaSource).toContain("totpEnabledAt DateTime?");
|
||||
expect(schemaSource).toContain("totpPendingCreatedAt DateTime?");
|
||||
|
||||
for (const column of ["totpSecretEncrypted", "totpPendingSecretEncrypted", "totpEnabledAt", "totpPendingCreatedAt"]) {
|
||||
expect(migrationSource).toContain(`ADD COLUMN "${column}"`);
|
||||
expect(userTableSource).toMatch(new RegExp(`"${column}"\\s+(?:text|timestamp\\(3\\) without time zone),`, "i"));
|
||||
}
|
||||
expect(migrationSource).not.toMatch(/NOT NULL|DEFAULT|otpauth|secret_fixture|totp-secret/i);
|
||||
expect(userTableSource).not.toMatch(/"totp(?:SecretEncrypted|PendingSecretEncrypted|EnabledAt|PendingCreatedAt)"[^,]*(?:NOT NULL|DEFAULT)/i);
|
||||
expect(userTableSource).not.toMatch(/otpauth|secret_fixture|totp-secret/i);
|
||||
});
|
||||
|
||||
test("schema and migration define nullable hashed recovery-code state without plaintext fixtures", () => {
|
||||
test("schema and baseline define nullable hashed recovery-code state without plaintext fixtures", () => {
|
||||
expect(schemaSource).toContain("mfaRecoveryCodeHashes Json?");
|
||||
expect(schemaSource).toContain("mfaRecoveryCodesGeneratedAt DateTime?");
|
||||
expect(schemaSource).toContain("mfaRecoveryCodeLastUsedAt DateTime?");
|
||||
expect(schemaSource).not.toMatch(/recoveryCodesPlaintext|recoveryCodePlaintext|mfaRecoveryCodePlain|mfaRecoveryCodesPlain/i);
|
||||
|
||||
for (const column of ["mfaRecoveryCodeHashes", "mfaRecoveryCodesGeneratedAt", "mfaRecoveryCodeLastUsedAt"]) {
|
||||
expect(recoveryCodesMigrationSource).toContain(`ADD COLUMN "${column}"`);
|
||||
expect(userTableSource).toMatch(new RegExp(`"${column}"\\s+(?:jsonb|timestamp\\(3\\) without time zone),`, "i"));
|
||||
}
|
||||
expect(recoveryCodesMigrationSource).not.toMatch(/NOT NULL|DEFAULT|\b[A-Z0-9]{4}-[A-Z0-9]{4}\b|plaintext|plain text|secret_fixture|recovery-code-secret/i);
|
||||
expect(userTableSource).not.toMatch(/"mfaRecoveryCode(?:Hashes|sGeneratedAt|LastUsedAt)"[^,]*(?:NOT NULL|DEFAULT)/i);
|
||||
expect(userTableSource).not.toMatch(/\b[A-Z0-9]{4}-[A-Z0-9]{4}\b|plaintext|plain text|secret_fixture|recovery-code-secret/i);
|
||||
});
|
||||
|
||||
test("generic getUser select omits encrypted TOTP fields and recovery-code hashes", () => {
|
||||
@@ -89,6 +88,31 @@ describe("user TOTP MFA storage contract", () => {
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("user:user_1");
|
||||
});
|
||||
|
||||
test("clearUserTotpPendingSecret only clears the expected pending enrollment", async () => {
|
||||
const { clearUserTotpPendingSecret } = await import("./users.db.server");
|
||||
const { clearCacheKey } = await import("../cache.server");
|
||||
const pendingCreatedAt = new Date("2026-05-08T13:00:00.000Z");
|
||||
mockUpdateMany.mockResolvedValueOnce({ count: 1 });
|
||||
|
||||
await clearUserTotpPendingSecret("user_1", {
|
||||
totpPendingSecretEncrypted: "encrypted-pending-secret",
|
||||
totpPendingCreatedAt: pendingCreatedAt,
|
||||
});
|
||||
|
||||
expect(mockUpdateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "user_1",
|
||||
totpPendingSecretEncrypted: "encrypted-pending-secret",
|
||||
totpPendingCreatedAt: pendingCreatedAt,
|
||||
},
|
||||
data: {
|
||||
totpPendingSecretEncrypted: null,
|
||||
totpPendingCreatedAt: null,
|
||||
},
|
||||
});
|
||||
expect(clearCacheKey).toHaveBeenCalledWith("user:user_1");
|
||||
});
|
||||
|
||||
test("activateUserTotpPendingSecret promotes pending secret, clears pending fields, and clears cache", async () => {
|
||||
const { activateUserTotpPendingSecret } = await import("./users.db.server");
|
||||
const { clearCacheKey } = await import("../cache.server");
|
||||
|
||||
Reference in new issue
Block a user