Skip to content

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

feat(sso): self-service SSO config with DNS-verified domains (#13507)

Mark Salpeter871a8d5a0728
diff --git a/packages/shared/prisma/migrations/20260506144028_add_verified_domains/migration.sql b/packages/shared/prisma/migrations/20260506144028_add_verified_domains/migration.sql
new file mode 100644
index 0000000000..67bf376a06
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260506144028_add_verified_domains/migration.sql
@@ -0,0 +1,25 @@
+-- CreateTable
+CREATE TABLE "verified_domains" (
+ "id" TEXT NOT NULL,
+ "organization_id" TEXT NOT NULL,
+ "domain" TEXT NOT NULL,
+ "verification_token" TEXT NOT NULL,
+ "verified_at" TIMESTAMP(3),
+ "created_by_user_id" TEXT,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "verified_domains_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "verified_domains_domain_key" ON "verified_domains"("domain");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "verified_domains_verification_token_key" ON "verified_domains"("verification_token");
+
+-- CreateIndex
+CREATE INDEX "verified_domains_organization_id_idx" ON "verified_domains"("organization_id");
+
+-- AddForeignKey
+ALTER TABLE "verified_domains" ADD CONSTRAINT "verified_domains_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/migrations/20260507120000_share_pending_verified_domains/migration.sql b/packages/shared/prisma/migrations/20260507120000_share_pending_verified_domains/migration.sql
new file mode 100644
index 0000000000..557430cda2
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260507120000_share_pending_verified_domains/migration.sql
@@ -0,0 +1,14 @@
+-- Pending claims are now shareable across orgs; verified claims remain
+-- exclusive. Drop the global uniqueness on `domain` and replace it with:
+-- 1. a per-org uniqueness on (organization_id, domain) for idempotency
+-- 2. a partial unique index on `domain` where verified_at IS NOT NULL,
+-- so at most one org can hold a verified claim for any given domain.
+
+DROP INDEX "verified_domains_domain_key";
+
+CREATE UNIQUE INDEX "verified_domains_organization_id_domain_key"
+ ON "verified_domains" ("organization_id", "domain");
+
+CREATE UNIQUE INDEX "verified_domains_domain_verified_key"
+ ON "verified_domains" ("domain")
+ WHERE "verified_at" IS NOT NULL;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 3458c52aa0..da15b9d2c4 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -106,6 +106,7 @@ model Organization {
ApiKey ApiKey[]
surveys Survey[]
cloudSpendAlerts CloudSpendAlert[]
+ verifiedDomains VerifiedDomain[]
@@map("organizations")
}
@@ -1066,6 +1067,28 @@ model SsoConfig {
@@map("sso_configs")
}
+// Domain ownership claim for an organization, verified via DNS TXT record.
+// Required before an SsoConfig can be created for that domain.
+model VerifiedDomain {
+ id String @id @default(uuid())
+ organizationId String @map("organization_id")
+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
+ domain String
+ verificationToken String @unique @default(uuid()) @map("verification_token")
+ verifiedAt DateTime? @map("verified_at")
+ createdByUserId String? @map("created_by_user_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ // A domain can have at most one pending claim per org (idempotency for
+ // create) and at most one verified claim across the whole instance
+ // (enforced via a partial unique index added in the migration, since
+ // Prisma cannot express partial uniqueness in the schema DSL).
+ @@unique([organizationId, domain])
+ @@index([organizationId])
+ @@map("verified_domains")
+}
+
model PosthogIntegration {
projectId String @id @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
diff --git a/web/src/__tests__/server/ssoConfigRouter.servertest.ts b/web/src/__tests__/server/ssoConfigRouter.servertest.ts
new file mode 100644
index 0000000000..872e8cbc68
--- /dev/null
+++ b/web/src/__tests__/server/ssoConfigRouter.servertest.ts
@@ -0,0 +1,840 @@
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { prisma } from "@langfuse/shared/src/db";
+import { decrypt, encrypt } from "@langfuse/shared/encryption";
+import { Role } from "@langfuse/shared";
+import type { Session } from "next-auth";
+import { v4 as uuidv4 } from "uuid";
+
+// `validateSsoConfig` does a live OIDC discovery fetch. Default mock returns
+// a valid response that mirrors the issuer; individual tests override.
+const fetchMock = vi.fn<typeof fetch>();
+beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ mockDiscoveryOk("https://example.okta.com");
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function mockDiscoveryOk(expectedIssuer: string) {
+ // Construct a fresh Response per call — Response bodies are single-use and
+ // tests that call `save` more than once would otherwise hit a consumed body.
+ fetchMock.mockImplementation(
+ async () =>
+ new Response(
+ JSON.stringify({
+ issuer: expectedIssuer,
+ authorization_endpoint: `${expectedIssuer}/authorize`,
+ token_endpoint: `${expectedIssuer}/oauth/token`,
+ jwks_uri: `${expectedIssuer}/.well-known/jwks.json`,
+ }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ );
+}
+
+async function createTestOrg() {
+ const orgId = uuidv4();
+ const userId = uuidv4();
+
+ const org = await prisma.organization.create({
+ data: { id: orgId, name: `SsoConfig Org ${orgId.slice(0, 8)}` },
+ });
+
+ const user = await prisma.user.create({
+ data: {
+ id: userId,
+ email: `ssoc-${userId.slice(0, 8)}@test.com`,
+ name: "Test User",
+ },
+ });
+
+ return { org, user };
+}
+
+function createSession(
+ user: { id: string; email: string | null; name: string | null },
+ org: { id: string; name: string },
+ role: Role,
+ plan: "cloud:enterprise" | "cloud:hobby",
+): Session {
+ return {
+ expires: "1",
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: org.id,
+ name: org.name,
+ role,
+ plan,
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: false,
+ projects: [],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ v4BetaToggleVisible: false,
+ observationEvals: false,
+ experimentsV4Enabled: false,
+ },
+ admin: false,
+ },
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: "cloud:enterprise",
+ },
+ };
+}
+
+async function prepareWithRole(
+ role: Role,
+ plan: "cloud:enterprise" | "cloud:hobby" = "cloud:enterprise",
+) {
+ const { org, user } = await createTestOrg();
+ await prisma.organizationMembership.create({
+ data: { userId: user.id, orgId: org.id, role },
+ });
+ const session = createSession(user, org, role, plan);
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+ return { org, user, session, caller };
+}
+
+const prepare = () => prepareWithRole(Role.OWNER);
+
+async function addVerifiedDomain(
+ orgId: string,
+ domain: string,
+ verified = true,
+) {
+ return prisma.verifiedDomain.create({
+ data: {
+ organizationId: orgId,
+ domain,
+ verifiedAt: verified ? new Date() : null,
+ },
+ });
+}
+
+const samplePayload = (domain: string) => ({
+ domain,
+ authProvider: "okta" as const,
+ authConfig: {
+ clientId: "client-123",
+ clientSecret: "super-secret-value",
+ issuer: "https://example.okta.com",
+ allowDangerousEmailAccountLinking: false,
+ },
+});
+
+describe("ssoConfigRouter.save", () => {
+ it("rejects when the domain has no verified VerifiedDomain row for the org", async () => {
+ const { org, caller } = await prepare();
+ const domain = `unverified-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain, /* verified */ false);
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+
+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(row).toBeNull();
+ });
+
+ it("rejects OIDC issuers that pass the https:// prefix but fail URL grammar", async () => {
+ // Pre-PR these fields used z.url(); the scheme-tightening refactor
+ // dropped grammar validation. `https://` (scheme only) and `https:// foo`
+ // both pass startsWith but are not valid URLs.
+ const { org, caller } = await prepare();
+ const domain = `bad-grammar-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ for (const badIssuer of ["https://", "https:// foo"]) {
+ await expect(
+ caller.ssoConfig.save({
+ orgId: org.id,
+ payload: {
+ ...samplePayload(domain),
+ authConfig: {
+ ...samplePayload(domain).authConfig,
+ issuer: badIssuer,
+ },
+ },
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ }
+ });
+
+ it("rejects Custom OIDC payloads with an empty name", async () => {
+ // The form labels Display Name as a user-facing required field; reject
+ // empty values at the schema layer so the form contract is enforced.
+ const { org, caller } = await prepare();
+ const domain = `custom-empty-name-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await expect(
+ caller.ssoConfig.save({
+ orgId: org.id,
+ payload: {
+ domain,
+ authProvider: "custom" as const,
+ authConfig: {
+ name: "",
+ clientId: "client-123",
+ clientSecret: "super-secret",
+ issuer: "https://example.okta.com",
+ allowDangerousEmailAccountLinking: false,
+ },
+ },
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+
+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(row).toBeNull();
+ });
+
+ it("rejects Azure AD payloads with an empty tenantId", async () => {
+ // Empty tenantId saves cleanly otherwise but locks all users out at
+ // sign-in (NextAuth builds https://login.microsoftonline.com//v2.0/...).
+ const { org, caller } = await prepare();
+ const domain = `azure-empty-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await expect(
+ caller.ssoConfig.save({
+ orgId: org.id,
+ payload: {
+ domain,
+ authProvider: "azure-ad" as const,
+ authConfig: {
+ clientId: "client-123",
+ clientSecret: "super-secret",
+ tenantId: "",
+ allowDangerousEmailAccountLinking: false,
+ },
+ },
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+
+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(row).toBeNull();
+ });
+
+ it("rejects when the verified domain belongs to a different org", async () => {
+ const a = await prepare();
+ const b = await prepare();
+ const domain = `cross-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(a.org.id, domain, true);
+
+ await expect(
+ b.caller.ssoConfig.save({
+ orgId: b.org.id,
+ payload: samplePayload(domain),
+ }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("creates a row, encrypts clientSecret, and emits an audit log", async () => {
+ const { org, user, caller } = await prepare();
+ const domain = `create-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ const result = await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+
+ expect(result.domain).toBe(domain);
+ expect(result.authProvider).toBe("okta");
+ // clientSecret must not appear in returned authConfig
+ expect((result.authConfig as Record<string, unknown>).clientSecret).toBe(
+ undefined,
+ );
+
+ const stored = await prisma.ssoConfig.findUniqueOrThrow({
+ where: { domain },
+ });
+ const storedConfig = stored.authConfig as Record<string, unknown>;
+ expect(storedConfig.clientId).toBe("client-123");
+ // clientSecret on disk is the encrypted blob, not the plaintext
+ expect(storedConfig.clientSecret).not.toBe("super-secret-value");
+ expect(decrypt(storedConfig.clientSecret as string)).toBe(
+ "super-secret-value",
+ );
+
+ const log = await prisma.auditLog.findFirst({
+ where: {
+ resourceType: "ssoConfig",
+ resourceId: domain,
+ action: "create",
+ },
+ });
+ expect(log).not.toBeNull();
+ expect(log?.userId).toBe(user.id);
+ expect(log?.orgId).toBe(org.id);
+ // before/after JSON must not contain plaintext clientSecret
+ expect(log?.after).not.toContain("super-secret-value");
+ expect(log?.before).toBeNull();
+ });
+
+ it("is idempotent — saving twice with the same payload yields one row", async () => {
+ const { org, caller } = await prepare();
+ const domain = `idem-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+
+ const count = await prisma.ssoConfig.count({ where: { domain } });
+ expect(count).toBe(1);
+ });
+
+ it("replaces the existing row on update and records action='update' in the audit log", async () => {
+ const { org, caller } = await prepare();
+ const domain = `update-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: {
+ ...samplePayload(domain),
+ authConfig: {
+ ...samplePayload(domain).authConfig,
+ clientId: "new-client-id",
+ clientSecret: "rotated-secret",
+ },
+ },
+ });
+
+ const stored = await prisma.ssoConfig.findUniqueOrThrow({
+ where: { domain },
+ });
+ const cfg = stored.authConfig as Record<string, unknown>;
+ expect(cfg.clientId).toBe("new-client-id");
+ expect(decrypt(cfg.clientSecret as string)).toBe("rotated-secret");
+
+ const updateLog = await prisma.auditLog.findFirst({
+ where: {
+ resourceType: "ssoConfig",
+ resourceId: domain,
+ action: "update",
+ },
+ orderBy: { createdAt: "desc" },
+ });
+ expect(updateLog).not.toBeNull();
+ expect(updateLog?.before).not.toBeNull();
+ expect(updateLog?.before).not.toContain("super-secret-value");
+ expect(updateLog?.before).not.toContain("rotated-secret");
+ });
+
+ it("preserves advanced authConfig fields on update for the same provider", async () => {
+ // Legacy support-endpoint configs may set scope, tokenEndpointAuthMethod,
+ // idTokenSignedResponseAlg, etc. The self-service form doesn't surface
+ // those fields, so a naive whole-row replace would silently wipe them
+ // when the admin re-enters the secret. Merge instead.
+ const { org, caller } = await prepare();
+ const domain = `merge-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await prisma.ssoConfig.create({
+ data: {
+ domain,
+ authProvider: "okta",
+ authConfig: {
+ clientId: "old-client",
+ clientSecret: encrypt("old-secret"),
+ issuer: "https://example.okta.com",
+ tokenEndpointAuthMethod: "private_key_jwt",
+ idTokenSignedResponseAlg: "RS256",
+ },
+ },
+ });
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+
+ const stored = await prisma.ssoConfig.findUniqueOrThrow({
+ where: { domain },
+ });
+ const cfg = stored.authConfig as Record<string, unknown>;
+ // Form-supplied fields take priority on the merge.
+ expect(cfg.clientId).toBe("client-123");
+ expect(decrypt(cfg.clientSecret as string)).toBe("super-secret-value");
+ // Advanced fields the form doesn't carry are preserved.
+ expect(cfg.tokenEndpointAuthMethod).toBe("private_key_jwt");
+ expect(cfg.idTokenSignedResponseAlg).toBe("RS256");
+ });
+
+ it("resets authConfig fields when the provider changes", async () => {
+ // Switching providers is an explicit reset — Custom-only fields like
+ // `name`/`scope` aren't valid in another provider's schema and shouldn't
+ // bleed across.
+ const { org, caller } = await prepare();
+ const domain = `switch-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await prisma.ssoConfig.create({
+ data: {
+ domain,
+ authProvider: "custom",
+ authConfig: {
+ name: "Old Custom",
+ clientId: "old-client",
+ clientSecret: encrypt("old-secret"),
+ issuer: "https://old.example.com",
+ scope: "openid email custom-scope",
+ },
+ },
+ });
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+
+ const stored = await prisma.ssoConfig.findUniqueOrThrow({
+ where: { domain },
+ });
+ const cfg = stored.authConfig as Record<string, unknown>;
+ expect(stored.authProvider).toBe("okta");
+ expect(cfg.name).toBeUndefined();
+ expect(cfg.scope).toBeUndefined();
+ });
+
+ it("rejects callers without organization:update scope (MEMBER role)", async () => {
+ const { org, caller } = await prepareWithRole(Role.MEMBER);
+ const domain = `forbidden-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+
+ it("rejects when the org plan lacks the cloud-multi-tenant-sso entitlement", async () => {
+ const { org, caller } = await prepareWithRole(Role.OWNER, "cloud:hobby");
+ const domain = `entitlement-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+});
+
+describe("ssoConfigRouter.get", () => {
+ it("returns rows scoped to verified domains for the org with clientSecret stripped", async () => {
+ const { org, caller } = await prepare();
+ const domain = `get-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+
+ const rows = await caller.ssoConfig.get({ orgId: org.id });
+ expect(rows).toHaveLength(1);
+ const row = rows[0];
+ expect(row.domain).toBe(domain);
+ const cfg = row.authConfig as Record<string, unknown>;
+ expect(cfg.clientId).toBe("client-123");
+ expect(cfg.clientSecret).toBe(undefined);
+ expect(cfg.issuer).toBe("https://example.okta.com");
+ });
+
+ it("does not return rows for unverified domains", async () => {
+ const { org, caller } = await prepare();
+ const verified = `verified-${uuidv4().slice(0, 8)}.com`;
+ const pending = `pending-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, verified, true);
+ await addVerifiedDomain(org.id, pending, false);
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(verified),
+ });
+ // Insert a stale config directly (mirrors a domain that was previously
+ // verified but later un-verified, or one that pre-dates the
+ // verified-domains feature).
+ await prisma.ssoConfig.create({
+ data: {
+ domain: pending,
+ authProvider: "okta",
+ authConfig: {
+ clientId: "x",
+ clientSecret: "y",
+ issuer: "https://x.okta.com",
+ },
+ },
+ });
+
+ const rows = await caller.ssoConfig.get({ orgId: org.id });
+ const domains = rows.map((r) => r.domain);
+ expect(domains).toContain(verified);
+ expect(domains).not.toContain(pending);
+ });
+
+ it("does not return rows for verified domains belonging to a different org", async () => {
+ const a = await prepare();
+ const b = await prepare();
+ const domainA = `org-a-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(a.org.id, domainA);
+ await a.caller.ssoConfig.save({
+ orgId: a.org.id,
+ payload: samplePayload(domainA),
+ });
+
+ const rowsB = await b.caller.ssoConfig.get({ orgId: b.org.id });
+ expect(rowsB.map((r) => r.domain)).not.toContain(domainA);
+ });
+});
+
+describe("ssoConfigRouter.delete", () => {
+ it("removes the row and emits an audit log", async () => {
+ const { org, caller } = await prepare();
+ const domain = `delete-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+ await caller.ssoConfig.delete({ orgId: org.id, domain });
+
+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(row).toBeNull();
+
+ const log = await prisma.auditLog.findFirst({
+ where: {
+ resourceType: "ssoConfig",
+ resourceId: domain,
+ action: "delete",
+ },
+ });
+ expect(log).not.toBeNull();
+ expect(log?.before).not.toContain("super-secret-value");
+ });
+
+ it("returns NOT_FOUND when the domain has no SsoConfig", async () => {
+ const { org, caller } = await prepare();
+ const domain = `missing-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ await expect(
+ caller.ssoConfig.delete({ orgId: org.id, domain }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it("returns NOT_FOUND when the verified domain belongs to a different org", async () => {
+ const a = await prepare();
+ const b = await prepare();
+ const domain = `cross-delete-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(a.org.id, domain);
+ await a.caller.ssoConfig.save({
+ orgId: a.org.id,
+ payload: samplePayload(domain),
+ });
+
+ await expect(
+ b.caller.ssoConfig.delete({ orgId: b.org.id, domain }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+
+ // The row must still exist for org A.
+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(row).not.toBeNull();
+ });
+
+ it("returns NOT_FOUND when the caller only holds a pending VerifiedDomain claim", async () => {
+ // Guards the legacy-config bypass: an SsoConfig provisioned by the admin
+ // REST handler has no VerifiedDomain backing. Without the verifiedAt gate,
+ // any org could claim a pending row for that domain and delete the
+ // active config out from under the real owner.
+ const { org, caller } = await prepare();
+ const domain = `pending-delete-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain, /* verified */ false);
+ await prisma.ssoConfig.create({
+ data: {
+ domain,
+ authProvider: "okta",
+ authConfig: {
+ clientId: "x",
+ clientSecret: "y",
+ issuer: "https://x.okta.com",
+ },
+ },
+ });
+
+ await expect(
+ caller.ssoConfig.delete({ orgId: org.id, domain }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+
+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(row).not.toBeNull();
+ });
+
+ it("rejects callers without organization:update scope (MEMBER role)", async () => {
+ const owner = await prepare();
+ const member = await prepareWithRole(Role.MEMBER);
+ const domain = `delete-rbac-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(owner.org.id, domain);
+ await owner.caller.ssoConfig.save({
+ orgId: owner.org.id,
+ payload: samplePayload(domain),
+ });
+
+ await expect(
+ member.caller.ssoConfig.delete({ orgId: member.org.id, domain }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+});
+
+describe("ssoConfigRouter.save — IdP discovery validation", () => {
+ function discoveryResponse(body: unknown, status = 200) {
+ return new Response(
+ typeof body === "string" ? body : JSON.stringify(body),
+ { status, headers: { "content-type": "application/json" } },
+ );
+ }
+
+ it("rejects when the discovery endpoint returns a non-2xx", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-404-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ fetchMock.mockResolvedValueOnce(discoveryResponse({}, 404));
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+
+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(row).toBeNull();
+ });
+
+ it("rejects when the discovery endpoint is unreachable", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-unreachable-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ fetchMock.mockRejectedValueOnce(new Error("ECONNREFUSED"));
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("rejects when the discovery endpoint redirects (SSRF defense)", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-redirect-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ // `redirect: "error"` means a 3xx surfaces as a fetch rejection. Real
+ // IdPs serve `.well-known/openid-configuration` with a 200 directly per
+ // OIDC Discovery §4; a redirect is a sign that the configured issuer is
+ // either misconfigured or trying to bounce us at an internal endpoint.
+ fetchMock.mockRejectedValueOnce(new TypeError("redirect not allowed"));
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("rejects when the discovery body is not valid JSON", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-bad-json-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ fetchMock.mockResolvedValueOnce(discoveryResponse("not json", 200));
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("rejects when the discovery doc is missing required fields", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-missing-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ fetchMock.mockResolvedValueOnce(
+ discoveryResponse({ issuer: "https://example.okta.com" }),
+ );
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("rejects when the returned issuer does not match the configured one", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-mismatch-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ fetchMock.mockResolvedValueOnce(
+ discoveryResponse({
+ issuer: "https://different.okta.com",
+ authorization_endpoint: "https://different.okta.com/authorize",
+ token_endpoint: "https://different.okta.com/oauth/token",
+ jwks_uri: "https://different.okta.com/.well-known/jwks.json",
+ }),
+ );
+
+ await expect(
+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("accepts a discovery doc whose issuer matches modulo trailing slash", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-slash-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ // Auth0-style: discovery returns the issuer with a trailing slash even
+ // though we configured it without one.
+ fetchMock.mockResolvedValueOnce(
+ discoveryResponse({
+ issuer: "https://example.okta.com/",
+ authorization_endpoint: "https://example.okta.com/authorize",
+ token_endpoint: "https://example.okta.com/oauth/token",
+ jwks_uri: "https://example.okta.com/.well-known/jwks.json",
+ }),
+ );
+
+ const result = await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+ expect(result.domain).toBe(domain);
+ });
+
+ it("calls the right discovery URL for the configured issuer", async () => {
+ const { org, caller } = await prepare();
+ const domain = `discovery-url-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ mockDiscoveryOk("https://example.okta.com");
+
+ await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: samplePayload(domain),
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://example.okta.com/.well-known/openid-configuration",
+ expect.any(Object),
+ );
+ });
+
+ it("accepts the {tenantid} placeholder in Azure AD multi-tenant discovery responses", async () => {
+ // Microsoft returns a literal `{tenantid}` placeholder in the discovery
+ // doc for tenantId values "common", "organizations", and "consumers" —
+ // the actual tenant is bound at sign-in time per user. A strict
+ // equality check would block these legitimate multi-tenant configs.
+ const { org, caller } = await prepare();
+ const domain = `azure-multi-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ fetchMock.mockResolvedValueOnce(
+ discoveryResponse({
+ issuer: "https://login.microsoftonline.com/{tenantid}/v2.0",
+ authorization_endpoint:
+ "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
+ token_endpoint:
+ "https://login.microsoftonline.com/common/oauth2/v2.0/token",
+ jwks_uri:
+ "https://login.microsoftonline.com/common/discovery/v2.0/keys",
+ }),
+ );
+
+ const result = await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: {
+ domain,
+ authProvider: "azure-ad" as const,
+ authConfig: {
+ clientId: "azure-client",
+ clientSecret: "azure-secret",
+ tenantId: "common",
+ allowDangerousEmailAccountLinking: false,
+ },
+ },
+ });
+
+ expect(result.domain).toBe(domain);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration",
+ expect.any(Object),
+ );
+ });
+
+ it("still rejects single-tenant Azure AD when the discovery issuer does not match", async () => {
+ const { org, caller } = await prepare();
+ const domain = `azure-single-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+
+ // Specific tenantId — Microsoft returns a real issuer with that tenant
+ // GUID, not the placeholder. A mismatch must still throw.
+ fetchMock.mockResolvedValueOnce(
+ discoveryResponse({
+ issuer: "https://login.microsoftonline.com/{tenantid}/v2.0",
+ authorization_endpoint: "https://login.microsoftonline.com/x/authorize",
+ token_endpoint: "https://login.microsoftonline.com/x/token",
+ jwks_uri: "https://login.microsoftonline.com/x/keys",
+ }),
+ );
+
+ await expect(
+ caller.ssoConfig.save({
+ orgId: org.id,
+ payload: {
+ domain,
+ authProvider: "azure-ad" as const,
+ authConfig: {
+ clientId: "azure-client",
+ clientSecret: "azure-secret",
+ tenantId: "00000000-0000-0000-0000-000000000000",
+ allowDangerousEmailAccountLinking: false,
+ },
+ },
+ }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("skips discovery for OAuth-only providers (github)", async () => {
+ const { org, caller } = await prepare();
+ const domain = `github-skip-${uuidv4().slice(0, 8)}.com`;
+ await addVerifiedDomain(org.id, domain);
+ fetchMock.mockClear();
+
+ const result = await caller.ssoConfig.save({
+ orgId: org.id,
+ payload: {
+ domain,
+ authProvider: "github" as const,
+ authConfig: {
+ clientId: "gh-client",
+ clientSecret: "gh-secret",
+ allowDangerousEmailAccountLinking: true,
+ },
+ },
+ });
+
+ expect(result.domain).toBe(domain);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/__tests__/server/verifiedDomainRouter.servertest.ts b/web/src/__tests__/server/verifiedDomainRouter.servertest.ts
new file mode 100644
index 0000000000..5cc1751f5b
--- /dev/null
+++ b/web/src/__tests__/server/verifiedDomainRouter.servertest.ts
@@ -0,0 +1,560 @@
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { resolveTxtFresh } from "@/src/ee/features/verified-domains/server/dnsLookup";
+import { prisma, Prisma } from "@langfuse/shared/src/db";
+import { Role } from "@langfuse/shared";
+import { TRPCError } from "@trpc/server";
+import type { Session } from "next-auth";
+import type { Mock } from "vitest";
+import { v4 as uuidv4 } from "uuid";
+
+vi.mock("@/src/ee/features/verified-domains/server/dnsLookup", () => ({
+ resolveTxtFresh: vi.fn(),
+}));
+
+const resolveTxtMock = resolveTxtFresh as unknown as Mock;
+
+beforeEach(() => {
+ resolveTxtMock.mockReset();
+});
+
+async function createTestOrg() {
+ const orgId = uuidv4();
+ const userId = uuidv4();
+
+ const org = await prisma.organization.create({
+ data: { id: orgId, name: `VerifiedDomain Org ${orgId.slice(0, 8)}` },
+ });
+
+ const user = await prisma.user.create({
+ data: {
+ id: userId,
+ email: `vd-${userId.slice(0, 8)}@test.com`,
+ name: "Test User",
+ },
+ });
+
+ return { org, user };
+}
+
+function createSession(
+ user: { id: string; email: string | null; name: string | null },
+ org: { id: string; name: string },
+ role: Role,
+ plan: "cloud:enterprise" | "cloud:hobby",
+): Session {
+ return {
+ expires: "1",
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: org.id,
+ name: org.name,
+ role,
+ plan,
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: false,
+ projects: [],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ v4BetaToggleVisible: false,
+ observationEvals: false,
+ experimentsV4Enabled: false,
+ },
+ admin: false,
+ },
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: "cloud:enterprise",
+ },
+ };
+}
+
+async function prepareWithRole(
+ role: Role,
+ plan: "cloud:enterprise" | "cloud:hobby" = "cloud:enterprise",
+) {
+ const { org, user } = await createTestOrg();
+ await prisma.organizationMembership.create({
+ data: { userId: user.id, orgId: org.id, role },
+ });
+ const session = createSession(user, org, role, plan);
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+ return { org, user, session, caller };
+}
+
+const prepare = () => prepareWithRole(Role.OWNER);
+
+describe("verifiedDomainRouter.create", () => {
+ it("creates a pending row and returns DNS record details", async () => {
+ const { org, user, caller } = await prepare();
+ const domain = `acme-${uuidv4().slice(0, 8)}.com`;
+
+ const result = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ expect(result.domain).toBe(domain);
+ expect(result.verifiedAt).toBeNull();
+ expect(result.recordHost).toBe("_langfuse-verification");
+ expect(result.recordValue).toMatch(/^langfuse-verify=/);
+
+ const row = await prisma.verifiedDomain.findFirst({ where: { domain } });
+ expect(row?.organizationId).toBe(org.id);
+ expect(row?.createdByUserId).toBe(user.id);
+ });
+
+ it("is idempotent for the same org (returns existing row)", async () => {
+ const { org, caller } = await prepare();
+ const domain = `idem-${uuidv4().slice(0, 8)}.com`;
+
+ const first = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+ const second = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ expect(second.id).toBe(first.id);
+ expect(second.recordValue).toBe(first.recordValue);
+
+ const count = await prisma.verifiedDomain.count({ where: { domain } });
+ expect(count).toBe(1);
+ });
+
+ it("allows another org to create a pending claim for the same domain", async () => {
+ // Pending claims are shareable across orgs — they're just unverified DNS
+ // intent. Only verified rows are exclusive. Without this, a hobby-plan
+ // squatter could lock out the legitimate enterprise customer.
+ const a = await prepare();
+ const b = await prepare();
+ const domain = `shared-pending-${uuidv4().slice(0, 8)}.com`;
+
+ await a.caller.verifiedDomain.create({ orgId: a.org.id, domain });
+ const bResult = await b.caller.verifiedDomain.create({
+ orgId: b.org.id,
+ domain,
+ });
+
+ expect(bResult.domain).toBe(domain);
+ expect(bResult.verifiedAt).toBeNull();
+
+ const rows = await prisma.verifiedDomain.findMany({ where: { domain } });
+ expect(rows).toHaveLength(2);
+ });
+
+ it("returns CONFLICT when another org has already verified the domain", async () => {
+ const a = await prepare();
+ const b = await prepare();
+ const domain = `verified-elsewhere-${uuidv4().slice(0, 8)}.com`;
+
+ await prisma.verifiedDomain.create({
+ data: {
+ organizationId: a.org.id,
+ domain,
+ verifiedAt: new Date(),
+ },
+ });
+
+ await expect(
+ b.caller.verifiedDomain.create({ orgId: b.org.id, domain }),
+ ).rejects.toThrow(TRPCError);
+ await expect(
+ b.caller.verifiedDomain.create({ orgId: b.org.id, domain }),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+ });
+
+ it("rejects callers without organization:update scope (MEMBER role)", async () => {
+ const { org, caller } = await prepareWithRole(Role.MEMBER);
+ const domain = `forbidden-${uuidv4().slice(0, 8)}.com`;
+
+ await expect(
+ caller.verifiedDomain.create({ orgId: org.id, domain }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+
+ it("rejects when the org plan lacks the cloud-multi-tenant-sso entitlement", async () => {
+ const { org, caller } = await prepareWithRole(Role.OWNER, "cloud:hobby");
+ const domain = `entitlement-${uuidv4().slice(0, 8)}.com`;
+
+ await expect(
+ caller.verifiedDomain.create({ orgId: org.id, domain }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+
+ it("returns CONFLICT when the create races a concurrent verified insert (P2002)", async () => {
+ const { org, caller } = await prepare();
+ const domain = `race-${uuidv4().slice(0, 8)}.com`;
+
+ // Simulate the race where another org verifies between our pre-check and
+ // create — the partial unique index on `domain WHERE verified_at IS NOT
+ // NULL` fires. The handler must translate P2002 to CONFLICT.
+ const spy = vi.spyOn(prisma.verifiedDomain, "create").mockRejectedValueOnce(
+ new Prisma.PrismaClientKnownRequestError("Unique constraint failed", {
+ code: "P2002",
+ clientVersion: "test",
+ }),
+ );
+
+ await expect(
+ caller.verifiedDomain.create({ orgId: org.id, domain }),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+
+ spy.mockRestore();
+ });
+
+ it("emits an audit log on create", async () => {
+ const { org, user, caller } = await prepare();
+ const domain = `audit-${uuidv4().slice(0, 8)}.com`;
+
+ const result = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ const log = await prisma.auditLog.findFirst({
+ where: {
+ resourceType: "verifiedDomain",
+ resourceId: result.id,
+ action: "create",
+ },
+ });
+ expect(log).not.toBeNull();
+ expect(log?.userId).toBe(user.id);
+ expect(log?.orgId).toBe(org.id);
+ });
+});
+
+describe("verifiedDomainRouter.list", () => {
+ it("returns rows scoped to the caller's org", async () => {
+ const { org, caller } = await prepare();
+ const a = `list-a-${uuidv4().slice(0, 8)}.com`;
+ const b = `list-b-${uuidv4().slice(0, 8)}.com`;
+
+ await caller.verifiedDomain.create({ orgId: org.id, domain: a });
+ await caller.verifiedDomain.create({ orgId: org.id, domain: b });
+
+ const rows = await caller.verifiedDomain.list({ orgId: org.id });
+ const domains = rows.map((r) => r.domain).sort();
+ expect(domains).toEqual([a, b].sort());
+
+ rows.forEach((r) => {
+ expect(r.recordHost).toBe("_langfuse-verification");
+ expect(r.recordValue).toMatch(/^langfuse-verify=/);
+ });
+ });
+});
+
+describe("verifiedDomainRouter.verify", () => {
+ it("sets verifiedAt and emits an audit log when the TXT record matches", async () => {
+ const { org, caller } = await prepare();
+ const domain = `verify-ok-${uuidv4().slice(0, 8)}.com`;
+
+ const created = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ resolveTxtMock.mockResolvedValueOnce([
+ ["some-other-record"],
+ [created.recordValue],
+ ]);
+
+ const result = await caller.verifiedDomain.verify({
+ orgId: org.id,
+ id: created.id,
+ });
+
+ expect(result.verifiedAt).not.toBeNull();
+ expect(resolveTxtMock).toHaveBeenCalledWith(
+ `${created.recordHost}.${created.domain}`,
+ );
+
+ const log = await prisma.auditLog.findFirst({
+ where: {
+ resourceType: "verifiedDomain",
+ resourceId: created.id,
+ action: "verify",
+ },
+ });
+ expect(log).not.toBeNull();
+ });
+
+ it("joins multi-chunk TXT record values before matching", async () => {
+ const { org, caller } = await prepare();
+ const domain = `verify-chunked-${uuidv4().slice(0, 8)}.com`;
+
+ const created = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ const half = Math.floor(created.recordValue.length / 2);
+ const chunked = [
+ [created.recordValue.slice(0, half), created.recordValue.slice(half)],
+ ];
+ resolveTxtMock.mockResolvedValueOnce(chunked);
+
+ const result = await caller.verifiedDomain.verify({
+ orgId: org.id,
+ id: created.id,
+ });
+ expect(result.verifiedAt).not.toBeNull();
+ });
+
+ it("returns PRECONDITION_FAILED when no TXT record matches", async () => {
+ const { org, caller } = await prepare();
+ const domain = `verify-mismatch-${uuidv4().slice(0, 8)}.com`;
+
+ const created = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ resolveTxtMock.mockResolvedValueOnce([["langfuse-verify=wrong"]]);
+
+ await expect(
+ caller.verifiedDomain.verify({ orgId: org.id, id: created.id }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+
+ const row = await prisma.verifiedDomain.findFirst({ where: { domain } });
+ expect(row?.verifiedAt).toBeNull();
+ });
+
+ it("returns PRECONDITION_FAILED when DNS lookup throws", async () => {
+ const { org, caller } = await prepare();
+ const domain = `verify-nxdomain-${uuidv4().slice(0, 8)}.com`;
+
+ const created = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ const err = Object.assign(new Error("queryTxt ENOTFOUND"), {
+ code: "ENOTFOUND",
+ });
+ resolveTxtMock.mockRejectedValueOnce(err);
+
+ await expect(
+ caller.verifiedDomain.verify({ orgId: org.id, id: created.id }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ });
+
+ it("is a no-op for an already-verified row", async () => {
+ const { org, caller } = await prepare();
+ const domain = `verify-noop-${uuidv4().slice(0, 8)}.com`;
+
+ const created = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ resolveTxtMock.mockResolvedValueOnce([[created.recordValue]]);
+ await caller.verifiedDomain.verify({ orgId: org.id, id: created.id });
+
+ const second = await caller.verifiedDomain.verify({
+ orgId: org.id,
+ id: created.id,
+ });
+
+ expect(second.verifiedAt).not.toBeNull();
+ expect(resolveTxtMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns CONFLICT when another org verifies the same domain first", async () => {
+ const a = await prepare();
+ const b = await prepare();
+ const domain = `verify-race-${uuidv4().slice(0, 8)}.com`;
+
+ const aRow = await a.caller.verifiedDomain.create({
+ orgId: a.org.id,
+ domain,
+ });
+ const bRow = await b.caller.verifiedDomain.create({
+ orgId: b.org.id,
+ domain,
+ });
+
+ resolveTxtMock.mockResolvedValue([[aRow.recordValue], [bRow.recordValue]]);
+
+ await a.caller.verifiedDomain.verify({ orgId: a.org.id, id: aRow.id });
+
+ // The partial unique index fires on B's update; the handler translates
+ // P2002 into CONFLICT.
+ await expect(
+ b.caller.verifiedDomain.verify({ orgId: b.org.id, id: bRow.id }),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+
+ const bAfter = await prisma.verifiedDomain.findUnique({
+ where: { id: bRow.id },
+ });
+ expect(bAfter?.verifiedAt).toBeNull();
+ });
+
+ it("returns NOT_FOUND when the row belongs to a different org", async () => {
+ const a = await prepare();
+ const b = await prepare();
+
+ const created = await a.caller.verifiedDomain.create({
+ orgId: a.org.id,
+ domain: `cross-org-${uuidv4().slice(0, 8)}.com`,
+ });
+
+ await expect(
+ b.caller.verifiedDomain.verify({ orgId: b.org.id, id: created.id }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+});
+
+describe("verifiedDomainRouter.delete", () => {
+ it("removes the row and emits an audit log", async () => {
+ const { org, caller } = await prepare();
+ const domain = `delete-${uuidv4().slice(0, 8)}.com`;
+
+ const created = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+
+ await caller.verifiedDomain.delete({ orgId: org.id, id: created.id });
+
+ const row = await prisma.verifiedDomain.findFirst({ where: { domain } });
+ expect(row).toBeNull();
+
+ const log = await prisma.auditLog.findFirst({
+ where: {
+ resourceType: "verifiedDomain",
+ resourceId: created.id,
+ action: "delete",
+ },
+ });
+ expect(log).not.toBeNull();
+ });
+
+ it("returns NOT_FOUND when the row belongs to a different org", async () => {
+ const a = await prepare();
+ const b = await prepare();
+
+ const created = await a.caller.verifiedDomain.create({
+ orgId: a.org.id,
+ domain: `delete-cross-${uuidv4().slice(0, 8)}.com`,
+ });
+
+ await expect(
+ b.caller.verifiedDomain.delete({ orgId: b.org.id, id: created.id }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it("returns PRECONDITION_FAILED when deleting a verified domain whose SSO is still active", async () => {
+ const { org, caller } = await prepare();
+ const domain = `delete-with-sso-${uuidv4().slice(0, 8)}.com`;
+
+ const created = await caller.verifiedDomain.create({
+ orgId: org.id,
+ domain,
+ });
+ await prisma.verifiedDomain.update({
+ where: { id: created.id },
+ data: { verifiedAt: new Date() },
+ });
+ await prisma.ssoConfig.create({
+ data: {
+ domain,
+ authProvider: "okta",
+ authConfig: {
+ clientId: "x",
+ clientSecret: "y",
+ issuer: "https://x.okta.com",
+ },
+ },
+ });
+
+ await expect(
+ caller.verifiedDomain.delete({ orgId: org.id, id: created.id }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+
+ const row = await prisma.verifiedDomain.findFirst({ where: { domain } });
+ expect(row).not.toBeNull();
+ });
+
+ it("allows deleting a pending claim even when another org's verified SsoConfig exists for the domain", async () => {
+ // Pending claims are shareable across orgs and have no SSO bearing — the
+ // active SsoConfig necessarily belongs to a different org's verified
+ // row. Without this exemption, a stale pending claim would be trapped
+ // permanently because the orphan check would fire on the other org's
+ // config.
+ const a = await prepare();
+ const b = await prepare();
+ const domain = `pending-with-other-sso-${uuidv4().slice(0, 8)}.com`;
+
+ const pendingClaim = await a.caller.verifiedDomain.create({
+ orgId: a.org.id,
+ domain,
+ });
+ const verifiedClaim = await b.caller.verifiedDomain.create({
+ orgId: b.org.id,
+ domain,
+ });
+ await prisma.verifiedDomain.update({
+ where: { id: verifiedClaim.id },
+ data: { verifiedAt: new Date() },
+ });
+ await prisma.ssoConfig.create({
+ data: {
+ domain,
+ authProvider: "okta",
+ authConfig: {
+ clientId: "x",
+ clientSecret: "y",
+ issuer: "https://x.okta.com",
+ },
+ },
+ });
+
+ await a.caller.verifiedDomain.delete({
+ orgId: a.org.id,
+ id: pendingClaim.id,
+ });
+
+ const pendingAfter = await prisma.verifiedDomain.findUnique({
+ where: { id: pendingClaim.id },
+ });
+ expect(pendingAfter).toBeNull();
+ // Org B's verified row + SSO config are untouched.
+ const verifiedAfter = await prisma.verifiedDomain.findUnique({
+ where: { id: verifiedClaim.id },
+ });
+ expect(verifiedAfter?.verifiedAt).not.toBeNull();
+ const sso = await prisma.ssoConfig.findUnique({ where: { domain } });
+ expect(sso).not.toBeNull();
+ });
+
+ it("rejects callers without organization:update scope (MEMBER role)", async () => {
+ const owner = await prepare();
+ const member = await prepareWithRole(Role.MEMBER);
+
+ const created = await owner.caller.verifiedDomain.create({
+ orgId: owner.org.id,
+ domain: `delete-rbac-${uuidv4().slice(0, 8)}.com`,
+ });
+
+ await expect(
+ member.caller.verifiedDomain.delete({
+ orgId: member.org.id,
+ id: created.id,
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+});
diff --git a/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts b/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts
index d9ee657249..64fc19948b 100644
--- a/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts
+++ b/web/src/ee/features/multi-tenant-sso/createNewSsoConfigHandler.ts
@@ -1,6 +1,8 @@
import { prisma } from "@langfuse/shared/src/db";
import { encrypt } from "@langfuse/shared/encryption";
import { SsoProviderSchema } from "./types";
+import { validateSsoConfig } from "@/src/ee/features/multi-tenant-sso/validateSsoConfig";
+import { TRPCError } from "@trpc/server";
import { type NextApiRequest, type NextApiResponse } from "next";
import { env } from "@/src/env.mjs";
import { logger } from "@langfuse/shared/src/server";
@@ -60,6 +62,19 @@ export async function createNewSsoConfigHandler(
return;
}
+ // Pre-flight the IdP discovery doc so misconfigurations surface here
+ // instead of locking out users at first sign-in. Same check applied by
+ // the self-service tRPC `ssoConfig.save` mutation.
+ try {
+ await validateSsoConfig(body.data);
+ } catch (e) {
+ if (e instanceof TRPCError) {
+ res.status(412).json({ error: e.message });
+ return;
+ }
+ throw e;
+ }
+
const encryptedClientSecret = authConfig
? {
...authConfig,
diff --git a/web/src/ee/features/multi-tenant-sso/server/ssoConfigRouter.ts b/web/src/ee/features/multi-tenant-sso/server/ssoConfigRouter.ts
new file mode 100644
index 0000000000..4797287fdd
--- /dev/null
+++ b/web/src/ee/features/multi-tenant-sso/server/ssoConfigRouter.ts
@@ -0,0 +1,256 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import {
+ createTRPCRouter,
+ protectedOrganizationProcedure,
+} from "@/src/server/api/trpc";
+import { SsoProviderSchema } from "@/src/ee/features/multi-tenant-sso/types";
+import { validateSsoConfig } from "@/src/ee/features/multi-tenant-sso/validateSsoConfig";
+import { encrypt } from "@langfuse/shared/encryption";
+import { TRPCError } from "@trpc/server";
+import * as z from "zod";
+
+const SSO_CONFIG_ENTITLEMENT = "cloud-multi-tenant-sso" as const;
+
+type SsoConfigRow = {
+ domain: string;
+ authProvider: string;
+ authConfig: Record<string, unknown> | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+// Strip clientSecret from any nested authConfig before sending to the client.
+// The encrypted secret stays server-side; the form re-prompts on update.
+const maskAuthConfig = (
+ authConfig: SsoConfigRow["authConfig"],
+): Record<string, unknown> | null => {
+ if (!authConfig) return null;
+ const { clientSecret: _omit, ...rest } = authConfig as {
+ clientSecret?: unknown;
+ } & Record<string, unknown>;
+ return rest;
+};
+
+export const ssoConfigRouter = createTRPCRouter({
+ get: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ entitlement: SSO_CONFIG_ENTITLEMENT,
+ });
+
+ const verifiedDomains = await ctx.prisma.verifiedDomain.findMany({
+ where: {
+ organizationId: input.orgId,
+ verifiedAt: { not: null },
+ },
+ select: { domain: true },
+ });
+
+ if (verifiedDomains.length === 0) return [];
+
+ const rows = await ctx.prisma.ssoConfig.findMany({
+ where: { domain: { in: verifiedDomains.map((d) => d.domain) } },
+ });
+
+ return rows.map((row) => ({
+ domain: row.domain,
+ authProvider: row.authProvider,
+ authConfig: maskAuthConfig(
+ row.authConfig as SsoConfigRow["authConfig"],
+ ),
+ createdAt: row.createdAt,
+ updatedAt: row.updatedAt,
+ }));
+ }),
+
+ save: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ payload: SsoProviderSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ entitlement: SSO_CONFIG_ENTITLEMENT,
+ });
+
+ const { domain, authProvider, authConfig } = input.payload;
+
+ const verifiedDomain = await ctx.prisma.verifiedDomain.findFirst({
+ where: {
+ domain,
+ organizationId: input.orgId,
+ verifiedAt: { not: null },
+ },
+ });
+ if (!verifiedDomain) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `Domain "${domain}" is not verified for this organization. Verify the domain first in the Verified Domains section.`,
+ });
+ }
+
+ // Pre-flight the IdP discovery doc so misconfigurations surface here
+ // instead of locking out users at first sign-in. Throws TRPCError with
+ // PRECONDITION_FAILED on any failure.
+ await validateSsoConfig(input.payload);
+
+ const existing = await ctx.prisma.ssoConfig.findUnique({
+ where: { domain },
+ });
+
+ // Preserve advanced authConfig fields the self-service form doesn't
+ // surface (scope, idToken, tokenEndpointAuthMethod, idTokenSignedResponseAlg)
+ // when the admin re-saves the same provider — typically just to rotate a
+ // secret. Without this merge, fields originally set via the legacy
+ // support endpoint would silently disappear and break sign-in. Switching
+ // providers is treated as an intentional reset (Custom-only fields like
+ // `name` or `scope` would be incompatible with the new provider).
+ const mergedAuthConfig =
+ existing &&
+ existing.authProvider === authProvider &&
+ authConfig &&
+ existing.authConfig
+ ? {
+ ...(existing.authConfig as Record<string, unknown>),
+ ...authConfig,
+ }
+ : authConfig;
+
+ const encryptedAuthConfig = mergedAuthConfig
+ ? {
+ ...mergedAuthConfig,
+ clientSecret: encrypt(
+ (mergedAuthConfig as { clientSecret: string }).clientSecret,
+ ),
+ }
+ : null;
+
+ const upserted = await ctx.prisma.ssoConfig.upsert({
+ where: { domain },
+ create: {
+ domain,
+ authProvider,
+ authConfig: encryptedAuthConfig ?? undefined,
+ },
+ update: {
+ authProvider,
+ authConfig: encryptedAuthConfig ?? undefined,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "ssoConfig",
+ resourceId: upserted.domain,
+ action: existing ? "update" : "create",
+ before: existing
+ ? {
+ domain: existing.domain,
+ authProvider: existing.authProvider,
+ authConfig: maskAuthConfig(
+ existing.authConfig as SsoConfigRow["authConfig"],
+ ),
+ }
+ : undefined,
+ after: {
+ domain: upserted.domain,
+ authProvider: upserted.authProvider,
+ authConfig: maskAuthConfig(
+ upserted.authConfig as SsoConfigRow["authConfig"],
+ ),
+ },
+ });
+
+ return {
+ domain: upserted.domain,
+ authProvider: upserted.authProvider,
+ authConfig: maskAuthConfig(
+ upserted.authConfig as SsoConfigRow["authConfig"],
+ ),
+ createdAt: upserted.createdAt,
+ updatedAt: upserted.updatedAt,
+ };
+ }),
+
+ delete: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string(), domain: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ entitlement: SSO_CONFIG_ENTITLEMENT,
+ });
+
+ // Domain ownership: only allow deleting configs for domains the caller's
+ // org has actually verified. Requiring `verifiedAt` here matches the
+ // `save` gate and prevents an org from creating a pending claim for
+ // someone else's domain (e.g. a config provisioned by the legacy admin
+ // handler with no VerifiedDomain backing) and using it to delete an
+ // SSO config they don't own.
+ const verifiedDomain = await ctx.prisma.verifiedDomain.findFirst({
+ where: {
+ domain: input.domain,
+ organizationId: input.orgId,
+ verifiedAt: { not: null },
+ },
+ });
+ if (!verifiedDomain) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "SSO configuration not found",
+ });
+ }
+
+ const existing = await ctx.prisma.ssoConfig.findUnique({
+ where: { domain: input.domain },
+ });
+ if (!existing) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "SSO configuration not found",
+ });
+ }
+
+ await ctx.prisma.ssoConfig.delete({ where: { domain: input.domain } });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "ssoConfig",
+ resourceId: existing.domain,
+ action: "delete",
+ before: {
+ domain: existing.domain,
+ authProvider: existing.authProvider,
+ authConfig: maskAuthConfig(
+ existing.authConfig as SsoConfigRow["authConfig"],
+ ),
+ },
+ });
+
+ return { domain: existing.domain };
+ }),
+});
diff --git a/web/src/ee/features/multi-tenant-sso/types.ts b/web/src/ee/features/multi-tenant-sso/types.ts
index 37785a973b..b191abf993 100644
--- a/web/src/ee/features/multi-tenant-sso/types.ts
+++ b/web/src/ee/features/multi-tenant-sso/types.ts
@@ -35,6 +35,17 @@ const idTokenSignedResponseAlg = z
])
.optional();
+// OIDC Discovery (§4) requires the issuer to be served over TLS, and OAuth
+// credential exchange likewise cannot ride on HTTP without leaking tokens, so
+// every user-supplied URL we build OAuth/OIDC endpoints from must start with
+// https://. `z.url()` enforces RFC 3986 grammar so values like `"https://"`
+// or `"https:// foo"` don't sneak through and only blow up at sign-in.
+const oidcIssuer = z
+ .url({ message: "OIDC issuer urls must be a valid URL" })
+ .startsWith("https://", {
+ message: "OIDC issuer urls must start with https://",
+ });
+
export const GoogleProviderSchema = base.extend({
authProvider: z.literal("google"),
authConfig: z
@@ -67,7 +78,11 @@ export const GithubEnterpriseProviderSchema = base.extend({
clientId: z.string(),
clientSecret: z.string(),
enterprise: z.object({
- baseUrl: z.url(),
+ baseUrl: z
+ .url({ message: "Github Enterprise baseUrls must be a valid URL" })
+ .startsWith("https://", {
+ message: "Github Enterprise baseUrls must start with https://",
+ }),
}),
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
@@ -81,7 +96,7 @@ export const GitlabProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string().optional(),
+ issuer: oidcIssuer.optional(),
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
idTokenSignedResponseAlg: idTokenSignedResponseAlg,
@@ -95,7 +110,7 @@ export const Auth0ProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string(),
+ issuer: oidcIssuer,
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
idTokenSignedResponseAlg: idTokenSignedResponseAlg,
@@ -109,9 +124,7 @@ export const OktaProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string().startsWith("https://", {
- message: "Okta issuer must start with https://",
- }),
+ issuer: oidcIssuer,
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
idTokenSignedResponseAlg: idTokenSignedResponseAlg,
@@ -125,7 +138,7 @@ export const AuthentikProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string().regex(/^https:\/\/.+\/application\/o\/[^/]+$/, {
+ issuer: oidcIssuer.regex(/^https:\/\/.+\/application\/o\/[^/]+$/, {
message:
"Authentik issuer must be in format https://<domain>/application/o/<slug> without trailing slash",
}),
@@ -142,7 +155,7 @@ export const OneLoginProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string(),
+ issuer: oidcIssuer,
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
idTokenSignedResponseAlg: idTokenSignedResponseAlg,
@@ -156,7 +169,13 @@ export const AzureAdProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- tenantId: z.string(),
+ // NextAuth interpolates tenantId straight into
+ // https://login.microsoftonline.com/<tenantId>/v2.0/...; an empty
+ // string saves cleanly and only blows up at sign-in (double slash,
+ // no tenant). Same class of footgun as a schemeless issuer URL.
+ tenantId: z.string().min(1, {
+ message: "Azure AD tenantId is required",
+ }),
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
idTokenSignedResponseAlg: idTokenSignedResponseAlg,
@@ -170,7 +189,7 @@ export const CognitoProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string(),
+ issuer: oidcIssuer,
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
idTokenSignedResponseAlg: idTokenSignedResponseAlg,
@@ -185,7 +204,7 @@ export const KeycloakProviderSchema = base.extend({
name: z.string().optional(),
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string(),
+ issuer: oidcIssuer,
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
idTokenSignedResponseAlg: idTokenSignedResponseAlg,
@@ -197,10 +216,13 @@ export const CustomProviderSchema = base.extend({
authProvider: z.literal("custom"),
authConfig: z
.object({
- name: z.string(),
+ // Display label rendered as "Display Name" in the form. Surfaced as
+ // a required field; reject empty strings so the schema matches the
+ // form contract.
+ name: z.string().min(1, { message: "Name is required" }),
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.string(),
+ issuer: oidcIssuer,
scope: z.string().nullish(),
idToken: z.boolean().optional().default(true),
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
@@ -216,7 +238,7 @@ export const JumpCloudProviderSchema = base.extend({
.object({
clientId: z.string(),
clientSecret: z.string(),
- issuer: z.url(),
+ issuer: oidcIssuer,
scope: z.string().nullish(),
allowDangerousEmailAccountLinking: z.boolean().optional().default(false),
tokenEndpointAuthMethod: tokenEndpointAuthMethod,
diff --git a/web/src/ee/features/multi-tenant-sso/validateSsoConfig.ts b/web/src/ee/features/multi-tenant-sso/validateSsoConfig.ts
new file mode 100644
index 0000000000..517252f9de
--- /dev/null
+++ b/web/src/ee/features/multi-tenant-sso/validateSsoConfig.ts
@@ -0,0 +1,154 @@
+import { type SsoProviderSchema } from "@/src/ee/features/multi-tenant-sso/types";
+import { TRPCError } from "@trpc/server";
+
+const DISCOVERY_TIMEOUT_MS = 5000;
+
+type DiscoveryDoc = {
+ authorization_endpoint?: unknown;
+ token_endpoint?: unknown;
+ jwks_uri?: unknown;
+ issuer?: unknown;
+};
+
+const REQUIRED_DISCOVERY_FIELDS = [
+ "authorization_endpoint",
+ "token_endpoint",
+ "jwks_uri",
+ "issuer",
+] as const;
+
+// Returns the issuer URL to hit `.well-known/openid-configuration` against, or
+// null when the provider doesn't speak OIDC discovery (the GitHub family is
+// OAuth2-only — we have no way to validate at save time, the misconfiguration
+// surfaces on first sign-in attempt).
+function discoveryIssuerFor(payload: SsoProviderSchema): string | null {
+ switch (payload.authProvider) {
+ case "github":
+ case "github-enterprise":
+ return null;
+ case "google":
+ return "https://accounts.google.com";
+ case "azure-ad":
+ return payload.authConfig
+ ? `https://login.microsoftonline.com/${payload.authConfig.tenantId}/v2.0`
+ : null;
+ case "gitlab":
+ return payload.authConfig?.issuer ?? "https://gitlab.com";
+ case "auth0":
+ case "okta":
+ case "authentik":
+ case "onelogin":
+ case "cognito":
+ case "keycloak":
+ case "jumpcloud":
+ case "custom":
+ return payload.authConfig?.issuer ?? null;
+ default:
+ return null;
+ }
+}
+
+const stripTrailingSlash = (url: string) => url.replace(/\/$/, "");
+
+// Microsoft's documented multi-tenant tenantId values. Discovery for these
+// returns `issuer` with the literal `{tenantid}` placeholder string instead
+// of the configured tenantId — the actual tenant is bound at token-issuance
+// time per user's home tenant. NextAuth's AzureADProvider handles this at
+// sign-in, so save-time we compare against the placeholder rather than the
+// configured value to avoid blocking legitimate multi-tenant configurations.
+const AZURE_AD_MULTI_TENANT = new Set(["common", "organizations", "consumers"]);
+const AZURE_AD_TENANT_PLACEHOLDER = "{tenantid}";
+
+function expectedReturnedIssuer(
+ payload: SsoProviderSchema,
+ trimmedIssuer: string,
+): string {
+ if (
+ payload.authProvider === "azure-ad" &&
+ payload.authConfig &&
+ AZURE_AD_MULTI_TENANT.has(payload.authConfig.tenantId)
+ ) {
+ return trimmedIssuer.replace(
+ `/${payload.authConfig.tenantId}/`,
+ `/${AZURE_AD_TENANT_PLACEHOLDER}/`,
+ );
+ }
+ return trimmedIssuer;
+}
+
+// Pre-flight check that the IdP's OIDC discovery document is reachable, well
+// formed, and reports the issuer we configured. Catches gross misconfigurations
+// (wrong issuer URL, unreachable IdP, mistyped tenant id) at save time instead
+// of locking out users at first sign-in. OAuth-only providers (GitHub family)
+// skip silently since they have no `.well-known` endpoint.
+export async function validateSsoConfig(
+ payload: SsoProviderSchema,
+): Promise<void> {
+ const issuer = discoveryIssuerFor(payload);
+ if (!issuer) return;
+
+ const trimmedIssuer = stripTrailingSlash(issuer);
+ const discoveryUrl = `${trimmedIssuer}/.well-known/openid-configuration`;
+
+ let resp: Response;
+ try {
+ // SSRF defense: refuse to follow redirects. An admin can configure any
+ // issuer host, and a malicious one could 302 us at internal endpoints
+ // (cloud metadata services, kube API, localhost). Per OIDC Discovery §4
+ // the discovery doc is served directly at the issuer URL with no
+ // redirects, so legitimate IdPs (Auth0, Okta, Google, Azure AD,
+ // JumpCloud, etc.) all return 200 directly. `redirect: "error"` makes
+ // fetch throw on any 3xx, which we catch as the same "Could not reach"
+ // error the admin sees for any other connection failure.
+ resp = await fetch(discoveryUrl, {
+ signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
+ redirect: "error",
+ });
+ } catch {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `Could not reach ${discoveryUrl}. Verify the issuer URL is correct and reachable from the public internet.`,
+ });
+ }
+
+ if (!resp.ok) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `OIDC discovery at ${discoveryUrl} returned ${resp.status}. Verify the issuer URL is correct.`,
+ });
+ }
+
+ let doc: DiscoveryDoc;
+ try {
+ doc = (await resp.json()) as DiscoveryDoc;
+ } catch {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `OIDC discovery at ${discoveryUrl} did not return valid JSON.`,
+ });
+ }
+
+ const missing = REQUIRED_DISCOVERY_FIELDS.filter(
+ (k) => typeof doc[k] !== "string",
+ );
+ if (missing.length > 0) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `OIDC discovery at ${discoveryUrl} is missing required field(s): ${missing.join(", ")}.`,
+ });
+ }
+
+ // Per OIDC Discovery §3, the discovery doc's `issuer` must match the URL we
+ // used to fetch it. Trim trailing slashes on both sides — Auth0 and friends
+ // typically serve the issuer with a trailing `/` even if users don't enter it.
+ // Azure AD multi-tenant endpoints return `{tenantid}` as a literal
+ // placeholder; map our expected issuer to the same shape before comparing.
+ const returnedIssuer = stripTrailingSlash(doc.issuer as string);
+ const expectedIssuer = expectedReturnedIssuer(payload, trimmedIssuer);
+ if (returnedIssuer !== expectedIssuer) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `OIDC discovery at ${discoveryUrl} reported issuer "${doc.issuer as string}" but we expected "${expectedIssuer}". Check the issuer URL matches exactly.`,
+ });
+ }
+}
diff --git a/web/src/ee/features/sso-settings/components/SSOSettings.tsx b/web/src/ee/features/sso-settings/components/SSOSettings.tsx
index 3b0040c73b..85bd930814 100644
--- a/web/src/ee/features/sso-settings/components/SSOSettings.tsx
+++ b/web/src/ee/features/sso-settings/components/SSOSettings.tsx
@@ -1,61 +1,746 @@
import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
-import { AlertCircle } from "lucide-react";
-import { useHasEntitlement } from "@/src/features/entitlements/hooks";
-import Header from "@/src/components/layouts/header";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/src/components/ui/alert-dialog";
+import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
-import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+import { Card } from "@/src/components/ui/card";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableCellWithCopyButton,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/src/components/ui/table";
+import Header from "@/src/components/layouts/header";
+import { useHasEntitlement } from "@/src/features/entitlements/hooks";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { VerifiedDomainsSettings } from "@/src/ee/features/verified-domains/components/VerifiedDomainsSettings";
+import { SsoProviderSchema } from "@/src/ee/features/multi-tenant-sso/types";
+import { api } from "@/src/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertCircle, TrashIcon } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+
+const SSO_PROVIDERS: ReadonlyArray<{
+ id: SsoProviderSchema["authProvider"];
+ label: string;
+ fields: ReadonlyArray<"issuer" | "tenantId" | "baseUrl" | "name">;
+}> = [
+ { id: "google", label: "Google", fields: [] },
+ { id: "github", label: "GitHub", fields: [] },
+ { id: "github-enterprise", label: "GitHub Enterprise", fields: ["baseUrl"] },
+ { id: "gitlab", label: "GitLab", fields: [] },
+ { id: "auth0", label: "Auth0", fields: ["issuer"] },
+ { id: "okta", label: "Okta", fields: ["issuer"] },
+ { id: "authentik", label: "Authentik", fields: ["issuer"] },
+ { id: "onelogin", label: "OneLogin", fields: ["issuer"] },
+ { id: "azure-ad", label: "Azure AD / Entra ID", fields: ["tenantId"] },
+ { id: "cognito", label: "AWS Cognito", fields: ["issuer"] },
+ { id: "keycloak", label: "Keycloak", fields: ["issuer"] },
+ { id: "jumpcloud", label: "JumpCloud", fields: ["issuer"] },
+ // Custom OIDC requires a display name on the schema; surface it in the form.
+ { id: "custom", label: "Custom OIDC", fields: ["name", "issuer"] },
+];
+
+const providerLabel = (id: string) =>
+ SSO_PROVIDERS.find((p) => p.id === id)?.label ?? id;
+
+// Loose form schema; the strict validation lives in SsoProviderSchema and runs
+// at submit time. Keeping the form schema permissive lets users mid-edit a
+// field without immediate noise from required-field errors on every render.
+const formSchema = z.object({
+ authProvider: z.enum(SSO_PROVIDERS.map((p) => p.id) as [string, ...string[]]),
+ authConfig: z.object({
+ clientId: z.string().min(1, "Required"),
+ clientSecret: z.string().min(1, "Required"),
+ issuer: z.string().optional(),
+ tenantId: z.string().optional(),
+ baseUrl: z.string().optional(),
+ // Required by CustomProviderSchema; optional in the form so other
+ // providers don't carry a stray field. The strict provider schema
+ // enforces presence at submit for `custom`.
+ name: z.string().optional(),
+ }),
+});
+
+type FormValues = z.infer<typeof formSchema>;
+
+type SsoConfigRow = {
+ domain: string;
+ authProvider: string;
+ authConfig: Record<string, unknown> | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
-export const SSOSettings = () => {
+export const SSOSettings = ({ orgId }: { orgId: string }) => {
const hasEntitlement = useHasEntitlement("cloud-multi-tenant-sso");
- const { setOpen: setSupportDrawerOpen } = useSupportDrawer();
+ const hasAccess = useHasOrganizationAccess({
+ organizationId: orgId,
+ scope: "organization:update",
+ });
- const commonContent = (
+ const heading = (
<>
<Header title="SSO Configuration" />
<p className="text-muted-foreground mb-4 text-sm">
- Configure Single Sign-On (SSO) for your organization. SSO allows your
- team to use your existing identity provider for authentication, e.g.
- Okta, AzureAD/EntraID. Alternatively, you can enforce the use of a
- public provider such as Google, GitHub and Microsoft.
+ Configure Single Sign-On per verified domain. Once active, every user
+ signing in with that domain is redirected to your identity provider.
</p>
</>
);
if (!hasEntitlement) {
return (
- <div>
- {commonContent}
- <Alert>
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>Not available</AlertTitle>
- <AlertDescription>
- Enterprise SSO and SSO Enforcement are not available on your plan.
- Please upgrade to access this feature.
- </AlertDescription>
- </Alert>
+ <div className="space-y-8">
+ <VerifiedDomainsSettings orgId={orgId} />
+ <div>
+ {heading}
+ <Alert>
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Not available</AlertTitle>
+ <AlertDescription>
+ Enterprise SSO is not available on your plan. Please upgrade to
+ access this feature.
+ </AlertDescription>
+ </Alert>
+ </div>
+ </div>
+ );
+ }
+
+ if (!hasAccess) {
+ return (
+ <div className="space-y-8">
+ <VerifiedDomainsSettings orgId={orgId} />
+ <div>
+ {heading}
+ <Alert>
+ <AlertTitle>Access Denied</AlertTitle>
+ <AlertDescription>
+ You do not have permission to configure SSO for this organization.
+ </AlertDescription>
+ </Alert>
+ </div>
</div>
);
}
return (
- <div>
- {commonContent}
- <Alert>
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>Contact Langfuse Support</AlertTitle>
- <AlertDescription className="flex flex-col gap-3">
- <p>
- To set up or change your SSO configuration, please reach out to our
- support engineering team.
- </p>
- <Button
- onClick={() => setSupportDrawerOpen(true)}
- className="self-start"
- >
- Contact Support
- </Button>
- </AlertDescription>
- </Alert>
+ <div className="space-y-8">
+ <VerifiedDomainsSettings orgId={orgId} />
+ <div className="space-y-6">
+ {heading}
+ <SsoConfigsTable orgId={orgId} />
+ </div>
</div>
);
};
+
+function SsoConfigsTable({ orgId }: { orgId: string }) {
+ const verifiedDomainsQuery = api.verifiedDomain.list.useQuery({ orgId });
+ const ssoConfigsQuery = api.ssoConfig.get.useQuery({ orgId });
+
+ const verifiedDomains = useMemo(
+ () => verifiedDomainsQuery.data?.filter((d) => d.verifiedAt != null) ?? [],
+ [verifiedDomainsQuery.data],
+ );
+ const configByDomain = useMemo(() => {
+ const map = new Map<string, SsoConfigRow>();
+ ssoConfigsQuery.data?.forEach((cfg) => map.set(cfg.domain, cfg));
+ return map;
+ }, [ssoConfigsQuery.data]);
+
+ if (verifiedDomains.length === 0) {
+ return (
+ <Card className="overflow-hidden">
+ <p className="text-muted-foreground px-6 py-12 text-center text-sm">
+ Verify a domain in the section above to configure SSO for it.
+ </p>
+ </Card>
+ );
+ }
+
+ return (
+ <Card className="mb-4 overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-primary pl-2.5">Domain</TableHead>
+ <TableHead className="text-primary">Provider</TableHead>
+ <TableHead className="text-primary hidden md:table-cell">
+ Updated
+ </TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody className="text-muted-foreground">
+ {verifiedDomains.map((row) => (
+ <SsoConfigRow
+ key={row.domain}
+ orgId={orgId}
+ domain={row.domain}
+ config={configByDomain.get(row.domain) ?? null}
+ />
+ ))}
+ </TableBody>
+ </Table>
+ </Card>
+ );
+}
+
+function SsoConfigRow({
+ orgId,
+ domain,
+ config,
+}: {
+ orgId: string;
+ domain: string;
+ config: SsoConfigRow | null;
+}) {
+ return (
+ <TableRow className="hover:bg-primary-foreground">
+ <TableCell density="comfortable" className="font-mono">
+ {domain}
+ </TableCell>
+ <TableCell density="comfortable">
+ {config ? (
+ <Badge variant="default">{providerLabel(config.authProvider)}</Badge>
+ ) : (
+ <Badge variant="secondary">Not configured</Badge>
+ )}
+ </TableCell>
+ <TableCell density="comfortable" className="hidden md:table-cell">
+ {config ? config.updatedAt.toLocaleDateString() : "—"}
+ </TableCell>
+ <TableCell
+ density="comfortable"
+ className="flex items-center justify-end gap-2"
+ >
+ <SsoConfigDialog orgId={orgId} domain={domain} existing={config} />
+ {config ? (
+ <DeleteSsoConfigButton orgId={orgId} domain={domain} />
+ ) : null}
+ </TableCell>
+ </TableRow>
+ );
+}
+
+function SsoConfigDialog({
+ orgId,
+ domain,
+ existing,
+}: {
+ orgId: string;
+ domain: string;
+ existing: SsoConfigRow | null;
+}) {
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [pendingValues, setPendingValues] = useState<FormValues | null>(null);
+ const utils = api.useUtils();
+
+ const defaultValues = useMemo<FormValues>(() => {
+ const cfg = (existing?.authConfig ?? {}) as Record<string, unknown>;
+ const enterprise = cfg.enterprise as { baseUrl?: string } | undefined;
+ return {
+ authProvider:
+ existing?.authProvider ?? ("okta" as SsoProviderSchema["authProvider"]),
+ authConfig: {
+ clientId: typeof cfg.clientId === "string" ? cfg.clientId : "",
+ clientSecret: "",
+ issuer: typeof cfg.issuer === "string" ? cfg.issuer : "",
+ tenantId: typeof cfg.tenantId === "string" ? cfg.tenantId : "",
+ baseUrl: enterprise?.baseUrl ?? "",
+ name: typeof cfg.name === "string" ? cfg.name : "",
+ },
+ };
+ }, [existing]);
+
+ const form = useForm<FormValues>({
+ resolver: zodResolver(formSchema),
+ defaultValues,
+ });
+ // Reset the form when the dialog reopens against new defaults (e.g. user
+ // toggled between Configure and Update without remounting the component).
+ useEffect(() => {
+ if (dialogOpen) form.reset(defaultValues);
+ }, [dialogOpen, defaultValues, form]);
+
+ const selectedProvider = form.watch("authProvider");
+ const providerSpec = useMemo(
+ () =>
+ SSO_PROVIDERS.find((p) => p.id === selectedProvider) ?? SSO_PROVIDERS[0],
+ [selectedProvider],
+ );
+
+ const callbackUrl = useMemo(() => {
+ if (typeof window === "undefined") return "";
+ return `${window.location.origin}/api/auth/callback/${domain}.${selectedProvider}`;
+ }, [domain, selectedProvider]);
+
+ const saveMutation = api.ssoConfig.save.useMutation({
+ onSuccess: () => {
+ void utils.ssoConfig.get.invalidate({ orgId });
+ showSuccessToast({
+ title: existing ? "SSO updated" : "SSO configured",
+ description: `Active for @${domain} within 1 hour.`,
+ });
+ setDialogOpen(false);
+ setConfirmOpen(false);
+ setPendingValues(null);
+ form.reset();
+ },
+ onError: (err) => {
+ showErrorToast(
+ existing ? "Update failed" : "SSO configuration failed",
+ err.message,
+ );
+ },
+ });
+
+ function onSubmit(values: FormValues) {
+ setPendingValues(values);
+ setConfirmOpen(true);
+ }
+
+ function handleConfirm() {
+ if (!pendingValues) return;
+ const payload = buildSsoPayload(domain, pendingValues);
+ const parsed = SsoProviderSchema.safeParse(payload);
+ if (!parsed.success) {
+ const firstIssue = parsed.error.issues[0];
+ const schemaPath = firstIssue.path.join(".");
+ // `buildSsoPayload` re-nests `baseUrl` under `enterprise` for
+ // github-enterprise; the strict schema reports errors at the nested
+ // path, but the form field is registered flat. Map back so
+ // `setError` lands on a watched field and the inline message renders.
+ const formPath =
+ schemaPath === "authConfig.enterprise.baseUrl"
+ ? "authConfig.baseUrl"
+ : schemaPath;
+ const formField = formPath.startsWith("authConfig.")
+ ? (formPath as `authConfig.${"clientId" | "clientSecret" | "issuer" | "tenantId" | "baseUrl" | "name"}`)
+ : "authProvider";
+ form.setError(formField, { message: firstIssue.message });
+ // Defensive fallback: if a future schema path doesn't map cleanly to
+ // a registered form field, surface a toast so the user is never left
+ // with a silently-closing dialog and no feedback.
+ const FORM_FIELDS = [
+ "authProvider",
+ "authConfig.clientId",
+ "authConfig.clientSecret",
+ "authConfig.issuer",
+ "authConfig.tenantId",
+ "authConfig.baseUrl",
+ "authConfig.name",
+ ];
+ if (!FORM_FIELDS.includes(formField)) {
+ showErrorToast(
+ existing ? "Update failed" : "SSO configuration failed",
+ firstIssue.message,
+ );
+ }
+ setConfirmOpen(false);
+ return;
+ }
+ saveMutation.mutate({ orgId, payload: parsed.data });
+ }
+
+ return (
+ <>
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogTrigger asChild>
+ <Button size="sm" variant={existing ? "outline" : "default"}>
+ {existing ? "Update" : "Configure SSO"}
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>
+ {existing
+ ? `Update SSO for ${domain}`
+ : `Configure SSO for ${domain}`}
+ </DialogTitle>
+ </DialogHeader>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <DialogBody className="space-y-4">
+ <FormField
+ control={form.control}
+ name="authProvider"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Provider</FormLabel>
+ <FormControl>
+ <Select
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select an SSO provider" />
+ </SelectTrigger>
+ <SelectContent>
+ {SSO_PROVIDERS.map((p) => (
+ <SelectItem key={p.id} value={p.id}>
+ {p.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <CallbackUrlPanel callbackUrl={callbackUrl} />
+
+ {providerSpec.fields.includes("name") ? (
+ <FormField
+ control={form.control}
+ name="authConfig.name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Display Name</FormLabel>
+ <FormControl>
+ <Input placeholder="Acme SSO" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : null}
+
+ <FormField
+ control={form.control}
+ name="authConfig.clientId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Client ID</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="authConfig.clientSecret"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Client Secret</FormLabel>
+ <FormControl>
+ <Input
+ type="password"
+ autoComplete="off"
+ placeholder={
+ existing ? "Re-enter to update" : undefined
+ }
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {providerSpec.fields.includes("issuer") ? (
+ <FormField
+ control={form.control}
+ name="authConfig.issuer"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Issuer URL</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="https://example.okta.com"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : null}
+
+ {providerSpec.fields.includes("tenantId") ? (
+ <FormField
+ control={form.control}
+ name="authConfig.tenantId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Tenant ID</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : null}
+
+ {providerSpec.fields.includes("baseUrl") ? (
+ <FormField
+ control={form.control}
+ name="authConfig.baseUrl"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Base URL</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="https://github.acme.com"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : null}
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setDialogOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" loading={saveMutation.isPending}>
+ Save
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+
+ <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {existing
+ ? `Replace SSO for @${domain}?`
+ : `Activate SSO for @${domain}?`}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ <span className="block">
+ Saving will activate SSO for{" "}
+ <span className="font-medium">@{domain}</span> within 1 hour.
+ Every user at that domain will be redirected to your identity
+ provider on sign-in &mdash; they will not be able to use Google,
+ GitHub, password, or any other method until SSO is deleted.
+ </span>
+ {existing ? (
+ <span className="mt-2 block">
+ The new credentials will replace the active configuration.
+ </span>
+ ) : null}
+ <span className="mt-2 block">
+ Tip: sign in via the new SSO in a second browser to confirm it
+ works before closing this tab.
+ </span>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleConfirm}
+ disabled={saveMutation.isPending}
+ >
+ {existing ? "Replace" : "Activate SSO"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
+
+function CallbackUrlPanel({ callbackUrl }: { callbackUrl: string }) {
+ return (
+ <div>
+ <p className="mb-2 text-sm font-medium">Callback URL</p>
+ <Card className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>URL</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <TableRow>
+ <TableCellWithCopyButton
+ density="comfortable"
+ text={callbackUrl}
+ className="py-3 font-mono break-all"
+ />
+ </TableRow>
+ </TableBody>
+ </Table>
+ </Card>
+ <p className="text-muted-foreground mt-2 text-xs">
+ Add this URL as an authorized redirect URI in your identity provider.
+ </p>
+ </div>
+ );
+}
+
+function DeleteSsoConfigButton({
+ orgId,
+ domain,
+}: {
+ orgId: string;
+ domain: string;
+}) {
+ const utils = api.useUtils();
+
+ const deleteMutation = api.ssoConfig.delete.useMutation({
+ onSuccess: () => {
+ void utils.ssoConfig.get.invalidate({ orgId });
+ showSuccessToast({
+ title: "SSO disabled",
+ description: `SSO for @${domain} has been removed.`,
+ });
+ },
+ onError: (err) => {
+ showErrorToast("Failed to remove SSO", err.message);
+ },
+ });
+
+ return (
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={`Delete SSO for ${domain}`}
+ >
+ <TrashIcon className="h-4 w-4" />
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove SSO for @{domain}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Users at this domain will be able to sign in with any enabled method
+ again. Active sessions are not invalidated.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => deleteMutation.mutate({ orgId, domain })}
+ disabled={deleteMutation.isPending}
+ >
+ Remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+// Build the SsoProviderSchema-shaped payload from the flat form values.
+// Handles the nested github-enterprise.enterprise.baseUrl shape.
+function buildSsoPayload(domain: string, values: FormValues) {
+ const { authProvider, authConfig } = values;
+ // allowDangerousEmailAccountLinking is required for SSO migration of
+ // existing accounts. Cross-tenant misuse is prevented by the DNS-verified
+ // domain check at save time + the runtime domain enforcement in
+ // web/src/server/auth.ts.
+ const base = {
+ clientId: authConfig.clientId,
+ clientSecret: authConfig.clientSecret,
+ allowDangerousEmailAccountLinking: true,
+ };
+
+ switch (authProvider) {
+ case "google":
+ case "github":
+ case "gitlab":
+ return { domain, authProvider, authConfig: base };
+ case "github-enterprise":
+ return {
+ domain,
+ authProvider,
+ authConfig: {
+ ...base,
+ enterprise: { baseUrl: authConfig.baseUrl ?? "" },
+ },
+ };
+ case "azure-ad":
+ return {
+ domain,
+ authProvider,
+ authConfig: { ...base, tenantId: authConfig.tenantId ?? "" },
+ };
+ case "auth0":
+ case "okta":
+ case "authentik":
+ case "onelogin":
+ case "cognito":
+ case "keycloak":
+ case "jumpcloud":
+ return {
+ domain,
+ authProvider,
+ authConfig: { ...base, issuer: authConfig.issuer ?? "" },
+ };
+ case "custom":
+ return {
+ domain,
+ authProvider,
+ authConfig: {
+ ...base,
+ issuer: authConfig.issuer ?? "",
+ name: authConfig.name ?? "",
+ },
+ };
+ default:
+ return { domain, authProvider, authConfig: base };
+ }
+}
diff --git a/web/src/ee/features/verified-domains/components/VerifiedDomainsSettings.tsx b/web/src/ee/features/verified-domains/components/VerifiedDomainsSettings.tsx
new file mode 100644
index 0000000000..273e6f6eac
--- /dev/null
+++ b/web/src/ee/features/verified-domains/components/VerifiedDomainsSettings.tsx
@@ -0,0 +1,442 @@
+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/src/components/ui/alert-dialog";
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import { Card } from "@/src/components/ui/card";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableCellWithCopyButton,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/src/components/ui/table";
+import Header from "@/src/components/layouts/header";
+import { useHasEntitlement } from "@/src/features/entitlements/hooks";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { api } from "@/src/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertCircle, ChevronRight, TrashIcon } from "lucide-react";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+
+const addDomainSchema = z.object({
+ domain: z
+ .string()
+ .trim()
+ .min(3)
+ .max(253)
+ .transform((v) => v.toLowerCase())
+ .refine(
+ (v) =>
+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/.test(
+ v,
+ ),
+ { message: "Must be a valid domain (e.g. acme.com)" },
+ ),
+});
+
+type AddDomainInput = z.infer<typeof addDomainSchema>;
+
+export const VerifiedDomainsSettings = ({ orgId }: { orgId: string }) => {
+ const hasEntitlement = useHasEntitlement("cloud-multi-tenant-sso");
+ const hasAccess = useHasOrganizationAccess({
+ organizationId: orgId,
+ scope: "organization:update",
+ });
+
+ const heading = (
+ <>
+ <Header title="Verified Domains" />
+ <p className="text-muted-foreground mb-4 text-sm">
+ You can only configure SSO for domains your organization owns. Verify a
+ domain via DNS to enable SSO for it.
+ </p>
+ </>
+ );
+
+ if (!hasEntitlement) {
+ return (
+ <div>
+ {heading}
+ <Alert>
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Not available</AlertTitle>
+ <AlertDescription>
+ Verified Domains and Enterprise SSO are not available on your plan.
+ Please upgrade to access this feature.
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+ }
+
+ if (!hasAccess) {
+ return (
+ <div>
+ {heading}
+ <Alert>
+ <AlertTitle>Access Denied</AlertTitle>
+ <AlertDescription>
+ You do not have permission to manage verified domains for this
+ organization.
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <Header
+ title="Verified Domains"
+ actionButtons={<AddDomainButton orgId={orgId} />}
+ />
+ <p className="text-muted-foreground text-sm">
+ You can only configure SSO for domains your organization owns. Verify a
+ domain via DNS to enable SSO for it.
+ </p>
+ <DomainsTable orgId={orgId} />
+ </div>
+ );
+};
+
+function DomainsTable({ orgId }: { orgId: string }) {
+ const query = api.verifiedDomain.list.useQuery({ orgId });
+
+ return (
+ <Card className="mb-4 overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-primary pl-2.5">Domain</TableHead>
+ <TableHead className="text-primary">Status</TableHead>
+ <TableHead className="text-primary hidden md:table-cell">
+ Added
+ </TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody className="text-muted-foreground">
+ {query.data && query.data.length === 0 ? (
+ <TableRow>
+ <TableCell
+ density="comfortable"
+ colSpan={4}
+ className="py-12 text-center text-sm"
+ >
+ No domains added yet
+ </TableCell>
+ </TableRow>
+ ) : (
+ query.data?.map((row) => (
+ <DomainRow key={row.id} orgId={orgId} row={row} />
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </Card>
+ );
+}
+
+type DomainRowData = {
+ id: string;
+ domain: string;
+ verifiedAt: Date | null;
+ createdAt: Date;
+ recordHost: string;
+ recordValue: string;
+};
+
+function DomainRow({ orgId, row }: { orgId: string; row: DomainRowData }) {
+ const [expanded, setExpanded] = useState(!row.verifiedAt);
+ const utils = api.useUtils();
+
+ const verifyMutation = api.verifiedDomain.verify.useMutation({
+ onSuccess: () => {
+ void utils.verifiedDomain.list.invalidate({ orgId });
+ showSuccessToast({
+ title: "Domain verified",
+ description: `${row.domain} is now verified.`,
+ });
+ },
+ onError: (err) => {
+ showErrorToast("Verification failed", err.message);
+ },
+ });
+
+ return (
+ <>
+ <TableRow className="hover:bg-primary-foreground">
+ <TableCell density="comfortable" className="font-mono">
+ {!row.verifiedAt ? (
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="flex items-center gap-1"
+ >
+ <ChevronRight
+ className={`h-3 w-3 transition-transform ${
+ expanded ? "rotate-90" : ""
+ }`}
+ />
+ {row.domain}
+ </button>
+ ) : (
+ row.domain
+ )}
+ </TableCell>
+ <TableCell density="comfortable">
+ {row.verifiedAt ? (
+ <Badge variant="default">Verified</Badge>
+ ) : (
+ <Badge variant="secondary">Pending verification</Badge>
+ )}
+ </TableCell>
+ <TableCell density="comfortable" className="hidden md:table-cell">
+ {row.createdAt.toLocaleDateString()}
+ </TableCell>
+ <TableCell
+ density="comfortable"
+ className="flex items-center justify-end gap-2"
+ >
+ {!row.verifiedAt && (
+ <Button
+ size="sm"
+ onClick={() => verifyMutation.mutate({ orgId, id: row.id })}
+ loading={verifyMutation.isPending}
+ >
+ Verify
+ </Button>
+ )}
+ <DeleteDomainButton
+ orgId={orgId}
+ id={row.id}
+ domain={row.domain}
+ verified={Boolean(row.verifiedAt)}
+ />
+ </TableCell>
+ </TableRow>
+ {!row.verifiedAt && expanded && (
+ <TableRow className="bg-muted/30">
+ <TableCell colSpan={4} className="py-4">
+ <DnsInstructions
+ recordHost={row.recordHost}
+ recordValue={row.recordValue}
+ />
+ </TableCell>
+ </TableRow>
+ )}
+ </>
+ );
+}
+
+function DnsInstructions({
+ recordHost,
+ recordValue,
+}: {
+ recordHost: string;
+ recordValue: string;
+}) {
+ return (
+ <div className="space-y-3">
+ <p className="text-sm font-medium">
+ Add the following TXT record to your DNS provider:
+ </p>
+ <Card className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-16">Type</TableHead>
+ <TableHead className="w-54">Host</TableHead>
+ <TableHead>Value</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <TableRow>
+ <TableCell density="comfortable" className="w-16 font-mono">
+ TXT
+ </TableCell>
+ <TableCellWithCopyButton
+ density="comfortable"
+ text={recordHost}
+ className="w-54 py-3 font-mono break-all"
+ />
+ <TableCellWithCopyButton
+ density="comfortable"
+ text={recordValue}
+ className="py-3 font-mono break-all"
+ />
+ </TableRow>
+ </TableBody>
+ </Table>
+ </Card>
+ <p className="text-muted-foreground text-xs">
+ DNS changes may take up to 24h to propagate. After adding the record,
+ click <span className="font-medium">Verify</span>.
+ </p>
+ </div>
+ );
+}
+
+function AddDomainButton({ orgId }: { orgId: string }) {
+ const [open, setOpen] = useState(false);
+ const utils = api.useUtils();
+
+ const form = useForm<AddDomainInput>({
+ resolver: zodResolver(addDomainSchema),
+ defaultValues: { domain: "" },
+ });
+
+ const createMutation = api.verifiedDomain.create.useMutation({
+ onSuccess: () => {
+ void utils.verifiedDomain.list.invalidate({ orgId });
+ showSuccessToast({
+ title: "Domain added",
+ description:
+ "Add the DNS TXT record shown in the table, then click Verify.",
+ });
+ form.reset();
+ setOpen(false);
+ },
+ onError: (err) => {
+ form.setError("domain", { message: err.message });
+ },
+ });
+
+ function onSubmit(values: AddDomainInput) {
+ createMutation.mutate({ orgId, domain: values.domain });
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button size="sm">Add Domain</Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add a domain</DialogTitle>
+ </DialogHeader>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <DialogBody>
+ <FormField
+ control={form.control}
+ name="domain"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Domain</FormLabel>
+ <FormControl>
+ <Input placeholder="acme.com" autoFocus {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" loading={createMutation.isPending}>
+ Add
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function DeleteDomainButton({
+ orgId,
+ id,
+ domain,
+ verified,
+}: {
+ orgId: string;
+ id: string;
+ domain: string;
+ verified: boolean;
+}) {
+ const utils = api.useUtils();
+
+ const deleteMutation = api.verifiedDomain.delete.useMutation({
+ onSuccess: () => {
+ void utils.verifiedDomain.list.invalidate({ orgId });
+ showSuccessToast({
+ title: "Domain removed",
+ description: `${domain} has been removed.`,
+ });
+ },
+ onError: (err) => {
+ showErrorToast("Failed to remove domain", err.message);
+ },
+ });
+
+ return (
+ <AlertDialog>
+ <AlertDialogTrigger asChild>
+ <Button variant="ghost" size="icon-xs" aria-label={`Delete ${domain}`}>
+ <TrashIcon className="h-4 w-4" />
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove {domain}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {verified
+ ? "If an SSO configuration exists for this domain, you must remove it first. The domain can be re-verified later."
+ : "This removes the pending claim. The domain can be re-added and verified later."}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => deleteMutation.mutate({ orgId, id })}
+ disabled={deleteMutation.isPending}
+ >
+ Remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/web/src/ee/features/verified-domains/server/dnsLookup.ts b/web/src/ee/features/verified-domains/server/dnsLookup.ts
new file mode 100644
index 0000000000..c61d0351d3
--- /dev/null
+++ b/web/src/ee/features/verified-domains/server/dnsLookup.ts
@@ -0,0 +1,19 @@
+import { Resolver } from "node:dns";
+
+// Query through Cloudflare and Google public resolvers instead of the system
+// resolver so verification reflects DNS changes within seconds rather than
+// waiting for the OS-configured recursive resolver's negative cache (which can
+// persist up to the zone's SOA minimum TTL — typically up to 1 hour). Both
+// resolvers strictly respect record TTLs and validate DNSSEC.
+const PUBLIC_DNS_SERVERS = ["8.8.8.8", "1.1.1.1"] as const;
+
+export async function resolveTxtFresh(fqdn: string): Promise<string[][]> {
+ const resolver = new Resolver({ timeout: 3000, tries: 2 });
+ resolver.setServers([...PUBLIC_DNS_SERVERS]);
+ return await new Promise<string[][]>((resolve, reject) => {
+ resolver.resolveTxt(fqdn, (err, records) => {
+ if (err) reject(err);
+ else resolve(records);
+ });
+ });
+}
diff --git a/web/src/ee/features/verified-domains/server/verifiedDomainRouter.ts b/web/src/ee/features/verified-domains/server/verifiedDomainRouter.ts
new file mode 100644
index 0000000000..e2fb8df8e5
--- /dev/null
+++ b/web/src/ee/features/verified-domains/server/verifiedDomainRouter.ts
@@ -0,0 +1,325 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import {
+ createTRPCRouter,
+ protectedOrganizationProcedure,
+} from "@/src/server/api/trpc";
+import { resolveTxtFresh } from "@/src/ee/features/verified-domains/server/dnsLookup";
+import { Prisma } from "@langfuse/shared/src/db";
+import { TRPCError } from "@trpc/server";
+import * as z from "zod";
+
+// Verified domains are infrastructure for multi-tenant SSO; gate every
+// mutation on the same entitlement so the API surface matches the UI
+// (`useHasEntitlement` already hides the feature on lower plans). Pending
+// claims are shareable so squatting no longer locks out enterprise
+// customers, but limiting reach to entitled orgs is still cleaner — fewer
+// stale rows from hobby orgs poking at the API directly.
+const VERIFIED_DOMAIN_ENTITLEMENT = "cloud-multi-tenant-sso" as const;
+
+const VERIFICATION_RECORD_PREFIX = "_langfuse-verification";
+const VERIFICATION_VALUE_PREFIX = "langfuse-verify=";
+
+const domainInput = z
+ .string()
+ .trim()
+ .min(3)
+ .max(253)
+ .transform((v) => v.toLowerCase())
+ .refine(
+ (v) =>
+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/.test(
+ v,
+ ),
+ { message: "Must be a valid domain (e.g. acme.com)" },
+ );
+
+// FQDN form, used internally by the verifier to dig the TXT record.
+const recordFqdnFor = (domain: string) =>
+ `${VERIFICATION_RECORD_PREFIX}.${domain}`;
+const recordValueFor = (token: string) =>
+ `${VERIFICATION_VALUE_PREFIX}${token}`;
+
+export const verifiedDomainRouter = createTRPCRouter({
+ list: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ entitlement: VERIFIED_DOMAIN_ENTITLEMENT,
+ });
+
+ const rows = await ctx.prisma.verifiedDomain.findMany({
+ where: { organizationId: input.orgId },
+ orderBy: { createdAt: "asc" },
+ });
+
+ return rows.map((row) => ({
+ id: row.id,
+ domain: row.domain,
+ verifiedAt: row.verifiedAt,
+ createdAt: row.createdAt,
+ recordHost: VERIFICATION_RECORD_PREFIX,
+ recordValue: recordValueFor(row.verificationToken),
+ }));
+ }),
+
+ create: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string(), domain: domainInput }))
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ entitlement: VERIFIED_DOMAIN_ENTITLEMENT,
+ });
+
+ // Pending claims are shareable across orgs; only verified claims are
+ // exclusive. Block create only when another org has already verified
+ // the domain — otherwise a hobby-plan org could squat a global slot
+ // for a domain it doesn't own. Verified-claim exclusivity is also
+ // enforced at the DB level by a partial unique index on
+ // `domain WHERE verified_at IS NOT NULL`.
+ const verifiedElsewhere = await ctx.prisma.verifiedDomain.findFirst({
+ where: { domain: input.domain, verifiedAt: { not: null } },
+ });
+ if (
+ verifiedElsewhere &&
+ verifiedElsewhere.organizationId !== input.orgId
+ ) {
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: `Domain "${input.domain}" is already verified by another organization.`,
+ });
+ }
+
+ // Per-org idempotency: returning the existing row lets the UI re-open
+ // the same DNS instructions without minting a fresh verification token.
+ const existing = await ctx.prisma.verifiedDomain.findUnique({
+ where: {
+ organizationId_domain: {
+ organizationId: input.orgId,
+ domain: input.domain,
+ },
+ },
+ });
+ if (existing) {
+ return {
+ id: existing.id,
+ domain: existing.domain,
+ verifiedAt: existing.verifiedAt,
+ createdAt: existing.createdAt,
+ recordHost: VERIFICATION_RECORD_PREFIX,
+ recordValue: recordValueFor(existing.verificationToken),
+ };
+ }
+
+ // Race protection: two parallel creates from the same org or two orgs
+ // racing each other after a verified row was just created. The
+ // (organizationId, domain) unique index and the partial index on
+ // verified rows both surface as Prisma P2002.
+ let row;
+ try {
+ row = await ctx.prisma.verifiedDomain.create({
+ data: {
+ organizationId: input.orgId,
+ domain: input.domain,
+ createdByUserId: ctx.session.user.id,
+ },
+ });
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ ) {
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: `Domain "${input.domain}" is already verified by another organization.`,
+ });
+ }
+ throw error;
+ }
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "verifiedDomain",
+ resourceId: row.id,
+ action: "create",
+ after: { domain: row.domain, organizationId: row.organizationId },
+ });
+
+ return {
+ id: row.id,
+ domain: row.domain,
+ verifiedAt: row.verifiedAt,
+ createdAt: row.createdAt,
+ recordHost: VERIFICATION_RECORD_PREFIX,
+ recordValue: recordValueFor(row.verificationToken),
+ };
+ }),
+
+ verify: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string(), id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ entitlement: VERIFIED_DOMAIN_ENTITLEMENT,
+ });
+
+ const row = await ctx.prisma.verifiedDomain.findFirst({
+ where: { id: input.id, organizationId: input.orgId },
+ });
+
+ if (!row) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Verified domain not found",
+ });
+ }
+
+ if (row.verifiedAt) {
+ return { id: row.id, domain: row.domain, verifiedAt: row.verifiedAt };
+ }
+
+ const recordFqdn = recordFqdnFor(row.domain);
+ const expected = recordValueFor(row.verificationToken);
+
+ let records: string[][] = [];
+ try {
+ records = await resolveTxtFresh(recordFqdn);
+ } catch {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `Could not find a TXT record at "${recordFqdn}". DNS changes may take up to 24h to propagate.`,
+ });
+ }
+
+ const flat = records.map((chunks) => chunks.join(""));
+ const matched = flat.includes(expected);
+
+ if (!matched) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `TXT record at "${recordFqdn}" does not contain the expected value "${expected}". Found ${flat.length} record(s).`,
+ });
+ }
+
+ // Verified-claim exclusivity is enforced by a partial unique index on
+ // `domain WHERE verified_at IS NOT NULL`. If another org already
+ // verified this domain (e.g. they raced us after we both proved DNS),
+ // the update returns P2002. Translate to CONFLICT so the user sees a
+ // clean message instead of an opaque 500.
+ let updated;
+ try {
+ updated = await ctx.prisma.verifiedDomain.update({
+ where: { id: row.id },
+ data: { verifiedAt: new Date() },
+ });
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ ) {
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: `Domain "${row.domain}" is already verified by another organization.`,
+ });
+ }
+ throw error;
+ }
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "verifiedDomain",
+ resourceId: updated.id,
+ action: "verify",
+ before: { verifiedAt: null },
+ after: { verifiedAt: updated.verifiedAt },
+ });
+
+ return {
+ id: updated.id,
+ domain: updated.domain,
+ verifiedAt: updated.verifiedAt,
+ };
+ }),
+
+ delete: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string(), id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ entitlement: VERIFIED_DOMAIN_ENTITLEMENT,
+ });
+
+ const row = await ctx.prisma.verifiedDomain.findFirst({
+ where: { id: input.id, organizationId: input.orgId },
+ });
+
+ if (!row) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Verified domain not found",
+ });
+ }
+
+ // Once verified, refuse to drop the row while its SsoConfig is still
+ // active — otherwise the config would be orphaned: it would continue
+ // to enforce SSO at sign-in but disappear from the UI and become
+ // undeletable through the normal flow. Pending claims are exempt:
+ // since they're shareable across orgs (any number can claim the same
+ // domain unverified), an SsoConfig that exists for the domain
+ // necessarily belongs to a *different* org's verified row, and
+ // blocking on it would trap stale pending claims permanently.
+ if (row.verifiedAt) {
+ const ssoConfig = await ctx.prisma.ssoConfig.findUnique({
+ where: { domain: row.domain },
+ });
+ if (ssoConfig) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: `An SSO configuration is active for "${row.domain}". Remove the SSO configuration before deleting this domain.`,
+ });
+ }
+ }
+
+ await ctx.prisma.verifiedDomain.delete({ where: { id: row.id } });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "verifiedDomain",
+ resourceId: row.id,
+ action: "delete",
+ before: {
+ domain: row.domain,
+ organizationId: row.organizationId,
+ verifiedAt: row.verifiedAt,
+ },
+ });
+
+ return { id: row.id };
+ }),
+});
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 3802d71cb6..64420688ec 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -42,6 +42,8 @@ export type AuditableResource =
| "action"
| "slackIntegration"
| "cloudSpendAlert"
+ | "verifiedDomain"
+ | "ssoConfig"
// legacy resources
| "membership";
diff --git a/web/src/pages/organization/[organizationId]/settings/index.tsx b/web/src/pages/organization/[organizationId]/settings/index.tsx
index e32865cafc..9d048ee346 100644
--- a/web/src/pages/organization/[organizationId]/settings/index.tsx
+++ b/web/src/pages/organization/[organizationId]/settings/index.tsx
@@ -138,8 +138,19 @@ export const getOrganizationSettingsPages = ({
{
title: "SSO",
slug: "sso",
- cmdKKeywords: ["sso", "login", "auth", "okta", "saml", "azure"],
- content: <SSOSettings />,
+ cmdKKeywords: [
+ "sso",
+ "login",
+ "auth",
+ "okta",
+ "saml",
+ "azure",
+ "domain",
+ "dns",
+ "txt",
+ "verify",
+ ],
+ content: <SSOSettings orgId={organization.id} />,
show: isLangfuseCloud,
},
{
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 120145b6ae..b4e5964d95 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -26,6 +26,8 @@ import { llmSchemaRouter } from "@/src/features/llm-schemas/server/router";
import { llmToolRouter } from "@/src/features/llm-tools/server/router";
import { organizationsRouter } from "@/src/features/organizations/server/organizationRouter";
import { organizationApiKeysRouter } from "@/src/features/public-api/server/organizationApiKeyRouter";
+import { verifiedDomainRouter } from "@/src/ee/features/verified-domains/server/verifiedDomainRouter";
+import { ssoConfigRouter } from "@/src/ee/features/multi-tenant-sso/server/ssoConfigRouter";
import { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";
import { publicRouter } from "@/src/server/api/routers/public";
import { credentialsRouter } from "@/src/features/auth-credentials/server/credentialsRouter";
@@ -74,6 +76,8 @@ export const appRouter = createTRPCRouter({
dashboard: dashboardRouter,
organizations: organizationsRouter,
organizationApiKeys: organizationApiKeysRouter,
+ verifiedDomain: verifiedDomainRouter,
+ ssoConfig: ssoConfigRouter,
projects: projectsRouter,
users: userRouter,
userAccount: userAccountRouter,