🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix: require admin api key for background migration retries in OSS (#9028)
Max Deichmanna618d53451ce
diff --git a/web/src/ee/features/admin-api/server/adminApiAuth.ts b/web/src/ee/features/admin-api/server/adminApiAuth.tsindex 01a5a99e6e..7b52e26e21 100644--- a/web/src/ee/features/admin-api/server/adminApiAuth.ts+++ b/web/src/ee/features/admin-api/server/adminApiAuth.ts@@ -1,5 +1,6 @@import { env } from "@/src/env.mjs";import { logger } from "@langfuse/shared/src/server";+import { type IncomingHttpHeaders } from "http";import { type NextApiRequest, type NextApiResponse } from "next";export interface AdminAuthResult {@@ -8,17 +9,10 @@ export interface AdminAuthResult {}export class AdminApiAuthService {- /**- * Verifies if the request is authorized to access admin APIs- * @param req The Next.js API request- * @param enforceLangfuseCloudOnly Whether to check if the NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is set (default: true)- * @returns An object with isAuthorized flag and optional error message- */- private static verifyAdminAuth(- req: NextApiRequest,+ static verifyAdminAuthFromAuthString = (+ authString: string,enforceLangfuseCloudOnly = true,- ): AdminAuthResult {- // Check if we're in Langfuse cloud environment (optional)+ ): AdminAuthResult => {if (enforceLangfuseCloudOnly && !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {return {isAuthorized: false,@@ -35,16 +29,7 @@ export class AdminApiAuthService {};}- // Check bearer token- const { authorization } = req.headers;- if (!authorization) {- return {- isAuthorized: false,- error: "Unauthorized: No authorization header provided",- };- }-- const [scheme, token] = authorization.split(" ");+ const [scheme, token] = authString.split(" ");if (scheme !== "Bearer" || !token || token !== env.ADMIN_API_KEY) {return {isAuthorized: false,@@ -55,6 +40,31 @@ export class AdminApiAuthService {return {isAuthorized: true,};+ };++ /**+ * Verifies if the request is authorized to access admin APIs+ * @param req The Next.js API request+ * @param enforceLangfuseCloudOnly Whether to check if the NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is set (default: true)+ * @returns An object with isAuthorized flag and optional error message+ */++ private static verifyAdminAuthFromHeader(+ headers: IncomingHttpHeaders,+ enforceLangfuseCloudOnly = true,+ ): AdminAuthResult {+ // Check bearer token+ const { authorization } = headers;+ if (!authorization) {+ return {+ isAuthorized: false,+ error: "Unauthorized: No authorization header provided",+ };+ }+ return AdminApiAuthService.verifyAdminAuthFromAuthString(+ authorization,+ enforceLangfuseCloudOnly,+ );}/**@@ -69,8 +79,8 @@ export class AdminApiAuthService {res: NextApiResponse,enforceLangfuseCloudOnly = true,): boolean {- const authResult = AdminApiAuthService.verifyAdminAuth(- req,+ const authResult = AdminApiAuthService.verifyAdminAuthFromHeader(+ req.headers,enforceLangfuseCloudOnly,);diff --git a/web/src/features/background-migrations/components/background-migrations.tsx b/web/src/features/background-migrations/components/background-migrations.tsxindex 8e114929d3..de03d8bd0f 100644--- a/web/src/features/background-migrations/components/background-migrations.tsx+++ b/web/src/features/background-migrations/components/background-migrations.tsx@@ -1,4 +1,3 @@-import Header from "@/src/components/layouts/header";import { DataTable } from "@/src/components/table/data-table";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import { type LangfuseColumnDef } from "@/src/components/table/types";@@ -6,6 +5,7 @@ import { api } from "@/src/utils/api";import { type BackgroundMigration } from "@langfuse/shared";import { RetryBackgroundMigration } from "@/src/features/background-migrations/components/retry-background-migration";import { StatusBadge } from "@/src/components/layouts/status-badge";+import Page from "@/src/components/layouts/page";export default function BackgroundMigrationsTable() {const backgroundMigrations = api.backgroundMigrations.all.useQuery();@@ -83,8 +83,11 @@ export default function BackgroundMigrationsTable() {] as LangfuseColumnDef<BackgroundMigration>[];return (- <>- <Header title="Background Migrations" />+ <Page+ headerProps={{+ title: "Background Migrations",+ }}+ ><DataTableToolbar columns={columns} /><DataTabletableName={"backgroundMigrations"}@@ -105,6 +108,6 @@ export default function BackgroundMigrationsTable() {}}/>- </>+ </Page>);}diff --git a/web/src/features/background-migrations/components/retry-background-migration.tsx b/web/src/features/background-migrations/components/retry-background-migration.tsxindex 8975d8b83e..622cef23e7 100644--- a/web/src/features/background-migrations/components/retry-background-migration.tsx+++ b/web/src/features/background-migrations/components/retry-background-migration.tsx@@ -6,7 +6,10 @@ import {PopoverContent,PopoverTrigger,} from "@/src/components/ui/popover";+import { Input } from "@/src/components/ui/input";+import { Label } from "@/src/components/ui/label";import { RotateCcw } from "lucide-react";+import { toast } from "sonner";export function RetryBackgroundMigration({backgroundMigrationName,@@ -17,40 +20,108 @@ export function RetryBackgroundMigration({}) {const utils = api.useUtils();const [isOpen, setIsOpen] = useState(false);+ const [adminApiKey, setAdminApiKey] = useState("");+ const [isLoading, setIsLoading] = useState(false);const mutRetryBackgroundMigration =api.backgroundMigrations.retry.useMutation({onSuccess: () => {void utils.backgroundMigrations.invalidate();+ toast.success("Migration scheduled for retry");+ setIsOpen(false);+ setAdminApiKey("");+ },+ onError: (error) => {+ toast.error(error?.message || "Failed to retry migration");+ },+ onSettled: () => {+ setIsLoading(false);},});+ const handleRetry = async () => {+ if (!adminApiKey.trim()) {+ toast.error("Admin API key is required");+ return;+ }+ setIsLoading(true);+ try {+ await mutRetryBackgroundMigration.mutateAsync({+ name: backgroundMigrationName,+ adminApiKey: "Bearer " + adminApiKey.trim(),+ });+ } catch (e) {+ // Error handled in onError+ }+ };+return (- <Popover open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>+ <Popover open={isOpen} onOpenChange={() => setIsOpen((prev) => !prev)}><PopoverTrigger asChild><Button variant="ghost" size="xs" disabled={!isRetryable}><RotateCcw className="h-4 w-4" /></Button></PopoverTrigger>- <PopoverContent>- <h2 className="text-md mb-3 font-semibold">Please confirm</h2>- <p className="mb-3 text-sm">+ <PopoverContent className="w-96">+ <h2 className="text-md mb-3 font-semibold">+ Retry Background Migration+ </h2>+ <p className="mb-4 text-sm">This action schedules the migration for retry. Restart the workercontainers to re-initiate the migration.</p>- <div className="flex justify-end space-x-4">++ <div className="mb-4">+ <Label htmlFor="admin-api-key" className="text-sm font-medium">+ Admin API Key+ </Label>+ <Input+ id="admin-api-key"+ type="password"+ placeholder="Enter admin API key"+ value={adminApiKey}+ onChange={(e) => setAdminApiKey(e.target.value)}+ className="mt-1"+ disabled={isLoading}+ autoComplete="off"+ inputMode="text"+ name="admin-api-key"+ />+ <p className="mt-1 text-xs text-muted-foreground">+ Required for security. This key must match your ADMIN_API_KEY+ environment variable{" ("}+ <a+ href="https://langfuse.com/self-hosting/administration/organization-management-api#authentication"+ target="_blank"+ rel="noopener noreferrer"+ className="text-muted-foreground underline hover:text-primary"+ >+ Docs+ </a>+ {")."}+ </p>+ </div>++ <div className="flex justify-end space-x-2"><Buttontype="button"- variant="default"- loading={mutRetryBackgroundMigration.isPending}+ variant="outline"onClick={() => {- void mutRetryBackgroundMigration.mutateAsync({- name: backgroundMigrationName,- });setIsOpen(false);+ setAdminApiKey("");}}+ disabled={isLoading}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="default"+ loading={isLoading}+ onClick={handleRetry}+ disabled={isLoading}>- Retry Background Migration+ Retry Migration</Button></div></PopoverContent>diff --git a/web/src/features/background-migrations/server/background-migrations-router.ts b/web/src/features/background-migrations/server/background-migrations-router.tsindex 52febe3107..29b3c026da 100644--- a/web/src/features/background-migrations/server/background-migrations-router.ts+++ b/web/src/features/background-migrations/server/background-migrations-router.ts@@ -1,6 +1,7 @@import { z } from "zod/v4";import {createTRPCRouter,+ adminProcedure,authenticatedProcedure,} from "@/src/server/api/trpc";import { TRPCError } from "@trpc/server";@@ -48,8 +49,8 @@ export const backgroundMigrationsRouter = createTRPCRouter({return { status: "FINISHED" };}),- retry: authenticatedProcedure- .input(z.object({ name: z.string() }))+ retry: adminProcedure+ .input(z.object({ name: z.string(), adminApiKey: z.string() })).mutation(async ({ input, ctx }) => {denyOnLangfuseCloud();diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 4c1e42e1af..13625d9420 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -89,6 +89,8 @@ import {contextWithLangfuseProps,} from "@langfuse/shared/src/server";+import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";+setUpSuperjson();const t = initTRPC.context<typeof createTRPCContext>().create({@@ -534,3 +536,47 @@ const enforceSessionAccess = t.middleware(async (opts) => {export const protectedGetSessionProcedure = withOtelTracingProcedure.use(withErrorHandling).use(enforceSessionAccess);++const inputAdminSchema = z.object({+ adminApiKey: z.string(),+});++/** Reusable middleware that enforces admin API key authentication */+const enforceAdminAuth = t.middleware(async (opts) => {+ const { ctx, next } = opts;++ const actualInput = await opts.getRawInput();+ const result = inputAdminSchema.safeParse(actualInput);+ if (!result.success) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid input, adminApiKey is required",+ });+ }++ const adminAuthResult = AdminApiAuthService.verifyAdminAuthFromAuthString(+ result.data.adminApiKey,+ false,+ );++ if (!adminAuthResult.isAuthorized) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: adminAuthResult.error,+ });+ }++ return next({+ ctx,+ });+});++/**+ * Admin authenticated procedure+ *+ * This procedure requires a valid admin API key in the Authorization header.+ * It should be used for sensitive operations that require admin-level access.+ */+export const adminProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceAdminAuth);