🪢 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(self-host): provision instance with default org/project/user/keys via `LANGFUSE_PROVISION_*` envs (#3216)
Marc Klingenddf43c0836c6
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 584217f972..d6feed5fba 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -110,7 +110,6 @@ jobs:- name: Seed DBrun: |pnpm run db:migrate- pnpm run db:seed- name: Buildrun: pnpm run build@@ -121,6 +120,16 @@ jobs:- name: Start Langfuserun: (pnpm run start&)+ env:+ LANGFUSE_PROVISION_ORG_ID: "seed-org-id"+ LANGFUSE_PROVISION_ORG_NAME: "Seed Org"+ LANGFUSE_PROVISION_PROJECT_ID: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"+ LANGFUSE_PROVISION_PROJECT_NAME: "Seed Project"+ LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY: "pk-lf-1234567890"+ LANGFUSE_PROVISION_PROJECT_SECRET_KEY: "sk-lf-1234567890"+ LANGFUSE_PROVISION_USER_EMAIL: "[email protected]"+ LANGFUSE_PROVISION_USER_NAME: "Demo User"+ LANGFUSE_PROVISION_USER_PASSWORD: "password"- name: run testsrun: pnpm --filter=web run testdiff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 5618cf7471..c730127b3e 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -21,6 +21,10 @@"import": "./dist/src/server/index.js","require": "./dist/src/server/index.js"},+ "./src/server/auth/apiKeys": {+ "import": "./dist/src/server/auth/apiKeys.js",+ "require": "./dist/src/server/auth/apiKeys.js"+ },"./encryption": {"import": "./dist/src/encryption/index.js","require": "./dist/src/encryption/index.js"diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex bb38ad4b47..04e25363e1 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -38,6 +38,7 @@ const EnvSchema = z.object({.number().positive().default(60 * 10),+ SALT: z.string().optional(), // used by components imported by web package});export const env = EnvSchema.parse(process.env);diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 946edcabda..b2400afa00 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -9,7 +9,7 @@ export * from "./types";export * from "./filterToPrisma";export * from "./orderByToPrisma";export * from "./tracesTable";-export * from "./server/auth/auth";+export * from "./server/auth/apiKeys";export * from "./observationsTable";export * from "./utils/zod";export * from "./utils/json";diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.tsnew file mode 100644index 0000000000..8522464fa4--- /dev/null+++ b/packages/shared/src/server/auth/apiKeys.ts@@ -0,0 +1,81 @@+import { PrismaClient } from "@prisma/client";+import { compare, hash } from "bcryptjs";+import { randomUUID } from "crypto";+import * as crypto from "crypto";+import { env } from "../../env";++export function getDisplaySecretKey(secretKey: string) {+ return secretKey.slice(0, 6) + "..." + secretKey.slice(-4);+}++export async function hashSecretKey(key: string) {+ // legacy, uses bcrypt, transformed into hashed key upon first use+ const hashedKey = await hash(key, 11);+ return hashedKey;+}++async function generateKeySet() {+ return {+ pk: `pk-lf-${randomUUID()}`,+ sk: `sk-lf-${randomUUID()}`,+ };+}++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;+}++export async function createAndAddApiKeysToDb(p: {+ prisma: PrismaClient;+ projectId: string;+ note?: string;+ predefinedKeys?: {+ secretKey: string;+ publicKey: string;+ };+}) {+ const salt = env.SALT;+ if (!salt) {+ throw new Error("SALT is not set");+ }++ const { pk, sk } = p.predefinedKeys+ ? { pk: p.predefinedKeys.publicKey, sk: p.predefinedKeys.secretKey }+ : await generateKeySet();++ const hashedSk = await hashSecretKey(sk);+ const displaySk = getDisplaySecretKey(sk);++ const hashFromProvidedKey = createShaHash(sk, salt);++ const apiKey = await p.prisma.apiKey.create({+ data: {+ projectId: p.projectId,+ publicKey: pk,+ hashedSecretKey: hashedSk,+ displaySecretKey: displaySk,+ fastHashedSecretKey: hashFromProvidedKey,+ note: p.note,+ },+ });++ return {+ id: apiKey.id,+ createdAt: apiKey.createdAt,+ note: apiKey.note,+ publicKey: apiKey.publicKey,+ secretKey: sk,+ displaySecretKey: displaySk,+ };+}diff --git a/packages/shared/src/server/auth/auth.ts b/packages/shared/src/server/auth/auth.tsdeleted file mode 100644index 6b5489583f..0000000000--- a/packages/shared/src/server/auth/auth.ts+++ /dev/null@@ -1,81 +0,0 @@-import { compare, hash } from "bcryptjs";-import { randomUUID } from "crypto";-import * as crypto from "crypto";-import type { OAuthConfig, OAuthUserConfig } from "next-auth/providers/oauth";--export function generateSecretKey() {- return `sk-lf-${randomUUID()}`;-}--export function generatePublicKey() {- return `pk-lf-${randomUUID()}`;-}--export function getDisplaySecretKey(secretKey: string) {- return secretKey.slice(0, 6) + "..." + secretKey.slice(-4);-}--export async function hashSecretKey(key: string) {- // legacy, uses bcrypt, transformed into hashed key upon first use- const hashedKey = await hash(key, 11);- return hashedKey;-}--export async function generateKeySet() {- const pk = generatePublicKey();- const sk = generateSecretKey();- const hashedSk = await hashSecretKey(sk);- const displaySk = getDisplaySecretKey(sk);-- return {- pk,- sk,- hashedSk,- displaySk,- };-}--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;-}--export interface CustomSSOUser extends Record<string, any> {- email: string;- id: string;- name: string;- verified: boolean;-}--export function CustomSSOProvider<P extends CustomSSOUser>(- options: OAuthUserConfig<P>-): OAuthConfig<P> {- return {- id: "custom",- name: "CustomSSOProvider",- type: "oauth",- wellKnown: `${options.issuer}/.well-known/openid-configuration`,- authorization: { params: { scope: "openid email profile" } }, // overridden by options.authorization to be able to set custom scopes, deep merged with this default- checks: ["pkce", "state"],- idToken: true,- profile(profile) {- return {- id: profile.sub,- name: profile.name,- email: profile.email,- image: null,- };- },- options,- };-}diff --git a/packages/shared/src/server/auth/customSsoProvider.ts b/packages/shared/src/server/auth/customSsoProvider.tsnew file mode 100644index 0000000000..97f9bbf9e2--- /dev/null+++ b/packages/shared/src/server/auth/customSsoProvider.ts@@ -0,0 +1,31 @@+import type { OAuthConfig, OAuthUserConfig } from "next-auth/providers/oauth";++interface CustomSSOUser extends Record<string, any> {+ email: string;+ id: string;+ name: string;+ verified: boolean;+}++export function CustomSSOProvider<P extends CustomSSOUser>(+ options: OAuthUserConfig<P>+): OAuthConfig<P> {+ return {+ id: "custom",+ name: "CustomSSOProvider",+ type: "oauth",+ wellKnown: `${options.issuer}/.well-known/openid-configuration`,+ authorization: { params: { scope: "openid email profile" } }, // overridden by options.authorization to be able to set custom scopes, deep merged with this default+ checks: ["pkce", "state"],+ idToken: true,+ profile(profile) {+ return {+ id: profile.sub,+ name: profile.name,+ email: profile.email,+ image: null,+ };+ },+ options,+ };+}diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 84a3f17a45..36cf8483c9 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -3,7 +3,8 @@ export * from "./services/email/organizationInvitation/sendMembershipInvitationEexport * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";export * from "./services/PromptService";-export * from "./auth/auth";+export * from "./auth/apiKeys";+export * from "./auth/customSsoProvider";export * from "./llm/fetchLLMCompletion";export * from "./llm/types";export * from "./utils/DatabaseReadStream";diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex 40cf79757f..eea64f088c 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -1,7 +1,4 @@-import { hash } from "bcryptjs";-import { env } from "@/src/env.mjs";-import { getDisplaySecretKey, hashSecretKey } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { type z } from "zod";@@ -24,10 +21,7 @@ export const pruneDatabase = async () => {await prisma.llmApiKeys.deleteMany();};-export function createBasicAuthHeader(- username: string,- password: string,-): string {+function createBasicAuthHeader(username: string, password: string): string {const base64Credentials = Buffer.from(`${username}:${password}`).toString("base64",);@@ -97,38 +91,3 @@ export async function makeZodVerifiedAPICall<T extends z.ZodTypeAny>(}return { body: resBody, status };}--export const setupUserAndProject = async () => {- const user = await prisma.user.create({- data: {- id: "user-1",- name: "Demo User",- email: "[email protected]",- password: await hash("password", 12),- },- });-- const project = await prisma.project.create({- data: {- id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- name: "llm-app",- apiKeys: {- create: [- {- note: "seeded key",- hashedSecretKey: await hashSecretKey("sk-lf-1234567890"),- displaySecretKey: getDisplaySecretKey("sk-lf-1234567890"),- publicKey: "pk-lf-1234567890",- },- ],- },- projectMembers: {- create: {- role: "OWNER",- userId: user.id,- },- },- },- });- return { user, project };-};diff --git a/web/src/env.mjs b/web/src/env.mjsindex 4bcc156413..3c91b4d9c8 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -171,6 +171,15 @@ export const env = createEnv({SENTRY_AUTH_TOKEN: z.string().optional(),SENTRY_CSP_REPORT_URI: z.string().optional(),LANGFUSE_RATE_LIMITS_ENABLED: z.enum(["true", "false"]).default("true"),+ LANGFUSE_PROVISION_ORG_ID: z.string().optional(),+ LANGFUSE_PROVISION_ORG_NAME: z.string().optional(),+ LANGFUSE_PROVISION_PROJECT_ID: z.string().optional(),+ LANGFUSE_PROVISION_PROJECT_NAME: z.string().optional(),+ LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY: z.string().optional(),+ LANGFUSE_PROVISION_PROJECT_SECRET_KEY: z.string().optional(),+ LANGFUSE_PROVISION_USER_EMAIL: z.string().email().optional(),+ LANGFUSE_PROVISION_USER_NAME: z.string().optional(),+ LANGFUSE_PROVISION_USER_PASSWORD: z.string().optional(),},/**@@ -323,6 +332,16 @@ export const env = createEnv({SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN,SENTRY_CSP_REPORT_URI: process.env.SENTRY_CSP_REPORT_URI,LANGFUSE_RATE_LIMITS_ENABLED: process.env.LANGFUSE_RATE_LIMITS_ENABLED,+ // provisioning+ LANGFUSE_PROVISION_ORG_ID: process.env.LANGFUSE_PROVISION_ORG_ID,+ LANGFUSE_PROVISION_ORG_NAME: process.env.LANGFUSE_PROVISION_ORG_NAME,+ LANGFUSE_PROVISION_PROJECT_ID: process.env.LANGFUSE_PROVISION_PROJECT_ID,+ LANGFUSE_PROVISION_PROJECT_NAME: process.env.LANGFUSE_PROVISION_PROJECT_NAME,+ LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY: process.env.LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY,+ LANGFUSE_PROVISION_PROJECT_SECRET_KEY: process.env.LANGFUSE_PROVISION_PROJECT_SECRET_KEY,+ LANGFUSE_PROVISION_USER_EMAIL: process.env.LANGFUSE_PROVISION_USER_EMAIL,+ LANGFUSE_PROVISION_USER_NAME: process.env.LANGFUSE_PROVISION_USER_NAME,+ LANGFUSE_PROVISION_USER_PASSWORD: process.env.LANGFUSE_PROVISION_USER_PASSWORD,},// Skip validation in Docker builds// DOCKER_BUILD is set in Dockerfilediff --git a/web/src/features/auth-credentials/server/signupApiHandler.ts b/web/src/features/auth-credentials/server/signupApiHandler.tsindex 0d5c3d55f6..211212eb72 100644--- a/web/src/features/auth-credentials/server/signupApiHandler.ts+++ b/web/src/features/auth-credentials/server/signupApiHandler.ts@@ -52,8 +52,8 @@ export async function signupApiHandler(}// EE: check if custom SSO configuration is enabled for this domain- const customSsoProvider = await getSsoAuthProviderIdForDomain(domain);- if (customSsoProvider) {+ const multiTenantSsoProvider = await getSsoAuthProviderIdForDomain(domain);+ if (multiTenantSsoProvider) {res.status(422).json({message: "You must sign in via SSO for this domain.",});diff --git a/web/src/features/public-api/server/apiKeyRouter.ts b/web/src/features/public-api/server/apiKeyRouter.tsindex 9c871edf06..38ba808872 100644--- a/web/src/features/public-api/server/apiKeyRouter.ts+++ b/web/src/features/public-api/server/apiKeyRouter.ts@@ -1,5 +1,4 @@import { auditLog } from "@/src/features/audit-logs/auditLog";-import { createShaHash, generateKeySet } from "@langfuse/shared/src/server";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,@@ -8,7 +7,7 @@ import {import * as z from "zod";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { redis } from "@langfuse/shared/src/server";-import { env } from "@/src/env.mjs";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";export const apiKeysRouter = createTRPCRouter({byProjectId: protectedProjectProcedure@@ -56,37 +55,20 @@ export const apiKeysRouter = createTRPCRouter({scope: "apiKeys:create",});- const { pk, sk, hashedSk, displaySk } = await generateKeySet();-- const salt = env.SALT;- const hashFromProvidedKey = createShaHash(sk, salt);-- const apiKey = await ctx.prisma.apiKey.create({- data: {- projectId: input.projectId,- publicKey: pk,- hashedSecretKey: hashedSk,- displaySecretKey: displaySk,- fastHashedSecretKey: hashFromProvidedKey,- note: input.note,- },+ const apiKeyMeta = await createAndAddApiKeysToDb({+ prisma: ctx.prisma,+ projectId: input.projectId,+ note: input.note,});await auditLog({session: ctx.session,resourceType: "apiKey",- resourceId: apiKey.id,+ resourceId: apiKeyMeta.id,action: "create",});- return {- id: apiKey.id,- createdAt: apiKey.createdAt,- note: input.note,- publicKey: apiKey.publicKey,- secretKey: sk,- displaySecretKey: displaySk,- };+ return apiKeyMeta;}),delete: protectedProjectProcedure.input(diff --git a/web/src/instrumentation.ts b/web/src/instrumentation.tsindex a9b837bfa7..8ef3ef9b0a 100644--- a/web/src/instrumentation.ts+++ b/web/src/instrumentation.ts@@ -3,5 +3,6 @@export async function register() {if (process.env.NEXT_RUNTIME === "nodejs") {await import("./datadog.server.config");+ await import("./provisioning");}}diff --git a/web/src/provisioning.ts b/web/src/provisioning.tsnew file mode 100644index 0000000000..ec306e2e78--- /dev/null+++ b/web/src/provisioning.ts@@ -0,0 +1,99 @@+import { env } from "@/src/env.mjs";+import { createUserEmailPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";+import { prisma } from "@langfuse/shared/src/db";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";++// Create Organization+if (env.LANGFUSE_PROVISION_ORG_ID) {+ const org = await prisma.organization.upsert({+ where: { id: env.LANGFUSE_PROVISION_ORG_ID },+ update: {},+ create: {+ id: env.LANGFUSE_PROVISION_ORG_ID,+ name: env.LANGFUSE_PROVISION_ORG_NAME ?? "Provisioned Org",+ },+ });++ // Create Project: Org -> Project+ if (env.LANGFUSE_PROVISION_PROJECT_ID) {+ await prisma.project.upsert({+ where: { id: env.LANGFUSE_PROVISION_PROJECT_ID },+ update: {},+ create: {+ id: env.LANGFUSE_PROVISION_PROJECT_ID,+ name: env.LANGFUSE_PROVISION_PROJECT_NAME ?? "Provisioned Project",+ orgId: org.id,+ },+ });++ // Add API Keys: Project -> API Key+ if (+ env.LANGFUSE_PROVISION_PROJECT_SECRET_KEY &&+ env.LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY+ ) {+ const existingApiKey = await prisma.apiKey.findUnique({+ where: { publicKey: env.LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY },+ });++ // Delete key if project changed+ if (+ existingApiKey &&+ existingApiKey.projectId !== env.LANGFUSE_PROVISION_PROJECT_ID+ ) {+ await prisma.apiKey.delete({+ where: { publicKey: env.LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY },+ });+ }++ // Create new key if it doesn't exist or project changed+ if (+ !existingApiKey ||+ existingApiKey.projectId !== env.LANGFUSE_PROVISION_PROJECT_ID+ ) {+ await createAndAddApiKeysToDb({+ prisma,+ projectId: env.LANGFUSE_PROVISION_PROJECT_ID,+ note: "Provisioned API Key",+ predefinedKeys: {+ secretKey: env.LANGFUSE_PROVISION_PROJECT_SECRET_KEY,+ publicKey: env.LANGFUSE_PROVISION_PROJECT_PUBLIC_KEY,+ },+ });+ }+ }+ }++ // Create User: Org -> User+ if (+ env.LANGFUSE_PROVISION_USER_EMAIL &&+ env.LANGFUSE_PROVISION_USER_PASSWORD+ ) {+ const existingUser = await prisma.user.findUnique({+ where: { email: env.LANGFUSE_PROVISION_USER_EMAIL },+ });++ let userId = existingUser?.id;++ // Create user if it doesn't exist yet+ if (!userId) {+ userId = await createUserEmailPassword(+ env.LANGFUSE_PROVISION_USER_EMAIL,+ env.LANGFUSE_PROVISION_USER_PASSWORD,+ env.LANGFUSE_PROVISION_USER_NAME ?? "Provisioned User",+ );+ }++ // Create OrgMembership: Org -> OrgMembership <- User+ await prisma.organizationMembership.upsert({+ where: {+ orgId_userId: { userId, orgId: org.id },+ },+ update: { role: "OWNER" },+ create: {+ userId,+ orgId: org.id,+ role: "OWNER",+ },+ });+ }+}diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 280a53e208..58fbf04d6d 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -104,8 +104,9 @@ const staticProviders: Provider[] = [}// EE: Check custom SSO enforcement- const customSsoProvider = await getSsoAuthProviderIdForDomain(domain);- if (customSsoProvider) {+ const multiTenantSsoProvider =+ await getSsoAuthProviderIdForDomain(domain);+ if (multiTenantSsoProvider) {throw new Error(`You must sign in via SSO for this domain.`);}@@ -416,8 +417,12 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {// EE: Check custom SSO enforcement, enforce the specific SSO provider on email domain// This also blocks setting a password for an email that is enforced to use SSO via password reset flowconst domain = email.split("@")[1];- const customSsoProvider = await getSsoAuthProviderIdForDomain(domain);- if (customSsoProvider && account?.provider !== customSsoProvider) {+ const multiTenantSsoProvider =+ await getSsoAuthProviderIdForDomain(domain);+ if (+ multiTenantSsoProvider &&+ account?.provider !== multiTenantSsoProvider+ ) {console.log("Custom SSO provider enforced for domain, user signed in with other provider",);