using security classes from the services security module in airavata-services
Project: http://git-wip-us.apache.org/repos/asf/airavata/repo Commit: http://git-wip-us.apache.org/repos/asf/airavata/commit/f5235276 Tree: http://git-wip-us.apache.org/repos/asf/airavata/tree/f5235276 Diff: http://git-wip-us.apache.org/repos/asf/airavata/diff/f5235276 Branch: refs/heads/develop Commit: f52352760c01dd1c58e3e5298c14002b2b52dfa7 Parents: 2870924 Author: scnakandala <[email protected]> Authored: Tue May 2 13:53:59 2017 -0400 Committer: scnakandala <[email protected]> Committed: Tue May 2 13:53:59 2017 -0400 ---------------------------------------------------------------------- airavata-api/airavata-api-server/pom.xml | 10 + .../airavata/api/server/AiravataAPIServer.java | 8 +- .../security/AiravataSecurityManager.java | 42 --- .../DefaultAiravataSecurityManager.java | 272 ----------------- .../api/server/security/IdentityContext.java | 42 --- .../security/KeyCloakSecurityManager.java | 290 ------------------- .../airavata/api/server/security/Main.java | 178 ------------ .../server/security/SecurityManagerFactory.java | 59 ---- .../server/security/authzcache/AuthzCache.java | 60 ---- .../security/authzcache/AuthzCacheEntry.java | 62 ---- .../security/authzcache/AuthzCacheIndex.java | 89 ------ .../security/authzcache/AuthzCacheManager.java | 79 ----- .../authzcache/AuthzCacheManagerFactory.java | 59 ---- .../security/authzcache/AuthzCachedStatus.java | 33 --- .../authzcache/DefaultAuthzCacheManager.java | 105 ------- .../security/interceptor/SecurityCheck.java | 35 --- .../interceptor/SecurityInterceptor.java | 82 ------ .../security/interceptor/SecurityModule.java | 42 --- .../security/oauth/DefaultOAuthClient.java | 90 ------ .../server/security/xacml/DefaultPAPClient.java | 124 -------- .../server/security/xacml/DefaultXACMLPEP.java | 132 --------- .../security/KeyCloakSecurityManager.java | 289 ++++++++++++++++++ 22 files changed, 303 insertions(+), 1879 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/pom.xml ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/pom.xml b/airavata-api/airavata-api-server/pom.xml index a1092a5..8cbb8fa 100644 --- a/airavata-api/airavata-api-server/pom.xml +++ b/airavata-api/airavata-api-server/pom.xml @@ -88,6 +88,11 @@ <artifactId>airavata-sharing-registry-stubs</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.apache.airavata</groupId> + <artifactId>services-security</artifactId> + <version>${project.version}</version> + </dependency> <!--<dependency>--> <!--<groupId>org.apache.airavata</groupId>--> <!--<artifactId>group-manager</artifactId>--> @@ -168,6 +173,11 @@ <artifactId>profile-service-stubs</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.apache.airavata</groupId> + <artifactId>services-security</artifactId> + <version>0.17-SNAPSHOT</version> + </dependency> </dependencies> </project> http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/AiravataAPIServer.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/AiravataAPIServer.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/AiravataAPIServer.java index 9fb93ba..1dd2d4c 100644 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/AiravataAPIServer.java +++ b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/AiravataAPIServer.java @@ -23,16 +23,16 @@ import com.google.inject.Guice; import com.google.inject.Injector; import org.apache.airavata.api.Airavata; import org.apache.airavata.api.server.handler.AiravataServerHandler; -import org.apache.airavata.api.server.security.AiravataSecurityManager; -import org.apache.airavata.api.server.security.SecurityManagerFactory; -import org.apache.airavata.api.server.security.interceptor.SecurityModule; -import org.apache.airavata.api.server.util.*; +import org.apache.airavata.api.server.util.Constants; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.IServer; import org.apache.airavata.common.utils.ServerSettings; import org.apache.airavata.model.error.AiravataErrorType; import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.security.AiravataSecurityException; +import org.apache.airavata.service.security.AiravataSecurityManager; +import org.apache.airavata.service.security.SecurityManagerFactory; +import org.apache.airavata.service.security.interceptor.SecurityModule; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TSSLTransportFactory; http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/AiravataSecurityManager.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/AiravataSecurityManager.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/AiravataSecurityManager.java deleted file mode 100644 index d4b598f..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/AiravataSecurityManager.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security; - -import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.security.AiravataSecurityException; - -import java.util.Map; - -public interface AiravataSecurityManager { - /** - * Implement this method in your SecurityManager to perform necessary initializations at the server startup. - * @throws AiravataSecurityException - */ - public void initializeSecurityInfra() throws AiravataSecurityException; - - /** - * Implement this method with the user authentication/authorization logic in your SecurityManager. - * @param authzToken : this includes OAuth token and user's claims - * @param metaData : this includes other meta data needed for security enforcements. - * @return - * @throws AiravataSecurityException - */ - public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException; -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/DefaultAiravataSecurityManager.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/DefaultAiravataSecurityManager.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/DefaultAiravataSecurityManager.java deleted file mode 100644 index 429c4e4..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/DefaultAiravataSecurityManager.java +++ /dev/null @@ -1,272 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security; - -import org.apache.airavata.api.server.security.authzcache.*; -import org.apache.airavata.api.server.security.oauth.DefaultOAuthClient; -import org.apache.airavata.api.server.security.xacml.DefaultPAPClient; -import org.apache.airavata.api.server.security.xacml.DefaultXACMLPEP; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.client.CredentialStoreClientFactory; -import org.apache.airavata.credential.store.cpi.CredentialStoreService; -import org.apache.airavata.model.credential.store.PasswordCredential; -import org.apache.airavata.credential.store.exception.CredentialStoreException; -import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; -import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.registry.api.RegistryService; -import org.apache.airavata.registry.api.client.RegistryServiceClientFactory; -import org.apache.airavata.registry.api.exception.RegistryServiceException; -import org.apache.airavata.security.AiravataSecurityException; -import org.apache.airavata.security.util.TrustStoreManager; -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.ConfigurationContextFactory; -import org.apache.thrift.TException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; - -import java.io.*; -import java.util.List; -import java.util.Map; - -/** - * This enforces authentication and authorization on Airavata API calls. - */ -public class DefaultAiravataSecurityManager implements AiravataSecurityManager { - private final static Logger logger = LoggerFactory.getLogger(DefaultAiravataSecurityManager.class); - - @Override - public void initializeSecurityInfra() throws AiravataSecurityException { - /* in the default security manager, this method checks if the xacml authorization policy is published, - * and if not, publish the policy to the PDP (of WSO2 Identity Server) - */ - try { - if (ServerSettings.isAPISecured()) { - ConfigurationContext configContext = - ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); - //initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server. - TrustStoreManager trustStoreManager = new TrustStoreManager(); - trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), - ServerSettings.getTrustStorePassword()); - List<GatewayResourceProfile> gwProfiles = getRegistryServiceClient().getAllGatewayResourceProfiles(); - //read the policy as a string - BufferedReader bufferedReader = new BufferedReader(new FileReader(new File( - ServerSettings.getAuthorizationPoliyName() + ".xml"))); - String line; - StringBuilder stringBuilder = new StringBuilder(); - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - String defaultXACMLPolicy = stringBuilder.toString(); - CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); - - for(GatewayResourceProfile gwrp : gwProfiles){ - if(gwrp.getIdentityServerPwdCredToken() != null && gwrp.getIdentityServerTenant() != null){ - PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); - String username = credential.getLoginUserName(); - if(gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty()) - username = username + "@" + gwrp.getIdentityServerTenant(); - String password = credential.getPassword(); - DefaultPAPClient PAPClient = new DefaultPAPClient(ServerSettings.getRemoteAuthzServerUrl(), - username, password, configContext); - boolean policyAdded = PAPClient.isPolicyAdded(ServerSettings.getAuthorizationPoliyName()); - if (policyAdded) { - logger.debug("Authorization policy is already added in the authorization server."); - } else { - //publish the policy and enable it in a separate thread - PAPClient.addPolicy(defaultXACMLPolicy); - logger.debug("Authorization policy is published in the authorization server."); - } - }else{ - logger.warn("Identity Server configuration missing for gateway : " + gwrp.getGatewayID()); - } - } - } - } catch (AxisFault axisFault) { - logger.error(axisFault.getMessage(), axisFault); - throw new AiravataSecurityException("Error in initializing the configuration context for creating the " + - "PAP client."); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in reading configuration when creating the PAP client."); - } catch (FileNotFoundException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in reading authorization policy."); - } catch (IOException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in reading the authorization policy."); - } catch (RegistryServiceException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in reading the Gateway Profiles from App Catalog."); - } catch (TException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in connecting to Credential Store Service."); - } - } - - public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException { - try { - String subject = authzToken.getClaimsMap().get(Constants.USER_NAME); - String accessToken = authzToken.getAccessToken(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String action = metaData.get(Constants.API_METHOD_NAME); - - //if the authz cache is enabled, check in the cache if the authz decision is cached and if so, what the status is - if (ServerSettings.isAuthzCacheEnabled()) { - //obtain an instance of AuthzCacheManager implementation. - AuthzCacheManager authzCacheManager = AuthzCacheManagerFactory.getAuthzCacheManager(); - - //check in the cache - AuthzCachedStatus authzCachedStatus = authzCacheManager.getAuthzCachedStatus( - new AuthzCacheIndex(subject, gatewayId, accessToken, action)); - - if (AuthzCachedStatus.AUTHORIZED.equals(authzCachedStatus)) { - logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache."); - return true; - } else if (AuthzCachedStatus.NOT_AUTHORIZED.equals(authzCachedStatus)) { - logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache."); - return false; - } else if (AuthzCachedStatus.NOT_CACHED.equals(authzCachedStatus)) { - logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is not in the cache. " + - "Obtaining it from the authorization server."); - - CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); - GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId); - PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); - String username = credential.getLoginUserName(); - if(gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty()) - username = username + "@" + gwrp.getIdentityServerTenant(); - String password = credential.getPassword(); - - //talk to Authorization Server, obtain the decision, cache it and return the result. - ConfigurationContext configContext = - ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); - - //initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server. - TrustStoreManager trustStoreManager = new TrustStoreManager(); - trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), - ServerSettings.getTrustStorePassword()); - - DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), - username, password, configContext); - OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken( - authzToken.getAccessToken()); - if(validationResponse.getValid()){ - String authorizedUserName = validationResponse.getAuthorizedUser(); - if(authorizedUserName.contains("@")){ - authorizedUserName = authorizedUserName.split("@")[0]; - } - if(subject.contains("@")){ - subject = subject.split("@")[0]; - } - //cannot impersonate users - if(!authorizedUserName.toLowerCase().equals(subject.toLowerCase())) - return false; - - long expiryTimestamp = validationResponse.getExpiryTime(); - - //check for fine grained authorization for the API invocation, based on XACML. - DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), - username, password, configContext); - boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData); - - //cache the authorization decision - authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), - new AuthzCacheEntry(authorizationDecision, expiryTimestamp, System.currentTimeMillis())); - - return authorizationDecision; - }else { - return false; - } - - - } else { - //undefined status returned from the authz cache manager - throw new AiravataSecurityException("Error in reading from the authorization cache."); - } - } else { - CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); - GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId); - PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); - String username = credential.getLoginUserName(); - if(gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty()) - username = username + "@" + gwrp.getIdentityServerTenant(); - String password = credential.getPassword(); - - //talk to Authorization Server, obtain the decision and return the result (authz cache is not enabled). - ConfigurationContext configContext = - ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); - - //initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server. - TrustStoreManager trustStoreManager = new TrustStoreManager(); - trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), - ServerSettings.getTrustStorePassword()); - - DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), - username, password, configContext); - OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken( - authzToken.getAccessToken()); - boolean isOAuthTokenValid = validationResponse.getValid(); - //if XACML based authorization is enabled, check for role based authorization for the API invocation - DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), - username, password, configContext); - boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData); - - return (isOAuthTokenValid && authorizationDecision); - } - - } catch (AxisFault axisFault) { - logger.error(axisFault.getMessage(), axisFault); - throw new AiravataSecurityException("Error in initializing the configuration context for creating the OAuth validation client."); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in reading OAuth server configuration."); - } catch (RegistryServiceException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in accessing AppCatalog."); - } catch (TException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in connecting to Credential Store Service."); - } - } - - private CredentialStoreService.Client getCredentialStoreServiceClient() throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getCredentialStoreServerPort()); - final String serverHost = ServerSettings.getCredentialStoreServerHost(); - try { - return CredentialStoreClientFactory.createAiravataCSClient(serverHost, serverPort); - } catch (CredentialStoreException e) { - throw new TException("Unable to create credential store client...", e); - } - } - - private RegistryService.Client getRegistryServiceClient() throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort()); - final String serverHost = ServerSettings.getRegistryServerHost(); - try { - return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort); - } catch (RegistryServiceException e) { - throw new TException("Unable to create registry client...", e); - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/IdentityContext.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/IdentityContext.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/IdentityContext.java deleted file mode 100644 index 133fadf..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/IdentityContext.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security; - -import org.apache.airavata.model.security.AuthzToken; - -/** - * This provides a thread local container for AuthzToken through out the execution of a particular thread. - */ -public class IdentityContext { - private static ThreadLocal authzTokenContainer = new ThreadLocal(); - - public static void set(AuthzToken authzToken){ - authzTokenContainer.set(authzToken); - } - - public static void unset(){ - authzTokenContainer.remove(); - } - - public static AuthzToken get(){ - return (AuthzToken) authzTokenContainer.get(); - } - -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/KeyCloakSecurityManager.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/KeyCloakSecurityManager.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/KeyCloakSecurityManager.java deleted file mode 100644 index 92cc5d9..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/KeyCloakSecurityManager.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ -package org.apache.airavata.api.server.security; - -import org.apache.airavata.api.server.security.authzcache.*; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.client.CredentialStoreClientFactory; -import org.apache.airavata.credential.store.cpi.CredentialStoreService; -import org.apache.airavata.credential.store.exception.CredentialStoreException; -import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; -import org.apache.airavata.model.credential.store.PasswordCredential; -import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.registry.api.RegistryService; -import org.apache.airavata.registry.api.client.RegistryServiceClientFactory; -import org.apache.airavata.registry.api.exception.RegistryServiceException; -import org.apache.airavata.security.AiravataSecurityException; -import org.apache.airavata.security.util.TrustStoreManager; -import org.apache.thrift.TException; -import org.json.JSONArray; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class KeyCloakSecurityManager implements AiravataSecurityManager { - private final static Logger logger = LoggerFactory.getLogger(KeyCloakSecurityManager.class); - - private HashMap<String, String> rolePermissionConfig = new HashMap<>(); - - - public KeyCloakSecurityManager() throws AiravataSecurityException { - rolePermissionConfig.put("admin", "/airavata/.*"); - rolePermissionConfig.put("gateway-provider", "/airavata/.*"); - rolePermissionConfig.put("admin-read-only", "/airavata/getSSHPubKey|/airavata/getAllGatewaySSHPubKeys" + - "|/airavata/getAllGatewayPWDCredentials|/airavata/getApplicationModule|/airavata/getAllAppModules" + - "|/airavata/getApplicationDeployment|/airavata/getAllApplicationDeployments|/airavata/getAppModuleDeployedResources" + - "|/airavata/getStorageResource|/airavata/getAllStorageResourceNames|/airavata/getSCPDataMovement" + - "|/airavata/getUnicoreDataMovement|/airavata/getGridFTPDataMovement|/airavata/getResourceJobManager" + - "|/airavata/deleteResourceJobManager|/airavata/getGatewayResourceProfile|/airavata/getGatewayComputeResourcePreference" + - "|/airavata/getGatewayStoragePreference|/airavata/getAllGatewayComputeResourcePreferences" + - "|/airavata/getAllGatewayStoragePreferences|/airavata/getAllGatewayResourceProfiles|/airavata/getAPIVersion" + - "|/airavata/getNotification|/airavata/getAllNotifications|/airavata/createProject|/airavata/updateProject" + - "|/airavata/getProject|/airavata/deleteProject|/airavata/getUserProjects|/airavata/searchProjectsByProjectName" + - "|/airavata/searchProjectsByProjectDesc|/airavata/searchExperimentsByName|/airavata/searchExperimentsByDesc" + - "|/airavata/searchExperimentsByApplication|/airavata/searchExperimentsByStatus|/airavata/searchExperimentsByCreationTime" + - "|/airavata/searchExperiments|/airavata/getExperimentStatistics|/airavata/getExperimentsInProject" + - "|/airavata/getUserExperiments|/airavata/createExperiment|/airavata/deleteExperiment|/airavata/getExperiment" + - "|/airavata/getDetailedExperimentTree|/airavata/updateExperiment|/airavata/updateExperimentConfiguration" + - "|/airavata/updateResourceScheduleing|/airavata/validateExperiment|/airavata/launchExperiment" + - "|/airavata/getExperimentStatus|/airavata/getExperimentOutputs|/airavata/getIntermediateOutputs" + - "|/airavata/getJobStatuses|/airavata/getJobDetails|/airavata/cloneExperiment|/airavata/terminateExperiment" + - "|/airavata/getApplicationInterface|/airavata/getAllApplicationInterfaceNames|/airavata/getAllApplicationInterfaces" + - "|/airavata/getApplicationInputs|/airavata/getApplicationOutputs|/airavata/getAvailableAppInterfaceComputeResources" + - "|/airavata/getComputeResource|/airavata/getAllComputeResourceNames|/airavata/getWorkflow|/airavata/getWorkflowTemplateId" + - "|/airavata/isWorkflowExistWithName|/airavata/registerDataProduct|/airavata/getDataProduct|/airavata/registerReplicaLocation" + - "|/airavata/getParentDataProduct|/airavata/getChildDataProducts"); - rolePermissionConfig.put("gateway-user", "/airavata/getAPIVersion|/airavata/getNotification|/airavata/getAllNotifications|" + - "/airavata/createProject|/airavata/updateProject|/airavata/getProject|/airavata/deleteProject|/airavata/getUserProjects|" + - "/airavata/searchProjectsByProjectName|/airavata/searchProjectsByProjectDesc|/airavata/searchExperimentsByName|" + - "/airavata/searchExperimentsByDesc|/airavata/searchExperimentsByApplication|/airavata/searchExperimentsByStatus|" + - "/airavata/searchExperimentsByCreationTime|/airavata/searchExperiments|/airavata/getExperimentStatistics|" + - "/airavata/getExperimentsInProject|/airavata/getUserExperiments|/airavata/createExperiment|/airavata/deleteExperiment|" + - "/airavata/getExperiment|/airavata/getDetailedExperimentTree|/airavata/updateExperiment|/airavata/updateExperimentConfiguration|" + - "/airavata/updateResourceScheduleing|/airavata/validateExperiment|/airavata/launchExperiment|/airavata/getExperimentStatus|" + - "/airavata/getExperimentOutputs|/airavata/getIntermediateOutputs|/airavata/getJobStatuses|/airavata/getJobDetails|" + - "/airavata/cloneExperiment|/airavata/terminateExperiment|/airavata/getApplicationInterface|/airavata/getAllApplicationInterfaceNames|" + - "/airavata/getAllApplicationInterfaces|/airavata/getApplicationInputs|/airavata/getApplicationOutputs|" + - "/airavata/getAvailableAppInterfaceComputeResources|/airavata/getComputeResource|/airavata/getAllComputeResourceNames|" + - "/airavata/getWorkflow|/airavata/getWorkflowTemplateId|/airavata/isWorkflowExistWithName|/airavata/registerDataProduct|" + - "/airavata/getDataProduct|/airavata/registerReplicaLocation|/airavata/getParentDataProduct|/airavata/getChildDataProducts"); - - initializeSecurityInfra(); - } - - /** - * Implement this method in your SecurityManager to perform necessary initializations at the server startup. - * - * @throws AiravataSecurityException - */ - @Override - public void initializeSecurityInfra() throws AiravataSecurityException { - try { - //initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server. - TrustStoreManager trustStoreManager = new TrustStoreManager(); - trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), - ServerSettings.getTrustStorePassword()); - } catch (Exception e) { - throw new AiravataSecurityException(e.getMessage(), e); - } - - } - - /** - * Implement this method with the user authentication/authorization logic in your SecurityManager. - * - * @param authzToken : this includes OAuth token and user's claims - * @param metaData : this includes other meta data needed for security enforcements. - * @return - * @throws AiravataSecurityException - */ - @Override - public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException { - String subject = authzToken.getClaimsMap().get(Constants.USER_NAME); - String accessToken = authzToken.getAccessToken(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String action = "/airavata/" + metaData.get(Constants.API_METHOD_NAME); - try { - if (!ServerSettings.isAPISecured()) { - return true; - } - - if (ServerSettings.isAuthzCacheEnabled()) { - //obtain an instance of AuthzCacheManager implementation. - AuthzCacheManager authzCacheManager = AuthzCacheManagerFactory.getAuthzCacheManager(); - - //check in the cache - AuthzCachedStatus authzCachedStatus = authzCacheManager.getAuthzCachedStatus( - new AuthzCacheIndex(subject, gatewayId, accessToken, action)); - - if (AuthzCachedStatus.AUTHORIZED.equals(authzCachedStatus)) { - logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache."); - return true; - } else if (AuthzCachedStatus.NOT_AUTHORIZED.equals(authzCachedStatus)) { - logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache."); - return false; - } else if (AuthzCachedStatus.NOT_CACHED.equals(authzCachedStatus)) { - logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is not in the cache. " + - "Obtaining it from the authorization server."); - String[] roles = getUserRolesFromOAuthToken(subject, accessToken, gatewayId); - boolean authorizationDecision = hasPermission(roles, action); - //cache the authorization decision - long currentTime = System.currentTimeMillis(); - //TODO get the actual token expiration time - authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), - new AuthzCacheEntry(authorizationDecision, currentTime + 1000 * 60 * 60, currentTime)); - return authorizationDecision; - } else { - //undefined status returned from the authz cache manager - throw new AiravataSecurityException("Error in reading from the authorization cache."); - } - } else { - String[] roles = getUserRolesFromOAuthToken(subject, accessToken, gatewayId); - return hasPermission(roles, action); - } - - } catch (ApplicationSettingsException e) { - e.printStackTrace(); - throw new AiravataSecurityException(e.getMessage(), e); - } catch (Exception e) { - e.printStackTrace(); - throw new AiravataSecurityException(e.getMessage(), e); - } - } - - private String[] getUserRolesFromOAuthToken(String username, String token, String gatewayId) throws Exception { - GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId); - String identityServerRealm = gwrp.getIdentityServerTenant(); - String openIdConnectUrl = getOpenIDConfigurationUrl(identityServerRealm); - JSONObject openIdConnectConfig = new JSONObject(getFromUrl(openIdConnectUrl, token)); - String userInfoEndPoint = openIdConnectConfig.getString("userinfo_endpoint"); - JSONObject userInfo = new JSONObject(getFromUrl(userInfoEndPoint, token)); - if (!username.equals(userInfo.get("preferred_username"))) { - throw new AiravataSecurityException("Subject name and username for the token doesn't match"); - } - String userId = userInfo.getString("sub"); - - String userRoleMappingUrl = ServerSettings.getRemoteIDPServiceUrl() + "/admin/realms/" - + identityServerRealm + "/users/" - + userId + "/role-mappings/realm"; - JSONArray roleMappings = new JSONArray(getFromUrl(userRoleMappingUrl, getAdminAccessToken(gatewayId))); - String[] roles = new String[roleMappings.length()]; - for (int i = 0; i < roleMappings.length(); i++) { - roles[i] = (new JSONObject(roleMappings.get(i).toString())).get("name").toString(); - } - - return roles; - } - - private String getOpenIDConfigurationUrl(String realm) throws ApplicationSettingsException { - return ServerSettings.getRemoteIDPServiceUrl() + "/realms/" + realm + "/.well-known/openid-configuration"; - } - - public String getFromUrl(String urlToRead, String token) throws Exception { - StringBuilder result = new StringBuilder(); - URL url = new URL(urlToRead); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - if (token != null) { - String bearerAuth = "Bearer " + token; - conn.setRequestProperty("Authorization", bearerAuth); - } - BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = rd.readLine()) != null) { - result.append(line); - } - rd.close(); - return result.toString(); - } - - private String getAdminAccessToken(String gatewayId) throws Exception { - CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); - GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId); - String identityServerRealm = gwrp.getIdentityServerTenant(); - String openIdConnectUrl = getOpenIDConfigurationUrl(identityServerRealm); - JSONObject openIdConnectConfig = new JSONObject(getFromUrl(openIdConnectUrl, null)); - PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); - String username = credential.getLoginUserName(); - String password = credential.getPassword(); - String urlString = openIdConnectConfig.getString("token_endpoint"); - StringBuilder result = new StringBuilder(); - URL url = new URL(urlString); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.setDoOutput(true); - String postFields = "client_id=admin-cli&username=" + username + "&password=" + password + "&grant_type=password"; - conn.getOutputStream().write(postFields.getBytes()); - BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = rd.readLine()) != null) { - result.append(line); - } - rd.close(); - JSONObject tokenInfo = new JSONObject(result.toString()); - return tokenInfo.get("access_token").toString(); - } - - - private boolean hasPermission(String[] roles, String apiMethod) { - for (int i = 0; i < roles.length; i++) { - String role = roles[i]; - if (this.rolePermissionConfig.keySet().contains(role)) { - Pattern pattern = Pattern.compile(this.rolePermissionConfig.get(role)); - Matcher matcher = pattern.matcher(apiMethod); - if (matcher.matches()) - return true; - } - } - return false; - } - - private RegistryService.Client getRegistryServiceClient() throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort()); - final String serverHost = ServerSettings.getRegistryServerHost(); - try { - return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort); - } catch (RegistryServiceException e) { - throw new TException("Unable to create registry client...", e); - } - } - - private CredentialStoreService.Client getCredentialStoreServiceClient() throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getCredentialStoreServerPort()); - final String serverHost = ServerSettings.getCredentialStoreServerHost(); - try { - return CredentialStoreClientFactory.createAiravataCSClient(serverHost, serverPort); - } catch (CredentialStoreException e) { - throw new TException("Unable to create credential store client...", e); - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/Main.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/Main.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/Main.java deleted file mode 100644 index abe7654..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/Main.java +++ /dev/null @@ -1,178 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security; - -import org.apache.airavata.api.server.security.oauth.DefaultOAuthClient; -import org.apache.airavata.api.server.security.xacml.DefaultXACMLPEP; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.model.error.AuthenticationException; -import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.security.AiravataSecurityException; -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.ConfigurationContextFactory; -import org.apache.oltu.oauth2.client.URLConnectionClient; -import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest; -import org.apache.oltu.oauth2.client.response.OAuthResourceResponse; -import org.apache.oltu.oauth2.common.OAuth; -import org.apache.oltu.oauth2.common.message.types.GrantType; -import org.codehaus.jackson.map.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; - -import java.util.HashMap; -import java.util.Map; - -public class Main { - private final static Logger logger = LoggerFactory.getLogger(Main.class); - - private static String username = "scigap_admin"; - private static String password = "sci9067@min"; - private static String hostName = "https://idp.scigap.org:7443"; -// private static String clientId = "KUu0a74dFbrwvSxD3C_GhwKeNrQa"; - private static String clientId = "O3iUdkkVYyHgzWPiVTQpY_tb96Ma"; -// private static String clientSecret = "UTKb9nDOPsuWB4lEX39TwhkW8qIa"; - private static String clientSecret = "6Ck1jZoa2oRtrzodSqkUZ2iINkUa"; - - public static void main(String[] args) throws AuthenticationException, AiravataSecurityException, AxisFault { - String accessToken = authenticate("[email protected]", "master").getAccess_token(); - ConfigurationContext configContext = - ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); - DefaultOAuthClient defaultOAuthClient = new DefaultOAuthClient(hostName+"/services/",username,password, configContext); - OAuth2TokenValidationResponseDTO tokenValidationRequestDTO = defaultOAuthClient.validateAccessToken(accessToken); - String authorizedUser = tokenValidationRequestDTO.getAuthorizedUser(); - AuthzToken authzToken = new AuthzToken(); - authzToken.setAccessToken(accessToken); - Map<String, String> claimsMap = new HashMap<>(); - claimsMap.put(Constants.USER_NAME, "scigap_admin"); - claimsMap.put(Constants.API_METHOD_NAME, "/airavata/getAPIVersion"); - authzToken.setClaimsMap(claimsMap); - - DefaultXACMLPEP defaultXACMLPEP = new DefaultXACMLPEP(hostName+"/services/",username,password,configContext); - HashMap<String, String> metaDataMap = new HashMap(); - boolean result = defaultXACMLPEP.getAuthorizationDecision(authzToken, metaDataMap); - System.out.println(result); - } - - public static AuthResponse authenticate(String username,String password) throws AuthenticationException { - try { - OAuthClientRequest request = OAuthClientRequest.tokenLocation(hostName+"/oauth2/token"). - setClientId(clientId).setClientSecret(clientSecret). - setGrantType(GrantType.PASSWORD). - setRedirectURI(""). - setUsername(username). - setPassword(password). - setScope("openid"). - buildBodyMessage(); - - - URLConnectionClient ucc = new URLConnectionClient(); - - org.apache.oltu.oauth2.client.OAuthClient oAuthClient = new org.apache.oltu.oauth2.client.OAuthClient(ucc); - OAuthResourceResponse resp = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class); - - //converting JSON to object - ObjectMapper mapper = new ObjectMapper(); - AuthResponse authResponse; - try{ - authResponse = mapper.readValue(resp.getBody(), AuthResponse.class); - }catch (Exception e){ - return null; - } - - String accessToken = authResponse.getAccess_token(); - if(accessToken != null && !accessToken.isEmpty()){ - request = new OAuthBearerClientRequest(hostName + "/oauth2/userinfo?schema=openid"). - buildQueryMessage(); - ucc = new URLConnectionClient(); - request.setHeader("Authorization","Bearer "+accessToken); - oAuthClient = new org.apache.oltu.oauth2.client.OAuthClient(ucc); - resp = oAuthClient.resource(request, OAuth.HttpMethod.GET, - OAuthResourceResponse.class); - Map<String,String> profile = mapper.readValue(resp.getBody(), Map.class); - return authResponse; - } - }catch (Exception ex){ - throw new AuthenticationException(ex.getMessage()); - } - return null; - } -} - -class AuthResponse{ - - private String token_type; - private int expires_in; - private String refresh_token; - private String access_token; - public String id_token; - private String scope; - - - public String getToken_type() { - return token_type; - } - - public void setToken_type(String token_type) { - this.token_type = token_type; - } - - public int getExpires_in() { - return expires_in; - } - - public void setExpires_in(int expires_in) { - this.expires_in = expires_in; - } - - public String getRefresh_token() { - return refresh_token; - } - - public void setRefresh_token(String refresh_token) { - this.refresh_token = refresh_token; - } - - public String getAccess_token() { - return access_token; - } - - public void setAccess_token(String access_token) { - this.access_token = access_token; - } - - public String getId_token() { - return id_token; - } - - public void setId_token(String id_token) { - this.id_token = id_token; - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/SecurityManagerFactory.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/SecurityManagerFactory.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/SecurityManagerFactory.java deleted file mode 100644 index b68b741..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/SecurityManagerFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security; - -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.security.AiravataSecurityException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This initializes an instance of the appropriate security manager according to the - * configuration. - */ -public class SecurityManagerFactory { - private final static Logger logger = LoggerFactory.getLogger(SecurityManagerFactory.class); - - public static AiravataSecurityManager getSecurityManager() throws AiravataSecurityException { - try { - Class secManagerImpl = Class.forName(ServerSettings.getSecurityManagerClassName()); - AiravataSecurityManager securityManager = (AiravataSecurityManager) secManagerImpl.newInstance(); - return securityManager; - } catch (ClassNotFoundException e) { - String error = "Security Manager class could not be found."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - } catch (ApplicationSettingsException e) { - String error = "Error in reading the configuration related to Security Manager class."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - } catch (InstantiationException e) { - String error = "Error in instantiating the Security Manager class."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - } catch (IllegalAccessException e) { - String error = "Error in instantiating the Security Manager class."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - - } - } -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCache.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCache.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCache.java deleted file mode 100644 index 068c98a..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCache.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.authzcache; - -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.ServerSettings; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.LinkedHashMap; -import java.util.Map; - -public class AuthzCache extends LinkedHashMap<AuthzCacheIndex, AuthzCacheEntry> { - - private static int MAX_SIZE; - private final static Logger logger = LoggerFactory.getLogger(AuthzCache.class); - - private static AuthzCache authzCache = null; - - public static AuthzCache getInstance() throws ApplicationSettingsException { - if (authzCache == null) { - synchronized (AuthzCache.class) { - if (authzCache == null) { - authzCache = new AuthzCache(ServerSettings.getCacheSize()); - } - } - } - return authzCache; - } - - private AuthzCache(int initialCapacity) { - super(initialCapacity); - MAX_SIZE = initialCapacity; - } - - @Override - protected boolean removeEldestEntry(Map.Entry<AuthzCacheIndex, AuthzCacheEntry> eldest) { - if (size() > MAX_SIZE) { - logger.info("Authz cache max size exceeded. Removing the old entries."); - } - return size() > MAX_SIZE; - } -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheEntry.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheEntry.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheEntry.java deleted file mode 100644 index 83bee72..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheEntry.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.authzcache; - -/** - * Cache entry in the default authorization cache. - */ -public class AuthzCacheEntry { - //authorization decision for the authorization request associated with this cache entry. - private boolean decision; - //time to live value for the access token in seconds. - private long expiryTime; - //time stamp in milli seconds at the time this entry is put into the cache - private long entryTimestamp; - - public AuthzCacheEntry(boolean decision, long expiryTime, long entryTimestamp) { - this.decision = decision; - this.expiryTime = expiryTime; - this.entryTimestamp = entryTimestamp; - } - - public long getEntryTimestamp() { - return entryTimestamp; - } - - public void setEntryTimestamp(long entryTimestamp) { - this.entryTimestamp = entryTimestamp; - } - - public long getExpiryTime() { - return expiryTime; - } - - public void setExpiryTime(long timestamp) { - this.expiryTime = timestamp; - } - - public boolean getDecision() { - return decision; - } - - public void setDecision(boolean decision) { - this.decision = decision; - } -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheIndex.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheIndex.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheIndex.java deleted file mode 100644 index 50e5873..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheIndex.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.authzcache; - -/** - * Cache index of the default authorization cache. - */ -public class AuthzCacheIndex { - - private String subject; - private String oauthAccessToken; - private String action; - private String gatewayId; - - public AuthzCacheIndex(String userName, String gatewayId, String accessToken, String actionString) { - this.subject = userName; - this.oauthAccessToken = accessToken; - this.action = actionString; - this.gatewayId = gatewayId; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getOauthAccessToken() { - return oauthAccessToken; - } - - public void setOauthAccessToken(String oauthAccessToken) { - this.oauthAccessToken = oauthAccessToken; - } - - public String getGatewayId() { - return gatewayId; - } - - public void setGatewayId(String gatewayId) { - this.gatewayId = gatewayId; - } - - /*Equals and hash code methods are overridden since this is being used as an index of a map and that containsKey method - * should return true if the values of two index objects are equal.*/ - @Override - public boolean equals(Object other) { - if (other == null || other.getClass() != getClass()) { - return false; - } - return ((this.getSubject().equals(((AuthzCacheIndex) other).getSubject())) - && (this.getGatewayId().equals(((AuthzCacheIndex) other).getGatewayId())) - && (this.getOauthAccessToken().equals(((AuthzCacheIndex) other).getOauthAccessToken())) - && (this.getAction().equals(((AuthzCacheIndex) other).getAction()))); - } - - @Override - public int hashCode() { - return this.getSubject().hashCode() + this.getOauthAccessToken().hashCode() + this.getGatewayId().hashCode() - + this.getAction().hashCode(); - } -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManager.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManager.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManager.java deleted file mode 100644 index 90cd605..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManager.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.authzcache; - -import org.apache.airavata.security.AiravataSecurityException; - -/** - * This is the interface through which security manager accesses the underlying caching implementation - * See the DefaultAuthzCacheManager.java for an example implementation of this interface. - */ -public interface AuthzCacheManager { - /** - * Returns the status of the cache w.r.t the given authorization request which is encapsulated in - * the AuthzCacheIndex. - * - * @param authzCacheIndex - * @return - */ - public AuthzCachedStatus getAuthzCachedStatus(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException; - - /** - * Add to cache the authorization decision pertaining to a given authorization request. - * - * @param authzCacheIndex - * @param authzCacheEntry - * @throws AiravataSecurityException - */ - public void addToAuthzCache(AuthzCacheIndex authzCacheIndex, AuthzCacheEntry authzCacheEntry) throws AiravataSecurityException; - - /** - * Check if a valid decision is cached for a given authorization request. - * - * @param authzCacheIndex - * @return - */ - public boolean isAuthzDecisionCached(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException; - - /** - * Returns the AuthzCacheEntry for a given authorization request. - * - * @param authzCacheIndex - * @return - * @throws AiravataSecurityException - */ - public AuthzCacheEntry getAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException; - - /** - * Removes the authorization cache entry for a given authorization request. - * - * @param authzCacheIndex - * @throws AiravataSecurityException - */ - public void removeAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException; - - /** - * Clear the authorization cache. - * - * @return - */ - public void clearCache() throws AiravataSecurityException; - -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManagerFactory.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManagerFactory.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManagerFactory.java deleted file mode 100644 index 75e7db9..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCacheManagerFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.authzcache; - -import org.apache.airavata.api.server.security.AiravataSecurityManager; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.security.AiravataSecurityException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * This initializes the AuthzCacheManager implementation to be used as defined by the configuration. - */ -public class AuthzCacheManagerFactory { - private final static Logger logger = LoggerFactory.getLogger(AuthzCacheManagerFactory.class); - - public static AuthzCacheManager getAuthzCacheManager() throws AiravataSecurityException { - try { - Class authzCacheManagerImpl = Class.forName(ServerSettings.getAuthzCacheManagerClassName()); - AuthzCacheManager authzCacheManager = (AuthzCacheManager) authzCacheManagerImpl.newInstance(); - return authzCacheManager; - } catch (ClassNotFoundException e) { - String error = "Authorization Cache Manager class could not be found."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - } catch (ApplicationSettingsException e) { - String error = "Error in reading the configuration related to Authorization Cache Manager class."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - } catch (InstantiationException e) { - String error = "Error in instantiating the Authorization Cache Manager class."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - } catch (IllegalAccessException e) { - String error = "Error in instantiating the Authorization Cache Manager class."; - logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); - - } - } - -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCachedStatus.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCachedStatus.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCachedStatus.java deleted file mode 100644 index ef739fb..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/AuthzCachedStatus.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.authzcache; - -/** - * This enum defines the status of the authorization cache returned by the authorization cache manager - * when an authorization status is checked against an authorization request. - */ -public enum AuthzCachedStatus { - /*Authorization decision is cached for the given authrization request and the decision authorizes the request.*/ - AUTHORIZED, - /*Authorization decision is cached for the given authorization request and the decision denies authorization.*/ - NOT_AUTHORIZED, - /*Authorization decision is not either cached or the cached entry is invalid such that re-authorization is needed.*/ - NOT_CACHED -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/DefaultAuthzCacheManager.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/DefaultAuthzCacheManager.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/DefaultAuthzCacheManager.java deleted file mode 100644 index 93c9212..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/authzcache/DefaultAuthzCacheManager.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.authzcache; - -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.security.AiravataSecurityException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DefaultAuthzCacheManager implements AuthzCacheManager { - - private final static Logger logger = LoggerFactory.getLogger(DefaultAuthzCacheManager.class); - - @Override - public AuthzCachedStatus getAuthzCachedStatus(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException { - if (isAuthzDecisionCached(authzCacheIndex)) { - AuthzCacheEntry cacheEntry = getAuthzCacheEntry(authzCacheIndex); - long expiryTime = cacheEntry.getExpiryTime(); - long currentTime = System.currentTimeMillis(); - long timePassed = (currentTime - cacheEntry.getEntryTimestamp()) / 1000; - if (expiryTime > timePassed) { - //access token is still valid. Hence, return the cached decision - if (cacheEntry.getDecision()) { - return AuthzCachedStatus.AUTHORIZED; - } else { - return AuthzCachedStatus.NOT_AUTHORIZED; - } - } else { - //access token has been expired. Hence, remove the entry and return. - removeAuthzCacheEntry(authzCacheIndex); - return AuthzCachedStatus.NOT_CACHED; - } - } else { - return AuthzCachedStatus.NOT_CACHED; - } - } - - @Override - public void addToAuthzCache(AuthzCacheIndex authzCacheIndex, AuthzCacheEntry authzCacheEntry) throws AiravataSecurityException { - try { - AuthzCache.getInstance().put(authzCacheIndex, authzCacheEntry); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); - } - } - - @Override - public boolean isAuthzDecisionCached(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException { - try { - return AuthzCache.getInstance().containsKey(authzCacheIndex); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); - } - } - - @Override - public AuthzCacheEntry getAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException { - try { - return AuthzCache.getInstance().get(authzCacheIndex); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); - } - } - - @Override - public void removeAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throws AiravataSecurityException { - try { - AuthzCache.getInstance().remove(authzCacheIndex); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); - } - } - - @Override - public void clearCache() throws AiravataSecurityException { - try { - AuthzCache.getInstance().clear(); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); - - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityCheck.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityCheck.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityCheck.java deleted file mode 100644 index c137898..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityCheck.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.interceptor; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import com.google.inject.BindingAnnotation; - -/** - * This is just the definition of the annotation used to mark the API methods to be intercepted. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -@BindingAnnotation -public @interface SecurityCheck { -} http://git-wip-us.apache.org/repos/asf/airavata/blob/f5235276/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityInterceptor.java ---------------------------------------------------------------------- diff --git a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityInterceptor.java b/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityInterceptor.java deleted file mode 100644 index 6278dc3..0000000 --- a/airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/security/interceptor/SecurityInterceptor.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.airavata.api.server.security.interceptor; - -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.apache.airavata.api.server.security.AiravataSecurityManager; -import org.apache.airavata.api.server.security.IdentityContext; -import org.apache.airavata.api.server.security.SecurityManagerFactory; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.model.error.AuthorizationException; -import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.security.AiravataSecurityException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; - -/** - * Interceptor of Airavata API calls for the purpose of applying security. - */ -public class SecurityInterceptor implements MethodInterceptor { - private final static Logger logger = LoggerFactory.getLogger(SecurityInterceptor.class); - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - //obtain the authz token from the input parameters - AuthzToken authzToken = (AuthzToken) invocation.getArguments()[0]; - //authorize the API call - HashMap<String, String> metaDataMap = new HashMap(); - metaDataMap.put(Constants.API_METHOD_NAME, invocation.getMethod().getName()); - authorize(authzToken, metaDataMap); - //set the user identity info in a thread local to be used in downstream execution. - IdentityContext.set(authzToken); - //let the method call procees upon successful authorization - Object returnObj = invocation.proceed(); - //clean the identity context before the method call returns - IdentityContext.unset(); - return returnObj; - } - - private void authorize(AuthzToken authzToken, Map<String, String> metaData) throws AuthorizationException { - try { - boolean isAPISecured = ServerSettings.isAPISecured(); - if (isAPISecured) { - AiravataSecurityManager securityManager = SecurityManagerFactory.getSecurityManager(); - boolean isAuthz = securityManager.isUserAuthorized(authzToken, metaData); - if (!isAuthz) { - throw new AuthorizationException("User is not authenticated or authorized."); - } - } - } catch (AiravataSecurityException e) { - logger.error(e.getMessage(), e); - throw new AuthorizationException("Error in authenticating or authorizing user."); - } catch (ApplicationSettingsException e) { - logger.error(e.getMessage(), e); - throw new AuthorizationException("Internal error in authenticating or authorizing user."); - } - } -} - -
