Skip to content

feat(platform): add generic OIDC identity provider adapter - #1809

Merged
yannickmonney merged 1 commit into
mainfrom
feat/generic-oidc
Jun 1, 2026
Merged

yannickmonney merged 1 commit into
mainfrom
feat/generic-oidc

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds a discovery-based generic OpenID Connect SSO adapter alongside the existing Microsoft Entra ID provider, so any OIDC issuer (Keycloak, Auth0, Okta, Google, …) can be configured. Part of the security & compliance baseline epic.

Backend

  • oidc_discovery.ts — resolves the authorization / token / userinfo endpoints from the issuer's .well-known/openid-configuration per auth flow. No endpoint is persisted, so there is no schema migration.
  • generic_oidc/adapter.ts — implements SsoProviderAdapter: forces the openid scope, maps sub → externalId / email / name (with given/family/preferred_username fallback) / groups, and reuses the provider-agnostic role matcher. Registered as 'generic-oidc'.
  • Interface change — buildAuthorizeUrl is now async-capable and getUserInfo / getGroups / getAppRoles take the provider config so discovery-driven adapters can resolve endpoints. Entra signatures and all call sites (authorize handler, callback handler, team sync, login) updated.
  • validate_sso_config.ts — now dispatches to the selected adapter (Entra Graph client-credentials probe vs. OIDC discovery) instead of hardcoding a Microsoft Graph scope.

UI

  • sso-config-dialog.tsx gains a provider-type selector. Entra-only controls (OneDrive/SharePoint, Graph team sync, exclude groups) are gated to Entra; the generic path sends standard OIDC scopes and persists no provider features. Issuer/client help text and the connected-state copy adapt per type.
  • en / de / fr strings added (de-CH inherits from de).

Tests

  • generic_oidc/adapter.test.ts — discovery, code→token exchange, userinfo claim mapping (incl. name fallbacks), and validateConfig success / unreachable-issuer / missing-userinfo paths (7 cases).
  • use-sso-config-form.test.ts — provider-type branching: Entra sends Graph scopes + features, generic sends standard scopes + no features, the test path targets the correct adapter, and the type is derived from a loaded config (4 cases).

Verification

bun run --filter @tale/platform typecheck · lint · test (server + ui) all green. CodeRabbit review applied (scope-selection helper deduped; load-mapping test added).

Refs #1506. Tracked under the security baseline epic #1803.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Generic OpenID Connect (OIDC) as an SSO provider option alongside Entra ID.
    • SSO configuration UI now displays provider-specific icons, descriptions, and help text based on selected provider type.
    • Generic OIDC automatically discovers endpoints from issuer configuration.
  • Improvements

    • Enhanced SSO configuration validation to support multiple provider types.
    • Added multi-language support (English, French, German) for Generic OIDC provider.

@coderabbitai

coderabbitai Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds support for Generic OpenID Connect (OIDC) as a new SSO provider type alongside the existing Entra ID provider. The changes span backend and frontend: OIDC discovery fetches and validates .well-known configurations; a new generic OIDC adapter implements authorization, token exchange, and user info retrieval with claim mapping; the adapter interface is updated to accept config objects and support async authorization URL building; backend handlers are wired to construct and thread SsoConfig through adapter calls; the frontend hook manages provider type state and scopes; the dialog conditionally renders different UI for each provider; and localization provides translated strings for English, German, and French.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

The PR combines new logic (OIDC adapter, discovery) with systematic updates across the adapter interface, backend wiring, and frontend form/dialog. Most changes follow established patterns (adapter implementation, handler updates, hook state management). The primary complexity is understanding the OIDC flow and how config objects are threaded through handlers, but the architecture is clear and changes are well-isolated.

Possibly related issues

Suggested reviewers

  • Israeltheminer
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.34% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers key backend/UI changes, tests, and verification steps, but the pre-merge checklist is incomplete with empty boxes. Complete the pre-merge checklist by ticking boxes or marking N/A with reasons. Confirm bun run check passed and docs were updated if needed.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a generic OIDC adapter alongside the existing Entra provider.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/generic-oidc

Warning

Billing warning: we have not been able to collect payment for this subscription for more than 72 hours. Please update the payment method or pay any pending invoices in Billing to avoid service interruption.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
services/platform/app/features/settings/integrations/components/sso-config-dialog.tsx (1)

200-224: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Hardcoded English placeholders bypass the translation layer.

'your-client-id' (Line 222) and 'All-Employees, Domain-Users' (Line 309) are user-facing English literals rendered directly in JSX. Route descriptive placeholder copy through t(...). The URL/UUID-format placeholders (Lines 202-203, 223) are format examples and are acceptable to leave inline.

As per coding guidelines: "No hardcoded user-facing strings in React — always use the translation hook; a stray English literal in JSX is a bug".

Also applies to: 309-309

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@services/platform/app/features/settings/integrations/components/sso-config-dialog.tsx`
around lines 200 - 224, The JSX contains hardcoded user-facing placeholders in
the SSOConfigDialog (specifically the Input with id "sso-client-id" and the
groups input placeholder "All-Employees, Domain-Users"); replace those literals
with translation keys via the t(...) hook (e.g., add/usage of
t('integrations.sso.clientIdPlaceholder') and
t('integrations.sso.groupsPlaceholder') or similar) so the placeholders route
through the i18n layer, leaving format/example literals (URLs/UUIDs) as-is;
update any tests or translation files to include the new keys.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@services/platform/convex/sso_providers/generic_oidc/adapter.test.ts`:
- Around line 73-76: The mock fetch handler uses a type assertion "as
URLSearchParams" for init?.body; replace that with a runtime type guard: in the
mockFetch callback (the function referencing DISCOVERY, jsonResponse and
tokenBody) check if init?.body instanceof URLSearchParams and then assign
tokenBody = init.body, otherwise handle the alternative types (e.g., if it's a
string parse it into URLSearchParams or throw/assert), so you remove the "as"
cast and safely narrow the body at runtime using instanceof before assigning to
tokenBody.

In `@services/platform/convex/sso_providers/generic_oidc/adapter.ts`:
- Around line 121-126: The returned mapping in adapter.ts currently sets
externalId to String(data.sub) which yields "undefined" if sub is missing;
update the mapping logic (the code that builds externalId alongside
email/name/groups) to validate that data.sub is present (not
null/undefined/empty) before converting to string and, if missing, fail fast by
throwing a clear error (or returning an explicit failure) indicating a missing
OIDC "sub" claim so callers of this function won’t receive a bogus externalId.

In `@services/platform/convex/sso_providers/oidc_discovery.ts`:
- Around line 37-49: The discoverOidc function currently fetches the well-known
OIDC document on every call; add a small in-memory module-level cache keyed by
issuer to store OidcEndpoints returned by wellKnownUrl/discoverOidc with a short
TTL (e.g., seconds-to-minutes) to avoid repeated network requests during a
single login flow. Implement cache lookup at the top of discoverOidc and return
the cached entry if not expired; on a cache miss fetch as today, store the
parsed OidcEndpoints in the cache with an expiry timestamp, and ensure cache
entries are not persisted to disk and are safely scoped to the module. Keep the
existing error handling and use the same identifiers (discoverOidc,
wellKnownUrl, OidcEndpoints) when updating the function.
- Around line 37-54: discoverOidc currently calls fetch(url) with no timeout and
no caching, which can hang SSO flows; update discoverOidc to call fetch with an
AbortSignal.timeout (or equivalent abort controller) and a reasonable timeout
(e.g., 2–5s) and propagate the abort to the error handling in discoverOidc so
failures surface quickly; additionally, implement simple in-memory caching keyed
by issuer (or well-known URL) inside the same module so the discovery document
is stored and reused between requests instead of refetching every flow; apply
the same timeout pattern to the other fetches noted (generic_oidc adapter
token/userinfo, entra_id adapter token/graph/discovery in validateConfig) using
the same timeout constant to keep behavior consistent.

In `@services/platform/convex/sso_providers/sso_callback_handler.ts`:
- Around line 203-208: Multiple discovery fetches happen during a single login
because adapter.exchangeCodeForTokens, adapter.getUserInfo (and the authorize
handler) each resolve the OIDC discovery document; add a short-lived in-memory
TTL cache keyed by issuer to store the discovery document and consult it before
performing network discovery. Implement the cache inside the generic-oidc
adapter (or a thin wrapper around adapter.exchangeCodeForTokens and
adapter.getUserInfo) so both methods reuse the cached discovery document, ensure
TTL expiry (e.g., configurable seconds) and safe fallback to re-fetch on cache
miss or error, and do this without any persistent schema changes.

---

Outside diff comments:
In
`@services/platform/app/features/settings/integrations/components/sso-config-dialog.tsx`:
- Around line 200-224: The JSX contains hardcoded user-facing placeholders in
the SSOConfigDialog (specifically the Input with id "sso-client-id" and the
groups input placeholder "All-Employees, Domain-Users"); replace those literals
with translation keys via the t(...) hook (e.g., add/usage of
t('integrations.sso.clientIdPlaceholder') and
t('integrations.sso.groupsPlaceholder') or similar) so the placeholders route
through the i18n layer, leaving format/example literals (URLs/UUIDs) as-is;
update any tests or translation files to include the new keys.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 02a4e166-5149-4d7e-b11a-4726f52040e4

📥 Commits

Reviewing files that changed from the base of the PR and between 0c56486 and 5944886.

📒 Files selected for processing (19)
  • services/platform/app/features/settings/integrations/components/sso-config-dialog.tsx
  • services/platform/app/features/settings/integrations/hooks/use-sso-config-form.test.ts
  • services/platform/app/features/settings/integrations/hooks/use-sso-config-form.ts
  • services/platform/convex/sso_providers/actions.ts
  • services/platform/convex/sso_providers/entra_id/adapter.ts
  • services/platform/convex/sso_providers/entra_id/team_sync.ts
  • services/platform/convex/sso_providers/generic_oidc/adapter.test.ts
  • services/platform/convex/sso_providers/generic_oidc/adapter.ts
  • services/platform/convex/sso_providers/handle_sso_login.ts
  • services/platform/convex/sso_providers/oidc_discovery.ts
  • services/platform/convex/sso_providers/registry.ts
  • services/platform/convex/sso_providers/sso_authorize_handler.ts
  • services/platform/convex/sso_providers/sso_callback_handler.ts
  • services/platform/convex/sso_providers/types.ts
  • services/platform/convex/sso_providers/upsert_sso_provider.ts
  • services/platform/convex/sso_providers/validate_sso_config.ts
  • services/platform/messages/de.json
  • services/platform/messages/en.json
  • services/platform/messages/fr.json

Comment on lines +73 to +76
mockFetch((url, init) => {
if (url.includes('.well-known')) return jsonResponse(DISCOVERY);
if (url === DISCOVERY.token_endpoint) {
tokenBody = init?.body as URLSearchParams;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Avoid the as cast in the fetch mock.

Narrow with instanceof instead of asserting the body type.

♻️ Proposed change
-      if (url === DISCOVERY.token_endpoint) {
-        tokenBody = init?.body as URLSearchParams;
+      if (url === DISCOVERY.token_endpoint) {
+        if (init?.body instanceof URLSearchParams) tokenBody = init.body;
As per coding guidelines: "Never use `as`, `any`, or `unknown` in TypeScript — use type guards, generics, discriminated unions, or `never` instead".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/convex/sso_providers/generic_oidc/adapter.test.ts` around
lines 73 - 76, The mock fetch handler uses a type assertion "as URLSearchParams"
for init?.body; replace that with a runtime type guard: in the mockFetch
callback (the function referencing DISCOVERY, jsonResponse and tokenBody) check
if init?.body instanceof URLSearchParams and then assign tokenBody = init.body,
otherwise handle the alternative types (e.g., if it's a string parse it into
URLSearchParams or throw/assert), so you remove the "as" cast and safely narrow
the body at runtime using instanceof before assigning to tokenBody.

Comment on lines +121 to +126
return {
externalId: String(data.sub),
email: data.email ?? data.preferred_username,
name,
groups: toStringArray(data.groups),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard against a missing sub claim.

If the userinfo response omits sub, String(data.sub) yields the literal string "undefined", which becomes a valid-looking externalId and can collide across users. Fail fast instead.

🐛 Proposed guard
-  const data = await response.json();
+  const data = await response.json();
+  if (typeof data.sub !== 'string' || !data.sub) {
+    throw new Error('OIDC userinfo response is missing the required `sub` claim');
+  }
   const name =
   return {
-    externalId: String(data.sub),
+    externalId: data.sub,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/convex/sso_providers/generic_oidc/adapter.ts` around lines
121 - 126, The returned mapping in adapter.ts currently sets externalId to
String(data.sub) which yields "undefined" if sub is missing; update the mapping
logic (the code that builds externalId alongside email/name/groups) to validate
that data.sub is present (not null/undefined/empty) before converting to string
and, if missing, fail fast by throwing a clear error (or returning an explicit
failure) indicating a missing OIDC "sub" claim so callers of this function won’t
receive a bogus externalId.

Comment on lines +37 to +49
export async function discoverOidc(issuer: string): Promise<OidcEndpoints> {
const url = wellKnownUrl(issuer);
let response: Response;
try {
response = await fetch(url);
} catch (err) {
throw new Error(
`OIDC discovery failed: could not reach ${url} (${
err instanceof Error ? err.message : 'network error'
})`,
{ cause: err },
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider caching the discovery document.

The header comment notes the well-known document is cacheable, but discoverOidc re-fetches on every call. During a single callback the adapter resolves discovery for token exchange, userinfo, and (via team sync) group lookup, multiplying outbound requests per login. A small module-level cache keyed by issuer with a short TTL would cut this without persisting endpoints.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/convex/sso_providers/oidc_discovery.ts` around lines 37 -
49, The discoverOidc function currently fetches the well-known OIDC document on
every call; add a small in-memory module-level cache keyed by issuer to store
OidcEndpoints returned by wellKnownUrl/discoverOidc with a short TTL (e.g.,
seconds-to-minutes) to avoid repeated network requests during a single login
flow. Implement cache lookup at the top of discoverOidc and return the cached
entry if not expired; on a cache miss fetch as today, store the parsed
OidcEndpoints in the cache with an expiry timestamp, and ensure cache entries
are not persisted to disk and are safely scoped to the module. Keep the existing
error handling and use the same identifiers (discoverOidc, wellKnownUrl,
OidcEndpoints) when updating the function.

Comment on lines +37 to +54
export async function discoverOidc(issuer: string): Promise<OidcEndpoints> {
const url = wellKnownUrl(issuer);
let response: Response;
try {
response = await fetch(url);
} catch (err) {
throw new Error(
`OIDC discovery failed: could not reach ${url} (${
err instanceof Error ? err.message : 'network error'
})`,
{ cause: err },
);
}
if (!response.ok) {
throw new Error(
`OIDC discovery failed: ${url} returned ${response.status}`,
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the referenced files
ls -la services/platform/convex/sso_providers || true
ls -la services/platform/convex/sso_providers/generic_oidc || true
ls -la services/platform/convex/sso_providers/* || true

# Show the discoverOidc implementation around the referenced lines
echo "---- oidc_discovery.ts (lines 1-140) ----"
sed -n '1,140p' services/platform/convex/sso_providers/oidc_discovery.ts

# Find fetch(url) patterns in OIDC related files
echo "---- rg for fetch calls near OIDC discovery/adapters ----"
rg -n --glob='services/platform/convex/sso_providers/**/*.{ts,tsx,js,jsx}' "fetch\(" services/platform/convex/sso_providers

# Inspect generic OIDC adapter token/userinfo fetches
echo "---- generic_oidc/adapter.ts (first 240 lines) ----"
sed -n '1,240p' services/platform/convex/sso_providers/generic_oidc/adapter.ts

# If there is an Entra adapter, find it and inspect for token/userinfo fetches
echo "---- list Entra adapters if present ----"
fd -t f -g'*entra*' services/platform/convex/sso_providers || true

echo "---- rg for entra adapter fetch(url) ----"
rg -n --glob='services/platform/convex/sso_providers/**/*.{ts,tsx,js,jsx}' "entra|Entra" services/platform/convex/sso_providers

# Look for cacheability claims / caching logic in oidc_discovery.ts
echo "---- rg for 'cache' in oidc_discovery.ts ----"
rg -n "cache|cach" services/platform/convex/sso_providers/oidc_discovery.ts

Repository: tale-project/tale

Length of output: 21441


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) How discoverOidc is called across adapters
echo "---- rg: discoverOidc( ----"
rg -n "discoverOidc\(" services/platform/convex/sso_providers

# 2) Inspect full oidc_discovery.ts for the caching claim/context
echo "---- oidc_discovery.ts (full) ----"
wc -l services/platform/convex/sso_providers/oidc_discovery.ts
sed -n '1,220p' services/platform/convex/sso_providers/oidc_discovery.ts

# 3) Inspect Entra adapter fetch usages around the reported lines
echo "---- entra_id/adapter.ts (fetch-related sections) ----"
sed -n '1,360p' services/platform/convex/sso_providers/entra_id/adapter.ts

# 4) Check if any timeout helper / AbortSignal.timeout / AbortController exists in this area
echo "---- rg: AbortSignal.timeout ----"
rg -n "AbortSignal\.timeout" services/platform/convex

echo "---- rg: AbortController ----"
rg -n "AbortController" services/platform/convex

echo "---- rg: timeout( helper keywords ----"
rg -n "timeout|setTimeout\(" services/platform/convex/sso_providers

Repository: tale-project/tale

Length of output: 16736


🌐 Web query:

Convex runtime fetch AbortSignal.timeout support

💡 Result:

As of June 1, 2026, AbortSignal.timeout() is a standard Web API supported in most modern JavaScript runtimes [1][2]. However, its usage within Convex depends on the specific context: 1. Client-Side Usage: You can use AbortSignal.timeout() in your frontend code (e.g., React, Next.js) when making standard fetch requests or interacting with other browser APIs [1][3]. If you are using the ConvexHttpClient in a browser or Node.js environment, you can provide a custom fetch implementation via the fetch option in the constructor [4]. This allows you to pass requests that utilize AbortSignal.timeout() if your custom fetch implementation supports it. 2. Convex Functions (Actions/Mutations): There is no native, first-class support for passing an AbortSignal directly into Convex mutation or action function calls to cancel the execution on the server side [5]. Convex actions run in a custom environment that supports many browser-like APIs, but canceling an already-executing server-side function via an AbortSignal is not currently implemented [6][5]. While there have been community requests to add AbortSignal support to the Convex client for canceling queued mutations or in-flight actions, it remains an open area of development [5]. In summary, while you can utilize AbortSignal.timeout() for standard network requests made from your client or within actions to external APIs, it does not provide a mechanism to abort or time out the internal execution of Convex functions themselves [1][5].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect one of the existing AbortSignal.timeout + fetch usage sites
echo "---- services/platform/convex/oauth2.ts (relevant excerpts) ----"
sed -n '60,190p' services/platform/convex/oauth2.ts

# Check SSO discover handler / authorize/callback to see if any caching/persistence is done
echo "---- inspect SSO handlers that may call discovery ----"
sed -n '1,220p' services/platform/convex/sso_providers/sso_discover_handler.ts
sed -n '1,220p' services/platform/convex/sso_providers/sso_authorize_handler.ts
sed -n '1,260p' services/platform/convex/sso_providers/sso_callback_handler.ts

# Confirm no caching for OIDC discovery elsewhere
echo "---- rg: OIDC discovery caching or persistence ----"
rg -n "discoverOidc|openid-configuration|userinfoEndpoint|tokenEndpoint" services/platform/convex/sso_providers/sso_* services/platform/convex/sso_providers/* || true

Repository: tale-project/tale

Length of output: 1956


Add timeouts to OIDC/Entra external fetches on the SSO login path.

services/platform/convex/sso_providers/oidc_discovery.ts calls fetch(url) in discoverOidc with no timeout, so a slow/unresponsive issuer can hang the authorize/callback request indefinitely. The same unbounded fetch(...) pattern exists in:

  • services/platform/convex/sso_providers/generic_oidc/adapter.ts (token + userinfo fetches)
  • services/platform/convex/sso_providers/entra_id/adapter.ts (token + Graph fetches, plus discovery fetch in validateConfig)

Also, the discovery JSDoc says the document is “cacheable”, but there’s no caching/persistence—so discovery is re-fetched per flow.

🛡️ Proposed fix using AbortSignal.timeout
   try {
-    response = await fetch(url);
+    response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
   } catch (err) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export async function discoverOidc(issuer: string): Promise<OidcEndpoints> {
const url = wellKnownUrl(issuer);
let response: Response;
try {
response = await fetch(url);
} catch (err) {
throw new Error(
`OIDC discovery failed: could not reach ${url} (${
err instanceof Error ? err.message : 'network error'
})`,
{ cause: err },
);
}
if (!response.ok) {
throw new Error(
`OIDC discovery failed: ${url} returned ${response.status}`,
);
}
export async function discoverOidc(issuer: string): Promise<OidcEndpoints> {
const url = wellKnownUrl(issuer);
let response: Response;
try {
response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
} catch (err) {
throw new Error(
`OIDC discovery failed: could not reach ${url} (${
err instanceof Error ? err.message : 'network error'
})`,
{ cause: err },
);
}
if (!response.ok) {
throw new Error(
`OIDC discovery failed: ${url} returned ${response.status}`,
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/convex/sso_providers/oidc_discovery.ts` around lines 37 -
54, discoverOidc currently calls fetch(url) with no timeout and no caching,
which can hang SSO flows; update discoverOidc to call fetch with an
AbortSignal.timeout (or equivalent abort controller) and a reasonable timeout
(e.g., 2–5s) and propagate the abort to the error handling in discoverOidc so
failures surface quickly; additionally, implement simple in-memory caching keyed
by issuer (or well-known URL) inside the same module so the discovery document
is stored and reused between requests instead of refetching every flow; apply
the same timeout pattern to the other fetches noted (generic_oidc adapter
token/userinfo, entra_id adapter token/graph/discovery in validateConfig) using
the same timeout constant to keep behavior consistent.

Comment on lines +203 to +208
const tokens = await adapter.exchangeCodeForTokens(ssoConfig, {
code,
redirectUri: state.redirectUri,
});

const userInfo = await adapter.getUserInfo(tokens.accessToken);
const userInfo = await adapter.getUserInfo(ssoConfig, tokens.accessToken);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider caching OIDC discovery to avoid per-login round trips.

For generic-oidc, exchangeCodeForTokens and getUserInfo each resolve endpoints via .well-known/openid-configuration discovery, and the authorize handler does the same — so a single login can trigger multiple discovery fetches. Since this is intentionally not persisted (no schema migration), consider a short-lived in-memory/TTL cache of the discovery document keyed by issuer to reduce latency and dependency on the IdP's availability on every flow.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/convex/sso_providers/sso_callback_handler.ts` around lines
203 - 208, Multiple discovery fetches happen during a single login because
adapter.exchangeCodeForTokens, adapter.getUserInfo (and the authorize handler)
each resolve the OIDC discovery document; add a short-lived in-memory TTL cache
keyed by issuer to store the discovery document and consult it before performing
network discovery. Implement the cache inside the generic-oidc adapter (or a
thin wrapper around adapter.exchangeCodeForTokens and adapter.getUserInfo) so
both methods reuse the cached discovery document, ensure TTL expiry (e.g.,
configurable seconds) and safe fallback to re-fetch on cache miss or error, and
do this without any persistent schema changes.

Adds a discovery-based generic OpenID Connect SSO adapter alongside the
existing Microsoft Entra ID provider, so any OIDC issuer (Keycloak, Auth0,
Okta, Google, …) can be configured.

Backend:
- oidc_discovery.ts resolves the authorization/token/userinfo endpoints from
  the issuer's .well-known/openid-configuration per auth flow, so no endpoint
  is persisted and no schema migration is needed.
- generic_oidc/adapter.ts implements SsoProviderAdapter (forces the openid
  scope, maps sub→externalId/email/name/groups, reuses the provider-agnostic
  role matcher) and is registered as 'generic-oidc'.
- SsoProviderAdapter.buildAuthorizeUrl is now async-capable and getUserInfo/
  getGroups/getAppRoles take the provider config so discovery-driven adapters
  can resolve endpoints; Entra signatures and all call sites updated.
- validate_sso_config dispatches to the selected adapter (Entra Graph probe vs
  OIDC discovery).

UI:
- sso-config-dialog gains a provider-type selector; Entra-only controls
  (OneDrive, Graph team sync, exclude groups) are gated to Entra, and the
  generic path sends standard OIDC scopes with no provider features.
- en/de/fr strings added.

Tests: generic adapter (discovery, token exchange, userinfo mapping,
validateConfig) and the provider-type branching in the config form.

Refs #1506, #1803
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit review (pushed):

  • Missing sub claim — getUserInfo now fails fast with a clear error instead of producing externalId: "undefined" (which would collide every such user onto one account). Accepts string or numeric sub. Test added.
  • Discovery caching — added a short-lived (5 min) in-memory cache keyed by issuer in oidc_discovery.ts, so a single login callback (token exchange + userinfo + group sync) folds into one network call. Best-effort per isolate, never persisted. Test added asserting one .well-known fetch across calls. This also resolves the "multiple discovery fetches per login" note on the callback handler.
  • Fetch timeout — discovery, token, and userinfo fetches now use AbortSignal.timeout(10_000) (matching the oauth2.ts convention) so a stuck IdP socket fails fast instead of hanging the flow.
  • Test type-assertion — replaced init?.body as URLSearchParams with an instanceof URLSearchParams narrow.

Skipped (with reason):

  • i18n the your-client-id / All-Employees, Domain-Users placeholders — every placeholder in this dialog (the tenant-GUID example, the issuer URL, the groups example) is a literal example, and CodeRabbit's own guidance is to leave format/example literals as-is. Routing one through i18n while the others stay literal would be inconsistent, so I've left the established pattern intact.
  • Entra adapter fetch timeouts — pre-existing code outside this PR's scope; worth a separate hardening pass.

@yannickmonney
yannickmonney merged commit 758b0ba into main Jun 1, 2026
28 checks passed
@yannickmonney
yannickmonney deleted the feat/generic-oidc branch June 1, 2026 23:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant