Skip to content

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

refactor(ee): move multi-tenant sso to /web/src/ee (#2722)

Marc Klingenc27c32f844c9
diff --git a/ee/src/env.ts b/ee/src/env.ts
index 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.ts
new file mode 100644
index 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.ts
similarity index 100%
rename from ee/src/sso/types.ts
rename to web/src/ee/features/multi-tenant-sso/types.ts
diff --git a/ee/src/sso/index.ts b/web/src/ee/features/multi-tenant-sso/utils.ts
similarity index 75%
rename from ee/src/sso/index.ts
rename to web/src/ee/features/multi-tenant-sso/utils.ts
index 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 minute
const DB_MAX_WAIT = 2000; // 2 seconds
const 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-vars
const _: 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.mjs
index 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 License
LANGFUSE_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 License
LANGFUSE_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 Dockerfile
diff --git a/web/src/features/auth-credentials/server/signupApiHandler.ts b/web/src/features/auth-credentials/server/signupApiHandler.ts
index 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.ts
index 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.ts
index 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.tsx
index 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/AuthCloudPriv
import { 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.ts
index 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 {