Skip to content

oauth2: add a generic OIDC provider type - #14205

Open
rootnomad wants to merge 6 commits into
apache:mainfrom
rootnomad:feature/generic-oidc-provider
Open

rootnomad wants to merge 6 commits into
apache:mainfrom
rootnomad:feature/generic-oidc-provider

Conversation

@rootnomad

@rootnomad rootnomad commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Description

The OAuth2 plugin resolves a login to a UserOAuth2Authenticator through a fixed
provider-name to Spring-bean map. Each OIDC vendor is its own bean
(GoogleOAuth2Provider, GithubOAuth2Provider, KeycloakOAuth2Provider) running the
same authorization-code flow with no vendor-specific logic in it. Two consequences:
adding an IdP means shipping a new class, and because provider is simultaneously the
display name and the routing key, a domain can register exactly one keycloak.

This PR decouples the two by adding a type column to oauth_provider:

  • OAuth2AuthManagerImpl.getUserOAuth2AuthenticationProvider looks the name up in the
    bean map first, as before, and only on a miss falls back to the registration's type.
    provider becomes an admin-chosen label; type selects the implementation. One bean
    can serve any number of registrations under arbitrary names.
  • getUserOAuth2AuthenticationProvider, verifyUser and verifySecretCodeAndFetchEmail
    now carry the registration name, so a shared bean knows which row it is acting for.
  • Existing google/github/keycloak rows have a null type and continue to dispatch
    by name, on the same code path as today.

GenericOIDCOAuth2Provider is registered under type=oidc and configured with the issuer
URL alone. It reads token_endpoint and jwks_uri from the issuer's
.well-known/openid-configuration (cached; the document's issuer must match the
configured value), and validates the id_token before trusting any claim in it: signature
against the JWKS key named by the token kid, then issuer, audience and expiry, via CXF's
JwsJwtCompactConsumer / JwkUtils / JwtUtils. That is cxf-rt-rs-security-jose,
already on the plugin classpath, so no new dependency.

Unlike the vendor providers, it holds no token in an instance field. The code is exchanged
per call, and a code verified through verifyOAuthCodeAndGetUser is cached for 60s and
consumed once, so the oauthlogin that immediately follows does not re-present it to the
IdP.

API / response fix: ListOAuthProvidersCmd and UpdateOAuthProviderCmd derived the
response enabled flag from authenticatorPluginNames.contains(provider), 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.

type is settable on register but not on update: changing it would swap the
implementation under an existing row.

Schema: adds type and issuer_url to oauth_provider in the 4.23.0.0 to 24.0.0
upgrade file.

UI: Login.vue renders a button per registered oidc provider (in addition to the
existing google/github/keycloak buttons), labelled "Sign in with ". Clicking it
reads the issuer's authorization_endpoint from discovery and starts the
authorization-code flow. As with the keycloak provider, the registered redirecturi must
carry verifyOauth (for example https://<ui-host>/client?verifyOauth) so the callback
lands on the verify handler.

Fixes: #9609

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)

Feature/Enhancement Scale or Bug Severity

Feature/Enhancement Scale

  • Major
  • Minor

Screenshots (if appropriate):

1-login-with-oidc-button 2-keycloak-login 3-dashboard-logged-in

How Has This Been Tested?

Unit tests - oauth2 module, 103 tests green.

  • GenericOIDCOAuth2ProviderTest (27 tests) generates an RSA keypair, publishes the
    matching JWKS, and asserts that a genuinely signed token is accepted while these are
    rejected: a token with altered claims, one signed by a different key, one naming a kid
    absent from the JWKS, and issuer / audience / expiry mismatches. Also covers discovery
    document validation (issuer mismatch) and that a verified code is redeemed exactly once.
  • OAuth2AuthManagerImplTest covers the type fallback, an unknown type rejected at
    register time, and a real bean name winning without a DB lookup.
  • Vendor provider tests updated for the name-carrying signatures.
  • DatabaseUpgradeCheckerTest green with the new schema file.

Integration - KVM advanced zone against Keycloak 25. Registered an oidc provider
pointing at a Keycloak realm and logged a real user in through the Keycloak form:
verifyOAuthCodeAndGetUser validates the RS256 signature against the realm JWKS and
returns the email, oauthlogin with the same code issues the session, and
listOauthProviders reports the generically-named provider as enabled.

How did you try to break this feature and the system with this change?

  • A login presenting a valid, correctly signed token but claiming a different CloudStack
    user's email - rejected, no session.
  • Replay of an already-consumed code - rejected, no session.
  • A bogus/garbage code - rejected, no session.
  • After each of the above, a fresh correct login still succeeds.
  • Existing google/github/keycloak registrations are untouched and still log in
    (name-based dispatch, null type).
  • Discovery document whose issuer does not match the configured issuer URL - rejected.

@rootnomad

Copy link
Copy Markdown
Contributor Author

This is the generic OIDC provider from the discussion on #13854: one oidc type that serves any number of registrations under admin-chosen names, with discovery and full id_token validation, so a new IdP no longer needs its own class.

It overlaps #13499 (ForgeRock), which @bddvlpr put on hold in favour of doing the generic feature. My GenericOIDCOAuth2Provider is separate from the AbstractOIDCOAuth2Provider there, but three files touch the same code: RegisterOAuthProviderCmd, spring-oauth2-context.xml and Login.vue. Whichever lands second is a small rebase and I am happy for that to be mine.

@bddvlpr @Damans227 this builds on your design, so please review. If you would rather fold the ForgeRock case in here as an oidc registration, or keep it as a named provider on top, either works.

@rootnomad

Copy link
Copy Markdown
Contributor Author

@DaanHoogland @weizhouapache Could you pls take a look

@DaanHoogland

Copy link
Copy Markdown
Contributor

@blueorangutan package

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 64.08669% with 116 lines in your changes missing coverage. Please review.
✅ Project coverage is 20.24%. Comparing base (f03cffc) to head (9cbe466).
⚠️ Report is 94 commits behind head on main.

Files with missing lines Patch % Lines
...udstack/oauth2/oidc/GenericOIDCOAuth2Provider.java 67.52% 67 Missing and 9 partials ⚠️
...tack/oauth2/api/command/ListOAuthProvidersCmd.java 0.00% 8 Missing ⚠️
...ack/oauth2/api/command/UpdateOAuthProviderCmd.java 0.00% 8 Missing ⚠️
...pache/cloudstack/auth/UserOAuth2Authenticator.java 0.00% 6 Missing ⚠️
...pache/cloudstack/oauth2/OAuth2AuthManagerImpl.java 80.00% 5 Missing and 1 partial ⚠️
...ack/oauth2/api/response/OauthProviderResponse.java 50.00% 6 Missing ⚠️
...k/oauth2/api/command/RegisterOAuthProviderCmd.java 50.00% 4 Missing and 1 partial ⚠️
...che/cloudstack/oauth2/OAuth2UserAuthenticator.java 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main   #14205      +/-   ##
============================================
+ Coverage     20.21%   20.24%   +0.02%     
- Complexity    20747    20808      +61     
============================================
  Files          6426     6428       +2     
  Lines        580181   580502     +321     
  Branches      71033    71068      +35     
============================================
+ Hits         117282   117494     +212     
- Misses       450184   450284     +100     
- Partials      12715    12724       +9     
Flag Coverage Δ
uitests 3.68% <ø> (-0.01%) ⬇️
unittests 21.53% <64.08%> (+0.02%) ⬆️

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.

@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.

Copilot AI 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.

Copilot review overview

🟡 Changes recommended

Authentication state handling, domain cache isolation, and several OIDC interoperability issues must be corrected.

Review effort: Balanced
Findings: 3 High severity · 4 Medium severity · 3 Low severity

Open (10)
What changed in this PR

Adds reusable generic OIDC authentication, separating provider labels from implementation types.

Changes:

  • Adds OIDC discovery, token validation, and registration-type dispatch.
  • Extends schema and APIs with provider type and issuer URL.
  • Adds generic OIDC login UI and tests.
File Description
ui/​src/​views/​auth/​Login.vue Adds generic OIDC login buttons and discovery.
ui/​public/​locales/​en.json Adds OIDC login messages.
ui/​public/​assets/​oidc.svg Adds the OIDC logo.
plugins/​user-authenticators/​oauth2/​src/​test/​java/​org/​apache/​cloudstack/​oauth2/​oidc/​GenericOIDCOAuth2ProviderTest.java Tests OIDC validation and code caching.
plugins/​user-authenticators/​oauth2/​src/​test/​java/​org/​apache/​cloudstack/​oauth2/​OAuth2UserAuthenticatorTest.java Updates provider-aware authentication tests.
plugins/​user-authenticators/​oauth2/​src/​test/​java/​org/​apache/​cloudstack/​oauth2/​OAuth2AuthManagerImplTest.java Tests type-based provider dispatch.
plugins/​user-authenticators/​oauth2/​src/​main/​resources/​META-INF/​cloudstack/​oauth2/​spring-oauth2-context.xml Registers the generic OIDC bean.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​vo/​OauthProviderVO.java Maps type and issuer fields.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​oidc/​GenericOIDCOAuth2Provider.java Implements generic OIDC authentication.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​OAuth2UserAuthenticator.java Passes registration context during login.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​OAuth2AuthManagerImpl.java Resolves providers by registration type.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​OAuth2AuthManager.java Extends the manager contract.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​api/​response/​OauthProviderResponse.java Exposes type and issuer URL.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​api/​command/​UpdateOAuthProviderCmd.java Supports issuer URL updates.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​api/​command/​RegisterOAuthProviderCmd.java Supports generic OIDC registration.
plugins/​user-authenticators/​oauth2/​src/​main/​java/​org/​apache/​cloudstack/​oauth2/​api/​command/​ListOAuthProvidersCmd.java Reports type-backed providers correctly.
engine/​schema/​src/​main/​resources/​META-INF/​db/​schema-42300to2400.sql Adds type and issuer columns.
api/​src/​main/​java/​org/​apache/​cloudstack/​auth/​UserOAuth2Authenticator.java Adds registration-aware default methods.
api/​src/​main/​java/​org/​apache/​cloudstack/​api/​ApiConstants.java Adds the issuer URL API constant.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread ui/src/views/auth/Login.vue Resolved
Comment thread ui/src/views/auth/Login.vue Resolved
Comment thread ui/src/views/auth/Login.vue Resolved
Comment thread ui/src/views/auth/Login.vue Resolved

@Damans227 Damans227 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

can you rebase? there are conflicts with main

try (CloseableHttpResponse response = httpClient.execute(post)) {
String body = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() != 200) {
throw new CloudRuntimeException(String.format("%s error during token generation: %s", provider.getProvider(), body));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

should the IdP's raw error go to the log instead of back to the caller?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Makes sense, thank you. The provider's raw error now goes to the server log and the caller gets a generic message instead.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

that covers the token exchange, thanks. can we do the same for the discovery and keys fetch? they still send the raw body back

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done, same treatment as the token exchange: the discovery and JWKS fetches now log the provider's response and throw a generic message, so the raw body no longer reaches the caller. Added a test asserting the body is not in the thrown message. Fixed in a6b99d9.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

that covers it, thanks. discovery and keys fetch now log the body and return a plain message

@rootnomad
rootnomad force-pushed the feature/generic-oidc-provider branch from 2a72050 to f98eb11 Compare October 1, 2026 17:04
@rootnomad

Copy link
Copy Markdown
Contributor Author

Thanks @Damans227, good catch. I've rebased it onto the latest main now, so the conflicts should be gone. Please let me know if you spot anything else.

@Damans227 Damans227 mentioned this pull request Oct 1, 2026
2 of 14 tasks
@DaanHoogland

Copy link
Copy Markdown
Contributor

@blueorangutan package

@blueorangutan

Copy link
Copy Markdown

@DaanHoogland a [SL] Jenkins job has been kicked to build packages. It will be bundled with no SystemVM templates. I'll keep you posted as I make progress.

@blueorangutan

Copy link
Copy Markdown

Packaging result [SF]: ✖️ el8 ✖️ el9 ✖️ debian ✖️ suse15. SL-JID 19384

@DaanHoogland

Copy link
Copy Markdown
Contributor

@nagaboinaramgopal fyi:

17:11:16 [ERROR] Tests run: 30, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 4.034 s <<< FAILURE! - in org.apache.cloudstack.oauth2.oidc.GenericOIDCOAuth2ProviderTest
17:11:16 [ERROR] testValidTokenYieldsTheEmailClaim(org.apache.cloudstack.oauth2.oidc.GenericOIDCOAuth2ProviderTest)  Time elapsed: 0.009 s  <<< ERROR!
17:11:16 com.cloud.exception.CloudAuthenticationException: The identity provider has not verified the email address in the id_token
17:11:16 	at org.apache.cloudstack.oauth2.oidc.GenericOIDCOAuth2ProviderTest.testValidTokenYieldsTheEmailClaim(GenericOIDCOAuth2ProviderTest.java:333)
17:11:16 
17:11:16 [INFO] Running org.apache.cloudstack.oauth2.keycloak.KeycloakOAuth2ProviderTest
17:11:17 [INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.201 s - in org.apache.cloudstack.oauth2.keycloak.KeycloakOAuth2ProviderTest
17:11:17 [INFO] Running org.apache.cloudstack.oauth2.api.command.DeleteOAuthProviderCmdTest
17:11:17 [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.241 s - in org.apache.cloudstack.oauth2.api.command.DeleteOAuthProviderCmdTest
17:11:17 [INFO] Running org.apache.cloudstack.oauth2.api.command.VerifyOAuthCodeAndGetUserCmdTest
17:11:17 [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.505 s - in org.apache.cloudstack.oauth2.api.command.VerifyOAuthCodeAndGetUserCmdTest
17:11:17 [INFO] Running org.apache.cloudstack.oauth2.api.command.OauthLoginAPIAuthenticatorCmdTest
17:11:17 [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.208 s - in org.apache.cloudstack.oauth2.api.command.OauthLoginAPIAuthenticatorCmdTest
17:11:17 [INFO] Running org.apache.cloudstack.oauth2.api.command.RegisterOAuthProviderCmdTest
17:11:18 [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.199 s - in org.apache.cloudstack.oauth2.api.command.RegisterOAuthProviderCmdTest
17:11:18 [INFO] Running org.apache.cloudstack.oauth2.OAuth2AuthManagerImplTest
17:11:18 [INFO] Tests run: 38, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.673 s - in org.apache.cloudstack.oauth2.OAuth2AuthManagerImplTest
17:11:18 [INFO] Running org.apache.cloudstack.oauth2.OAuth2UserAuthenticatorTest
17:11:19 [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.56 s - in org.apache.cloudstack.oauth2.OAuth2UserAuthenticatorTest
17:11:19 [INFO] Running org.apache.cloudstack.oauth2.google.GoogleOAuth2ProviderTest
17:11:20 [INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.637 s - in org.apache.cloudstack.oauth2.google.GoogleOAuth2ProviderTest
17:11:20 [INFO] 
17:11:20 [INFO] Results:
17:11:20 [INFO] 
17:11:20 [ERROR] Errors: 
17:11:20 [ERROR]   GenericOIDCOAuth2ProviderTest.testValidTokenYieldsTheEmailClaim:333 ? CloudAuthentication

@blueorangutan

Copy link
Copy Markdown

Packaging result [SF]: ✔️ el8 ✔️ el9 ✔️ el10 ✔️ debian ✔️ suse15. SL-JID 19424

@DaanHoogland

Copy link
Copy Markdown
Contributor

@blueorangutan test

@blueorangutan

Copy link
Copy Markdown

@DaanHoogland a [SL] Trillian-Jenkins test job (ol8 mgmt + kvm-ol8) has been kicked to run smoke tests

@blueorangutan

Copy link
Copy Markdown

[SF] Trillian test result (tid-17321)
Environment: kvm-ol8 (x2), zone: Advanced Networking with Mgmt server ol8
Total time taken: 61934 seconds
Marvin logs: https://github.com/blueorangutan/acs-prs/releases/download/trillian/pr14205-t17321-kvm-ol8.zip
Smoke tests completed. 157 look OK, 0 have errors, 0 did not run
Only failed and skipped tests results shown below:

Test Result Time (s) Test File

@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.

@rootnomad
rootnomad force-pushed the feature/generic-oidc-provider branch from 85bffa2 to d1475f1 Compare November 12, 2026 19:46
rootnomad pushed a commit to rootnomad/cloudstack that referenced this pull request Nov 12, 2026
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.
@RosiKyu

RosiKyu commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

@blueorangutan package

@blueorangutan

Copy link
Copy Markdown

@RosiKyu a [SL] Jenkins job has been kicked to build packages. It will be bundled with no SystemVM templates. I'll keep you posted as I make progress.

@blueorangutan

Copy link
Copy Markdown

Packaging result [SF]: ✔️ el8 ✔️ el9 ✔️ el10 ✔️ debian ✔️ suse15. SL-JID 20036

@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.

@RosiKyu

RosiKyu commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

@rootnomad could you please resolve the conflicts? Thank you!

Ramgopal Nagaboina added 5 commits November 20, 2026 18:23
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.
@rootnomad
rootnomad force-pushed the feature/generic-oidc-provider branch from d1475f1 to 4eb70e4 Compare November 20, 2026 23:23
rootnomad pushed a commit to rootnomad/cloudstack that referenced this pull request Nov 20, 2026
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.
@jmsperu

jmsperu commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Tested the PR head (4eb70e4) as a full build of main with a fresh database, against a small test identity provider that I can make misbehave on purpose (discovery document, JWKS with two RS256 keys, token endpoint with client_secret_basic). API level only, through registerOauthProvider, oauthlogin and verifyOAuthCodeAndGetUser. The PR does not apply to 4.22, so this was not run on our 4.22.1.1 lab.

What works:

Check Result
Register with type=oidc and issuerurl OK
type=oidc without issuerurl refused: "Parameter issuerurl is mandatory for an oidc OAuth provider"
Two providers with different names (same issuer) both registered, login works through each
Same name twice refused
Valid id_token, email matches a user logged in
Wrong signature refused: "The id_token signature is not valid"
alg none refused (same message)
Unknown kid refused: "No matching signing key was published by the identity provider"
Wrong audience refused: "Audience mismatch"
Wrong issuer in the token refused: "Issuer mismatch"
No email claim refused
email_verified=false refused, also with oauth2.oidc.require.verified.email=false
email_verified missing refused with the setting on (the message names the setting), accepted with the setting off
Email with no CloudStack user refused
listOauthProvider without a session does not return the secret key

Things I would change:

  1. Several failures give HTTP 200 with an empty body instead of an error. No session is created, so this is not a security problem, but the caller gets nothing to show. Seen for: the identity provider rejecting the code (invalid_grant), a wrong client secret (401 from the token endpoint), an expired id_token ("unknown exception writing api response ... JwtException: The token has expired" in the log), an unreachable issuer or a discovery document naming another issuer, an id_token for another email than the one in the request, and verifyOAuthCodeAndGetUser with a bad signature or a rejected code. These paths throw CloudRuntimeException or JwtException, and oauthlogin only converts CloudAuthenticationException. The GitHub provider throws CloudRuntimeException in the same way, so part of this is older than the PR, but it would be good to return a 531 with a message for all of them here.

  2. registerOauthProvider accepts an issuer that does not answer, and one whose discovery document names a different issuer. The mistake only shows at the first login, and then as the empty reply above. Reading the discovery document at registration (or at least a warning in the response) would help.

  3. The response of registerOauthProvider says "enabled": false for an oidc provider while listOauthProvider says true for the same provider straight after. The register response seems to compare the provider name with oauth2.plugins, which cannot match a free name.

  4. The API name in the code is registerOauthProvider (small "a"); registerOAuthProvider gives "Unknown API command". Worth a line in the documentation.

Not tested: the login page button and redirect in the UI, providers registered for a domain, a real identity provider (Keycloak, Entra, Authentik), ES256 keys, key rotation.

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.
@rootnomad

Copy link
Copy Markdown
Contributor Author

Tested the PR head (4eb70e4) as a full build of main with a fresh database, against a small test identity provider that I can make misbehave on purpose (discovery document, JWKS with two RS256 keys, token endpoint with client_secret_basic).

Thanks, this was a really useful test pass. All four are addressed in the latest push:

  1. The login and verify handlers now return a 531 with a message for the operational failures (rejected code, wrong secret, expired token, unreachable or mismatched issuer, bad signature in verifyOAuthCodeAndGetUser) instead of an empty 200.

  2. The issuer is now checked at registration: the discovery document is fetched and its issuer must match. It is best effort so a brief IdP outage does not block registering, and the same problem still surfaces with a clear error at first login.

  3. register now reports enabled using the same name-or-type check that list and update use, so it agrees with listOauthProvider right after registration.

  4. Added a note on the exact casing to the registerOauthProvider description, since registerOAuthProvider is not a valid command name.

While in there I also tightened a few things your tests pointed at: multi-audience tokens now require azp to match the registered client, only asymmetric id_token signatures are accepted (HS and none are rejected), and the issuer, token and JWKS endpoints must use https (oauth2.oidc.require.https, default true, can be turned off for an http lab IdP).

Mind giving it another look when you get a chance?

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.

Integrate Cloudstack SSO with Generic OpenID Connect on-premise solution

8 participants