🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(sso): block internal targets in OIDC discovery validation (#15897)
Mark Salpeter1d59d34261b0
diff --git a/.env.dev.example b/.env.dev.exampleindex 562fbca4e9..4e82fa7226 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -184,6 +184,10 @@ LANGFUSE_AI_FEATURES_PROJECT_ID=7a88fb47-b4e2-43b8-a06c-a5ce950dc53a# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST=localhost# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS=127.0.0.1,::1# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IP_SEGMENTS=127.0.0.0/8+# Allow internal IdP hosts/IPs for SSO OIDC discovery validation.+# LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST=localhost+# LANGFUSE_SSO_DISCOVERY_WHITELISTED_IPS=127.0.0.1,::1+# LANGFUSE_SSO_DISCOVERY_WHITELISTED_IP_SEGMENTS=127.0.0.0/8# Langfuse AI Bedrock credentialsAWS_ACCESS_KEY_ID="A123456789"diff --git a/.env.prod.example b/.env.prod.exampleindex d842a23ef4..e5c033b4dc 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -345,6 +345,10 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST=# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS=# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IP_SEGMENTS=+# Allow internal IdP hosts/IPs for SSO OIDC discovery validation.+# LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST=+# LANGFUSE_SSO_DISCOVERY_WHITELISTED_IPS=+# LANGFUSE_SSO_DISCOVERY_WHITELISTED_IP_SEGMENTS=# LANGFUSE_CACHE_MODEL_MATCH_ENABLED=# LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS=diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 7d79e9da22..f91c94d08b 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -446,6 +446,24 @@ const EnvSchema = z.object({.transform((s) =>s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],),+ LANGFUSE_SSO_DISCOVERY_WHITELISTED_IPS: z+ .string()+ .optional()+ .transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],+ ),+ LANGFUSE_SSO_DISCOVERY_WHITELISTED_IP_SEGMENTS: z+ .string()+ .optional()+ .transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],+ ),+ LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST: z+ .string()+ .optional()+ .transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],+ ),SLACK_CLIENT_ID: z.string().optional(),SLACK_CLIENT_SECRET: z.string().optional(),SLACK_STATE_SECRET: z.string().optional(),diff --git a/web/src/__tests__/server/ssoConfigRouter.servertest.ts b/web/src/__tests__/server/ssoConfigRouter.servertest.tsindex a3c440fa42..ac54989d7f 100644--- a/web/src/__tests__/server/ssoConfigRouter.servertest.ts+++ b/web/src/__tests__/server/ssoConfigRouter.servertest.ts@@ -2,6 +2,7 @@ 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 { env as sharedEnv } from "@langfuse/shared/src/env";import { Role } from "@langfuse/shared";import type { Session } from "next-auth";import { v4 as uuidv4 } from "uuid";@@ -12,7 +13,7 @@ const fetchMock = vi.fn<typeof fetch>();beforeEach(() => {fetchMock.mockReset();vi.stubGlobal("fetch", fetchMock);- mockDiscoveryOk("https://example.okta.com");+ mockDiscoveryOk("https://example.com");});afterEach(() => {vi.unstubAllGlobals();@@ -133,7 +134,7 @@ const samplePayload = (domain: string) => ({authConfig: {clientId: "client-123",clientSecret: "super-secret-value",- issuer: "https://example.okta.com",+ issuer: "https://example.com",allowDangerousEmailAccountLinking: false,},});@@ -145,7 +146,7 @@ const sampleCustomPayload = (domain: string, idToken: boolean) => ({name: "Custom OIDC",clientId: "client-123",clientSecret: "super-secret-value",- issuer: "https://example.okta.com",+ issuer: "https://example.com",idToken,allowDangerousEmailAccountLinking: false,},@@ -206,7 +207,7 @@ describe("ssoConfigRouter.save", () => {name: "",clientId: "client-123",clientSecret: "super-secret",- issuer: "https://example.okta.com",+ issuer: "https://example.com",allowDangerousEmailAccountLinking: false,},},@@ -377,7 +378,7 @@ describe("ssoConfigRouter.save", () => {authConfig: {clientId: "old-client",clientSecret: encrypt("old-secret"),- issuer: "https://example.okta.com",+ issuer: "https://example.com",tokenEndpointAuthMethod: "private_key_jwt",idTokenSignedResponseAlg: "RS256",},@@ -507,7 +508,7 @@ describe("ssoConfigRouter.get", () => {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");+ expect(cfg.issuer).toBe("https://example.com");});it("does not return rows for unverified domains", async () => {@@ -531,7 +532,7 @@ describe("ssoConfigRouter.get", () => {authConfig: {clientId: "x",clientSecret: "y",- issuer: "https://x.okta.com",+ issuer: "https://x.example.com",},},});@@ -627,7 +628,7 @@ describe("ssoConfigRouter.delete", () => {authConfig: {clientId: "x",clientSecret: "y",- issuer: "https://x.okta.com",+ issuer: "https://x.example.com",},},});@@ -694,17 +695,43 @@ describe("ssoConfigRouter.save — IdP discovery validation", () => {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"));+ fetchMock.mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { location: "https://169.254.169.254/" },+ }),+ );await expect(caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });});+ it.each([+ ["loopback literal", "https://127.0.0.1"],+ ["IPv6 loopback literal", "https://[::1]"],+ ["cloud metadata literal", "https://169.254.169.254"],+ ["RFC1918 literal", "https://10.0.0.1"],+ ["localhost", "https://localhost"],+ ["embedded URL credentials", "https://user:[email protected]"],+ ])("rejects an internal discovery target: %s", async (_label, issuer) => {+ const { org, caller } = await prepare();+ const domain = `discovery-ssrf-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);++ const payload = samplePayload(domain);+ await expect(+ caller.ssoConfig.save({+ orgId: org.id,+ payload: { ...payload, authConfig: { ...payload.authConfig, issuer } },+ }),+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });++ expect(fetchMock).not.toHaveBeenCalled();+ const row = await prisma.ssoConfig.findUnique({ where: { domain } });+ expect(row).toBeNull();+ });+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`;@@ -721,12 +748,56 @@ describe("ssoConfigRouter.save — IdP discovery validation", () => {const domain = `discovery-missing-${uuidv4().slice(0, 8)}.com`;await addVerifiedDomain(org.id, domain);fetchMock.mockResolvedValueOnce(- discoveryResponse({ issuer: "https://example.okta.com" }),+ discoveryResponse({ issuer: "https://example.com" }),+ );++ await expect(+ caller.ssoConfig.save({ orgId: org.id, payload: samplePayload(domain) }),+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });+ });++ it("rejects when the discovery doc points a server-fetched endpoint at an internal address", async () => {+ const { org, caller } = await prepare();+ const domain = `discovery-internal-endpoint-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);+ fetchMock.mockResolvedValueOnce(+ discoveryResponse({+ issuer: "https://example.com",+ authorization_endpoint: "https://example.com/authorize",+ token_endpoint: "https://169.254.169.254/oauth/token",+ jwks_uri: "https://example.com/.well-known/jwks.json",+ }),);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 doc points userinfo_endpoint at an internal address", async () => {+ const { org, caller } = await prepare();+ const domain = `discovery-userinfo-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);+ fetchMock.mockResolvedValueOnce(+ discoveryResponse({+ issuer: "https://example.com",+ authorization_endpoint: "https://example.com/authorize",+ token_endpoint: "https://example.com/oauth/token",+ jwks_uri: "https://example.com/.well-known/jwks.json",+ userinfo_endpoint:+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/",+ }),+ );++ 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 returned issuer does not match the configured one", async () => {@@ -735,10 +806,10 @@ describe("ssoConfigRouter.save — IdP discovery validation", () => {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",+ issuer: "https://different.example.com",+ authorization_endpoint: "https://different.example.com/authorize",+ token_endpoint: "https://different.example.com/oauth/token",+ jwks_uri: "https://different.example.com/.well-known/jwks.json",}),);@@ -755,10 +826,10 @@ describe("ssoConfigRouter.save — IdP discovery validation", () => {// 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",+ issuer: "https://example.com/",+ authorization_endpoint: "https://example.com/authorize",+ token_endpoint: "https://example.com/oauth/token",+ jwks_uri: "https://example.com/.well-known/jwks.json",}),);@@ -773,7 +844,7 @@ describe("ssoConfigRouter.save — IdP discovery validation", () => {const { org, caller } = await prepare();const domain = `discovery-url-${uuidv4().slice(0, 8)}.com`;await addVerifiedDomain(org.id, domain);- mockDiscoveryOk("https://example.okta.com");+ mockDiscoveryOk("https://example.com");await caller.ssoConfig.save({orgId: org.id,@@ -781,7 +852,7 @@ describe("ssoConfigRouter.save — IdP discovery validation", () => {});expect(fetchMock).toHaveBeenCalledWith(- "https://example.okta.com/.well-known/openid-configuration",+ "https://example.com/.well-known/openid-configuration",expect.any(Object),);});@@ -861,6 +932,52 @@ describe("ssoConfigRouter.save — IdP discovery validation", () => {).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });});+ it("saves an issuer on a non-standard port", async () => {+ const { org, caller } = await prepare();+ const domain = `discovery-port-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);+ mockDiscoveryOk("https://example.com:8443");++ const payload = samplePayload(domain);+ const result = await caller.ssoConfig.save({+ orgId: org.id,+ payload: {+ ...payload,+ authConfig: {+ ...payload.authConfig,+ issuer: "https://example.com:8443",+ },+ },+ });+ expect(result.domain).toBe(domain);+ });++ it("saves an internal issuer host when LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST allows it", async () => {+ const { org, caller } = await prepare();+ const domain = `discovery-whitelist-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);+ mockDiscoveryOk("https://idp.internal");++ const original = sharedEnv.LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST;+ try {+ sharedEnv.LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST = ["idp.internal"];+ const payload = samplePayload(domain);+ const result = await caller.ssoConfig.save({+ orgId: org.id,+ payload: {+ ...payload,+ authConfig: {+ ...payload.authConfig,+ issuer: "https://idp.internal",+ },+ },+ });+ expect(result.domain).toBe(domain);+ } finally {+ sharedEnv.LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST = original;+ }+ });+it("skips discovery for OAuth-only providers (github)", async () => {const { org, caller } = await prepare();const domain = `github-skip-${uuidv4().slice(0, 8)}.com`;diff --git a/web/src/ee/features/multi-tenant-sso/validateSsoConfig.ts b/web/src/ee/features/multi-tenant-sso/validateSsoConfig.tsindex 517252f9de..38c72a54fe 100644--- a/web/src/ee/features/multi-tenant-sso/validateSsoConfig.ts+++ b/web/src/ee/features/multi-tenant-sso/validateSsoConfig.ts@@ -1,27 +1,46 @@-import { type SsoProviderSchema } from "@/src/ee/features/multi-tenant-sso/types";import { TRPCError } from "@trpc/server";+import { z } from "zod";++import {+ fetchWithSecureRedirects,+ validateWebhookURL,+} from "@langfuse/shared/src/server";+import { env } from "@langfuse/shared/src/env";+import { type SsoProviderSchema } from "@/src/ee/features/multi-tenant-sso/types";++const discoveryTimeoutMs = 5000;++const DiscoveryDocSchema = z.object({+ authorization_endpoint: z.string(),+ token_endpoint: z.string(),+ jwks_uri: z.string(),+ issuer: z.string(),+ userinfo_endpoint: z.string().optional(),+});++/** validateSsoConfig checks at save time that the IdP's OIDC discovery doc is reachable, well formed, and reports the configured issuer. */+export async function validateSsoConfig(+ payload: SsoProviderSchema,+): Promise<void> {+ const issuer = getDiscoveryIssuer(payload);+ if (!issuer) return;++ const discoveryUrl = getDiscoveryUrl(issuer);++ try {+ const resp = await fetchWithSsrfDefense(discoveryUrl);+ const doc = parseDiscoveryDoc(await parseJson(resp));+ await validateUrls(doc);+ validateDiscoveryIssuer(doc, payload, issuer);+ } catch (error) {+ if (error instanceof TRPCError)+ throw prefixError(`OIDC discovery at ${discoveryUrl}: `, error);+ throw error;+ }+}-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 {+/** getDiscoveryIssuer returns the provider's configured issuer URL, or null when the provider has no OIDC discovery (GitHub family is OAuth2-only). */+function getDiscoveryIssuer(payload: SsoProviderSchema): string | null {switch (payload.authProvider) {case "github":case "github-enterprise":@@ -43,112 +62,143 @@ function discoveryIssuerFor(payload: SsoProviderSchema): string | null {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;+/** getDiscoveryUrl builds the discovery-document URL for issuer. */+function getDiscoveryUrl(issuer: string): string {+ return `${stripTrailingSlash(issuer)}/.well-known/openid-configuration`;}-// 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`;+const stripTrailingSlash = (url: string) => url.replace(/\/$/, "");- let resp: Response;+/** fetchWithSsrfDefense fetches url with internal-address blocking and the operator whitelist applied. */+async function fetchWithSsrfDefense(url: string): Promise<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",- });+ const whitelist = discoveryWhitelistFromEnv();+ // any port: NextAuth's sign-in fetch has no port restriction+ await validateWebhookURL(url, whitelist, { allowedPorts: "any" });+ const result = await fetchWithSecureRedirects(+ url,+ { signal: AbortSignal.timeout(discoveryTimeoutMs) },+ {+ maxRedirects: 0, // OIDC Discovery §4: doc is served directly at the issuer URL+ redirectValidation: {+ validateUrl: validateWebhookURL,+ whitelist,+ },+ },+ );+ return result.response;} catch {throw new TRPCError({code: "PRECONDITION_FAILED",- message: `Could not reach ${discoveryUrl}. Verify the issuer URL is correct and reachable from the public internet.`,+ message:+ "could not reach the URL. Verify the issuer URL is correct and reachable from the public internet.",});}+}- if (!resp.ok) {+/** discoveryWhitelistFromEnv builds the operator-configured exemptions to the internal-address blocklist. */+function discoveryWhitelistFromEnv() {+ return {+ hosts: env.LANGFUSE_SSO_DISCOVERY_WHITELISTED_HOST || [],+ ips: env.LANGFUSE_SSO_DISCOVERY_WHITELISTED_IPS || [],+ ip_ranges: env.LANGFUSE_SSO_DISCOVERY_WHITELISTED_IP_SEGMENTS || [],+ };+}++/** parseJson parses a 2xx response body as JSON, throwing on non-2xx status or invalid JSON. */+async function parseJson<T = unknown>(response: Response): Promise<T> {+ if (!response.ok) {throw new TRPCError({code: "PRECONDITION_FAILED",- message: `OIDC discovery at ${discoveryUrl} returned ${resp.status}. Verify the issuer URL is correct.`,+ message: `returned ${response.status}. Verify the issuer URL is correct.`,});}-- let doc: DiscoveryDoc;try {- doc = (await resp.json()) as DiscoveryDoc;+ return (await response.json()) as T;} catch {throw new TRPCError({code: "PRECONDITION_FAILED",- message: `OIDC discovery at ${discoveryUrl} did not return valid JSON.`,+ message: "did not return valid JSON.",});}+}- const missing = REQUIRED_DISCOVERY_FIELDS.filter(- (k) => typeof doc[k] !== "string",- );- if (missing.length > 0) {+/** parseDiscoveryDoc validates body against the discovery-doc schema, throwing when required fields are missing. */+function parseDiscoveryDoc(body: unknown): DiscoveryDoc {+ const parsed = DiscoveryDocSchema.safeParse(body);+ if (!parsed.success) {+ const missing = parsed.error.issues.map((i) => i.path.join("."));throw new TRPCError({code: "PRECONDITION_FAILED",- message: `OIDC discovery at ${discoveryUrl} is missing required field(s): ${missing.join(", ")}.`,+ message: `missing required field(s): ${missing.join(", ")}.`,});}+ return parsed.data;+}++/** validateUrls checks the endpoints NextAuth fetches server-side at sign-in don't target internal addresses. */+async function validateUrls(doc: DiscoveryDoc): Promise<void> {+ const whitelist = discoveryWhitelistFromEnv();+ for (const key of [+ "token_endpoint",+ "jwks_uri",+ "userinfo_endpoint",+ ] as const) {+ const url = doc[key];+ if (!url) continue;+ try {+ await validateWebhookURL(url, whitelist, {+ allowedPorts: "any",+ });+ } catch {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: `${key} "${url}" must be reachable from the public internet.`,+ });+ }+ }+}++/** validateDiscoveryIssuer checks the doc reports the configured issuer. */+function validateDiscoveryIssuer(+ doc: DiscoveryDoc,+ payload: SsoProviderSchema,+ issuer: string,+): void {+ // Azure multi-tenant endpoints report the literal `{tenantid}` placeholder+ // as issuer — the tenant is bound at sign-in.+ const azureMultiTenantIds = ["common", "organizations", "consumers"];+ const expectedIssuer =+ payload.authProvider === "azure-ad" &&+ payload.authConfig &&+ azureMultiTenantIds.includes(payload.authConfig.tenantId)+ ? stripTrailingSlash(issuer).replace(+ `/${payload.authConfig.tenantId}/`,+ "/{tenantid}/",+ )+ : stripTrailingSlash(issuer);- // 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);+ // OIDC Discovery §3: the doc's issuer must match the URL it was fetched from.+ // Trailing slashes trimmed on both sides — Auth0 and friends serve one.+ const returnedIssuer = stripTrailingSlash(doc.issuer);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.`,+ message: `reported issuer "${doc.issuer}" but we expected "${expectedIssuer}". Check the issuer URL matches exactly.`,});}}++/** prefixError returns a copy of error with prefix prepended to its message. */+function prefixError(prefix: string, error: TRPCError): TRPCError {+ return new TRPCError({+ code: error.code,+ message: `${prefix}${error.message}`,+ });+}++/** DiscoveryDoc is the slice of the OIDC discovery document the validators inspect. */+type DiscoveryDoc = z.infer<typeof DiscoveryDocSchema>;