🪢 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
feat: delete API keys via API (#3448)
Max Deichmannaf29424b4873
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 626fe279ed..1f604fde10 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -33,7 +33,7 @@ export class ApiAuthService {// this function needs to be called, when the organisation is updated// - when projects move across organisations, the orgId in the API key cache needs to be updated// - when the plan of the org changes, the plan in the API key cache needs to be updated as well- private async invalidate(apiKeys: ApiKey[], identifier: string) {+ async invalidate(apiKeys: ApiKey[], identifier: string) {const hashKeys = apiKeys.map((key) => key.fastHashedSecretKey);const filteredHashKeys = hashKeys.filter((hash): hash is string =>@@ -47,9 +47,7 @@ export class ApiAuthService {if (this.redis) {logger.info(`Invalidating API keys in redis for ${identifier}`);await this.redis.del(- filteredHashKeys- .filter((hash): hash is string => Boolean(hash))- .map((hash) => this.createRedisKey(hash)),+ filteredHashKeys.map((hash) => this.createRedisKey(hash)),);}}diff --git a/web/src/pages/api/admin/api-keys/index.ts b/web/src/pages/api/admin/api-keys/index.tsnew file mode 100644index 0000000000..2d78db8ed2--- /dev/null+++ b/web/src/pages/api/admin/api-keys/index.ts@@ -0,0 +1,86 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { env } from "@/src/env.mjs";+import { z } from "zod";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";++const DeleteApiKeySchema = z.object({+ projectIds: z.array(z.string()),+});++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ // allow only POST requests+ if (req.method !== "DELETE") {+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }+ // check if ADMIN_API_KEY is set+ if (!env.ADMIN_API_KEY) {+ logger.error("ADMIN_API_KEY is not set");+ res.status(500).json({ error: "ADMIN_API_KEY is not set" });+ return;+ }++ // check bearer token+ const { authorization } = req.headers;+ if (!authorization) {+ res+ .status(401)+ .json({ error: "Unauthorized: No authorization header provided" });+ return;+ }+ const [scheme, token] = authorization.split(" ");+ if (scheme !== "Bearer" || !token || token !== env.ADMIN_API_KEY) {+ res.status(401).json({ error: "Unauthorized: Invalid token" });+ return;+ }++ const body = DeleteApiKeySchema.safeParse(req.body);++ if (!body.success) {+ res.status(400).json({ error: body.error });+ return;+ }++ logger.info(+ `trying to remove API keys for projects ${body.data.projectIds.join(", ")}`,+ );++ // delete the API keys in the database first+ const apiKeysToBeDeleted = await prisma.apiKey.findMany({+ where: {+ projectId: {+ in: body.data.projectIds,+ },+ },+ });++ await prisma.apiKey.deleteMany({+ where: {+ projectId: {+ in: body.data.projectIds,+ },+ },+ });++ // then delete from the cache+ await new ApiAuthService(prisma, redis).invalidate(+ apiKeysToBeDeleted,+ `projects ${body.data.projectIds.join(", ")}`,+ );++ logger.info(+ `Removed API keys for projects ${body.data.projectIds.join(", ")}`,+ );++ res.status(200).json({ message: "API keys deleted" });+ } catch (e) {+ logger.error("failed to remove API keys", e);+ res.status(500).json({ error: e });+ }+}