Skip to content

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

feat(api): route prompt public handlers through the auth seam (#17533)

Mark Salpeter854f0ba53e55
diff --git a/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap b/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap
index 5723f7f1ae..e5302b88d2 100644
--- a/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap
+++ b/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap
@@ -142,6 +142,13 @@ exports[`public-api auth parity > legacy matches the captured baseline except do
"DELETE v2/evaluators/[evaluatorId] | org/bearer": 401,
"DELETE v2/evaluators/[evaluatorId] | project/basic": 404,
"DELETE v2/evaluators/[evaluatorId] | project/bearer": 403,
+ "DELETE v2/prompts/[promptName]/index | admin/admin": 401,
+ "DELETE v2/prompts/[promptName]/index | agent/basic": 404,
+ "DELETE v2/prompts/[promptName]/index | agent/bearer": 403,
+ "DELETE v2/prompts/[promptName]/index | org/basic": 403,
+ "DELETE v2/prompts/[promptName]/index | org/bearer": 401,
+ "DELETE v2/prompts/[promptName]/index | project/basic": 404,
+ "DELETE v2/prompts/[promptName]/index | project/bearer": 403,
"GET annotation-queues/[queueId]/index | admin/admin": 401,
"GET annotation-queues/[queueId]/index | agent/basic": 401,
"GET annotation-queues/[queueId]/index | agent/bearer": 401,
@@ -359,6 +366,13 @@ exports[`public-api auth parity > legacy matches the captured baseline except do
"GET projects/index | org/bearer": 401,
"GET projects/index | project/basic": 200,
"GET projects/index | project/bearer": 403,
+ "GET prompts | admin/admin": 401,
+ "GET prompts | agent/basic": 401,
+ "GET prompts | agent/bearer": 401,
+ "GET prompts | org/basic": 403,
+ "GET prompts | org/bearer": 401,
+ "GET prompts | project/basic": 400,
+ "GET prompts | project/bearer": 403,
"GET scim/ResourceTypes | admin/admin": 401,
"GET scim/ResourceTypes | agent/basic": 401,
"GET scim/ResourceTypes | agent/bearer": 401,
@@ -541,6 +555,20 @@ exports[`public-api auth parity > legacy matches the captured baseline except do
"GET v2/observations/index | org/bearer": 401,
"GET v2/observations/index | project/basic": 200,
"GET v2/observations/index | project/bearer": 403,
+ "GET v2/prompts/[promptName]/index | admin/admin": 401,
+ "GET v2/prompts/[promptName]/index | agent/basic": 404,
+ "GET v2/prompts/[promptName]/index | agent/bearer": 403,
+ "GET v2/prompts/[promptName]/index | org/basic": 403,
+ "GET v2/prompts/[promptName]/index | org/bearer": 401,
+ "GET v2/prompts/[promptName]/index | project/basic": 404,
+ "GET v2/prompts/[promptName]/index | project/bearer": 403,
+ "GET v2/prompts/index | admin/admin": 401,
+ "GET v2/prompts/index | agent/basic": 200,
+ "GET v2/prompts/index | agent/bearer": 403,
+ "GET v2/prompts/index | org/basic": 403,
+ "GET v2/prompts/index | org/bearer": 401,
+ "GET v2/prompts/index | project/basic": 200,
+ "GET v2/prompts/index | project/bearer": 403,
"GET v2/scores/[scoreId] | admin/admin": 401,
"GET v2/scores/[scoreId] | agent/basic": 401,
"GET v2/scores/[scoreId] | agent/bearer": 401,
@@ -639,6 +667,13 @@ exports[`public-api auth parity > legacy matches the captured baseline except do
"PATCH v2/evaluators/[evaluatorId] | org/bearer": 401,
"PATCH v2/evaluators/[evaluatorId] | project/basic": 400,
"PATCH v2/evaluators/[evaluatorId] | project/bearer": 403,
+ "PATCH v2/prompts/[promptName]/versions/[promptVersion] | admin/admin": 401,
+ "PATCH v2/prompts/[promptName]/versions/[promptVersion] | agent/basic": 400,
+ "PATCH v2/prompts/[promptName]/versions/[promptVersion] | agent/bearer": 403,
+ "PATCH v2/prompts/[promptName]/versions/[promptVersion] | org/basic": 403,
+ "PATCH v2/prompts/[promptName]/versions/[promptVersion] | org/bearer": 401,
+ "PATCH v2/prompts/[promptName]/versions/[promptVersion] | project/basic": 400,
+ "PATCH v2/prompts/[promptName]/versions/[promptVersion] | project/bearer": 403,
"POST annotation-queues/[queueId]/assignments | admin/admin": 401,
"POST annotation-queues/[queueId]/assignments | agent/basic": 401,
"POST annotation-queues/[queueId]/assignments | agent/bearer": 401,
@@ -755,6 +790,13 @@ exports[`public-api auth parity > legacy matches the captured baseline except do
"POST projects/index | org/bearer": 401,
"POST projects/index | project/basic": 403,
"POST projects/index | project/bearer": 403,
+ "POST prompts | admin/admin": 401,
+ "POST prompts | agent/basic": 401,
+ "POST prompts | agent/bearer": 401,
+ "POST prompts | org/basic": 403,
+ "POST prompts | org/bearer": 401,
+ "POST prompts | project/basic": 400,
+ "POST prompts | project/bearer": 403,
"POST scim/Users/index | admin/admin": 401,
"POST scim/Users/index | agent/basic": 401,
"POST scim/Users/index | agent/bearer": 401,
@@ -832,6 +874,13 @@ exports[`public-api auth parity > legacy matches the captured baseline except do
"POST v2/evaluators/index | org/bearer": 401,
"POST v2/evaluators/index | project/basic": 400,
"POST v2/evaluators/index | project/bearer": 403,
+ "POST v2/prompts/index | admin/admin": 401,
+ "POST v2/prompts/index | agent/basic": 400,
+ "POST v2/prompts/index | agent/bearer": 403,
+ "POST v2/prompts/index | org/basic": 403,
+ "POST v2/prompts/index | org/bearer": 401,
+ "POST v2/prompts/index | project/basic": 400,
+ "POST v2/prompts/index | project/bearer": 403,
"PUT integrations/blob-storage/index | admin/admin": 401,
"PUT integrations/blob-storage/index | agent/basic": 401,
"PUT integrations/blob-storage/index | agent/bearer": 401,
diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
index 5ec5523d74..97a05ac5f7 100644
--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
@@ -82,6 +82,7 @@ describe("in-app agent public API route auth", () => {
expect(res._getJSONData()).toEqual({
message:
"Access denied - in-app agent keys are not allowed for this endpoint",
+ error: "UnauthorizedError",
});
});
@@ -92,6 +93,7 @@ describe("in-app agent public API route auth", () => {
expect(res._getJSONData()).toEqual({
message:
"Access denied - in-app agent keys are not allowed for this endpoint",
+ error: "UnauthorizedError",
});
});
diff --git a/web/src/__tests__/server/mcp-error-formatting.servertest.ts b/web/src/__tests__/server/mcp-error-formatting.servertest.ts
index f0522efdd9..3355778b43 100644
--- a/web/src/__tests__/server/mcp-error-formatting.servertest.ts
+++ b/web/src/__tests__/server/mcp-error-formatting.servertest.ts
@@ -26,6 +26,7 @@ import {
LangfuseNotFoundError,
InvalidRequestError,
BaseError,
+ ApiError,
} from "@langfuse/shared";
import { ClickHouseResourceError } from "@langfuse/shared/src/server";
@@ -201,6 +202,17 @@ describe("MCP Error Formatting", () => {
expect(mcpError.message).toContain("API key");
});
+ it("should pass through ApiError 401 message for connection auth", () => {
+ const error = new ApiError(
+ "Invalid credentials. Confirm that you've configured the correct host.",
+ 401,
+ );
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain("Invalid credentials");
+ });
+
it("should format ForbiddenError with permission message", () => {
const error = new ForbiddenError("Access denied");
const mcpError = formatErrorForUser(error);
diff --git a/web/src/__tests__/server/prompts.v1.servertest.ts b/web/src/__tests__/server/prompts.v1.servertest.ts
index f6d910c074..36042c438f 100644
--- a/web/src/__tests__/server/prompts.v1.servertest.ts
+++ b/web/src/__tests__/server/prompts.v1.servertest.ts
@@ -1,3 +1,6 @@
+import { createMocks } from "node-mocks-http";
+import type { NextApiRequest, NextApiResponse } from "next";
+
import { prisma, Prisma } from "@langfuse/shared/src/db";
import { makeAPICall } from "@/src/__tests__/test-utils";
import { v4 as uuidv4, v4 } from "uuid";
@@ -6,12 +9,14 @@ import {
PromptType,
LegacyPromptSchema,
type LegacyValidatedPrompt,
+ PRODUCTION_LABEL,
} from "@langfuse/shared";
import {
createOrgProjectAndApiKey,
getObservationById,
} from "@langfuse/shared/src/server";
import { createPromptForApi } from "@/src/features/prompts/server/prompt-api-service";
+import handler from "@/src/pages/api/public/prompts";
describe("/api/public/prompts API Endpoint", () => {
let auth: string;
@@ -28,6 +33,31 @@ describe("/api/public/prompts API Endpoint", () => {
projectId = setup.projectId;
});
+ it("maps isActive onto production before the protected-label create guard", async () => {
+ await prisma.promptProtectedLabels.create({
+ data: { projectId, label: PRODUCTION_LABEL },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: { authorization: auth },
+ body: {
+ name: `v1-protected-${projectId.slice(0, 8)}`,
+ prompt: "hello",
+ isActive: true,
+ },
+ });
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(201);
+ const body = res._getJSONData() as {
+ isActive: boolean;
+ labels: string[];
+ };
+ expect(body.isActive).toBe(true);
+ expect(body.labels).toContain(PRODUCTION_LABEL);
+ });
+
it("keeps prompt version conflicts as invalid public API requests", async () => {
const transactionSpy = vi
.spyOn(prisma, "$transaction")
@@ -49,6 +79,7 @@ describe("/api/public/prompts API Endpoint", () => {
projectId,
orgId: "test-org",
apiKeyId: "test-api-key",
+ accessLevel: "project",
},
input: {
name: "concurrent-prompt",
diff --git a/web/src/__tests__/server/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.ts
index 2a9976fbed..8ea13b93ac 100644
--- a/web/src/__tests__/server/prompts.v2.servertest.ts
+++ b/web/src/__tests__/server/prompts.v2.servertest.ts
@@ -1,5 +1,5 @@
/* eslint-disable @repo/no-exotic-operators */
-import { prisma } from "@langfuse/shared/src/db";
+import { prisma, Role } from "@langfuse/shared/src/db";
import { disconnectQueues, makeAPICall } from "@/src/__tests__/test-utils";
import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
@@ -16,11 +16,17 @@ import { nanoid } from "nanoid";
import { type PromptsMetaResponse } from "@/src/features/prompts/server/actions/getPromptsMeta";
import {
+ createAndAddApiKeysToDb,
+ createBasicAuthHeader,
createOrgProjectAndApiKey,
getObservationById,
MAX_PROMPT_NESTING_DEPTH,
ChatMessageType,
} from "@langfuse/shared/src/server";
+import {
+ createUserWithOrgRole,
+ protectPromptLabel,
+} from "@/src/__tests__/server/mcp-helpers";
import { randomUUID } from "node:crypto";
import waitForExpect from "wait-for-expect";
import { createPrompt } from "@/src/features/prompts/server/actions/createPrompt";
@@ -3127,6 +3133,186 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {
});
describe("DELETE /api/public/v2/prompts/:promptName", () => {
+ it("returns a bodyless 204", async () => {
+ const { projectId, auth } = await createOrgProjectAndApiKey();
+ const name = "deletePromptBodyless" + uuidv4();
+ await prisma.prompt.create({
+ data: {
+ id: uuidv4(),
+ name,
+ prompt: "p1",
+ labels: [],
+ version: 1,
+ projectId,
+ createdBy: "user",
+ config: {},
+ type: "TEXT",
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ query: { promptName: name },
+ headers: { authorization: auth },
+ });
+
+ await promptNameHandler(req, res);
+
+ expect(res._getStatusCode()).toBe(204);
+ expect(res._getData()).toBe("");
+ });
+
+ it("rejects a MEMBER in-app-agent key deleting a production-labeled prompt", async () => {
+ const { projectId, orgId } = await createOrgProjectAndApiKey();
+ await protectPromptLabel({ projectId, label: "production" });
+ const { userId } = await createUserWithOrgRole({
+ orgId,
+ role: Role.MEMBER,
+ });
+ const apiKey = await createAndAddApiKeysToDb({
+ prisma,
+ entityId: projectId,
+ scope: "PROJECT",
+ isInAppAgentKey: true,
+ createdByUserId: userId,
+ });
+ const name = "deleteProtectedAgent" + uuidv4();
+ await prisma.prompt.create({
+ data: {
+ id: uuidv4(),
+ name,
+ prompt: "p1",
+ labels: ["production"],
+ version: 1,
+ projectId,
+ createdBy: "user",
+ config: {},
+ type: "TEXT",
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ query: { promptName: name },
+ headers: {
+ authorization: createBasicAuthHeader(
+ apiKey.publicKey,
+ apiKey.secretKey,
+ ),
+ },
+ });
+
+ await promptNameHandler(req, res);
+
+ expect(res._getStatusCode()).toBe(403);
+ expect(res._getJSONData().message).toContain(
+ "delete a prompt with a protected label",
+ );
+
+ const remaining = await prisma.prompt.findMany({
+ where: { projectId, name },
+ });
+ expect(remaining.length).toBe(1);
+ });
+
+ it("lets an ordinary project key delete a production-labeled prompt", async () => {
+ const { projectId, auth } = await createOrgProjectAndApiKey();
+ await protectPromptLabel({ projectId, label: "production" });
+ const name = "deleteProtectedProjectKey" + uuidv4();
+ await prisma.prompt.create({
+ data: {
+ id: uuidv4(),
+ name,
+ prompt: "p1",
+ labels: ["production"],
+ version: 1,
+ projectId,
+ createdBy: "user",
+ config: {},
+ type: "TEXT",
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ query: { promptName: name },
+ headers: { authorization: auth },
+ });
+
+ await promptNameHandler(req, res);
+
+ expect(res._getStatusCode()).toBe(204);
+
+ const remaining = await prisma.prompt.findMany({
+ where: { projectId, name },
+ });
+ expect(remaining.length).toBe(0);
+ });
+
+ it("lets a MEMBER in-app-agent key delete an unlabeled version when a sibling version is production", async () => {
+ const { projectId, orgId } = await createOrgProjectAndApiKey();
+ await protectPromptLabel({ projectId, label: "production" });
+ const { userId } = await createUserWithOrgRole({
+ orgId,
+ role: Role.MEMBER,
+ });
+ const apiKey = await createAndAddApiKeysToDb({
+ prisma,
+ entityId: projectId,
+ scope: "PROJECT",
+ isInAppAgentKey: true,
+ createdByUserId: userId,
+ });
+ const name = "deleteUnlabeledSibling" + uuidv4();
+ await prisma.prompt.createMany({
+ data: [
+ {
+ id: uuidv4(),
+ name,
+ prompt: "p1",
+ labels: ["production"],
+ version: 1,
+ projectId,
+ createdBy: "user",
+ config: {},
+ type: "TEXT",
+ },
+ {
+ id: uuidv4(),
+ name,
+ prompt: "p2",
+ labels: [],
+ version: 2,
+ projectId,
+ createdBy: "user",
+ config: {},
+ type: "TEXT",
+ },
+ ],
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ query: { promptName: name, version: "2" },
+ headers: {
+ authorization: createBasicAuthHeader(
+ apiKey.publicKey,
+ apiKey.secretKey,
+ ),
+ },
+ });
+
+ await promptNameHandler(req, res);
+
+ expect(res._getStatusCode()).toBe(204);
+
+ const remaining = await prisma.prompt.findMany({
+ where: { projectId, name },
+ });
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0]?.version).toBe(1);
+ });
+
it("deletes all versions of a prompt", async () => {
const { projectId, auth } = await createOrgProjectAndApiKey();
const name = "deletePrompt" + uuidv4();
diff --git a/web/src/__tests__/server/public-api-auth-parity.servertest.ts b/web/src/__tests__/server/public-api-auth-parity.servertest.ts
index 7abc76d0fa..dca012a9f6 100644
--- a/web/src/__tests__/server/public-api-auth-parity.servertest.ts
+++ b/web/src/__tests__/server/public-api-auth-parity.servertest.ts
@@ -111,6 +111,13 @@ const projectRoutes: Route[] = [
{ route: "ingestion", methods: ["POST"] },
{ route: "otel/v1/traces/index", methods: ["POST"] },
{ route: "otel/v1/metrics/index", methods: ["POST"] },
+ { route: "prompts", methods: ["GET", "POST"] },
+ { route: "v2/prompts/index", methods: ["GET", "POST"] },
+ { route: "v2/prompts/[promptName]/index", methods: ["GET", "DELETE"] },
+ {
+ route: "v2/prompts/[promptName]/versions/[promptVersion]",
+ methods: ["PATCH"],
+ },
];
// Org and misc routes call shadowAuth directly from the handler body.
@@ -143,8 +150,6 @@ const orgRoutes: Route[] = [
const denylistPrefixes = [
"health", // liveness probe
"ready", // readiness probe
- "prompts", // prompt handlers, own auth path
- "v2/prompts", // prompt list/name handlers, own auth path
"mcp", // MCP server, own auth path
"otel/otlp-proto", // generated protobuf, not a route
"slack", // Slack OAuth, own auth path
diff --git a/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
index 77f8465c8b..1efc16cf80 100644
--- a/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
+++ b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
@@ -359,6 +359,7 @@ describe("createAuthedProjectAPIRoute auth error handling", () => {
expect(res._getJSONData()).toEqual({
message:
"Invalid credentials. Confirm that you've configured the correct host.",
+ error: "UnauthorizedError",
});
});
@@ -372,6 +373,7 @@ describe("createAuthedProjectAPIRoute auth error handling", () => {
expect(res.statusCode).toBe(503);
expect(res._getJSONData()).toEqual({
message: "Service Unavailable",
+ error: "ServiceUnavailableError",
});
expect(mockTraceException).toHaveBeenCalledWith(prismaLikeError);
});
@@ -523,4 +525,30 @@ describe("createAuthedProjectAPIRoute auth error handling", () => {
message: "Response payload is too large",
});
});
+
+ it("sends a bodyless 204 when successStatusCode is 204", async () => {
+ mockVerifyAuthHeaderAndReturnScope.mockResolvedValueOnce(validAuth);
+
+ const handler = createAuthedProjectAPIRoute({
+ name: "Delete Route",
+ action: "prompts:CUD",
+ querySchema: z.object({}),
+ responseSchema: z.void(),
+ successStatusCode: 204,
+ fn: async () => undefined,
+ });
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ headers: {
+ authorization: "Basic test",
+ },
+ query: {},
+ });
+
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(204);
+ expect(res._isEndCalled()).toBe(true);
+ expect(res._getData()).toBe("");
+ });
});
diff --git a/web/src/features/mcp/server/prompts/tools/createChatPrompt.ts b/web/src/features/mcp/server/prompts/tools/createChatPrompt.ts
index 2be7c5a979..0ae214c58c 100644
--- a/web/src/features/mcp/server/prompts/tools/createChatPrompt.ts
+++ b/web/src/features/mcp/server/prompts/tools/createChatPrompt.ts
@@ -148,6 +148,7 @@ export const [createChatPromptTool, handleCreateChatPrompt] = defineTool({
fn: async (span) => {
const createdPrompt = await createPromptForApi({
context,
+ ctx: context.auth,
input: CreatePromptSchema.parse({
name: input.name,
type: PromptType.Chat,
diff --git a/web/src/features/mcp/server/prompts/tools/createTextPrompt.ts b/web/src/features/mcp/server/prompts/tools/createTextPrompt.ts
index eaf0d19ed9..f09c9d1dfb 100644
--- a/web/src/features/mcp/server/prompts/tools/createTextPrompt.ts
+++ b/web/src/features/mcp/server/prompts/tools/createTextPrompt.ts
@@ -99,6 +99,7 @@ export const [createTextPromptTool, handleCreateTextPrompt] = defineTool({
fn: async (span) => {
const createdPrompt = await createPromptForApi({
context,
+ ctx: context.auth,
input: CreatePromptSchema.parse({
name: input.name,
type: PromptType.Text,
diff --git a/web/src/features/mcp/server/prompts/tools/updatePromptLabels.ts b/web/src/features/mcp/server/prompts/tools/updatePromptLabels.ts
index 2d8ff43014..a0739b282a 100644
--- a/web/src/features/mcp/server/prompts/tools/updatePromptLabels.ts
+++ b/web/src/features/mcp/server/prompts/tools/updatePromptLabels.ts
@@ -86,6 +86,7 @@ export const [updatePromptLabelsTool, handleUpdatePromptLabels] = defineTool({
const { updatedPrompt } = await updatePromptLabelsForApi({
context,
+ ctx: context.auth,
promptName: name,
promptVersion: version,
newLabels,
diff --git a/web/src/features/prompts/server/handlers/promptNameHandler.ts b/web/src/features/prompts/server/handlers/promptNameHandler.ts
index a4a4f1f30e..c117afd7ab 100644
--- a/web/src/features/prompts/server/handlers/promptNameHandler.ts
+++ b/web/src/features/prompts/server/handlers/promptNameHandler.ts
@@ -1,118 +1,76 @@
-import type { NextApiRequest, NextApiResponse } from "next";
+import { z } from "zod";
-import { getPromptForApi } from "@/src/features/prompts/server/prompt-api-service";
-import { deletePrompt } from "@/src/features/prompts/server/actions/deletePrompt";
+import {
+ deletePromptForApi,
+ getPromptForApi,
+} from "@/src/features/prompts/server/prompt-api-service";
import {
withMiddlewares,
- RateLimitService,
+ createAuthedProjectAPIRoute,
} from "@/src/features/public-api/server";
-import { authorizePromptRequestOrThrow } from "../utils/authorizePromptRequest";
import {
GetPromptByNameSchema,
LangfuseNotFoundError,
PRODUCTION_LABEL,
} from "@langfuse/shared";
-import { auditLog } from "@/src/features/audit-logs/server";
-import { prisma } from "@langfuse/shared/src/db";
-
-const getPromptNameHandler = async (
- req: NextApiRequest,
- res: NextApiResponse,
-) => {
- const authCheck = await authorizePromptRequestOrThrow(req);
-
- const rateLimitCheck = await RateLimitService.getInstance().rateLimitRequest(
- authCheck.scope,
- "prompts",
- );
-
- if (rateLimitCheck?.isRateLimited()) {
- return rateLimitCheck.sendRestResponseIfLimited(res);
- }
-
- const { promptName, version, label, resolve } = GetPromptByNameSchema.parse(
- req.query,
- );
-
- const prompt = await getPromptForApi({
- promptName: promptName,
- projectId: authCheck.scope.projectId,
- version,
- label,
- resolve,
- });
-
- if (!prompt) {
- let errorMessage = `Prompt not found: '${promptName}'`;
-
- if (version) {
- errorMessage += ` with version ${version}`;
- } else {
- errorMessage += ` with label '${label ?? PRODUCTION_LABEL}'`;
- }
-
- throw new LangfuseNotFoundError(errorMessage);
- }
-
- res.status(200).json({
- ...prompt,
- isActive: prompt.labels.includes(PRODUCTION_LABEL),
- });
-};
-
-const deletePromptNameHandler = async (
- req: NextApiRequest,
- res: NextApiResponse,
-) => {
- const authCheck = await authorizePromptRequestOrThrow(req);
-
- const rateLimitCheck = await RateLimitService.getInstance().rateLimitRequest(
- authCheck.scope,
- "prompts",
- );
-
- if (rateLimitCheck?.isRateLimited()) {
- return rateLimitCheck.sendRestResponseIfLimited(res);
- }
-
- const { promptName, version, label } = GetPromptByNameSchema.parse(req.query);
-
- // Fetch prompts for audit logging
- const where = {
- projectId: authCheck.scope.projectId,
- name: promptName,
- ...(version ? { version } : {}),
- ...(label ? { labels: { has: label } } : {}),
- };
-
- const prompts = await prisma.prompt.findMany({ where });
-
- // Audit log before deletion
- for (const prompt of prompts) {
- await auditLog({
- action: "delete",
- resourceType: "prompt",
- resourceId: prompt.id,
- projectId: authCheck.scope.projectId,
- orgId: authCheck.scope.orgId,
- apiKeyId: authCheck.scope.apiKeyId,
- before: prompt,
- });
- }
-
- // Delete prompt versions
- await deletePrompt({
- promptName,
- projectId: authCheck.scope.projectId,
- version,
- label,
- promptVersions: prompts,
- });
-
- res.status(204).end();
-};
export const promptNameHandler = withMiddlewares({
- GET: getPromptNameHandler,
- DELETE: deletePromptNameHandler,
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Prompt",
+ action: "prompts:read",
+ querySchema: GetPromptByNameSchema,
+ responseSchema: z.any(),
+ allowInAppAgentKey: true,
+ isAdminApiKeyAuthAllowed: false,
+ rateLimitResource: "prompts",
+ fn: async ({ query, auth }) => {
+ const { promptName, version, label, resolve } = query;
+
+ const prompt = await getPromptForApi({
+ promptName,
+ projectId: auth.scope.projectId,
+ version,
+ label,
+ resolve,
+ });
+
+ if (!prompt) {
+ let errorMessage = `Prompt not found: '${promptName}'`;
+
+ if (version) {
+ errorMessage += ` with version ${version}`;
+ } else {
+ errorMessage += ` with label '${label ?? PRODUCTION_LABEL}'`;
+ }
+
+ throw new LangfuseNotFoundError(errorMessage);
+ }
+
+ return {
+ ...prompt,
+ isActive: prompt.labels.includes(PRODUCTION_LABEL),
+ };
+ },
+ }),
+ DELETE: createAuthedProjectAPIRoute({
+ name: "Delete Prompt",
+ action: "prompts:CUD",
+ querySchema: GetPromptByNameSchema,
+ responseSchema: z.void(),
+ successStatusCode: 204,
+ allowInAppAgentKey: true,
+ isAdminApiKeyAuthAllowed: false,
+ rateLimitResource: "prompts",
+ fn: async ({ query, auth, ctx }) => {
+ const { promptName, version, label } = query;
+
+ await deletePromptForApi({
+ context: auth.scope,
+ promptName,
+ version,
+ label,
+ ctx,
+ });
+ },
+ }),
});
diff --git a/web/src/features/prompts/server/handlers/promptVersionHandler.ts b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
index a5e4421cc8..3b832c7f97 100644
--- a/web/src/features/prompts/server/handlers/promptVersionHandler.ts
+++ b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
@@ -21,8 +21,11 @@ export const promptVersionHandler = withMiddlewares({
action: "prompts:CUD",
bodySchema: UpdatePromptBodySchema,
responseSchema: z.any(),
- fn: async ({ body, req, auth }) => {
- const { newLabels } = UpdatePromptBodySchema.parse(body);
+ allowInAppAgentKey: true,
+ isAdminApiKeyAuthAllowed: false,
+ rateLimitResource: "prompts",
+ fn: async ({ body, req, auth, ctx }) => {
+ const { newLabels } = body;
const { promptName, promptVersion } = req.query;
const { updatedPrompt } = await updatePromptLabelsForApi({
@@ -30,6 +33,7 @@ export const promptVersionHandler = withMiddlewares({
promptName: promptName as string,
promptVersion: Number(promptVersion),
newLabels,
+ ctx,
});
return updatedPrompt;
diff --git a/web/src/features/prompts/server/handlers/promptsHandler.ts b/web/src/features/prompts/server/handlers/promptsHandler.ts
index 7fa6f34bc8..67c967a6b7 100644
--- a/web/src/features/prompts/server/handlers/promptsHandler.ts
+++ b/web/src/features/prompts/server/handlers/promptsHandler.ts
@@ -1,4 +1,4 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
+import { z } from "zod";
import {
createPromptForApi,
@@ -6,57 +6,41 @@ import {
} from "@/src/features/prompts/server/prompt-api-service";
import {
withMiddlewares,
- RateLimitService,
+ createAuthedProjectAPIRoute,
} from "@/src/features/public-api/server";
-import { authorizePromptRequestOrThrow } from "../utils/authorizePromptRequest";
import { CreatePromptSchema, GetPromptsMetaSchema } from "@langfuse/shared";
-const getPromptsHandler = async (req: NextApiRequest, res: NextApiResponse) => {
- const authCheck = await authorizePromptRequestOrThrow(req);
-
- const rateLimitCheck = await RateLimitService.getInstance().rateLimitRequest(
- authCheck.scope,
- "prompts",
- );
-
- if (rateLimitCheck?.isRateLimited()) {
- return rateLimitCheck.sendRestResponseIfLimited(res);
- }
-
- const input = GetPromptsMetaSchema.parse(req.query);
- const promptsMetadata = await listPromptsForApi({
- ...input,
- projectId: authCheck.scope.projectId,
- });
-
- return res.status(200).json(promptsMetadata);
-};
-
-const postPromptsHandler = async (
- req: NextApiRequest,
- res: NextApiResponse,
-) => {
- const authCheck = await authorizePromptRequestOrThrow(req);
-
- const rateLimitCheck = await RateLimitService.getInstance().rateLimitRequest(
- authCheck.scope,
- "prompts",
- );
-
- if (rateLimitCheck?.isRateLimited()) {
- return rateLimitCheck.sendRestResponseIfLimited(res);
- }
-
- const input = CreatePromptSchema.parse(req.body);
- const createdPrompt = await createPromptForApi({
- context: authCheck.scope,
- input,
- });
-
- return res.status(201).json(createdPrompt);
-};
-
export const promptsHandler = withMiddlewares({
- GET: getPromptsHandler,
- POST: postPromptsHandler,
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Prompts",
+ action: "prompts:read",
+ querySchema: GetPromptsMetaSchema,
+ responseSchema: z.any(),
+ allowInAppAgentKey: true,
+ isAdminApiKeyAuthAllowed: false,
+ rateLimitResource: "prompts",
+ fn: async ({ query, auth }) => {
+ return await listPromptsForApi({
+ ...query,
+ projectId: auth.scope.projectId,
+ });
+ },
+ }),
+ POST: createAuthedProjectAPIRoute({
+ name: "Create Prompt",
+ action: "prompts:CUD",
+ bodySchema: CreatePromptSchema,
+ responseSchema: z.any(),
+ successStatusCode: 201,
+ allowInAppAgentKey: true,
+ isAdminApiKeyAuthAllowed: false,
+ rateLimitResource: "prompts",
+ fn: async ({ body, auth, ctx }) => {
+ return await createPromptForApi({
+ context: auth.scope,
+ input: body,
+ ctx,
+ });
+ },
+ }),
});
diff --git a/web/src/features/prompts/server/prompt-api-service.ts b/web/src/features/prompts/server/prompt-api-service.ts
index 761fb297c1..4e87384f4d 100644
--- a/web/src/features/prompts/server/prompt-api-service.ts
+++ b/web/src/features/prompts/server/prompt-api-service.ts
@@ -10,10 +10,14 @@ import {
LangfuseNotFoundError,
hasProjectAccessByRole,
} from "@langfuse/shared";
+import { type ApiAccessLevel } from "@langfuse/shared/src/server";
import type { z } from "zod";
import { auditLog } from "@/src/features/audit-logs/server";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+import { shadowAuthorize } from "@/src/features/public-api/server/shadowAuth";
import { createPrompt } from "./actions/createPrompt";
+import { deletePrompt } from "./actions/deletePrompt";
import { getPromptByName } from "./actions/getPromptByName";
import { getPromptsMeta } from "./actions/getPromptsMeta";
import { updatePrompt } from "./actions/updatePrompts";
@@ -23,6 +27,7 @@ type ApiKeyProjectContext = {
projectId: string;
orgId: string;
apiKeyId: string;
+ accessLevel: ApiAccessLevel;
};
type ListPromptsForApiInput = z.infer<typeof GetPromptsMetaSchema> & {
@@ -99,24 +104,13 @@ async function resolveApiKeyCreatorProjectAccess(params: {
/**
* Ordinary project API keys may still promote protected labels (CI). Temporary
* in-app-agent keys must honor the creator's promptProtectedLabels:CUD right.
+ * Call after checkHasProtectedLabels; skip when that result is false.
*/
async function assertInAppAgentMayMutateProtectedLabels(params: {
context: ApiKeyProjectContext;
- labelsToCheck: string[];
+ protectedLabels: string[];
forbiddenErrorMessage: string;
}): Promise<void> {
- const { hasProtectedLabels, protectedLabels } = await checkHasProtectedLabels(
- {
- prisma,
- projectId: params.context.projectId,
- labelsToCheck: params.labelsToCheck,
- },
- );
-
- if (!hasProtectedLabels) {
- return;
- }
-
const apiKey = await prisma.apiKey.findUnique({
where: { id: params.context.apiKeyId },
select: {
@@ -147,20 +141,57 @@ async function assertInAppAgentMayMutateProtectedLabels(params: {
if (!mayMutateProtectedLabels) {
throw new ForbiddenError(
- `${params.forbiddenErrorMessage}\n\n Protected labels are: ${protectedLabels.join(", ")}`,
+ `${params.forbiddenErrorMessage}\n\n Protected labels are: ${params.protectedLabels.join(", ")}`,
);
}
}
+/** authorizeProtectedLabelMutation runs the per-item seam and the in-app-agent creator check when the label set includes a protected label. */
+async function authorizeProtectedLabelMutation(params: {
+ context: ApiKeyProjectContext;
+ ctx?: AuthorizationContext;
+ labelsToCheck: string[];
+ forbiddenErrorMessage: string;
+}): Promise<void> {
+ const { hasProtectedLabels, protectedLabels } = await checkHasProtectedLabels(
+ {
+ prisma,
+ projectId: params.context.projectId,
+ labelsToCheck: params.labelsToCheck,
+ },
+ );
+
+ if (!hasProtectedLabels) {
+ return;
+ }
+
+ const decision = shadowAuthorize({
+ ctx: params.ctx,
+ action: "promptProtectedLabels:CUD",
+ resource: { projectId: params.context.projectId },
+ accessLevel: params.context.accessLevel,
+ });
+ if (!decision.success) throw decision.error;
+
+ await assertInAppAgentMayMutateProtectedLabels({
+ context: params.context,
+ protectedLabels,
+ forbiddenErrorMessage: params.forbiddenErrorMessage,
+ });
+}
+
export const createPromptForApi = async ({
context,
input,
+ ctx,
}: {
context: ApiKeyProjectContext;
input: z.infer<typeof CreatePromptSchema>;
+ ctx?: AuthorizationContext;
}) => {
- await assertInAppAgentMayMutateProtectedLabels({
+ await authorizeProtectedLabelMutation({
context,
+ ctx,
labelsToCheck: input.labels ?? [],
forbiddenErrorMessage:
"You don't have permission to create a prompt with a protected label. Please contact your project admin for assistance.",
@@ -210,11 +241,13 @@ export const updatePromptLabelsForApi = async ({
promptName,
promptVersion,
newLabels,
+ ctx,
}: {
context: ApiKeyProjectContext;
promptName: string;
promptVersion: number;
newLabels: string[];
+ ctx?: AuthorizationContext;
}) => {
const existingPrompt = await prisma.prompt.findUnique({
where: {
@@ -238,8 +271,9 @@ export const updatePromptLabelsForApi = async ({
(label) => !existingPrompt.labels.includes(label),
);
- await assertInAppAgentMayMutateProtectedLabels({
+ await authorizeProtectedLabelMutation({
context,
+ ctx,
labelsToCheck: addedLabels,
forbiddenErrorMessage:
"You don't have permission to add a protected label to a prompt. Please contact your project admin for assistance.",
@@ -268,3 +302,54 @@ export const updatePromptLabelsForApi = async ({
updatedPrompt: Prompt;
};
};
+
+export const deletePromptForApi = async ({
+ context,
+ promptName,
+ version,
+ label,
+ ctx,
+}: {
+ context: ApiKeyProjectContext;
+ promptName: string;
+ version?: number | null;
+ label?: string;
+ ctx?: AuthorizationContext;
+}) => {
+ const where = {
+ projectId: context.projectId,
+ name: promptName,
+ ...(version ? { version } : {}),
+ ...(label ? { labels: { has: label } } : {}),
+ };
+
+ const prompts = await prisma.prompt.findMany({ where });
+
+ await authorizeProtectedLabelMutation({
+ context,
+ ctx,
+ labelsToCheck: prompts.flatMap((prompt) => prompt.labels),
+ forbiddenErrorMessage:
+ "You don't have permission to delete a prompt with a protected label. Please contact your project admin for assistance.",
+ });
+
+ for (const prompt of prompts) {
+ await auditLog({
+ action: "delete",
+ resourceType: "prompt",
+ resourceId: prompt.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: prompt,
+ });
+ }
+
+ await deletePrompt({
+ promptName,
+ projectId: context.projectId,
+ version,
+ label,
+ promptVersions: prompts,
+ });
+};
diff --git a/web/src/features/prompts/server/utils/authorizePromptRequest.ts b/web/src/features/prompts/server/utils/authorizePromptRequest.ts
deleted file mode 100644
index 68eb4bb904..0000000000
--- a/web/src/features/prompts/server/utils/authorizePromptRequest.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { ApiAuthService } from "@/src/features/public-api/server";
-import { type NextApiRequest } from "next";
-import { UnauthorizedError, ForbiddenError } from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
-import {
- type AuthHeaderValidVerificationResult,
- redis,
-} from "@langfuse/shared/src/server";
-
-export async function authorizePromptRequestOrThrow(req: NextApiRequest) {
- const authCheck = await new ApiAuthService(
- prisma,
- redis,
- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
- if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
- if (authCheck.scope.accessLevel !== "project")
- throw new ForbiddenError(
- `Access denied - need to use basic auth with secret key to ${req.method} prompts`,
- );
- if (!authCheck.scope.projectId) {
- throw new ForbiddenError(`No valid projectId found for auth token`);
- }
- return authCheck as AuthHeaderValidVerificationResult & {
- scope: { projectId: string; accessLevel: "project" };
- };
-}
diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
index 7cdbf8293c..f3a2874d8f 100644
--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
@@ -9,7 +9,11 @@ import {
} from "@langfuse/shared/src/server";
import {
BaseError,
+ ForbiddenError,
+ LangfuseNotFoundError,
PayloadTooLargeError,
+ ServiceUnavailableError,
+ UnauthorizedError,
type RateLimitResource,
type ApiDeprecationInfo,
} from "@langfuse/shared";
@@ -31,13 +35,40 @@ import { attachDeprecation } from "@/src/features/public-api/server/deprecations
import { applyLegacyApiOrganizationCutoff } from "@/src/features/public-api/server/legacyApiOrganizationCutoff";
import { type RouteAccessLevel } from "@/src/features/public-api/server/verifyProjectApiKeyAuth";
import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";
-import { type ProjectAction } from "@/src/features/auth/policy/types";
+import {
+ type AuthorizationContext,
+ type ProjectAction,
+} from "@/src/features/auth/policy/types";
// Next's res.json uses JSON.stringify; V8 throws this when the JSON string
// exceeds the engine limit. Keep this check scoped to the response write.
const isJsonStringTooLargeError = (error: unknown): error is RangeError =>
error instanceof RangeError && error.message === "Invalid string length";
+/** toMiddlewareAuthError maps seam auth failures onto the BaseError classes whose `name` withMiddlewares already puts in `{ error }`. */
+function toMiddlewareAuthError(error: BaseError): BaseError {
+ switch (error.httpCode) {
+ case 401:
+ return error instanceof UnauthorizedError
+ ? error
+ : new UnauthorizedError(error.message);
+ case 403:
+ return error instanceof ForbiddenError
+ ? error
+ : new ForbiddenError(error.message);
+ case 404:
+ return error instanceof LangfuseNotFoundError
+ ? error
+ : new LangfuseNotFoundError(error.message);
+ case 503:
+ return error instanceof ServiceUnavailableError
+ ? error
+ : new ServiceUnavailableError(error.message);
+ default:
+ return error;
+ }
+}
+
export type AuthedProjectAPIRouteConfig<
TQuery extends ZodType<any>,
TBody extends ZodType<any>,
@@ -78,7 +109,6 @@ export type AuthedProjectAPIRouteConfig<
allowedAccessLevels?: RouteAccessLevel[];
/**
* Whether in-app agent API keys can call this route without additional confirmation. Defaults to false.
- * Only set this to true on non-mutating (GET) routes that should be callable by the in-app agent.
*/
allowInAppAgentKey?: boolean;
/**
@@ -104,6 +134,11 @@ export type AuthedProjectAPIRouteConfig<
auth: AuthHeaderValidVerificationResult & {
scope: { projectId: string; accessLevel: RouteAccessLevel };
};
+ /**
+ * Policy context from the new auth pipeline. Present in shadow and
+ * enforce; absent in legacy and on gateway-token auth.
+ */
+ ctx?: AuthorizationContext;
}) => Promise<z.infer<TResponse>>;
};
@@ -140,14 +175,21 @@ export const createAuthedProjectAPIRoute = <
return;
}
- const renderAuthError = (statusCode: number, message: string) => {
+ const renderAuthError = (error: BaseError) => {
+ const publicError = toMiddlewareAuthError(error);
if (routeConfig.errorContract === structuredPublicApiErrorContract) {
return sendStructuredPublicApiErrorResponse(
res,
- createStructuredPublicApiAuthError({ statusCode, message }),
+ createStructuredPublicApiAuthError({
+ statusCode: publicError.httpCode,
+ message: publicError.message,
+ }),
);
}
- res.status(statusCode).json({ message });
+ res.status(publicError.httpCode).json({
+ message: publicError.message,
+ error: publicError.name,
+ });
};
// A signed AI-gateway ingestion token authorizes the project directly,
@@ -163,8 +205,13 @@ export const createAuthedProjectAPIRoute = <
);
} catch (error) {
renderAuthError(
- error instanceof BaseError ? error.httpCode : 401,
- error instanceof BaseError ? error.message : "Authentication failed",
+ error instanceof BaseError
+ ? error
+ : new UnauthorizedError(
+ error instanceof Error
+ ? error.message
+ : "Authentication failed",
+ ),
);
return;
}
@@ -178,6 +225,7 @@ export const createAuthedProjectAPIRoute = <
accessLevel: RouteAccessLevel;
};
};
+ let authzCtx: AuthorizationContext | undefined;
if (gatewayAuth) {
auth = gatewayAuth;
@@ -191,7 +239,7 @@ export const createAuthedProjectAPIRoute = <
});
if (!result.success) {
- renderAuthError(result.error.httpCode, result.error.message);
+ renderAuthError(result.error);
return;
}
@@ -202,6 +250,7 @@ export const createAuthedProjectAPIRoute = <
accessLevel: RouteAccessLevel;
},
};
+ authzCtx = result.ctx;
}
const rateLimitResponse =
@@ -276,7 +325,7 @@ export const createAuthedProjectAPIRoute = <
throw error;
}
- const ctx = contextWithLangfuseProps({
+ const otelCtx = contextWithLangfuseProps({
headers: req.headers,
projectId: auth.scope.projectId,
apiKeyId: auth.scope.apiKeyId,
@@ -285,7 +334,7 @@ export const createAuthedProjectAPIRoute = <
route: clickHouseRouteForRequest(req),
},
});
- return opentelemetry.context.with(ctx, async () => {
+ return opentelemetry.context.with(otelCtx, async () => {
const response = await routeConfig.fn({
query,
body,
@@ -296,6 +345,7 @@ export const createAuthedProjectAPIRoute = <
auth: auth as AuthHeaderValidVerificationResult & {
scope: { projectId: string; accessLevel: RouteAccessLevel };
},
+ ctx: authzCtx,
});
if (env.NODE_ENV === "development" && routeConfig.responseSchema) {
@@ -306,12 +356,18 @@ export const createAuthedProjectAPIRoute = <
}
}
- res.status(
+ const statusCode =
// Check whether status code was already set inside handler to non default value
res.statusCode !== 200
? res.statusCode
- : routeConfig.successStatusCode || 200,
- );
+ : routeConfig.successStatusCode || 200;
+
+ if (statusCode === 204) {
+ res.status(204).end();
+ return;
+ }
+
+ res.status(statusCode);
try {
res.json(attachDeprecation(response || { message: "OK" }, deprecation));
diff --git a/web/src/pages/api/public/prompts.ts b/web/src/pages/api/public/prompts.ts
index 07da36c352..511f480cda 100644
--- a/web/src/pages/api/public/prompts.ts
+++ b/web/src/pages/api/public/prompts.ts
@@ -1,146 +1,73 @@
-import { createPrompt } from "@/src/features/prompts/server/actions/createPrompt";
+import { z } from "zod";
+
import { getPromptByName } from "@/src/features/prompts/server/actions/getPromptByName";
-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { isZodError } from "@/src/features/public-api/server/withMiddlewares";
-import { prisma } from "@langfuse/shared/src/db";
-import { isPrismaException } from "@/src/utils/exceptions";
-import { type NextApiRequest, type NextApiResponse } from "next";
+import { createPromptForApi } from "@/src/features/prompts/server/prompt-api-service";
+import {
+ createAuthedProjectAPIRoute,
+ withMiddlewares,
+} from "@/src/features/public-api/server";
+import { telemetry } from "@/src/features/telemetry";
import {
- UnauthorizedError,
- LangfuseNotFoundError,
- BaseError,
- MethodNotAllowedError,
- ForbiddenError,
GetPromptSchema,
+ LangfuseNotFoundError,
LegacyCreatePromptSchema,
PRODUCTION_LABEL,
} from "@langfuse/shared";
-import { redis, traceException, logger } from "@langfuse/shared/src/server";
-import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
-import { telemetry } from "@/src/features/telemetry";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
- try {
- // Authentication and authorization
- const authCheck = await new ApiAuthService(
- prisma,
- redis,
- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
-
- if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
- if (
- authCheck.scope.accessLevel !== "project" ||
- !authCheck.scope.projectId
- ) {
- throw new ForbiddenError(
- `Access denied: Bearer auth and org api keys are not allowed to access`,
- );
- }
-
- await telemetry();
-
- // Handle GET requests
- if (req.method === "GET") {
- const searchParams = GetPromptSchema.parse(req.query);
- const projectId = authCheck.scope.projectId;
- const promptName = searchParams.name;
- const version = searchParams.version ?? undefined;
-
- const rateLimitCheck =
- await RateLimitService.getInstance().rateLimitRequest(
- authCheck.scope,
- "prompts",
- );
-
- if (rateLimitCheck?.isRateLimited()) {
- return rateLimitCheck.sendRestResponseIfLimited(res);
- }
+export default withMiddlewares({
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Prompt (Legacy)",
+ action: "prompts:read",
+ querySchema: GetPromptSchema,
+ responseSchema: z.any(),
+ allowInAppAgentKey: false,
+ isAdminApiKeyAuthAllowed: false,
+ rateLimitResource: "prompts",
+ fn: async ({ query, auth }) => {
+ await telemetry();
const prompt = await getPromptByName({
- promptName,
- projectId,
- version,
+ promptName: query.name,
+ projectId: auth.scope.projectId,
+ version: query.version ?? undefined,
});
if (!prompt) throw new LangfuseNotFoundError("Prompt not found");
- return res.status(200).json({
+ return {
...prompt,
isActive: prompt.labels.includes(PRODUCTION_LABEL),
- });
- }
-
- // Handle POST requests
- if (req.method === "POST") {
- const rateLimitCheck =
- await RateLimitService.getInstance().rateLimitRequest(
- authCheck.scope,
- "prompts",
- );
-
- if (rateLimitCheck?.isRateLimited()) {
- return rateLimitCheck.sendRestResponseIfLimited(res);
- }
-
- const input = LegacyCreatePromptSchema.parse(req.body);
- const prompt = await createPrompt({
- ...input,
- labels: input.isActive
- ? [...new Set([...input.labels, PRODUCTION_LABEL])] // Ensure labels are unique
- : input.labels, // If production label is already present, this will still promote the prompt
- config: input.config ?? {}, // Config can be null in which case zod default value is not used
- projectId: authCheck.scope.projectId,
- createdBy: "API",
- prisma: prisma,
+ };
+ },
+ }),
+ POST: createAuthedProjectAPIRoute({
+ name: "Create Prompt (Legacy)",
+ action: "prompts:CUD",
+ bodySchema: LegacyCreatePromptSchema,
+ responseSchema: z.any(),
+ successStatusCode: 201,
+ allowInAppAgentKey: false,
+ isAdminApiKeyAuthAllowed: false,
+ rateLimitResource: "prompts",
+ fn: async ({ body, auth, ctx }) => {
+ await telemetry();
+
+ const { isActive, ...input } = body;
+ const prompt = await createPromptForApi({
+ context: auth.scope,
+ input: {
+ ...input,
+ labels: isActive
+ ? [...new Set([...input.labels, PRODUCTION_LABEL])]
+ : input.labels,
+ },
+ ctx,
});
- return res.status(201).json({
+ return {
...prompt,
isActive: prompt.labels.includes(PRODUCTION_LABEL),
- });
- }
-
- throw new MethodNotAllowedError();
- } catch (error: unknown) {
- if (error instanceof BaseError) {
- if (!error.isUserError()) {
- logger.error(error);
- traceException(error);
- }
-
- return res.status(error.httpCode).json({
- error: error.name,
- message: error.message,
- });
- }
-
- if (isZodError(error)) {
- logger.warn(`Zod exception`, { issues: error.issues });
- return res.status(400).json({
- message: "Invalid request data",
- error: error.issues,
- });
- }
-
- logger.error(error);
- traceException(error);
-
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
-
- return res.status(500).json({
- message: "Invalid request data",
- error:
- error instanceof Error ? error.message : "An unknown error occurred",
- });
- }
-}
+ };
+ },
+ }),
+});