From e8a5d3672d06506ad8dd3bffa08161cc10146798 Mon Sep 17 00:00:00 2001 From: Lashini Jayasekara <30428591+lashinijay@users.noreply.github.com> Date: Thu, 12 Dec 2024 15:30:53 +0530 Subject: [PATCH 1/8] [Spring Cleanup] Remove spring dependency in client attestation filter (#2634) --- .../pom.xml | 5 -- .../filter/ClientAttestationProxy.java | 4 +- .../ClientAttestationServiceHolder.java | 59 +++++++------------ .../ApplicationManagementServiceFactory.java | 56 ------------------ .../ClientAttestationServiceFactory.java | 54 ----------------- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 - 6 files changed, 23 insertions(+), 157 deletions(-) delete mode 100644 components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ApplicationManagementServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ClientAttestationServiceFactory.java diff --git a/components/org.wso2.carbon.identity.client.attestation.filter/pom.xml b/components/org.wso2.carbon.identity.client.attestation.filter/pom.xml index d7893b06371..81781a6633a 100644 --- a/components/org.wso2.carbon.identity.client.attestation.filter/pom.xml +++ b/components/org.wso2.carbon.identity.client.attestation.filter/pom.xml @@ -46,11 +46,6 @@ org.wso2.carbon.identity.inbound.auth.oauth2 org.wso2.carbon.identity.oauth - - org.springframework - spring-web - provided - org.wso2.carbon.identity.framework org.wso2.carbon.identity.base diff --git a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationProxy.java b/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationProxy.java index 4e17820081c..204dc068d9f 100644 --- a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationProxy.java +++ b/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationProxy.java @@ -115,7 +115,7 @@ public void handleMessage(Message message) { // Attestation validation should be performed only if API-based authentication is enabled. if (serviceProvider.isAPIBasedAuthenticationEnabled()) { // Validate the attestation header and obtain client attestation context - clientAttestationContext = ClientAttestationServiceHolder.getInstance() + clientAttestationContext = ClientAttestationServiceHolder .getClientAttestationService().validateAttestation(attestationHeader, serviceProvider.getApplicationResourceId(), IdentityTenantUtil.resolveTenantDomain()); @@ -265,7 +265,7 @@ private ServiceProvider getServiceProvider(String clientId, String tenantDomain) ServiceProvider serviceProvider; try { - serviceProvider = ClientAttestationServiceHolder.getInstance().getApplicationManagementService() + serviceProvider = ClientAttestationServiceHolder.getApplicationManagementService() .getServiceProviderByClientId(clientId, OAUTH2, tenantDomain); } catch (IdentityApplicationManagementClientException e) { throw new WebApplicationException( diff --git a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationServiceHolder.java b/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationServiceHolder.java index 57f6f01e246..6a0aa1f4d2e 100644 --- a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationServiceHolder.java +++ b/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/ClientAttestationServiceHolder.java @@ -19,6 +19,7 @@ package org.wso2.carbon.identity.client.attestation.filter; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.client.attestation.mgt.services.ClientAttestationService; @@ -29,43 +30,32 @@ */ public class ClientAttestationServiceHolder { - // Singleton instance - private static ClientAttestationServiceHolder instance = new ClientAttestationServiceHolder(); - // Service instances - private ClientAttestationService clientAttestationService; - private ApplicationManagementService applicationManagementService; - // Private constructor to enforce Singleton pattern - private ClientAttestationServiceHolder() {} - - /** - * Returns the singleton instance of the ClientAttestationServiceHolder. - * - * @return The singleton instance. - */ - public static ClientAttestationServiceHolder getInstance() { + private static class ClientAttestationHolder { - return instance; + static final ClientAttestationService SERVICE = (ClientAttestationService) + PrivilegedCarbonContext.getThreadLocalCarbonContext() + .getOSGiService(ClientAttestationService.class, null); } - /** - * Gets the instance of the Client Attestation Service. - * - * @return The Client Attestation Service instance. - */ - public ClientAttestationService getClientAttestationService() { + private static class ApplicationManagementHolder { - return ClientAttestationServiceHolder.getInstance().clientAttestationService; + static final ApplicationManagementService SERVICE = (ApplicationManagementService) + PrivilegedCarbonContext.getThreadLocalCarbonContext() + .getOSGiService(ApplicationManagementService.class, null); } /** - * Sets the instance of the Client Attestation Service. + * Gets the instance of the Client Attestation Service. * - * @param clientAttestationService The Client Attestation Service instance to set. + * @return The Client Attestation Service instance. */ - public void setClientAttestationService(ClientAttestationService clientAttestationService) { + public static ClientAttestationService getClientAttestationService() { - ClientAttestationServiceHolder.getInstance().clientAttestationService = clientAttestationService; + if (ClientAttestationHolder.SERVICE == null) { + throw new IllegalStateException("ClientAttestationService is not available from OSGI context."); + } + return ClientAttestationHolder.SERVICE; } /** @@ -73,18 +63,11 @@ public void setClientAttestationService(ClientAttestationService clientAttestati * * @return The Application Management Service instance. */ - public ApplicationManagementService getApplicationManagementService() { - - return ClientAttestationServiceHolder.getInstance().applicationManagementService; - } - - /** - * Sets the instance of the Application Management Service. - * - * @param applicationManagementService The Application Management Service instance to set. - */ - public void setApplicationManagementService(ApplicationManagementService applicationManagementService) { + public static ApplicationManagementService getApplicationManagementService() { - ClientAttestationServiceHolder.getInstance().applicationManagementService = applicationManagementService; + if (ApplicationManagementHolder.SERVICE == null) { + throw new IllegalStateException("ApplicationManagementService is not available from OSGI context."); + } + return ApplicationManagementHolder.SERVICE; } } diff --git a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ApplicationManagementServiceFactory.java b/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ApplicationManagementServiceFactory.java deleted file mode 100644 index 79e17064f31..00000000000 --- a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ApplicationManagementServiceFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.client.attestation.filter.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the ApplicationManagementService type of object inside the container. - */ -public class ApplicationManagementServiceFactory extends AbstractFactoryBean { - - public ApplicationManagementService applicationManagementService; - - - @Override - public Class getObjectType() { - - return ApplicationManagementService.class; - } - - @Override - protected ApplicationManagementService createInstance() throws Exception { - - if (this.applicationManagementService != null) { - return this.applicationManagementService; - } else { - ApplicationManagementService applicationManagementService = - (ApplicationManagementService) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(ApplicationManagementService.class, null); - if (applicationManagementService != null) { - this.applicationManagementService = applicationManagementService; - } - return applicationManagementService; - } - } -} diff --git a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ClientAttestationServiceFactory.java b/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ClientAttestationServiceFactory.java deleted file mode 100644 index 517da3f082d..00000000000 --- a/components/org.wso2.carbon.identity.client.attestation.filter/src/main/java/org/wso2/carbon/identity/client/attestation/filter/factory/ClientAttestationServiceFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.client.attestation.filter.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.client.attestation.mgt.services.ClientAttestationService; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the ClientAttestationService type of object inside the container. - */ -public class ClientAttestationServiceFactory extends AbstractFactoryBean { - - public ClientAttestationService clientAttestationService; - - @Override - public Class getObjectType() { - - return ClientAttestationService.class; - } - - @Override - protected ClientAttestationService createInstance() throws Exception { - - if (this.clientAttestationService != null) { - return this.clientAttestationService; - } else { - ClientAttestationService clientAttestationService = (ClientAttestationService) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(ClientAttestationService.class, null); - if (clientAttestationService != null) { - this.clientAttestationService = clientAttestationService; - } - return clientAttestationService; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml index 912d5458a4e..4c5a34b03d9 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -68,8 +68,6 @@ - - From d73a48a228ed6a290b1f9608cb7489fe7f61059a Mon Sep 17 00:00:00 2001 From: Lashini Jayasekara <30428591+lashinijay@users.noreply.github.com> Date: Tue, 7 Jan 2025 12:18:08 +0530 Subject: [PATCH 2/8] [Spring Cleanup] Remove spring dependency in client authn filter (#2656) --- .../pom.xml | 5 --- .../filter/OAuthClientAuthenticatorProxy.java | 16 +------- .../OAuthClientAuthnServiceFactory.java | 38 ++++++++----------- 3 files changed, 17 insertions(+), 42 deletions(-) diff --git a/components/org.wso2.carbon.identity.oauth.client.authn.filter/pom.xml b/components/org.wso2.carbon.identity.oauth.client.authn.filter/pom.xml index 6e0d59371c2..7df7b8e965f 100644 --- a/components/org.wso2.carbon.identity.oauth.client.authn.filter/pom.xml +++ b/components/org.wso2.carbon.identity.oauth.client.authn.filter/pom.xml @@ -45,11 +45,6 @@ org.wso2.carbon.identity.inbound.auth.oauth2 org.wso2.carbon.identity.oauth - - org.springframework - spring-web - provided - diff --git a/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthenticatorProxy.java b/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthenticatorProxy.java index cad84aadd7f..d1229ed2296 100644 --- a/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthenticatorProxy.java +++ b/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthenticatorProxy.java @@ -30,7 +30,6 @@ import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnService; import java.util.Arrays; import java.util.HashMap; @@ -51,7 +50,6 @@ public class OAuthClientAuthenticatorProxy extends AbstractPhaseInterceptor PROXY_ENDPOINT_LIST = Arrays.asList("/oauth2/token", "/oauth2/revoke", "/oauth2/device_authorize", "/oauth2/ciba", "/oauth2/par", "/oauth2/authorize"); - private OAuthClientAuthnService oAuthClientAuthnService; private static final String SLASH = "/"; public OAuthClientAuthenticatorProxy() { @@ -60,16 +58,6 @@ public OAuthClientAuthenticatorProxy() { super(Phase.PRE_INVOKE); } - public OAuthClientAuthnService getOAuthClientAuthnService() { - - return oAuthClientAuthnService; - } - - public void setOAuthClientAuthnService(OAuthClientAuthnService oAuthClientAuthnService) { - - this.oAuthClientAuthnService = oAuthClientAuthnService; - } - /** * Handles the incoming JAX-RS message for the purpose of OAuth2 client authentication. * @@ -82,8 +70,8 @@ public void handleMessage(Message message) { HttpServletRequest request = ((HttpServletRequest) message.get(HTTP_REQUEST)); if (canHandle(message)) { try { - OAuthClientAuthnContext oAuthClientAuthnContext = oAuthClientAuthnService - .authenticateClient(request, bodyContentParams); + OAuthClientAuthnContext oAuthClientAuthnContext = OAuthClientAuthnServiceFactory + .getOAuthClientAuthnService().authenticateClient(request, bodyContentParams); if (!oAuthClientAuthnContext.isPreviousAuthenticatorEngaged()) { /* If the previous authenticator is not engaged it means that either client authentication flow failed or no supported authenticaiton mechanism was found.If the error details are already diff --git a/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthnServiceFactory.java b/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthnServiceFactory.java index 8cf4955e76d..8bb57472b36 100644 --- a/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthnServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.client.authn.filter/src/main/java/org/wso2/carbon/identity/oauth/client/authn/filter/OAuthClientAuthnServiceFactory.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2019-2024, WSO2 LLC. (http://www.wso2.com). * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. 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 @@ -18,37 +18,29 @@ package org.wso2.carbon.identity.oauth.client.authn.filter; -import org.springframework.beans.factory.config.AbstractFactoryBean; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.oauth2.client.authentication.OAuthClientAuthnService; /** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the OAuthClientAuthnService type of object inside the container. + * Factory class to get OAuthClientAuthnService OSGI service. */ -public class OAuthClientAuthnServiceFactory extends AbstractFactoryBean { +public class OAuthClientAuthnServiceFactory { - public OAuthClientAuthnService oAuthClientAuthnService; + private static final OAuthClientAuthnService SERVICE; + static { + OAuthClientAuthnService oAuthClientAuthnService = (OAuthClientAuthnService) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(OAuthClientAuthnService.class, null); - @Override - public Class getObjectType() { + if (oAuthClientAuthnService == null) { + throw new IllegalStateException("OAuthClientAuthnService is not available from OSGI context."); + } - return OAuthClientAuthnService.class; + SERVICE = oAuthClientAuthnService; } - @Override - protected OAuthClientAuthnService createInstance() throws Exception { - - if (this.oAuthClientAuthnService != null) { - return this.oAuthClientAuthnService; - } else { - OAuthClientAuthnService oAuthClientAuthnService = (OAuthClientAuthnService) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(OAuthClientAuthnService.class, null); - if (oAuthClientAuthnService != null) { - this.oAuthClientAuthnService = oAuthClientAuthnService; - } - return oAuthClientAuthnService; - } + public static OAuthClientAuthnService getOAuthClientAuthnService() { + + return SERVICE; } } From dde81abad73574aa09ef278125b7e7661bb84074 Mon Sep 17 00:00:00 2001 From: Lashini Jayasekara <30428591+lashinijay@users.noreply.github.com> Date: Wed, 8 Jan 2025 14:02:35 +0530 Subject: [PATCH 3/8] [Spring Cleanup] Remove Spring dependency from oauth component (#2648) * remove spring dependency from oauth2 components * fix formattings and unit tests --- .../pom.xml | 7 +- .../endpoint/authz/OAuth2AuthzEndpoint.java | 56 +-- .../authz/OAuth2AuthzServiceFactory.java | 44 +++ .../endpoint/ciba/OAuth2CibaEndpoint.java | 5 +- .../oauth/endpoint/device/DeviceEndpoint.java | 10 +- .../endpoint/device/DeviceServiceFactory.java | 45 +++ .../device/UserAuthenticationEndpoint.java | 11 +- .../endpoint/factory/CibaServiceFactory.java | 54 --- .../factory/DeviceAuthServiceFactory.java | 53 --- .../endpoint/factory/IDPManagerFactory.java | 53 --- .../factory/OAuth2ScopeServiceFactory.java | 53 --- .../factory/OAuth2ServiceFactory.java | 53 --- .../factory/OAuthAdminServiceFactory.java | 53 --- .../OAuthServerConfigurationFactory.java | 53 --- .../OpenIDConnectClaimFilterFactory.java | 55 --- .../endpoint/factory/ParServiceFactory.java | 52 --- .../factory/RequestObjectServiceFactory.java | 53 --- .../factory/SSOConsentServiceFactory.java | 53 --- .../oidcdiscovery/OIDCDiscoveryEndpoint.java | 18 +- .../OIDCDiscoveryServiceFactory.java | 44 +++ .../oauth/endpoint/par/OAuth2ParEndpoint.java | 4 +- .../revoke/OAuthRevocationEndpoint.java | 2 +- .../state/OAuthRequestStateValidator.java | 2 +- .../endpoint/token/OAuth2TokenEndpoint.java | 3 +- .../impl/UserInfoISAccessTokenValidator.java | 5 +- .../oauth/endpoint/util/EndpointUtil.java | 221 ++--------- .../util/factory/CibaAuthServiceFactory.java | 46 +++ .../factory/IdpManagerServiceFactory.java | 45 +++ .../util/factory/OAuth2ServiceFactory.java | 45 +++ .../OAuth2TokenValidatorServiceFactory.java | 46 +++ .../factory/OAuthAdminServiceFactory.java | 46 +++ .../OAuthServerConfigurationFactory.java | 45 +++ .../OIDCProviderRequestValidatorFactory.java | 46 +++ .../factory/OIDCProviderServiceFactory.java | 46 +++ .../factory/Oauth2ScopeServiceFactory.java | 45 +++ .../util/factory/ParAuthServiceFactory.java | 45 +++ .../factory/RequestObjectServiceFactory.java | 45 +++ .../factory/SSOConsentServiceFactory.java | 45 +++ .../factory/ScopeMetadataServiceFactory.java} | 56 +-- .../util/factory/WebFingerServiceFactory.java | 46 +++ .../src/main/webapp/WEB-INF/web.xml | 37 +- .../authz/OAuth2AuthzEndpointTest.java | 301 +++++++++++---- .../endpoint/ciba/OAuth2CibaEndpointTest.java | 68 +++- .../endpoint/device/DeviceEndpointTest.java | 39 +- .../UserAuthenticationEndpointTest.java | 34 +- .../OIDCDiscoveryEndpointTest.java | 88 ++++- .../endpoint/par/OAuth2ParEndpointTest.java | 50 ++- .../revoke/OAuthRevocationEndpointTest.java | 47 ++- .../token/OAuth2TokenEndpointTest.java | 49 ++- .../UserInfoISAccessTokenValidatorTest.java | 67 +++- .../impl/UserInfoJSONResponseBuilderTest.java | 350 +++++++++--------- .../oauth/endpoint/util/EndpointUtilTest.java | 203 ++++++---- 52 files changed, 1725 insertions(+), 1317 deletions(-) create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/CibaServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/DeviceAuthServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/IDPManagerFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ScopeServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthAdminServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthServerConfigurationFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OpenIDConnectClaimFilterFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/ParServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/RequestObjectServiceFactory.java delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/SSOConsentServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/CibaAuthServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/IdpManagerServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OAuth2ServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OAuth2TokenValidatorServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OAuthAdminServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OAuthServerConfigurationFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OIDCProviderRequestValidatorFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OIDCProviderServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/Oauth2ScopeServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/ParAuthServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/RequestObjectServiceFactory.java create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/SSOConsentServiceFactory.java rename components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/{factory/ScopeServiceFactory.java => util/factory/ScopeMetadataServiceFactory.java} (70%) create mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml b/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml index 1c4f3c90e4a..2d5a0beb41f 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml +++ b/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml @@ -169,11 +169,6 @@ org.wso2.carbon.identity.client.attestation.filter provided - - org.springframework - spring-web - provided - com.fasterxml.jackson.core jackson-databind @@ -331,7 +326,7 @@ COMPLEXITY COVEREDRATIO - 0.48 + 0.47 diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java index c6724c68cdb..b12082cac57 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java @@ -136,7 +136,6 @@ import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; import org.wso2.carbon.identity.oauth2.responsemode.provider.AuthorizationResponseDTO; import org.wso2.carbon.identity.oauth2.responsemode.provider.ResponseModeProvider; -import org.wso2.carbon.identity.oauth2.scopeservice.ScopeMetadataService; import org.wso2.carbon.identity.oauth2.token.bindings.TokenBinder; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.identity.oauth2.util.RequestUtil; @@ -144,7 +143,6 @@ import org.wso2.carbon.identity.oidc.session.util.OIDCSessionManagementUtil; import org.wso2.carbon.identity.openidconnect.OIDCConstants; import org.wso2.carbon.identity.openidconnect.OIDCRequestObjectUtil; -import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImpl; import org.wso2.carbon.identity.openidconnect.model.RequestObject; import org.wso2.carbon.identity.openidconnect.model.RequestedClaim; import org.wso2.carbon.utils.CarbonUtils; @@ -211,12 +209,13 @@ import static org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.USER_CONSENT_RESPONSE; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getErrorPageURL; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getLoginPageURL; -import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuth2Service; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuthAuthzRequest; -import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuthServerConfiguration; -import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getSSOConsentService; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.retrieveStateForErrorURL; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateParams; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory.getOAuth2Service; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuthServerConfigurationFactory.getOAuthServerConfiguration; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.RequestObjectServiceFactory.getRequestObjectService; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.SSOConsentServiceFactory.getSSOConsentService; import static org.wso2.carbon.identity.oauth2.OAuth2Constants.TokenBinderType.CLIENT_REQUEST; import static org.wso2.carbon.identity.oauth2.util.OAuth2Util.ACCESS_TOKEN_JS_OBJECT; import static org.wso2.carbon.identity.oauth2.util.OAuth2Util.DYNAMIC_TOKEN_DATA_FUNCTION; @@ -276,37 +275,11 @@ public class OAuth2AuthzEndpoint { private static final String OIDC_DIALECT = "http://wso2.org/oidc/claim"; - private static OpenIDConnectClaimFilterImpl openIDConnectClaimFilter; - - private static ScopeMetadataService scopeMetadataService; - private static DeviceAuthService deviceAuthService; private static final String AUTH_SERVICE_RESPONSE = "authServiceResponse"; private static final String IS_API_BASED_AUTH_HANDLED = "isApiBasedAuthHandled"; private static final ApiAuthnHandler API_AUTHN_HANDLER = new ApiAuthnHandler(); - public static OpenIDConnectClaimFilterImpl getOpenIDConnectClaimFilter() { - - return openIDConnectClaimFilter; - } - - public static void setOpenIDConnectClaimFilter(OpenIDConnectClaimFilterImpl openIDConnectClaimFilter) { - - OAuth2AuthzEndpoint.openIDConnectClaimFilter = openIDConnectClaimFilter; - } - - public static ScopeMetadataService getScopeMetadataService() { - - return scopeMetadataService; - } - - public static void setScopeMetadataService(ScopeMetadataService scopeMetadataService) { - - OAuth2AuthzEndpoint.scopeMetadataService = scopeMetadataService; - } - - private static Class oAuthAuthzRequestClass; - @GET @Path("/") @Consumes("application/x-www-form-urlencoded") @@ -1005,9 +978,11 @@ private ConsentClaimsData getConsentRequiredClaims(AuthenticatedUser user, Servi if (hasPromptContainsConsent(oAuth2Parameters)) { // Ignore all previous consents and get consent required claims - return getSSOConsentService().getConsentRequiredClaimsWithoutExistingConsents(serviceProvider, user); + return getSSOConsentService().getConsentRequiredClaimsWithoutExistingConsents( + serviceProvider, user); } else { - return getSSOConsentService().getConsentRequiredClaimsWithExistingConsents(serviceProvider, user); + return getSSOConsentService().getConsentRequiredClaimsWithExistingConsents( + serviceProvider, user); } } @@ -1147,7 +1122,7 @@ private void handleDeniedConsent(OAuthMessage oAuthMessage, AuthorizationRespons getOauth2Params(oAuthMessage).getApplicationName(), false, oauth2Params.getClientId()); - OAuthErrorDTO oAuthErrorDTO = EndpointUtil.getOAuth2Service().handleUserConsentDenial(oauth2Params); + OAuthErrorDTO oAuthErrorDTO = getOAuth2Service().handleUserConsentDenial(oauth2Params); OAuthProblemException consentDenialException = buildConsentDenialException(oAuthErrorDTO); if (ResponseModeProvider.AuthResponseType.POST_RESPONSE.equals(responseModeProvider.getAuthResponseType())) { @@ -1384,7 +1359,7 @@ private Response handleFailedAuthentication(OAuthMessage oAuthMessage, OAuth2Par AuthorizationResponseDTO authorizationResponseDTO) throws URISyntaxException { - OAuthErrorDTO oAuthErrorDTO = EndpointUtil.getOAuth2Service().handleAuthenticationFailure(oauth2Params); + OAuthErrorDTO oAuthErrorDTO = getOAuth2Service().handleAuthenticationFailure(oauth2Params); OAuthProblemException oauthException = buildOAuthProblemException(authnResult, oAuthErrorDTO); return handleFailedState(oAuthMessage, oauth2Params, oauthException, authorizationResponseDTO); } @@ -2355,9 +2330,9 @@ private void persistRequestObject(OAuth2Parameters params, RequestObject request throws RequestObjectException { String sessionDataKey = params.getSessionDataKey(); - if (EndpointUtil.getRequestObjectService() != null) { + if (getRequestObjectService() != null) { if (requestObject != null && MapUtils.isNotEmpty(requestObject.getRequestedClaims())) { - EndpointUtil.getRequestObjectService().addRequestObject(params.getClientId(), sessionDataKey, + getRequestObjectService().addRequestObject(params.getClientId(), sessionDataKey, new ArrayList(requestObject.getRequestedClaims().values())); params.setRequestObjectFlow(true); } @@ -3443,16 +3418,17 @@ private List getRequestedOidcClaimsList(ConsentClaimsData claimsF // Get the claims uri list of all the requested scopes. Eg:- country, email. List claimListOfScopes = - openIDConnectClaimFilter.getClaimsFilteredByOIDCScopes(oauth2Params.getScopes(), spTenantDomain); + OAuth2AuthzServiceFactory.getOpenIdClaimFilterImpl().getClaimsFilteredByOIDCScopes( + oauth2Params.getScopes(), spTenantDomain); List essentialRequestedClaims = new ArrayList<>(); if (oauth2Params.isRequestObjectFlow()) { // Get the requested claims came through request object. - List requestedClaimsOfIdToken = EndpointUtil.getRequestObjectService() + List requestedClaimsOfIdToken = getRequestObjectService() .getRequestedClaimsForSessionDataKey(oauth2Params.getSessionDataKey(), false); - List requestedClaimsOfUserInfo = EndpointUtil.getRequestObjectService() + List requestedClaimsOfUserInfo = getRequestObjectService() .getRequestedClaimsForSessionDataKey(oauth2Params.getSessionDataKey(), true); diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java new file mode 100644 index 00000000000..661e12843aa --- /dev/null +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. 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.wso2.carbon.identity.oauth.endpoint.authz; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImpl; + +/** + * Service holder for managing instances of OAuth2 Authorization related services. + */ +public class OAuth2AuthzServiceFactory { + + private static final OpenIDConnectClaimFilterImpl SERVICE; + + static { + OpenIDConnectClaimFilterImpl openIDConnectClaimFilter = (OpenIDConnectClaimFilterImpl) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(OpenIDConnectClaimFilterImpl.class, null); + if (openIDConnectClaimFilter == null) { + throw new IllegalStateException("OpenIDConnectClaimFilterImpl is not available from OSGi context."); + } + SERVICE = openIDConnectClaimFilter; + } + + public static OpenIDConnectClaimFilterImpl getOpenIdClaimFilterImpl() { + + return SERVICE; + } +} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpoint.java index e1da2d43456..c8d409a976c 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpoint.java @@ -35,7 +35,7 @@ import org.wso2.carbon.identity.oauth.endpoint.OAuthRequestWrapper; import org.wso2.carbon.identity.oauth.endpoint.exception.CibaAuthFailureException; import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException; -import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.CibaAuthServiceFactory; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.RequestObjectException; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; @@ -161,7 +161,8 @@ private CibaAuthCodeResponse getCibaAuthCodeResponse(CibaAuthCodeRequest cibaAut throws CibaAuthFailureException { try { - cibaAuthCodeResponse = EndpointUtil.getCibaAuthService().generateAuthCodeResponse(cibaAuthCodeRequest); + cibaAuthCodeResponse = CibaAuthServiceFactory.getCibaAuthService() + .generateAuthCodeResponse(cibaAuthCodeRequest); } catch (CibaCoreException | CibaClientException e) { throw new CibaAuthFailureException(OAuth2ErrorCodes.SERVER_ERROR, "Error while generating " + "authentication response.", e); diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java index e3d0d8b4199..79d577d33bd 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java @@ -37,7 +37,6 @@ import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; -import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; import org.wso2.carbon.identity.oauth2.device.codegenerator.GenerateKeys; import org.wso2.carbon.identity.oauth2.device.constants.Constants; import org.wso2.carbon.identity.oauth2.device.util.DeviceFlowUtil; @@ -61,12 +60,6 @@ @InInterceptors(classes = OAuthClientAuthenticatorProxy.class) public class DeviceEndpoint { private static final Log log = LogFactory.getLog(DeviceEndpoint.class); - private DeviceAuthService deviceAuthService; - - public void setDeviceAuthService(DeviceAuthService deviceAuthService) { - - this.deviceAuthService = deviceAuthService; - } @POST @Path("/") @@ -108,7 +101,8 @@ private String getUniqueUserCode(String deviceCode, String clientId, String scop String temporaryUserCode = GenerateKeys.getKey(OAuthServerConfiguration.getInstance().getDeviceCodeKeyLength()); long quantifier = GenerateKeys.getCurrentQuantifier(); - return deviceAuthService.generateDeviceResponse(deviceCode, temporaryUserCode, quantifier, clientId, scopes); + return DeviceServiceFactory.getDeviceAuthService().generateDeviceResponse(deviceCode, temporaryUserCode, + quantifier, clientId, scopes); } private void validateRepeatedParams(HttpServletRequest request, MultivaluedMap paramMap) diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java new file mode 100644 index 00000000000..f6bb6170ac9 --- /dev/null +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. 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.wso2.carbon.identity.oauth.endpoint.device; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; +import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthServiceImpl; + +/** + * Service holder for managing instances of Device Authentication related services. + */ +public class DeviceServiceFactory { + + private static final DeviceAuthServiceImpl SERVICE; + + static { + DeviceAuthServiceImpl deviceAuthService = (DeviceAuthServiceImpl) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(DeviceAuthServiceImpl.class, null); + if (deviceAuthService == null) { + throw new IllegalStateException("DeviceAuthService is not available from OSGi context."); + } + SERVICE = deviceAuthService; + } + + public static DeviceAuthService getDeviceAuthService() { + + return SERVICE; + } +} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java index 127a7aa3105..afff573f89c 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java @@ -33,7 +33,6 @@ import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; import org.wso2.carbon.identity.oauth2.device.constants.Constants; import org.wso2.carbon.identity.oauth2.device.dao.DeviceFlowPersistenceFactory; import org.wso2.carbon.identity.oauth2.device.model.DeviceFlowDO; @@ -63,12 +62,6 @@ public class UserAuthenticationEndpoint { public static final String INVALID_CODE_ERROR_KEY = "invalid.code"; private OAuth2AuthzEndpoint oAuth2AuthzEndpoint = new OAuth2AuthzEndpoint(); private DeviceFlowDO deviceFlowDO = new DeviceFlowDO(); - private DeviceAuthService deviceAuthService; - - public void setDeviceAuthService(DeviceAuthService deviceAuthService) { - - this.deviceAuthService = deviceAuthService; - } @POST @Path("/") @@ -89,10 +82,10 @@ public Response deviceAuthorize(@Context HttpServletRequest request, @Context Ht return Response.status(HttpServletResponse.SC_FOUND).location(URI.create(error)).build(); } DeviceFlowDO deviceFlowDODetails = - deviceAuthService.getDetailsByUserCode(userCode); + DeviceServiceFactory.getDeviceAuthService().getDetailsByUserCode(userCode); if (!isExpiredUserCode(deviceFlowDODetails)) { String clientId = deviceFlowDODetails.getConsumerKey(); - deviceAuthService.setAuthenticationStatus(userCode); + DeviceServiceFactory.getDeviceAuthService().setAuthenticationStatus(userCode); CommonAuthRequestWrapper commonAuthRequestWrapper = new CommonAuthRequestWrapper(request); commonAuthRequestWrapper.setParameter(Constants.CLIENT_ID, clientId); commonAuthRequestWrapper.setParameter(Constants.RESPONSE_TYPE, Constants.RESPONSE_TYPE_DEVICE); diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/CibaServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/CibaServiceFactory.java deleted file mode 100644 index a46e71617de..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/CibaServiceFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth.ciba.api.CibaAuthService; -import org.wso2.carbon.identity.oauth.ciba.api.CibaAuthServiceImpl; - -/** - * This class is used to register CibaAuthService as a factory bean. - */ -public class CibaServiceFactory extends AbstractFactoryBean { - - private CibaAuthServiceImpl cibaAuthService; - - @Override - public Class getObjectType() { - - return CibaAuthServiceImpl.class; - } - - @Override - protected CibaAuthServiceImpl createInstance() throws Exception { - - if (cibaAuthService != null) { - return cibaAuthService; - } else { - CibaAuthServiceImpl cibaAuthService = (CibaAuthServiceImpl) - PrivilegedCarbonContext.getThreadLocalCarbonContext(). - getOSGiService(CibaAuthService.class, null); - if (cibaAuthService != null) { - this.cibaAuthService = cibaAuthService; - } - return cibaAuthService; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/DeviceAuthServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/DeviceAuthServiceFactory.java deleted file mode 100644 index e3c737bcb37..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/DeviceAuthServiceFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; - -/** - * This class is used to register DeviceAuthService as a factory bean. - */ -public class DeviceAuthServiceFactory extends AbstractFactoryBean { - - private DeviceAuthService deviceAuthService; - - @Override - public Class getObjectType() { - - return DeviceAuthService.class; - } - - @Override - protected DeviceAuthService createInstance() throws Exception { - - if (this.deviceAuthService != null) { - return this.deviceAuthService; - } else { - DeviceAuthService deviceAuthService = (DeviceAuthService) - PrivilegedCarbonContext.getThreadLocalCarbonContext(). - getOSGiService(DeviceAuthService.class, null); - if (deviceAuthService != null) { - this.deviceAuthService = deviceAuthService; - } - return deviceAuthService; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/IDPManagerFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/IDPManagerFactory.java deleted file mode 100644 index a91b038495e..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/IDPManagerFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.idp.mgt.IdpManager; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the IDP Management service type of object inside the container. - */ -public class IDPManagerFactory extends AbstractFactoryBean { - - private IdpManager idpManager; - - @Override - public Class getObjectType() { - - return IdpManager.class; - } - - @Override - protected IdpManager createInstance() throws Exception { - - if (this.idpManager != null) { - return idpManager; - } else { - IdpManager idpManager = (IdpManager) PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getOSGiService(IdpManager.class, null); - if (idpManager != null) { - this.idpManager = idpManager; - } - return idpManager; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ScopeServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ScopeServiceFactory.java deleted file mode 100644 index 6cc13c943ec..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ScopeServiceFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth2.OAuth2ScopeService; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the OAuth2ScopeService type of object inside the container. - */ -public class OAuth2ScopeServiceFactory extends AbstractFactoryBean { - - private OAuth2ScopeService oAuth2ScopeService; - - @Override - public Class getObjectType() { - - return OAuth2ScopeService.class; - } - - @Override - protected OAuth2ScopeService createInstance() throws Exception { - - if (this.oAuth2ScopeService != null) { - return this.oAuth2ScopeService; - } else { - OAuth2ScopeService oAuth2ScopeService = (OAuth2ScopeService) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(OAuth2ScopeService.class, null); - if (oAuth2ScopeService != null) { - this.oAuth2ScopeService = oAuth2ScopeService; - } - return oAuth2ScopeService; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ServiceFactory.java deleted file mode 100644 index 57b9aabcf01..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuth2ServiceFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth2.OAuth2Service; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the OAuth2Service type of object inside the container. - */ -public class OAuth2ServiceFactory extends AbstractFactoryBean { - - private OAuth2Service oauth2Service; - - @Override - public Class getObjectType() { - - return OAuth2Service.class; - } - - @Override - protected OAuth2Service createInstance() throws Exception { - - if (this.oauth2Service != null) { - return this.oauth2Service; - } else { - OAuth2Service oauth2Service = (OAuth2Service) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(OAuth2Service.class, null); - if (oauth2Service != null) { - this.oauth2Service = oauth2Service; - } - return oauth2Service; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthAdminServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthAdminServiceFactory.java deleted file mode 100644 index 0d80643ff15..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthAdminServiceFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the OAuthAdminService type of object inside the container. - */ -public class OAuthAdminServiceFactory extends AbstractFactoryBean { - - private OAuthAdminServiceImpl oAuthAdminService; - - @Override - public Class getObjectType() { - - return OAuthAdminServiceImpl.class; - } - - @Override - protected OAuthAdminServiceImpl createInstance() throws Exception { - - if (this.oAuthAdminService != null) { - return this.oAuthAdminService; - } else { - OAuthAdminServiceImpl oAuthAdminService = (OAuthAdminServiceImpl) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(OAuthAdminServiceImpl.class, null); - if (oAuthAdminService != null) { - this.oAuthAdminService = oAuthAdminService; - } - return oAuthAdminService; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthServerConfigurationFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthServerConfigurationFactory.java deleted file mode 100644 index 75250a7ef7c..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OAuthServerConfigurationFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the OAuthServerConfiguration type of object inside the container. - */ -public class OAuthServerConfigurationFactory extends AbstractFactoryBean { - - private OAuthServerConfiguration oAuthServerConfiguration; - - @Override - public Class getObjectType() { - - return OAuthServerConfiguration.class; - } - - @Override - protected OAuthServerConfiguration createInstance() throws Exception { - - if (this.oAuthServerConfiguration != null) { - return this.oAuthServerConfiguration; - } else { - OAuthServerConfiguration oAuthServerConfiguration = (OAuthServerConfiguration) PrivilegedCarbonContext. - getThreadLocalCarbonContext().getOSGiService(OAuthServerConfiguration.class, null); - if (oAuthServerConfiguration != null) { - this.oAuthServerConfiguration = oAuthServerConfiguration; - } - return oAuthServerConfiguration; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OpenIDConnectClaimFilterFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OpenIDConnectClaimFilterFactory.java deleted file mode 100644 index a865e317d14..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/OpenIDConnectClaimFilterFactory.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilter; -import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImpl; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the OpenIDConnectClaimFilterImpl type of object inside the container. - */ -public class OpenIDConnectClaimFilterFactory extends AbstractFactoryBean { - - private OpenIDConnectClaimFilterImpl openIDConnectClaimFilter; - - @Override - public Class getObjectType() { - - return OpenIDConnectClaimFilterImpl.class; - } - - @Override - protected OpenIDConnectClaimFilterImpl createInstance() throws Exception { - - if (this.openIDConnectClaimFilter != null) { - return this.openIDConnectClaimFilter; - } else { - OpenIDConnectClaimFilterImpl openIDConnectClaimFilter = (OpenIDConnectClaimFilterImpl) - PrivilegedCarbonContext.getThreadLocalCarbonContext(). - getOSGiService(OpenIDConnectClaimFilter.class, null); - if (openIDConnectClaimFilter != null) { - this.openIDConnectClaimFilter = openIDConnectClaimFilter; - } - return openIDConnectClaimFilter; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/ParServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/ParServiceFactory.java deleted file mode 100644 index 64c060c442b..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/ParServiceFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.oauth.par.core.ParAuthService; - -/** - * PAR Service Factory. - */ -public class ParServiceFactory extends AbstractFactoryBean { - private ParAuthService parAuthService; - - @Override - public Class getObjectType() { - - return ParAuthService.class; - } - - @Override - protected ParAuthService createInstance() throws Exception { - - if (parAuthService != null) { - return parAuthService; - } - - ParAuthService parAuthService = (ParAuthService) - PrivilegedCarbonContext.getThreadLocalCarbonContext(). - getOSGiService(ParAuthService.class, null); - if (parAuthService != null) { - this.parAuthService = parAuthService; - } - return parAuthService; - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/RequestObjectServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/RequestObjectServiceFactory.java deleted file mode 100644 index cb9465cc3bc..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/RequestObjectServiceFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.openidconnect.RequestObjectService; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the RequestObjectService type of object inside the container. - */ -public class RequestObjectServiceFactory extends AbstractFactoryBean { - - private RequestObjectService requestObjectService; - - @Override - public Class getObjectType() { - - return RequestObjectService.class; - } - - @Override - protected RequestObjectService createInstance() throws Exception { - - if (this.requestObjectService != null) { - return this.requestObjectService; - } else { - RequestObjectService requestObjectService = (RequestObjectService) PrivilegedCarbonContext. - getThreadLocalCarbonContext().getOSGiService(RequestObjectService.class, null); - if (requestObjectService != null) { - this.requestObjectService = requestObjectService; - } - return requestObjectService; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/SSOConsentServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/SSOConsentServiceFactory.java deleted file mode 100644 index 7523727293b..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/factory/SSOConsentServiceFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.oauth.endpoint.factory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService; - -/** - * Factory Beans serves as a factory for creating other beans within the IOC container. This factory bean is used to - * instantiate the SSOConsentService type of object inside the container. - */ -public class SSOConsentServiceFactory extends AbstractFactoryBean { - - private SSOConsentService ssoConsentService; - - @Override - public Class getObjectType() { - - return SSOConsentService.class; - } - - @Override - protected SSOConsentService createInstance() throws Exception { - - if (this.ssoConsentService != null) { - return this.ssoConsentService; - } else { - SSOConsentService ssoConsentService = (SSOConsentService) PrivilegedCarbonContext. - getThreadLocalCarbonContext().getOSGiService(SSOConsentService.class, null); - if (ssoConsentService != null) { - this.ssoConsentService = ssoConsentService; - } - return ssoConsentService; - } - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java index 87b0088cc43..359fdb8eddc 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java @@ -21,7 +21,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.ServerConfigurationException; import org.wso2.carbon.identity.core.util.IdentityUtil; @@ -29,7 +28,7 @@ import org.wso2.carbon.identity.discovery.OIDCProcessor; import org.wso2.carbon.identity.discovery.builders.OIDProviderResponseBuilder; import org.wso2.carbon.identity.oauth.common.OAuthConstants; -import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OIDCProviderServiceFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -97,9 +96,9 @@ private boolean isValidIssuer(String issuer) { private Response getResponse(HttpServletRequest request, String tenant) { String response; - OIDCProcessor processor = EndpointUtil.getOIDCService(); + OIDCProcessor processor = OIDCProviderServiceFactory.getOIDCService(); try { - OIDProviderResponseBuilder responseBuilder = getOidProviderResponseBuilder(); + OIDProviderResponseBuilder responseBuilder = OIDCDiscoveryServiceFactory.getOIDProviderResponseBuilder(); response = responseBuilder.getOIDProviderConfigString(processor.getResponse(request, tenant)); } catch (OIDCDiscoveryEndPointException e) { Response.ResponseBuilder errorResponse = Response.status(processor.handleError(e)); @@ -112,15 +111,4 @@ private Response getResponse(HttpServletRequest request, String tenant) { Response.ResponseBuilder responseBuilder = Response.status(HttpServletResponse.SC_OK); return responseBuilder.entity(response).build(); } - - @Autowired - public void setOidProviderResponseBuilder(OIDProviderResponseBuilder oidProviderResponseBuilder) { - - this.oidProviderResponseBuilder = oidProviderResponseBuilder; - } - - public OIDProviderResponseBuilder getOidProviderResponseBuilder() { - - return this.oidProviderResponseBuilder; - } } diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java new file mode 100644 index 00000000000..d9fd4c64285 --- /dev/null +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. 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.wso2.carbon.identity.oauth.endpoint.oidcdiscovery; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.discovery.builders.OIDProviderResponseBuilder; + +/** + * Service holder for managing instances of OIDC Discovery related services. + */ +public class OIDCDiscoveryServiceFactory { + + private static final OIDProviderResponseBuilder SERVICE; + + static { + OIDProviderResponseBuilder oidProviderResponseBuilder = (OIDProviderResponseBuilder) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(OIDProviderResponseBuilder.class, null); + if (oidProviderResponseBuilder == null) { + throw new IllegalStateException("OIDProviderResponseBuilder is not available from OSGi context."); + } + SERVICE = oidProviderResponseBuilder; + } + + public static OIDProviderResponseBuilder getOIDProviderResponseBuilder() { + + return SERVICE; + } +} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpoint.java index 4f4479cb0a0..0b3f2886979 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpoint.java @@ -77,11 +77,11 @@ import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.RESPONSE_MODE; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.RESPONSE_TYPE; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.SCOPE; -import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuth2Service; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuthAuthzRequest; -import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getParAuthService; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getSPTenantDomainFromClientId; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateParams; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory.getOAuth2Service; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.ParAuthServiceFactory.getParAuthService; /** * REST implementation for OAuth2 PAR endpoint. diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpoint.java index 2643328de7b..b97fd313e41 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpoint.java @@ -69,9 +69,9 @@ import static org.wso2.carbon.identity.oauth.common.OAuthConstants.HTTP_RESP_HEADER_VAL_CACHE_CONTROL_NO_STORE; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.HTTP_RESP_HEADER_VAL_PRAGMA_NO_CACHE; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.extractCredentialsFromAuthzHeader; -import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuth2Service; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getRealmInfo; import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateParams; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory.getOAuth2Service; /** * Rest implementation for oauth revocation endpoint. diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/state/OAuthRequestStateValidator.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/state/OAuthRequestStateValidator.java index aa2ae22854c..a06d69fe4f5 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/state/OAuthRequestStateValidator.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/state/OAuthRequestStateValidator.java @@ -36,7 +36,7 @@ import static org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.AUTHENTICATION_RESPONSE; import static org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.INITIAL_REQUEST; import static org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.USER_CONSENT_RESPONSE; -import static org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuth2Service; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory.getOAuth2Service; /** * This class validate the OAuth request state. diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpoint.java index acff55c6e87..7120aa71608 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpoint.java @@ -42,6 +42,7 @@ import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException; import org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointBadRequestException; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory; import org.wso2.carbon.identity.oauth2.ResponseHeader; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO; @@ -383,7 +384,7 @@ private OAuth2AccessTokenRespDTO issueAccessToken(CarbonOAuthTokenRequest oauthR OAuth2AccessTokenReqDTO tokenReqDTO = buildAccessTokenReqDTO(oauthRequest, httpServletRequestWrapper, httpServletResponseWrapper); - return EndpointUtil.getOAuth2Service().issueAccessToken(tokenReqDTO); + return OAuth2ServiceFactory.getOAuth2Service().issueAccessToken(tokenReqDTO); } private OAuth2AccessTokenReqDTO buildAccessTokenReqDTO(CarbonOAuthTokenRequest oauthRequest, diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidator.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidator.java index c54f13bebb7..ecac085e6b6 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidator.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidator.java @@ -20,7 +20,7 @@ import org.apache.commons.lang.ArrayUtils; import org.apache.oltu.oauth2.common.error.OAuthError; import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; -import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2TokenValidatorServiceFactory; import org.wso2.carbon.identity.oauth.user.UserInfoAccessTokenValidator; import org.wso2.carbon.identity.oauth.user.UserInfoEndpointException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; @@ -61,7 +61,8 @@ public OAuth2TokenValidationResponseDTO validateToken(String accessTokenIdentifi accessToken.setTokenType("bearer"); accessToken.setIdentifier(accessTokenIdentifier); dto.setAccessToken(accessToken); - OAuth2TokenValidationResponseDTO response = EndpointUtil.getOAuth2TokenValidationService().validate(dto); + OAuth2TokenValidationResponseDTO response = OAuth2TokenValidatorServiceFactory + .getOAuth2TokenValidatorService().validate(dto); AccessTokenDO accessTokenDO; // invalid access token diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtil.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtil.java index 2c7fa73ccfb..6bfbb91868d 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtil.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtil.java @@ -44,7 +44,6 @@ import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry; import org.wso2.carbon.identity.application.authentication.framework.config.builder.FileBasedConfigurationBuilder; import org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException; -import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationRequest; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; @@ -62,19 +61,13 @@ import org.wso2.carbon.identity.core.URLBuilderException; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.discovery.DefaultOIDCProcessor; -import org.wso2.carbon.identity.discovery.OIDCProcessor; -import org.wso2.carbon.identity.discovery.builders.DefaultOIDCProviderRequestBuilder; -import org.wso2.carbon.identity.discovery.builders.OIDCProviderRequestBuilder; import org.wso2.carbon.identity.event.IdentityEventException; import org.wso2.carbon.identity.event.event.Event; import org.wso2.carbon.identity.event.services.IdentityEventService; import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException; -import org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl; import org.wso2.carbon.identity.oauth.cache.SessionDataCache; import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; import org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey; -import org.wso2.carbon.identity.oauth.ciba.api.CibaAuthServiceImpl; import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException; @@ -86,16 +79,13 @@ import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException; import org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointBadRequestException; import org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage; -import org.wso2.carbon.identity.oauth.par.core.ParAuthService; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory; import org.wso2.carbon.identity.oauth.par.exceptions.ParClientException; import org.wso2.carbon.identity.oauth.user.UserInfoEndpointException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeConsentException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException; -import org.wso2.carbon.identity.oauth2.OAuth2ScopeService; -import org.wso2.carbon.identity.oauth2.OAuth2Service; -import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.identity.oauth2.Oauth2ScopeConstants; import org.wso2.carbon.identity.oauth2.RequestObjectException; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; @@ -106,20 +96,15 @@ import org.wso2.carbon.identity.oauth2.model.OAuth2Parameters; import org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse; import org.wso2.carbon.identity.oauth2.scopeservice.OAuth2Resource; -import org.wso2.carbon.identity.oauth2.scopeservice.ScopeMetadataService; import org.wso2.carbon.identity.oauth2.util.AuthzUtil; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.identity.openidconnect.OIDCRequestObjectUtil; import org.wso2.carbon.identity.openidconnect.RequestObjectBuilder; -import org.wso2.carbon.identity.openidconnect.RequestObjectService; import org.wso2.carbon.identity.openidconnect.RequestObjectValidator; import org.wso2.carbon.identity.openidconnect.internal.OpenIDConnectServiceComponentHolder; import org.wso2.carbon.identity.openidconnect.model.RequestObject; -import org.wso2.carbon.identity.webfinger.DefaultWebFingerProcessor; -import org.wso2.carbon.identity.webfinger.WebFingerProcessor; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; import org.wso2.carbon.idp.mgt.IdentityProviderManager; -import org.wso2.carbon.idp.mgt.IdpManager; import org.wso2.carbon.utils.DiagnosticLog; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; @@ -157,6 +142,10 @@ import static org.wso2.carbon.identity.oauth.common.OAuthConstants.HTTP_REQ_HEADER_AUTH_METHOD_BASIC; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OauthAppStates.APP_STATE_ACTIVE; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.ResponseModes.JWT; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuthAdminServiceFactory.getOAuthAdminService; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuthServerConfigurationFactory.getOAuthServerConfiguration; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.Oauth2ScopeServiceFactory.getOAuth2ScopeService; +import static org.wso2.carbon.identity.oauth.endpoint.util.factory.ScopeMetadataServiceFactory.getScopeMetadataService; import static org.wso2.carbon.identity.oauth.par.common.ParConstants.PRE_HANDLE_PAR_REQUEST; import static org.wso2.carbon.identity.oauth.par.common.ParConstants.REQUEST_HEADERS; import static org.wso2.carbon.identity.oauth.par.common.ParConstants.REQUEST_PARAMETERS; @@ -185,154 +174,15 @@ public class EndpointUtil { private static final String REQUEST_URI = "request_uri"; private static final String NOT_AVAILABLE = "N/A"; private static final String UNKNOWN_ERROR = "unknown_error"; - private static OAuth2Service oAuth2Service; - private static OAuth2ScopeService oAuth2ScopeService; - private static OAuthAdminServiceImpl oAuthAdminService; - private static ScopeMetadataService scopeMetadataService; - private static SSOConsentService ssoConsentService; - private static OAuthServerConfiguration oauthServerConfiguration; - private static RequestObjectService requestObjectService; - private static CibaAuthServiceImpl cibaAuthService; - private static ParAuthService parAuthService; - private static IdpManager idpManager; private static final String ALLOW_ADDITIONAL_PARAMS_FROM_ERROR_URL = "OAuth.AllowAdditionalParamsFromErrorUrl"; private static final String KEEP_OIDC_SCOPES_IN_CONSENT_URL = "OAuth.KeepOIDCScopesInConsentURL"; private static final String IDP_ENTITY_ID = "IdPEntityId"; private static Class oAuthAuthzRequestClass; - public static void setIdpManager(IdpManager idpManager) { - - EndpointUtil.idpManager = idpManager; - } - - public static void setOAuth2Service(OAuth2Service oAuth2Service) { - - EndpointUtil.oAuth2Service = oAuth2Service; - } - - public static void setOAuth2ScopeService(OAuth2ScopeService oAuth2ScopeService) { - - EndpointUtil.oAuth2ScopeService = oAuth2ScopeService; - } - - public static void setOAuthAdminService(OAuthAdminServiceImpl oAuthAdminService) { - - EndpointUtil.oAuthAdminService = oAuthAdminService; - } - - public static void setSSOConsentService(SSOConsentService ssoConsentService) { - - EndpointUtil.ssoConsentService = ssoConsentService; - } - - public static void setOauthServerConfiguration(OAuthServerConfiguration oauthServerConfiguration) { - - EndpointUtil.oauthServerConfiguration = oauthServerConfiguration; - } - - public static void setRequestObjectService(RequestObjectService requestObjectService) { - - EndpointUtil.requestObjectService = requestObjectService; - } - - public static ScopeMetadataService getScopeMetadataService() { - - return scopeMetadataService; - } - - public static void setScopeMetadataService(ScopeMetadataService scopeMetadataService) { - - EndpointUtil.scopeMetadataService = scopeMetadataService; - } - private EndpointUtil() { } - /** - * Returns the registered {@code {@link SSOConsentService}} instance - * - * @return - */ - public static SSOConsentService getSSOConsentService() { - - return ssoConsentService; - } - - /** - * Returns the {@code DefaultWebFingerProcessor} instance - * - * @return DefaultWebFingerProcessor - */ - public static DefaultWebFingerProcessor getWebFingerService() { - - return (DefaultWebFingerProcessor) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService - (WebFingerProcessor.class, null); - } - - /** - * Returns the {@code OIDCProviderRequestBuilder} instance - * - * @return DefaultOIDCProviderRequestBuilder - */ - public static DefaultOIDCProviderRequestBuilder getOIDProviderRequestValidator() { - - return (DefaultOIDCProviderRequestBuilder) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService - (OIDCProviderRequestBuilder.class, null); - } - - /** - * Returns the {@code DefaultOIDCProcessor} instance - * - * @return DefaultOIDCProcessor - */ - public static DefaultOIDCProcessor getOIDCService() { - - return (DefaultOIDCProcessor) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService - (OIDCProcessor.class, null); - } - - /** - * Returns the {@code RequestObjectService} instance - * - * @return RequestObjectService - */ - public static RequestObjectService getRequestObjectService() { - - return requestObjectService; - } - - /** - * Returns the {@code OAuth2Service} instance - * - * @return OAuth2Service - */ - public static OAuth2Service getOAuth2Service() { - - return oAuth2Service; - } - - /** - * Returns the {@code OAuthServerConfiguration} instance - * - * @return OAuthServerConfiguration - */ - public static OAuthServerConfiguration getOAuthServerConfiguration() { - - return oauthServerConfiguration; - } - - /** - * Returns the {@code OAuthServerConfiguration} instance - * - * @return OAuth2TokenValidationService - */ - public static OAuth2TokenValidationService getOAuth2TokenValidationService() { - - return (OAuth2TokenValidationService) PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getOSGiService(OAuth2TokenValidationService.class, null); - } - /** * Returns the request validator class name * @@ -922,7 +772,7 @@ private static ServiceProvider getServiceProvider(OAuth2Parameters params) throw private static String getScopeMetadataQueryParam(Set scopes, String tenantDomain) { try { - List oidcScopeList = oAuthAdminService.getRegisteredOIDCScope(tenantDomain); + List oidcScopeList = getOAuthAdminService().getRegisteredOIDCScope(tenantDomain); List nonOidcScopeList = new ArrayList<>(); oidcScopeList.retainAll(scopes); nonOidcScopeList.addAll(scopes.stream().filter(scope -> @@ -931,7 +781,7 @@ private static String getScopeMetadataQueryParam(Set scopes, String tena if (nonOidcScopeList.isEmpty()) { return null; } - List scopesMetaData = scopeMetadataService.getMetadata(nonOidcScopeList); + List scopesMetaData = getScopeMetadataService().getMetadata(nonOidcScopeList); String scopeMetadata = new Gson().toJson(scopesMetaData); return "scopeMetadata=" + URLEncoder.encode(scopeMetadata, UTF_8); } catch (Exception e) { @@ -1067,7 +917,7 @@ public static boolean isUserAlreadyConsentedForOAuthScopes(AuthenticatedUser use } String userId = getUserIdOfAuthenticatedUser(user); String appId = getAppIdFromClientId(oAuth2Parameters.getClientId()); - return oAuth2ScopeService.hasUserProvidedConsentForAllRequestedScopes(userId, appId, + return getOAuth2ScopeService().hasUserProvidedConsentForAllRequestedScopes(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), scopesToBeConsented); } @@ -1107,25 +957,25 @@ public static void storeOAuthScopeConsent(AuthenticatedUser user, OAuth2Paramete log.debug("Overriding existing consents of the user : " + userId + " for application : " + appId); } - oAuth2ScopeService.addUserConsentForApplication(userId, appId, + getOAuth2ScopeService().addUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null); } else { - boolean isUserConsentExist = oAuth2ScopeService.isUserHasAnExistingConsentForApp( + boolean isUserConsentExist = getOAuth2ScopeService().isUserHasAnExistingConsentForApp( userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain())); if (isUserConsentExist) { if (log.isDebugEnabled()) { log.debug("Updating existing consents of the user : " + userId + " for application : " + appId); } - oAuth2ScopeService.updateUserConsentForApplication(userId, appId, + getOAuth2ScopeService().updateUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null); } else { if (log.isDebugEnabled()) { log.debug("Adding new consent to the user : " + userId + " for application : " + appId); } - oAuth2ScopeService.addUserConsentForApplication(userId, appId, + getOAuth2ScopeService().addUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null); } @@ -1165,7 +1015,7 @@ public static void storeOAuthScopeConsent(AuthenticatedUser user, OAuth2Paramete private static List getOIDCScopeNames() throws IdentityOAuthAdminException { - return Arrays.asList(ArrayUtils.nullToEmpty(oAuthAdminService.getScopeNames())); + return Arrays.asList(ArrayUtils.nullToEmpty(getOAuthAdminService().getScopeNames())); } /** @@ -1192,7 +1042,7 @@ private static List getRequestedOIDCScopes(OAuth2Parameters params) List requestedOIDCScopes = new ArrayList<>(); try { // Get registered OIDC scopes. - List oidcScopeList = oAuthAdminService.getRegisteredOIDCScope(params.getTenantDomain()); + List oidcScopeList = getOAuthAdminService().getRegisteredOIDCScope(params.getTenantDomain()); for (String scope : allowedScopes) { if (oidcScopeList.contains(scope)) { requestedOIDCScopes.add(scope.toLowerCase()); @@ -1222,7 +1072,7 @@ private static List dropOIDCAndUnregisteredScopesFromConsentRequiredScop /* If DropUnregisteredScopes scopes config is enabled then any unregistered scopes(excluding internal scopes and allowed scopes) will be dropped. Therefore, they will not be shown in the user consent screen.*/ - if (oauthServerConfiguration.isDropUnregisteredScopes()) { + if (getOAuthServerConfiguration().isDropUnregisteredScopes()) { if (log.isDebugEnabled()) { log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes."); } @@ -1234,7 +1084,7 @@ private static List dropOIDCAndUnregisteredScopesFromConsentRequiredScop allowedRegisteredScopes.addAll(allowedScopes); } else { // Get registered OIDC scopes. - String[] oidcScopes = oAuthAdminService.getScopeNames(); + String[] oidcScopes = getOAuthAdminService().getScopeNames(); List oidcScopeList = new ArrayList<>(Arrays.asList(oidcScopes)); for (String scope : allowedScopes) { if (!oidcScopeList.contains(scope)) { @@ -1265,7 +1115,7 @@ private static List filterConsentRequiredScopes(AuthenticatedUser user, if (user != null && !isPromptContainsConsent(params)) { String userId = getUserIdOfAuthenticatedUser(user); String appId = getAppIdFromClientId(params.getClientId()); - OAuth2ScopeConsentResponse existingUserConsent = oAuth2ScopeService.getUserConsentForApp( + OAuth2ScopeConsentResponse existingUserConsent = getOAuth2ScopeService().getUserConsentForApp( userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain())); if (existingUserConsent != null) { if (CollectionUtils.isNotEmpty(existingUserConsent.getApprovedScopes())) { @@ -1327,7 +1177,7 @@ private static Set dropUnregisteredScopes(OAuth2Parameters params) throw Set requestedScopes = new HashSet<>(params.getScopes()); Set registeredScopes = getRegisteredScopes(requestedScopes, params.getTenantDomain()); - List allowedScopesFromConfig = oauthServerConfiguration.getAllowedScopes(); + List allowedScopesFromConfig = getOAuthServerConfiguration().getAllowedScopes(); Set filteredScopes = new HashSet<>(); // Filtering allowed scopes. @@ -1360,7 +1210,8 @@ private static Set getRegisteredScopes(Set requestedScopes, Stri try { String requestedScopesStr = StringUtils.join(requestedScopes, " "); Set registeredScopes = new HashSet<>(); - Set registeredScopeSet = oAuth2ScopeService.getScopes(null, null, true, requestedScopesStr); + Set registeredScopeSet = getOAuth2ScopeService().getScopes(null, null, + true, requestedScopesStr); registeredScopeSet.forEach(scope -> registeredScopes.add(scope.getName())); if (!AuthzUtil.isLegacyAuthzRuntime()) { List registeredAPIScopes = getRegisteredAPIScopes(requestedScopes, tenantDomain); @@ -1544,7 +1395,7 @@ public static void startSuperTenantFlow() { */ public static void validateOauthApplication(String consumerKey) throws InvalidApplicationClientException { - String appState = EndpointUtil.getOAuth2Service().getOauthApplicationState(consumerKey); + String appState = OAuth2ServiceFactory.getOAuth2Service().getOauthApplicationState(consumerKey); DiagnosticLog.DiagnosticLogBuilder diagnosticLogBuilder = null; if (LoggerUtils.isDiagnosticLogsEnabled()) { @@ -1807,36 +1658,6 @@ private static void addStringToMap(String name, String value, Map { +public class ScopeMetadataServiceFactory { - private ScopeMetadataService scopeMetadataService; + private static final ScopeMetadataService SERVICE; - private static final Log log = LogFactory.getLog(ScopeServiceFactory.class); + private static final Log LOG = LogFactory.getLog(ScopeMetadataServiceFactory.class); - @Override - public Class getObjectType() { + static { + ScopeMetadataService scopeMetadataService = setScopeMetadataService(); - return ScopeMetadataService.class; + if (scopeMetadataService == null) { + throw new IllegalStateException("ScopeMetadataService is not available from OSGi context."); + } + SERVICE = scopeMetadataService; } - @Override - protected ScopeMetadataService createInstance() throws Exception { - - if (this.scopeMetadataService != null) { - return this.scopeMetadataService; - } + private static ScopeMetadataService setScopeMetadataService() { - ScopeMetadataService scopeMetadataService = getScopeMetadataService(); + ScopeMetadataService scopeMetadataService = getScopeMetadataServiceFromConfig(); if (scopeMetadataService != null) { - this.scopeMetadataService = scopeMetadataService; - return this.scopeMetadataService; + return scopeMetadataService; } + // Get the OSGi services registered for ScopeService interface. List scopeServices = PrivilegedCarbonContext .getThreadLocalCarbonContext().getOSGiServices(ScopeMetadataService.class, null); @@ -79,13 +75,12 @@ protected ScopeMetadataService createInstance() throws Exception { } if (scopeMetadataService == null) { - throw new IdentityOAuth2ServerException("ScopeMetadataService is not available."); + throw new IllegalStateException("ScopeMetadataService is not available from OSGi context."); } - this.scopeMetadataService = scopeMetadataService; - return this.scopeMetadataService; + return scopeMetadataService; } - private ScopeMetadataService getScopeMetadataService() { + private static ScopeMetadataService getScopeMetadataServiceFromConfig() { String scopeMetadataServiceClassName = OAuthServerConfiguration.getInstance() .getScopeMetadataExtensionImpl(); @@ -97,19 +92,24 @@ private ScopeMetadataService getScopeMetadataService() { if (obj instanceof ScopeMetadataService) { return (ScopeMetadataService) obj; } else { - log.error(scopeMetadataServiceClassName + " is not an instance of " + + LOG.error(scopeMetadataServiceClassName + " is not an instance of " + ScopeMetadataService.class.getName()); } } catch (ClassNotFoundException e) { - log.error("ClassNotFoundException while trying to find class " + scopeMetadataServiceClassName); + LOG.error("ClassNotFoundException while trying to find class " + scopeMetadataServiceClassName); } catch (InstantiationException e) { - log.error("InstantiationException while trying to instantiate class " + + LOG.error("InstantiationException while trying to instantiate class " + scopeMetadataServiceClassName); } catch (IllegalAccessException e) { - log.error("IllegalAccessException while trying to instantiate class " + + LOG.error("IllegalAccessException while trying to instantiate class " + scopeMetadataServiceClassName); } } return null; } + + public static ScopeMetadataService getScopeMetadataService() { + + return SERVICE; + } } diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java new file mode 100644 index 00000000000..e530993538b --- /dev/null +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. 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.wso2.carbon.identity.oauth.endpoint.util.factory; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.webfinger.DefaultWebFingerProcessor; +import org.wso2.carbon.identity.webfinger.WebFingerProcessor; + +/** + * Factory class for WebFingerService. + */ +public class WebFingerServiceFactory { + + private static final WebFingerProcessor SERVICE; + + static { + WebFingerProcessor webFingerService = (DefaultWebFingerProcessor) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(WebFingerProcessor.class, null); + + if (webFingerService == null) { + throw new IllegalStateException("WebFingerService is not available from OSGI context."); + } + SERVICE = webFingerService; + } + + public static WebFingerProcessor getWebFingerService() { + + return SERVICE; + } +} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/web.xml b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/web.xml index 5e45661d5fb..468487abc50 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/web.xml +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/web.xml @@ -75,9 +75,44 @@ OAuth2Endpoints - org.apache.cxf.transport.servlet.CXFServlet + org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet 1 + + jaxrs.serviceClasses + + org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint, + org.wso2.carbon.identity.oauth.endpoint.token.OAuth2TokenEndpoint, + org.wso2.carbon.identity.oauth.endpoint.introspection.OAuth2IntrospectionEndpoint, + org.wso2.carbon.identity.oauth.endpoint.revoke.OAuthRevocationEndpoint, + org.wso2.carbon.identity.oauth.endpoint.user.OpenIDConnectUserEndpoint, + org.wso2.carbon.identity.oauth.endpoint.jwks.JwksEndpoint, + org.wso2.carbon.identity.oauth.endpoint.oidcdiscovery.OIDCDiscoveryEndpoint, + org.wso2.carbon.identity.oauth.endpoint.device.DeviceEndpoint, + org.wso2.carbon.identity.oauth.endpoint.device.UserAuthenticationEndpoint, + org.wso2.carbon.identity.oauth.endpoint.ciba.OAuth2CibaEndpoint, + org.wso2.carbon.identity.oauth.endpoint.api.auth.ApiAuthnEndpoint, + org.wso2.carbon.identity.oauth.endpoint.par.OAuth2ParEndpoint + + + + jaxrs.address + / + + + jaxrs.providers + + org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper + + + + + jaxrs.inInterceptors + + org.wso2.carbon.identity.oauth.client.authn.filter.OAuthClientAuthenticatorProxy + + + diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpointTest.java index 145f6b2795b..66ad92c7e30 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpointTest.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017-2024, WSO2 LLC. (http://www.wso2.com). * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. 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 @@ -15,6 +15,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.identity.oauth.endpoint.authz; import com.nimbusds.jose.JOSEException; @@ -39,11 +40,17 @@ import org.apache.oltu.oauth2.common.message.types.ResponseType; import org.apache.oltu.oauth2.common.validators.OAuthValidator; import org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; @@ -53,6 +60,8 @@ import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus; import org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler; import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheEntry; @@ -60,6 +69,7 @@ import org.wso2.carbon.identity.application.authentication.framework.handler.request.RequestCoordinator; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService; +import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult; import org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper; @@ -99,11 +109,18 @@ import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; import org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore; import org.wso2.carbon.identity.oauth.endpoint.util.TestOAuthEndpointBase; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2TokenValidatorServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuthAdminServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuthServerConfigurationFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.Oauth2ScopeServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.SSOConsentServiceFactory; import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ClientException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.OAuth2ScopeService; import org.wso2.carbon.identity.oauth2.OAuth2Service; +import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.identity.oauth2.RequestObjectException; import org.wso2.carbon.identity.oauth2.authz.AuthorizationHandlerManager; import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; @@ -181,16 +198,18 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; @@ -203,6 +222,7 @@ public class OAuth2AuthzEndpointTest extends TestOAuthEndpointBase { + private static final Logger log = LoggerFactory.getLogger(OAuth2AuthzEndpointTest.class); @Mock HttpServletRequest httpServletRequest; @@ -254,7 +274,6 @@ public class OAuth2AuthzEndpointTest extends TestOAuthEndpointBase { @Mock OIDCSessionManager oidcSessionManager; - @Mock OAuthMessage oAuthMessage; @@ -285,6 +304,17 @@ public class OAuth2AuthzEndpointTest extends TestOAuthEndpointBase { @Mock private CentralLogMgtServiceComponentHolder centralLogMgtServiceComponentHolderMock; + @Mock + SSOConsentService mockedSSOConsentService; + + @Mock + OAuth2TokenValidationService oAuth2TokenValidator; + + @Mock + BundleContext bundleContext; + + MockedConstruction mockedConstruction; + private static final String ERROR_PAGE_URL = "https://localhost:9443/authenticationendpoint/oauth2_error.do"; private static final String LOGIN_PAGE_URL = "https://localhost:9443/authenticationendpoint/login.do"; private static final String USER_CONSENT_URL = @@ -335,7 +365,8 @@ public void setUp() throws Exception { // ignore } try { - createOAuthApp(INACTIVE_CLIENT_ID_VALUE, "dummySecret", USERNAME, INACTIVE_APP_NAME, "INACTIVE"); + createOAuthApp(INACTIVE_CLIENT_ID_VALUE, "dummySecret", USERNAME, INACTIVE_APP_NAME, + "INACTIVE"); } catch (JdbcSQLIntegrityConstraintViolationException e) { // ignore } @@ -350,24 +381,63 @@ public void setUp() throws Exception { @BeforeMethod public void setUpMethod() { - initMocks(this); + MockitoAnnotations.openMocks(this); identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); mockDatabase(identityDatabaseUtil); IdentityEventService identityEventService = mock(IdentityEventService.class); CentralLogMgtServiceComponentHolder.getInstance().setIdentityEventService(identityEventService); - } - @AfterClass - public void tearDown() throws Exception { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); - super.cleanData(); - CentralLogMgtServiceComponentHolder.getInstance().setIdentityEventService(null); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(OAuth2Service.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuth2Service}); + } + if (argumentCaptor.getValue().contains(OpenIDConnectClaimFilterImpl.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{openIDConnectClaimFilter}); + } + if (argumentCaptor.getValue().contains(SSOConsentService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{mockedSSOConsentService}); + } + if (argumentCaptor.getValue().contains(RequestObjectService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{requestObjectService}); + } + if (argumentCaptor.getValue().contains(OAuthAdminServiceImpl.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuthAdminService}); + } + if (argumentCaptor.getValue().contains(OAuth2ScopeService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuth2ScopeService}); + } + if (argumentCaptor.getValue().contains(OAuthServerConfiguration.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{mockOAuthServerConfiguration}); + } + if (argumentCaptor.getValue().contains(OAuth2TokenValidationService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuth2TokenValidator}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); } @AfterMethod public void tearDownMethod() { - identityDatabaseUtil.close(); + if (identityDatabaseUtil != null) { + identityDatabaseUtil.close(); + } + Mockito.reset(oAuth2ScopeService); + mockedConstruction.close(); + PrivilegedCarbonContext.endTenantFlow(); + } + + @AfterClass + public void tearDown() throws Exception { + + super.cleanData(); + CentralLogMgtServiceComponentHolder.getInstance().setIdentityEventService(null); } @DataProvider(name = "providePostParams") @@ -403,6 +473,7 @@ public void testAuthorizePost(Object paramObject, Map requestP try (MockedStatic oAuthServerConfiguration = mockStatic( OAuthServerConfiguration.class);) { + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); @@ -516,7 +587,12 @@ public void testAuthorize(Object flowStatusObject, String[] clientId, String ses Mockito.CALLS_REAL_METHODS); MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class); MockedStatic endpointUtil = mockStatic(EndpointUtil.class, - Mockito.CALLS_REAL_METHODS);) { + Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class); + MockedStatic oAuthAdminServiceFactory = + mockStatic(OAuthAdminServiceFactory.class); + MockedStatic oAuth2TokenValidatorServiceFactory = + mockStatic(OAuth2TokenValidatorServiceFactory.class);) { AuthenticatorFlowStatus flowStatus = (AuthenticatorFlowStatus) flowStatusObject; Map requestParams = new HashMap<>(); @@ -577,6 +653,13 @@ public void testAuthorize(Object flowStatusObject, String[] clientId, String ses new HashSet<>(Collections.singletonList(OAuthConstants.Scope.OPENID)), APP_NAME, null, null)); mockEndpointUtil(false, endpointUtil); + + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); + oAuthAdminServiceFactory.when(OAuthAdminServiceFactory::getOAuthAdminService) + .thenReturn(oAuthAdminService); + oAuth2TokenValidatorServiceFactory.when(OAuth2TokenValidatorServiceFactory + ::getOAuth2TokenValidatorService) + .thenReturn(oAuth2TokenValidator); when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE"); doCallRealMethod().when(oAuth2Service).validateInputParameters(httpServletRequest); if (ArrayUtils.isNotEmpty(clientId) && (clientId[0].equalsIgnoreCase("invalidId") || clientId[0] @@ -710,7 +793,8 @@ public void testAuthorizeForAuthenticationResponse(boolean isResultInRequest, bo throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class)) { + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic sessionDataCache = mockStatic(SessionDataCache.class); MockedStatic loggerUtils = mockStatic(LoggerUtils.class); @@ -725,8 +809,13 @@ public void testAuthorizeForAuthenticationResponse(boolean isResultInRequest, bo MockedStatic identityUtil = mockStatic(IdentityUtil.class, Mockito.CALLS_REAL_METHODS); MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class); + MockedStatic oAuth2ScopeServiceFactory = + mockStatic(Oauth2ScopeServiceFactory.class);) { + oAuth2ScopeServiceFactory.when(Oauth2ScopeServiceFactory::getOAuth2ScopeService) + .thenReturn(oAuth2ScopeService); sessionDataCache.when(SessionDataCache::getInstance).thenReturn(mockSessionDataCache); SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE); when(mockSessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry); @@ -806,11 +895,11 @@ public void testAuthorizeForAuthenticationResponse(boolean isResultInRequest, bo thenReturn(true); mockEndpointUtil(false, endpointUtil); + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE"); mockApplicationManagementService(); - mockEndpointUtil(false, endpointUtil); when(oAuth2Service.handleAuthenticationFailure(oAuth2Params)).thenReturn(oAuthErrorDTO); when(oAuth2ScopeService.hasUserProvidedConsentForAllRequestedScopes( anyString(), isNull(), anyInt(), anyList())).thenReturn(true); @@ -908,9 +997,9 @@ public void testUserConsentResponse(String consent, String redirectUrl, Set oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class)) { + mockSSOConsentService(true); mockOAuthServerConfiguration(oAuthServerConfiguration); - try (MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); @@ -920,7 +1009,8 @@ public void testUserConsentResponse(String consent, String redirectUrl, Set openIDConnectUserRPStore = mockStatic(OpenIDConnectUserRPStore.class); MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = + mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS);) { when(authCookie.getValue()).thenReturn("dummyValue"); frameworkUtils.when(() -> FrameworkUtils.getAuthCookie(any())).thenReturn(authCookie); @@ -939,7 +1029,6 @@ public void testUserConsentResponse(String consent, String redirectUrl, Set mappings = new HashSet<>(); ExternalClaim claim = new ExternalClaim(OIDC_DIALECT, "country", "http://wso2.org/country"); @@ -1149,7 +1238,8 @@ public void testHandleOAuthAuthorizationRequest(String clientId, String redirect throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class)) { + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class, Mockito.CALLS_REAL_METHODS); @@ -1160,8 +1250,10 @@ public void testHandleOAuthAuthorizationRequest(String clientId, String redirect MockedStatic oAuth2Util = mockStatic(OAuth2Util.class); MockedStatic oAuthURL = mockStatic(OAuth2Util.OAuthURL.class); MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class);) { + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); Map requestParams = new HashMap(); Map requestAttributes = new HashMap(); @@ -1299,7 +1391,7 @@ public void testHandleOAuthAuthorizationRequest(String clientId, String redirect @DataProvider(name = "provideRequestParams") public Object[][] provideRequestParams() { - initMocks(this); + MockitoAnnotations.openMocks(this); return addDiagnosticLogStatusToExistingDataProvider(new Object[][]{ {AuthenticatorFlowStatus.SUCCESS_COMPLETED, "sample_scope", HttpServletResponse.SC_FOUND} }); @@ -1310,7 +1402,7 @@ public void testTestAuthorize(Object flowStatusObject, String scope, int expecte boolean diagnosticLogsEnabled) throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class)) { mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class, Mockito.CALLS_REAL_METHODS); @@ -1325,8 +1417,14 @@ public void testTestAuthorize(Object flowStatusObject, String scope, int expecte MockedStatic oAuth2Util = mockStatic(OAuth2Util.class); MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); - MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class);) { + MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class); + MockedStatic oauth2ScopeServiceFactory = mockStatic( + Oauth2ScopeServiceFactory.class);) { + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); + oauth2ScopeServiceFactory.when(Oauth2ScopeServiceFactory::getOAuth2ScopeService).thenReturn( + oAuth2ScopeService); Map requestParams = new HashMap<>(); Map requestAttributes = new HashMap<>(); @@ -1342,7 +1440,8 @@ public void testTestAuthorize(Object flowStatusObject, String scope, int expecte (AuthenticatorFlowStatus) flowStatusObject); requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE); requestParams.put(REDIRECT_URI, new String[]{APP_REDIRECT_URL}); - AuthenticationResult result = setAuthenticationResult(true, null, null, null, null); + AuthenticationResult result = setAuthenticationResult(true, null, null, + null, null); result.getSubject().setAuthenticatedSubjectIdentifier("Impersonator"); requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result); @@ -1350,7 +1449,8 @@ public void testTestAuthorize(Object flowStatusObject, String scope, int expecte oAuthURL.when(OAuth2Util.OAuthURL::getOAuth2ErrorPageUrl).thenReturn(ERROR_PAGE_URL); - frameworkUtils.when(() -> FrameworkUtils.startTenantFlow(anyString())).thenAnswer(invocation -> null); + frameworkUtils.when(() -> FrameworkUtils.startTenantFlow(anyString())).thenAnswer( + invocation -> null); frameworkUtils.when(FrameworkUtils::endTenantFlow).thenAnswer(invocation -> null); loggerUtils.when(LoggerUtils::isDiagnosticLogsEnabled).thenReturn(diagnosticLogsEnabled); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn( @@ -1404,7 +1504,7 @@ public void testTestAuthorize(Object flowStatusObject, String scope, int expecte when(loginCacheEntry.getAuthzReqMsgCtx()).thenReturn(authzReqMsgCtx); when(oAuth2ScopeService.hasUserProvidedConsentForAllRequestedScopes( - anyString(), anyString(), anyInt(), anyList())).thenReturn(true); + anyString(), isNull(), anyInt(), anyList())).thenReturn(true); oAuth2Util.when(() -> OAuth2Util.getServiceProvider(CLIENT_ID_VALUE)).thenReturn(new ServiceProvider()); when(mockOAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(true); @@ -1448,7 +1548,8 @@ public void testTestAuthorize(Object flowStatusObject, String scope, int expecte public void testErrorWhenPARMandated() throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class)) { + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class, Mockito.CALLS_REAL_METHODS); @@ -1459,7 +1560,10 @@ public void testErrorWhenPARMandated() throws Exception { MockedStatic oAuth2Util = mockStatic(OAuth2Util.class); MockedStatic oAuthURL = mockStatic(OAuth2Util.OAuthURL.class); MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class);) { + + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); Map requestParams = new HashMap<>(); Map requestAttributes = new HashMap<>(); @@ -1579,7 +1683,8 @@ public void testHandleUserConsent(boolean isRespDTONull, String consent, boolean String expectedLocation) throws Exception { try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { + mockStatic(OAuthServerConfiguration.class)) { + mockSSOConsentService(false); oAuthServerConfiguration.when( OAuthServerConfiguration::getInstance).thenReturn(mockOAuthServerConfiguration); when(mockOAuthServerConfiguration.getAuthorizationCodeValidityPeriodInSeconds()).thenReturn(300L); @@ -1592,7 +1697,8 @@ public void testHandleUserConsent(boolean isRespDTONull, String consent, boolean MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class, Mockito.CALLS_REAL_METHODS); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class)) { Map requestParams = new HashMap<>(); Map requestAttributes = new HashMap<>(); @@ -1635,6 +1741,7 @@ public void testHandleUserConsent(boolean isRespDTONull, String consent, boolean } } mockEndpointUtil(false, endpointUtil); + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); when(oAuth2Service.authorize(any(OAuthAuthzReqMessageContext.class))).thenReturn(authzRespDTO); when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE"); @@ -1645,7 +1752,7 @@ public void testHandleUserConsent(boolean isRespDTONull, String consent, boolean oAuth2Util.when(() -> OAuth2Util.getServiceProvider(CLIENT_ID_VALUE)).thenReturn(new ServiceProvider()); mockApplicationManagementService(); - frameworkUtils.when(()-> FrameworkUtils.startTenantFlow(anyString())).thenAnswer(invocation -> null); + frameworkUtils.when(() -> FrameworkUtils.startTenantFlow(anyString())).thenAnswer(invocation -> null); frameworkUtils.when(FrameworkUtils::endTenantFlow).thenAnswer(invocation -> null); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn( MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -1718,8 +1825,13 @@ public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserAp boolean idTokenHintValid, String loggedInUser, String idTokenHintSubject, String errorCode) throws Exception { - try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + try (MockedStatic oAuthServerConfiguration = + mockStatic(OAuthServerConfiguration.class); + MockedStatic ssoConsentServiceFactory = + mockStatic(SSOConsentServiceFactory.class)) { + ssoConsentServiceFactory.when(SSOConsentServiceFactory::getSSOConsentService) + .thenReturn(mockedSSOConsentService); + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic sessionDataCache = mockStatic(SessionDataCache.class); MockedStatic openIDConnectUserRPStore = @@ -1732,9 +1844,12 @@ public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserAp Mockito.CALLS_REAL_METHODS); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class, Mockito.CALLS_REAL_METHODS); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class)) { - AuthenticationResult result = setAuthenticationResult(true, null, null, null, null); + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); + AuthenticationResult result = setAuthenticationResult(true, null, null, + null, null); result.getSubject().setAuthenticatedSubjectIdentifier(loggedInUser); Map requestParams = new HashMap<>(); @@ -1750,7 +1865,8 @@ public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserAp mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST); - OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<>(), APP_NAME, null, APP_REDIRECT_URL); + OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<>(), APP_NAME, null, + APP_REDIRECT_URL); oAuth2Params.setClientId(CLIENT_ID_VALUE); oAuth2Params.setPrompt(prompt); oAuth2Params.setIDTokenHint(idTokenHint); @@ -1804,7 +1920,8 @@ public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserAp frameworkUtils.when(() -> FrameworkUtils.resolveUserIdFromUsername(anyInt(), anyString(), anyString())) .thenReturn("sample"); - frameworkUtils.when(() -> FrameworkUtils.startTenantFlow(anyString())).thenAnswer(invocation -> null); + frameworkUtils.when(() -> FrameworkUtils.startTenantFlow(anyString())).thenAnswer( + invocation -> null); frameworkUtils.when(FrameworkUtils::endTenantFlow).thenAnswer(invocation -> null); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantId(nullable(String.class))) @@ -1831,7 +1948,7 @@ public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserAp "Location header not found in the response"); String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0)); assertFalse(location.isEmpty(), "Redirect URL is empty"); - + log.info("Redirect URL: " + location); if (errorCode != null) { assertTrue(location.contains(errorCode), "Expected error code not found in URL"); } @@ -1874,7 +1991,8 @@ public void testManageOIDCSessionState(Object cookieObject, Object sessionStateO throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class)) { + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic oAuthURL = mockStatic(OAuth2Util.OAuthURL.class); MockedStatic oidcSessionManagementUtil = @@ -1888,11 +2006,17 @@ public void testManageOIDCSessionState(Object cookieObject, Object sessionStateO Mockito.CALLS_REAL_METHODS); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class, Mockito.CALLS_REAL_METHODS); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuthServerConfigurationFactory = + mockStatic(OAuthServerConfigurationFactory.class); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class)) { + + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); Cookie opBrowserStateCookie = (Cookie) cookieObject; Cookie newOpBrowserStateCookie = new Cookie("opbs", "f6454r678776gffdgdsfafa"); OIDCSessionState previousSessionState = (OIDCSessionState) sessionStateObject; - AuthenticationResult result = setAuthenticationResult(true, null, null, null, null); + AuthenticationResult result = setAuthenticationResult(true, null, null, + null, null); Map requestParams = new HashMap<>(); Map requestAttributes = new HashMap<>(); @@ -1915,7 +2039,8 @@ public void testManageOIDCSessionState(Object cookieObject, Object sessionStateO oAuth2Params.setPrompt(OAuthConstants.Prompt.LOGIN); mockEndpointUtil(false, endpointUtil); - + oAuthServerConfigurationFactory.when(OAuthServerConfigurationFactory::getOAuthServerConfiguration) + .thenReturn(mockOAuthServerConfiguration); when(mockOAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(true); OAuth2AuthorizeRespDTO authzRespDTO = new OAuth2AuthorizeRespDTO(); @@ -1943,8 +2068,8 @@ public void testManageOIDCSessionState(Object cookieObject, Object sessionStateO , anyString())) .thenReturn("sessionStateValue"); oidcSessionManagementUtil.when( - () -> OIDCSessionManagementUtil.addSessionStateToURL(anyString(), anyString(), - isNull())).thenCallRealMethod(); + () -> OIDCSessionManagementUtil.addSessionStateToURL(anyString(), anyString(), + isNull())).thenCallRealMethod(); sessionDataCache.when(SessionDataCache::getInstance).thenReturn(mockSessionDataCache); SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE); @@ -2333,18 +2458,34 @@ public void testHandleOAuthAuthorizationRequest1(boolean showDisplayName, Object boolean diagnosticLogsEnabled) throws Exception { - try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + try (MockedStatic oAuthServerConfiguration = + mockStatic(OAuthServerConfiguration.class); + MockedStatic oAuthServerConfigurationFactory = + mockStatic(OAuthServerConfigurationFactory.class); + MockedStatic ssoConsentServiceFactory = + mockStatic(SSOConsentServiceFactory.class)) { + ssoConsentServiceFactory.when(SSOConsentServiceFactory::getSSOConsentService) + .thenReturn(mockedSSOConsentService); + oAuthServerConfigurationFactory.when(OAuthServerConfigurationFactory::getOAuthServerConfiguration) + .thenReturn(mockOAuthServerConfiguration); + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic centralLogMgtServiceComponentMock = mockStatic(CentralLogMgtServiceComponentHolder.class); MockedStatic sessionDataCache = mockStatic(SessionDataCache.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class); + MockedStatic oAuth2ScopeServiceFactory = + mockStatic(Oauth2ScopeServiceFactory.class)) { + + oAuth2ScopeServiceFactory.when(Oauth2ScopeServiceFactory::getOAuth2ScopeService) + .thenReturn(oAuth2ScopeService); ServiceProvider sp = (ServiceProvider) spObj; sp.setApplicationName(APP_NAME); + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); mockApplicationManagementService(sp); mockEndpointUtil(false, endpointUtil); @@ -2454,7 +2595,8 @@ public void testHandleOIDCRequestObjectForFAPI(boolean withRequestObject, Object String testName) throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class)) { + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); @@ -2585,12 +2727,21 @@ private static JWTClaimsSet getJwtClaimsSet(String issuer, String subject, Strin public void testIdentityOAuthAdminException() throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class);) { + OAuthServerConfiguration.class); + MockedStatic oAuthServerConfigurationFactory = + mockStatic(OAuthServerConfigurationFactory.class);) { + + oAuthServerConfigurationFactory.when(OAuthServerConfigurationFactory::getOAuthServerConfiguration) + .thenReturn(mockOAuthServerConfiguration); + mockSSOConsentService(false); mockOAuthServerConfiguration(oAuthServerConfiguration); try (MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); MockedStatic oAuthURL = mockStatic(OAuth2Util.OAuthURL.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class)) { + + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); //OAuthAdminException will not occur due to introduce a new Service to get the App State instead // directly use dao Map requestParams = new HashMap<>(); @@ -2666,39 +2817,14 @@ private void mockHttpRequest(final Map requestParams, when(httpServletRequest.getHeader("Authorization")).thenReturn(authHeader); } - private void mockEndpointUtil(boolean isConsentMgtEnabled, MockedStatic endpointUtil) - throws Exception { + private void mockEndpointUtil(boolean isConsentMgtEnabled, MockedStatic endpointUtil) { - endpointUtil.when(EndpointUtil::getOAuth2Service).thenReturn(oAuth2Service); endpointUtil.when(() -> EndpointUtil.getSPTenantDomainFromClientId(anyString())) .thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - - endpointUtil.when(EndpointUtil::getOAuthServerConfiguration).thenReturn(mockOAuthServerConfiguration); endpointUtil.when(() -> EndpointUtil.getUserConsentURL(any(OAuth2Parameters.class), - anyString(), anyString(), any(OAuthMessage.class), anyString())).thenReturn(USER_CONSENT_URL); - - endpointUtil.when(EndpointUtil::getRequestObjectService).thenReturn(requestObjectService); + anyString(), anyString(), any(OAuthMessage.class), anyString())).thenReturn(USER_CONSENT_URL); endpointUtil.when(() -> EndpointUtil.getLoginPageURL(anyString(), anyString(), anyBoolean(), - anyBoolean(), anySet(), anyMap(), any())).thenReturn(LOGIN_PAGE_URL); - EndpointUtil.setOAuthAdminService(oAuthAdminService); - EndpointUtil.setOAuth2ScopeService(oAuth2ScopeService); - - // TODO: Remove mocking consentUtil and test the consent flow as well - // https://github.com/wso2/product-is/issues/2679 - SSOConsentService ssoConsentService = mock(SSOConsentService.class); - when(ssoConsentService - .getConsentRequiredClaimsWithExistingConsents(any(ServiceProvider.class), any(AuthenticatedUser.class))) - .thenReturn(new ConsentClaimsData()); - - when(ssoConsentService - .getConsentRequiredClaimsWithoutExistingConsents(any(ServiceProvider.class), - any(AuthenticatedUser.class))) - .thenReturn(new ConsentClaimsData()); - - when(ssoConsentService.isSSOConsentManagementEnabled(any())).thenReturn(isConsentMgtEnabled); - - endpointUtil.when(EndpointUtil::getSSOConsentService).thenReturn(ssoConsentService); - + anyBoolean(), anySet(), anyMap(), any())).thenReturn(LOGIN_PAGE_URL); } private AuthenticationResult setAuthenticationResult(boolean isAuthenticated, Map attributes, @@ -3043,4 +3169,19 @@ private void setSupportedResponseModes() throws ClassNotFoundException, Instanti OAuth2ServiceComponentHolder.setResponseModeProviders(supportedResponseModeProviders); OAuth2ServiceComponentHolder.setDefaultResponseModeProvider(defaultResponseModeProvider); } + + private void mockSSOConsentService(boolean isConsentMgtEnabled) throws SSOConsentServiceException { + + // TODO: Remove mocking consentUtil and test the consent flow as well + // https://github.com/wso2/product-is/issues/2679 +// SSOConsentService ssoConsentService = mock(SSOConsentService.class); + when(mockedSSOConsentService + .getConsentRequiredClaimsWithExistingConsents(any(ServiceProvider.class), any(AuthenticatedUser.class))) + .thenReturn(new ConsentClaimsData()); + when(mockedSSOConsentService + .getConsentRequiredClaimsWithoutExistingConsents(any(ServiceProvider.class), + any(AuthenticatedUser.class))).thenReturn(new ConsentClaimsData()); + + when(mockedSSOConsentService.isSSOConsentManagementEnabled(any())).thenReturn(isConsentMgtEnabled); + } } diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpointTest.java index 7c68c442afe..9cb9bde922a 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/ciba/OAuth2CibaEndpointTest.java @@ -19,22 +19,30 @@ package org.wso2.carbon.identity.oauth.endpoint.ciba; import org.junit.Assert; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.testng.MockitoTestNGListener; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.core.ServiceURL; import org.wso2.carbon.identity.core.ServiceURLBuilder; import org.wso2.carbon.identity.core.URLBuilderException; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.oauth.ciba.api.CibaAuthService; import org.wso2.carbon.identity.oauth.ciba.api.CibaAuthServiceImpl; import org.wso2.carbon.identity.oauth.ciba.common.CibaConstants; import org.wso2.carbon.identity.oauth.ciba.model.CibaAuthCodeResponse; @@ -43,6 +51,7 @@ import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; import org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.CibaAuthServiceFactory; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.identity.openidconnect.CIBARequestObjectValidatorImpl; @@ -64,11 +73,14 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @WithCarbonHome @@ -99,7 +111,9 @@ public class OAuth2CibaEndpointTest { Response response; @Mock - CIBARequestObjectValidatorImpl cibaRequestObjectValidator; + BundleContext bundleContext; + + MockedConstruction mockedConstruction; private MockedStatic oAuthServerConfiguration; private MockedStatic oAuth2Util; @@ -121,13 +135,20 @@ public class OAuth2CibaEndpointTest { CibaAuthCodeResponse authCodeResponse = new CibaAuthCodeResponse(); String[] scopes = new String[]{"scope1", "scope2", OAuthConstants.Scope.OPENID}; + @BeforeClass + public void setUpClass() { + + System.setProperty(CarbonBaseConstants.CARBON_HOME, Paths.get(System.getProperty("user.dir"), + "src", "test", "resources").toString()); + } + @BeforeMethod public void setUp() throws Exception { System.setProperty( CarbonBaseConstants.CARBON_HOME, Paths.get(System.getProperty("user.dir"), "src", "test", "resources").toString() - ); + ); oAuth2CibaEndpoint = new OAuth2CibaEndpoint(); oAuthServerConfiguration = mockStatic(OAuthServerConfiguration.class); @@ -150,6 +171,19 @@ public void setUp() throws Exception { .thenReturn("https://localhost:9443/oauth2/token"); serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(CibaAuthService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{authService}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); } @AfterMethod @@ -159,6 +193,7 @@ public void tearDown() { oAuth2Util.close(); endpointUtil.close(); serviceURLBuilder.close(); + mockedConstruction.close(); } @DataProvider(name = "provideRequestParamsForBadRequest") @@ -324,20 +359,23 @@ public void testCibaForProperRequest() throws Exception { "suBggOdBCjn1NyprpJoEg"}); try (MockedStatic loggerUtils = mockStatic(LoggerUtils.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic cibaAuthServiceFactory = + mockStatic(CibaAuthServiceFactory.class);) { loggerUtils.when(LoggerUtils::isDiagnosticLogsEnabled).thenReturn(true); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantId(anyString())) .thenReturn(MultitenantConstants.SUPER_TENANT_ID); - when(httpServletRequest.getParameterNames()).thenReturn(Collections.enumeration(requestParams.keySet())); + when(httpServletRequest.getParameterNames()).thenReturn(Collections.enumeration( + requestParams.keySet())); when(httpServletRequest.getParameter(REQUEST_ATTRIBUTE)).thenReturn( - "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJaenhtRHFxSzhZWWZqdGxPaDl2dzg1cW5OVm9hIiwiYXVkIjoiaHR0cHM6Ly9sb2Nh" + - "bGhvc3Q6OTQ0My9vYXV0aDIvY2liYSIsImJpbmRpbmdfbWVzc2FnZSI6InRyeSIsImxvZ2luX2hpbnQiOiJ2aXZlayI" + - "sInNjb3BlIjoib3BlbmlkIHNjb3BlMSBzY29wZXgiLCJpYXQiOjExMjg3MTQyMTksImV4cCI6OTYyODcxNDIxOSwib" + - "mJmIjoxMTI4NzE0MjE5LCJhY3IiOiI1Nzg4ODc4OCIsImp0aSI6IjlmZjg0NWI5LTIwYmYtNDAzMy05ZWQzLTNjY2M" + - "2M2Y1MjA0YyIsInRyYW5zYWN0aW9uX2NvbnRleHQiOnsidXNlciI6InVzZXIiLCJhbW91bnQiOjEwMDAsInNob3AiO" + - "iJXU08yIENJQkEgREVNTyBDT05TT0xFIiwiYXBwbGljYXRpb24iOiJQYXlIZXJlIn19.Sx_MjjautinmOV9vvP8yhu" + - "suBggOdBCjn1NyprpJoEg"); + "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJaenhtRHFxSzhZWWZqdGxPaDl2dzg1cW5OVm9hIiwiYXVkIjoiaHR0cHM" + + "6Ly9sb2NhbGhvc3Q6OTQ0My9vYXV0aDIvY2liYSIsImJpbmRpbmdfbWVzc2FnZSI6InRyeSIsImxvZ2luX2" + + "hpbnQiOiJ2aXZlayIsInNjb3BlIjoib3BlbmlkIHNjb3BlMSBzY29wZXgiLCJpYXQiOjExMjg3MTQyMTksI" + + "mV4cCI6OTYyODcxNDIxOSwibmJmIjoxMTI4NzE0MjE5LCJhY3IiOiI1Nzg4ODc4OCIsImp0aSI6IjlmZjg0" + + "NWI5LTIwYmYtNDAzMy05ZWQzLTNjY2M2M2Y1MjA0YyIsInRyYW5zYWN0aW9uX2NvbnRleHQiOnsidXNlciI" + + "6InVzZXIiLCJhbW91bnQiOjEwMDAsInNob3AiOiJXU08yIENJQkEgREVNTyBDT05TT0xFIiwiYXBwbGljYX" + + "Rpb24iOiJQYXlIZXJlIn19.Sx_MjjautinmOV9vvP8yhusuBggOdBCjn1NyprpJoEg"); OAuthClientAuthnContext oAuthClientAuthnContext = new OAuthClientAuthnContext(); oAuthClientAuthnContext.setAuthenticated(true); oAuthClientAuthnContext.setClientId("ZzxmDqqK8YYfjtlOh9vw85qnNVoa"); @@ -358,15 +396,15 @@ public void testCibaForProperRequest() throws Exception { when(oauthServerConfigurationMock.getCIBARequestObjectValidator()).thenReturn(requestObjectValidator); doReturn(true).when(requestObjectValidator).validateSignature(any(), any()); - RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder(); + RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = + new RequestParamRequestObjectBuilder(); Map requestObjectBuilderMap = new HashMap<>(); requestObjectBuilderMap.put(REQUEST_PARAM_VALUE_BUILDER, requestParamRequestObjectBuilder); when((oauthServerConfigurationMock.getRequestObjectBuilders())).thenReturn(requestObjectBuilderMap); mockServiceURLBuilder(serviceURLBuilder); - endpointUtil.when(EndpointUtil::getCibaAuthService).thenReturn(authService); - endpointUtil.when(EndpointUtil::getCibaAuthService).thenReturn(authService); + cibaAuthServiceFactory.when(CibaAuthServiceFactory::getCibaAuthService).thenReturn(authService); when(authService.generateAuthCodeResponse(any())).thenReturn(authCodeResponse); CibaAuthzHandler cibaAuthzHandler = new CibaAuthzHandler(); @@ -379,6 +417,7 @@ public void testCibaForProperRequest() throws Exception { Response response = oAuth2CibaEndpoint.ciba(httpServletRequest, httpServletResponse, new MultivaluedHashMap()); Assert.assertEquals(200, response.getStatus()); + } } @@ -387,6 +426,7 @@ private void mockServiceURLBuilder(MockedStatic serviceURLBui ServiceURLBuilder builder = new ServiceURLBuilder() { String path = ""; + @Override public ServiceURLBuilder addPath(String... strings) { diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java index ff8abb073ec..57b5d05e506 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java @@ -21,12 +21,16 @@ import org.apache.oltu.oauth2.common.OAuth; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.junit.Assert; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.mockito.testng.MockitoTestNGListener; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; @@ -34,6 +38,8 @@ import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.core.ServiceURL; import org.wso2.carbon.identity.core.ServiceURLBuilder; @@ -67,9 +73,13 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Use for unit tests in device end-point. @@ -92,12 +102,20 @@ public class DeviceEndpointTest extends TestOAuthEndpointBase { @Mock DeviceFlowPersistenceFactory deviceFlowPersistenceFactory; + @Mock + DeviceAuthServiceImpl deviceAuthService; + @Mock DeviceFlowDAO deviceFlowDAO; @Mock HttpServletRequest request; + @Mock + BundleContext bundleContext; + + MockedConstruction mockedConstruction; + private static final String CLIENT_ID_VALUE = "ca19a540f544777860e44e75f605d927"; private static final String TEST_URL = "testURL"; @@ -119,6 +137,19 @@ public void setUp() throws Exception { loggerUtils.when(LoggerUtils::isDiagnosticLogsEnabled).thenReturn(true); identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); mockDatabase(identityDatabaseUtil); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(DeviceAuthServiceImpl.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{deviceAuthService}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); } @AfterMethod @@ -126,6 +157,8 @@ public void tearDown() { loggerUtils.close(); identityDatabaseUtil.close(); + mockedConstruction.close(); + PrivilegedCarbonContext.endTenantFlow(); } @DataProvider(name = "provideValues") @@ -184,7 +217,7 @@ public static Object[][] errorResponseValues() { * @param expectedStatus Expected status for response. * @param status Status of user code. * @throws IdentityOAuth2Exception If failed at device endpoint - * @throws OAuthSystemException If failed at device endpoint. + * @throws OAuthSystemException If failed at device endpoint. */ @Test(dataProvider = "dataValues") public void testDevice(String clientId, int expectedStatus, boolean status) @@ -195,7 +228,7 @@ public void testDevice(String clientId, int expectedStatus, boolean status) MockedStatic deviceFlowPersistenceFactory = mockStatic(DeviceFlowPersistenceFactory.class); MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { + mockStatic(OAuthServerConfiguration.class)) { DeviceEndpoint deviceEndpoint = spy(new DeviceEndpoint()); mockOAuthServerConfiguration(oAuthServerConfiguration); @@ -212,8 +245,6 @@ public void testDevice(String clientId, int expectedStatus, boolean status) oAuthClientAuthnContext.setClientId(clientId); oAuthClientAuthnContext.setAuthenticated(status); lenient().when(request.getAttribute(anyString())).thenReturn(oAuthClientAuthnContext); - DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl(); - deviceEndpoint.setDeviceAuthService(deviceAuthService); lenient().when(httpServletRequest.getParameter(anyString())).thenReturn(clientId); lenient().when(httpServletRequest.getAttribute(OAuthConstants.CLIENT_AUTHN_CONTEXT)) diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java index 2855ed65c01..0ddf4f105f8 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java @@ -31,6 +31,7 @@ import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper; import org.wso2.carbon.identity.core.ServiceURL; import org.wso2.carbon.identity.core.ServiceURLBuilder; @@ -110,6 +111,9 @@ public class UserAuthenticationEndpointTest extends TestOAuthEndpointBase { @Mock ServiceURL serviceURL; + @Mock + PrivilegedCarbonContext mockPrivilegedCarbonContext; + private static final String TEST_USER_CODE = "testUserCode"; private static final String TEST_URL = "testURL"; private static final String PENDING = "PENDING"; @@ -148,6 +152,7 @@ public void setUp() throws Exception { public void tearDown() throws Exception { cleanData(); + PrivilegedCarbonContext.endTenantFlow(); } @BeforeMethod @@ -189,9 +194,17 @@ public void testDeviceAuthorize(String userCode, String clientId, int expectedVa throws Exception { try (MockedStatic oAuthServerConfiguration = mockStatic( - OAuthServerConfiguration.class)) { - mockOAuthServerConfiguration(oAuthServerConfiguration); + OAuthServerConfiguration.class); + MockedStatic privilegedCarbonContext + = mockStatic(PrivilegedCarbonContext.class)) { + DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl(); + privilegedCarbonContext.when( + PrivilegedCarbonContext::getThreadLocalCarbonContext).thenReturn(mockPrivilegedCarbonContext); + lenient().when(mockPrivilegedCarbonContext.getOSGiService(DeviceAuthServiceImpl.class, null)) + .thenReturn(deviceAuthService); + + mockOAuthServerConfiguration(oAuthServerConfiguration); setInternalState(userAuthenticationEndpoint, "oAuth2AuthzEndpoint", oAuth2AuthzEndpoint); try (MockedStatic deviceFlowPersistenceFactory = @@ -224,9 +237,7 @@ public void testDeviceAuthorize(String userCode, String clientId, int expectedVa lenient().when(oAuth2AuthzEndpoint.authorize(any(CommonAuthRequestWrapper.class), any(HttpServletResponse.class))).thenReturn(response); - DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl(); userAuthenticationEndpoint = new UserAuthenticationEndpoint(); - userAuthenticationEndpoint.setDeviceAuthService(deviceAuthService); setInternalState(userAuthenticationEndpoint, "oAuth2AuthzEndpoint", oAuth2AuthzEndpoint); response1 = userAuthenticationEndpoint.deviceAuthorize(httpServletRequest, httpServletResponse); Assert.assertNotNull(response1); @@ -282,7 +293,8 @@ public void testDeviceAuthorizeForURLBuilderExceptionPath(String userCode, Strin mockStatic(DeviceFlowPersistenceFactory.class); MockedStatic oAuth2Util = mockStatic(OAuth2Util.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class);) { + MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + MockedStatic deviceServiceHolder = mockStatic(DeviceServiceFactory.class);) { deviceFlowPersistenceFactory.when( DeviceFlowPersistenceFactory::getInstance).thenReturn(mockDeviceFlowPersistenceFactory); @@ -310,8 +322,10 @@ public void testDeviceAuthorizeForURLBuilderExceptionPath(String userCode, Strin any(HttpServletResponse.class))). thenReturn(response); DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl(); + deviceServiceHolder.when(DeviceServiceFactory::getDeviceAuthService).thenReturn(deviceAuthService); + userAuthenticationEndpoint = new UserAuthenticationEndpoint(); - userAuthenticationEndpoint.setDeviceAuthService(deviceAuthService); + setInternalState(userAuthenticationEndpoint, "oAuth2AuthzEndpoint", oAuth2AuthzEndpoint); response1 = userAuthenticationEndpoint.deviceAuthorize(httpServletRequest, httpServletResponse); if (expectedValue == HttpServletResponse.SC_ACCEPTED) { @@ -356,7 +370,9 @@ public void testDeviceAuthorizeForIOExceptionPath(String userCode, String client mockStatic(DeviceFlowPersistenceFactory.class); MockedStatic oAuth2Util = mockStatic(OAuth2Util.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class);) { + MockedStatic serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + MockedStatic deviceServiceHolder = mockStatic(DeviceServiceFactory.class);) { + deviceFlowPersistenceFactory.when( DeviceFlowPersistenceFactory::getInstance).thenReturn(mockDeviceFlowPersistenceFactory); when(mockDeviceFlowPersistenceFactory.getDeviceFlowDAO()).thenReturn(deviceFlowDAO); @@ -381,9 +397,11 @@ public void testDeviceAuthorizeForIOExceptionPath(String userCode, String client lenient().when(oAuth2AuthzEndpoint.authorize(any(CommonAuthRequestWrapper.class), any(HttpServletResponse.class))).thenReturn(response); + DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl(); + deviceServiceHolder.when(DeviceServiceFactory::getDeviceAuthService).thenReturn(deviceAuthService); + userAuthenticationEndpoint = new UserAuthenticationEndpoint(); - userAuthenticationEndpoint.setDeviceAuthService(deviceAuthService); setInternalState(userAuthenticationEndpoint, "oAuth2AuthzEndpoint", oAuth2AuthzEndpoint); response1 = userAuthenticationEndpoint.deviceAuthorize(httpServletRequest, httpServletResponse); if (expectedValue == HttpServletResponse.SC_ACCEPTED) { diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpointTest.java index 6f9e92dcf23..230ff4c6c02 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpointTest.java @@ -1,37 +1,49 @@ /* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2019-2024, WSO2 LLC. (http://www.wso2.com). * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * WSO2 LLC. 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. + * 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.wso2.carbon.identity.oauth.endpoint.oidcdiscovery; import org.junit.Assert; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.testng.MockitoTestNGListener; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; +import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.discovery.DefaultOIDCProcessor; import org.wso2.carbon.identity.discovery.OIDCDiscoveryEndPointException; +import org.wso2.carbon.identity.discovery.OIDCProcessor; import org.wso2.carbon.identity.discovery.OIDProviderConfigResponse; +import org.wso2.carbon.identity.discovery.builders.OIDProviderResponseBuilder; import org.wso2.carbon.identity.oauth.common.OAuthConstants; -import org.wso2.carbon.identity.oauth.endpoint.oidcdiscovery.impl.OIDProviderJSONResponseBuilder; -import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OIDCProviderServiceFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -44,12 +56,17 @@ import javax.ws.rs.core.Response; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * This class does unit test coverage for OIDCDiscoveryEndpoint class. */ +@WithCarbonHome @Listeners(MockitoTestNGListener.class) public class OIDCDiscoveryEndpointTest { @@ -62,6 +79,14 @@ public class OIDCDiscoveryEndpointTest { @Mock DefaultOIDCProcessor defaultOIDCProcessor; + @Mock + OIDProviderResponseBuilder oidProviderResponseBuilder; + + @Mock + BundleContext bundleContext; + + MockedConstruction mockedConstruction; + private OIDCDiscoveryEndpoint oidcDiscoveryEndpoint; private Object identityUtilObj; @@ -73,6 +98,33 @@ public void setUp() throws Exception { identityUtilObj = clazz.newInstance(); } + @BeforeMethod + public void setUpMethod() { + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(OIDProviderResponseBuilder.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oidProviderResponseBuilder}); + } + if (argumentCaptor.getValue().contains(OIDCProcessor.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{defaultOIDCProcessor}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); + } + + @AfterMethod + public void tearDown() { + + mockedConstruction.close(); + PrivilegedCarbonContext.endTenantFlow(); + } + @DataProvider(name = "provideDataForGetOIDProviderConfigurationTokenEndpoint") public Object[][] provideDataGetOIDProviderConfigurationTokenEndpoint() { @@ -118,18 +170,24 @@ protected Map initialValue() { threadLocalPropertiesField.setAccessible(true); threadLocalPropertiesField.set(identityUtilObj, threadLocalProperties); - try (MockedStatic endpointUtil = mockStatic(EndpointUtil.class)) { - endpointUtil.when(EndpointUtil::getOIDCService).thenReturn(defaultOIDCProcessor); - lenient().when(defaultOIDCProcessor.getResponse(any(HttpServletRequest.class), any(String.class))) - .thenReturn(oidProviderConfigResponse); + try (MockedStatic oidcProviderServiceFactory = + mockStatic(OIDCProviderServiceFactory.class); + MockedStatic oidcDiscoveryServiceFactory = + mockStatic(OIDCDiscoveryServiceFactory.class)) { + + oidcDiscoveryServiceFactory.when(OIDCDiscoveryServiceFactory::getOIDProviderResponseBuilder) + .thenReturn(oidProviderResponseBuilder); + oidcProviderServiceFactory.when(OIDCProviderServiceFactory::getOIDCService) + .thenReturn(defaultOIDCProcessor); + lenient().when(defaultOIDCProcessor.getResponse(any(), any())).thenReturn(oidProviderConfigResponse); lenient().when(oidProviderConfigResponse.getConfigMap()).thenReturn(configMap); lenient().when(defaultOIDCProcessor.handleError(any(OIDCDiscoveryEndPointException.class))) .thenReturn(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - oidcDiscoveryEndpoint.setOidProviderResponseBuilder(new OIDProviderJSONResponseBuilder()); Response response = oidcDiscoveryEndpoint.getOIDProviderConfiguration(tokenEp, httpServletRequest); Assert.assertEquals(expectedResponse, response.getStatus()); threadLocalProperties.get().remove(OAuthConstants.TENANT_NAME_FROM_CONTEXT); } + } private Map getSampleConfigMap() { diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpointTest.java index ac6ca0462ed..dc4ed562aae 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/par/OAuth2ParEndpointTest.java @@ -24,10 +24,14 @@ import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.validators.OAuthValidator; import org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.testng.MockitoTestNGListener; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; @@ -36,6 +40,8 @@ import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; @@ -47,7 +53,10 @@ import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; import org.wso2.carbon.identity.oauth.endpoint.util.TestOAuthEndpointBase; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.ParAuthServiceFactory; import org.wso2.carbon.identity.oauth.par.core.OAuthParRequestWrapper; +import org.wso2.carbon.identity.oauth.par.core.ParAuthService; import org.wso2.carbon.identity.oauth.par.core.ParAuthServiceImpl; import org.wso2.carbon.identity.oauth.par.model.ParAuthData; import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; @@ -75,10 +84,14 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; @@ -107,6 +120,11 @@ public class OAuth2ParEndpointTest extends TestOAuthEndpointBase { @Mock private ParAuthData parAuthData; + @Mock + BundleContext bundleContext; + + MockedConstruction mockedConstruction; + private static final String CLIENT_ID_VALUE = "ca19a540f544777860e44e75f605d927"; private static final String APP_NAME = "myApp"; private static final String INACTIVE_CLIENT_ID_VALUE = "inactiveId"; @@ -157,12 +175,30 @@ public void setUpBeforeMethod() { identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); mockDatabase(identityDatabaseUtil); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(OAuth2Service.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuth2Service}); + } + if (argumentCaptor.getValue().contains(ParAuthService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{parAuthService}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); } @AfterMethod public void tearDownAfterMethod() { + mockedConstruction.close(); identityDatabaseUtil.close(); + PrivilegedCarbonContext.endTenantFlow(); } @DataProvider(name = "testParDataProvider") @@ -190,7 +226,7 @@ public Object[][] testParDataProvider() { Map requestParams7 = createRequestParamsMap(new String[]{CLIENT_ID_VALUE}, new String[]{"http://localhost:8080" + - "/invalid-redirect"}, new String[]{RESPONSE_TYPE_CODE}); + "/invalid-redirect"}, new String[]{RESPONSE_TYPE_CODE}); Map requestParams8 = createRequestParamsMap(new String[]{CLIENT_ID_VALUE}, new String[]{APP_REDIRECT_URL}, new String[]{RESPONSE_TYPE_CODE}); @@ -350,8 +386,7 @@ public void testPar(Object requestParamsObj, Object paramMapObj, Object oAuthCli throws Exception { try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class)) { - + mockStatic(OAuthServerConfiguration.class)) { MultivaluedMap paramMap = (MultivaluedMap) paramMapObj; Map requestParams = (Map) requestParamsObj; OAuthClientAuthnContext oAuthClientAuthnContext = (OAuthClientAuthnContext) oAuthClientAuthnContextObj; @@ -362,8 +397,12 @@ public void testPar(Object requestParamsObj, Object paramMapObj, Object oAuthCli MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); MockedStatic identityUtil = mockStatic(IdentityUtil.class, Mockito.CALLS_REAL_METHODS); MockedStatic oidcRequestObjectUtil = mockStatic(OIDCRequestObjectUtil.class); - MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class); + MockedStatic parAuthServiceFactory = mockStatic(ParAuthServiceFactory.class)) { + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); + parAuthServiceFactory.when(ParAuthServiceFactory::getParAuthService).thenReturn(parAuthService); identityTenantUtil.when(IdentityTenantUtil::getLoginTenantId).thenReturn(-1234); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantId("carbon.super")).thenReturn(-1234); @@ -385,11 +424,8 @@ public void testPar(Object requestParamsObj, Object paramMapObj, Object oAuthCli .thenReturn(SERVER_BASE_PATH); request.setAttribute(OAuthConstants.TRANSPORT_ENDPOINT_ADDRESS, PAR_EP_URL); - endpointUtil.when(EndpointUtil::getOAuth2Service).thenReturn(oAuth2Service); - lenient().doCallRealMethod().when(oAuth2Service).validateInputParameters(request); lenient().doCallRealMethod().when(oAuth2Service).validateClientInfo(any(OAuthParRequestWrapper.class)); - endpointUtil.when(EndpointUtil::getParAuthService).thenReturn(parAuthService); if (testOAuthSystemException) { endpointUtil.when(() -> EndpointUtil.getOAuthAuthzRequest(any())) .thenThrow(new OAuthSystemException()); diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpointTest.java index c819acb3291..841709fe077 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/revoke/OAuthRevocationEndpointTest.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017-2024, WSO2 LLC. (http://www.wso2.com). * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. 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 @@ -15,23 +15,29 @@ * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.identity.oauth.endpoint.revoke; import org.apache.axiom.util.base64.Base64Utils; import org.apache.commons.collections.iterators.IteratorEnumeration; import org.apache.commons.lang.StringUtils; import org.apache.oltu.oauth2.common.OAuth; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; -import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes; @@ -39,8 +45,7 @@ import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException; import org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper; -import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; -import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory; import org.wso2.carbon.identity.oauth2.OAuth2Service; import org.wso2.carbon.identity.oauth2.ResponseHeader; import org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO; @@ -59,9 +64,12 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; @@ -73,15 +81,17 @@ public class OAuthRevocationEndpointTest { @Mock OAuthServerConfiguration mockOAuthServerConfiguration; - @Mock - TokenPersistenceProcessor tokenPersistenceProcessor; - @Mock OAuthRevocationResponseDTO oAuthRevocationResponseDTO; @Mock OAuth2Service oAuth2Service; + @Mock + BundleContext bundleContext; + + MockedConstruction mockedConstruction; + private static final String TOKEN_PARAM = "token"; private static final String TOKEN_TYPE_HINT_PARAM = "token_type_hint"; private static final String CALLBACK_PARAM = "callback"; @@ -104,7 +114,7 @@ public void setUp() { System.setProperty( CarbonBaseConstants.CARBON_HOME, Paths.get(System.getProperty("user.dir"), "src", "test", "resources").toString() - ); + ); revocationEndpoint = new OAuthRevocationEndpoint(); } @@ -114,12 +124,27 @@ public void setUpBeforeMethod() { initMocks(this); oAuthServerConfiguration = mockStatic(OAuthServerConfiguration.class); oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance).thenReturn(mockOAuthServerConfiguration); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(OAuth2Service.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuth2Service}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); } @AfterMethod public void tearDown() { oAuthServerConfiguration.close(); + mockedConstruction.close(); + PrivilegedCarbonContext.endTenantFlow(); } @DataProvider(name = "testRevokeAccessTokenDataProvider") @@ -220,7 +245,7 @@ public void testRevokeAccessToken(String authzHeader, boolean addReqParams, Stri try (MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); MockedStatic loggerUtils = mockStatic(LoggerUtils.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS)) { + MockedStatic oauth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class)) { MultivaluedMap parameterMap = new MultivaluedHashMap<>(); ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj; parameterMap.add(TOKEN_PARAM, token); @@ -239,7 +264,7 @@ public void testRevokeAccessToken(String authzHeader, boolean addReqParams, Stri HttpServletRequest request = mockHttpRequest(requestedParams, new HashMap<>()); when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader); - endpointUtil.when(EndpointUtil::getOAuth2Service).thenReturn(oAuth2Service); + oauth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); final OAuthRevocationRequestDTO[] revokeReqDTO; revokeReqDTO = new OAuthRevocationRequestDTO[1]; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpointTest.java index e2833a9ce9d..b03c892ebe0 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/token/OAuth2TokenEndpointTest.java @@ -28,12 +28,16 @@ import org.apache.oltu.oauth2.common.message.types.GrantType; import org.apache.oltu.oauth2.common.validators.OAuthValidator; import org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.mockito.testng.MockitoTestNGListener; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; @@ -43,6 +47,7 @@ import org.testng.annotations.Test; import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; @@ -55,6 +60,7 @@ import org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; import org.wso2.carbon.identity.oauth.endpoint.util.TestOAuthEndpointBase; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory; import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; import org.wso2.carbon.identity.oauth2.OAuth2Service; import org.wso2.carbon.identity.oauth2.ResponseHeader; @@ -83,10 +89,13 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -107,6 +116,11 @@ public class OAuth2TokenEndpointTest extends TestOAuthEndpointBase { @Mock OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO; + @Mock + BundleContext bundleContext; + + MockedConstruction mockedConstruction; + private static final String SQL_ERROR = "sql_error"; private static final String TOKEN_ERROR = "token_error"; private static final String CLIENT_ID_VALUE = "ca19a540f544777860e44e75f605d927"; @@ -162,12 +176,27 @@ public void setUpBeforeMethod() { identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); mockDatabase(identityDatabaseUtil); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(OAuth2Service.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuth2Service}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); } @AfterMethod public void tearDownAfterMethod() { identityDatabaseUtil.close(); + mockedConstruction.close(); + PrivilegedCarbonContext.endTenantFlow(); } @DataProvider(name = "testIssueAccessTokenDataProvider") @@ -264,7 +293,8 @@ public void testIssueAccessToken(String clientId, String authzHeader, Object par mockStatic(OAuthServerConfiguration.class); MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS);) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oauth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class);) { MultivaluedMap paramMap = (MultivaluedMap) paramMapObj; ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj; Map customResponseParameters = (Map) customResponseParamObj; @@ -296,7 +326,7 @@ public void testIssueAccessToken(String clientId, String authzHeader, Object par }})); endpointUtil.when(EndpointUtil::getRealmInfo).thenReturn(REALM); - endpointUtil.when(EndpointUtil::getOAuth2Service).thenReturn(oAuth2Service); + oauth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); lenient().when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class))).thenReturn( oAuth2AccessTokenRespDTO); @@ -385,7 +415,9 @@ public void testTokenErrorResponse(String errorCode, Object headerObj, int expec mockStatic(OAuthServerConfiguration.class); MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS);) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class);) { + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj; Map requestParams = new HashMap<>(); @@ -407,7 +439,6 @@ public void testTokenErrorResponse(String errorCode, Object headerObj, int expec }})); endpointUtil.when(EndpointUtil::getRealmInfo).thenReturn(REALM); - endpointUtil.when(EndpointUtil::getOAuth2Service).thenReturn(oAuth2Service); when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class))).thenReturn( oAuth2AccessTokenRespDTO); @@ -450,7 +481,8 @@ public void testIssueAccessTokenWithInvalidClientSecret() throws Exception { mockStatic(OAuthServerConfiguration.class); MockedStatic loggerUtils = mockStatic(LoggerUtils.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS);) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class);) { ResponseHeader[] responseHeaders = new ResponseHeader[]{null}; Map requestParams = new HashMap<>(); requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[]{GrantType.CLIENT_CREDENTIALS.toString()}); @@ -472,7 +504,7 @@ public void testIssueAccessTokenWithInvalidClientSecret() throws Exception { }})); endpointUtil.when(EndpointUtil::getRealmInfo).thenReturn(REALM); - endpointUtil.when(EndpointUtil::getOAuth2Service).thenReturn(oAuth2Service); + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); mockOAuthServerConfiguration(oAuthServerConfiguration); Map>> grantTypeValidators = new Hashtable<>(); grantTypeValidators.put(GrantType.CLIENT_CREDENTIALS.toString(), PasswordValidator.class); @@ -519,7 +551,8 @@ public void testGetAccessToken(String grantType, String additionalParameters) th try (MockedStatic oAuthServerConfiguration = mockStatic(OAuthServerConfiguration.class); - MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS);) { + MockedStatic endpointUtil = mockStatic(EndpointUtil.class, Mockito.CALLS_REAL_METHODS); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class);) { Map requestParams = new HashMap<>(); requestParams.put(OAuth.OAUTH_CLIENT_ID, new String[]{CLIENT_ID_VALUE}); requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[]{grantType}); @@ -562,7 +595,7 @@ public void testGetAccessToken(String grantType, String additionalParameters) th mockOAuthServerConfiguration(oAuthServerConfiguration); when(mockOAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators); - endpointUtil.when(EndpointUtil::getOAuth2Service).thenReturn(oAuth2Service); + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(oAuth2Service); final Map parametersSetToRequest = new HashMap<>(); doAnswer(new Answer() { @Override diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidatorTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidatorTest.java index 4134c1bb3c5..b4380adb6d5 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidatorTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoISAccessTokenValidatorTest.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017-2024, WSO2 LLC. (http://www.wso2.com). * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. 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 @@ -18,14 +18,23 @@ package org.wso2.carbon.identity.oauth.endpoint.user.impl; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.testng.MockitoTestNGListener; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; -import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.base.CarbonBaseConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2TokenValidatorServiceFactory; import org.wso2.carbon.identity.oauth.user.UserInfoEndpointException; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; @@ -33,16 +42,21 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Paths; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; @Listeners(MockitoTestNGListener.class) @@ -50,8 +64,15 @@ public class UserInfoISAccessTokenValidatorTest { @Mock private HttpServletRequest httpServletRequest; + @Mock private OAuth2TokenValidationService oAuth2TokenValidationService; + + @Mock + BundleContext bundleContext; + + MockedConstruction mockedConstruction; + private UserInforRequestDefaultValidator userInforRequestDefaultValidator; private UserInfoISAccessTokenValidator userInfoISAccessTokenValidator; private final String token = "ZWx1c3VhcmlvOnlsYWNsYXZl"; @@ -61,8 +82,40 @@ public class UserInfoISAccessTokenValidatorTest { @BeforeClass public void setup() { + System.setProperty(CarbonBaseConstants.CARBON_HOME, Paths.get(System.getProperty("user.dir"), + "src", "test", "resources").toString()); + userInforRequestDefaultValidator = new UserInforRequestDefaultValidator(); userInfoISAccessTokenValidator = new UserInfoISAccessTokenValidator(); + if (mockedConstruction != null) { + mockedConstruction.close(); + } + } + + @BeforeMethod + public void setUp() { + + initMocks(this); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(OAuth2TokenValidationService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{oAuth2TokenValidationService}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); + } + + @AfterMethod + public void tearDown() { + + mockedConstruction.close(); + PrivilegedCarbonContext.endTenantFlow(); } @Test @@ -106,7 +159,7 @@ public Object[][] requestBodyWithNonASCII() { @DataProvider public Object[][] getTokens() { - return new Object[][] { + return new Object[][]{ {"48544572-a796-3d42-a571-505bc609acd8"}, }; } @@ -116,8 +169,10 @@ public void testTokenValidation(String accessTokenIdentifier) throws Exception { prepareOAuth2TokenValidationService(); - try (MockedStatic endpointUtil = mockStatic(EndpointUtil.class)) { - endpointUtil.when(EndpointUtil::getOAuth2TokenValidationService).thenReturn(oAuth2TokenValidationService); + try (MockedStatic utilServiceHolder = + mockStatic(OAuth2TokenValidatorServiceFactory.class)) { + utilServiceHolder.when(OAuth2TokenValidatorServiceFactory::getOAuth2TokenValidatorService) + .thenReturn(oAuth2TokenValidationService); OAuth2TokenValidationResponseDTO responseDTO = userInfoISAccessTokenValidator .validateToken(accessTokenIdentifier); diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoJSONResponseBuilderTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoJSONResponseBuilderTest.java index 368d87c8a26..5220872de96 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoJSONResponseBuilderTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInfoJSONResponseBuilderTest.java @@ -23,7 +23,9 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.testng.MockitoTestNGListener; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -78,6 +80,7 @@ public class UserInfoJSONResponseBuilderTest extends UserInfoResponseBaseTest { private UserInfoJSONResponseBuilder userInfoJSONResponseBuilder; + MockedStatic oAuthServerConfiguration; Connection con = null; @@ -94,6 +97,20 @@ public void setUpTest() throws Exception { con = TestUtils.getConnection(); } + @BeforeMethod + public void setUpMethod() { + + oAuthServerConfiguration = mockStatic(OAuthServerConfiguration.class); + oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance).thenReturn(mockOAuthServerConfiguration); + } + + @AfterMethod + public void tearDown() { + + oAuthServerConfiguration.close(); + } + + private void setUpRequestObjectService() throws RequestObjectException { List requestedClaims = Collections.emptyList(); @@ -129,65 +146,58 @@ public void testGetResponseString(Map inputClaims, String[] requestedScopes, Map expectedClaims) throws Exception { - try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { - oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance) - .thenReturn(mockOAuthServerConfiguration); - try (MockedStatic jdbcPersistenceManager = - mockStatic(JDBCPersistenceManager.class); - MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic authorizationGrantCache = - mockStatic(AuthorizationGrantCache.class); - MockedStatic claimUtil = mockStatic(ClaimUtil.class); - MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic userInfoEndpointConfig = - mockStatic(UserInfoEndpointConfig.class);) { - setUpRequestObjectService(); - prepareForResponseClaimTest(inputClaims, oidcScopeMap, getClaimsFromCache, - authorizationGrantCache, frameworkUtils, claimUtil, oAuth2Util, identityTenantUtil, - userInfoEndpointConfig); - mockDataSource(jdbcPersistenceManager); - mockObjectsRelatedToTokenValidation(oAuth2Util); - - frameworkUtils.when(() -> FrameworkUtils.resolveUserIdFromUsername(anyInt(), anyString(), anyString())) - .thenReturn(AUTHORIZED_USER_ID); - - AuthenticatedUser authenticatedUser = new AuthenticatedUser(); - authenticatedUser.setUserName(AUTHORIZED_USER_NAME); - authenticatedUser.setTenantDomain(TENANT_DOT_COM); - authenticatedUser.setUserStoreDomain(JDBC_DOMAIN); - authenticatedUser.setUserId(AUTHORIZED_USER_ID); - authenticatedUser.setAuthenticatedSubjectIdentifier(AUTHORIZED_USER_ID); - mockAccessTokenDOInOAuth2Util(authenticatedUser, oAuth2Util); - - String responseString = - userInfoJSONResponseBuilder.getResponseString( - getTokenResponseDTO(AUTHORIZED_USER_FULL_QUALIFIED, requestedScopes)); - - Map claimsInResponse = JSONUtils.parseJSON(responseString); - assertNotNull(claimsInResponse); - assertFalse(claimsInResponse.isEmpty()); - assertNotNull(claimsInResponse.get(sub)); - - for (Map.Entry expectClaimEntry : expectedClaims.entrySet()) { - assertTrue(claimsInResponse.containsKey(expectClaimEntry.getKey())); - assertNotNull(claimsInResponse.get(expectClaimEntry.getKey())); - assertEquals(expectClaimEntry.getValue(), claimsInResponse.get(expectClaimEntry.getKey())); - } - - } finally { - PrivilegedCarbonContext.endTenantFlow(); + try (MockedStatic jdbcPersistenceManager = + mockStatic(JDBCPersistenceManager.class); + MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); + MockedStatic authorizationGrantCache = + mockStatic(AuthorizationGrantCache.class); + MockedStatic claimUtil = mockStatic(ClaimUtil.class); + MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic userInfoEndpointConfig = + mockStatic(UserInfoEndpointConfig.class);) { + setUpRequestObjectService(); + prepareForResponseClaimTest(inputClaims, oidcScopeMap, getClaimsFromCache, + authorizationGrantCache, frameworkUtils, claimUtil, oAuth2Util, identityTenantUtil, + userInfoEndpointConfig); + mockDataSource(jdbcPersistenceManager); + mockObjectsRelatedToTokenValidation(oAuth2Util); + + frameworkUtils.when(() -> FrameworkUtils.resolveUserIdFromUsername(anyInt(), anyString(), anyString())) + .thenReturn(AUTHORIZED_USER_ID); + + AuthenticatedUser authenticatedUser = new AuthenticatedUser(); + authenticatedUser.setUserName(AUTHORIZED_USER_NAME); + authenticatedUser.setTenantDomain(TENANT_DOT_COM); + authenticatedUser.setUserStoreDomain(JDBC_DOMAIN); + authenticatedUser.setUserId(AUTHORIZED_USER_ID); + authenticatedUser.setAuthenticatedSubjectIdentifier(AUTHORIZED_USER_ID); + mockAccessTokenDOInOAuth2Util(authenticatedUser, oAuth2Util); + + String responseString = + userInfoJSONResponseBuilder.getResponseString( + getTokenResponseDTO(AUTHORIZED_USER_FULL_QUALIFIED, requestedScopes)); + + Map claimsInResponse = JSONUtils.parseJSON(responseString); + assertNotNull(claimsInResponse); + assertFalse(claimsInResponse.isEmpty()); + assertNotNull(claimsInResponse.get(sub)); + + for (Map.Entry expectClaimEntry : expectedClaims.entrySet()) { + assertTrue(claimsInResponse.containsKey(expectClaimEntry.getKey())); + assertNotNull(claimsInResponse.get(expectClaimEntry.getKey())); + assertEquals(expectClaimEntry.getValue(), claimsInResponse.get(expectClaimEntry.getKey())); } + + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } @Test public void testEssentialClaims() throws Exception { - try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class); - MockedStatic authorizationGrantCache = + try (MockedStatic authorizationGrantCache = mockStatic(AuthorizationGrantCache.class); MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); MockedStatic claimUtil = mockStatic(ClaimUtil.class);) { @@ -260,76 +270,59 @@ public void testEssentialClaims() throws Exception { @Test public void testUpdateAtClaim() throws Exception { - try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { - oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance) - .thenReturn(mockOAuthServerConfiguration); - - try (MockedStatic jdbcPersistenceManager = - mockStatic(JDBCPersistenceManager.class); - MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic authorizationGrantCache = - mockStatic(AuthorizationGrantCache.class); - MockedStatic claimUtil = mockStatic(ClaimUtil.class); - MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic userInfoEndpointConfig = - mockStatic(UserInfoEndpointConfig.class);) { - String updateAtValue = "1509556412"; - testLongClaimInUserInfoResponse(UPDATED_AT, updateAtValue, jdbcPersistenceManager, frameworkUtils, - authorizationGrantCache, claimUtil, oAuth2Util, identityTenantUtil, userInfoEndpointConfig); - } + try (MockedStatic jdbcPersistenceManager = + mockStatic(JDBCPersistenceManager.class); + MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); + MockedStatic authorizationGrantCache = + mockStatic(AuthorizationGrantCache.class); + MockedStatic claimUtil = mockStatic(ClaimUtil.class); + MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic userInfoEndpointConfig = + mockStatic(UserInfoEndpointConfig.class);) { + String updateAtValue = "1509556412"; + testLongClaimInUserInfoResponse(UPDATED_AT, updateAtValue, jdbcPersistenceManager, frameworkUtils, + authorizationGrantCache, claimUtil, oAuth2Util, identityTenantUtil, userInfoEndpointConfig); } } @Test public void testEmailVerified() throws Exception { - try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { - oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance) - .thenReturn(mockOAuthServerConfiguration); - - try (MockedStatic jdbcPersistenceManager = - mockStatic(JDBCPersistenceManager.class); - MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic authorizationGrantCache = - mockStatic(AuthorizationGrantCache.class); - MockedStatic claimUtil = mockStatic(ClaimUtil.class); - MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic userInfoEndpointConfig = - mockStatic(UserInfoEndpointConfig.class);) { - String emailVerifiedClaimValue = "true"; - testBooleanClaimInUserInfoResponse(EMAIL_VERIFIED, emailVerifiedClaimValue, jdbcPersistenceManager, - frameworkUtils, authorizationGrantCache, claimUtil, oAuth2Util, identityTenantUtil, - userInfoEndpointConfig); - } + try (MockedStatic jdbcPersistenceManager = + mockStatic(JDBCPersistenceManager.class); + MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); + MockedStatic authorizationGrantCache = + mockStatic(AuthorizationGrantCache.class); + MockedStatic claimUtil = mockStatic(ClaimUtil.class); + MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic userInfoEndpointConfig = + mockStatic(UserInfoEndpointConfig.class);) { + String emailVerifiedClaimValue = "true"; + testBooleanClaimInUserInfoResponse(EMAIL_VERIFIED, emailVerifiedClaimValue, jdbcPersistenceManager, + frameworkUtils, authorizationGrantCache, claimUtil, oAuth2Util, identityTenantUtil, + userInfoEndpointConfig); } } @Test public void testPhoneNumberVerified() throws Exception { - try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { - oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance) - .thenReturn(mockOAuthServerConfiguration); - try (MockedStatic jdbcPersistenceManager = - mockStatic(JDBCPersistenceManager.class); - MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic authorizationGrantCache = - mockStatic(AuthorizationGrantCache.class); - MockedStatic claimUtil = mockStatic(ClaimUtil.class); - MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic userInfoEndpointConfig = - mockStatic(UserInfoEndpointConfig.class);) { - String phoneNumberVerifiedClaimValue = "true"; - testBooleanClaimInUserInfoResponse(PHONE_NUMBER_VERIFIED, phoneNumberVerifiedClaimValue, - jdbcPersistenceManager, frameworkUtils, authorizationGrantCache, - claimUtil, oAuth2Util, identityTenantUtil, userInfoEndpointConfig); - } + try (MockedStatic jdbcPersistenceManager = + mockStatic(JDBCPersistenceManager.class); + MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); + MockedStatic authorizationGrantCache = + mockStatic(AuthorizationGrantCache.class); + MockedStatic claimUtil = mockStatic(ClaimUtil.class); + MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic userInfoEndpointConfig = + mockStatic(UserInfoEndpointConfig.class);) { + String phoneNumberVerifiedClaimValue = "true"; + testBooleanClaimInUserInfoResponse(PHONE_NUMBER_VERIFIED, phoneNumberVerifiedClaimValue, + jdbcPersistenceManager, frameworkUtils, authorizationGrantCache, + claimUtil, oAuth2Util, identityTenantUtil, userInfoEndpointConfig); } } @@ -418,41 +411,36 @@ public void testSubjectClaim(Map inputClaims, boolean appendUserStoreDomain, boolean isPairwiseSubject, String expectedSubjectValue, String expectedPPID) throws Exception { - try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { - oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance) - .thenReturn(mockOAuthServerConfiguration); - try (MockedStatic jdbcPersistenceManager = - mockStatic(JDBCPersistenceManager.class); - MockedStatic authorizationGrantCache = - mockStatic(AuthorizationGrantCache.class); - MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic claimUtil = mockStatic(ClaimUtil.class); - MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic userInfoEndpointConfig = - mockStatic(UserInfoEndpointConfig.class);) { - setUpRequestObjectService(); - AuthenticatedUser authzUser = (AuthenticatedUser) authorizedUser; - prepareForSubjectClaimTest(authzUser, inputClaims, appendTenantDomain, appendUserStoreDomain, - isPairwiseSubject, authorizationGrantCache, frameworkUtils, claimUtil, oAuth2Util, - identityTenantUtil, userInfoEndpointConfig); - updateAuthenticatedSubjectIdentifier(authzUser, appendTenantDomain, appendUserStoreDomain, inputClaims); - when(userInfoJSONResponseBuilder.retrieveUserClaims(any(OAuth2TokenValidationResponseDTO.class))) - .thenReturn(inputClaims); - Mockito.when(IdentityTenantUtil.getTenantId(isNull())).thenReturn(-1234); - mockDataSource(jdbcPersistenceManager); - mockObjectsRelatedToTokenValidation(oAuth2Util); - String responseString = - userInfoJSONResponseBuilder - .getResponseString(getTokenResponseDTO((authzUser).toFullQualifiedUsername())); - - Map claimsInResponse = JSONUtils.parseJSON(responseString); - assertSubjectClaimPresent(claimsInResponse); - assertEquals(claimsInResponse.get(sub), isPairwiseSubject ? expectedPPID : expectedSubjectValue); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } + try (MockedStatic jdbcPersistenceManager = + mockStatic(JDBCPersistenceManager.class); + MockedStatic authorizationGrantCache = + mockStatic(AuthorizationGrantCache.class); + MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); + MockedStatic claimUtil = mockStatic(ClaimUtil.class); + MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic userInfoEndpointConfig = + mockStatic(UserInfoEndpointConfig.class);) { + setUpRequestObjectService(); + AuthenticatedUser authzUser = (AuthenticatedUser) authorizedUser; + prepareForSubjectClaimTest(authzUser, inputClaims, appendTenantDomain, appendUserStoreDomain, + isPairwiseSubject, authorizationGrantCache, frameworkUtils, claimUtil, oAuth2Util, + identityTenantUtil, userInfoEndpointConfig); + updateAuthenticatedSubjectIdentifier(authzUser, appendTenantDomain, appendUserStoreDomain, inputClaims); + when(userInfoJSONResponseBuilder.retrieveUserClaims(any(OAuth2TokenValidationResponseDTO.class))) + .thenReturn(inputClaims); + Mockito.when(IdentityTenantUtil.getTenantId(isNull())).thenReturn(-1234); + mockDataSource(jdbcPersistenceManager); + mockObjectsRelatedToTokenValidation(oAuth2Util); + String responseString = + userInfoJSONResponseBuilder + .getResponseString(getTokenResponseDTO((authzUser).toFullQualifiedUsername())); + + Map claimsInResponse = JSONUtils.parseJSON(responseString); + assertSubjectClaimPresent(claimsInResponse); + assertEquals(claimsInResponse.get(sub), isPairwiseSubject ? expectedPPID : expectedSubjectValue); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } @@ -464,45 +452,39 @@ public void testSubjectClaimWithAlteredApplicationConfigs(Map in String expectedSubjectValue, String expectedPPID) throws Exception { - try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { - oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance) - .thenReturn(mockOAuthServerConfiguration); - - try (MockedStatic jdbcPersistenceManager = - mockStatic(JDBCPersistenceManager.class); - MockedStatic authorizationGrantCache = - mockStatic(AuthorizationGrantCache.class); - MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic claimUtil = mockStatic(ClaimUtil.class); - MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); - MockedStatic userInfoEndpointConfig = - mockStatic(UserInfoEndpointConfig.class);) { - setUpRequestObjectService(); - AuthenticatedUser authzUser = (AuthenticatedUser) authorizedUser; - prepareForSubjectClaimTest(authzUser, inputClaims, !appendTenantDomain, !appendUserStoreDomain, - isPairwiseSubject, authorizationGrantCache, frameworkUtils, claimUtil, oAuth2Util, - identityTenantUtil, userInfoEndpointConfig); - authzUser.setAuthenticatedSubjectIdentifier(expectedSubjectValue, - applicationManagementService.getServiceProviderByClientId(CLIENT_ID, - IdentityApplicationConstants.OAuth2.NAME, SUPER_TENANT_DOMAIN_NAME)); - - when(userInfoJSONResponseBuilder.retrieveUserClaims(any(OAuth2TokenValidationResponseDTO.class))) - .thenReturn(inputClaims); - Mockito.when(IdentityTenantUtil.getTenantId(isNull())).thenReturn(-1234); - mockDataSource(jdbcPersistenceManager); - mockObjectsRelatedToTokenValidation(oAuth2Util); - String responseString = - userInfoJSONResponseBuilder - .getResponseString(getTokenResponseDTO((authzUser).toFullQualifiedUsername())); - - Map claimsInResponse = JSONUtils.parseJSON(responseString); - assertSubjectClaimPresent(claimsInResponse); - assertEquals(claimsInResponse.get(sub), isPairwiseSubject ? expectedPPID : expectedSubjectValue); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } + try (MockedStatic jdbcPersistenceManager = + mockStatic(JDBCPersistenceManager.class); + MockedStatic authorizationGrantCache = + mockStatic(AuthorizationGrantCache.class); + MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); + MockedStatic claimUtil = mockStatic(ClaimUtil.class); + MockedStatic oAuth2Util = mockStatic(OAuth2Util.class, Mockito.CALLS_REAL_METHODS); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic userInfoEndpointConfig = + mockStatic(UserInfoEndpointConfig.class);) { + setUpRequestObjectService(); + AuthenticatedUser authzUser = (AuthenticatedUser) authorizedUser; + prepareForSubjectClaimTest(authzUser, inputClaims, !appendTenantDomain, !appendUserStoreDomain, + isPairwiseSubject, authorizationGrantCache, frameworkUtils, claimUtil, oAuth2Util, + identityTenantUtil, userInfoEndpointConfig); + authzUser.setAuthenticatedSubjectIdentifier(expectedSubjectValue, + applicationManagementService.getServiceProviderByClientId(CLIENT_ID, + IdentityApplicationConstants.OAuth2.NAME, SUPER_TENANT_DOMAIN_NAME)); + + when(userInfoJSONResponseBuilder.retrieveUserClaims(any(OAuth2TokenValidationResponseDTO.class))) + .thenReturn(inputClaims); + Mockito.when(IdentityTenantUtil.getTenantId(isNull())).thenReturn(-1234); + mockDataSource(jdbcPersistenceManager); + mockObjectsRelatedToTokenValidation(oAuth2Util); + String responseString = + userInfoJSONResponseBuilder + .getResponseString(getTokenResponseDTO((authzUser).toFullQualifiedUsername())); + + Map claimsInResponse = JSONUtils.parseJSON(responseString); + assertSubjectClaimPresent(claimsInResponse); + assertEquals(claimsInResponse.get(sub), isPairwiseSubject ? expectedPPID : expectedSubjectValue); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } } diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java index 188c2943859..2fd006c97a0 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java @@ -28,12 +28,16 @@ import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.message.OAuthResponse; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.testng.MockitoTestNGListener; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.ServiceTracker; import org.testng.Assert; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; @@ -41,9 +45,9 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry; import org.wso2.carbon.identity.application.authentication.framework.config.builder.FileBasedConfigurationBuilder; -import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig; @@ -57,7 +61,6 @@ import org.wso2.carbon.identity.discovery.DefaultOIDCProcessor; import org.wso2.carbon.identity.discovery.OIDCProcessor; import org.wso2.carbon.identity.discovery.builders.DefaultOIDCProviderRequestBuilder; -import org.wso2.carbon.identity.discovery.builders.OIDCProviderRequestBuilder; import org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl; import org.wso2.carbon.identity.oauth.cache.SessionDataCache; import org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry; @@ -67,6 +70,15 @@ import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidApplicationClientException; import org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2ServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2TokenValidatorServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuthAdminServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuthServerConfigurationFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OIDCProviderRequestValidatorFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OIDCProviderServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.Oauth2ScopeServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.RequestObjectServiceFactory; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.WebFingerServiceFactory; import org.wso2.carbon.identity.oauth2.OAuth2ScopeService; import org.wso2.carbon.identity.oauth2.OAuth2Service; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; @@ -106,9 +118,12 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; @@ -138,9 +153,6 @@ public class EndpointUtilTest { @Mock HttpServletResponse mockedHttpServletResponse; - @Mock - PrivilegedCarbonContext mockedPrivilegedCarbonContext; - @Mock ServerConfiguration mockedServerConfiguration; @@ -151,16 +163,15 @@ public class EndpointUtilTest { OAuthAdminServiceImpl mockedOAuthAdminService; @Mock - SSOConsentService mockedSSOConsentService; + OAuth2ScopeService oAuth2ScopeService; @Mock - RequestObjectService mockedRequestObjectService; + FileBasedConfigurationBuilder mockFileBasedConfigurationBuilder; @Mock - OAuth2ScopeService oAuth2ScopeService; + BundleContext bundleContext; - @Mock - FileBasedConfigurationBuilder mockFileBasedConfigurationBuilder; + MockedConstruction mockedConstruction; private static final String COMMONAUTH_URL = "https://localhost:9443/commonauth"; private static final String OIDC_CONSENT_PAGE_URL = @@ -207,6 +218,52 @@ public void setUp() { user.setUserId("4b4414e1-916b-4475-aaee-6b0751c29ff6"); oAuth2ScopeConsentResponse = new OAuth2ScopeConsentResponse("sampleUser", "sampleApp", -1234, new ArrayList<>(), new ArrayList<>()); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("carbon.super"); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + mockedConstruction = mockConstruction(ServiceTracker.class, + (mock, context) -> { + verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); + if (argumentCaptor.getValue().contains(DefaultOIDCProviderRequestBuilder.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{new DefaultOIDCProviderRequestBuilder()}); + } + if (argumentCaptor.getValue().contains(OAuthServerConfiguration.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{mockedOAuthServerConfiguration}); + } + if (argumentCaptor.getValue().contains(WebFingerProcessor.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{DefaultWebFingerProcessor.getInstance()}); + } + if (argumentCaptor.getValue().contains(OIDCProcessor.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{DefaultOIDCProcessor.getInstance()}); + } + if (argumentCaptor.getValue().contains(OAuth2Service.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{new OAuth2Service()}); + } + if (argumentCaptor.getValue().contains(OAuth2TokenValidationService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{new OAuth2TokenValidationService()}); + } + if (argumentCaptor.getValue().contains(RequestObjectService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{new RequestObjectService()}); + } + if (argumentCaptor.getValue().contains(OAuth2ScopeService.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{new OAuth2ScopeService()}); + } + if (argumentCaptor.getValue().contains(OAuthAdminServiceImpl.class.getName())) { + when(mock.getServices()).thenReturn(new Object[]{new OAuthAdminServiceImpl()}); + } + }); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); + } + + @AfterMethod + public void tearDown() { + + mockedConstruction.close(); + PrivilegedCarbonContext.endTenantFlow(); + Mockito.reset(bundleContext); + OSGiDataHolder.getInstance().setBundleContext(bundleContext); } @DataProvider(name = "provideAuthzHeader") @@ -283,7 +340,9 @@ public void testGetUserConsentURL(Object oAuth2ParamObject, boolean isOIDC, bool try (MockedStatic oAuthServerConfiguration = mockStatic( OAuthServerConfiguration.class); MockedStatic fileBasedConfigurationBuilder = - mockStatic(FileBasedConfigurationBuilder.class);) { + mockStatic(FileBasedConfigurationBuilder.class); + MockedStatic oAuthServerConfigurationFactory = + mockStatic(OAuthServerConfigurationFactory.class)) { oAuthServerConfiguration.when(OAuthServerConfiguration::getInstance) .thenReturn(mockedOAuthServerConfiguration); @@ -291,11 +350,17 @@ public void testGetUserConsentURL(Object oAuth2ParamObject, boolean isOIDC, bool MockedStatic oAuthURL = mockStatic(OAuth2Util.OAuthURL.class); MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); MockedStatic frameworkUtils = mockStatic(FrameworkUtils.class); - MockedStatic sessionDataCache = mockStatic(SessionDataCache.class);) { + MockedStatic sessionDataCache = mockStatic(SessionDataCache.class); + MockedStatic oauth2ScopeServiceFactory = + mockStatic(Oauth2ScopeServiceFactory.class); + MockedStatic oAuthAdminServiceFactory = + mockStatic(OAuthAdminServiceFactory.class)) { - EndpointUtil.setOauthServerConfiguration(mockedOAuthServerConfiguration); + oAuthServerConfigurationFactory.when(OAuthServerConfigurationFactory::getOAuthServerConfiguration) + .thenReturn(mockedOAuthServerConfiguration); lenient().when(mockedOAuthServerConfiguration.isDropUnregisteredScopes()).thenReturn(false); - EndpointUtil.setOAuth2ScopeService(oAuth2ScopeService); + oauth2ScopeServiceFactory.when(Oauth2ScopeServiceFactory::getOAuth2ScopeService) + .thenReturn(oAuth2ScopeService); lenient().when(oAuth2ScopeService.getUserConsentForApp(anyString(), anyString(), anyInt())) .thenReturn(oAuth2ScopeConsentResponse); @@ -339,7 +404,8 @@ public void testGetUserConsentURL(Object oAuth2ParamObject, boolean isOIDC, bool thenReturn(null); } - EndpointUtil.setOAuthAdminService(mockedOAuthAdminService); + oAuthAdminServiceFactory.when(OAuthAdminServiceFactory::getOAuthAdminService) + .thenReturn(mockedOAuthAdminService); lenient().when(mockedOAuthAdminService.getScopeNames()).thenReturn(new String[0]); lenient().when(mockedOAuthAdminService.getRegisteredOIDCScope(anyString())) .thenReturn(Arrays.asList("openid", "email", "profile", "groups")); @@ -548,19 +614,20 @@ public void testGetErrorRedirectURL(boolean isImplicitResponse, boolean isImplic try (MockedConstruction mockedConstruction = Mockito.mockConstruction(OAuthResponse.OAuthErrorResponseBuilder.class, - (mock, context) -> { - when(mock.error(any(OAuthProblemException.class))).thenReturn(mock); - when(mock.location(anyString())).thenReturn(mock); - when(mock.setState(anyString())).thenReturn(mock); - when(mock.setParam(anyString(), isNull())). - thenReturn(mock); - if (exeObject != null) { - OAuthSystemException oAuthSystemException = (OAuthSystemException) exeObject; - when(mock.buildQueryMessage()).thenThrow(oAuthSystemException); - } else { - when(mock.buildQueryMessage()).thenReturn(mockedOAuthResponse); - } - })) { + (mock, context) -> { + when(mock.error(any(OAuthProblemException.class))).thenReturn(mock); + when(mock.location(anyString())).thenReturn(mock); + when(mock.setState(anyString())).thenReturn(mock); + when(mock.setParam(anyString(), isNull())). + thenReturn(mock); + if (exeObject != null) { + OAuthSystemException oAuthSystemException = + (OAuthSystemException) exeObject; + when(mock.buildQueryMessage()).thenThrow(oAuthSystemException); + } else { + when(mock.buildQueryMessage()).thenReturn(mockedOAuthResponse); + } + })) { lenient().when(mockedOAuthResponse.getLocationUri()).thenReturn("http://localhost:8080/location"); String url = EndpointUtil.getErrorRedirectURL(exception, parameters); @@ -616,7 +683,7 @@ public void testGetErrorPageURL(boolean isImplicitResponse, boolean isHybridResp OAuth2Parameters parameters = (OAuth2Parameters) oAuth2ParamObject; try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class);) { + mockStatic(OAuthServerConfiguration.class);) { oAuthServerConfiguration.when( OAuthServerConfiguration::getInstance).thenReturn(mockedOAuthServerConfiguration); when(mockedOAuthServerConfiguration.isRedirectToRequestedRedirectUriEnabled()) @@ -624,8 +691,8 @@ public void testGetErrorPageURL(boolean isImplicitResponse, boolean isHybridResp try (MockedStatic oAuth2Util = mockStatic(OAuth2Util.class); MockedStatic oAuthURL = mockStatic(OAuth2Util.OAuthURL.class);) { - oAuth2Util.when(()->OAuth2Util.isImplicitResponseType(anyString())).thenReturn(isImplicitResponse); - oAuth2Util.when(()->OAuth2Util.isHybridResponseType(anyString())).thenReturn(isHybridResponse); + oAuth2Util.when(() -> OAuth2Util.isImplicitResponseType(anyString())).thenReturn(isImplicitResponse); + oAuth2Util.when(() -> OAuth2Util.isHybridResponseType(anyString())).thenReturn(isHybridResponse); oAuthURL.when(OAuth2Util.OAuthURL::getOAuth2ErrorPageUrl).thenReturn(ERROR_PAGE_URL); @@ -689,7 +756,7 @@ public void testValidateParams(Object paramObject, Map request public void testGetLoginPageURLFromCache() throws Exception { try (MockedStatic oAuthServerConfiguration = - mockStatic(OAuthServerConfiguration.class)) { + mockStatic(OAuthServerConfiguration.class)) { oAuthServerConfiguration.when( OAuthServerConfiguration::getInstance).thenReturn(mockedOAuthServerConfiguration); @@ -725,29 +792,23 @@ public void testGetLoginPageURLFromCache() throws Exception { @Test public void testGetServices() { - try (MockedStatic privilegedCarbonContext = - mockStatic(PrivilegedCarbonContext.class);) { - mockPrivilegedCarbonContext(privilegedCarbonContext); - EndpointUtil.setOAuth2Service(mockedOAuth2Service); - EndpointUtil.setSSOConsentService(mockedSSOConsentService); - EndpointUtil.setRequestObjectService(mockedRequestObjectService); - assertTrue(EndpointUtil.getWebFingerService() instanceof DefaultWebFingerProcessor, - "Retrieved incorrect WebFingerService"); - assertTrue(EndpointUtil.getOIDProviderRequestValidator() instanceof DefaultOIDCProviderRequestBuilder, - "Retrieved incorrect OIDProviderRequestValidator"); - assertTrue(EndpointUtil.getOIDCService() instanceof DefaultOIDCProcessor, - "Retrieved incorrect OIDCService"); - assertTrue(EndpointUtil.getOAuth2Service() instanceof OAuth2Service, - "Retrieved incorrect OAuth2Service"); - assertTrue(EndpointUtil.getOAuthServerConfiguration() instanceof OAuthServerConfiguration, - "Retrieved incorrect OAuthServerConfiguration"); - assertTrue(EndpointUtil.getOAuth2TokenValidationService() instanceof OAuth2TokenValidationService, - "Retrieved incorrect OAuth2TokenValidationService"); - assertTrue(EndpointUtil.getSSOConsentService() instanceof SSOConsentService, - "Retrieved incorrect SSOConsentService"); - assertTrue(EndpointUtil.getRequestObjectService() instanceof RequestObjectService, - "Retrieved incorrect RequestObjectService"); - } + assertTrue(WebFingerServiceFactory.getWebFingerService() instanceof DefaultWebFingerProcessor, + "Retrieved incorrect WebFingerService"); + assertTrue(OIDCProviderRequestValidatorFactory.getOIDProviderRequestValidator() + instanceof DefaultOIDCProviderRequestBuilder, + "Retrieved incorrect OIDProviderRequestValidator"); + assertTrue(OIDCProviderServiceFactory.getOIDCService() instanceof DefaultOIDCProcessor, + "Retrieved incorrect OIDCService"); + assertTrue(OAuth2ServiceFactory.getOAuth2Service() instanceof OAuth2Service, + "Retrieved incorrect OAuth2Service"); + assertTrue(OAuthServerConfigurationFactory.getOAuthServerConfiguration() + instanceof OAuthServerConfiguration, + "Retrieved incorrect OAuthServerConfiguration"); + assertTrue(OAuth2TokenValidatorServiceFactory.getOAuth2TokenValidatorService() + instanceof OAuth2TokenValidationService, + "Retrieved incorrect OAuth2TokenValidationService"); + assertTrue(RequestObjectServiceFactory.getRequestObjectService() instanceof RequestObjectService, + "Retrieved incorrect RequestObjectService"); } @Test @@ -764,17 +825,18 @@ public void testGetRealmInfo() { @Test public void testGetOAuthServerConfigProperties() throws Exception { - try (MockedStatic privilegedCarbonContext = - mockStatic(PrivilegedCarbonContext.class);) { - mockPrivilegedCarbonContext(privilegedCarbonContext); + try (MockedStatic oAuthServerConfigurationFactory = + mockStatic(OAuthServerConfigurationFactory.class)) { + oAuthServerConfigurationFactory.when(OAuthServerConfigurationFactory::getOAuthServerConfiguration) + .thenReturn(mockedOAuthServerConfiguration); setMockedOAuthServerConfiguration(); - EndpointUtil.setOauthServerConfiguration(mockedOAuthServerConfiguration); assertEquals(EndpointUtil.getUserInfoRequestValidator(), USER_INFO_REQUEST_VALIDATOR); assertEquals(EndpointUtil.getAccessTokenValidator(), USER_INFO_TOKEN_VALIDATOR); assertEquals(EndpointUtil.getUserInfoResponseBuilder(), USER_INFO_RESPONSE_BUILDER); assertEquals(EndpointUtil.getUserInfoClaimRetriever(), USER_INFO_CLAIM_RETRIEVER); assertEquals(EndpointUtil.getUserInfoClaimDialect(), USER_INFO_CLAIM_DIALECT); } + } @DataProvider(name = "provideState") @@ -790,9 +852,10 @@ public Object[][] provideState() { @Test(dataProvider = "provideState") public void testValidateOauthApplication(String state, boolean diagnosticLogEnabled) { - try (MockedStatic loggerUtils = mockStatic(LoggerUtils.class);) { + try (MockedStatic loggerUtils = mockStatic(LoggerUtils.class); + MockedStatic oAuth2ServiceFactory = mockStatic(OAuth2ServiceFactory.class);) { loggerUtils.when(LoggerUtils::isDiagnosticLogsEnabled).thenReturn(diagnosticLogEnabled); - EndpointUtil.setOAuth2Service(mockedOAuth2Service); + oAuth2ServiceFactory.when(OAuth2ServiceFactory::getOAuth2Service).thenReturn(mockedOAuth2Service); when(mockedOAuth2Service.getOauthApplicationState(anyString())).thenReturn(state); Response response; @@ -832,24 +895,6 @@ private void setMockedLog(boolean isDebugEnabled) throws Exception { lenient().when(mockedLog.isDebugEnabled()).thenReturn(isDebugEnabled); } - private void mockPrivilegedCarbonContext(MockedStatic privilegedCarbonContext) { - - privilegedCarbonContext.when( - PrivilegedCarbonContext::getThreadLocalCarbonContext).thenReturn(mockedPrivilegedCarbonContext); - lenient().when(mockedPrivilegedCarbonContext.getOSGiService(OAuthServerConfiguration.class, null)). - thenReturn(mockedOAuthServerConfiguration); - lenient().when(mockedPrivilegedCarbonContext.getOSGiService(WebFingerProcessor.class, null)). - thenReturn(DefaultWebFingerProcessor.getInstance()); - lenient().when(mockedPrivilegedCarbonContext.getOSGiService(OIDCProviderRequestBuilder.class, null)). - thenReturn(new DefaultOIDCProviderRequestBuilder()); - lenient().when(mockedPrivilegedCarbonContext.getOSGiService(OIDCProcessor.class, null)). - thenReturn(DefaultOIDCProcessor.getInstance()); - lenient().when(mockedPrivilegedCarbonContext.getOSGiService(OAuth2Service.class, null)) - .thenReturn(new OAuth2Service()); - lenient().when(mockedPrivilegedCarbonContext.getOSGiService(OAuth2TokenValidationService.class, null)). - thenReturn(new OAuth2TokenValidationService()); - } - private void setMockedOAuthServerConfiguration() { when(mockedOAuthServerConfiguration.getOpenIDConnectUserInfoEndpointRequestValidator()). From bf3c8bfd62d49081e4948811fedbe3e824425228 Mon Sep 17 00:00:00 2001 From: lashinie Date: Thu, 16 Jan 2025 20:57:45 +0530 Subject: [PATCH 4/8] refactor OIDCDiscoveryServiceFactory.java --- .../oidcdiscovery/OIDCDiscoveryEndpoint.java | 1 + .../OIDCDiscoveryServiceFactory.java | 8 +- .../src/main/webapp/WEB-INF/beans.xml | 29 ----- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 104 ------------------ 4 files changed, 3 insertions(+), 139 deletions(-) delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/beans.xml delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java index 359fdb8eddc..31e7fdc0e62 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java @@ -28,6 +28,7 @@ import org.wso2.carbon.identity.discovery.OIDCProcessor; import org.wso2.carbon.identity.discovery.builders.OIDProviderResponseBuilder; import org.wso2.carbon.identity.oauth.common.OAuthConstants; +import org.wso2.carbon.identity.oauth.endpoint.oidcdiscovery.impl.OIDProviderJSONResponseBuilder; import org.wso2.carbon.identity.oauth.endpoint.util.factory.OIDCProviderServiceFactory; import javax.servlet.http.HttpServletRequest; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java index d9fd4c64285..68d3b169d25 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java @@ -20,6 +20,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.discovery.builders.OIDProviderResponseBuilder; +import org.wso2.carbon.identity.oauth.endpoint.oidcdiscovery.impl.OIDProviderJSONResponseBuilder; /** * Service holder for managing instances of OIDC Discovery related services. @@ -29,12 +30,7 @@ public class OIDCDiscoveryServiceFactory { private static final OIDProviderResponseBuilder SERVICE; static { - OIDProviderResponseBuilder oidProviderResponseBuilder = (OIDProviderResponseBuilder) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(OIDProviderResponseBuilder.class, null); - if (oidProviderResponseBuilder == null) { - throw new IllegalStateException("OIDProviderResponseBuilder is not available from OSGi context."); - } - SERVICE = oidProviderResponseBuilder; + SERVICE = new OIDProviderJSONResponseBuilder(); } public static OIDProviderResponseBuilder getOIDProviderResponseBuilder() { diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/beans.xml b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index c4de3c03efd..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index 4c5a34b03d9..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 093663303f4d99ff523f154bc6c336cd1cbe2896 Mon Sep 17 00:00:00 2001 From: lashinie Date: Thu, 16 Jan 2025 21:14:01 +0530 Subject: [PATCH 5/8] fix checkstyles issues --- .../oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java | 1 - .../endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java | 1 - 2 files changed, 2 deletions(-) diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java index 31e7fdc0e62..359fdb8eddc 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryEndpoint.java @@ -28,7 +28,6 @@ import org.wso2.carbon.identity.discovery.OIDCProcessor; import org.wso2.carbon.identity.discovery.builders.OIDProviderResponseBuilder; import org.wso2.carbon.identity.oauth.common.OAuthConstants; -import org.wso2.carbon.identity.oauth.endpoint.oidcdiscovery.impl.OIDProviderJSONResponseBuilder; import org.wso2.carbon.identity.oauth.endpoint.util.factory.OIDCProviderServiceFactory; import javax.servlet.http.HttpServletRequest; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java index 68d3b169d25..8e28eb5285c 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/oidcdiscovery/OIDCDiscoveryServiceFactory.java @@ -18,7 +18,6 @@ package org.wso2.carbon.identity.oauth.endpoint.oidcdiscovery; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.discovery.builders.OIDProviderResponseBuilder; import org.wso2.carbon.identity.oauth.endpoint.oidcdiscovery.impl.OIDProviderJSONResponseBuilder; From 62f8c22f947d72235046548e22d0336d0aa831fb Mon Sep 17 00:00:00 2001 From: lashini Date: Fri, 17 Jan 2025 09:26:30 +0530 Subject: [PATCH 6/8] fix OAuth2AuthzServiceFactory.java --- .../oauth/endpoint/authz/OAuth2AuthzServiceFactory.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java index 661e12843aa..9e23d11c32d 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java @@ -18,7 +18,6 @@ package org.wso2.carbon.identity.oauth.endpoint.authz; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImpl; /** @@ -29,12 +28,7 @@ public class OAuth2AuthzServiceFactory { private static final OpenIDConnectClaimFilterImpl SERVICE; static { - OpenIDConnectClaimFilterImpl openIDConnectClaimFilter = (OpenIDConnectClaimFilterImpl) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(OpenIDConnectClaimFilterImpl.class, null); - if (openIDConnectClaimFilter == null) { - throw new IllegalStateException("OpenIDConnectClaimFilterImpl is not available from OSGi context."); - } - SERVICE = openIDConnectClaimFilter; + SERVICE = new OpenIDConnectClaimFilterImpl(); } public static OpenIDConnectClaimFilterImpl getOpenIdClaimFilterImpl() { From df14c67f03a260fefe6e6b6f270e12e3f1af711c Mon Sep 17 00:00:00 2001 From: lashini Date: Fri, 17 Jan 2025 13:26:02 +0530 Subject: [PATCH 7/8] fix osgi service resolving issues --- .../pom.xml | 1 - .../authz/OAuth2AuthzServiceFactory.java | 10 +++- .../endpoint/device/DeviceServiceFactory.java | 7 ++- .../util/factory/WebFingerServiceFactory.java | 46 ------------------- .../oauth/endpoint/util/EndpointUtilTest.java | 3 -- 5 files changed, 12 insertions(+), 55 deletions(-) delete mode 100644 components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml b/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml index 2d5a0beb41f..0357eec64bc 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml +++ b/components/org.wso2.carbon.identity.oauth.endpoint/pom.xml @@ -229,7 +229,6 @@ org.wso2.carbon.identity.oauth.extension compile - diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java index 9e23d11c32d..a4f19aa548a 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java @@ -18,6 +18,8 @@ package org.wso2.carbon.identity.oauth.endpoint.authz; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilter; import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImpl; /** @@ -28,7 +30,13 @@ public class OAuth2AuthzServiceFactory { private static final OpenIDConnectClaimFilterImpl SERVICE; static { - SERVICE = new OpenIDConnectClaimFilterImpl(); + OpenIDConnectClaimFilterImpl openIDConnectClaimFilter = (OpenIDConnectClaimFilterImpl) + PrivilegedCarbonContext.getThreadLocalCarbonContext(). + getOSGiService(OpenIDConnectClaimFilter.class, null); + if (openIDConnectClaimFilter == null) { + throw new IllegalStateException("OpenIdConnectClaimFilter is not available from OSGi context."); + } + SERVICE = openIDConnectClaimFilter; } public static OpenIDConnectClaimFilterImpl getOpenIdClaimFilterImpl() { diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java index f6bb6170ac9..8327f57852b 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java @@ -20,18 +20,17 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; -import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthServiceImpl; /** * Service holder for managing instances of Device Authentication related services. */ public class DeviceServiceFactory { - private static final DeviceAuthServiceImpl SERVICE; + private static final DeviceAuthService SERVICE; static { - DeviceAuthServiceImpl deviceAuthService = (DeviceAuthServiceImpl) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(DeviceAuthServiceImpl.class, null); + DeviceAuthService deviceAuthService = (DeviceAuthService) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(DeviceAuthService.class, null); if (deviceAuthService == null) { throw new IllegalStateException("DeviceAuthService is not available from OSGi context."); } diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java deleted file mode 100644 index e530993538b..00000000000 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/WebFingerServiceFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.oauth.endpoint.util.factory; - -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.webfinger.DefaultWebFingerProcessor; -import org.wso2.carbon.identity.webfinger.WebFingerProcessor; - -/** - * Factory class for WebFingerService. - */ -public class WebFingerServiceFactory { - - private static final WebFingerProcessor SERVICE; - - static { - WebFingerProcessor webFingerService = (DefaultWebFingerProcessor) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(WebFingerProcessor.class, null); - - if (webFingerService == null) { - throw new IllegalStateException("WebFingerService is not available from OSGI context."); - } - SERVICE = webFingerService; - } - - public static WebFingerProcessor getWebFingerService() { - - return SERVICE; - } -} diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java index 2fd006c97a0..d1367ec77ab 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/util/EndpointUtilTest.java @@ -78,7 +78,6 @@ import org.wso2.carbon.identity.oauth.endpoint.util.factory.OIDCProviderServiceFactory; import org.wso2.carbon.identity.oauth.endpoint.util.factory.Oauth2ScopeServiceFactory; import org.wso2.carbon.identity.oauth.endpoint.util.factory.RequestObjectServiceFactory; -import org.wso2.carbon.identity.oauth.endpoint.util.factory.WebFingerServiceFactory; import org.wso2.carbon.identity.oauth2.OAuth2ScopeService; import org.wso2.carbon.identity.oauth2.OAuth2Service; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; @@ -792,8 +791,6 @@ public void testGetLoginPageURLFromCache() throws Exception { @Test public void testGetServices() { - assertTrue(WebFingerServiceFactory.getWebFingerService() instanceof DefaultWebFingerProcessor, - "Retrieved incorrect WebFingerService"); assertTrue(OIDCProviderRequestValidatorFactory.getOIDProviderRequestValidator() instanceof DefaultOIDCProviderRequestBuilder, "Retrieved incorrect OIDProviderRequestValidator"); From 15433b943383f9073de4768d1fccd4d4d0dfc7b9 Mon Sep 17 00:00:00 2001 From: lashini Date: Fri, 17 Jan 2025 14:14:31 +0530 Subject: [PATCH 8/8] refactor tests --- .../identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java | 1 + .../identity/oauth/endpoint/device/DeviceEndpoint.java | 1 + .../oauth/endpoint/device/UserAuthenticationEndpoint.java | 1 + .../{device => util/factory}/DeviceServiceFactory.java | 2 +- .../{authz => util/factory}/OAuth2AuthzServiceFactory.java | 2 +- .../identity/oauth/endpoint/device/DeviceEndpointTest.java | 3 ++- .../endpoint/device/UserAuthenticationEndpointTest.java | 6 ++++-- 7 files changed, 11 insertions(+), 5 deletions(-) rename components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/{device => util/factory}/DeviceServiceFactory.java (95%) rename components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/{authz => util/factory}/OAuth2AuthzServiceFactory.java (96%) diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java index b12082cac57..9e5ca124bd4 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java @@ -111,6 +111,7 @@ import org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; import org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.OAuth2AuthzServiceFactory; import org.wso2.carbon.identity.oauth.extension.engine.JSEngine; import org.wso2.carbon.identity.oauth.extension.utils.EngineUtils; import org.wso2.carbon.identity.oauth2.IdentityOAuth2ClientException; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java index 79d577d33bd..eed7a255c85 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpoint.java @@ -35,6 +35,7 @@ import org.wso2.carbon.identity.oauth.endpoint.OAuthRequestWrapper; import org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointBadRequestException; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.DeviceServiceFactory; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; import org.wso2.carbon.identity.oauth2.device.codegenerator.GenerateKeys; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java index afff573f89c..a12d2e1e056 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpoint.java @@ -32,6 +32,7 @@ import org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint; import org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException; import org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.DeviceServiceFactory; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.device.constants.Constants; import org.wso2.carbon.identity.oauth2.device.dao.DeviceFlowPersistenceFactory; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/DeviceServiceFactory.java similarity index 95% rename from components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java rename to components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/DeviceServiceFactory.java index 8327f57852b..14ae27bda63 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/DeviceServiceFactory.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.oauth.endpoint.device; +package org.wso2.carbon.identity.oauth.endpoint.util.factory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OAuth2AuthzServiceFactory.java similarity index 96% rename from components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java rename to components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OAuth2AuthzServiceFactory.java index a4f19aa548a..35985995063 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzServiceFactory.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/util/factory/OAuth2AuthzServiceFactory.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.oauth.endpoint.authz; +package org.wso2.carbon.identity.oauth.endpoint.util.factory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilter; diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java index 57b5d05e506..ea2a12c039c 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/DeviceEndpointTest.java @@ -52,6 +52,7 @@ import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext; +import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthServiceImpl; import org.wso2.carbon.identity.oauth2.device.dao.DeviceFlowDAO; import org.wso2.carbon.identity.oauth2.device.dao.DeviceFlowPersistenceFactory; @@ -145,7 +146,7 @@ public void setUp() throws Exception { mockedConstruction = mockConstruction(ServiceTracker.class, (mock, context) -> { verify(bundleContext, atLeastOnce()).createFilter(argumentCaptor.capture()); - if (argumentCaptor.getValue().contains(DeviceAuthServiceImpl.class.getName())) { + if (argumentCaptor.getValue().contains(DeviceAuthService.class.getName())) { when(mock.getServices()).thenReturn(new Object[]{deviceAuthService}); } }); diff --git a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java index 0ddf4f105f8..e073ff71a77 100644 --- a/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java +++ b/components/org.wso2.carbon.identity.oauth.endpoint/src/test/java/org/wso2/carbon/identity/oauth/endpoint/device/UserAuthenticationEndpointTest.java @@ -42,7 +42,9 @@ import org.wso2.carbon.identity.oauth.dao.OAuthAppDO; import org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint; import org.wso2.carbon.identity.oauth.endpoint.util.TestOAuthEndpointBase; +import org.wso2.carbon.identity.oauth.endpoint.util.factory.DeviceServiceFactory; import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor; +import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthService; import org.wso2.carbon.identity.oauth2.device.api.DeviceAuthServiceImpl; import org.wso2.carbon.identity.oauth2.device.dao.DeviceFlowDAO; import org.wso2.carbon.identity.oauth2.device.dao.DeviceFlowPersistenceFactory; @@ -201,7 +203,7 @@ public void testDeviceAuthorize(String userCode, String clientId, int expectedVa privilegedCarbonContext.when( PrivilegedCarbonContext::getThreadLocalCarbonContext).thenReturn(mockPrivilegedCarbonContext); - lenient().when(mockPrivilegedCarbonContext.getOSGiService(DeviceAuthServiceImpl.class, null)) + lenient().when(mockPrivilegedCarbonContext.getOSGiService(DeviceAuthService.class, null)) .thenReturn(deviceAuthService); mockOAuthServerConfiguration(oAuthServerConfiguration); @@ -321,7 +323,7 @@ public void testDeviceAuthorizeForURLBuilderExceptionPath(String userCode, Strin when(oAuth2AuthzEndpoint.authorize(any(CommonAuthRequestWrapper.class), any(HttpServletResponse.class))). thenReturn(response); - DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl(); + DeviceAuthService deviceAuthService = new DeviceAuthServiceImpl(); deviceServiceHolder.when(DeviceServiceFactory::getDeviceAuthService).thenReturn(deviceAuthService); userAuthenticationEndpoint = new UserAuthenticationEndpoint();