Search in sources :

Example 11 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateMgtUtilTest method testDeleteNonExistingCertificate.

@Test
public void testDeleteNonExistingCertificate() {
    ResponseCode responseCode = certificateMgtUtils.removeCertificateFromTrustStore(ALIAS_NOT_EXIST);
    Assert.assertEquals(responseCode, ResponseCode.CERTIFICATE_NOT_FOUND);
}
Also used : ResponseCode(org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode) Test(org.junit.Test)

Example 12 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class CertificateManagerImplTest method testRemoveFromPublisher.

@Test
public void testRemoveFromPublisher() throws CertificateManagementException {
    PowerMockito.stub(PowerMockito.method(CertificateMgtUtils.class, "removeCertificateFromTrustStore", String.class)).toReturn(ResponseCode.SUCCESS);
    Mockito.when(certificateMgtDAO.deleteCertificate(ALIAS, END_POINT, TENANT_ID)).thenReturn(true);
    List<CertificateMetadataDTO> certificateMetadataDTOList = new ArrayList<>();
    CertificateMetadataDTO certificateMetadataDTO = new CertificateMetadataDTO();
    certificateMetadataDTO.setAlias(ALIAS);
    certificateMetadataDTO.setEndpoint(END_POINT);
    certificateMetadataDTOList.add(certificateMetadataDTO);
    Mockito.when(certificateMgtDAO.getCertificates(ALIAS, null, TENANT_ID)).thenReturn(certificateMetadataDTOList);
    ResponseCode responseCode = certificateManager.deleteCertificateFromParentNode(ALIAS, END_POINT, TENANT_ID);
    Assert.assertEquals(ResponseCode.SUCCESS, responseCode);
}
Also used : CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) ArrayList(java.util.ArrayList) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 13 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class OAuthClient method getTokenResponse.

/**
 * Method to retrieve the token response sent from the backend
 * @param response CloseableHttpResponse object
 * @return TokenResponse object containing the details retrieved from the backend
 * @throws APIManagementException In the event of an unexpected HTTP status code from the backend
 * @throws IOException In the event of a problem parsing the response from the backend
 */
private static TokenResponse getTokenResponse(CloseableHttpResponse response) throws APIManagementException, IOException, ParseException {
    int responseCode = response.getStatusLine().getStatusCode();
    if (!(responseCode == HttpStatus.SC_OK)) {
        throw new APIManagementException("Error while accessing the Token URL. " + "Found http status " + response.getStatusLine());
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
    String inputLine;
    StringBuilder stringBuilder = new StringBuilder();
    while ((inputLine = reader.readLine()) != null) {
        stringBuilder.append(inputLine);
    }
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse = (JSONObject) parser.parse(stringBuilder.toString());
    TokenResponse tokenResponse = new TokenResponse();
    if (jsonResponse.containsKey("access_token")) {
        tokenResponse.setAccessToken((String) jsonResponse.get("access_token"));
        if (jsonResponse.containsKey("refresh_token")) {
            tokenResponse.setRefreshToken((String) jsonResponse.get("refresh_token"));
        }
        if (jsonResponse.containsKey("scope")) {
            Set<String> scopeSet = Stream.of(jsonResponse.get("scope").toString().trim().split("\\s*,\\s*")).collect(Collectors.toSet());
            tokenResponse.setScope(scopeSet);
        }
        if (jsonResponse.containsKey("token_type")) {
            tokenResponse.setTokenType((String) jsonResponse.get("token_type"));
        }
        if (jsonResponse.containsKey("expires_in")) {
            tokenResponse.setExpiresIn(jsonResponse.get("expires_in").toString());
            long currentTimeInSeconds = System.currentTimeMillis() / 1000;
            long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
            tokenResponse.setValidTill(expiryTimeInSeconds);
        } else if (null != APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG)) {
            tokenResponse.setExpiresIn(APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG));
            long currentTimeInSeconds = System.currentTimeMillis() / 1000;
            long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
            tokenResponse.setValidTill(expiryTimeInSeconds);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Response: [status-code] " + responseCode + " [message] " + stringBuilder.toString());
    }
    if (tokenResponse.getAccessToken() != null) {
        return tokenResponse;
    } else {
        return null;
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) InputStreamReader(java.io.InputStreamReader) JSONObject(org.json.simple.JSONObject) BufferedReader(java.io.BufferedReader) JSONParser(org.json.simple.parser.JSONParser)

Example 14 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method deleteAPIClientCertificateByAlias.

@Override
public Response deleteAPIClientCertificateByAlias(String alias, String apiId, MessageContext messageContext) {
    String organization = null;
    try {
        organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        validateAPIExistence(apiId);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
        int responseCode = apiProvider.deleteClientCertificate(RestApiCommonUtil.getLoggedInUsername(), clientCertificateDTO.getApiIdentifier(), alias);
        if (responseCode == ResponseCode.SUCCESS.getResponseCode()) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            if (log.isDebugEnabled()) {
                log.debug(String.format("The client certificate which belongs to tenant : %s represented by the " + "alias : %s is deleted successfully", organization, alias));
            }
            return Response.ok().entity("The certificate for alias '" + alias + "' deleted successfully.").build();
        } else {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Failed to delete the client certificate which belongs to tenant : %s " + "represented by the alias : %s.", organization, alias));
            }
            RestApiUtil.handleInternalServerError("Error while deleting the client certificate for alias '" + alias + "'.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while deleting the client certificate with alias " + alias + " for the tenant " + organization, e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 15 with ResponseCode

use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method addAPIClientCertificate.

@Override
public Response addAPIClientCertificate(String apiId, InputStream certificateInputStream, Attachment certificateDetail, String alias, String tier, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isEmpty(alias) || StringUtils.isEmpty(apiId)) {
            RestApiUtil.handleBadRequest("The alias and/ or apiId should not be empty", log);
        }
        if (StringUtils.isBlank(fileName)) {
            RestApiUtil.handleBadRequest("Certificate addition failed. Proper Certificate file should be provided", log);
        }
        // validate if api exists
        validateAPIExistence(apiId);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        String userName = RestApiCommonUtil.getLoggedInUsername();
        String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
        int responseCode = apiProvider.addClientCertificate(userName, api.getId(), base64EncodedCert, alias, tier, organization);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Add certificate operation response code : %d", responseCode));
        }
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            ClientCertMetadataDTO certificateDTO = new ClientCertMetadataDTO();
            certificateDTO.setAlias(alias);
            certificateDTO.setApiId(apiId);
            certificateDTO.setTier(tier);
            URI createdCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.created(createdCertUri).entity(certificateDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Internal server error while adding the client certificate to " + "API " + apiId, log);
        } else if (ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceAlreadyExistsError("The alias '" + alias + "' already exists in the trust store.", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while adding the certificate to the API " + apiId + ". " + "Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("APIManagement exception while adding the certificate to the API " + apiId + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("IOException while generating the encoded certificate for the API " + apiId, e, log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Aggregations

ResponseCode (org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode)18 Test (org.junit.Test)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 IOException (java.io.IOException)8 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 ArrayList (java.util.ArrayList)5 CertificateMetadataDTO (org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 UserStoreException (org.wso2.carbon.user.api.UserStoreException)4 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 ContentDisposition (org.apache.cxf.jaxrs.ext.multipart.ContentDisposition)3 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)3 API (org.wso2.carbon.apimgt.api.model.API)3 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)3 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)3 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)3 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)3 CertificateAliasExistsException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateAliasExistsException)3 CertificateManagementException (org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException)3