Skip to content

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

feat: add org API keys to organization settings (#6729)

Steffen Schmitz38ed98a76de4
diff --git a/web/src/__tests__/async/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/async/organizations-api-key-trpc.servertest.ts
new file mode 100644
index 0000000000..47dce859e7
--- /dev/null
+++ b/web/src/__tests__/async/organizations-api-key-trpc.servertest.ts
@@ -0,0 +1,232 @@
+/** @jest-environment node */
+/* eslint-disable @typescript-eslint/no-unsafe-member-access */
+
+import type { Session } from "next-auth";
+import { pruneDatabase } from "@/src/__tests__/test-utils";
+import { prisma } from "@langfuse/shared/src/db";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { TRPCError } from "@trpc/server";
+
+describe("organization API keys trpc", () => {
+ const organizationId = "seed-org-id";
+
+ beforeEach(async () => await pruneDatabase());
+
+ const ownerSession: Session = {
+ expires: "1",
+ user: {
+ id: "user-1",
+ canCreateOrganizations: true,
+ name: "Demo User",
+ organizations: [
+ {
+ id: organizationId,
+ name: "Test Organization",
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ projects: [],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ },
+ admin: true,
+ },
+ environment: {} as any,
+ };
+
+ const memberSession: Session = {
+ expires: "1",
+ user: {
+ id: "user-2",
+ canCreateOrganizations: true,
+ name: "Member User",
+ organizations: [
+ {
+ id: organizationId,
+ name: "Test Organization",
+ role: "MEMBER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ projects: [],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ },
+ admin: false,
+ },
+ environment: {} as any,
+ };
+
+ const ownerCtx = createInnerTRPCContext({ session: ownerSession });
+ const ownerCaller = appRouter.createCaller({ ...ownerCtx, prisma });
+
+ const memberCtx = createInnerTRPCContext({ session: memberSession });
+ const memberCaller = appRouter.createCaller({ ...memberCtx, prisma });
+
+ const unAuthedCtx = createInnerTRPCContext({ session: null });
+ const unAuthedCaller = appRouter.createCaller({ ...unAuthedCtx, prisma });
+
+ describe("organizationApiKeys.byOrganizationId", () => {
+ it("owner can fetch organization API keys", async () => {
+ // Create a test API key first
+ const apiKeyResult = await ownerCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "Test API Key",
+ });
+
+ expect(apiKeyResult).toBeDefined();
+ expect(apiKeyResult.secretKey).toBeDefined();
+ expect(apiKeyResult.publicKey).toBeDefined();
+
+ // Now fetch the keys
+ const apiKeys = await ownerCaller.organizationApiKeys.byOrganizationId({
+ orgId: organizationId,
+ });
+
+ expect(apiKeys.length).toBeGreaterThanOrEqual(1);
+ const newKey = apiKeys.find((key) => key.id === apiKeyResult.id);
+ expect(newKey?.note).toBe("Test API Key");
+ expect(newKey?.publicKey).toBe(apiKeyResult.publicKey);
+ expect(newKey?.displaySecretKey).toBeDefined();
+ });
+
+ it("regular member cannot fetch organization API keys", async () => {
+ await expect(
+ memberCaller.organizationApiKeys.byOrganizationId({
+ orgId: organizationId,
+ }),
+ ).rejects.toThrow(TRPCError);
+ });
+
+ it("unauthenticated user cannot fetch organization API keys", async () => {
+ await expect(
+ unAuthedCaller.organizationApiKeys.byOrganizationId({
+ orgId: organizationId,
+ }),
+ ).rejects.toThrow(TRPCError);
+ });
+ });
+
+ describe("organizationApiKeys.create", () => {
+ it("owner can create organization API keys", async () => {
+ const apiKeyResult = await ownerCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "Test API Key",
+ });
+
+ expect(apiKeyResult).toBeDefined();
+ expect(apiKeyResult.secretKey).toBeDefined();
+ expect(apiKeyResult.publicKey).toBeDefined();
+ expect(apiKeyResult.note).toBe("Test API Key");
+ });
+
+ it("regular member cannot create organization API keys", async () => {
+ await expect(
+ memberCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "Test API Key",
+ }),
+ ).rejects.toThrow(TRPCError);
+ });
+
+ it("unauthenticated user cannot create organization API keys", async () => {
+ await expect(
+ unAuthedCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "Test API Key",
+ }),
+ ).rejects.toThrow(TRPCError);
+ });
+ });
+
+ describe("organizationApiKeys.updateNote", () => {
+ it("owner can update API key note", async () => {
+ // Create a key first
+ const apiKeyResult = await ownerCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "Original Note",
+ });
+
+ // Update the note
+ await ownerCaller.organizationApiKeys.updateNote({
+ orgId: organizationId,
+ keyId: apiKeyResult.id,
+ note: "Updated Note",
+ });
+
+ // Fetch to verify
+ const apiKeys = await ownerCaller.organizationApiKeys.byOrganizationId({
+ orgId: organizationId,
+ });
+
+ expect(apiKeys.length).toBeGreaterThanOrEqual(1);
+ const updatedKey = apiKeys.find((key) => key.id === apiKeyResult.id);
+ expect(updatedKey?.note).toBe("Updated Note");
+ });
+
+ it("regular member cannot update API key note", async () => {
+ // Create a key as owner
+ const apiKeyResult = await ownerCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "Original Note",
+ });
+
+ // Try to update as member
+ await expect(
+ memberCaller.organizationApiKeys.updateNote({
+ orgId: organizationId,
+ keyId: apiKeyResult.id,
+ note: "Updated Note",
+ }),
+ ).rejects.toThrow(TRPCError);
+ });
+ });
+
+ describe("organizationApiKeys.delete", () => {
+ it("owner can delete API key", async () => {
+ // Create a key first
+ const apiKeyResult = await ownerCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "To Be Deleted",
+ });
+
+ // Delete the key
+ await ownerCaller.organizationApiKeys.delete({
+ orgId: organizationId,
+ id: apiKeyResult.id,
+ });
+
+ // Verify it's gone
+ const apiKeys = await ownerCaller.organizationApiKeys.byOrganizationId({
+ orgId: organizationId,
+ });
+
+ const deletedKey = apiKeys.find((key) => key.id === apiKeyResult.id);
+ expect(deletedKey).toBeUndefined();
+ });
+
+ it("regular member cannot delete API key", async () => {
+ // Create a key as owner
+ const apiKeyResult = await ownerCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ note: "To Be Deleted",
+ });
+
+ // Try to delete as member
+ await expect(
+ memberCaller.organizationApiKeys.delete({
+ orgId: organizationId,
+ id: apiKeyResult.id,
+ }),
+ ).rejects.toThrow(TRPCError);
+ });
+ });
+});
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 2e7e20aec7..de8082596b 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -174,6 +174,8 @@ const events = {
"send_membership_invitation",
"delete_membership_invitation",
"delete_membership",
+ "api_key_create",
+ "api_key_delete",
"pricing_dialog_opened",
"delete_organization",
],
diff --git a/web/src/features/public-api/components/ApiKeyList.tsx b/web/src/features/public-api/components/ApiKeyList.tsx
index 2763b9a9dd..d60e0c497d 100644
--- a/web/src/features/public-api/components/ApiKeyList.tsx
+++ b/web/src/features/public-api/components/ApiKeyList.tsx
@@ -22,26 +22,48 @@ import {
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { CreateApiKeyButton } from "@/src/features/public-api/components/CreateApiKeyButton";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
import { api } from "@/src/utils/api";
import { DialogDescription } from "@radix-ui/react-dialog";
import { TrashIcon } from "lucide-react";
import { useState } from "react";
import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
+import { startCase } from "lodash";
-export function ApiKeyList(props: { projectId: string }) {
- const hasAccess = useHasProjectAccess({
- projectId: props.projectId,
- scope: "apiKeys:read",
+type ApiKeyScope = "project" | "organization";
+type ApiKeyEntity = { id: string; note: string | null };
+
+export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {
+ const { entityId, scope } = props;
+ if (!entityId) {
+ throw new Error(
+ `${scope}Id is required for ApiKeyList with scope ${scope}`,
+ );
+ }
+
+ const hasProjectAccess = useHasProjectAccess({
+ projectId: props.entityId,
+ scope: "apiKeys:CUD",
+ });
+ const hasOrganizationAccess = useHasOrganizationAccess({
+ organizationId: props.entityId,
+ scope: "organization:CRUD_apiKeys",
});
- const apiKeys = api.projectApiKeys.byProjectId.useQuery(
- {
- projectId: props.projectId,
- },
- {
- enabled: hasAccess,
- },
+ const hasAccess =
+ props.scope === "project" ? hasProjectAccess : hasOrganizationAccess;
+
+ const projectApiKeysQuery = api.projectApiKeys.byProjectId.useQuery(
+ { projectId: entityId },
+ { enabled: hasProjectAccess && props.scope === "project" },
);
+ const organizationApiKeysQuery =
+ api.organizationApiKeys.byOrganizationId.useQuery(
+ { orgId: entityId },
+ { enabled: hasOrganizationAccess && props.scope === "organization" },
+ );
+ const apiKeysQuery =
+ props.scope === "project" ? projectApiKeysQuery : organizationApiKeysQuery;
if (!hasAccess) {
return (
@@ -50,7 +72,7 @@ export function ApiKeyList(props: { projectId: string }) {
<Alert>
<AlertTitle>Access Denied</AlertTitle>
<AlertDescription>
- You do not have permission to view API keys for this project.
+ You do not have permission to view API keys for this {scope}.
</AlertDescription>
</Alert>
</div>
@@ -59,7 +81,16 @@ export function ApiKeyList(props: { projectId: string }) {
return (
<div>
- <Header title="API Keys" />
+ <Header
+ title={startCase(`${scope} API keys`)}
+ help={{
+ description: `Learn more about ${scope} API keys`,
+ href:
+ scope === "project"
+ ? "https://langfuse.com/docs/api#authentication"
+ : "https://langfuse.com/docs/api#org-scoped-routes",
+ }}
+ />
<Card className="mb-4 overflow-hidden">
<Table>
<TableHeader>
@@ -75,14 +106,14 @@ export function ApiKeyList(props: { projectId: string }) {
</TableRow>
</TableHeader>
<TableBody className="text-muted-foreground">
- {apiKeys.data?.length === 0 ? (
+ {apiKeysQuery.data?.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center">
None
</TableCell>
</TableRow>
) : (
- apiKeys.data?.map((apiKey) => (
+ apiKeysQuery.data?.map((apiKey) => (
<TableRow
key={apiKey.id}
className="hover:bg-primary-foreground"
@@ -91,7 +122,11 @@ export function ApiKeyList(props: { projectId: string }) {
{apiKey.createdAt.toLocaleDateString()}
</TableCell>
<TableCell>
- <ApiKeyNote apiKey={apiKey} projectId={props.projectId} />
+ <ApiKeyNote
+ apiKey={apiKey}
+ entityId={entityId}
+ scope={scope}
+ />
</TableCell>
<TableCell className="font-mono">
<CodeView
@@ -107,8 +142,9 @@ export function ApiKeyList(props: { projectId: string }) {
</TableCell> */}
<TableCell>
<DeleteApiKeyButton
- projectId={props.projectId}
+ entityId={entityId}
apiKeyId={apiKey.id}
+ scope={scope}
/>
</TableCell>
</TableRow>
@@ -117,27 +153,75 @@ export function ApiKeyList(props: { projectId: string }) {
</TableBody>
</Table>
</Card>
- <CreateApiKeyButton projectId={props.projectId} />
+ <CreateApiKeyButton entityId={entityId} scope={scope} />
</div>
);
}
// show dialog to let user confirm that this is a destructive action
-function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
+function DeleteApiKeyButton(props: {
+ entityId: string;
+ apiKeyId: string;
+ scope: ApiKeyScope;
+}) {
+ const { entityId, apiKeyId, scope } = props;
const capture = usePostHogClientCapture();
- const hasAccess = useHasProjectAccess({
- projectId: props.projectId,
+
+ const hasProjectAccess = useHasProjectAccess({
+ projectId: props.entityId,
scope: "apiKeys:CUD",
});
+ const hasOrganizationAccess = useHasOrganizationAccess({
+ organizationId: props.entityId,
+ scope: "organization:CRUD_apiKeys",
+ });
+
+ const hasAccess =
+ props.scope === "project" ? hasProjectAccess : hasOrganizationAccess;
const utils = api.useUtils();
- const mutDeleteApiKey = api.projectApiKeys.delete.useMutation({
+
+ const mutDeleteProjectApiKey = api.projectApiKeys.delete.useMutation({
onSuccess: () => utils.projectApiKeys.invalidate(),
});
+ const mutDeleteOrgApiKey = api.organizationApiKeys.delete.useMutation({
+ onSuccess: () => utils.organizationApiKeys.invalidate(),
+ });
+
const [open, setOpen] = useState(false);
if (!hasAccess) return null;
+ const handleDelete = () => {
+ if (scope === "project") {
+ mutDeleteProjectApiKey
+ .mutateAsync({
+ projectId: entityId,
+ id: apiKeyId,
+ })
+ .then(() => {
+ capture(`${scope}_settings:api_key_delete`);
+ setOpen(false);
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ } else {
+ mutDeleteOrgApiKey
+ .mutateAsync({
+ orgId: entityId,
+ id: apiKeyId,
+ })
+ .then(() => {
+ capture(`${scope}_settings:api_key_delete`);
+ setOpen(false);
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }
+ };
+
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
@@ -156,21 +240,10 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
<DialogFooter>
<Button
variant="destructive"
- onClick={() => {
- mutDeleteApiKey
- .mutateAsync({
- projectId: props.projectId,
- id: props.apiKeyId,
- })
- .then(() => {
- capture("project_settings:api_key_delete");
- setOpen(false);
- })
- .catch((error) => {
- console.error(error);
- });
- }}
- loading={mutDeleteApiKey.isLoading}
+ onClick={handleDelete}
+ loading={
+ mutDeleteOrgApiKey.isLoading || mutDeleteProjectApiKey.isLoading
+ }
>
Permanently delete
</Button>
@@ -185,21 +258,32 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
function ApiKeyNote({
apiKey,
- projectId,
+ entityId,
+ scope,
}: {
- apiKey: { id: string; note: string | null };
- projectId: string;
+ apiKey: ApiKeyEntity;
+ entityId: string;
+ scope: ApiKeyScope;
}) {
const utils = api.useUtils();
- const updateNote = api.projectApiKeys.updateNote.useMutation({
- onSuccess: () => {
- utils.projectApiKeys.invalidate();
- },
- });
- const hasEditAccess = useHasProjectAccess({
- projectId,
+
+ const hasProjectAccess = useHasProjectAccess({
+ projectId: entityId,
scope: "apiKeys:CUD",
});
+ const hasOrganizationAccess = useHasOrganizationAccess({
+ organizationId: entityId,
+ scope: "organization:CRUD_apiKeys",
+ });
+ const hasEditAccess =
+ scope === "project" ? hasProjectAccess : hasOrganizationAccess;
+
+ const mutUpdateProjectApiKey = api.projectApiKeys.updateNote.useMutation({
+ onSuccess: () => utils.projectApiKeys.invalidate(),
+ });
+ const mutUpdateOrgApiKey = api.organizationApiKeys.updateNote.useMutation({
+ onSuccess: () => utils.organizationApiKeys.invalidate(),
+ });
const [note, setNote] = useState(apiKey.note ?? "");
const [isEditing, setIsEditing] = useState(false);
@@ -207,11 +291,19 @@ function ApiKeyNote({
const handleBlur = () => {
setIsEditing(false);
if (note !== apiKey.note) {
- updateNote.mutate({
- projectId,
- keyId: apiKey.id,
- note,
- });
+ if (scope === "project") {
+ mutUpdateProjectApiKey.mutate({
+ projectId: entityId,
+ keyId: apiKey.id,
+ note,
+ });
+ } else {
+ mutUpdateOrgApiKey.mutate({
+ orgId: entityId,
+ keyId: apiKey.id,
+ note,
+ });
+ }
}
};
diff --git a/web/src/features/public-api/components/CreateApiKeyButton.tsx b/web/src/features/public-api/components/CreateApiKeyButton.tsx
index b5ec7dad7f..632c702ffe 100644
--- a/web/src/features/public-api/components/CreateApiKeyButton.tsx
+++ b/web/src/features/public-api/components/CreateApiKeyButton.tsx
@@ -10,22 +10,40 @@ import {
} from "@/src/components/ui/dialog";
import { CodeView } from "@/src/components/ui/CodeJsonViewer";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
import { QuickstartExamples } from "@/src/features/public-api/components/QuickstartExamples";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
import { env } from "@/src/env.mjs";
-export function CreateApiKeyButton(props: { projectId: string }) {
+type ApiKeyScope = "project" | "organization";
+
+export function CreateApiKeyButton(props: {
+ entityId: string;
+ scope: ApiKeyScope;
+}) {
const utils = api.useUtils();
const capture = usePostHogClientCapture();
- const hasAccess = useHasProjectAccess({
- projectId: props.projectId,
+
+ const hasProjectAccess = useHasProjectAccess({
+ projectId: props.entityId,
scope: "apiKeys:CUD",
});
+ const hasOrganizationAccess = useHasOrganizationAccess({
+ organizationId: props.entityId,
+ scope: "organization:CRUD_apiKeys",
+ });
+
+ const hasAccess =
+ props.scope === "project" ? hasProjectAccess : hasOrganizationAccess;
- const mutCreateApiKey = api.projectApiKeys.create.useMutation({
+ const mutCreateProjectApiKey = api.projectApiKeys.create.useMutation({
onSuccess: () => utils.projectApiKeys.invalidate(),
});
+ const mutCreateOrgApiKey = api.organizationApiKeys.create.useMutation({
+ onSuccess: () => utils.organizationApiKeys.invalidate(),
+ });
+
const [open, setOpen] = useState(false);
const [generatedKeys, setGeneratedKeys] = useState<{
secretKey: string;
@@ -37,21 +55,39 @@ export function CreateApiKeyButton(props: { projectId: string }) {
setOpen(false);
setGeneratedKeys(null);
} else {
- mutCreateApiKey
- .mutateAsync({
- projectId: props.projectId,
- })
- .then(({ secretKey, publicKey }) => {
- setGeneratedKeys({
- secretKey,
- publicKey,
+ if (props.scope === "project") {
+ mutCreateProjectApiKey
+ .mutateAsync({
+ projectId: props.entityId,
+ })
+ .then(({ secretKey, publicKey }) => {
+ setGeneratedKeys({
+ secretKey,
+ publicKey,
+ });
+ setOpen(true);
+ capture(`${props.scope}_settings:api_key_create`);
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ } else {
+ mutCreateOrgApiKey
+ .mutateAsync({
+ orgId: props.entityId,
+ })
+ .then(({ secretKey, publicKey }) => {
+ setGeneratedKeys({
+ secretKey,
+ publicKey,
+ });
+ setOpen(true);
+ capture(`${props.scope}_settings:api_key_create`);
+ })
+ .catch((error) => {
+ console.error(error);
});
- setOpen(true);
- capture("project_settings:api_key_create");
- })
- .catch((error) => {
- console.error(error);
- });
+ }
}
};
@@ -60,7 +96,12 @@ export function CreateApiKeyButton(props: { projectId: string }) {
return (
<Dialog open={open} onOpenChange={createApiKey}>
<DialogTrigger asChild>
- <Button variant="secondary" loading={mutCreateApiKey.isLoading}>
+ <Button
+ variant="secondary"
+ loading={
+ mutCreateProjectApiKey.isLoading || mutCreateOrgApiKey.isLoading
+ }
+ >
<PlusIcon className="-ml-0.5 mr-1.5 h-5 w-5" aria-hidden="true" />
Create new API keys
</Button>
@@ -71,8 +112,11 @@ export function CreateApiKeyButton(props: { projectId: string }) {
>
<DialogTitle>API Keys</DialogTitle>
<div className="shrink overflow-x-hidden overflow-y-scroll">
- <ApiKeyRender generatedKeys={generatedKeys ?? undefined} />
- {generatedKeys && (
+ <ApiKeyRender
+ scope={props.scope}
+ generatedKeys={generatedKeys ?? undefined}
+ />
+ {generatedKeys && props.scope === "project" && (
<div className="mt-4 max-w-full">
<div className="text-md my-2 font-semibold">Usage</div>
<QuickstartExamples
@@ -88,8 +132,10 @@ export function CreateApiKeyButton(props: { projectId: string }) {
}
export const ApiKeyRender = ({
+ scope,
generatedKeys,
}: {
+ scope: ApiKeyScope;
generatedKeys?: { secretKey: string; publicKey: string };
}) => {
const uiCustomization = useUiCustomization();
@@ -99,7 +145,7 @@ export const ApiKeyRender = ({
<div className="text-md font-semibold">Secret Key</div>
<div className="my-2 text-sm">
This key can only be viewed once. You can always create new keys in
- the project settings.
+ the {scope} settings.
</div>
<CodeView content={generatedKeys?.secretKey ?? "Loading ..."} />
</div>
diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.ts
new file mode 100644
index 0000000000..d130c96906
--- /dev/null
+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts
@@ -0,0 +1,136 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import {
+ createTRPCRouter,
+ protectedOrganizationProcedure,
+} from "@/src/server/api/trpc";
+import * as z from "zod";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
+import { redis } from "@langfuse/shared/src/server";
+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+
+export const organizationApiKeysRouter = createTRPCRouter({
+ byOrganizationId: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:CRUD_apiKeys",
+ });
+
+ return ctx.prisma.apiKey.findMany({
+ where: {
+ orgId: input.orgId,
+ scope: "ORGANIZATION",
+ },
+ select: {
+ id: true,
+ createdAt: true,
+ expiresAt: true,
+ lastUsedAt: true,
+ note: true,
+ publicKey: true,
+ displaySecretKey: true,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+ }),
+ create: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ note: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:CRUD_apiKeys",
+ });
+
+ const apiKeyMeta = await createAndAddApiKeysToDb({
+ prisma: ctx.prisma,
+ entityId: input.orgId,
+ note: input.note,
+ scope: "ORGANIZATION",
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "apiKey",
+ resourceId: apiKeyMeta.id,
+ action: "create",
+ });
+
+ return apiKeyMeta;
+ }),
+ updateNote: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ keyId: z.string(),
+ note: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:CRUD_apiKeys",
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "apiKey",
+ resourceId: input.keyId,
+ action: "update",
+ });
+
+ await ctx.prisma.apiKey.update({
+ where: {
+ id: input.keyId,
+ orgId: input.orgId,
+ },
+ data: {
+ note: input.note,
+ },
+ });
+
+ // do not return the api key
+ return;
+ }),
+ delete: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ id: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:CRUD_apiKeys",
+ });
+ await auditLog({
+ session: ctx.session,
+ resourceType: "apiKey",
+ resourceId: input.id,
+ action: "delete",
+ });
+
+ return await new ApiAuthService(ctx.prisma, redis).deleteApiKey(
+ input.id,
+ input.orgId,
+ "ORGANIZATION",
+ );
+ }),
+});
diff --git a/web/src/features/rbac/constants/organizationAccessRights.ts b/web/src/features/rbac/constants/organizationAccessRights.ts
index b8a3f42ad1..3e66bb664c 100644
--- a/web/src/features/rbac/constants/organizationAccessRights.ts
+++ b/web/src/features/rbac/constants/organizationAccessRights.ts
@@ -3,6 +3,7 @@ import { type Role } from "@langfuse/shared/src/db";
const organizationScopes = [
"projects:create",
"projects:transfer_org",
+ "organization:CRUD_apiKeys",
"organization:update",
"organization:delete",
"organizationMembers:read",
@@ -17,6 +18,7 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {
OWNER: [
"projects:create",
"projects:transfer_org",
+ "organization:CRUD_apiKeys",
"organization:update",
"organization:delete",
"organizationMembers:CUD",
@@ -26,6 +28,7 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {
ADMIN: [
"projects:create",
"projects:transfer_org",
+ "organization:CRUD_apiKeys",
"organization:update",
"organizationMembers:CUD",
"organizationMembers:read",
diff --git a/web/src/features/setup/components/SetupPage.tsx b/web/src/features/setup/components/SetupPage.tsx
index 7d4fda572a..68558931ca 100644
--- a/web/src/features/setup/components/SetupPage.tsx
+++ b/web/src/features/setup/components/SetupPage.tsx
@@ -270,7 +270,7 @@ const TracingSetup = ({
more keys later in the project settings.
</p>
{apiKeys ? (
- <ApiKeyRender generatedKeys={apiKeys} />
+ <ApiKeyRender generatedKeys={apiKeys} scope={"project"} />
) : (
<div className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">
diff --git a/web/src/pages/organization/[organizationId]/settings/index.tsx b/web/src/pages/organization/[organizationId]/settings/index.tsx
index 2d0a30e344..09506710c8 100644
--- a/web/src/pages/organization/[organizationId]/settings/index.tsx
+++ b/web/src/pages/organization/[organizationId]/settings/index.tsx
@@ -14,6 +14,7 @@ import ContainerPage from "@/src/components/layouts/container-page";
import { SSOSettings } from "@/src/ee/features/sso-settings/components/SSOSettings";
import { isCloudPlan } from "@langfuse/shared";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
+import { ApiKeyList } from "@/src/features/public-api/components/ApiKeyList";
type OrganizationSettingsPage = {
title: string;
@@ -25,6 +26,7 @@ type OrganizationSettingsPage = {
export function useOrganizationSettingsPages(): OrganizationSettingsPage[] {
const { organization } = useQueryProjectOrOrganization();
const showBillingSettings = useHasEntitlement("cloud-billing");
+ const showOrgApiKeySettings = useHasEntitlement("admin-api");
const plan = usePlan();
const isLangfuseCloud = isCloudPlan(plan) ?? false;
@@ -33,6 +35,7 @@ export function useOrganizationSettingsPages(): OrganizationSettingsPage[] {
return getOrganizationSettingsPages({
organization,
showBillingSettings,
+ showOrgApiKeySettings,
isLangfuseCloud,
});
}
@@ -40,10 +43,12 @@ export function useOrganizationSettingsPages(): OrganizationSettingsPage[] {
export const getOrganizationSettingsPages = ({
organization,
showBillingSettings,
+ showOrgApiKeySettings,
isLangfuseCloud,
}: {
organization: { id: string; name: string; metadata: Record<string, unknown> };
showBillingSettings: boolean;
+ showOrgApiKeySettings: boolean;
isLangfuseCloud: boolean;
}): OrganizationSettingsPage[] => [
{
@@ -77,6 +82,16 @@ export const getOrganizationSettingsPages = ({
</div>
),
},
+ {
+ title: "API Keys",
+ slug: "api-keys",
+ content: (
+ <div className="flex flex-col gap-6">
+ <ApiKeyList entityId={organization.id} scope="organization" />
+ </div>
+ ),
+ show: showOrgApiKeySettings,
+ },
{
title: "Members",
slug: "members",
diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsx
index a5bead1d3a..5c55e3ba0f 100644
--- a/web/src/pages/project/[projectId]/settings/index.tsx
+++ b/web/src/pages/project/[projectId]/settings/index.tsx
@@ -132,7 +132,7 @@ export const getProjectSettingsPages = ({
cmdKKeywords: ["auth", "public key", "secret key"],
content: (
<div className="flex flex-col gap-6">
- <ApiKeyList projectId={project.id} />
+ <ApiKeyList entityId={project.id} scope="project" />
</div>
),
},
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 6e038e5a5e..aa1b8bbadc 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -20,6 +20,7 @@ import { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";
import { llmSchemaRouter } from "@/src/features/llm-schemas/server/router";
import { llmToolRouter } from "@/src/features/llm-tools/server/router";
import { organizationsRouter } from "@/src/features/organizations/server/organizationRouter";
+import { organizationApiKeysRouter } from "@/src/features/public-api/server/organizationApiKeyRouter";
import { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";
import { publicRouter } from "@/src/server/api/routers/public";
import { credentialsRouter } from "@/src/features/auth-credentials/server/credentialsRouter";
@@ -54,6 +55,7 @@ export const appRouter = createTRPCRouter({
scoreConfigs: scoreConfigsRouter,
dashboard: dashboardRouter,
organizations: organizationsRouter,
+ organizationApiKeys: organizationApiKeysRouter,
projects: projectsRouter,
users: userRouter,
projectApiKeys: projectApiKeysRouter,