DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Anypoint Platform Audit — Extracting API Access and Client Contracts

Anypoint Platform Audit — Extracting API Access and Client Contracts

Learn how to extract API access and client contracts.

Mishal Sabharwal user avatar by
Mishal Sabharwal
·
Dhaneesh T user avatar by
Dhaneesh T
·
Feb. 04, 19 · Tutorial
Like (7)
Save
Tweet
Share
15.04K Views

Join the DZone community and get the full member experience.

Join For Free

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.

API Continuous Integration/Deployment application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Simulate Network Latency and Packet Drop In Linux
  • Educating the Next Generation of Cloud Engineers With Google Cloud
  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future
  • Do Not Forget About Testing!

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: