Skip to content

oauth2: OIDC login nonce and per-attempt CSRF state - #14296

Draft
rootnomad wants to merge 11 commits into
apache:mainfrom
rootnomad:feature/oidc-nonce-state
Draft

rootnomad wants to merge 11 commits into
apache:mainfrom
rootnomad:feature/oidc-nonce-state

Conversation

@rootnomad

@rootnomad rootnomad commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Follow-up to #14205. Finishes and hardens the generic OIDC login, from the review on #14205.

  • Per-attempt CSRF state: the UI generates a random nonce and state, sends the nonce in the authorization request, and rejects the callback when the returned state does not match, before the code is exchanged (state was fixed to cloudstack before).
  • Nonce: the id_token nonce claim is verified against the nonce from the request, carried by a new nonce API parameter. Only the generic OIDC provider checks it and the state check only applies to the OIDC flow, so the built-in google, github and keycloak logins are unchanged.
  • The authorization endpoint is discovered and stored server side at registration, so the UI redirects without reading the discovery document from the browser, which removes the IdP CORS requirement. The UI falls back to browser discovery when the endpoint is not stored.
  • The authorize URL is built with the URL API so an endpoint that already has a query component is preserved.
  • The global generic provider list is restored when the domain field is cleared, so stale domain-specific buttons are not shown.

Depends on #14205.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)
  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (improves an existing feature and functionality)
  • Cleanup (Code refactoring and cleanup, that may add test cases)
  • Build/CI
  • Test (unit or integration test code)

How Has This Been Tested?

All 110 tests in the oauth2 plugin pass, built and run on a Linux build host with Java 17. The provider tests use real RS256 signing and verification against a JWKS: a matching nonce is accepted and a mismatched one rejected, an unverified email is rejected, a key without alg falls back to the token header, the keys are cached across logins, and the usual signature, issuer, audience and expiry checks hold.

The frontend state and nonce round trip has been reviewed by hand but not run in a browser, since that needs a live identity provider.

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown

This pull request has merge conflicts. Dear author, please fix the conflicts and sync your branch with the base branch.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

This pull request has merge conflicts. Dear author, please fix the conflicts and sync your branch with the base branch.

@github-actions

Copy link
Copy Markdown

This pull request has merge conflicts. Dear author, please fix the conflicts and sync your branch with the base branch.

@github-actions

Copy link
Copy Markdown

This pull request has merge conflicts. Dear author, please fix the conflicts and sync your branch with the base branch.

The OAuth2 plugin resolves a login to a UserOAuth2Authenticator through a fixed
provider-name to Spring-bean map, and each OIDC vendor is its own bean running the
same authorization-code flow with no vendor-specific logic. A new IdP needs a new
class, and since provider is both the display name and the routing key, a domain can
register only one keycloak.

This adds a type column to oauth_provider. OAuth2AuthManagerImpl looks the name up in
the bean map first and only on a miss falls back to the registration's type, so
provider becomes an admin-chosen label and type selects the implementation. One bean
then serves any number of registrations under arbitrary names. Existing google, github
and keycloak rows carry a null type and dispatch by name as before.

GenericOIDCOAuth2Provider is registered under type oidc and configured with the issuer
URL. It reads the token and JWKS endpoints from the issuer's discovery document (the
issuer must match), and validates the id_token before trusting it: signature against the
JWKS key named by the token kid, then issuer, audience and expiry, using the CXF JOSE
library already on the classpath. It holds no token state between logins, and a code
verified through verifyOAuthCodeAndGetUser is redeemed once so the following oauthlogin
does not re-present it.

ListOAuthProvidersCmd and UpdateOAuthProviderCmd derived the response enabled flag from a
name-to-bean check, which reported every generically-named registration as disabled; both
now also accept a registration whose type resolves to a plugin.

The schema change adds type and issuer_url to oauth_provider in the 4.23.0.0 to 24.0.0
upgrade file. Login.vue renders the OAuth buttons from the registered provider list so a
generic oidc provider gets a Sign in with <label> button and starts the flow from the
issuer's authorize endpoint, resolved from discovery.
- fall back to the id_token header algorithm when a published JWK omits alg
  (Entra ID does this), so verification no longer fails for those providers
- cache the JWKS per issuer like the discovery document, refetching once on
  an unknown key id for rotation, instead of fetching on every login
- reject registering an OIDC type under a name reserved by a built-in
  provider, where the name would shadow the type during dispatch
- log the provider's raw token-exchange error server side and return a
  generic message to the caller
- require a verified email (email_verified) in the id_token before using it
  as the account identity, so an unverified address cannot claim a user
- key the single-use verified-email cache by domain as well, so a code
  verified for one domain cannot be consumed for another
- store the provider type lowercased so list, update and the UI agree with
  the case-insensitive dispatch lookup
- correct the since metadata on the new type/issuerUrl parameters and
  response fields from 4.24.0 to 24.0.0
Key the one-time email cache on the resolved registration instead of the
request domain. verifyOAuthCodeAndGetUser can resolve the code with no
domain while the login that follows lands on a concrete domain; the old key
mixed the two, so the single use authorization code was redeemed a second
time and rejected. The registration is resolved up front and its uuid keys
the cache, which also keeps a code scoped to its own registration.

Make the verified-email requirement a domain setting
(oauth2.oidc.require.verified.email, default true). An explicit
email_verified=false is always rejected; an absent claim is rejected only
when the setting is on, so a trusted provider that does not send it, such as
Microsoft Entra ID, can be allowed per domain.

Stop returning the provider's raw response body on a failed discovery or
JWKS fetch; it now goes to the log and the caller gets a generic message,
matching the token exchange.
Fixes from testing feedback and a security pass on the generic OIDC provider.

Correctness and UX:
- register now reports enabled using the same name-or-type check as list and
  update, so a generic oidc provider is no longer reported disabled right after
  registration while list reports it enabled.
- the login and verify API handlers now convert any failure to a proper API
  error with a message instead of letting a CloudRuntimeException or JwtException
  surface as an empty HTTP 200.
- the issuer is validated at registration (reachable discovery document whose
  issuer matches). This is best effort and does not block registration if the
  issuer is briefly unreachable; the same problem still surfaces with a clear
  error at the first login.
- listOauthProvider returns an empty list instead of a list holding a null when
  a uuid or name matches nothing.
- the registerOauthProvider API description notes the exact casing of the name,
  since registerOAuthProvider is not a valid command name.

Hardening:
- the id_token audience is validated per OIDC core: multiple audiences require an
  authorized party (azp) that matches the registered client, closing an
  audience-confusion login with a token minted for another client on the same
  issuer.
- only asymmetric id_token signatures (RS, PS, ES) are accepted, rejecting HMAC
  and none and the RS256 to HS256 key-confusion attack.
- issuer, token and JWKS endpoints must use https (loopback excepted), so the
  client secret is never sent in cleartext and a tampered discovery document
  cannot redirect the server to an internal http target. This is controlled by
  oauth2.oidc.require.https (default true) and can be disabled for a trusted lab
  identity provider served over http.
- the not-before claim is honored, hostile or malformed provider responses no
  longer crash the login (missing audience, non-string email, non-JSON bodies),
  provider responses are read with a size cap, and token endpoint error bodies
  are no longer logged.
- updateOauthProvider and listOauthProvider no longer disable sensitive-info
  redaction, so the client secret is not written to the API logs.
…ogin URL safely

On the login page, clearing the domain field restored the per-vendor providers
but left the generic OIDC provider list scoped to the last domain, so the global
providers did not come back. Cache the global generic list and restore it when
the domain is cleared.

Build the generic OIDC sign-in URL with the URL API so a provider authorization
endpoint that already contains a query string does not get a second question
mark.
Binds the generic OIDC login to the authorization request:
- the UI generates a random nonce and state per attempt, sends the nonce in
  the authorization request, and rejects the callback when the returned
  state does not match before the code is exchanged
- the id_token nonce claim is verified against the nonce from the request
  (generic OIDC only; the built-in providers ignore it)

Follow-up to apache#14205.
Discover and store the authorization endpoint at registration so the UI
redirects without reading the discovery document from the browser, which
removes the IdP CORS requirement. The login page falls back to discovery
when no endpoint is stored.
Align the existing provider and command tests with the hardened behavior:
verifyUser resolves through the nonce-aware path, the verified-email tests
stub the four-argument resolveEmail, the token helper sets email_verified,
and the command test mocks the nonce overload. All 110 oauth2 tests pass.
@rootnomad
rootnomad force-pushed the feature/oidc-nonce-state branch from ce96af0 to 406095b Compare December 2, 2026 16:12
@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 61.15880% with 181 lines in your changes missing coverage. Please review.
✅ Project coverage is 21.20%. Comparing base (8eaff97) to head (406095b).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...udstack/oauth2/oidc/GenericOIDCOAuth2Provider.java 66.16% 91 Missing and 21 partials ⚠️
...pache/cloudstack/auth/UserOAuth2Authenticator.java 0.00% 14 Missing ⚠️
...pache/cloudstack/oauth2/OAuth2AuthManagerImpl.java 71.73% 11 Missing and 2 partials ⚠️
...k/oauth2/api/command/RegisterOAuthProviderCmd.java 65.38% 4 Missing and 5 partials ⚠️
...tack/oauth2/api/command/ListOAuthProvidersCmd.java 0.00% 8 Missing ⚠️
...ack/oauth2/api/command/UpdateOAuthProviderCmd.java 0.00% 8 Missing ⚠️
...uth2/api/command/VerifyOAuthCodeAndGetUserCmd.java 45.45% 5 Missing and 1 partial ⚠️
...ack/oauth2/api/response/OauthProviderResponse.java 50.00% 6 Missing ⚠️
...th2/api/command/OauthLoginAPIAuthenticatorCmd.java 33.33% 3 Missing and 1 partial ⚠️
...che/cloudstack/oauth2/OAuth2UserAuthenticator.java 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##              main   #14296       +/-   ##
============================================
+ Coverage     3.86%   21.20%   +17.33%     
- Complexity       0    21650    +21650     
============================================
  Files          494     6082     +5588     
  Lines        42890   552259   +509369     
  Branches      8142    79402    +71260     
============================================
+ Hits          1657   117088   +115431     
- Misses       41001   421349   +380348     
- Partials       232    13822    +13590     
Flag Coverage Δ
uitests 3.86% <ø> (+<0.01%) ⬆️
unittests 22.67% <61.15%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Cover passing the nonce from verifyOAuthCodeAndGetUser through the manager
to the OIDC provider, the authorize endpoint discovery when an OIDC provider
is registered without one, and the UserOAuth2Authenticator defaults.
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

This pull request has merge conflicts. Dear author, please fix the conflicts and sync your branch with the base branch.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant