Search in sources :

Example 36 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project airavata by apache.

the class DefaultAiravataSecurityManager method isUserAuthorized.

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.");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) TException(org.apache.thrift.TException) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) DefaultXACMLPEP(org.apache.airavata.service.security.xacml.DefaultXACMLPEP) ApplicationSettingsException(org.apache.airavata.common.exception.ApplicationSettingsException) GatewayResourceProfile(org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile) RegistryServiceException(org.apache.airavata.registry.api.exception.RegistryServiceException) PasswordCredential(org.apache.airavata.model.credential.store.PasswordCredential) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO) DefaultOAuthClient(org.apache.airavata.service.security.oauth.DefaultOAuthClient) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) CredentialStoreService(org.apache.airavata.credential.store.cpi.CredentialStoreService)

Example 37 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project ballerina by ballerina-lang.

the class RenameUtil method getRenameTextEdits.

/**
 * Get the list of rename related TextEdits.
 *
 * @param locationList      List of locations of occurrences
 * @param documentManager   {@link WorkspaceDocumentManager} instance
 * @param newName           New name to be replaced with
 * @param replaceSymbolName Symbol name being replaced
 * @return {@link List}         List of TextEdits
 */
public static List<TextDocumentEdit> getRenameTextEdits(List<Location> locationList, WorkspaceDocumentManager documentManager, String newName, String replaceSymbolName) {
    Map<String, ArrayList<Location>> documentLocationMap = new HashMap<>();
    List<TextDocumentEdit> documentEdits = new ArrayList<>();
    Comparator<Location> locationComparator = (location1, location2) -> location1.getRange().getStart().getCharacter() - location2.getRange().getStart().getCharacter();
    locationList.forEach(location -> {
        if (documentLocationMap.containsKey(location.getUri())) {
            documentLocationMap.get(location.getUri()).add(location);
        } else {
            documentLocationMap.put(location.getUri(), (ArrayList<Location>) Lists.of(location));
        }
    });
    documentLocationMap.forEach((uri, locations) -> {
        Collections.sort(locations, locationComparator);
        String fileContent = documentManager.getFileContent(CommonUtil.getPath(new LSDocument(uri)));
        String[] contentComponents = fileContent.split("\\n|\\r\\n|\\r");
        int lastNewLineCharIndex = Math.max(fileContent.lastIndexOf("\n"), fileContent.lastIndexOf("\r"));
        int lastCharCol = fileContent.substring(lastNewLineCharIndex + 1).length();
        for (Location location : locations) {
            int line = location.getRange().getStart().getLine();
            StringBuilder lineComponent = new StringBuilder(contentComponents[line]);
            int index = lineComponent.indexOf(replaceSymbolName);
            while (index >= 0) {
                char previousChar = lineComponent.charAt(index - 1);
                if (Character.isLetterOrDigit(previousChar) || String.valueOf(previousChar).equals("_")) {
                    index = lineComponent.indexOf(replaceSymbolName, index + replaceSymbolName.length());
                } else {
                    lineComponent.replace(index, index + replaceSymbolName.length(), newName);
                    index = lineComponent.indexOf(replaceSymbolName, index + newName.length());
                }
            }
            contentComponents[line] = lineComponent.toString();
        }
        Range range = new Range(new Position(0, 0), new Position(contentComponents.length, lastCharCol));
        TextEdit textEdit = new TextEdit(range, String.join("\r\n", Arrays.asList(contentComponents)));
        VersionedTextDocumentIdentifier textDocumentIdentifier = new VersionedTextDocumentIdentifier();
        textDocumentIdentifier.setUri(uri);
        TextDocumentEdit textDocumentEdit = new TextDocumentEdit(textDocumentIdentifier, Collections.singletonList(textEdit));
        documentEdits.add(textDocumentEdit);
    });
    return documentEdits;
}
Also used : CommonUtil(org.ballerinalang.langserver.common.utils.CommonUtil) Arrays(java.util.Arrays) Range(org.eclipse.lsp4j.Range) HashMap(java.util.HashMap) Lists(org.wso2.ballerinalang.util.Lists) ArrayList(java.util.ArrayList) LSDocument(org.ballerinalang.langserver.common.LSDocument) List(java.util.List) TextEdit(org.eclipse.lsp4j.TextEdit) TextDocumentEdit(org.eclipse.lsp4j.TextDocumentEdit) Map(java.util.Map) Location(org.eclipse.lsp4j.Location) Position(org.eclipse.lsp4j.Position) VersionedTextDocumentIdentifier(org.eclipse.lsp4j.VersionedTextDocumentIdentifier) WorkspaceDocumentManager(org.ballerinalang.langserver.workspace.WorkspaceDocumentManager) RenameParams(org.eclipse.lsp4j.RenameParams) Comparator(java.util.Comparator) Collections(java.util.Collections) HashMap(java.util.HashMap) Position(org.eclipse.lsp4j.Position) ArrayList(java.util.ArrayList) TextDocumentEdit(org.eclipse.lsp4j.TextDocumentEdit) Range(org.eclipse.lsp4j.Range) VersionedTextDocumentIdentifier(org.eclipse.lsp4j.VersionedTextDocumentIdentifier) LSDocument(org.ballerinalang.langserver.common.LSDocument) TextEdit(org.eclipse.lsp4j.TextEdit) Location(org.eclipse.lsp4j.Location)

Example 38 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project ballerina by ballerina-lang.

the class TopLevelNodeScopeResolver method isCursorBeforeNode.

/**
 * Check whether the cursor is positioned before the given node start.
 *
 * @param nodePosition      Position of the node
 * @param node              Node
 * @param treeVisitor       {@link TreeVisitor} current tree visitor instance
 * @param completionContext Completion operation context
 * @return {@link Boolean}      Whether the cursor is before the node start or not
 */
@Override
public boolean isCursorBeforeNode(DiagnosticPos nodePosition, Node node, TreeVisitor treeVisitor, TextDocumentServiceContext completionContext) {
    int line = completionContext.get(DocumentServiceKeys.POSITION_KEY).getPosition().getLine();
    int col = completionContext.get(DocumentServiceKeys.POSITION_KEY).getPosition().getCharacter();
    DiagnosticPos zeroBasedPos = CommonUtil.toZeroBasedPosition(nodePosition);
    int nodeSLine = zeroBasedPos.sLine;
    int nodeSCol = zeroBasedPos.sCol;
    if (line < nodeSLine || (line == nodeSLine && col <= nodeSCol)) {
        treeVisitor.setTerminateVisitor(true);
        return true;
    }
    return false;
}
Also used : DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)

Example 39 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class BPMNAppDeployer method undeployArtifacts.

/**
 * Check the artifact type and if it is a BPMN, delete the file from the BPMN
 * deployment hot folder
 *
 * @param carbonApp  - CarbonApplication instance to check for BPMN artifacts
 * @param axisConfig - - axisConfig of the current tenant
 */
public void undeployArtifacts(CarbonApplication carbonApp, AxisConfiguration axisConfig) {
    List<Artifact.Dependency> artifacts = carbonApp.getAppConfig().getApplicationArtifact().getDependencies();
    // loop through all dependencies
    for (Artifact.Dependency dep : artifacts) {
        Deployer deployer;
        Artifact artifact = dep.getArtifact();
        if (artifact == null) {
            continue;
        }
        if (BPMN_TYPE.equals(artifact.getType())) {
            deployer = AppDeployerUtils.getArtifactDeployer(axisConfig, BPMN_DIR, "bar");
        } else {
            continue;
        }
        List<CappFile> files = artifact.getFiles();
        if (files.size() != 1) {
            log.error("A BPMN artifact must have a single file. But " + files.size() + " files found.");
            continue;
        }
        if (deployer != null && AppDeployerConstants.DEPLOYMENT_STATUS_DEPLOYED.equals(artifact.getDeploymentStatus())) {
            String fileName = artifact.getFiles().get(0).getName();
            String artifactPath = artifact.getExtractedPath() + File.separator + fileName;
            try {
                deployer.undeploy(artifactPath);
                artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_PENDING);
            } catch (DeploymentException e) {
                artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_FAILED);
                log.error("Error occured while trying to un deploy : " + artifact.getName());
            }
        }
    }
}
Also used : DeploymentException(org.apache.axis2.deployment.DeploymentException) Artifact(org.wso2.carbon.application.deployer.config.Artifact) Deployer(org.apache.axis2.deployment.Deployer) CappFile(org.wso2.carbon.application.deployer.config.CappFile)

Example 40 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class HumanTaskAppDeployer method deployArtifacts.

/**
 * Check the artifact type and if it is a HumanTask artifact, copy it to the HumanTask deployment hot folder
 *
 * @param carbonApp  - CarbonApplication instance to check for HumanTask artifacts
 * @param axisConfig - AxisConfiguration of the current tenant
 */
public void deployArtifacts(CarbonApplication carbonApp, AxisConfiguration axisConfig) throws DeploymentException {
    List<Artifact.Dependency> artifacts = carbonApp.getAppConfig().getApplicationArtifact().getDependencies();
    // loop through all dependencies
    for (Artifact.Dependency dep : artifacts) {
        Deployer deployer;
        Artifact artifact = dep.getArtifact();
        if (artifact == null) {
            continue;
        }
        if (!isAccepted(artifact.getType())) {
            log.warn("Can't deploy artifact : " + artifact.getName() + " of type : " + artifact.getType() + ". Required features are not installed in the system");
            continue;
        }
        if (HUMANTASK_TYPE.equals(artifact.getType())) {
            deployer = AppDeployerUtils.getArtifactDeployer(axisConfig, HUMANTASK_DIR, "zip");
        } else {
            continue;
        }
        List<CappFile> files = artifact.getFiles();
        if (files.size() != 1) {
            log.error("HumanTask artifacts must have a single file to " + "be deployed. But " + files.size() + " files found.");
            continue;
        }
        if (deployer != null) {
            String fileName = artifact.getFiles().get(0).getName();
            String artifactPath = artifact.getExtractedPath() + File.separator + fileName;
            try {
                deployer.deploy(new DeploymentFileData(new File(artifactPath), deployer));
                artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_DEPLOYED);
                File artifactFile = new File(artifactPath);
                if (artifactFile.exists() && !artifactFile.delete()) {
                    log.warn("Couldn't delete App artifact file : " + artifactPath);
                }
            } catch (DeploymentException e) {
                artifact.setDeploymentStatus(AppDeployerConstants.DEPLOYMENT_STATUS_FAILED);
                throw e;
            }
        }
    }
}
Also used : DeploymentFileData(org.apache.axis2.deployment.repository.util.DeploymentFileData) DeploymentException(org.apache.axis2.deployment.DeploymentException) File(java.io.File) CappFile(org.wso2.carbon.application.deployer.config.CappFile) Artifact(org.wso2.carbon.application.deployer.config.Artifact) Deployer(org.apache.axis2.deployment.Deployer) CappFile(org.wso2.carbon.application.deployer.config.CappFile)

Aggregations

ArrayList (java.util.ArrayList)28 Test (org.junit.Test)23 Response (javax.ws.rs.core.Response)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)21 APIManagerFactory (org.wso2.carbon.apimgt.core.impl.APIManagerFactory)20 HashMap (java.util.HashMap)15 Path (javax.ws.rs.Path)15 RuntimeService (org.activiti.engine.RuntimeService)15 HistoricProcessInstance (org.activiti.engine.history.HistoricProcessInstance)15 InstanceManagementException (org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException)14 Produces (javax.ws.rs.Produces)13 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)13 IOException (java.io.IOException)12 APIMgtAdminServiceImpl (org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl)12 GET (javax.ws.rs.GET)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)10 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)9 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8