Search in sources :

Example 1 with AuditReportDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AuditReportDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAuditReportOfAPI.

/**
 * Method to retrieve Security Audit Report
 * @param apiId API ID of the API
 * @param accept Accept header string
 * @param messageContext Message Context string
 * @return Response object of Security Audit
 */
@Override
public Response getAuditReportOfAPI(String apiId, String accept, MessageContext messageContext) {
    boolean isDebugEnabled = log.isDebugEnabled();
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        APIIdentifier apiIdentifier = api.getId();
        String apiDefinition = apiProvider.getOpenAPIDefinition(apiIdentifier, organization);
        // Get configuration file, retrieve API token and collection id
        JSONObject securityAuditPropertyObject = apiProvider.getSecurityAuditAttributesFromConfig(username);
        String apiToken = (String) securityAuditPropertyObject.get("apiToken");
        String collectionId = (String) securityAuditPropertyObject.get("collectionId");
        String baseUrl = (String) securityAuditPropertyObject.get("baseUrl");
        if (baseUrl == null) {
            baseUrl = APIConstants.BASE_AUDIT_URL;
        }
        // Retrieve the uuid from the database
        String auditUuid = ApiMgtDAO.getInstance().getAuditApiId(api.getUuid());
        if (auditUuid != null) {
            updateAuditApi(apiDefinition, apiToken, auditUuid, baseUrl, isDebugEnabled);
        } else {
            auditUuid = createAuditApi(collectionId, apiToken, apiIdentifier, apiDefinition, baseUrl, isDebugEnabled, organization);
        }
        // Logic for the HTTP request
        String getUrl = baseUrl + "/" + auditUuid + APIConstants.ASSESSMENT_REPORT;
        URL getReportUrl = new URL(getUrl);
        try (CloseableHttpClient getHttpClient = (CloseableHttpClient) APIUtil.getHttpClient(getReportUrl.getPort(), getReportUrl.getProtocol())) {
            HttpGet httpGet = new HttpGet(getUrl);
            // Set the header properties of the request
            httpGet.setHeader(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
            httpGet.setHeader(APIConstants.HEADER_API_TOKEN, apiToken);
            httpGet.setHeader(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
            // Code block for the processing of the response
            try (CloseableHttpResponse response = getHttpClient.execute(httpGet)) {
                if (isDebugEnabled) {
                    log.debug("HTTP status " + response.getStatusLine().getStatusCode());
                }
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
                    String inputLine;
                    StringBuilder responseString = new StringBuilder();
                    while ((inputLine = reader.readLine()) != null) {
                        responseString.append(inputLine);
                    }
                    reader.close();
                    JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
                    String report = responseJson.get(APIConstants.DATA).toString();
                    String grade = (String) ((JSONObject) ((JSONObject) responseJson.get(APIConstants.ATTR)).get(APIConstants.DATA)).get(APIConstants.GRADE);
                    Integer numErrors = Integer.valueOf((String) ((JSONObject) ((JSONObject) responseJson.get(APIConstants.ATTR)).get(APIConstants.DATA)).get(APIConstants.NUM_ERRORS));
                    String decodedReport = new String(Base64Utils.decode(report), StandardCharsets.UTF_8);
                    AuditReportDTO auditReportDTO = new AuditReportDTO();
                    auditReportDTO.setReport(decodedReport);
                    auditReportDTO.setGrade(grade);
                    auditReportDTO.setNumErrors(numErrors);
                    auditReportDTO.setExternalApiId(auditUuid);
                    return Response.ok().entity(auditReportDTO).build();
                }
            }
        }
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error occurred while getting " + "HttpClient instance", e, log);
    } catch (ParseException e) {
        RestApiUtil.handleInternalServerError("API Definition String " + "could not be parsed into JSONObject.", e, log);
    } catch (APIManagementException e) {
        String errorMessage = "Error while Auditing API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URL(java.net.URL) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader) 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) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) AuditReportDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AuditReportDTO)

Aggregations

BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 URL (java.net.URL)1 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)1 HttpGet (org.apache.http.client.methods.HttpGet)1 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)1 JSONObject (org.json.simple.JSONObject)1 JSONParser (org.json.simple.parser.JSONParser)1 ParseException (org.json.simple.parser.ParseException)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)1 API (org.wso2.carbon.apimgt.api.model.API)1 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)1 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)1 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)1 AuditReportDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AuditReportDTO)1