diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java index 1004d0316254..e77d6b8d1373 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java @@ -1415,6 +1415,7 @@ public class ApiConstants { public static final String CLIENT_ID = "clientid"; public static final String REDIRECT_URI = "redirecturi"; public static final String TOKEN_URL = "tokenurl"; + public static final String ISSUER_URL = "issuerurl"; public static final String IS_TAG_A_RULE = "istagarule"; diff --git a/api/src/main/java/org/apache/cloudstack/auth/UserOAuth2Authenticator.java b/api/src/main/java/org/apache/cloudstack/auth/UserOAuth2Authenticator.java index cccc1fff9823..184289833727 100644 --- a/api/src/main/java/org/apache/cloudstack/auth/UserOAuth2Authenticator.java +++ b/api/src/main/java/org/apache/cloudstack/auth/UserOAuth2Authenticator.java @@ -56,9 +56,35 @@ public interface UserOAuth2Authenticator extends Adapter { */ String verifySecretCodeAndFetchEmail(String secretCode, Long domainId); + /** + * Verifies the user against the registration identified by providerName. Implementations that + * serve a single registration ignore the name; implementations shared by several registrations + * use it to select the one to authenticate against. + * @return true if it's a valid user, otherwise false + */ + default boolean verifyUser(String email, String secretCode, Long domainId, String providerName) { + return verifyUser(email, secretCode, domainId); + } + + /** + * Verifies the secret code against the registration identified by providerName and fetches email. + * @return email for the specified registration + */ + default String verifySecretCodeAndFetchEmail(String secretCode, Long domainId, String providerName) { + return verifySecretCodeAndFetchEmail(secretCode, domainId); + } + /** * Fetches email using the accessToken * @return returns email */ String getUserEmailAddress() throws CloudRuntimeException; + + /** + * Validate an issuer URL at provider registration so a misconfigured issuer is rejected at register + * time instead of silently failing at the first login. Providers that need no pre-flight validation + * leave this as a no-op. + */ + default void validateIssuer(String issuerUrl) { + } } diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql b/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql index 541caae23c11..3770011f1bcc 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql @@ -271,3 +271,6 @@ CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.disk_offering', 'error_policy', 'VAR -- Rename persisted FlashArray provider name (plugin getName() changed from 'Flash Array' to 'FlashArray') UPDATE `cloud`.`storage_pool` SET `storage_provider_name` = 'FlashArray' WHERE `storage_provider_name` = 'Flash Array'; +-- Generic OIDC OAuth2 provider: a type to select the implementation, and the issuer URL for discovery +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.oauth_provider', 'type', 'VARCHAR(40) DEFAULT NULL COMMENT ''Provider implementation serving this registration, for example oidc; NULL means the provider name selects the implementation'' AFTER `token_url` '); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.oauth_provider', 'issuer_url', 'VARCHAR(255) DEFAULT NULL COMMENT ''Issuer URL of the OpenID Connect provider, used to read its discovery document'' AFTER `type` '); diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManager.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManager.java index 133131d3928a..71c4b35187b3 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManager.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManager.java @@ -41,6 +41,15 @@ public interface OAuth2AuthManager extends PluggableAPIAuthenticator, PluggableS "List of OAuth plugins", true); public static final ConfigKey OAuth2PluginsExclude = new ConfigKey("Advanced", String.class, "oauth2.plugins.exclude", "", "List of OAuth plugins which are excluded", true); + public static final ConfigKey OIDCRequireVerifiedEmail = new ConfigKey("Advanced", Boolean.class, "oauth2.oidc.require.verified.email", "true", + "For the generic OIDC provider, require the id_token to assert a verified email (email_verified=true) before the address is used to identify a CloudStack account. " + + "When set to false for a trusted identity provider that does not send the claim (such as Microsoft Entra ID), an id_token without the claim is accepted, " + + "but one that explicitly marks the email as not verified is always rejected. This can be configured at domain level.", true, ConfigKey.Scope.Domain); + + public static final ConfigKey OIDCRequireHttps = new ConfigKey("Advanced", Boolean.class, "oauth2.oidc.require.https", "true", + "For the generic OIDC provider, require the issuer, token and JWKS endpoints to use https (loopback addresses are always allowed). " + + "Keep this enabled in production so the client secret is never sent in cleartext and a tampered discovery document cannot redirect the " + + "management server to a plain http target. Set to false only for a trusted lab identity provider served over http.", true, ConfigKey.Scope.Global); /** * Lists user OAuth2 provider plugins @@ -55,6 +64,16 @@ public interface OAuth2AuthManager extends PluggableAPIAuthenticator, PluggableS */ UserOAuth2Authenticator getUserOAuth2AuthenticationProvider(final String providerName); + /** + * Finds the user OAuth2 provider serving the named registration within a domain scope. A name + * that matches no provider plugin is resolved through the type of its registration, so that a + * generic provider can serve registrations under administrator chosen names. + * @param providerName name of the registration + * @param domainId domain id, or null for global + * @return OAuth2 provider + */ + UserOAuth2Authenticator getUserOAuth2AuthenticationProvider(final String providerName, final Long domainId); + String verifySecretCodeAndFetchEmail(String code, String provider, Long domainId); OauthProviderVO registerOauthProvider(RegisterOAuthProviderCmd cmd); diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java index 7fc1df009557..a519f097d52f 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.oauth2; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -125,13 +124,30 @@ public List listUserOAuth2AuthenticationProviders() { @Override public UserOAuth2Authenticator getUserOAuth2AuthenticationProvider(String providerName) { + return getUserOAuth2AuthenticationProvider(providerName, null); + } + + @Override + public UserOAuth2Authenticator getUserOAuth2AuthenticationProvider(String providerName, Long domainId) { if (StringUtils.isEmpty(providerName)) { throw new CloudRuntimeException("OAuth2 authentication provider name is empty"); } - if (!userOAuth2AuthenticationProvidersMap.containsKey(providerName.toLowerCase())) { + UserOAuth2Authenticator authenticator = userOAuth2AuthenticationProvidersMap.get(providerName.toLowerCase()); + if (authenticator == null) { + authenticator = findAuthenticatorByRegisteredType(providerName, domainId); + } + if (authenticator == null) { throw new CloudRuntimeException(String.format("Failed to find OAuth2 authentication provider by the name: %s.", providerName)); } - return userOAuth2AuthenticationProvidersMap.get(providerName.toLowerCase()); + return authenticator; + } + + protected UserOAuth2Authenticator findAuthenticatorByRegisteredType(String providerName, Long domainId) { + OauthProviderVO registration = _oauthProviderDao.findByProviderAndDomainWithGlobalFallback(providerName, domainId); + if (registration == null || StringUtils.isBlank(registration.getType())) { + return null; + } + return userOAuth2AuthenticationProvidersMap.get(registration.getType().toLowerCase()); } public List getUserOAuth2AuthenticationProviders() { @@ -152,8 +168,8 @@ protected void initializeUserOAuth2AuthenticationProvidersMap() { @Override public String verifySecretCodeAndFetchEmail(String code, String provider, Long domainId) { - UserOAuth2Authenticator authenticator = getUserOAuth2AuthenticationProvider(provider); - String email = authenticator.verifySecretCodeAndFetchEmail(code, domainId); + UserOAuth2Authenticator authenticator = getUserOAuth2AuthenticationProvider(provider, domainId); + String email = authenticator.verifySecretCodeAndFetchEmail(code, domainId, provider); return email; } @@ -169,11 +185,22 @@ public OauthProviderVO registerOauthProvider(RegisterOAuthProviderCmd cmd) { String authorizeUrl = StringUtils.trim(cmd.getAuthorizeUrl()); String tokenUrl = StringUtils.trim(cmd.getTokenUrl()); Boolean enabled = cmd.getEnabled(); + String type = StringUtils.trim(cmd.getType()); + String issuerUrl = StringUtils.trim(cmd.getIssuerUrl()); if (!isOAuthPluginEnabled(domainId)) { throw new CloudRuntimeException("OAuth is not enabled, please enable to register"); } + if (StringUtils.isNotBlank(type) && !userOAuth2AuthenticationProvidersMap.containsKey(type.toLowerCase())) { + throw new CloudRuntimeException(String.format("No OAuth2 provider plugin is available for the type %s", type)); + } + + if (StringUtils.isNotBlank(type) && userOAuth2AuthenticationProvidersMap.containsKey(provider.toLowerCase())) { + throw new CloudRuntimeException(String.format( + "The name %s is reserved by a built-in OAuth2 provider, so the type would be ignored; use a different name for an OIDC registration", provider)); + } + // Check for existing provider with same name and domain OauthProviderVO providerVO = _oauthProviderDao.findByProviderAndDomain(provider, domainId); if (providerVO != null) { @@ -184,18 +211,18 @@ public OauthProviderVO registerOauthProvider(RegisterOAuthProviderCmd cmd) { } } - return saveOauthProvider(provider, description, clientId, secretKey, redirectUri, authorizeUrl, tokenUrl, domainId, enabled); + return saveOauthProvider(provider, description, clientId, secretKey, redirectUri, authorizeUrl, tokenUrl, domainId, type, issuerUrl, enabled); } @Override public List listOauthProviders(String provider, String uuid, Long domainId) { List providers; if (uuid != null) { - providers = Collections.singletonList(_oauthProviderDao.findByUuid(uuid)); + providers = singleOrEmpty(_oauthProviderDao.findByUuid(uuid)); } else if (StringUtils.isNotBlank(provider) && domainId != null) { - providers = Collections.singletonList(_oauthProviderDao.findByProviderAndDomain(provider, domainId)); + providers = singleOrEmpty(_oauthProviderDao.findByProviderAndDomain(provider, domainId)); } else if (StringUtils.isNotBlank(provider)) { - providers = Collections.singletonList(_oauthProviderDao.findByProviderAndDomain(provider, null)); + providers = singleOrEmpty(_oauthProviderDao.findByProviderAndDomain(provider, null)); } else if (domainId != null) { providers = _oauthProviderDao.listByDomainIncludingGlobal(domainId); } else { @@ -204,6 +231,14 @@ public List listOauthProviders(String provider, String uuid, Lo return providers; } + private List singleOrEmpty(OauthProviderVO provider) { + List providers = new ArrayList<>(); + if (provider != null) { + providers.add(provider); + } + return providers; + } + @Override public OauthProviderVO updateOauthProvider(UpdateOAuthProviderCmd cmd) { Long id = cmd.getId(); @@ -213,6 +248,7 @@ public OauthProviderVO updateOauthProvider(UpdateOAuthProviderCmd cmd) { String secretKey = StringUtils.trim(cmd.getSecretKey()); String authorizeUrl = StringUtils.trim(cmd.getAuthorizeUrl()); String tokenUrl = StringUtils.trim(cmd.getTokenUrl()); + String issuerUrl = StringUtils.trim(cmd.getIssuerUrl()); Boolean enabled = cmd.getEnabled(); OauthProviderVO providerVO = _oauthProviderDao.findById(id); @@ -262,6 +298,9 @@ public OauthProviderVO updateOauthProvider(UpdateOAuthProviderCmd cmd) { if (StringUtils.isNotEmpty(tokenUrl)) { providerVO.setTokenUrl(tokenUrl); } + if (StringUtils.isNotEmpty(issuerUrl)) { + providerVO.setIssuerUrl(issuerUrl); + } if (enabled != null) { providerVO.setEnabled(enabled); } @@ -272,7 +311,8 @@ public OauthProviderVO updateOauthProvider(UpdateOAuthProviderCmd cmd) { return _oauthProviderDao.findById(id); } - private OauthProviderVO saveOauthProvider(String provider, String description, String clientId, String secretKey, String redirectUri, String authorizeUrl, String tokenUrl, Long domainId, Boolean enabled) { + private OauthProviderVO saveOauthProvider(String provider, String description, String clientId, String secretKey, String redirectUri, String authorizeUrl, + String tokenUrl, Long domainId, String type, String issuerUrl, Boolean enabled) { final OauthProviderVO oauthProviderVO = new OauthProviderVO(); oauthProviderVO.setProvider(provider); @@ -283,6 +323,8 @@ private OauthProviderVO saveOauthProvider(String provider, String description, S oauthProviderVO.setDomainId(domainId); oauthProviderVO.setAuthorizeUrl(authorizeUrl); oauthProviderVO.setTokenUrl(tokenUrl); + oauthProviderVO.setType(StringUtils.lowerCase(type)); + oauthProviderVO.setIssuerUrl(issuerUrl); // If enabled is null, default to true (enabled), NPE safeguard for Boolean unboxing oauthProviderVO.setEnabled(enabled == null || enabled); @@ -362,6 +404,7 @@ public String getConfigComponentName() { @Override public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {OAuth2IsPluginEnabled, OAuth2Plugins, OAuth2PluginsExclude}; + return new ConfigKey[] {OAuth2IsPluginEnabled, OAuth2Plugins, OAuth2PluginsExclude, OIDCRequireVerifiedEmail, + OIDCRequireHttps}; } } diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java index 49df94709836..395e668dfc87 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java @@ -74,8 +74,8 @@ public Pair authenticate(String username, String email = ((emailArray == null) ? null : emailArray[0]); String secretCode = ((secretCodeArray == null) ? null : secretCodeArray[0]); - UserOAuth2Authenticator authenticator = userOAuth2mgr.getUserOAuth2AuthenticationProvider(oauthProvider); - if (Objects.nonNull(user) && authenticator.verifyUser(email, secretCode, domainId)) { + UserOAuth2Authenticator authenticator = userOAuth2mgr.getUserOAuth2AuthenticationProvider(oauthProvider, domainId); + if (Objects.nonNull(user) && authenticator.verifyUser(email, secretCode, domainId, oauthProvider)) { return new Pair(true, null); } } diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java index 9c72e47e5595..771f2543dd6c 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java @@ -46,6 +46,7 @@ import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiServer; @@ -55,7 +56,7 @@ import com.cloud.utils.HttpUtils; @APICommand(name = "listOauthProvider", description = "List OAuth providers registered", responseObject = OauthProviderResponse.class, entityType = {}, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, + requestHasSensitiveInfo = false, responseHasSensitiveInfo = true, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}, since = "4.19.0") public class ListOAuthProvidersCmd extends BaseListCmd implements APIAuthenticator { @@ -184,8 +185,10 @@ public String authenticate(String command, Map params, HttpSes OauthProviderResponse r = new OauthProviderResponse(result.getUuid(), result.getProvider(), result.getDescription(), result.getClientId(), secretKeyAllowed ? result.getSecretKey() : null, result.getRedirectUri(), result.getAuthorizeUrl(), result.getTokenUrl(), domain); + r.setType(result.getType()); + r.setIssuerUrl(result.getIssuerUrl()); boolean oauthEnabled = OAuth2AuthManager.isPluginEnabledForDomain(result.getDomainId()); - if (oauthEnabled && authenticatorPluginNames.contains(result.getProvider()) && result.isEnabled()) { + if (oauthEnabled && isServedByPlugin(result, authenticatorPluginNames) && result.isEnabled()) { r.setEnabled(true); } else { r.setEnabled(false); @@ -200,7 +203,7 @@ public String authenticate(String command, Map params, HttpSes for (OauthProviderVO domainProvider : allProviders) { if (domainProvider.getDomainId() != null && domainProvider.isEnabled() && OAuth2AuthManager.isPluginEnabledForDomain(domainProvider.getDomainId()) - && authenticatorPluginNames.contains(domainProvider.getProvider())) { + && isServedByPlugin(domainProvider, authenticatorPluginNames)) { totalEnabledCount++; } } @@ -214,6 +217,11 @@ public String authenticate(String command, Map params, HttpSes return ApiResponseSerializer.toSerializedString(response, responseType); } + protected boolean isServedByPlugin(OauthProviderVO provider, List authenticatorPluginNames) { + return authenticatorPluginNames.contains(provider.getProvider()) + || (StringUtils.isNotBlank(provider.getType()) && authenticatorPluginNames.contains(provider.getType())); + } + @Override public APIAuthenticationType getAPIType() { return null; diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java index e9ef030aaab5..aac2a64bb5bc 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java @@ -154,13 +154,16 @@ public String authenticate(String command, Map params, HttpSes return doOauthAuthentication(session, domainId, domain, email, params, remoteAddress, responseType, auditTrailSb); } catch (final CloudAuthenticationException ex) { - throw toServerApiException(session, params, responseType, auditTrailSb, ex); + throw toServerApiException(session, params, responseType, auditTrailSb, ex.getMessage()); + } catch (final RuntimeException ex) { + logger.warn("OAuth login failed", ex); + throw toServerApiException(session, params, responseType, auditTrailSb, ex.getMessage()); } } - private ServerApiException toServerApiException(HttpSession session, Map params, String responseType, StringBuilder auditTrailSb, CloudAuthenticationException ex) { + private ServerApiException toServerApiException(HttpSession session, Map params, String responseType, StringBuilder auditTrailSb, String message) { ApiServlet.invalidateHttpSession(session, "fall through to API key,"); - String msg = ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user via OAuth"; + String msg = message != null ? message : "failed to authenticate user via OAuth"; auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + msg); String serializedResponse = _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), msg, params, responseType); return new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, serializedResponse); diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmd.java index 12d3bc641c5e..f41feca10ab6 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmd.java @@ -35,6 +35,7 @@ import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; import org.apache.cloudstack.oauth2.keycloak.KeycloakOAuth2Provider; +import org.apache.cloudstack.oauth2.oidc.GenericOIDCOAuth2Provider; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -42,8 +43,11 @@ import com.cloud.api.ApiDBUtils; import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; +import com.cloud.utils.exception.CloudRuntimeException; -@APICommand(name = "registerOauthProvider", responseObject = SuccessResponse.class, description = "Register the OAuth2 provider in CloudStack", since = "4.19.0") +@APICommand(name = "registerOauthProvider", responseObject = SuccessResponse.class, + description = "Register the OAuth2 provider in CloudStack. The API name is registerOauthProvider " + + "(lower case a in Oauth), not registerOAuthProvider.", since = "4.19.0") public class RegisterOAuthProviderCmd extends BaseCmd { ///////////////////////////////////////////////////// @@ -82,6 +86,16 @@ public class RegisterOAuthProviderCmd extends BaseCmd { @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, description = "OAuth provider will be enabled or disabled based on this value, defaults to true if not specified", since = "24.0.0") private Boolean enabled; + @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, + description = "Type of the provider implementation serving this registration, for example oidc for any OpenID Connect compliant provider. " + + "When set, the name in provider is a label chosen by the administrator rather than a built in provider name.", since = "24.0.0") + private String type; + + @Parameter(name = ApiConstants.ISSUER_URL, type = CommandType.STRING, + description = "Issuer URL of the OpenID Connect provider, required for type oidc. The token endpoint and the keys that sign " + + "its tokens are read from the issuer's discovery document", since = "24.0.0") + private String issuerUrl; + @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "Any OAuth provider details in key/value pairs using format details[i].keyname=keyvalue. Example: details[0].clientsecret=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") protected Map details; @@ -134,6 +148,14 @@ public Boolean getEnabled() { return enabled; } + public String getType() { + return type; + } + + public String getIssuerUrl() { + return issuerUrl; + } + public Map getDetails() { if (MapUtils.isEmpty(details)) { return null; @@ -156,12 +178,21 @@ public void execute() throws ServerApiException, ConcurrentOperationException, E } } + if (StringUtils.equalsIgnoreCase(GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE, getType())) { + if (StringUtils.isBlank(getIssuerUrl())) { + throw new ServerApiException(ApiErrorCode.BAD_REQUEST, "Parameter issuerurl is mandatory for an oidc OAuth provider"); + } + validateOidcIssuer(); + } + OauthProviderVO provider = _oauth2mgr.registerOauthProvider(this); Domain domain = provider.getDomainId() != null ? ApiDBUtils.findDomainById(provider.getDomainId()) : null; OauthProviderResponse response = new OauthProviderResponse(provider.getUuid(), provider.getProvider(), provider.getDescription(), provider.getClientId(), provider.getSecretKey(), provider.getRedirectUri(), provider.getAuthorizeUrl(), provider.getTokenUrl(), domain); + response.setType(provider.getType()); + response.setIssuerUrl(provider.getIssuerUrl()); response.setResponseName(getCommandName()); response.setObjectName(ApiConstants.OAUTH_PROVIDER); @@ -174,7 +205,9 @@ public void execute() throws ServerApiException, ConcurrentOperationException, E } boolean oauthEnabled = OAuth2AuthManager.isPluginEnabledForDomain(provider.getDomainId()); - if (oauthEnabled && authenticatorPluginNames.contains(provider.getProvider()) && provider.isEnabled()) { + boolean servedByPlugin = authenticatorPluginNames.contains(provider.getProvider()) + || (StringUtils.isNotBlank(provider.getType()) && authenticatorPluginNames.contains(provider.getType())); + if (oauthEnabled && servedByPlugin && provider.isEnabled()) { response.setEnabled(true); } else { response.setEnabled(false); @@ -182,4 +215,19 @@ public void execute() throws ServerApiException, ConcurrentOperationException, E setResponseObject(response); } + + private void validateOidcIssuer() { + for (UserOAuth2Authenticator authenticator : _oauth2mgr.listUserOAuth2AuthenticationProviders()) { + if (GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE.equals(authenticator.getName())) { + try { + authenticator.validateIssuer(getIssuerUrl()); + } catch (CloudRuntimeException ex) { + // Best effort: do not block registration if the issuer is briefly unreachable. The same + // problem surfaces with a clear error at the first login. + logger.warn("The OIDC issuer {} could not be validated at registration: {}", getIssuerUrl(), ex.getMessage()); + } + return; + } + } + } } diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java index f6e60caaade7..3096483bd4e0 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java @@ -34,12 +34,13 @@ import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; +import org.apache.commons.lang3.StringUtils; import com.cloud.api.ApiDBUtils; import com.cloud.domain.Domain; @APICommand(name = "updateOauthProvider", description = "Updates the registered OAuth provider details", responseObject = OauthProviderResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0") + requestHasSensitiveInfo = true, responseHasSensitiveInfo = true, since = "4.19.0") public final class UpdateOAuthProviderCmd extends BaseCmd { @@ -67,6 +68,10 @@ public final class UpdateOAuthProviderCmd extends BaseCmd { @Parameter(name = ApiConstants.TOKEN_URL, type = CommandType.STRING, description = "Token URL pre-registered in the specific OAuth provider", since = "4.23.0") private String tokenUrl; + @Parameter(name = ApiConstants.ISSUER_URL, type = CommandType.STRING, + description = "Issuer URL of the OpenID Connect provider, used to read its discovery document", since = "24.0.0") + private String issuerUrl; + @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, description = "OAuth provider will be enabled or disabled based on this value") private Boolean enabled; @@ -113,6 +118,10 @@ public String getTokenUrl() { return tokenUrl; } + public String getIssuerUrl() { + return issuerUrl; + } + public Boolean getEnabled() { return enabled; } @@ -152,6 +161,8 @@ public void execute() { OauthProviderResponse r = new OauthProviderResponse(result.getUuid(), result.getProvider(), result.getDescription(), result.getClientId(), result.getSecretKey(), result.getRedirectUri(), result.getAuthorizeUrl(), result.getTokenUrl(), domain); + r.setType(result.getType()); + r.setIssuerUrl(result.getIssuerUrl()); List userOAuth2AuthenticatorPlugins = _oauthMgr.listUserOAuth2AuthenticationProviders(); List authenticatorPluginNames = new ArrayList<>(); @@ -159,8 +170,10 @@ public void execute() { String name = authenticator.getName(); authenticatorPluginNames.add(name); } + boolean servedByPlugin = authenticatorPluginNames.contains(result.getProvider()) + || (StringUtils.isNotBlank(result.getType()) && authenticatorPluginNames.contains(result.getType())); boolean oauthEnabled = OAuth2AuthManager.isPluginEnabledForDomain(result.getDomainId()); - if (oauthEnabled && authenticatorPluginNames.contains(result.getProvider()) && result.isEnabled()) { + if (oauthEnabled && servedByPlugin && result.isEnabled()) { r.setEnabled(true); } else { r.setEnabled(false); diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java index d5c7455d0f33..8156ff579cfa 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java @@ -112,7 +112,14 @@ public String authenticate(String command, Map params, HttpSes } domainId = _oauth2mgr.resolveDomainId(params); - String email = _oauth2mgr.verifySecretCodeAndFetchEmail(secretCode, provider, domainId); + String email; + try { + email = _oauth2mgr.verifySecretCodeAndFetchEmail(secretCode, provider, domainId); + } catch (RuntimeException ex) { + logger.warn("Failed to verify the OAuth code with provider {}", provider, ex); + throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, + ex.getMessage() != null ? ex.getMessage() : "Unable to verify the code provided"); + } if (email != null) { UserResponse response = new UserResponse(); response.setEmail(email); diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/response/OauthProviderResponse.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/response/OauthProviderResponse.java index b363e13516bc..f58ac6ec2c61 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/response/OauthProviderResponse.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/response/OauthProviderResponse.java @@ -70,6 +70,14 @@ public class OauthProviderResponse extends BaseResponse { @Param(description = "path of the domain the provider belongs to (empty for global)", since = "4.23.0") private String domainPath; + @SerializedName(ApiConstants.TYPE) + @Param(description = "Type of the provider, for example oidc for a generic OpenID Connect provider. Empty for the built in providers", since = "24.0.0") + private String type; + + @SerializedName(ApiConstants.ISSUER_URL) + @Param(description = "Issuer URL of the OpenID Connect provider, used for discovery", since = "24.0.0") + private String issuerUrl; + @SerializedName(ApiConstants.AUTHORIZE_URL) @Param(description = "Authorize URL registered in the OAuth provider") private String authorizeUrl; @@ -180,6 +188,22 @@ public void setDomainPath(String domainPath) { this.domainPath = domainPath; } + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getIssuerUrl() { + return issuerUrl; + } + + public void setIssuerUrl(String issuerUrl) { + this.issuerUrl = issuerUrl; + } + public String getAuthorizeUrl() { return authorizeUrl; } diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2Provider.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2Provider.java new file mode 100644 index 000000000000..a29950a2983d --- /dev/null +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2Provider.java @@ -0,0 +1,552 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package org.apache.cloudstack.oauth2.oidc; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; +import javax.ws.rs.core.HttpHeaders; + +import org.apache.cloudstack.auth.UserOAuth2Authenticator; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.oauth2.OAuth2AuthManager; +import org.apache.cloudstack.oauth2.dao.OauthProviderDao; +import org.apache.cloudstack.oauth2.vo.OauthProviderVO; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; +import org.apache.cxf.rs.security.jose.jwk.JsonWebKey; +import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys; +import org.apache.cxf.rs.security.jose.jwk.JwkUtils; +import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer; +import org.apache.cxf.rs.security.jose.jwt.JwtClaims; +import org.apache.cxf.rs.security.jose.jwt.JwtUtils; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.cloud.exception.CloudAuthenticationException; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.exception.CloudRuntimeException; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +/** + * A single provider implementation for any OIDC compliant identity provider. Unlike the per vendor + * providers it is not bound to one registration: the registration is selected by name on every call, + * so one bean serves any number of registrations of type "oidc". + */ +public class GenericOIDCOAuth2Provider extends AdapterBase implements UserOAuth2Authenticator { + + public static final String OIDC_PROVIDER_TYPE = "oidc"; + + private static final String DISCOVERY_PATH = "/.well-known/openid-configuration"; + private static final int CLOCK_SKEW_SECONDS = 60; + private static final long METADATA_CACHE_MINUTES = 60; + private static final long VERIFIED_EMAIL_CACHE_SECONDS = 300; + private static final int HTTP_TIMEOUT_MILLIS = 10000; + private static final int MAX_RESPONSE_BYTES = 1024 * 1024; + + @Inject + OauthProviderDao oauthProviderDao; + + private CloseableHttpClient httpClient; + + private final Cache metadataCache = + Caffeine.newBuilder() + .expireAfterWrite(METADATA_CACHE_MINUTES, TimeUnit.MINUTES) + .maximumSize(64) + .build(); + + private final Cache verifiedEmailCache = + Caffeine.newBuilder() + .expireAfterWrite(VERIFIED_EMAIL_CACHE_SECONDS, TimeUnit.SECONDS) + .maximumSize(1024) + .build(); + + private final Cache jwksCache = + Caffeine.newBuilder() + .expireAfterWrite(METADATA_CACHE_MINUTES, TimeUnit.MINUTES) + .maximumSize(64) + .build(); + + protected Logger logger = LogManager.getLogger(getClass()); + + public GenericOIDCOAuth2Provider() { + this(HttpClientBuilder.create() + .setDefaultRequestConfig(RequestConfig.custom() + .setConnectTimeout(HTTP_TIMEOUT_MILLIS) + .setConnectionRequestTimeout(HTTP_TIMEOUT_MILLIS) + .setSocketTimeout(HTTP_TIMEOUT_MILLIS) + .build()) + .build()); + } + + public GenericOIDCOAuth2Provider(CloseableHttpClient httpClient) { + this.httpClient = httpClient; + } + + @Override + public String getName() { + return OIDC_PROVIDER_TYPE; + } + + @Override + public String getDescription() { + return "Generic OpenID Connect Provider Plugin"; + } + + @Override + public boolean verifyUser(String email, String secretCode) { + throw new CloudRuntimeException("The generic OIDC provider requires the registered provider name"); + } + + @Override + public boolean verifyUser(String email, String secretCode, Long domainId) { + throw new CloudRuntimeException("The generic OIDC provider requires the registered provider name"); + } + + @Override + public String verifySecretCodeAndFetchEmail(String secretCode) { + throw new CloudRuntimeException("The generic OIDC provider requires the registered provider name"); + } + + @Override + public String verifySecretCodeAndFetchEmail(String secretCode, Long domainId) { + throw new CloudRuntimeException("The generic OIDC provider requires the registered provider name"); + } + + @Override + public boolean verifyUser(String email, String secretCode, Long domainId, String providerName) { + if (StringUtils.isAnyEmpty(email, secretCode)) { + throw new CloudAuthenticationException("Either email or secret code should not be null/empty"); + } + + OauthProviderVO registration = findRegistration(providerName, domainId); + String verifiedEmail = verifiedEmailCache.asMap().remove(verifiedEmailKey(registration, secretCode)); + if (verifiedEmail == null) { + verifiedEmail = resolveEmail(registration, secretCode); + } + if (StringUtils.isBlank(verifiedEmail) || !email.equals(verifiedEmail)) { + throw new CloudRuntimeException("Unable to verify the email address with the provided secret"); + } + + return true; + } + + @Override + public String verifySecretCodeAndFetchEmail(String secretCode, Long domainId, String providerName) { + OauthProviderVO registration = findRegistration(providerName, domainId); + String email = resolveEmail(registration, secretCode); + verifiedEmailCache.put(verifiedEmailKey(registration, secretCode), email); + return email; + } + + protected String resolveEmail(OauthProviderVO registration, String secretCode) { + OIDCMetadata metadata = getMetadata(registration); + String idToken = exchangeAuthorizationCode(secretCode, registration, metadata); + + return validateAndExtractEmail(idToken, registration, metadata); + } + + /** + * Validate an issuer URL at provider registration: confirm it uses https (or loopback), that its + * discovery document is reachable, and that the document names the same issuer, so a bad issuer fails + * at registration instead of silently at the first login. + */ + public void validateIssuer(String issuerUrl) { + if (StringUtils.isBlank(issuerUrl)) { + throw new CloudRuntimeException("An issuer URL is required for an oidc provider"); + } + discover(StringUtils.trim(issuerUrl)); + } + + @Override + public String getUserEmailAddress() throws CloudRuntimeException { + return null; + } + + private String verifiedEmailKey(OauthProviderVO registration, String secretCode) { + return DigestUtils.sha256Hex(registration.getUuid() + ":" + secretCode); + } + + protected OauthProviderVO findRegistration(String providerName, Long domainId) { + if (StringUtils.isBlank(providerName)) { + throw new CloudAuthenticationException("The registered provider name is required"); + } + OauthProviderVO provider = oauthProviderDao.findByProviderAndDomainWithGlobalFallback(providerName, domainId); + if (provider == null) { + throw new CloudAuthenticationException(String.format("%s provider is not registered, so user cannot be verified", providerName)); + } + return provider; + } + + protected OIDCMetadata getMetadata(OauthProviderVO provider) { + String issuerUrl = StringUtils.trimToNull(provider.getIssuerUrl()); + if (issuerUrl == null) { + throw new CloudRuntimeException(String.format( + "Provider %s has no issuer URL, so its endpoints and signing keys cannot be discovered", provider.getProvider())); + } + return metadataCache.get(issuerUrl, this::discover); + } + + protected OIDCMetadata discover(String issuerUrl) { + requireHttps(issuerUrl, "issuer URL"); + String document = httpGet(StringUtils.removeEnd(issuerUrl, "/") + DISCOVERY_PATH, + String.format("Unable to read the OpenID Connect discovery document from %s", issuerUrl)); + + JsonObject json = asJsonObject(document, + String.format("The discovery document at %s is not a JSON object", issuerUrl)); + String issuer = readString(json, "issuer"); + String tokenEndpoint = readString(json, "token_endpoint"); + String jwksUri = readString(json, "jwks_uri"); + if (StringUtils.isAnyBlank(issuer, tokenEndpoint, jwksUri)) { + throw new CloudRuntimeException(String.format( + "The discovery document at %s is missing the issuer, the token endpoint or the JWKS URI", issuerUrl)); + } + if (!StringUtils.removeEnd(issuer, "/").equals(StringUtils.removeEnd(issuerUrl, "/"))) { + throw new CloudRuntimeException(String.format("The discovery document at %s names a different issuer: %s", issuerUrl, issuer)); + } + requireHttps(tokenEndpoint, "token endpoint"); + requireHttps(jwksUri, "JWKS URI"); + + return new OIDCMetadata(issuer, readString(json, "authorization_endpoint"), tokenEndpoint, jwksUri); + } + + protected String exchangeAuthorizationCode(String secretCode, OauthProviderVO provider, OIDCMetadata metadata) { + String auth = provider.getClientId() + ":" + provider.getSecretKey(); + String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)); + + List params = new ArrayList<>(); + params.add(new BasicNameValuePair("grant_type", "authorization_code")); + params.add(new BasicNameValuePair("code", secretCode)); + params.add(new BasicNameValuePair("redirect_uri", provider.getRedirectUri())); + + HttpPost post = new HttpPost(metadata.getTokenEndpoint()); + post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth); + try { + post.setEntity(new UrlEncodedFormEntity(params)); + } catch (UnsupportedEncodingException e) { + throw new CloudRuntimeException("Unable to generate URL parameters: " + e.getMessage()); + } + + try (CloseableHttpResponse response = httpClient.execute(post)) { + String body = readBody(response); + if (response.getStatusLine().getStatusCode() != 200) { + logger.warn("{} rejected the token exchange with HTTP {}", provider.getProvider(), + response.getStatusLine().getStatusCode()); + throw new CloudRuntimeException(String.format("The %s identity provider rejected the token exchange", provider.getProvider())); + } + + JsonObject json = asJsonObject(body, "The token endpoint response is not a JSON object"); + JsonElement fetchedIdToken = json.get("id_token"); + if (fetchedIdToken == null || !fetchedIdToken.isJsonPrimitive()) { + throw new CloudRuntimeException("No id_token found in the token endpoint response"); + } + return fetchedIdToken.getAsString(); + } catch (IOException e) { + throw new CloudRuntimeException(String.format("Unable to connect to the %s token endpoint", provider.getProvider()), e); + } + } + + protected String validateAndExtractEmail(String idToken, OauthProviderVO provider, OIDCMetadata metadata) { + JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(idToken); + + verifySignature(consumer, metadata, provider); + + JwtClaims claims = consumer.getJwtClaims(); + if (!metadata.getIssuer().equals(claims.getIssuer())) { + throw new CloudAuthenticationException("Issuer mismatch"); + } + validateAudience(claims, provider.getClientId()); + validateTokenTime(claims); + + Object emailClaim = claims.getClaim("email"); + String email = emailClaim instanceof String ? (String) emailClaim : null; + if (StringUtils.isBlank(email)) { + throw new CloudAuthenticationException("The id_token carries no email claim"); + } + Boolean emailVerified = emailVerifiedClaim(claims); + if (Boolean.FALSE.equals(emailVerified)) { + throw new CloudAuthenticationException("The identity provider has marked the email address in the id_token as not verified"); + } + if (emailVerified == null && isVerifiedEmailRequired(provider)) { + throw new CloudAuthenticationException(String.format( + "The identity provider did not assert that the email address is verified; set %s to false for this domain to accept it", + OAuth2AuthManager.OIDCRequireVerifiedEmail.key())); + } + return email; + } + + /** + * Validate the audience per OIDC core 3.1.3.7: the registered client must be an audience, and when the + * token lists more than one audience the authorized party (azp) must be present and must be this client. + * If azp is present at all it must match, so a token minted for another relying party on the same issuer + * cannot be replayed here. + */ + private void validateAudience(JwtClaims claims, String clientId) { + List audiences = claims.getAudiences(); + if (audiences == null || !audiences.contains(clientId)) { + throw new CloudAuthenticationException("Audience mismatch"); + } + Object azp = claims.getClaim("azp"); + if (audiences.size() > 1 && azp == null) { + throw new CloudAuthenticationException("The id_token has multiple audiences but no authorized party (azp)"); + } + if (azp != null && !clientId.equals(azp)) { + throw new CloudAuthenticationException("The authorized party (azp) does not match the registered client"); + } + } + + private void validateTokenTime(JwtClaims claims) { + try { + JwtUtils.validateJwtExpiry(claims, CLOCK_SKEW_SECONDS, true); + } catch (CloudAuthenticationException e) { + throw e; + } catch (RuntimeException e) { + throw new CloudAuthenticationException("The id_token has expired or carries no expiry"); + } + Long notBefore = claims.getNotBefore(); + if (notBefore != null && notBefore > (System.currentTimeMillis() / 1000L) + CLOCK_SKEW_SECONDS) { + throw new CloudAuthenticationException("The id_token is not valid yet"); + } + } + + private Boolean emailVerifiedClaim(JwtClaims claims) { + Object verified = claims.getClaim("email_verified"); + if (verified instanceof Boolean) { + return (Boolean) verified; + } + if (verified instanceof String) { + String value = ((String) verified).trim(); + if ("true".equalsIgnoreCase(value)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(value)) { + return Boolean.FALSE; + } + } + return null; + } + + protected boolean isVerifiedEmailRequired(OauthProviderVO provider) { + return Boolean.TRUE.equals( + OAuth2AuthManager.OIDCRequireVerifiedEmail.valueInScope(ConfigKey.Scope.Domain, provider.getDomainId(), false)); + } + + protected void verifySignature(JwsJwtCompactConsumer consumer, OIDCMetadata metadata, OauthProviderVO provider) { + if (StringUtils.isBlank(metadata.getJwksUri())) { + throw new CloudAuthenticationException(String.format( + "Provider %s has no JWKS endpoint, so the id_token signature cannot be verified", provider.getProvider())); + } + + String jwksUri = metadata.getJwksUri(); + String keyId = consumer.getJwsHeaders().getKeyId(); + + JsonWebKeys keys = jwksCache.get(jwksUri, this::readJwkSet); + JsonWebKey key = selectKey(keys, keyId); + if (key == null && StringUtils.isNotBlank(keyId)) { + keys = readJwkSet(jwksUri); + jwksCache.put(jwksUri, keys); + key = selectKey(keys, keyId); + } + if (key == null) { + throw new CloudAuthenticationException("No matching signing key was published by the identity provider"); + } + if (!consumer.verifySignatureWith(key, resolveAlgorithm(consumer, key))) { + throw new CloudAuthenticationException("The id_token signature is not valid"); + } + } + + private JsonWebKey selectKey(JsonWebKeys keys, String keyId) { + return StringUtils.isNotBlank(keyId) ? keys.getKey(keyId) : singleKey(keys); + } + + private SignatureAlgorithm resolveAlgorithm(JwsJwtCompactConsumer consumer, JsonWebKey key) { + SignatureAlgorithm algorithm = key.getAlgorithm() != null + ? SignatureAlgorithm.getAlgorithm(key.getAlgorithm()) + : consumer.getJwsHeaders().getSignatureAlgorithm(); + if (algorithm == null) { + throw new CloudAuthenticationException("The id_token does not name a signature algorithm"); + } + if (!isAsymmetricSignature(algorithm)) { + throw new CloudAuthenticationException("Unsupported id_token signature algorithm: " + algorithm.getJwaName()); + } + return algorithm; + } + + /** + * Only asymmetric signatures (RSA, RSA-PSS, ECDSA) are accepted for an id_token verified against a + * published JWKS. Rejecting HMAC (HS*) and "none" closes the RS256 to HS256 key-confusion attack where + * a token is HMAC-signed with the public key as the secret. + */ + private boolean isAsymmetricSignature(SignatureAlgorithm algorithm) { + String name = algorithm.getJwaName(); + return name != null && (name.startsWith("RS") || name.startsWith("PS") || name.startsWith("ES")); + } + + protected JsonWebKeys readJwkSet(String jwksUri) { + return JwkUtils.readJwkSet(httpGet(jwksUri, String.format("Unable to read the signing keys from %s", jwksUri))); + } + + private JsonWebKey singleKey(JsonWebKeys keys) { + List published = keys.getKeys(); + return published != null && published.size() == 1 ? published.get(0) : null; + } + + protected String httpGet(String url, String failureMessage) { + try (CloseableHttpResponse response = httpClient.execute(new HttpGet(url))) { + String body = readBody(response); + if (response.getStatusLine().getStatusCode() != 200) { + logger.warn("{} (HTTP {})", failureMessage, response.getStatusLine().getStatusCode()); + throw new CloudRuntimeException(failureMessage); + } + return body; + } catch (IOException e) { + throw new CloudRuntimeException(failureMessage, e); + } + } + + /** + * Read a response body with a hard size cap so a hostile or misbehaving identity provider cannot + * exhaust management-server memory by streaming an unbounded body. + */ + private String readBody(CloseableHttpResponse response) throws IOException { + HttpEntity entity = response.getEntity(); + if (entity == null) { + return ""; + } + if (entity.getContentLength() > MAX_RESPONSE_BYTES) { + throw new CloudRuntimeException("The identity provider response is too large"); + } + byte[] buffer = new byte[MAX_RESPONSE_BYTES + 1]; + int total = 0; + try (InputStream in = entity.getContent()) { + int read; + while (total <= MAX_RESPONSE_BYTES && (read = in.read(buffer, total, buffer.length - total)) != -1) { + total += read; + } + } + if (total > MAX_RESPONSE_BYTES) { + throw new CloudRuntimeException("The identity provider response is too large"); + } + return new String(buffer, 0, total, StandardCharsets.UTF_8); + } + + private JsonObject asJsonObject(String body, String failureMessage) { + try { + JsonElement element = JsonParser.parseString(body); + if (!element.isJsonObject()) { + throw new CloudRuntimeException(failureMessage); + } + return element.getAsJsonObject(); + } catch (CloudRuntimeException e) { + throw e; + } catch (RuntimeException e) { + throw new CloudRuntimeException(failureMessage); + } + } + + /** + * Require that an OIDC endpoint uses https, so the client secret is never POSTed in cleartext and a + * tampered discovery document cannot redirect the management server to an internal http target. Loopback + * is allowed for development. + */ + private void requireHttps(String url, String what) { + if (StringUtils.isBlank(url) || url.toLowerCase().startsWith("https://") || !isHttpsRequired()) { + return; + } + if (url.toLowerCase().startsWith("http://")) { + String host; + try { + host = URI.create(url).getHost(); + } catch (IllegalArgumentException e) { + throw new CloudRuntimeException(String.format("The %s is not a valid URL: %s", what, url)); + } + if ("localhost".equalsIgnoreCase(host) || "127.0.0.1".equals(host) || "::1".equals(host) || "[::1]".equals(host)) { + return; + } + } + throw new CloudRuntimeException(String.format("The %s must use https: %s (set %s to false to allow http)", + what, url, OAuth2AuthManager.OIDCRequireHttps.key())); + } + + protected boolean isHttpsRequired() { + return Boolean.TRUE.equals(OAuth2AuthManager.OIDCRequireHttps.value()); + } + + private String readString(JsonObject json, String member) { + JsonElement element = json.get(member); + return element == null || element.isJsonNull() ? null : element.getAsString(); + } + + public void setHttpClient(CloseableHttpClient httpClient) { + this.httpClient = httpClient; + } + + protected static class OIDCMetadata { + private final String issuer; + private final String authorizationEndpoint; + private final String tokenEndpoint; + private final String jwksUri; + + protected OIDCMetadata(String issuer, String authorizationEndpoint, String tokenEndpoint, String jwksUri) { + this.issuer = issuer; + this.authorizationEndpoint = authorizationEndpoint; + this.tokenEndpoint = tokenEndpoint; + this.jwksUri = jwksUri; + } + + public String getIssuer() { + return issuer; + } + + public String getAuthorizationEndpoint() { + return authorizationEndpoint; + } + + public String getTokenEndpoint() { + return tokenEndpoint; + } + + public String getJwksUri() { + return jwksUri; + } + } +} diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/vo/OauthProviderVO.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/vo/OauthProviderVO.java index 8aa9006e763e..4fe701315120 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/vo/OauthProviderVO.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/vo/OauthProviderVO.java @@ -60,12 +60,18 @@ public class OauthProviderVO implements Identity, InternalIdentity { @Column(name = "domain_id") private Long domainId; + @Column(name = "type") + private String type; + @Column(name = "authorize_url") private String authorizeUrl; @Column(name = "token_url") private String tokenUrl; + @Column(name = "issuer_url") + private String issuerUrl; + @Column(name = GenericDao.CREATED_COLUMN) private Date created; @@ -121,6 +127,22 @@ public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getIssuerUrl() { + return issuerUrl; + } + + public void setIssuerUrl(String issuerUrl) { + this.issuerUrl = issuerUrl; + } + public String getAuthorizeUrl() { return authorizeUrl; } diff --git a/plugins/user-authenticators/oauth2/src/main/resources/META-INF/cloudstack/oauth2/spring-oauth2-context.xml b/plugins/user-authenticators/oauth2/src/main/resources/META-INF/cloudstack/oauth2/spring-oauth2-context.xml index 06fe60f4c25e..a7b5f2f6001e 100644 --- a/plugins/user-authenticators/oauth2/src/main/resources/META-INF/cloudstack/oauth2/spring-oauth2-context.xml +++ b/plugins/user-authenticators/oauth2/src/main/resources/META-INF/cloudstack/oauth2/spring-oauth2-context.xml @@ -38,6 +38,9 @@ + + + @@ -48,7 +51,7 @@ class="org.apache.cloudstack.spring.lifecycle.registry.ExtensionRegistry"> - + diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImplTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImplTest.java index ffbfa6db6210..c5de9a962c5d 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImplTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImplTest.java @@ -144,6 +144,40 @@ public void testRegisterOauthProviderDisabledWhenRequested() { assertFalse(result.isEnabled()); } + @Test + public void testRegisterRejectsBuiltinNameWithType() { + OAuth2AuthManagerImpl.userOAuth2AuthenticationProvidersMap.put("oidc", Mockito.mock(org.apache.cloudstack.auth.UserOAuth2Authenticator.class)); + OAuth2AuthManagerImpl.userOAuth2AuthenticationProvidersMap.put("google", Mockito.mock(org.apache.cloudstack.auth.UserOAuth2Authenticator.class)); + when(_authManager.isOAuthPluginEnabled(Mockito.nullable(Long.class))).thenReturn(true); + RegisterOAuthProviderCmd cmd = Mockito.mock(RegisterOAuthProviderCmd.class); + when(cmd.getProvider()).thenReturn("google"); + when(cmd.getType()).thenReturn("oidc"); + when(cmd.getDomainId()).thenReturn(null); + try { + _authManager.registerOauthProvider(cmd); + Assert.fail("Expected CloudRuntimeException was not thrown"); + } catch (CloudRuntimeException e) { + assertTrue(e.getMessage().contains("reserved by a built-in")); + } + } + + @Test + public void testRegisterNormalizesTypeCasing() { + OAuth2AuthManagerImpl.userOAuth2AuthenticationProvidersMap.put("oidc", Mockito.mock(org.apache.cloudstack.auth.UserOAuth2Authenticator.class)); + when(_authManager.isOAuthPluginEnabled(Mockito.nullable(Long.class))).thenReturn(true); + RegisterOAuthProviderCmd cmd = Mockito.mock(RegisterOAuthProviderCmd.class); + when(cmd.getProvider()).thenReturn("corp-idp"); + when(cmd.getType()).thenReturn("OIDC"); + when(cmd.getDomainId()).thenReturn(null); + when(_authManager._oauthProviderDao.findByProviderAndDomain(Mockito.anyString(), Mockito.isNull())).thenReturn(null); + org.mockito.ArgumentCaptor captor = org.mockito.ArgumentCaptor.forClass(OauthProviderVO.class); + when(_authManager._oauthProviderDao.persist(captor.capture())).thenReturn(new OauthProviderVO()); + + _authManager.registerOauthProvider(cmd); + + assertEquals("oidc", captor.getValue().getType()); + } + @Test public void testUpdateOauthProvider() { Long id = 1L; @@ -549,6 +583,67 @@ public void testGetUserOAuth2AuthenticationProviderNotFound() { } } + @Test + public void testGetUserOAuth2AuthenticationProviderResolvesRegistrationByType() { + org.apache.cloudstack.auth.UserOAuth2Authenticator oidcProvider = + Mockito.mock(org.apache.cloudstack.auth.UserOAuth2Authenticator.class); + OAuth2AuthManagerImpl.userOAuth2AuthenticationProvidersMap.put("oidc", oidcProvider); + try { + OauthProviderVO registration = new OauthProviderVO(); + registration.setProvider("corp-idp"); + registration.setType("oidc"); + when(_oauthProviderDao.findByProviderAndDomainWithGlobalFallback("corp-idp", 5L)).thenReturn(registration); + + assertEquals(oidcProvider, _authManager.getUserOAuth2AuthenticationProvider("corp-idp", 5L)); + } finally { + OAuth2AuthManagerImpl.userOAuth2AuthenticationProvidersMap.remove("oidc"); + } + } + + @Test + public void testGetUserOAuth2AuthenticationProviderRejectsRegistrationWithoutType() { + OauthProviderVO registration = new OauthProviderVO(); + registration.setProvider("corp-idp"); + when(_oauthProviderDao.findByProviderAndDomainWithGlobalFallback("corp-idp", null)).thenReturn(registration); + + try { + _authManager.getUserOAuth2AuthenticationProvider("corp-idp", null); + Assert.fail("Expected CloudRuntimeException was not thrown"); + } catch (CloudRuntimeException e) { + assertTrue(e.getMessage().contains("corp-idp")); + } + } + + @Test + public void testGetUserOAuth2AuthenticationProviderPrefersRegisteredPluginName() { + org.apache.cloudstack.auth.UserOAuth2Authenticator githubProvider = + Mockito.mock(org.apache.cloudstack.auth.UserOAuth2Authenticator.class); + OAuth2AuthManagerImpl.userOAuth2AuthenticationProvidersMap.put("github", githubProvider); + try { + assertEquals(githubProvider, _authManager.getUserOAuth2AuthenticationProvider("github", 5L)); + Mockito.verify(_oauthProviderDao, Mockito.never()) + .findByProviderAndDomainWithGlobalFallback(Mockito.anyString(), Mockito.anyLong()); + } finally { + OAuth2AuthManagerImpl.userOAuth2AuthenticationProvidersMap.remove("github"); + } + } + + @Test + public void testRegisterOauthProviderRejectsUnknownType() { + when(_authManager.isOAuthPluginEnabled(Mockito.nullable(Long.class))).thenReturn(true); + RegisterOAuthProviderCmd cmd = Mockito.mock(RegisterOAuthProviderCmd.class); + when(cmd.getProvider()).thenReturn("corp-idp"); + when(cmd.getType()).thenReturn("saml"); + + try { + _authManager.registerOauthProvider(cmd); + Assert.fail("Expected CloudRuntimeException was not thrown"); + } catch (CloudRuntimeException e) { + assertTrue(e.getMessage().contains("saml")); + } + Mockito.verify(_oauthProviderDao, Mockito.never()).persist(Mockito.any(OauthProviderVO.class)); + } + // Multiple-domain OAuth tests @Test @@ -700,4 +795,24 @@ public void testDomainDeletionCleansUpOAuthProviders() { verify(_oauthProviderDao, Mockito.times(2)).expunge(Mockito.anyLong()); } + @Test + public void testListOauthProvidersReturnsEmptyWhenUuidMatchesNothing() { + when(_oauthProviderDao.findByUuid("missing")).thenReturn(null); + + List result = _authManager.listOauthProviders(null, "missing", null); + + Assert.assertNotNull(result); + Assert.assertTrue(result.isEmpty()); + } + + @Test + public void testListOauthProvidersReturnsEmptyWhenProviderMatchesNothing() { + when(_oauthProviderDao.findByProviderAndDomain("missing", null)).thenReturn(null); + + List result = _authManager.listOauthProviders("missing", null, null); + + Assert.assertNotNull(result); + Assert.assertTrue(result.isEmpty()); + } + } diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java index 1351c1ea4791..aa960cc5643c 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java @@ -92,8 +92,8 @@ public void testAuthenticateWithValidCredentials() { when(userAccountDao.getUserAccount(username, domainId)).thenReturn(userAccount); when(userDao.getUser(userAccount.getId())).thenReturn(user); - when(userOAuth2mgr.getUserOAuth2AuthenticationProvider(provider[0])).thenReturn(userOAuth2Authenticator); - when(userOAuth2Authenticator.verifyUser(email[0], secretCode[0], domainId)).thenReturn(true); + when(userOAuth2mgr.getUserOAuth2AuthenticationProvider(provider[0], domainId)).thenReturn(userOAuth2Authenticator); + when(userOAuth2Authenticator.verifyUser(email[0], secretCode[0], domainId, provider[0])).thenReturn(true); Map requestParameters = new HashMap<>(); requestParameters.put("provider", provider); @@ -107,8 +107,8 @@ public void testAuthenticateWithValidCredentials() { verify(userAccountDao).getUserAccount(username, domainId); verify(userDao).getUser(userAccount.getId()); - verify(userOAuth2mgr).getUserOAuth2AuthenticationProvider(provider[0]); - verify(userOAuth2Authenticator).verifyUser(email[0], secretCode[0], domainId); + verify(userOAuth2mgr).getUserOAuth2AuthenticationProvider(provider[0], domainId); + verify(userOAuth2Authenticator).verifyUser(email[0], secretCode[0], domainId, provider[0]); } @Test @@ -125,8 +125,8 @@ public void testAuthenticateWithInvalidCredentials() { when(userAccountDao.getUserAccount(username, domainId)).thenReturn(userAccount); when(userDao.getUser(userAccount.getId())).thenReturn(user); - when(userOAuth2mgr.getUserOAuth2AuthenticationProvider(provider[0])).thenReturn(userOAuth2Authenticator); - when(userOAuth2Authenticator.verifyUser(email[0], secretCode[0], domainId)).thenReturn(false); + when(userOAuth2mgr.getUserOAuth2AuthenticationProvider(provider[0], domainId)).thenReturn(userOAuth2Authenticator); + when(userOAuth2Authenticator.verifyUser(email[0], secretCode[0], domainId, provider[0])).thenReturn(false); Map requestParameters = new HashMap<>(); requestParameters.put("provider", provider); @@ -140,8 +140,8 @@ public void testAuthenticateWithInvalidCredentials() { verify(userAccountDao).getUserAccount(username, domainId); verify(userDao).getUser(userAccount.getId()); - verify(userOAuth2mgr).getUserOAuth2AuthenticationProvider(provider[0]); - verify(userOAuth2Authenticator).verifyUser(email[0], secretCode[0], domainId); + verify(userOAuth2mgr).getUserOAuth2AuthenticationProvider(provider[0], domainId); + verify(userOAuth2Authenticator).verifyUser(email[0], secretCode[0], domainId, provider[0]); } @Test @@ -166,7 +166,7 @@ public void testAuthenticateWithInvalidUserAccount() { verify(userAccountDao).getUserAccount(username, domainId); verify(userDao, never()).getUser(anyLong()); - verify(userOAuth2mgr, never()).getUserOAuth2AuthenticationProvider(anyString()); + verify(userOAuth2mgr, never()).getUserOAuth2AuthenticationProvider(anyString(), anyLong()); } @Test @@ -210,6 +210,6 @@ public void testAuthenticateNullProvider() { assertFalse(result.first()); assertNull(result.second()); - verify(userOAuth2mgr, never()).getUserOAuth2AuthenticationProvider(anyString()); + verify(userOAuth2mgr, never()).getUserOAuth2AuthenticationProvider(anyString(), anyLong()); } } diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java index 9a98cdf97305..86264e628629 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -32,9 +33,13 @@ import org.apache.cloudstack.auth.UserOAuth2Authenticator; import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; +import org.apache.cloudstack.oauth2.oidc.GenericOIDCOAuth2Provider; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; +import org.apache.commons.lang3.reflect.FieldUtils; import org.junit.Before; import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; public class RegisterOAuthProviderCmdTest { @@ -89,4 +94,34 @@ public void testExecuteSetsDisabledProviderResponseWhenProviderIsDisabled() thro assertEquals(ApiConstants.OAUTH_PROVIDER, response.getObjectName()); assertFalse(response.getEnabled()); } + + @Test + public void testOidcProviderIsReportedEnabledByType() throws Exception { + FieldUtils.writeField(_cmd, "type", GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE, true); + FieldUtils.writeField(_cmd, "issuerUrl", "https://idp.example.com", true); + + OauthProviderVO provider = mock(OauthProviderVO.class); + when(provider.getDomainId()).thenReturn(null); + when(provider.getUuid()).thenReturn("test-uuid"); + when(provider.getProvider()).thenReturn("mycorp"); + when(provider.getType()).thenReturn(GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE); + when(provider.getDescription()).thenReturn("test"); + when(provider.getClientId()).thenReturn("client-id"); + when(provider.getSecretKey()).thenReturn("secret-key"); + when(provider.getRedirectUri()).thenReturn("http://localhost"); + when(provider.isEnabled()).thenReturn(true); + when(_oauth2mgr.registerOauthProvider(any(RegisterOAuthProviderCmd.class))).thenReturn(provider); + UserOAuth2Authenticator authenticator = mock(UserOAuth2Authenticator.class); + when(authenticator.getName()).thenReturn(GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE); + when(_oauth2mgr.listUserOAuth2AuthenticationProviders()).thenReturn(Collections.singletonList(authenticator)); + + try (MockedStatic mocked = Mockito.mockStatic(OAuth2AuthManager.class)) { + mocked.when(() -> OAuth2AuthManager.isPluginEnabledForDomain(null)).thenReturn(true); + _cmd.execute(); + } + + OauthProviderResponse response = (OauthProviderResponse) _cmd.getResponseObject(); + assertEquals(ApiConstants.OAUTH_PROVIDER, response.getObjectName()); + assertTrue(response.getEnabled()); + } } diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2ProviderTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2ProviderTest.java new file mode 100644 index 000000000000..214d0e2a279b --- /dev/null +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2ProviderTest.java @@ -0,0 +1,625 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package org.apache.cloudstack.oauth2.oidc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; +import java.util.Collections; + +import org.apache.cloudstack.oauth2.dao.OauthProviderDao; +import org.apache.cloudstack.oauth2.vo.OauthProviderVO; +import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; +import org.apache.cxf.rs.security.jose.jwk.JsonWebKey; +import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys; +import org.apache.cxf.rs.security.jose.jwk.JwkUtils; +import org.apache.cxf.rs.security.jose.jws.JwsHeaders; +import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer; +import org.apache.cxf.rs.security.jose.jws.JwsUtils; +import org.apache.cxf.rs.security.jose.jwt.JwtClaims; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import com.cloud.exception.CloudAuthenticationException; +import com.cloud.utils.exception.CloudRuntimeException; + +public class GenericOIDCOAuth2ProviderTest { + + private static final String REGISTRATION = "corp-idp"; + private static final String ISSUER = "https://idp.example.com"; + private static final String CLIENT_ID = "test-client"; + + @Mock + private OauthProviderDao oauthProviderDao; + + @Mock + private CloseableHttpClient httpClient; + + private GenericOIDCOAuth2Provider provider; + + private OauthProviderVO registration; + + private AutoCloseable closeable; + + @Before + public void setUp() { + closeable = MockitoAnnotations.openMocks(this); + + provider = Mockito.spy(new GenericOIDCOAuth2Provider(httpClient)); + provider.oauthProviderDao = oauthProviderDao; + + registration = new OauthProviderVO(); + registration.setProvider(REGISTRATION); + registration.setType(GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE); + registration.setClientId(CLIENT_ID); + registration.setSecretKey("test-secret"); + registration.setRedirectUri("http://localhost/redirect"); + registration.setIssuerUrl(ISSUER); + } + + @After + public void tearDown() throws Exception { + closeable.close(); + } + + private String idToken(String issuer, String audience, String email, long expiresInSeconds) { + String header = "{\"alg\":\"RS256\",\"kid\":\"key-1\"}"; + String payload = "{" + + "\"iss\":\"" + issuer + "\"," + + "\"aud\":[\"" + audience + "\"]," + + "\"email_verified\":true," + + (email == null ? "" : "\"email\":\"" + email + "\",") + + "\"exp\":" + (System.currentTimeMillis() / 1000L + expiresInSeconds) + "," + + "\"sub\":\"12345\"" + + "}"; + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(header.getBytes(StandardCharsets.UTF_8)) + "." + + encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8)) + ".signature"; + } + + private GenericOIDCOAuth2Provider.OIDCMetadata metadata() { + return new GenericOIDCOAuth2Provider.OIDCMetadata(ISSUER, ISSUER + "/authorize", ISSUER + "/token", ISSUER + "/jwks"); + } + + @Test + public void testNameIsTheProviderType() { + assertEquals(GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE, provider.getName()); + assertNull(provider.getUserEmailAddress()); + } + + @Test(expected = CloudRuntimeException.class) + public void testVerifyUserWithoutRegistrationNameIsRejected() { + provider.verifyUser("user@example.com", "code"); + } + + @Test(expected = CloudRuntimeException.class) + public void testVerifySecretCodeWithoutRegistrationNameIsRejected() { + provider.verifySecretCodeAndFetchEmail("code"); + } + + @Test(expected = CloudAuthenticationException.class) + public void testBlankRegistrationNameIsRejected() { + provider.findRegistration(" ", null); + } + + @Test(expected = CloudAuthenticationException.class) + public void testUnregisteredProviderIsRejected() { + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(null); + provider.findRegistration(REGISTRATION, null); + } + + @Test(expected = CloudRuntimeException.class) + public void testRegistrationWithoutIssuerIsRejected() { + registration.setIssuerUrl(null); + registration.setAuthorizeUrl(ISSUER + "/authorize"); + registration.setTokenUrl(ISSUER + "/token"); + provider.getMetadata(registration); + } + + @Test + public void testDiscoveryReadsTheEndpoints() { + String document = "{" + + "\"issuer\":\"" + ISSUER + "\"," + + "\"authorization_endpoint\":\"" + ISSUER + "/authorize\"," + + "\"token_endpoint\":\"" + ISSUER + "/token\"," + + "\"jwks_uri\":\"" + ISSUER + "/jwks\"}"; + doReturn(document).when(provider).httpGet(eq(ISSUER + "/.well-known/openid-configuration"), anyString()); + + GenericOIDCOAuth2Provider.OIDCMetadata metadata = provider.discover(ISSUER); + + assertEquals(ISSUER, metadata.getIssuer()); + assertEquals(ISSUER + "/token", metadata.getTokenEndpoint()); + assertEquals(ISSUER + "/jwks", metadata.getJwksUri()); + } + + @Test(expected = CloudRuntimeException.class) + public void testDiscoveryWithoutTokenEndpointIsRejected() { + doReturn("{\"issuer\":\"" + ISSUER + "\"}").when(provider).httpGet(anyString(), anyString()); + provider.discover(ISSUER); + } + + @Test(expected = CloudRuntimeException.class) + public void testDiscoveryWithoutJwksIsRejected() { + doReturn("{\"issuer\":\"" + ISSUER + "\",\"token_endpoint\":\"" + ISSUER + "/token\"}") + .when(provider).httpGet(anyString(), anyString()); + provider.discover(ISSUER); + } + + @Test(expected = CloudRuntimeException.class) + public void testDiscoveryNamingAnotherIssuerIsRejected() { + doReturn("{\"issuer\":\"https://attacker.example.com\",\"token_endpoint\":\"" + ISSUER + "/token\"," + + "\"jwks_uri\":\"" + ISSUER + "/jwks\"}").when(provider).httpGet(anyString(), anyString()); + provider.discover(ISSUER); + } + + private KeyPair rsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private String signedIdToken(KeyPair keys, String keyId, String email) { + JwtClaims claims = new JwtClaims(); + claims.setIssuer(ISSUER); + claims.setAudiences(Collections.singletonList(CLIENT_ID)); + claims.setSubject("12345"); + claims.setExpiryTime(System.currentTimeMillis() / 1000L + 3600); + claims.setClaim("email", email); + claims.setClaim("email_verified", true); + JwsHeaders headers = new JwsHeaders(SignatureAlgorithm.RS256); + headers.setKeyId(keyId); + return new JwsJwtCompactProducer(headers, claims) + .signWith(JwsUtils.getPrivateKeySignatureProvider(keys.getPrivate(), SignatureAlgorithm.RS256)); + } + + private void publishKey(KeyPair keys, String keyId) { + JsonWebKey key = JwkUtils.fromRSAPublicKey((RSAPublicKey) keys.getPublic(), "RS256"); + key.setKeyId(keyId); + doReturn(JwkUtils.jwkSetToJson(new JsonWebKeys(key))).when(provider).httpGet(eq(ISSUER + "/jwks"), anyString()); + } + + @Test + public void testGenuinelySignedTokenIsAccepted() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + + assertEquals("user@example.com", + provider.validateAndExtractEmail(signedIdToken(keys, "key-1", "user@example.com"), registration, metadata())); + } + + @Test + public void testKeyWithoutAlgorithmFallsBackToTheTokenHeader() throws Exception { + KeyPair keys = rsaKeyPair(); + JsonWebKey key = JwkUtils.fromRSAPublicKey((RSAPublicKey) keys.getPublic(), "RS256"); + key.setAlgorithm(null); + key.setKeyId("key-1"); + doReturn(JwkUtils.jwkSetToJson(new JsonWebKeys(key))).when(provider).httpGet(eq(ISSUER + "/jwks"), anyString()); + + assertEquals("user@example.com", + provider.validateAndExtractEmail(signedIdToken(keys, "key-1", "user@example.com"), registration, metadata())); + } + + @Test + public void testSigningKeysAreCachedAcrossVerifications() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + + provider.validateAndExtractEmail(signedIdToken(keys, "key-1", "user@example.com"), registration, metadata()); + provider.validateAndExtractEmail(signedIdToken(keys, "key-1", "user@example.com"), registration, metadata()); + + verify(provider, times(1)).httpGet(eq(ISSUER + "/jwks"), anyString()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testUnverifiedEmailIsRejected() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + JwtClaims claims = new JwtClaims(); + claims.setIssuer(ISSUER); + claims.setAudiences(Collections.singletonList(CLIENT_ID)); + claims.setSubject("12345"); + claims.setExpiryTime(System.currentTimeMillis() / 1000L + 3600); + claims.setClaim("email", "user@example.com"); + claims.setClaim("email_verified", false); + JwsHeaders headers = new JwsHeaders(SignatureAlgorithm.RS256); + headers.setKeyId("key-1"); + String token = new JwsJwtCompactProducer(headers, claims) + .signWith(JwsUtils.getPrivateKeySignatureProvider(keys.getPrivate(), SignatureAlgorithm.RS256)); + + provider.validateAndExtractEmail(token, registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testTokenWithAlteredClaimsIsRejected() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + String[] parts = signedIdToken(keys, "key-1", "user@example.com").split("\\."); + String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8) + .replace("user@example.com", "admin@example.com"); + String tampered = parts[0] + "." + Base64.getUrlEncoder().withoutPadding() + .encodeToString(payload.getBytes(StandardCharsets.UTF_8)) + "." + parts[2]; + + provider.validateAndExtractEmail(tampered, registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testTokenSignedByAnotherKeyIsRejected() throws Exception { + publishKey(rsaKeyPair(), "key-1"); + + provider.validateAndExtractEmail(signedIdToken(rsaKeyPair(), "key-1", "user@example.com"), registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testTokenNamingAnUnpublishedKeyIsRejected() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + + provider.validateAndExtractEmail(signedIdToken(keys, "key-2", "user@example.com"), registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testUnsignedTokenIsRejectedWhenNoJwksIsPublished() { + GenericOIDCOAuth2Provider.OIDCMetadata noJwks = + new GenericOIDCOAuth2Provider.OIDCMetadata(ISSUER, null, ISSUER + "/token", null); + provider.validateAndExtractEmail(idToken(ISSUER, CLIENT_ID, "user@example.com", 3600), registration, noJwks); + } + + @Test(expected = CloudAuthenticationException.class) + public void testIssuerMismatchIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + provider.validateAndExtractEmail(idToken("https://attacker.example.com", CLIENT_ID, "user@example.com", 3600), + registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testAudienceMismatchIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + provider.validateAndExtractEmail(idToken(ISSUER, "another-client", "user@example.com", 3600), + registration, metadata()); + } + + @Test(expected = RuntimeException.class) + public void testExpiredTokenIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + provider.validateAndExtractEmail(idToken(ISSUER, CLIENT_ID, "user@example.com", -3600), + registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testTokenWithoutEmailClaimIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + provider.validateAndExtractEmail(idToken(ISSUER, CLIENT_ID, null, 3600), registration, metadata()); + } + + @Test + public void testValidTokenYieldsTheEmailClaim() { + doNothing().when(provider).verifySignature(any(), any(), any()); + + String email = provider.validateAndExtractEmail(idToken(ISSUER, CLIENT_ID, "user@example.com", 3600), + registration, metadata()); + + assertEquals("user@example.com", email); + } + + /** + * The provider is a singleton shared by every login, so it must hold no token state between + * calls: each call has to exchange the authorization code it was given. + */ + @Test + public void testEveryCallExchangesItsOwnAuthorizationCode() { + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(registration); + doReturn(metadata()).when(provider).getMetadata(registration); + doReturn("token-for-first").when(provider).exchangeAuthorizationCode(eq("first-code"), any(), any()); + doReturn("token-for-second").when(provider).exchangeAuthorizationCode(eq("second-code"), any(), any()); + doReturn("first@example.com").when(provider).validateAndExtractEmail(eq("token-for-first"), any(), any()); + doReturn("second@example.com").when(provider).validateAndExtractEmail(eq("token-for-second"), any(), any()); + + assertEquals("first@example.com", provider.verifySecretCodeAndFetchEmail("first-code", null, REGISTRATION)); + assertEquals("second@example.com", provider.verifySecretCodeAndFetchEmail("second-code", null, REGISTRATION)); + + verify(provider, times(1)).exchangeAuthorizationCode(eq("first-code"), any(), any()); + verify(provider, times(1)).exchangeAuthorizationCode(eq("second-code"), any(), any()); + } + + @Test(expected = CloudRuntimeException.class) + public void testVerifyUserRejectsAnEmailThatDoesNotMatchTheToken() { + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(registration); + doReturn("someone-else@example.com").when(provider).resolveEmail(registration, "code"); + + provider.verifyUser("user@example.com", "code", null, REGISTRATION); + } + + /** + * The UI resolves the code with verifyOAuthCodeAndGetUser and then logs in with the same code, and an + * identity provider accepts an authorization code only once, so the login must not redeem it again. + */ + @Test + public void testLoginAfterVerificationDoesNotRedeemTheCodeAgain() { + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(registration); + doReturn("user@example.com").when(provider).resolveEmail(registration, "code"); + + assertEquals("user@example.com", provider.verifySecretCodeAndFetchEmail("code", null, REGISTRATION)); + assertTrue(provider.verifyUser("user@example.com", "code", null, REGISTRATION)); + + verify(provider, times(1)).resolveEmail(registration, "code"); + } + + /** + * verifyOAuthCodeAndGetUser can resolve the code with no domain while the login that follows lands on a + * concrete domain. The cached email therefore has to key on the resolved registration, not the request + * domain, or the single use authorization code would be redeemed a second time and rejected. + */ + @Test + public void testCachedEmailIsReusedWhenTheLoginResolvesToADifferentDomainScope() { + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(registration); + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, 1L)).thenReturn(registration); + doReturn("user@example.com").when(provider).resolveEmail(registration, "code"); + + assertEquals("user@example.com", provider.verifySecretCodeAndFetchEmail("code", null, REGISTRATION)); + assertTrue(provider.verifyUser("user@example.com", "code", 1L, REGISTRATION)); + + verify(provider, times(1)).resolveEmail(registration, "code"); + } + + @Test + public void testVerifiedCodeIsServedFromTheCacheOnlyOnce() { + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(registration); + doReturn("user@example.com").when(provider).resolveEmail(registration, "code"); + + provider.verifySecretCodeAndFetchEmail("code", null, REGISTRATION); + provider.verifyUser("user@example.com", "code", null, REGISTRATION); + provider.verifyUser("user@example.com", "code", null, REGISTRATION); + + verify(provider, times(2)).resolveEmail(registration, "code"); + } + + @Test(expected = CloudRuntimeException.class) + public void testAnotherCodeIsNeverAnsweredFromTheCache() { + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(registration); + doReturn("user@example.com").when(provider).resolveEmail(registration, "user-code"); + doThrow(new CloudRuntimeException("invalid_grant")).when(provider).resolveEmail(registration, "unrelated-code"); + + provider.verifySecretCodeAndFetchEmail("user-code", null, REGISTRATION); + provider.verifyUser("user@example.com", "unrelated-code", null, REGISTRATION); + } + + @Test(expected = CloudRuntimeException.class) + public void testCachedCodeIsScopedToItsRegistration() { + OauthProviderVO other = new OauthProviderVO(); + other.setProvider("other-idp"); + other.setType(GenericOIDCOAuth2Provider.OIDC_PROVIDER_TYPE); + other.setIssuerUrl(ISSUER); + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback(REGISTRATION, null)).thenReturn(registration); + when(oauthProviderDao.findByProviderAndDomainWithGlobalFallback("other-idp", null)).thenReturn(other); + doReturn("user@example.com").when(provider).resolveEmail(registration, "code"); + doThrow(new CloudRuntimeException("invalid_grant")).when(provider).resolveEmail(other, "code"); + + provider.verifySecretCodeAndFetchEmail("code", null, REGISTRATION); + provider.verifyUser("user@example.com", "code", null, "other-idp"); + } + + @Test(expected = CloudAuthenticationException.class) + public void testVerifyUserRejectsEmptyArguments() { + provider.verifyUser("", "", null, REGISTRATION); + } + + /** + * Some conformant providers, such as Microsoft Entra ID, never send the email_verified claim. The domain + * can opt out of requiring it, and then a token without the claim is accepted. + */ + @Test + public void testAbsentEmailVerifiedIsAcceptedWhenTheDomainDoesNotRequireIt() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + doReturn(false).when(provider).isVerifiedEmailRequired(registration); + + assertEquals("user@example.com", + provider.validateAndExtractEmail(signedIdToken(keys, "key-1", "user@example.com", null), registration, metadata())); + } + + @Test(expected = CloudAuthenticationException.class) + public void testAbsentEmailVerifiedIsRejectedWhenTheDomainRequiresIt() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + doReturn(true).when(provider).isVerifiedEmailRequired(registration); + + provider.validateAndExtractEmail(signedIdToken(keys, "key-1", "user@example.com", null), registration, metadata()); + } + + /** + * An explicit email_verified=false is the provider telling us the address is not verified, so it is + * rejected regardless of the domain policy. + */ + @Test(expected = CloudAuthenticationException.class) + public void testExplicitlyUnverifiedEmailIsRejectedEvenWhenTheDomainDoesNotRequireVerification() throws Exception { + KeyPair keys = rsaKeyPair(); + publishKey(keys, "key-1"); + doReturn(false).when(provider).isVerifiedEmailRequired(registration); + + provider.validateAndExtractEmail(signedIdToken(keys, "key-1", "user@example.com", false), registration, metadata()); + } + + @Test + public void testHttpGetDoesNotLeakTheProviderBodyOnFailure() throws Exception { + CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + StatusLine statusLine = Mockito.mock(StatusLine.class); + when(statusLine.getStatusCode()).thenReturn(500); + when(response.getStatusLine()).thenReturn(statusLine); + when(response.getEntity()).thenReturn(new StringEntity("sensitive idp body")); + when(httpClient.execute(any(HttpGet.class))).thenReturn(response); + + try { + provider.httpGet(ISSUER + "/jwks", "Unable to read the signing keys from " + ISSUER + "/jwks"); + fail("expected the fetch to fail"); + } catch (CloudRuntimeException e) { + assertEquals("Unable to read the signing keys from " + ISSUER + "/jwks", e.getMessage()); + assertFalse(e.getMessage().contains("sensitive idp body")); + } + } + + private long future() { + return System.currentTimeMillis() / 1000L + 3600; + } + + private String token(String bodyJson) { + Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); + String header = "{\"alg\":\"RS256\",\"kid\":\"key-1\"}"; + return enc.encodeToString(header.getBytes(StandardCharsets.UTF_8)) + "." + + enc.encodeToString(bodyJson.getBytes(StandardCharsets.UTF_8)) + ".sig"; + } + + @Test + public void testMultiAudienceWithMatchingAzpIsAccepted() { + doNothing().when(provider).verifySignature(any(), any(), any()); + String body = "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + CLIENT_ID + "\",\"other\"],\"azp\":\"" + CLIENT_ID + + "\",\"email\":\"user@example.com\",\"email_verified\":true,\"exp\":" + future() + "}"; + assertEquals("user@example.com", provider.validateAndExtractEmail(token(body), registration, metadata())); + } + + @Test(expected = CloudAuthenticationException.class) + public void testMultiAudienceWithoutAzpIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + String body = "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + CLIENT_ID + "\",\"other\"]," + + "\"email\":\"user@example.com\",\"email_verified\":true,\"exp\":" + future() + "}"; + provider.validateAndExtractEmail(token(body), registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testAuthorizedPartyForAnotherClientIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + String body = "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + CLIENT_ID + "\"],\"azp\":\"other\"," + + "\"email\":\"user@example.com\",\"email_verified\":true,\"exp\":" + future() + "}"; + provider.validateAndExtractEmail(token(body), registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testTokenWithoutAudienceIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + String body = "{\"iss\":\"" + ISSUER + "\",\"email\":\"user@example.com\",\"email_verified\":true,\"exp\":" + future() + "}"; + provider.validateAndExtractEmail(token(body), registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testNonStringEmailClaimIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + String body = "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + CLIENT_ID + "\"],\"email\":12345," + + "\"email_verified\":true,\"exp\":" + future() + "}"; + provider.validateAndExtractEmail(token(body), registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testTokenNotYetValidIsRejected() { + doNothing().when(provider).verifySignature(any(), any(), any()); + String body = "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + CLIENT_ID + "\"],\"email\":\"user@example.com\"," + + "\"email_verified\":true,\"exp\":" + future() + ",\"nbf\":" + (future() + 1000) + "}"; + provider.validateAndExtractEmail(token(body), registration, metadata()); + } + + @Test(expected = CloudAuthenticationException.class) + public void testHmacAlgorithmIsRejectedEvenWhenTheKeyOmitsItsAlgorithm() throws Exception { + KeyPair keys = rsaKeyPair(); + JsonWebKey key = JwkUtils.fromRSAPublicKey((RSAPublicKey) keys.getPublic(), "RS256"); + key.setAlgorithm(null); + key.setKeyId("key-1"); + doReturn(JwkUtils.jwkSetToJson(new JsonWebKeys(key))).when(provider).httpGet(eq(ISSUER + "/jwks"), anyString()); + Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); + String header = "{\"alg\":\"HS256\",\"kid\":\"key-1\"}"; + String body = "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + CLIENT_ID + "\"],\"email\":\"user@example.com\"," + + "\"email_verified\":true,\"exp\":" + future() + "}"; + String hmacToken = enc.encodeToString(header.getBytes(StandardCharsets.UTF_8)) + "." + + enc.encodeToString(body.getBytes(StandardCharsets.UTF_8)) + ".sig"; + + provider.validateAndExtractEmail(hmacToken, registration, metadata()); + } + + @Test(expected = CloudRuntimeException.class) + public void testHttpIssuerIsRejectedAtValidation() { + doReturn(true).when(provider).isHttpsRequired(); + provider.validateIssuer("http://idp.example.com"); + } + + @Test + public void testHttpIssuerIsAcceptedWhenHttpsIsNotRequired() { + doReturn(false).when(provider).isHttpsRequired(); + String document = "{\"issuer\":\"http://idp.example.com\",\"authorization_endpoint\":\"http://idp.example.com/authorize\"," + + "\"token_endpoint\":\"http://idp.example.com/token\",\"jwks_uri\":\"http://idp.example.com/jwks\"}"; + doReturn(document).when(provider).httpGet(eq("http://idp.example.com/.well-known/openid-configuration"), anyString()); + + provider.validateIssuer("http://idp.example.com"); + } + + @Test + public void testValidateIssuerAcceptsAReachableHttpsIssuer() { + String document = "{\"issuer\":\"" + ISSUER + "\",\"authorization_endpoint\":\"" + ISSUER + "/authorize\"," + + "\"token_endpoint\":\"" + ISSUER + "/token\",\"jwks_uri\":\"" + ISSUER + "/jwks\"}"; + doReturn(document).when(provider).httpGet(eq(ISSUER + "/.well-known/openid-configuration"), anyString()); + + provider.validateIssuer(ISSUER); + } + + @Test(expected = CloudRuntimeException.class) + public void testDiscoveryWithHttpTokenEndpointIsRejected() { + doReturn(true).when(provider).isHttpsRequired(); + doReturn("{\"issuer\":\"" + ISSUER + "\",\"token_endpoint\":\"http://idp.example.com/token\",\"jwks_uri\":\"" + + ISSUER + "/jwks\"}").when(provider).httpGet(anyString(), anyString()); + provider.discover(ISSUER); + } + + private String signedIdToken(KeyPair keys, String keyId, String email, Boolean emailVerified) { + JwtClaims claims = new JwtClaims(); + claims.setIssuer(ISSUER); + claims.setAudiences(Collections.singletonList(CLIENT_ID)); + claims.setSubject("12345"); + claims.setExpiryTime(System.currentTimeMillis() / 1000L + 3600); + claims.setClaim("email", email); + if (emailVerified != null) { + claims.setClaim("email_verified", emailVerified); + } + JwsHeaders headers = new JwsHeaders(SignatureAlgorithm.RS256); + headers.setKeyId(keyId); + return new JwsJwtCompactProducer(headers, claims) + .signWith(JwsUtils.getPrivateKeySignatureProvider(keys.getPrivate(), SignatureAlgorithm.RS256)); + } +} diff --git a/ui/public/assets/oidc.svg b/ui/public/assets/oidc.svg new file mode 100644 index 000000000000..9be68623ee25 --- /dev/null +++ b/ui/public/assets/oidc.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/ui/public/locales/en.json b/ui/public/locales/en.json index a3d3a2285ac4..3bcb16d5d305 100644 --- a/ui/public/locales/en.json +++ b/ui/public/locales/en.json @@ -1673,6 +1673,7 @@ "label.loginfo": "Log file information", "label.login.external": "External", "label.login.portal": "Portal login", +"label.login.with": "Sign in with {provider}", "label.login.single.signon": "Single sign-on", "label.logout": "Logout", "label.lun": "LUN", @@ -4037,6 +4038,7 @@ "message.no.data.to.show.for.period": "No data to show for the selected period.", "message.no.description": "No description entered.", "message.no.more.readiness.rule.types": "All applicable readiness rule types have already been added.", +"message.oauth.provider.unreachable": "Unable to reach the OAuth provider to start the login.", "message.note.about.keypair.permissions.title": "Note about API key pair rule permissions", "message.note.about.keypair.permissions.body": "During the creation of API key pairs, it is possible to define a corresponding set of rule permissions. If a rule set is defined, the API key pair will only have access to APIs for which access has been explicitly granted (i.e., APIs whose corresponding rules are marked as allowed). On the other hand, if no rule set is specified, the API key pair permissions will follow and adapt to the permission set of the user's account role.", "message.offering.internet.protocol.warning": "WARNING: IPv6 supported Networks use static routing and will require upstream routes to be configured manually.", diff --git a/ui/src/views/auth/Login.vue b/ui/src/views/auth/Login.vue index 9dcc8b4f34c2..7713eb45b811 100644 --- a/ui/src/views/auth/Login.vue +++ b/ui/src/views/auth/Login.vue @@ -174,11 +174,11 @@
Enter your domain to see domain-specific providers
-
+
+
@@ -294,6 +304,7 @@ export default { oauthGithubRedirectUri: '', oauthKeycloakRedirectUri: '', oauthKeycloakAuthorizeUrl: '', + oauthGenericProviders: [], oauthLoading: false, oauthDomainQueried: false, loginType: 0, @@ -393,6 +404,7 @@ export default { getAPI('listOauthProvider', params).then(response => { if (response) { const oauthproviders = response.listoauthproviderresponse.oauthprovider || [] + this.oauthGenericProviders = oauthproviders.filter(item => item.type === 'oidc' && (item.enabled === true || item.enabled === 'true')) if (!domain) { oauthproviders.forEach(item => { if (item.provider === 'google') { @@ -510,6 +522,26 @@ export default { this.handleDomain() this.$store.commit('SET_OAUTH_PROVIDER_USED_TO_LOGIN', 'keycloak') }, + loginWithGenericOidc (provider) { + this.handleDomain() + this.$store.commit('SET_OAUTH_PROVIDER_USED_TO_LOGIN', provider.provider) + const discoveryUrl = provider.issuerurl.replace(/\/$/, '') + '/.well-known/openid-configuration' + return fetch(discoveryUrl).then(response => response.json()).then(config => { + const options = { + client_id: provider.clientid, + redirect_uri: provider.redirecturi, + response_type: 'code', + scope: 'openid email', + state: this.from || 'cloudstack' + } + window.location.href = `${config.authorization_endpoint}?${new URLSearchParams(options).toString()}` + }).catch(() => { + this.$notification.error({ + message: this.$t('label.error'), + description: this.$t('message.oauth.provider.unreachable') + }) + }) + }, handleDomain () { const values = toRaw(this.form) const domain = this.customActiveKey === 'oauth' ? values.oauthDomain : values.domain