Skip to content

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

Api auth (#382)

Max Deichmannadda58adb99d
diff --git a/.codespellrc b/.codespellrc
index 9572175333..d533d31fe1 100644
--- a/.codespellrc
+++ b/.codespellrc
@@ -1,4 +1,3 @@
[codespell]
skip = .git,*.pdf,*.svg,package-lock.json,*.prisma
-#
-# ignore-words-list =
+ignore-words-list = afterall
diff --git a/.env.cloud.example b/.env.cloud.example
index c2589129fd..1a5a572c31 100644
--- a/.env.cloud.example
+++ b/.env.cloud.example
@@ -17,7 +17,7 @@ DATABASE_URL="postgres://postgres:[pw]@db.[db_id].supabase.co:6543/postgres?pgbo
# openssl rand -base64 32
# https://next-auth.js.org/configuration/options#secret
NEXTAUTH_SECRET="secret"
-
+SALT="salt"
# Sentry; set via Vercel integration
# NEXT_PUBLIC_SENTRY_DSN=
# NEXT_SENTRY_ORG=
diff --git a/.env.dev.example b/.env.dev.example
index 1b0b730f38..835962ddde 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -15,4 +15,5 @@ NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="secret"
# Langfuse experimental features
-LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="true"
\ No newline at end of file
+LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="true"
+SALT="salt"
\ No newline at end of file
diff --git a/.env.local.example b/.env.local.example
index 364eff1f8f..a4f40b4a5b 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -12,4 +12,5 @@ NEXTAUTH_SECRET="secret"
NEXTAUTH_URL="http://localhost:3000"
# feature flag to enable experimental features locally
-LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="false"
\ No newline at end of file
+LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="false"
+SALT="salt"
\ No newline at end of file
diff --git a/prisma/migrations/20231019094815_add_additional_secret_key_column/migration.sql b/prisma/migrations/20231019094815_add_additional_secret_key_column/migration.sql
new file mode 100644
index 0000000000..e618ab1aa9
--- /dev/null
+++ b/prisma/migrations/20231019094815_add_additional_secret_key_column/migration.sql
@@ -0,0 +1,23 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[fast_hashed_secret_key]` on the table `api_keys` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- AlterTable
+ALTER TABLE "api_keys" ADD COLUMN "fast_hashed_secret_key" TEXT;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "api_keys_fast_hashed_secret_key_key" ON "api_keys"("fast_hashed_secret_key");
+
+-- CreateIndex
+CREATE INDEX "api_keys_project_id_idx" ON "api_keys"("project_id");
+
+-- CreateIndex
+CREATE INDEX "api_keys_public_key_idx" ON "api_keys"("public_key");
+
+-- CreateIndex
+CREATE INDEX "api_keys_hashed_secret_key_idx" ON "api_keys"("hashed_secret_key");
+
+-- CreateIndex
+CREATE INDEX "api_keys_fast_hashed_secret_key_idx" ON "api_keys"("fast_hashed_secret_key");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index b4da63afd2..84f890a789 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -89,17 +89,22 @@ model Project {
}
model ApiKey {
- id String @id @unique @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- note String?
- publicKey String @unique @map("public_key")
- hashedSecretKey String @unique @map("hashed_secret_key")
- displaySecretKey String @map("display_secret_key")
- lastUsedAt DateTime? @map("last_used_at")
- expiresAt DateTime? @map("expires_at")
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ id String @id @unique @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ note String?
+ publicKey String @unique @map("public_key")
+ hashedSecretKey String @unique @map("hashed_secret_key")
+ fastHashedSecretKey String? @unique @map("fast_hashed_secret_key")
+ displaySecretKey String @map("display_secret_key")
+ lastUsedAt DateTime? @map("last_used_at")
+ expiresAt DateTime? @map("expires_at")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ @@index(projectId)
+ @@index(publicKey)
+ @@index(hashedSecretKey)
+ @@index(fastHashedSecretKey)
@@map("api_keys")
}
diff --git a/src/__tests__/api-auth.servertest.ts b/src/__tests__/api-auth.servertest.ts
new file mode 100644
index 0000000000..b47440aeea
--- /dev/null
+++ b/src/__tests__/api-auth.servertest.ts
@@ -0,0 +1,115 @@
+import {
+ getDisplaySecretKey,
+ hashSecretKey,
+} from "@/src/features/public-api/lib/apiKeys";
+import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { prisma } from "@/src/server/db";
+
+describe("Validate api calls", () => {
+ beforeEach(async () => {
+ await prisma.score.deleteMany();
+ await prisma.observation.deleteMany();
+ await prisma.trace.deleteMany();
+ await prisma.apiKey.deleteMany();
+ });
+
+ it("should create new api key", async () => {
+ await createAPIKey();
+ const auth = await verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+ expect(auth.validKey).toBe(true);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
+ });
+
+ it("should create new api key and succeed with new key", async () => {
+ await createAPIKey();
+ const auth = await verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+ expect(auth.validKey).toBe(true);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
+
+ const auth2 = await verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+ expect(auth2.validKey).toBe(true);
+ });
+
+ it("should fail on wrong api key with new key", async () => {
+ await createAPIKey();
+ const auth = await verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+ expect(auth.validKey).toBe(true);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
+
+ const wrongAuth = await verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
+ );
+ expect(wrongAuth.validKey).toBe(false);
+ });
+
+ it("should fail on wrong api key without new key", async () => {
+ await createAPIKey();
+ const initialApiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(initialApiKey).not.toBeNull();
+ expect(initialApiKey?.fastHashedSecretKey).toBeNull();
+
+ const auth = await verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
+ );
+ expect(auth.validKey).toBe(false);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).toBeNull();
+ });
+
+ const createAPIKey = async () => {
+ const seedApiKey = {
+ id: "seed-api-key",
+ secret: "sk-lf-1234567890",
+ public: "pk-lf-1234567890",
+ note: "seeded key",
+ };
+ await prisma.apiKey.create({
+ data: {
+ note: seedApiKey.note,
+ id: seedApiKey.id,
+ publicKey: seedApiKey.public,
+ hashedSecretKey: await hashSecretKey(seedApiKey.secret),
+ displaySecretKey: getDisplaySecretKey(seedApiKey.secret),
+ project: {
+ connect: {
+ id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ },
+ },
+ });
+ };
+
+ afterAll(async () => {
+ await prisma.apiKey.deleteMany();
+ await createAPIKey();
+ });
+});
diff --git a/src/env.mjs b/src/env.mjs
index 2798249d87..30dc21fadf 100644
--- a/src/env.mjs
+++ b/src/env.mjs
@@ -29,6 +29,10 @@ export const env = createEnv({
LANGFUSE_NEW_USER_SIGNUP_WEBHOOK: z.string().url().optional(),
// Add `.min(1) on ID and SECRET if you want to make sure they're not empty
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: z.enum(["true", "false"]).optional(),
+ SALT: z.string({
+ required_error:
+ "A strong Salt is required to encrypt API keys securely. See: https://langfuse.com/docs/deployment/self-host#deploy-the-container",
+ }),
},
/**
@@ -63,5 +67,6 @@ export const env = createEnv({
LANGFUSE_TEAM_SLACK_WEBHOOK: process.env.LANGFUSE_TEAM_SLACK_WEBHOOK,
LANGFUSE_NEW_USER_SIGNUP_WEBHOOK:
process.env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK,
+ SALT: process.env.SALT,
},
});
diff --git a/src/features/public-api/lib/apiKeys.ts b/src/features/public-api/lib/apiKeys.ts
index c1f208a8af..e2420644d1 100644
--- a/src/features/public-api/lib/apiKeys.ts
+++ b/src/features/public-api/lib/apiKeys.ts
@@ -1,5 +1,6 @@
import { compare, hash } from "bcryptjs";
import { randomUUID } from "crypto";
+import * as crypto from "crypto";
export function generateSecretKey() {
return `sk-lf-${randomUUID()}`;
@@ -36,3 +37,13 @@ export async function verifySecretKey(key: string, hashedKey: string) {
const isValid = await compare(key, hashedKey);
return isValid;
}
+
+export function createShaHash(privateKey: string, salt: string): string {
+ const hash = crypto
+ .createHash("sha256")
+ .update(privateKey)
+ .update(crypto.createHash("sha256").update(salt, "utf8").digest("hex"))
+ .digest("hex");
+
+ return hash;
+}
diff --git a/src/features/public-api/server/apiAuth.ts b/src/features/public-api/server/apiAuth.ts
index c8f6de10c7..790684ccc7 100644
--- a/src/features/public-api/server/apiAuth.ts
+++ b/src/features/public-api/server/apiAuth.ts
@@ -1,4 +1,8 @@
-import { verifySecretKey } from "@/src/features/public-api/lib/apiKeys";
+import { env } from "@/src/env.mjs";
+import {
+ createShaHash,
+ verifySecretKey,
+} from "@/src/features/public-api/lib/apiKeys";
import { type ApiAccessScope } from "@/src/features/public-api/server/types";
import { prisma } from "@/src/server/db";
import { instrumentAsync } from "@/src/utils/instrumentation";
@@ -33,18 +37,38 @@ export async function verifyAuthHeaderAndReturnScope(
const { username: publicKey, password: secretKey } =
extractBasicAuthCredentials(authHeader);
- const dbKey = await findDbKeyOrThrow(publicKey);
+ const salt = env.SALT;
+ const hashFromProvidedKey = createShaHash(secretKey, salt);
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { fastHashedSecretKey: hashFromProvidedKey },
+ });
+ let projectId = apiKey?.projectId;
+
+ if (!apiKey || !apiKey.fastHashedSecretKey) {
+ const dbKey = await findDbKeyOrThrow(publicKey);
+ const isValid = await verifySecretKey(
+ secretKey,
+ dbKey.hashedSecretKey,
+ );
+ if (!isValid) throw new Error("Invalid credentials");
+
+ const shaKey = createShaHash(secretKey, salt);
- const isValid = await verifySecretKey(
- secretKey,
- dbKey.hashedSecretKey,
- );
- if (!isValid) throw new Error("Invalid credentials");
+ await prisma.apiKey.update({
+ where: { publicKey },
+ data: {
+ fastHashedSecretKey: shaKey,
+ },
+ });
+ projectId = dbKey.projectId;
+ }
+
+ if (!projectId) throw new Error("Invalid credentials");
return {
validKey: true,
scope: {
- projectId: dbKey.projectId,
+ projectId: projectId,
accessLevel: "all",
},
};