Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/features/sso-model-sign-in/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Model sign-in with company SSO

- **Feature:** `ssoModelSignIn`
- **Deployments:** `cloud`, `self_hosted`
- **Default:** `false`
- **Author:** `benjaminshafii`
- **Product guide:** [`packages/docs/ai-gateway/litellm.mdx#company-sso-sign-in`](../../../packages/docs/ai-gateway/litellm.mdx)

## What it does

Adds a fifth LiteLLM mode, **Company SSO sign-in** (`mode=oidc`), next to Microsoft sign-in (`mode=entra`). Each member signs in once with the company's own OpenID Connect identity provider. Den keeps their access and refresh tokens encrypted, and the gateway sends the member's access token to a LiteLLM proxy that runs JWT auth.

- Den first sends `prompt=none`. When the identity provider answers `login_required`, `interaction_required`, `consent_required` or `account_selection_required`, it rotates the state and redirects to the normal sign-in.
- The issuer is stored on the provider (`settings.litellm.oidcIssuer`). It is not reused from the organization's SSO connection: that connection may be SAML, and Okta's org authorization server issues tokens only Okta can check. den-web prefills the form from an enabled OIDC SSO connection and adds `/oauth2/default` for an Okta org issuer.
- Den accepts an issuer only when its discovery document names exactly that issuer, over https (or an http origin in `GATEWAY_EGRESS_ALLOWED_ORIGINS`). A token is kept only when its access token's `iss` is that issuer.
- Sign-in scopes are `openid profile offline_access <apiScope>`. The organization's SSO sign-in request is unchanged (`openid email profile`).

## Turning it off

With the flag off, Den refuses to create or edit an `oidc` provider and refuses `oauth/start`, `browser-status`, `browser-start` and the callback with `403 feature_disabled`. The gateway drops `oidc` grants, so members lose those models at once. Stored providers and sign-ins are kept and work again when the flag is turned back on. The other LiteLLM modes, Microsoft sign-in and Foundry, Vertex and Bedrock sign-in are unaffected.

## Storage

| Where | What |
| --- | --- |
| `settings.litellm` | `keySource: "oidc"`, `oidcIssuer`, `oidcScope` |
| Credential set "Company sign-in" | `oauth_client_id`, encrypted `oauth_client_secret` |
| Member credential | kind `oauth_oidc`: `accessToken`, `refreshToken`, `tokenType`, `oidcIdentity { issuer, subject, userName, clientId, scope, authorizationRevision }` |

Migration `0226_gateway_oidc_sign_in.sql` adds the `oauth_oidc` credential kind. Nothing existing is renamed.

## Evidence

- Gateway: `ee/apps/gateway/test/litellm-oidc-sign-in.test.ts`.
- den-web: `litellm-provider-data.test.ts`.
- Real Okta and LiteLLM proof is recorded in the PR.
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function providerSpecSchema<Ref extends z.ZodType, Secret extends z.ZodType>(ref
status: statusSchema,
settings: gatewayProviderSettingsSchema,
custom: z.object({ models: z.array(gatewayCustomModelSchema).min(1).max(500) }).strict().optional(),
litellm: z.object({ mode: z.enum(["org", "member"]), keySource: z.enum(["personal", "issued", "entra"]).nullable(), issueStrategy: z.enum(["per_team", "mirror"]).nullable(), mirrorFallback: z.enum(["per_team", "error"]).nullable() }).strict().optional(),
litellm: z.object({ mode: z.enum(["org", "member"]), keySource: z.enum(["personal", "issued", "entra", "oidc"]).nullable(), issueStrategy: z.enum(["per_team", "mirror"]).nullable(), mirrorFallback: z.enum(["per_team", "error"]).nullable() }).strict().optional(),
modelIds: z.array(modelIdSchema).max(500),
pinnedModelIds: z.array(modelIdSchema).max(500),
models: z.array(z.object({ id: idSchema, modelId: modelIdSchema, name: z.string().max(255) }).strict()).max(5000),
Expand Down
34 changes: 24 additions & 10 deletions ee/apps/den-api/src/llm/gateway-matrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { bedrockSettingsError, microsoftFoundrySettingsError, isAwsGatewayNpm, b
import { memberSignInConfigurationError, memberSignInCredentialKind, memberSignInCredentialUsable, memberSignInExtraneousFields, providerMemberSignInMethod, providerMemberSignInScope, readAwsSsoSettings, sameMemberSignInConfiguration } from "./gateway-member-sign-in.js"
import { effectiveGatewayGrants, memberGatewayTeams } from "./inference-provider-lifecycle.js"
import { liteLlmCatalogProvider, liteLlmStatus, readLiteLlmSettings } from "./litellm-settings.js"
import { organizationFeatureEnabled } from "../features.js"
import { trueFoundryCatalogProvider, trueFoundryStatus } from "./truefoundry-settings.js"
import { customCatalogProvider, customProviderStatus } from "./gateway-custom-provider.js"
import { isGatewayCustomProviderId } from "@openwork/types/den/gateway-custom-providers"
Expand Down Expand Up @@ -301,7 +302,7 @@ export function normalizeCredential(input: GatewayCredentialSetPatch, provider:
try {
const parsed = parseGatewayProviderSecret(credential.kind, credential.secret)
if (!isInferenceCredentialKindSupported(parsed.kind, provider.provider_id)
|| parsed.kind === "aws_sso" || parsed.kind === "oauth_azure"
|| parsed.kind === "aws_sso" || parsed.kind === "oauth_azure" || parsed.kind === "oauth_oidc"
|| parsed.kind === "api_key_map" && !pickInferenceApiKeyFromMap(parsed.apiKeys, envNames)
|| parsed.kind === "aws_keys" && parsed.awsKeys.region !== undefined && !isAwsRegion(parsed.awsKeys.region)) throw new Error("invalid")
} catch { throw new GatewayWriteError(400, "invalid_credential", "Credential kind and key fields must match the trusted provider catalog.") }
Expand Down Expand Up @@ -346,7 +347,7 @@ export async function writeGatewaySet(
provider: GatewayProvider,
input: GatewayCredentialSetPatch,
target: GatewaySet["id"] | { createdByOrgMembershipId: GatewayMemberId },
options: { awaitOrganizationKey?: boolean; createId?: GatewaySet["id"]; liteLlmEntraSignIn?: { scopeChanged: boolean } } = {},
options: { awaitOrganizationKey?: boolean; createId?: GatewaySet["id"]; liteLlmTokenSignIn?: { scopeChanged: boolean } } = {},
) {
const setId = typeof target === "string" ? target : undefined
let creatorId: GatewayMemberId | null = null
Expand Down Expand Up @@ -384,9 +385,9 @@ export async function writeGatewaySet(
const litellm = isLiteLlmProviderId(provider.provider_id)
const method = providerMemberSignInMethod(provider)
const signInScope = providerMemberSignInScope(provider)
if (signInScope !== null && !options.liteLlmEntraSignIn && (!existing || (input.credentialMode !== undefined && input.credentialMode !== existing.credential_mode)
if (signInScope !== null && !options.liteLlmTokenSignIn && (!existing || (input.credentialMode !== undefined && input.credentialMode !== existing.credential_mode)
|| input.oauthClientId !== undefined || input.oauthClientSecret !== undefined || input.oauthTenantId !== undefined)) {
throw new GatewayWriteError(400, "litellm_entra_managed", "Change this provider's Microsoft sign-in settings with PATCH /v1/inference-providers/{inferenceProviderId}/litellm.")
throw new GatewayWriteError(400, "litellm_entra_managed", "Change this provider's member sign-in settings with PATCH /v1/inference-providers/{inferenceProviderId}/litellm.")
}
if (mode === "member" && ((!method && !litellm) || input.credential !== undefined || input.apiKeys !== undefined)) {
throw new GatewayWriteError(400, "unsupported_credential_mode", "Member sets use each member's own sign-in or key, never an uploaded shared credential.")
Expand All @@ -396,7 +397,7 @@ export async function writeGatewaySet(
if (extraneous) throw new GatewayWriteError(400, "unsupported_sign_in_settings", extraneous)
const id = existing?.id ?? options.createId ?? createDenTypeId("gatewayCredentialSet")
const modeChanged = existing && mode !== existing.credential_mode
const clientChanged = existing && (options.liteLlmEntraSignIn?.scopeChanged === true || !sameMemberSignInConfiguration(signIn, existing))
const clientChanged = existing && (options.liteLlmTokenSignIn?.scopeChanged === true || !sameMemberSignInConfiguration(signIn, existing))
const disabled = existing?.status === "active" && input.status === "disabled"
const enabled = existing && existing.status !== "active" && input.status === "active"
if (mode === "member" && method && (!existing || modeChanged || clientChanged || enabled)) {
Expand Down Expand Up @@ -469,7 +470,7 @@ export type GatewaySummaryOptions = {
}

function withoutLiteLlmUpstreamConfiguration(status: GatewayLiteLlmStatus): GatewayLiteLlmStatus {
const { entraScope: _entraScope, ...shared } = status
const { entraScope: _entraScope, oidcIssuer: _oidcIssuer, oidcScope: _oidcScope, ...shared } = status
return { ...shared, baseUrl: null, attention: [] }
}

Expand All @@ -488,9 +489,20 @@ export type GatewaySummaryReads = {
manage: boolean
memberId: GatewayMemberId
providers: ReadonlyMap<GatewayProvider["id"], GatewaySummaryRows>
signInDisabled: ReadonlySet<GatewayProvider["id"]>
teamIds: string[]
}

function usesCompanySignIn(provider: GatewayProvider) {
return isLiteLlmProviderId(provider.provider_id) && readLiteLlmSettings(provider.settings)?.keySource === "oidc"
}

async function disabledSignInProviders(organizationId: GatewayProvider["organization_id"], providers: GatewayProvider[]) {
const signIn = providers.filter(usesCompanySignIn)
if (!signIn.length || await organizationFeatureEnabled(organizationId, "ssoModelSignIn")) return new Set<GatewayProvider["id"]>()
return new Set(signIn.map((provider) => provider.id))
}

function rowsByProvider<Row>(rows: Row[], providerId: (row: Row) => GatewayProvider["id"]) {
const grouped = new Map<GatewayProvider["id"], Row[]>()
for (const row of rows) {
Expand All @@ -506,7 +518,7 @@ export async function readGatewaySummaries(input: { identities: boolean; manage:
const reader = input.primary ? db.$primary : db
const providerIds = input.providers.map((provider) => provider.id)
if (input.providers.some((provider) => provider.organization_id !== organizationId)) throw new Error("gateway_summary_organization_mismatch")
const [[member], catalogModels, groups, sets, links, access, credentials, teams] = await Promise.all([
const [[member], catalogModels, groups, sets, links, access, credentials, teams, signInDisabled] = await Promise.all([
reader.select({ userId: MemberTable.userId }).from(MemberTable).where(and(eq(MemberTable.id, memberId), eq(MemberTable.organizationId, organizationId), isNull(MemberTable.removedAt))),
providerIds.length ? reader.select().from(GatewayProviderModelTable).where(inArray(GatewayProviderModelTable.gateway_provider_id, providerIds))
.orderBy(asc(GatewayProviderModelTable.gateway_provider_id), asc(GatewayProviderModelTable.model_id)) : [],
Expand All @@ -528,6 +540,7 @@ export async function readGatewaySummaries(input: { identities: boolean; manage:
)))
.orderBy(asc(GatewayProviderCredentialTable.gateway_provider_id), asc(GatewayProviderCredentialTable.id)) : [],
memberGatewayTeams(reader, organizationId, memberId),
disabledSignInProviders(organizationId, input.providers),
])
if (!member?.userId) throw new GatewayWriteError(403, "forbidden")
const creatorIds = [...new Set(sets.flatMap((set) => set.created_by_org_membership_id ? [set.created_by_org_membership_id] : []))]
Expand All @@ -553,13 +566,14 @@ export async function readGatewaySummaries(input: { identities: boolean; manage:
links: (linksByProvider.get(id) ?? []).map((row) => row.link),
sets: setsByProvider.get(id) ?? [],
}])),
signInDisabled,
teamIds: teams.map((team) => team.id),
}
}

export function effectiveGatewaySummaryGrants(provider: GatewayProvider, memberId: GatewayMemberId, reads: GatewaySummaryReads) {
const rows = reads.providers.get(provider.id)
if (!rows) return []
if (!rows || reads.signInDisabled.has(provider.id)) return []
const activeGroupIds = new Set(rows.groups.filter((group) => group.status === "active").map((group) => group.id))
const activeSetIds = new Set(rows.sets.filter((set) => set.status === "active").map((set) => set.id))
const activeAccess = rows.access.filter((grant) => activeGroupIds.has(grant.model_group_id) && activeSetIds.has(grant.credential_set_id))
Expand Down Expand Up @@ -588,7 +602,7 @@ export async function gatewaySummary(provider: GatewayProvider, memberId: Gatewa
}
const modelsByGroupId = new Map(groups.map((group) => [group.id, models.filter((model) => linkedModelIds.get(group.id)?.has(model.id))]))
const activeAccess = access.filter((grant) => activeGroupIds.has(grant.model_group_id) && activeSetIds.has(grant.credential_set_id))
const grants = provider.status === "active" ? effectiveGatewayGrants(activeAccess, memberId, summaryReads.teamIds) : []
const grants = provider.status === "active" && !summaryReads.signInDisabled.has(provider.id) ? effectiveGatewayGrants(activeAccess, memberId, summaryReads.teamIds) : []
const creators = summaryReads.creators
const setSummaries: GatewayCredentialSet[] = sets.map((set) => {
const creator = creators.find((member) => member.id === set.created_by_org_membership_id)
Expand All @@ -607,7 +621,7 @@ export async function gatewaySummary(provider: GatewayProvider, memberId: Gatewa
&& (set.credential_mode === "member"
? litellm ? parsed.kind === "api_key" && (!token.expires_at || token.expires_at.getTime() > Date.now())
: Boolean(method && memberSignInCredentialUsable(method, set, token, parsed, Date.now(), signInScope))
: parsed.kind !== "oauth_azure" && parsed.kind !== "aws_sso"
: parsed.kind !== "oauth_azure" && parsed.kind !== "oauth_oidc" && parsed.kind !== "aws_sso"
&& (parsed.kind !== "oauth_google" || token.last_error !== "invalid_client")
&& (parsed.kind !== "oauth_google" || Boolean(token.expires_at && Number.isFinite(token.expires_at.getTime())))
&& (parsed.kind !== "api_key_map" || Boolean(pickInferenceApiKeyFromMap(parsed.apiKeys, readProviderEnvNames(provider.provider_config))))
Expand Down
3 changes: 2 additions & 1 deletion ee/apps/den-api/src/llm/gateway-member-connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function gatewayMemberConnections(input: { organizationId: GatewayP
eq(GatewayProviderCredentialTable.org_membership_id, input.memberId),
inArray(GatewayProviderCredentialTable.gateway_provider_id, providerIds),
inArray(GatewayProviderCredentialTable.credential_set_id, sets.map((set) => set.id)),
inArray(GatewayProviderCredentialTable.kind, ["oauth_google", "oauth_azure", "aws_sso"]),
inArray(GatewayProviderCredentialTable.kind, ["oauth_google", "oauth_azure", "oauth_oidc", "aws_sso"]),
inArray(GatewayProviderCredentialTable.status, ["active", "refresh_failed"]),
))
const groups = await tx.select().from(GatewayModelGroupTable).where(and(inArray(GatewayModelGroupTable.gateway_provider_id, providerIds), eq(GatewayModelGroupTable.status, "active")))
Expand Down Expand Up @@ -58,6 +58,7 @@ export async function gatewayMemberConnections(input: { organizationId: GatewayP
&& !gatewayConfigurationError(provider.provider_config, provider.settings)
const identity = parsed?.kind === "oauth_google" ? { revision: parsed.token.googleIdentity?.authorizationRevision ?? null, account: parsed.token.googleIdentity?.emailVerified === true ? parsed.token.googleIdentity.email : null }
: parsed?.kind === "oauth_azure" ? { revision: parsed.token.microsoftIdentity?.authorizationRevision ?? null, account: parsed.token.microsoftIdentity?.userName ?? null }
: parsed?.kind === "oauth_oidc" ? { revision: parsed.token.oidcIdentity?.authorizationRevision ?? null, account: parsed.token.oidcIdentity?.userName ?? null }
: parsed?.kind === "aws_sso" ? { revision: parsed.awsSso.identity.authorizationRevision, account: parsed.awsSso.identity.userName }
: { revision: null, account: null }
connections.push({ providerId: provider.id, signInMethod: method, credentialSetId: set.id, providerName: provider.name, name: set.name,
Expand Down
Loading
Loading