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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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` ');
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ public interface OAuth2AuthManager extends PluggableAPIAuthenticator, PluggableS
"List of OAuth plugins", true);
public static final ConfigKey<String> OAuth2PluginsExclude = new ConfigKey<String>("Advanced", String.class, "oauth2.plugins.exclude", "",
"List of OAuth plugins which are excluded", true);
public static final ConfigKey<Boolean> OIDCRequireVerifiedEmail = new ConfigKey<Boolean>("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<Boolean> OIDCRequireHttps = new ConfigKey<Boolean>("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
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -125,13 +124,30 @@ public List<UserOAuth2Authenticator> 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<UserOAuth2Authenticator> getUserOAuth2AuthenticationProviders() {
Expand All @@ -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;
}
Expand All @@ -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));
Comment thread
rootnomad marked this conversation as resolved.
Resolved
}

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) {
Expand All @@ -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<OauthProviderVO> listOauthProviders(String provider, String uuid, Long domainId) {
List<OauthProviderVO> 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 {
Expand All @@ -204,6 +231,14 @@ public List<OauthProviderVO> listOauthProviders(String provider, String uuid, Lo
return providers;
}

private List<OauthProviderVO> singleOrEmpty(OauthProviderVO provider) {
List<OauthProviderVO> providers = new ArrayList<>();
if (provider != null) {
providers.add(provider);
}
return providers;
}

@Override
public OauthProviderVO updateOauthProvider(UpdateOAuthProviderCmd cmd) {
Long id = cmd.getId();
Expand All @@ -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);
Expand Down Expand Up @@ -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);
}
Expand All @@ -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);
Expand All @@ -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);

Expand Down Expand Up @@ -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};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ public Pair<Boolean, ActionOnFailedAuthentication> 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<Boolean, ActionOnFailedAuthentication>(true, null);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {

Expand Down Expand Up @@ -184,8 +185,10 @@ public String authenticate(String command, Map<String, Object[]> 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);
Expand All @@ -200,7 +203,7 @@ public String authenticate(String command, Map<String, Object[]> params, HttpSes
for (OauthProviderVO domainProvider : allProviders) {
if (domainProvider.getDomainId() != null && domainProvider.isEnabled()
&& OAuth2AuthManager.isPluginEnabledForDomain(domainProvider.getDomainId())
&& authenticatorPluginNames.contains(domainProvider.getProvider())) {
&& isServedByPlugin(domainProvider, authenticatorPluginNames)) {
totalEnabledCount++;
}
}
Expand All @@ -214,6 +217,11 @@ public String authenticate(String command, Map<String, Object[]> params, HttpSes
return ApiResponseSerializer.toSerializedString(response, responseType);
}

protected boolean isServedByPlugin(OauthProviderVO provider, List<String> authenticatorPluginNames) {
return authenticatorPluginNames.contains(provider.getProvider())
|| (StringUtils.isNotBlank(provider.getType()) && authenticatorPluginNames.contains(provider.getType()));
}

@Override
public APIAuthenticationType getAPIType() {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,16 @@ public String authenticate(String command, Map<String, Object[]> 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<String, Object[]> params, String responseType, StringBuilder auditTrailSb, CloudAuthenticationException ex) {
private ServerApiException toServerApiException(HttpSession session, Map<String, Object[]> 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);
Expand Down
Loading