Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(eslint): restrict ApiKey and RoleAssignment creates to their services (#19142)

Mark Salpeter3ca812771c89
diff --git a/packages/config-eslint/shared.js b/packages/config-eslint/shared.js
index 166e411d17..81e92ff6d0 100644
--- a/packages/config-eslint/shared.js
+++ b/packages/config-eslint/shared.js
@@ -4,6 +4,14 @@ import tseslint from "typescript-eslint";
import langfusePlugin from "@repo/eslint-plugin";
import "eslint-plugin-only-warn";
+// Files allowed to create each Prisma model's rows; globs match trailing path segments.
+const prismaWriters = {
+ apiKey: ["packages/shared/src/server/auth/apiKeys.ts"],
+ roleAssignment: [
+ "packages/shared/src/features/rbac/roleAssignmentService.ts",
+ ],
+};
+
export default [
{
name: "langfuse/shared/ignores",
@@ -35,6 +43,7 @@ export default [
"no-unneeded-ternary": "warn",
"no-nested-ternary": "error",
"@repo/no-exotic-operators": "warn",
+ "@repo/no-restricted-prisma-writes": ["error", { models: prismaWriters }],
},
},
diff --git a/packages/eslint-plugin/src/index.ts b/packages/eslint-plugin/src/index.ts
index 00e49ac390..446b24f14e 100644
--- a/packages/eslint-plugin/src/index.ts
+++ b/packages/eslint-plugin/src/index.ts
@@ -3,6 +3,7 @@ import { default as componentFileStructure } from "./rules/component-file-struct
import { default as noArbitraryColors } from "./rules/no-arbitrary-colors.js";
import { default as noAbstractedOverlayTrigger } from "./rules/no-abstracted-overlay-trigger.js";
import { default as noInSourceVitest } from "./rules/no-in-source-vitest.js";
+import { default as noRestrictedPrismaWrites } from "./rules/no-restricted-prisma-writes.js";
import { default as noExoticOperators } from "./rules/no-exotic-operators.js";
import { default as noUnescapedPrismaLikePattern } from "./rules/no-unescaped-prisma-like-pattern.js";
import { default as noMarginOnRootElements } from "./rules/no-margin-on-root-elements.js";
@@ -31,6 +32,7 @@ const plugin = {
"no-null-render": noNullRender,
"no-let-assign-in-react": noLetAssignInReact,
"no-overlay-zindex": noOverlayZindex,
+ "no-restricted-prisma-writes": noRestrictedPrismaWrites,
"no-raw-font-weight": noRawFontWeight,
"no-style-props": noStyleProps,
"no-switch-statements": noSwitchStatements,
diff --git a/packages/eslint-plugin/src/rules/no-restricted-prisma-writes.test.ts b/packages/eslint-plugin/src/rules/no-restricted-prisma-writes.test.ts
new file mode 100644
index 0000000000..eaf4206b2a
--- /dev/null
+++ b/packages/eslint-plugin/src/rules/no-restricted-prisma-writes.test.ts
@@ -0,0 +1,174 @@
+import { RuleTester } from "@typescript-eslint/rule-tester";
+import * as typescriptEslintParser from "@typescript-eslint/parser";
+import rule from "./no-restricted-prisma-writes.js";
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ parser: typescriptEslintParser,
+ parserOptions: {
+ ecmaVersion: 2022,
+ sourceType: "module",
+ },
+ },
+});
+
+const options = [
+ {
+ models: {
+ apiKey: ["packages/shared/src/server/auth/apiKeys.ts"],
+ roleAssignment: ["rbac/roleAssignmentService.ts", "*.servertest.ts"],
+ membership: ["*.test.ts"],
+ },
+ },
+] satisfies [object];
+
+/** restricted builds the expected report for a create on a restricted model */
+function restricted(model: string, method: string, writers: string) {
+ return {
+ messageId: "restricted" as const,
+ data: { model, method, writers },
+ };
+}
+
+ruleTester.run("no-restricted-prisma-writes", rule, {
+ valid: [
+ `await prisma.apiKey.create({ data });`,
+ { code: `await prisma.apiKey.findUnique({ where: { id } });`, options },
+ { code: `await prisma.apiKey.update({ where: { id }, data });`, options },
+ { code: `await prisma.apiKey.deleteMany({ where });`, options },
+ { code: `await prisma.project.create({ data });`, options },
+ { code: `await apiKey.create({ data });`, options },
+ { code: `const create = prisma.apiKey.create;`, options },
+ { code: `await prisma.apiKey[method]({ data });`, options },
+ { code: `await prisma[model].create({ data });`, options },
+ { code: `await prisma.apiKey[0]({ data });`, options },
+ { code: `await createFn()({ data });`, options },
+ {
+ code: `await prisma.apiKey.create({ data });`,
+ filename:
+ "/repo/.claude/worktrees/x/packages/shared/src/server/auth/apiKeys.ts",
+ options,
+ },
+ {
+ code: `await tx.roleAssignment.create({ data });`,
+ filename:
+ "C:\\repo\\packages\\shared\\src\\features\\rbac\\roleAssignmentService.ts",
+ options,
+ },
+ {
+ code: `await prisma.roleAssignment.create({ data });`,
+ filename: "/repo/web/src/__tests__/server/roles.servertest.ts",
+ options: [{ models: { roleAssignment: ["*.servertest.ts"] } }],
+ },
+ ],
+ invalid: [
+ {
+ code: `await prisma.apiKey.create({ data });`,
+ options,
+ errors: [
+ restricted(
+ "apiKey",
+ "create",
+ "packages/shared/src/server/auth/apiKeys.ts",
+ ),
+ ],
+ },
+ {
+ code: `await tx.apiKey.upsert({ where, create, update });`,
+ options,
+ errors: [
+ restricted(
+ "apiKey",
+ "upsert",
+ "packages/shared/src/server/auth/apiKeys.ts",
+ ),
+ ],
+ },
+ {
+ code: `await this.db.apiKey.createMany({ data: [] });`,
+ options,
+ errors: [
+ restricted(
+ "apiKey",
+ "createMany",
+ "packages/shared/src/server/auth/apiKeys.ts",
+ ),
+ ],
+ },
+ {
+ code: `await prisma["apiKey"]["createManyAndReturn"]({ data });`,
+ options,
+ errors: [
+ restricted(
+ "apiKey",
+ "createManyAndReturn",
+ "packages/shared/src/server/auth/apiKeys.ts",
+ ),
+ ],
+ },
+ {
+ code: `await prisma?.apiKey?.create({ data });`,
+ options,
+ errors: [
+ restricted(
+ "apiKey",
+ "create",
+ "packages/shared/src/server/auth/apiKeys.ts",
+ ),
+ ],
+ },
+ {
+ code: `await (prisma?.apiKey.create)!({ data });`,
+ options,
+ errors: [
+ restricted(
+ "apiKey",
+ "create",
+ "packages/shared/src/server/auth/apiKeys.ts",
+ ),
+ ],
+ },
+ {
+ code: `await prisma.apiKey!.create({ data });`,
+ filename: "/repo/web/src/server/auth/apiKeys.ts",
+ options,
+ errors: [
+ restricted(
+ "apiKey",
+ "create",
+ "packages/shared/src/server/auth/apiKeys.ts",
+ ),
+ ],
+ },
+ {
+ code: `await tx.roleAssignment.create({ data });`,
+ filename: "/repo/packages/shared/src/server/auth/apiKeys.ts",
+ options,
+ errors: [
+ restricted("roleAssignment", "create", "rbac/roleAssignmentService.ts"),
+ ],
+ },
+ {
+ code: `await prisma.roleAssignment.create({ data });`,
+ options: [
+ {
+ models: {
+ roleAssignment: ["a/roleAssignmentService.ts", "b/seed.ts"],
+ },
+ },
+ ],
+ errors: [
+ restricted(
+ "roleAssignment",
+ "create",
+ "a/roleAssignmentService.ts or b/seed.ts",
+ ),
+ ],
+ },
+ {
+ code: `await prisma.membership.create({ data });`,
+ options,
+ errors: [restricted("membership", "create", "an allowed file")],
+ },
+ ],
+});
diff --git a/packages/eslint-plugin/src/rules/no-restricted-prisma-writes.ts b/packages/eslint-plugin/src/rules/no-restricted-prisma-writes.ts
new file mode 100644
index 0000000000..b40b372cee
--- /dev/null
+++ b/packages/eslint-plugin/src/rules/no-restricted-prisma-writes.ts
@@ -0,0 +1,131 @@
+import { matchesGlob } from "node:path";
+import { type TSESTree } from "@typescript-eslint/utils";
+
+import { createRule } from "../util.js";
+
+const createMethods = new Set([
+ "create",
+ "createMany",
+ "createManyAndReturn",
+ "upsert",
+]);
+
+const globCharacters = /[*?[\]{}]/;
+
+/** rule flags Prisma creates on configured models outside the files allowed to write them */
+const rule = createRule<[Options], "restricted">({
+ name: "no-restricted-prisma-writes",
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Disallow Prisma creates on configured models outside their allowed files.",
+ },
+ messages: {
+ restricted:
+ "Do not call {{model}}.{{method}} directly; create {{model}} rows through {{writers}}.",
+ },
+ schema: [
+ {
+ type: "object",
+ properties: {
+ models: {
+ type: "object",
+ additionalProperties: { type: "array", items: { type: "string" } },
+ },
+ },
+ additionalProperties: false,
+ },
+ ],
+ },
+ defaultOptions: [{ models: {} }],
+ create(context, [{ models }]) {
+ const restricted = new Map(
+ Object.entries(models).filter(
+ ([, allow]) => !isAllowed(allow, context.filename),
+ ),
+ );
+ if (restricted.size === 0) return {};
+
+ return {
+ CallExpression(node) {
+ const call = modelCall(node.callee);
+ if (call === undefined || !createMethods.has(call.method)) return;
+
+ const allow = restricted.get(call.model);
+ if (allow === undefined) return;
+
+ context.report({
+ node,
+ messageId: "restricted",
+ data: { ...call, writers: writers(allow) },
+ });
+ },
+ };
+ },
+});
+
+export default rule;
+
+/** isAllowed reports whether a trailing run of the linted file's path segments matches an allow glob */
+function isAllowed(allow: string[], filename: string): boolean {
+ const suffixes = pathSuffixes(filename);
+ return allow.some((glob) =>
+ suffixes.some((suffix) => matchesGlob(suffix, glob)),
+ );
+}
+
+/** pathSuffixes lists every trailing run of path segments, e.g. `a/b/c` → `a/b/c`, `b/c`, `c` */
+function pathSuffixes(filename: string): string[] {
+ const segments = filename.split(/[\\/]/);
+ return segments.map((_, index) => segments.slice(index).join("/"));
+}
+
+/** writers names the literal allowed files for the report, leaving out wildcard exemptions like test globs */
+function writers(allow: string[]): string {
+ const files = allow.filter((glob) => !globCharacters.test(glob));
+ if (files.length === 0) return "an allowed file";
+ return files.join(" or ");
+}
+
+/** modelCall reads `<client>.<model>.<method>` from a call's callee */
+function modelCall(callee: TSESTree.Expression): ModelCall | undefined {
+ const call = unwrapChain(callee);
+ if (call.type !== "MemberExpression") return undefined;
+ const method = propertyName(call);
+ if (method === undefined) return undefined;
+
+ const delegate = unwrapChain(call.object);
+ if (delegate.type !== "MemberExpression") return undefined;
+ const model = propertyName(delegate);
+ if (model === undefined) return undefined;
+
+ return { model, method };
+}
+
+/** unwrapChain strips optional-chain and non-null wrappers around an expression */
+function unwrapChain(node: TSESTree.Expression): TSESTree.Expression {
+ if (node.type === "ChainExpression") return unwrapChain(node.expression);
+ if (node.type === "TSNonNullExpression") return unwrapChain(node.expression);
+ return node;
+}
+
+/** propertyName reads a member's static property name for `a.b` and `a["b"]` */
+function propertyName(node: TSESTree.MemberExpression): string | undefined {
+ if (!node.computed && node.property.type === "Identifier") {
+ return node.property.name;
+ }
+ if (
+ node.computed &&
+ node.property.type === "Literal" &&
+ typeof node.property.value === "string"
+ ) {
+ return node.property.value;
+ }
+ return undefined;
+}
+
+/** Options maps each restricted Prisma model to the file globs allowed to create its rows */
+type Options = { models: Record<string, string[]> };
+
+type ModelCall = { model: string; method: string };
diff --git a/packages/shared/scripts/seeder/load-seed-clickhouse.ts b/packages/shared/scripts/seeder/load-seed-clickhouse.ts
index 52fc204f11..b6793d1474 100644
--- a/packages/shared/scripts/seeder/load-seed-clickhouse.ts
+++ b/packages/shared/scripts/seeder/load-seed-clickhouse.ts
@@ -1,13 +1,7 @@
import { randomUUID } from "crypto";
import { prisma } from "../../src/db";
+import { createApiKey, logger } from "../../src/server";
import {
- createLegacySecretKeyPlaceholder,
- getDisplaySecretKey,
- logger,
-} from "../../src/server";
-import { assignRole } from "../../src/features/rbac/roleAssignmentService";
-import {
- ApiKeyId,
OrganizationId,
ProjectId,
SystemRoleId,
@@ -44,7 +38,7 @@ const prepareProjectsAndApiKeys = async (
},
});
- const project = await prisma.project.upsert({
+ await prisma.project.upsert({
where: { id: projectId },
update: {},
create: {
@@ -54,35 +48,17 @@ const prepareProjectsAndApiKeys = async (
},
});
- const apiKeyId = `api-key-${projectId}`;
- const apiKeyExists = await prisma.apiKey.findUnique({
- where: { id: apiKeyId },
+ const name = `API Key for ${projectId}`;
+ const apiKeyExists = await prisma.apiKey.findFirst({
+ where: { projectId, note: name },
});
if (!apiKeyExists) {
- const sk = `sk-lf-${randomUUID()}`;
- await prisma.$transaction(async (tx) => {
- await tx.apiKey.create({
- data: {
- id: apiKeyId,
- note: `API Key for ${projectId}`,
- publicKey: `pk-${Math.random().toString(36).slice(2, 11)}`,
- hashedSecretKey: createLegacySecretKeyPlaceholder(),
- displaySecretKey: getDisplaySecretKey(sk),
- scope: "PROJECT",
- project: {
- connect: {
- id: projectId,
- },
- },
- },
- });
- await assignRole(tx, {
- tenantId: OrganizationId(project.orgId),
- principalId: ApiKeyId(apiKeyId),
- roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
- ownerId: ProjectId(projectId),
- tags: [],
- });
+ await createApiKey(prisma, {
+ tenant: OrganizationId(orgId),
+ scope: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: "system",
+ name,
});
}
});
diff --git a/packages/shared/src/features/rbac/roleAssignmentService.ts b/packages/shared/src/features/rbac/roleAssignmentService.ts
index a3d6e6d28f..02362aeb5b 100644
--- a/packages/shared/src/features/rbac/roleAssignmentService.ts
+++ b/packages/shared/src/features/rbac/roleAssignmentService.ts
@@ -32,15 +32,15 @@ export async function getRoleAssignmentsForPrincipal(
export async function assignRole(
prisma: Prisma.TransactionClient,
ra: Omit<RoleAssignment, "id" | "createdAt" | "updatedAt">,
-): Promise<void> {
+): Promise<StoredRoleAssignment> {
const roleFields = validateRole(ra.roleId);
- await withTransaction(prisma, async (tx) => {
+ return await withTransaction(prisma, async (tx) => {
const ownerAndTenantFields = await validateTenancy(
tx,
ra.tenantId,
ra.ownerId,
);
- await tx.roleAssignment.create({
+ return await tx.roleAssignment.create({
data: {
...ownerAndTenantFields,
...principalFields(ra.principalId),
diff --git a/packages/shared/src/server/test-utils/org-factory.ts b/packages/shared/src/server/test-utils/org-factory.ts
index 8748c62c48..3f8d615089 100644
--- a/packages/shared/src/server/test-utils/org-factory.ts
+++ b/packages/shared/src/server/test-utils/org-factory.ts
@@ -1,15 +1,12 @@
import { v4 } from "uuid";
import { prisma } from "../../db";
-import { env } from "../../env";
import {
- ApiKeyId,
OrganizationId,
ProjectId,
SystemRoleId,
} from "../../features/rbac/types";
import { CloudConfigSchema } from "../../interfaces/cloudConfigSchema";
-import { assignRole } from "../../features/rbac/roleAssignmentService";
-import { createShaHash, getDisplaySecretKey } from "../auth/apiKeys";
+import { createApiKey } from "../auth/apiKeys";
export function createBasicAuthHeader(
username: string,
@@ -46,40 +43,13 @@ export const createOrgProjectAndApiKey = async (
orgId: org.id,
},
});
- const publicKey = `pk-lf-${v4()}`;
- const secretKey = `sk-lf-${v4()}`;
- const salt = env.SALT;
- if (!salt) {
- throw new Error("SALT is not set");
- }
-
- const auth = createBasicAuthHeader(publicKey, secretKey);
- const apiKeyRowId = v4();
- await prisma.$transaction(async (tx) => {
- await tx.apiKey.create({
- data: {
- id: apiKeyRowId,
- projectId: projectId,
- publicKey: publicKey,
- // Test fixtures use the modern fast-hash auth path. Avoid bcrypt here as
- // cost-11 hashing adds ~100ms per fixture; keep the legacy hash unique to
- // satisfy the database constraint without affecting authentication.
- hashedSecretKey: `test-hashed-secret-key-${v4()}`,
- fastHashedSecretKey: createShaHash(secretKey, salt),
- displaySecretKey: getDisplaySecretKey(secretKey),
- scope: "PROJECT",
- },
- });
-
- // Give the fixture key its legacy project permissions.
- await assignRole(tx, {
- tenantId: OrganizationId(org.id),
- principalId: ApiKeyId(apiKeyRowId),
- roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
- ownerId: ProjectId(projectId),
- tags: [],
- });
+ const { publicKey, secretKey } = await createApiKey(prisma, {
+ tenant: OrganizationId(org.id),
+ scope: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: "system",
});
+ const auth = createBasicAuthHeader(publicKey, secretKey);
return { projectId, orgId: org.id, publicKey, secretKey, auth, org, project };
};
diff --git a/web/src/__tests__/server/admin-api-key-auth.servertest.ts b/web/src/__tests__/server/admin-api-key-auth.servertest.ts
index 354c7aa42d..b7fad33af1 100644
--- a/web/src/__tests__/server/admin-api-key-auth.servertest.ts
+++ b/web/src/__tests__/server/admin-api-key-auth.servertest.ts
@@ -75,6 +75,7 @@ describe("Admin API Key Authentication", () => {
const publicKey = `pk-org-key-${timestamp}`;
const secretKey = `sk-org-key-${timestamp}`;
+ // eslint-disable-next-line @repo/no-restricted-prisma-writes -- needs a project-scoped key without a projectId, which createApiKey never produces.
await prisma.apiKey.create({
data: {
id: uniqueId,
diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.ts
index 5cdd480cfe..2e00adff41 100644
--- a/web/src/__tests__/server/api-auth.servertest.ts
+++ b/web/src/__tests__/server/api-auth.servertest.ts
@@ -264,6 +264,7 @@ describe("Authenticate API calls", () => {
it("should fail on wrong api key without new key", async () => {
const legacySecretKey = ["legacy", "secret", "key"].join("-");
const legacyPublicKey = `legacy-public-key-${v4()}`;
+ // eslint-disable-next-line @repo/no-restricted-prisma-writes -- needs a bcrypt-only legacy key, which createApiKey never produces.
await prisma.apiKey.create({
data: {
id: v4(),
@@ -539,6 +540,7 @@ describe("Authenticate API calls", () => {
legacyPublicKey,
legacySecretKey,
);
+ // eslint-disable-next-line @repo/no-restricted-prisma-writes -- needs a bcrypt-only legacy key, which createApiKey never produces.
await prisma.apiKey.create({
data: {
id: v4(),
diff --git a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
index a3006a5546..6af491785d 100644
--- a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
+++ b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
@@ -2,11 +2,19 @@ import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";
import { LLMAdapter, type Plan, Role } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
+ createApiKey,
createApiKeyCacheKey,
AUTHZ_CONTEXT_CACHE_KEY_PREFIX,
createAuthzContextCacheKey,
createShaHash,
} from "@langfuse/shared/src/server";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
+import { assignRole } from "@langfuse/shared/rbac/server";
import type { Session } from "next-auth";
import { v4 as uuidv4 } from "uuid";
import {
@@ -99,19 +107,13 @@ function cacheKeysFor({
}
async function seedOrgScopedKey(orgId: string) {
- const suffix = uuidv4().slice(0, 8);
- const fastHash = `fh-${suffix}`;
- const publicKey = `pk-lf-${suffix}`;
- await prisma.apiKey.create({
- data: {
- orgId,
- scope: "ORGANIZATION",
- publicKey,
- hashedSecretKey: `hsk-${suffix}`,
- fastHashedSecretKey: fastHash,
- displaySecretKey: `sk-...${suffix}`,
- },
+ const { publicKey, secretKey } = await createApiKey(prisma, {
+ tenant: OrganizationId(orgId),
+ scope: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: "system",
});
+ const fastHash = createShaHash(secretKey, env.SALT!);
const keys = cacheKeysFor({ fastHash, publicKey });
for (const key of keys) {
await setRedisValue(redis, key, "1");
@@ -402,16 +404,12 @@ describe("API-key cache invalidation on project/org lifecycle", () => {
const keys = await seedOrgScopedKey(orgId);
const user = await createUserInOrgs([orgId]);
- const assignment = await prisma.roleAssignment.create({
- data: {
- orgId,
- userId: user.id,
- principalId: `user/${user.id}`,
- projectId,
- ownerId: `project/${projectId}`,
- systemRole: "VIEWER",
- roleId: "system/VIEWER",
- },
+ const assignment = await assignRole(prisma, {
+ tenantId: OrganizationId(orgId),
+ ownerId: ProjectId(projectId),
+ principalId: UserId(user.id),
+ roleId: SystemRoleId("VIEWER"),
+ tags: [],
});
const res = makeRes();
diff --git a/web/src/__tests__/server/organizations-api.servertest.ts b/web/src/__tests__/server/organizations-api.servertest.ts
index b9eed88c66..9bccb0c6ce 100644
--- a/web/src/__tests__/server/organizations-api.servertest.ts
+++ b/web/src/__tests__/server/organizations-api.servertest.ts
@@ -581,15 +581,12 @@ describe("Admin Organizations API", () => {
testOrgId = org.id;
// Create a test API key for the organization
- await prisma.apiKey.create({
- data: {
- orgId: testOrgId,
- publicKey: `pk-lf-test-${randomUUID()}`,
- hashedSecretKey: "hashed-secret",
- displaySecretKey: "sk-lf-test...1234",
- note: "Test API Key",
- scope: "ORGANIZATION",
- },
+ await createApiKey(prisma, {
+ tenant: OrganizationId(testOrgId),
+ scope: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: "system",
+ name: "Test API Key",
});
});
@@ -623,7 +620,7 @@ describe("Admin Organizations API", () => {
expect(response.body.apiKeys[0]).toMatchObject({
name: "Test API Key",
note: "Test API Key",
- role: null,
+ role: "LEGACY_ORGANIZATION_API_KEY",
});
});
@@ -855,15 +852,12 @@ describe("Admin Organizations API", () => {
testOrgId = org.id;
// Create a test API key for the organization
- const apiKey = await prisma.apiKey.create({
- data: {
- orgId: testOrgId,
- publicKey: `pk-lf-test-${randomUUID()}`,
- hashedSecretKey: "hashed-secret",
- displaySecretKey: "sk-lf-test...1234",
- note: "Test API Key",
- scope: "ORGANIZATION",
- },
+ const apiKey = await createApiKey(prisma, {
+ tenant: OrganizationId(testOrgId),
+ scope: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: "system",
+ name: "Test API Key",
});
testApiKeyId = apiKey.id;
});
diff --git a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts
index 94643794fe..443fbfa15f 100644
--- a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts
+++ b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts
@@ -20,7 +20,10 @@ import {
SystemRoleId,
UserId,
} from "@langfuse/shared/rbac";
-import { getRoleAssignmentsForPrincipal } from "@langfuse/shared/rbac/server";
+import {
+ assignRole,
+ getRoleAssignmentsForPrincipal,
+} from "@langfuse/shared/rbac/server";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
@@ -204,16 +207,12 @@ describe("projectsRouter system role assignments", () => {
}),
).resolves.toBe(1);
- const assignment = await prisma.roleAssignment.create({
- data: {
- orgId,
- userId: user.id,
- principalId: `user/${user.id}`,
- projectId,
- ownerId: `project/${projectId}`,
- systemRole: "VIEWER",
- roleId: "system/VIEWER",
- },
+ const assignment = await assignRole(prisma, {
+ tenantId: OrganizationId(orgId),
+ ownerId: ProjectId(projectId),
+ principalId: UserId(user.id),
+ roleId: SystemRoleId("VIEWER"),
+ tags: [],
});
await caller.projects.delete({ projectId });
diff --git a/web/src/__tests__/server/roleAssignmentService.servertest.ts b/web/src/__tests__/server/roleAssignmentService.servertest.ts
index 24ceae5606..584b6a4e03 100644
--- a/web/src/__tests__/server/roleAssignmentService.servertest.ts
+++ b/web/src/__tests__/server/roleAssignmentService.servertest.ts
@@ -154,16 +154,12 @@ async function addUserAssignment(orgId: string, projectId: string) {
const user = await prisma.user.create({
data: { email: `${v4()}@example.com` },
});
- const assignment = await prisma.roleAssignment.create({
- data: {
- orgId,
- userId: user.id,
- principalId: UserId(user.id),
- projectId,
- ownerId: ProjectId(projectId),
- systemRole: "VIEWER",
- roleId: SystemRoleId("VIEWER"),
- },
+ const assignment = await assignRole(prisma, {
+ tenantId: OrganizationId(orgId),
+ ownerId: ProjectId(projectId),
+ principalId: UserId(user.id),
+ roleId: SystemRoleId("VIEWER"),
+ tags: [],
});
return { ...assignment, userId: user.id };
}
@@ -485,6 +481,7 @@ describe("role assignment foreign keys", () => {
};
await expect(
+ // eslint-disable-next-line @repo/no-restricted-prisma-writes -- writes a row with a dangling foreign key, which assignRole rejects before the database sees it.
prisma.roleAssignment.create({ data }),
).rejects.toMatchObject({
code: "P2003",
@@ -544,11 +541,18 @@ describe("role assignment foreign keys", () => {
}[invalidShape];
await expect(
+ // eslint-disable-next-line @repo/no-restricted-prisma-writes -- writes a malformed row, which assignRole rejects before the database sees it.
prisma.roleAssignment.create({
data: { ...validData, ...invalidFields },
}),
).rejects.toThrow(/check constraint/);
- const assignment = await prisma.roleAssignment.create({ data: validData });
+ const assignment = await assignRole(prisma, {
+ tenantId: OrganizationId(orgId),
+ ownerId: ProjectId(projectId),
+ principalId: UserId(user.id),
+ roleId: SystemRoleId("VIEWER"),
+ tags: [],
+ });
await expect(
prisma.roleAssignment.update({
where: { id: assignment.id },
diff --git a/web/src/__tests__/server/shadowAuth.servertest.ts b/web/src/__tests__/server/shadowAuth.servertest.ts
index 6eeacaf32c..267330e3b5 100644
--- a/web/src/__tests__/server/shadowAuth.servertest.ts
+++ b/web/src/__tests__/server/shadowAuth.servertest.ts
@@ -4,17 +4,21 @@ import { type NextApiRequest } from "next";
import { prisma } from "@langfuse/shared/src/db";
import {
+ createApiKey,
createBasicAuthHeader,
createOrgProjectAndApiKey,
createShaHash,
getDisplaySecretKey,
} from "@langfuse/shared/src/server";
import {
+ ApiKeyId,
OrganizationId,
ProjectId,
+ SystemRoleId,
type OrganizationAction,
type ProjectAction,
} from "@langfuse/shared/rbac";
+import { assignRole } from "@langfuse/shared/rbac/server";
import { env } from "@/src/env.mjs";
import { authorize } from "@/src/features/rbac/authorize";
@@ -137,29 +141,11 @@ const scopeOf = (result: ShadowResult): Record<string, unknown> => {
};
const createOrgApiKey = async (targetOrgId: string) => {
- const publicKey = `pk-lf-${randomUUID()}`;
- const secretKey = `sk-lf-${randomUUID()}`;
- const apiKeyRowId = randomUUID();
- await prisma.apiKey.create({
- data: {
- id: apiKeyRowId,
- orgId: targetOrgId,
- publicKey,
- hashedSecretKey: `test-hashed-secret-key-${randomUUID()}`,
- fastHashedSecretKey: createShaHash(secretKey, env.SALT as string),
- displaySecretKey: getDisplaySecretKey(secretKey),
- scope: "ORGANIZATION",
- },
- });
- await prisma.roleAssignment.create({
- data: {
- orgId: targetOrgId,
- apiKeyId: apiKeyRowId,
- principalId: `apiKey/${apiKeyRowId}`,
- systemRole: "LEGACY_ORGANIZATION_API_KEY",
- roleId: "system/LEGACY_ORGANIZATION_API_KEY",
- ownerId: `organization/${targetOrgId}`,
- },
+ const { publicKey, secretKey } = await createApiKey(prisma, {
+ tenant: OrganizationId(targetOrgId),
+ scope: OrganizationId(targetOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: "system",
});
return createBasicAuthHeader(publicKey, secretKey);
};
@@ -189,6 +175,7 @@ const ownedProjectIds = (context: AuthorizationContext): string[] =>
const createUnassignedApiKey = async (scope: "PROJECT" | "ORGANIZATION") => {
const publicKey = `pk-lf-${randomUUID()}`;
const secretKey = `sk-lf-${randomUUID()}`;
+ // eslint-disable-next-line @repo/no-restricted-prisma-writes -- needs a key with no role assignment, which createApiKey always adds.
const apiKey = await prisma.apiKey.create({
data: {
scope,
@@ -273,16 +260,12 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {
it("preserves a narrow assignment instead of restoring a legacy grant", async () => {
const { apiKey, authorization } = await createUnassignedApiKey("PROJECT");
- const assignment = await prisma.roleAssignment.create({
- data: {
- orgId,
- projectId,
- apiKeyId: apiKey.id,
- ownerId: `project/${projectId}`,
- principalId: `apiKey/${apiKey.id}`,
- roleId: "system/SCORES_INGEST",
- systemRole: "SCORES_INGEST",
- },
+ const assignment = await assignRole(prisma, {
+ tenantId: OrganizationId(orgId),
+ ownerId: ProjectId(projectId),
+ principalId: ApiKeyId(apiKey.id),
+ roleId: SystemRoleId("SCORES_INGEST"),
+ tags: [],
});
setMode("enforce");
const result = await shadowAuth({
@@ -526,16 +509,12 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {
it("a project ADMIN key on a project-nested route authorizes only its own project in enforce", async () => {
const { apiKey, authorization } = await createUnassignedApiKey("PROJECT");
- await prisma.roleAssignment.create({
- data: {
- orgId,
- projectId,
- apiKeyId: apiKey.id,
- ownerId: `project/${projectId}`,
- principalId: `apiKey/${apiKey.id}`,
- roleId: "system/ADMIN",
- systemRole: "ADMIN",
- },
+ await assignRole(prisma, {
+ tenantId: OrganizationId(orgId),
+ ownerId: ProjectId(projectId),
+ principalId: ApiKeyId(apiKey.id),
+ roleId: SystemRoleId("ADMIN"),
+ tags: [],
});
const sibling = await prisma.project.create({
data: { orgId, name: `sibling-${randomUUID()}` },