Skip to content

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

feat(api-keys): independently gate project and organization presets (#18419)

Mark Salpeter787f6890b23f
diff --git a/.env.prod.example b/.env.prod.example
index 703aad6b68..4a0e66de6e 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -253,6 +253,9 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# Auth migration: legacy (default) | shadow | enforce
# API_AUTH_MIGRATION=
+# Expose API key role selection per scope (default false). Only active with API_AUTH_MIGRATION=enforce.
+# API_KEY_PROJECT_ROLES_ENABLE=false
+# API_KEY_ORG_ROLES_ENABLE=false
# LANGFUSE_CACHE_PROMPT_ENABLED=
# LANGFUSE_CACHE_PROMPT_TTL_SECONDS=
diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts
index 950849fac8..f99e34e342 100644
--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts
+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts
@@ -23,10 +23,25 @@ import { randomUUID } from "crypto";
vi.mock("@/src/env.mjs", async (importOriginal) => {
const actual = await importOriginal<{ env: typeof env }>();
- return {
- ...actual,
- env: { ...actual.env, API_AUTH_MIGRATION: "enforce" },
- };
+ return { ...actual, env: { ...actual.env } };
+});
+
+const originalRoleConfig = {
+ API_AUTH_MIGRATION: env.API_AUTH_MIGRATION,
+ API_KEY_ORG_ROLES_ENABLE: env.API_KEY_ORG_ROLES_ENABLE,
+ API_KEY_PROJECT_ROLES_ENABLE: env.API_KEY_PROJECT_ROLES_ENABLE,
+};
+
+beforeEach(() => {
+ Object.assign(env, {
+ API_AUTH_MIGRATION: "enforce",
+ API_KEY_ORG_ROLES_ENABLE: "false",
+ API_KEY_PROJECT_ROLES_ENABLE: "false",
+ });
+});
+
+afterEach(() => {
+ Object.assign(env, originalRoleConfig);
});
describe("organization API keys trpc", () => {
@@ -591,6 +606,7 @@ describe("organization API keys trpc", () => {
// expands that owner to the project-kind wildcard, so a project-capable role
// reaches every project of the org rather than a chosen subset.
it("creates an org key that reaches every project via the project wildcard", async () => {
+ Object.assign(env, { API_KEY_ORG_ROLES_ENABLE: "true" });
const orgId = `org-${randomUUID()}`;
await prisma.organization.create({ data: { id: orgId, name: "Scoped" } });
@@ -607,47 +623,100 @@ describe("organization API keys trpc", () => {
expect(projectResources).toContain(ProjectId("*"));
});
- it("rejects a legacy role under enforce", async () => {
- const orgId = `org-${randomUUID()}`;
- await prisma.organization.create({ data: { id: orgId, name: "Scoped" } });
-
- await expect(
- ownerCallerForOrg(orgId).organizationApiKeys.create({
- orgId,
- role: "LEGACY_ORGANIZATION_API_KEY",
- }),
- ).rejects.toMatchObject({ code: "BAD_REQUEST" });
-
- await expect(prisma.apiKey.count({ where: { orgId } })).resolves.toBe(0);
- });
-
- it("accepts only the LEGACY_ORGANIZATION_API_KEY role when enforce is off", async () => {
- const orgId = `org-${randomUUID()}`;
- await prisma.organization.create({ data: { id: orgId, name: "Scoped" } });
-
- const originalMigration = (env as { API_AUTH_MIGRATION: string })
- .API_AUTH_MIGRATION;
- (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION = "legacy";
- try {
- await expect(
- ownerCallerForOrg(orgId).organizationApiKeys.create({
- orgId,
- role: "ADMIN",
- }),
- ).rejects.toMatchObject({ code: "BAD_REQUEST" });
-
+ it.each([
+ "ADMIN",
+ "VIEWER",
+ "INGEST",
+ "SCORES_INGEST",
+ "AI_GATEWAY",
+ ] as const)(
+ "creates an organization key with %s when role selection is enabled",
+ async (role) => {
+ Object.assign(env, { API_KEY_ORG_ROLES_ENABLE: "true" });
+ const orgId = `org-${randomUUID()}`;
+ await prisma.organization.create({
+ data: { id: orgId, name: "Scoped" },
+ });
const key = await ownerCallerForOrg(orgId).organizationApiKeys.create({
orgId,
- role: "LEGACY_ORGANIZATION_API_KEY",
+ role,
+ });
+ expect(
+ await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ }),
+ ).toMatchObject({ systemRole: role, ownerOrgId: orgId });
+ },
+ );
+
+ describe.each([
+ { migration: "legacy", enabled: "false" },
+ { migration: "legacy", enabled: "true" },
+ { migration: "shadow", enabled: "false" },
+ { migration: "shadow", enabled: "true" },
+ { migration: "enforce", enabled: "false" },
+ { migration: "enforce", enabled: "true" },
+ ])(
+ "role creation with $migration and exposure $enabled",
+ ({ migration, enabled }) => {
+ beforeEach(() => {
+ Object.assign(env, {
+ API_AUTH_MIGRATION: migration,
+ API_KEY_ORG_ROLES_ENABLE: enabled,
+ API_KEY_PROJECT_ROLES_ENABLE: "true",
+ });
});
- const roleIds = (await getRolesForPrincipal(ApiKeyId(key.id))).map(
- (role) => role.id,
+
+ it.each([{}, { role: undefined }, { role: null }])(
+ "defaults %j to the legacy role",
+ async (input) => {
+ const orgId = `org-${randomUUID()}`;
+ await prisma.organization.create({
+ data: { id: orgId, name: "Scoped" },
+ });
+ const key = await ownerCallerForOrg(
+ orgId,
+ ).organizationApiKeys.create({ orgId, ...input });
+ expect(
+ await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ }),
+ ).toMatchObject({
+ systemRole: "LEGACY_ORGANIZATION_API_KEY",
+ ownerOrgId: orgId,
+ });
+ },
);
- expect(roleIds).toContain(SystemRoleId("LEGACY_ORGANIZATION_API_KEY"));
- } finally {
- (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION =
- originalMigration;
- }
- });
+
+ it("rejects explicit legacy, empty, invalid and disabled roles without creating keys", async () => {
+ const orgId = `org-${randomUUID()}`;
+ await prisma.organization.create({
+ data: { id: orgId, name: "Scoped" },
+ });
+ const caller = ownerCallerForOrg(orgId);
+ const rejectedRoles = [
+ "LEGACY_PROJECT_API_KEY",
+ "LEGACY_ORGANIZATION_API_KEY",
+ "",
+ "OWNER",
+ "invalid",
+ ];
+ if (migration !== "enforce" || enabled === "false")
+ rejectedRoles.push(
+ "ADMIN",
+ "VIEWER",
+ "INGEST",
+ "SCORES_INGEST",
+ "AI_GATEWAY",
+ );
+ for (const role of rejectedRoles) {
+ await expect(
+ caller.organizationApiKeys.create({ orgId, role: role as never }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ }
+ expect(await prisma.apiKey.count({ where: { orgId } })).toBe(0);
+ });
+ },
+ );
});
});
diff --git a/web/src/__tests__/server/organizations-api.servertest.ts b/web/src/__tests__/server/organizations-api.servertest.ts
index 09529ac46a..368d999098 100644
--- a/web/src/__tests__/server/organizations-api.servertest.ts
+++ b/web/src/__tests__/server/organizations-api.servertest.ts
@@ -674,11 +674,16 @@ describe("Admin Organizations API", () => {
name: "Named key",
},
{ label: "null", role: null, expiresAt: null, name: "Named key" },
- { label: "empty", role: "", expiresAt: undefined, name: "" },
{
- label: "explicit legacy",
+ label: "omitted with empty name",
+ role: undefined,
+ expiresAt: undefined,
+ name: "",
+ },
+ {
+ label: "null with expiration",
name: undefined,
- role: "LEGACY_ORGANIZATION_API_KEY",
+ role: null,
expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
},
])(
@@ -747,6 +752,11 @@ describe("Admin Organizations API", () => {
{ label: "past expiration", body: { expiresAt: "2000-01-01T00:00:00Z" } },
{ label: "invalid expiration", body: { expiresAt: "not-a-date" } },
{ label: "numeric expiration", body: { expiresAt: 4_102_444_800_000 } },
+ { label: "empty role", body: { role: "" } },
+ {
+ label: "explicit legacy role",
+ body: { role: "LEGACY_ORGANIZATION_API_KEY" },
+ },
{
label: "wrong-scope legacy role",
body: { role: "LEGACY_PROJECT_API_KEY" },
diff --git a/web/src/__tests__/server/project-api-key-trpc.servertest.ts b/web/src/__tests__/server/project-api-key-trpc.servertest.ts
index 6f8f2c3c13..d25ba570c6 100644
--- a/web/src/__tests__/server/project-api-key-trpc.servertest.ts
+++ b/web/src/__tests__/server/project-api-key-trpc.servertest.ts
@@ -13,10 +13,25 @@ import { randomUUID } from "crypto";
vi.mock("@/src/env.mjs", async (importOriginal) => {
const actual = await importOriginal<{ env: typeof env }>();
- return {
- ...actual,
- env: { ...actual.env, API_AUTH_MIGRATION: "enforce" },
- };
+ return { ...actual, env: { ...actual.env } };
+});
+
+const originalRoleConfig = {
+ API_AUTH_MIGRATION: env.API_AUTH_MIGRATION,
+ API_KEY_PROJECT_ROLES_ENABLE: env.API_KEY_PROJECT_ROLES_ENABLE,
+ API_KEY_ORG_ROLES_ENABLE: env.API_KEY_ORG_ROLES_ENABLE,
+};
+
+beforeEach(() => {
+ Object.assign(env, {
+ API_AUTH_MIGRATION: "enforce",
+ API_KEY_PROJECT_ROLES_ENABLE: "false",
+ API_KEY_ORG_ROLES_ENABLE: "false",
+ });
+});
+
+afterEach(() => {
+ Object.assign(env, originalRoleConfig);
});
describe("project API keys trpc", () => {
@@ -130,6 +145,11 @@ describe("project API keys trpc", () => {
});
expect(dbKey.createdByUserId).toBe("user-1");
expect(dbKey.createdByApiKeyId).toBeNull();
+ expect(
+ await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: apiKeyResult.id },
+ }),
+ ).toMatchObject({ systemRole: "LEGACY_PROJECT_API_KEY" });
expect(dbKey.scope).toBe("PROJECT");
expect(dbKey.projectId).toBe(projectId);
expect(dbKey.orgId).toBeNull();
@@ -172,6 +192,7 @@ describe("project API keys trpc", () => {
// org-only AI Gateway role) would grant nothing on the project it is
// scoped to, so it is not among the roles the create input accepts.
it("rejects an organization-only role on a project key", async () => {
+ Object.assign(env, { API_KEY_PROJECT_ROLES_ENABLE: "true" });
const { caller, projectId } = await createProjectCaller();
await expect(
@@ -189,51 +210,81 @@ describe("project API keys trpc", () => {
).resolves.toBe(0);
});
- it("creates a project key with a project-capable role", async () => {
- const { caller, projectId } = await createProjectCaller();
-
- const key = await caller.projectApiKeys.create({
- projectId,
- name: "viewer project key",
- role: "VIEWER",
- });
-
- const assignment = await prisma.roleAssignment.findFirstOrThrow({
- where: { principalApiKeyId: key.id },
- });
- expect(assignment.systemRole).toBe("VIEWER");
- expect(assignment.ownerProjectId).toBe(projectId);
- });
-
- it("accepts only the LEGACY_PROJECT_API_KEY role when enforce is off", async () => {
- const { caller, projectId } = await createProjectCaller();
-
- const originalMigration = (env as { API_AUTH_MIGRATION: string })
- .API_AUTH_MIGRATION;
- (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION = "legacy";
- try {
- await expect(
- caller.projectApiKeys.create({
- projectId,
- name: "normal role off enforce",
- role: "VIEWER",
- }),
- ).rejects.toMatchObject({ code: "BAD_REQUEST" });
-
- const key = await caller.projectApiKeys.create({
- projectId,
- name: "legacy role off enforce",
- role: "LEGACY_PROJECT_API_KEY",
- });
+ it.each(["ADMIN", "VIEWER", "INGEST", "SCORES_INGEST"] as const)(
+ "creates a project key with %s when role selection is enabled",
+ async (role) => {
+ Object.assign(env, { API_KEY_PROJECT_ROLES_ENABLE: "true" });
+ const { caller, projectId } = await createProjectCaller();
+ const key = await caller.projectApiKeys.create({ projectId, role });
const assignment = await prisma.roleAssignment.findFirstOrThrow({
where: { principalApiKeyId: key.id },
});
- expect(assignment.systemRole).toBe("LEGACY_PROJECT_API_KEY");
- } finally {
- (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION =
- originalMigration;
- }
- });
+ expect(assignment.systemRole).toBe(role);
+ expect(assignment.ownerProjectId).toBe(projectId);
+ },
+ );
+
+ describe.each([
+ { migration: "legacy", enabled: "false" },
+ { migration: "legacy", enabled: "true" },
+ { migration: "shadow", enabled: "false" },
+ { migration: "shadow", enabled: "true" },
+ { migration: "enforce", enabled: "false" },
+ { migration: "enforce", enabled: "true" },
+ ])(
+ "role creation with $migration and exposure $enabled",
+ ({ migration, enabled }) => {
+ beforeEach(() => {
+ Object.assign(env, {
+ API_AUTH_MIGRATION: migration,
+ API_KEY_PROJECT_ROLES_ENABLE: enabled,
+ API_KEY_ORG_ROLES_ENABLE: "true",
+ });
+ });
+
+ it.each([{}, { role: undefined }, { role: null }])(
+ "defaults %j to the legacy role",
+ async (input) => {
+ const { caller, projectId } = await createProjectCaller();
+ const key = await caller.projectApiKeys.create({
+ projectId,
+ ...input,
+ });
+ expect(
+ await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ }),
+ ).toMatchObject({
+ systemRole: "LEGACY_PROJECT_API_KEY",
+ ownerProjectId: projectId,
+ });
+ },
+ );
+
+ it("rejects explicit legacy, empty, invalid and disabled roles without creating keys", async () => {
+ const { caller, projectId } = await createProjectCaller();
+ const before = await prisma.apiKey.count({ where: { projectId } });
+ const rejectedRoles = [
+ "LEGACY_PROJECT_API_KEY",
+ "LEGACY_ORGANIZATION_API_KEY",
+ "",
+ "OWNER",
+ "AI_GATEWAY",
+ "invalid",
+ ];
+ if (migration !== "enforce" || enabled === "false")
+ rejectedRoles.push("ADMIN", "VIEWER", "INGEST", "SCORES_INGEST");
+ for (const role of rejectedRoles) {
+ await expect(
+ caller.projectApiKeys.create({ projectId, role: role as never }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ }
+ expect(await prisma.apiKey.count({ where: { projectId } })).toBe(
+ before,
+ );
+ });
+ },
+ );
});
describe("projectApiKeys.updateName", () => {
diff --git a/web/src/__tests__/server/projects-api.servertest.ts b/web/src/__tests__/server/projects-api.servertest.ts
index 840560c964..fd813ebb2b 100644
--- a/web/src/__tests__/server/projects-api.servertest.ts
+++ b/web/src/__tests__/server/projects-api.servertest.ts
@@ -20,6 +20,16 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
import projectApiKeysHandler from "@/src/pages/api/public/projects/[projectId]/apiKeys";
import projectApiKeyHandler from "@/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId]";
+import {
+ organizationApiKeyCreationSchema,
+ projectApiKeyCreationSchema,
+} from "@/src/ee/features/admin-api/server/apiKeys";
+import { env } from "@/src/env.mjs";
+
+vi.mock("@/src/env.mjs", async (importOriginal) => {
+ const actual = await importOriginal<{ env: typeof env }>();
+ return { ...actual, env: { ...actual.env } };
+});
// Schema for project response
const ProjectResponseSchema = z.object({
@@ -94,6 +104,99 @@ const ApiKeyDeletionResponseSchema = z.object({
success: z.boolean(),
});
+describe("REST API key creation schemas", () => {
+ const originalFlags = {
+ API_AUTH_MIGRATION: env.API_AUTH_MIGRATION,
+ API_KEY_PROJECT_ROLES_ENABLE: env.API_KEY_PROJECT_ROLES_ENABLE,
+ API_KEY_ORG_ROLES_ENABLE: env.API_KEY_ORG_ROLES_ENABLE,
+ };
+
+ afterEach(() => {
+ Object.assign(env, originalFlags);
+ });
+
+ describe.each([
+ {
+ scope: "project",
+ schema: projectApiKeyCreationSchema,
+ legacyRole: "LEGACY_PROJECT_API_KEY",
+ roles: ["ADMIN", "VIEWER", "INGEST", "SCORES_INGEST"],
+ invalidRoles: [
+ "LEGACY_PROJECT_API_KEY",
+ "LEGACY_ORGANIZATION_API_KEY",
+ "AI_GATEWAY",
+ "OWNER",
+ "",
+ "INVALID",
+ [],
+ ],
+ },
+ {
+ scope: "organization",
+ schema: organizationApiKeyCreationSchema,
+ legacyRole: "LEGACY_ORGANIZATION_API_KEY",
+ roles: ["ADMIN", "VIEWER", "INGEST", "SCORES_INGEST", "AI_GATEWAY"],
+ invalidRoles: [
+ "LEGACY_PROJECT_API_KEY",
+ "LEGACY_ORGANIZATION_API_KEY",
+ "OWNER",
+ "",
+ "INVALID",
+ [],
+ ],
+ },
+ ])("$scope", ({ scope, schema, legacyRole, roles, invalidRoles }) => {
+ describe.each([
+ { migration: "legacy", projectEnabled: "true", orgEnabled: "true" },
+ { migration: "shadow", projectEnabled: "true", orgEnabled: "true" },
+ { migration: "enforce", projectEnabled: "false", orgEnabled: "false" },
+ { migration: "enforce", projectEnabled: "true", orgEnabled: "false" },
+ { migration: "enforce", projectEnabled: "false", orgEnabled: "true" },
+ { migration: "enforce", projectEnabled: "true", orgEnabled: "true" },
+ ])(
+ "$migration, project roles $projectEnabled, organization roles $orgEnabled",
+ ({ migration, projectEnabled, orgEnabled }) => {
+ beforeEach(() => {
+ Object.assign(env, {
+ API_AUTH_MIGRATION: migration,
+ API_KEY_PROJECT_ROLES_ENABLE: projectEnabled,
+ API_KEY_ORG_ROLES_ENABLE: orgEnabled,
+ });
+ });
+
+ it.each([
+ { label: "omitted", body: {} },
+ { label: "undefined", body: { role: undefined } },
+ { label: "null", body: { role: null } },
+ ])("defaults $label role to the stored legacy role", ({ body }) => {
+ expect(schema.parse(body).role).toBe(legacyRole);
+ });
+
+ it.each(roles)("gates %s on role exposure", (role) => {
+ const result = schema.safeParse({ role });
+
+ const rolesEnabled =
+ migration === "enforce" &&
+ (scope === "project" ? projectEnabled : orgEnabled) === "true";
+ if (rolesEnabled) {
+ expect(result.success).toBe(true);
+ expect(result.data?.role).toBe(role);
+ } else {
+ expect(result.success).toBe(false);
+ }
+ });
+
+ it.each(invalidRoles.map((role) => ({ role })))(
+ "rejects role $role",
+ ({ role }) => {
+ expect(schema.safeParse({ role }).success).toBe(false);
+ },
+ );
+ },
+ );
+ });
+});
+
describe("Projects API", () => {
// Test variables
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -884,11 +987,16 @@ describe("Projects API", () => {
name: "Named key",
},
{ label: "null", role: null, expiresAt: null, name: "Named key" },
- { label: "empty", role: "", expiresAt: undefined, name: "" },
{
- label: "explicit legacy",
+ label: "omitted with empty name",
+ role: undefined,
+ expiresAt: undefined,
+ name: "",
+ },
+ {
+ label: "null with expiration",
name: undefined,
- role: "LEGACY_PROJECT_API_KEY",
+ role: null,
expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
},
])(
@@ -958,6 +1066,11 @@ describe("Projects API", () => {
{ label: "past expiration", body: { expiresAt: "2000-01-01T00:00:00Z" } },
{ label: "invalid expiration", body: { expiresAt: "not-a-date" } },
{ label: "numeric expiration", body: { expiresAt: 4_102_444_800_000 } },
+ { label: "empty role", body: { role: "" } },
+ {
+ label: "explicit legacy role",
+ body: { role: "LEGACY_PROJECT_API_KEY" },
+ },
{
label: "wrong-scope legacy role",
body: { role: "LEGACY_ORGANIZATION_API_KEY" },
diff --git a/web/src/ee/features/admin-api/server/apiKeys.ts b/web/src/ee/features/admin-api/server/apiKeys.ts
index bed50299de..047f330adc 100644
--- a/web/src/ee/features/admin-api/server/apiKeys.ts
+++ b/web/src/ee/features/admin-api/server/apiKeys.ts
@@ -2,6 +2,8 @@ import { z } from "zod/v4";
import { type SystemRole } from "@langfuse/shared/src/db";
+import { apiKeyCreationRoleSchema } from "@/src/features/public-api/server/apiKeyCreationRoleSchema";
+
const apiKeyCreationFields = {
name: z.string().optional(),
note: z.string().optional(),
@@ -16,18 +18,12 @@ const apiKeyCreationFields = {
export const organizationApiKeyCreationSchema = z.object({
...apiKeyCreationFields,
- role: z
- .enum(["LEGACY_ORGANIZATION_API_KEY", ""])
- .nullish()
- .transform((role) => role || "LEGACY_ORGANIZATION_API_KEY"),
+ role: apiKeyCreationRoleSchema("organization"),
});
export const projectApiKeyCreationSchema = z.object({
...apiKeyCreationFields,
- role: z
- .enum(["LEGACY_PROJECT_API_KEY", ""])
- .nullish()
- .transform((role) => role || "LEGACY_PROJECT_API_KEY"),
+ role: apiKeyCreationRoleSchema("project"),
publicKey: z.string().optional(),
secretKey: z.string().optional(),
});
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 9a228d4b45..9d9ca3332c 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -404,6 +404,8 @@ export const env = createEnv({
API_AUTH_MIGRATION: z
.enum(["legacy", "shadow", "enforce"])
.default("legacy"),
+ API_KEY_PROJECT_ROLES_ENABLE: z.enum(["true", "false"]).default("false"),
+ API_KEY_ORG_ROLES_ENABLE: z.enum(["true", "false"]).default("false"),
// Multimodal media upload to S3
LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH: z.coerce
@@ -1122,6 +1124,8 @@ export const env = createEnv({
LANGFUSE_AI_GATEWAY_CACHE_RESOLVE_TTL_SECONDS:
process.env.LANGFUSE_AI_GATEWAY_CACHE_RESOLVE_TTL_SECONDS,
API_AUTH_MIGRATION: process.env.API_AUTH_MIGRATION,
+ API_KEY_PROJECT_ROLES_ENABLE: process.env.API_KEY_PROJECT_ROLES_ENABLE,
+ API_KEY_ORG_ROLES_ENABLE: process.env.API_KEY_ORG_ROLES_ENABLE,
LANGFUSE_ALLOWED_ORGANIZATION_CREATORS:
process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
diff --git a/web/src/features/apiKey/authenticatorCache.ts b/web/src/features/apiKey/authenticatorCache.ts
index 955a84e62d..ec4cc6e360 100644
--- a/web/src/features/apiKey/authenticatorCache.ts
+++ b/web/src/features/apiKey/authenticatorCache.ts
@@ -8,12 +8,12 @@ import {
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
+import { type Credential } from "@/src/features/apiKey/helpers/parseAuthorizationHeader";
import {
type ApiKeyAuthResults,
type Authenticated,
} from "@/src/features/apiKey/authenticator";
import { matchesAdminApiKey } from "@/src/features/apiKey/helpers/matchesAdminApiKey";
-import { type Credential } from "@/src/features/apiKey/helpers/parseAuthorizationHeader";
import { type AuthorizationContext } from "@/src/features/auth/policy/types";
/** AuthenticatorCache stores authorization contexts by credential. */
@@ -39,24 +39,6 @@ export class AuthenticatorCache {
}
}
- /** keyFor derives credential cache keys, excluding environment admins. */
- private keyFor(credential: Credential): string | null {
- if (credential.kind === "basic") {
- return createAuthzContextCacheKey(
- "basic",
- createShaHash(credential.secretKey, this.salt),
- );
- }
- if (credential.kind === "bearer") {
- if (matchesAdminApiKey(credential.token, this.adminApiKey)) return null;
- return createAuthzContextCacheKey(
- "bearer",
- createShaHash(credential.token, this.salt),
- );
- }
- return null;
- }
-
/** set caches database-key successes until their TTL or expiry. */
async set(
credential: Credential,
@@ -85,6 +67,24 @@ export class AuthenticatorCache {
return false;
}
}
+
+ /** keyFor derives credential cache keys, excluding environment admins. */
+ private keyFor(credential: Credential): string | null {
+ if (credential.kind === "basic") {
+ return createAuthzContextCacheKey(
+ "basic",
+ createShaHash(credential.secretKey, this.salt),
+ );
+ }
+ if (credential.kind === "bearer") {
+ if (matchesAdminApiKey(credential.token, this.adminApiKey)) return null;
+ return createAuthzContextCacheKey(
+ "bearer",
+ createShaHash(credential.token, this.salt),
+ );
+ }
+ return null;
+ }
}
/** cacheEnabled is the shared on/off switch for the context cache, reusing the legacy api-key cache flag. */
diff --git a/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx b/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx
index 9920d18abc..dbb820b6c0 100644
--- a/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx
+++ b/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx
@@ -12,7 +12,8 @@ const sessionWithRoleSelection = {
environment: {
enableExperimentalFeatures: false,
selfHostedInstancePlan: null,
- apiKeyRoleSelectionEnabled: true,
+ apiKeyProjectRoleSelectionEnabled: true,
+ apiKeyOrgRoleSelectionEnabled: true,
},
} as unknown as Session;
diff --git a/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx b/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
index 5bdbd87311..8e95861898 100644
--- a/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
+++ b/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
@@ -5,7 +5,6 @@ import { useSession } from "next-auth/react";
import { type SystemRole } from "@langfuse/shared/src/db";
import {
apiKeyRolesForScope,
- legacyApiKeyRoleForScope,
systemRoleAccessRights,
} from "@langfuse/shared/rbac";
@@ -45,7 +44,7 @@ const DEFAULT_ROLE: SystemRole = "ADMIN";
/** ApiKeyCreateValues is the resolved create-form payload the button forwards to the create mutation. */
export type ApiKeyCreateValues = {
name: string;
- role: SystemRole;
+ role?: SystemRole;
expiresAt: Date | null;
};
@@ -100,7 +99,9 @@ function ApiKeyCreateForm({
const roles = apiKeyRolesForScope(scope);
const { data: session } = useSession();
const roleSelectionEnabled =
- session?.environment?.apiKeyRoleSelectionEnabled ?? false;
+ (scope === "project"
+ ? session?.environment?.apiKeyProjectRoleSelectionEnabled
+ : session?.environment?.apiKeyOrgRoleSelectionEnabled) ?? false;
const [name, setName] = useState("");
const [role, setRole] = useState<SystemRole>(DEFAULT_ROLE);
@@ -125,7 +126,7 @@ function ApiKeyCreateForm({
if (submitDisabled) return;
onSubmit({
name: name.trim(),
- role: roleSelectionEnabled ? role : legacyApiKeyRoleForScope(scope),
+ ...(roleSelectionEnabled ? { role } : {}),
expiresAt,
});
};
diff --git a/web/src/features/public-api/components/CreateApiKeyButton.tsx b/web/src/features/public-api/components/CreateApiKeyButton.tsx
index 1f61998382..3fcf2fe455 100644
--- a/web/src/features/public-api/components/CreateApiKeyButton.tsx
+++ b/web/src/features/public-api/components/CreateApiKeyButton.tsx
@@ -48,7 +48,7 @@ export function CreateApiKeyButton(props: {
.mutateAsync({
projectId: props.entityId,
name: values.name || undefined,
- role: values.role,
+ ...(values.role === undefined ? {} : { role: values.role }),
expiresAt: values.expiresAt,
})
.then(({ secretKey, publicKey }) => {
@@ -64,7 +64,7 @@ export function CreateApiKeyButton(props: {
.mutateAsync({
orgId: props.entityId,
name: values.name || undefined,
- role: values.role,
+ ...(values.role === undefined ? {} : { role: values.role }),
expiresAt: values.expiresAt,
})
.then(({ secretKey, publicKey }) => {
diff --git a/web/src/features/public-api/server/apiKeyCreationRoleSchema.ts b/web/src/features/public-api/server/apiKeyCreationRoleSchema.ts
new file mode 100644
index 0000000000..2b76212d0e
--- /dev/null
+++ b/web/src/features/public-api/server/apiKeyCreationRoleSchema.ts
@@ -0,0 +1,24 @@
+import { z } from "zod/v4";
+
+import {
+ apiKeyRolesForScope,
+ legacyApiKeyRoleForScope,
+} from "@langfuse/shared/rbac";
+
+import { env } from "@/src/env.mjs";
+
+export function apiKeyCreationRoleSchema(scope: "project" | "organization") {
+ return z
+ .enum(apiKeyRolesForScope(scope))
+ .nullish()
+ .refine(
+ (role) =>
+ role == null ||
+ (env.API_AUTH_MIGRATION === "enforce" &&
+ (scope === "project"
+ ? env.API_KEY_PROJECT_ROLES_ENABLE
+ : env.API_KEY_ORG_ROLES_ENABLE) === "true"),
+ { message: "API key role selection is not enabled" },
+ )
+ .transform((role) => role ?? legacyApiKeyRoleForScope(scope));
+}
diff --git a/web/src/features/public-api/server/assertApiKeyRoleForMigration.ts b/web/src/features/public-api/server/assertApiKeyRoleForMigration.ts
deleted file mode 100644
index ff44ff8f21..0000000000
--- a/web/src/features/public-api/server/assertApiKeyRoleForMigration.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { InvalidRequestError } from "@langfuse/shared";
-import { isLegacyApiKeyRole } from "@langfuse/shared/rbac";
-import { type SystemRole } from "@langfuse/shared/src/db";
-
-import { env } from "@/src/env.mjs";
-
-/** assertApiKeyRoleForMigration rejects a role the active migration mode will not honor. */
-export function assertApiKeyRoleForMigration(role: SystemRole): void {
- const enforce = env.API_AUTH_MIGRATION === "enforce";
- if (enforce && isLegacyApiKeyRole(role)) {
- throw new InvalidRequestError(
- `Legacy role ${role} cannot be assigned to a new API key`,
- );
- }
- if (!enforce && !isLegacyApiKeyRole(role)) {
- throw new InvalidRequestError(
- `Role ${role} cannot be assigned until API key authorization is enforced`,
- );
- }
-}
diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.ts
index 2bdefc8657..b8155d03ba 100644
--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts
+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts
@@ -10,20 +10,8 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { redis } from "@langfuse/shared/src/server";
import { LangfuseNotFoundError } from "@langfuse/shared";
import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
-import {
- apiKeyRolesAcceptedForScope,
- OrganizationId,
- SystemRoleId,
- UserId,
-} from "@langfuse/shared/rbac";
-import { SystemRole } from "@langfuse/shared/src/db";
-
-import { assertApiKeyRoleForMigration } from "@/src/features/public-api/server/assertApiKeyRoleForMigration";
-
-const organizationApiKeyRoles = apiKeyRolesAcceptedForScope("organization") as [
- SystemRole,
- ...SystemRole[],
-];
+import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
+import { apiKeyCreationRoleSchema } from "@/src/features/public-api/server/apiKeyCreationRoleSchema";
export const organizationApiKeysRouter = createTRPCRouter({
byOrganizationId: protectedOrganizationProcedure
@@ -78,7 +66,7 @@ export const organizationApiKeysRouter = createTRPCRouter({
z.object({
orgId: z.string(),
name: z.string().optional(),
- role: z.enum(organizationApiKeyRoles).default(SystemRole.ADMIN),
+ role: apiKeyCreationRoleSchema("organization"),
expiresAt: z
.date()
.nullish()
@@ -102,8 +90,6 @@ export const organizationApiKeysRouter = createTRPCRouter({
orgId: input.orgId,
});
- assertApiKeyRoleForMigration(input.role);
-
const apiKeyMeta = await createApiKey(ctx.prisma, {
owner: OrganizationId(input.orgId),
role: SystemRoleId(input.role),
diff --git a/web/src/features/public-api/server/projectApiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.ts
index a02ab13c2f..0e5ac152d9 100644
--- a/web/src/features/public-api/server/projectApiKeyRouter.ts
+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts
@@ -9,20 +9,8 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { redis } from "@langfuse/shared/src/server";
import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
import { LangfuseNotFoundError, StringNoHTML } from "@langfuse/shared";
-import {
- apiKeyRolesAcceptedForScope,
- ProjectId,
- SystemRoleId,
- UserId,
-} from "@langfuse/shared/rbac";
-import { SystemRole } from "@langfuse/shared/src/db";
-
-import { assertApiKeyRoleForMigration } from "@/src/features/public-api/server/assertApiKeyRoleForMigration";
-
-const projectApiKeyRoles = apiKeyRolesAcceptedForScope("project") as [
- SystemRole,
- ...SystemRole[],
-];
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
+import { apiKeyCreationRoleSchema } from "@/src/features/public-api/server/apiKeyCreationRoleSchema";
export const projectApiKeysRouter = createTRPCRouter({
byProjectId: protectedProjectProcedure
@@ -77,7 +65,7 @@ export const projectApiKeysRouter = createTRPCRouter({
z.object({
projectId: z.string(),
name: StringNoHTML.optional(),
- role: z.enum(projectApiKeyRoles).default(SystemRole.ADMIN),
+ role: apiKeyCreationRoleSchema("project"),
expiresAt: z
.date()
.nullish()
@@ -93,8 +81,6 @@ export const projectApiKeysRouter = createTRPCRouter({
scope: "apiKeys:CUD",
});
- assertApiKeyRoleForMigration(input.role);
-
const apiKeyMeta = await createApiKey(ctx.prisma, {
owner: ProjectId(input.projectId),
role: SystemRoleId(input.role),
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index e0a39b9b78..46a61bc089 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -867,7 +867,12 @@ export async function getAuthOptions(signupAttribution?: {
// If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)
selfHostedInstancePlan: getSelfHostedInstancePlanServerSide(),
v4WriteMode,
- apiKeyRoleSelectionEnabled: env.API_AUTH_MIGRATION === "enforce",
+ apiKeyProjectRoleSelectionEnabled:
+ env.API_AUTH_MIGRATION === "enforce" &&
+ env.API_KEY_PROJECT_ROLES_ENABLE === "true",
+ apiKeyOrgRoleSelectionEnabled:
+ env.API_AUTH_MIGRATION === "enforce" &&
+ env.API_KEY_ORG_ROLES_ENABLE === "true",
},
user:
dbUser !== null
diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.ts
index 15f1588d45..42ed5434aa 100644
--- a/web/types/next-auth.d.ts
+++ b/web/types/next-auth.d.ts
@@ -78,9 +78,9 @@ declare module "next-auth" {
// Optional so existing session mocks need not set it; the real session
// callback always populates it.
v4WriteMode?: "legacy" | "dual" | "events_only";
- // Whether API key creation offers per-key role selection (API_AUTH_MIGRATION=enforce).
- // Optional so existing session mocks need not set it.
- apiKeyRoleSelectionEnabled?: boolean;
+ // Role selection requires API_AUTH_MIGRATION=enforce and the scope's rollout flag.
+ apiKeyProjectRoleSelectionEnabled?: boolean;
+ apiKeyOrgRoleSelectionEnabled?: boolean;
};
}