🪢 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
refactor(ee): move multi-tenant sso to /web/src/ee (#2722)
Marc Klingenc27c32f844c9
diff --git a/ee/src/env.ts b/ee/src/env.tsindex 74d23d4768..20f76a8098 100644--- a/ee/src/env.ts+++ b/ee/src/env.ts@@ -3,7 +3,6 @@ import { env as sharedEnv } from "@langfuse/shared";const EnvSchema = z.object({NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z.string().optional(),- ADMIN_API_KEY: z.string().optional(),});export const env = { ...sharedEnv, ...EnvSchema.parse(process.env) };diff --git a/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts b/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.tsnew file mode 100644index 0000000000..f316479ee0--- /dev/null+++ b/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts@@ -0,0 +1,74 @@+import { isEeEnabled } from "@/src/ee/utils/isEeEnabled";+import { prisma } from "@langfuse/shared/src/db";+import { encrypt } from "@langfuse/shared/encryption";+import { SsoProviderSchema } from "./types";+import { type NextApiRequest, type NextApiResponse } from "next";+import { env } from "@/src/env.mjs";++export async function createNewSsoConfigHandler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ if (!isEeEnabled) {+ res.status(403).json({ error: "EE is not available" });+ return;+ }+ // allow only POST requests+ if (req.method !== "POST") {+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }+ // check if ADMIN_API_KEY is set+ if (!env.ADMIN_API_KEY) {+ res.status(500).json({ error: "ADMIN_API_KEY is not set" });+ return;+ }+ if (!env.ENCRYPTION_KEY) {+ res.status(500).json({ error: "ENCRYPTION_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 = SsoProviderSchema.safeParse(req.body);+ if (!body.success) {+ res.status(400).json({ error: body.error });+ return;+ }++ const { domain, authProvider, authConfig } = body.data;++ const encryptedClientSecret = authConfig+ ? {+ ...authConfig,+ clientSecret: encrypt(authConfig.clientSecret),+ }+ : undefined;++ await prisma.ssoConfig.create({+ data: {+ domain,+ authProvider,+ authConfig: encryptedClientSecret,+ },+ });+ res.status(201).json({+ message: "SSO configuration created successfully",+ });+ } catch (e) {+ console.log(e);+ res.status(500).json({ error: "Internal Server Error" });+ }+}diff --git a/ee/src/sso/types.ts b/web/src/ee/features/multi-tenant-sso/types.tssimilarity index 100%rename from ee/src/sso/types.tsrename to web/src/ee/features/multi-tenant-sso/types.tsdiff --git a/ee/src/sso/index.ts b/web/src/ee/features/multi-tenant-sso/utils.tssimilarity index 75%rename from ee/src/sso/index.tsrename to web/src/ee/features/multi-tenant-sso/utils.tsindex 95735d1c40..fd03f72ca0 100644--- a/ee/src/sso/index.ts+++ b/web/src/ee/features/multi-tenant-sso/utils.ts@@ -5,12 +5,10 @@ import OktaProvider from "next-auth/providers/okta";import CognitoProvider from "next-auth/providers/cognito";import Auth0Provider from "next-auth/providers/auth0";import AzureADProvider from "next-auth/providers/azure-ad";-import { isEeAvailable } from "..";+import { isEeEnabled } from "@/src/ee/utils/isEeEnabled";import { type SsoConfig, prisma } from "@langfuse/shared/src/db";-import { encrypt, decrypt } from "@langfuse/shared/encryption";+import { decrypt } from "@langfuse/shared/encryption";import { SsoProviderSchema } from "./types";-import { type NextApiRequest, type NextApiResponse } from "next";-import { env } from "../env";import { CustomSSOProvider } from "@langfuse/shared/src/server";// Local cache for SSO configurations@@ -25,7 +23,7 @@ let cachedSsoConfigs: {* @returns {Promise<SsoProviderSchema[]>} - A list of all SSO configurations. Empty array if none are configured or EE is not available.*/async function getSsoConfigs(): Promise<SsoProviderSchema[]> {- if (!isEeAvailable) return [];+ if (!isEeEnabled) return [];const CACHE_TTL = 60 * 1000; // 1 minuteconst DB_MAX_WAIT = 2000; // 2 secondsconst DB_TIMEOUT = 3000; // 3 seconds@@ -43,7 +41,7 @@ async function getSsoConfigs(): Promise<SsoProviderSchema[]> {{maxWait: DB_MAX_WAIT,timeout: DB_TIMEOUT,- }+ },);} catch (e) {// cache empty array to prevent repeated DB calls on error@@ -65,7 +63,7 @@ async function getSsoConfigs(): Promise<SsoProviderSchema[]> {} catch (e) {console.error(`Failed to parse SSO provider config for domain ${v.domain}`,- e+ e,);return null;}@@ -87,7 +85,7 @@ async function getSsoConfigs(): Promise<SsoProviderSchema[]> {* @returns {Promise<Provider[]>} - A list of all custom SSO providers.*/export async function loadSsoProviders(): Promise<Provider[]> {- if (!isEeAvailable) return [];+ if (!isEeEnabled) return [];const ssoConfigs = await getSsoConfigs();@@ -105,7 +103,7 @@ export async function loadSsoProviders(): Promise<Provider[]> {* @returns `true` if any custom SSO provider is configured in the database.*/export async function isAnySsoConfigured(): Promise<boolean> {- if (!isEeAvailable) return false;+ if (!isEeEnabled) return false;const ssoConfigs = await getSsoConfigs();return ssoConfigs.length > 0;}@@ -117,11 +115,11 @@ export async function isAnySsoConfigured(): Promise<boolean> {* @returns `providerId` or null if none is configured or EE is not available.*/export async function getSsoAuthProviderIdForDomain(- domain: string+ domain: string,): Promise<string | null> {- if (!isEeAvailable) return null;+ if (!isEeEnabled) return null;const ssoConfig = (await getSsoConfigs()).find(- (ssoConfig) => ssoConfig.domain === domain.toLowerCase()+ (ssoConfig) => ssoConfig.domain === domain.toLowerCase(),);if (!ssoConfig) return null;@@ -185,10 +183,10 @@ const dbToNextAuthProvider = (provider: SsoProviderSchema): Provider | null => {});else {// Type check to ensure we handle all providers- // eslint-disable-next-line no-unused-vars+ // eslint-disable-next-line @typescript-eslint/no-unused-varsconst _: never = provider;throw new Error(- `Unrecognized SSO provider for domain ${(provider as any).domain}`+ `Unrecognized SSO provider for domain ${(provider as any).domain}`,);}};@@ -200,76 +198,8 @@ const dbToNextAuthProvider = (provider: SsoProviderSchema): Provider | null => {* @returns {string} - The providerId used in NextAuth.*/const getAuthProviderIdForSsoConfig = (- dbSsoConfig: SsoProviderSchema+ dbSsoConfig: SsoProviderSchema,): string => {if (!dbSsoConfig.authConfig) return dbSsoConfig.authProvider;return `${dbSsoConfig.domain}.${dbSsoConfig.authProvider}`;};--export async function createNewSsoConfigHandler(- req: NextApiRequest,- res: NextApiResponse-) {- try {- if (!isEeAvailable) {- res.status(403).json({ error: "EE is not available" });- return;- }- // allow only POST requests- if (req.method !== "POST") {- res.status(405).json({ error: "Method Not Allowed" });- return;- }- // check if ADMIN_API_KEY is set- if (!env.ADMIN_API_KEY) {- res.status(500).json({ error: "ADMIN_API_KEY is not set" });- return;- }- if (!env.ENCRYPTION_KEY) {- res.status(500).json({ error: "ENCRYPTION_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 = SsoProviderSchema.safeParse(req.body);- if (!body.success) {- res.status(400).json({ error: body.error });- return;- }-- const { domain, authProvider, authConfig } = body.data;-- const encryptedClientSecret = authConfig- ? {- ...authConfig,- clientSecret: encrypt(authConfig.clientSecret),- }- : undefined;-- await prisma.ssoConfig.create({- data: {- domain,- authProvider,- authConfig: encryptedClientSecret,- },- });- res.status(201).json({- message: "SSO configuration created successfully",- });- } catch (e) {- console.log(e);- res.status(500).json({ error: "Internal Server Error" });- }-}diff --git a/web/src/env.mjs b/web/src/env.mjsindex d3f4bec5c2..4268692b54 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -112,6 +112,14 @@ export const env = createEnv({ENABLE_EVENT_LOG: z.enum(["true", "false"]).optional().default("true"),// EE LicenseLANGFUSE_EE_LICENSE_KEY: z.string().optional(),+ ADMIN_API_KEY: z.string().optional(),+ ENCRYPTION_KEY: z+ .string()+ .length(+ 64,+ "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32"+ )+ .optional(),},/**@@ -229,6 +237,8 @@ export const env = createEnv({ENABLE_EVENT_LOG: process.env.ENABLE_EVENT_LOG,// EE LicenseLANGFUSE_EE_LICENSE_KEY: process.env.LANGFUSE_EE_LICENSE_KEY,+ ADMIN_API_KEY: process.env.ADMIN_API_KEY,+ ENCRYPTION_KEY: process.env.ENCRYPTION_KEY,},// 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 0e41b740be..0d5c3d55f6 100644--- a/web/src/features/auth-credentials/server/signupApiHandler.ts+++ b/web/src/features/auth-credentials/server/signupApiHandler.ts@@ -1,7 +1,7 @@import { env } from "@/src/env.mjs";import { createUserEmailPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";import { signupSchema } from "@/src/features/auth/lib/signupSchema";-import { getSsoAuthProviderIdForDomain } from "@langfuse/ee/sso";+import { getSsoAuthProviderIdForDomain } from "@/src/ee/features/multi-tenant-sso/utils";import type { NextApiRequest, NextApiResponse } from "next";/*diff --git a/web/src/pages/api/auth/add-sso-config.ts b/web/src/pages/api/auth/add-sso-config.tsindex a0e395834e..f0a7a0fc53 100644--- a/web/src/pages/api/auth/add-sso-config.ts+++ b/web/src/pages/api/auth/add-sso-config.ts@@ -4,6 +4,6 @@* This is an EE feature and will return a 404 response if EE is not available.*/-import { createNewSsoConfigHandler } from "@langfuse/ee/sso";+import { createNewSsoConfigHandler } from "@/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler";export default createNewSsoConfigHandler;diff --git a/web/src/pages/api/auth/check-sso.ts b/web/src/pages/api/auth/check-sso.tsindex 9a4104a037..c6bbd1e2b8 100644--- a/web/src/pages/api/auth/check-sso.ts+++ b/web/src/pages/api/auth/check-sso.ts@@ -4,7 +4,7 @@* If no custom SSO provider is configured or EE is not available, this API will return a 404 response.*/-import { getSsoAuthProviderIdForDomain } from "@langfuse/ee/sso";+import { getSsoAuthProviderIdForDomain } from "@/src/ee/features/multi-tenant-sso/utils";import type { NextApiRequest, NextApiResponse } from "next";import { z } from "zod";diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsxindex af47ac73b6..2171fa961e 100644--- a/web/src/pages/auth/sign-in.tsx+++ b/web/src/pages/auth/sign-in.tsx@@ -27,7 +27,7 @@ import { CloudPrivacyNotice } from "@/src/features/auth/components/AuthCloudPrivimport { CloudRegionSwitch } from "@/src/features/auth/components/AuthCloudRegionSwitch";import { PasswordInput } from "@/src/components/ui/password-input";import { Turnstile } from "@marsidev/react-turnstile";-import { isAnySsoConfigured } from "@langfuse/ee/sso";+import { isAnySsoConfigured } from "@/src/ee/features/multi-tenant-sso/utils";import { Shield } from "lucide-react";import { useRouter } from "next/router";import { captureException } from "@sentry/nextjs";diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 9edad92abb..514ac4f099 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -27,7 +27,7 @@ import { getCookieName, getCookieOptions } from "./utils/cookies";import {getSsoAuthProviderIdForDomain,loadSsoProviders,-} from "@langfuse/ee/sso";+} from "@/src/ee/features/multi-tenant-sso/utils";import { z } from "zod";import * as Sentry from "@sentry/nextjs";import {