Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Anypoint Platform Audit — Extracting API Access and Client Contracts

DZone 's Guide to

Anypoint Platform Audit — Extracting API Access and Client Contracts

Learn how to extract API access and client contracts.

Free Resource

Introduction

MuleSoft’s Anypoint Platform™ is the world’s leading integration platform for SOA, SaaS, and APIs. By leveraging Anypoint Platform, companies can re-architect their SOA infrastructure from legacy systems, proprietary platforms, and custom integration code to create business agility. They can migrate technology infrastructure to the public or private cloud and prioritize adoption of SaaS applications and other cloud technologies. It is also important to adapt to a DevOps culture to bring in this agility in the process of transforming the business.

Continuous Integration is the most important part of DevOps that is used to integrate various stages, and Jenkins is one of the most famous tools. Jenkins is an open source automation tool written in Java with plugins built for Continuous Integration purposes. Jenkins is used to build and test software projects continuously, making it easier for developers to integrate changes to the project and making it easier for users to obtain a fresh build. But shouldn’t there be more to it? What if we could create a Jenkins Scripted Pipeline that can be used to support some of the Audit asks?

What's the Puzzle?

There are many projects that use MuleSoft to implement their API strategy. The API Manager within the solution can manage every API implemented in the platform. This service can provide visibility around every consumer that a given API has and what the SLA’s that each consumer adheres to. There were asks on performing an audit on all the available clients for every API deployed in the platform. However, it becomes hard to have such audits manually on the platform as the number application in the System grows over time and so does the need for frequent audits.

But why is this audit important? Usually, there will be a need for having clear isolation among the clients calling the APIs on sandbox environments vs. production. They will be assigned different SLAs; support contract would be different, and the monitoring solution might track different metrics for these client applications or requests from those clients. Technically, there is no way in the platform we could enforce this. So, it becomes very important that we audit these frequently to ensure that they are being followed as per the standards. But then how to generate this report from the platform? There are platform APIs that could give us this data, but we will have to build that orchestration service somewhere to generate this report. That’s when we decided to implement a scripted pipeline in Jenkins to build this solution and realized how easy it was to get to that.

Solution

The below Jenkins Scripted Pipeline implements the orchestration of the Anypoint platform APIs and extracts all the information about the applications as well as their contract details in a CSV format. This CSV file is then published in the dashboard of the Job in Jenkins, which can then be downloaded to perform an Excel-based analysis. This Pipeline has the following stages:

  • Generate OAuth Token is responsible for logging in to the Anypoint platform and generating a bearer token to be used for further API calls
  • Fetch Applications extracts all the available client applications created in the platform
  • Fetch Contracts extracts all the available contracts (accesses to other APIs)
  • Publish Report organizes the extracted data into a CSV format and publishes it to the dashboard

Pipeline Script

pipeline {

agent any

stages {

    // To initialize the variable
    stage('Initialize'){
        steps{
            script{
                organizationID = 'XXXX'
            }
        }
  }

    /**
    * Login Call 
    * Extract Access Token 
    * Store it in a variable (authToken)
    **/ 

stage('Generate OAuth Token') {
steps {
script {

def jsonParser = new groovy.json.JsonSlurper()
def response = httpRequest (consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', httpMode: 'POST',validResponseCodes: '200', ignoreSslErrors: true, requestBody: '{"username":"XXXX","password":"XXXX"}', responseHandle: 'NONE', url: 'https://anypoint.mulesoft.com/accounts/login')
authToken = 'Bearer '+jsonParser.parseText(response.getContent()).access_token

}         
}
}

        /**
    * Application Call 
    * Pass the extracted Access Token in the Header
    * Extract information for Each Application
    **/

stage('Fetch Applications') {
steps {
script {

def jsonParser = new groovy.json.JsonSlurper()
def response = httpRequest(contentType: 'APPLICATION_JSON', customHeaders: [[name: 'Authorization', value: authToken]], /* consoleLogResponseBody: true */ ,validResponseCodes: '200', ignoreSslErrors: true, timeout: 30000, url: 'https://anypoint.mulesoft.com/apiplatform/repository/v2/organizations/'+organizationID+'/applications?targetAdminSite=true')
appsResponse = jsonParser.parseText(response.getContent())

}
}
}

/**
    * Contracts Call (for each Response id from above Applications Call)
    * Extract information for Each Contract in a Object (contract)
    * Store Each contract in contractList[]
    **/

stage('Fetch Contracts') {
steps {
script {

contractList = []
def jsonParser = new groovy.json.JsonSlurper()
for ( i = 0; i < appsResponse.total; i++) {

def response = httpRequest(contentType: 'APPLICATION_JSON', customHeaders: [[name: 'Authorization', value: authToken]],/*consoleLogResponseBody: true */,validResponseCodes: '200', ignoreSslErrors: true, timeout: 30000, url: 'https://anypoint.mulesoft.com/apiplatform/repository/v2/organizations/'+organizationID+'/applications/'+appsResponse.applications[i].id+'/contracts')
contractResponse = jsonParser.parseText(response.getContent())

contractResponse.each {
def contract = createContractObject(it, appsResponse)
contractList.push(contract)
}

}
}
}
}    

/**
    * Create a CSV File 
    * Publish it in the Jenkins Dashboard
    **/ 

stage('Publish Report') {
steps {
script {   

writeFile file: 'Contracts.csv', text: generateCSVContent(contractList)
archiveArtifacts 'Contracts.csv'

}
}
}
}
}

// A function to create contract object 
def createContractObject(contractResponse, appsResponse) {

def contract=[:]

contract.ApplicationID = appsResponse.applications[i].id
contract.ApplicationName = appsResponse.applications[i].name

if(appsResponse.applications[i].description != null)
{
    contract.Description = appsResponse.applications[i].description.replaceAll(/\n\s*/, " " )
        contract.Description = contract.Description.replaceAll(/,/," " )
}    

else
contract.Description = appsResponse.applications[i].description

contract.ClientID = appsResponse.applications[i].clientId
contract.Owner = appsResponse.applications[i].owner
contract.Email = appsResponse.applications[i].email
contract.APIID = contractResponse.apiVersion.api.id
contract.APIInstanceName = contractResponse.apiVersion.name
contract.APIName = contractResponse.apiVersion.api.exchangeAssetName

return contract


}

// A function to create content to store in a CSV File
def generateCSVContent(contractList) {   

    def increment=1
    def csvContent = "SNo,ApplicationID,ApplicationName,Description,ClientID,Owner,Email,APIID,APIInstanceName,APIName\n"

contractList.each {
def record = "${increment},${it.ApplicationID},${it.ApplicationName},${it.Description},${it.ClientID},${it.Owner},${it.Email},${it.APIID},${it.APIInstanceName},${it.APIName}\n"
csvContent = csvContent.plus(record)
increment++
}

return csvContent
}

Conclusion

At times, such audit asks are very important, and embracing DevOps culture throughout helps us to do these tasks seamlessly. Implementing operational asks as code helps running the platform with required agility, which otherwise could be a monotonous task. These implementations enrich the DevOps culture and reduce manual actions.

Topics:
devops ,integration ,extracting api access ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}