How to post yarn/npm vulnerabilities audit data into a slack channel

How to post yarn/npm vulnerabilities audit data into a slack channel

Often we receive a bunch of vulnerability alerts when we install some dependencies using the yarn package manager for node.js packages, after installing a dependency yarn warns about it showing us a message like 250 vulnerabilities found, separated by severity.

The normal process is to proceed to perform the command yarn audit fix to solve it in the development stage, but sometimes you might forget to apply that fix or you are super rushed to fix it ASAP, my advice is to solve it quickly. To keep us posted about how many vulnerabilities are in the package there using a CI/CD pipeline is another best approach to keep in mind, where you can apply policies to avoid going to production without vulnerabilities or just notify it and be aware of that in the next releases. Using a slack channel is useful for something like #packages-vulnerabilities and can help you to keep posted on how much compliance your system has.

Setup a slack application TL; TR

  1. Creates the channel
  2. Go to the apps page (https://slack.com/apps)
  3. Click build (Right upside) and create a new app from scratch
  4. Click on Oauth & permissions
  5. Add the chat:write scope
  6. Click on Install to Workspace
  7. Accept to install into a workspace.
  8. Copy the Slack token and save it in a secure place (We will use it later)

Creating a script to notify vulnerabilities

I will use typescript for easy proposals, this script solution applies to any stack. First of all, you need to export the yarn audit data into JSON for easy proposals, then run:

yarn audit --json > yarn_audit.json        

to generate the audit data, the data file result could be a little bit confusing due to the data structure being something like:

{data} {data}, .... {summary}        

where data has the following JSON schema:

	   "type":"auditAdvisory",
	   "data":{
	      "resolution":{
	         "id":1091144,
	         "path":"swagger-ui>@braintree/sanitize-url",
	         "dev":false,
	         "optional":false,
	         "bundled":false
	      },
	      "advisory":{
	       }
	      }...// Short for brevity
	 }{        

and summary:


	"type":"auditSummary",
	   "data":{
	      "vulnerabilities":{
	         "info":0,
	         "low":19,
	         "moderate":92,
	         "high":121,
	         "critical":28
	      },
	      "dependencies":1698,
	      "devDependencies":0,
	      "optionalDependencies":0,
	      "totalDependencies":1698
	   }
	}{        

at is the data of our interest, keeping that in mind let's code:

Note: all the code boilerplate link is pasted at the end of the article.

Then let's filter out the data of our interest


 private filterSummaryData(vulnerabilities: string []): AuditData {
   const summary: string | undefined =
       vulnerabilities.find((item: string) => {
	      const itemParsed: any = JSON.parse(item);
	      return itemParsed.type === 'auditSummary';
	   }) || '{}';
	

   const summaryData: any = JSON.parse(summary);
   return summaryData as AuditData;
 }        

Summarize all vulnerabilities, it does not matter if are critical, info, or high.

  private calculateVulnerabilities(dataVulnerabilities: Vulnerabilities): number {
    const countVulnerabilities: number = Object.values(
     dataVulnerabilities,
    ).reduce((total: number, current: number) => {
      return total + current;
    });
    return countVulnerabilities;
  }        

And finally, prepare data to send the slack message:


 private async sendSlackMessage(countVulnerabilities: number, packageName: string): Promise<void> {
    const postData = {
      attachments: [
        {
          author_name: 'YARN - AUDIT',
          color: '#ff0000',
          mrkdwn_in: ['text', 'pretext'],
          text: `Found *${countVulnerabilities}* vulnerabilities in _${packageName}_ project, for more details run _yarn audit_`,
        },
      ],
      channel: `#packages-vulnerabilities`,
      icon_emoji: ':warning:',
      mrkdwn: true,
      username: 'YARN Audit Alert',
    };

    const result = await this.client.post('', {
      body: postData,
    });

    if (!result.ok) {
      throw new Error('The message cannot be delivered');
    }
  }        

Inside the project, run

YARN_AUDIT_SLACK_TOKEN=<yourToken> yarn run audit_report        

You should receive a slack message on your slack channel, customize it as you prefer adding colors, formatting, and more.

Make sure the app is joined into the channel.

Hope you find this content useful.

Code repository: https://github.com/hendrixroa/yarn-audit

Thanks for reading!

要查看或添加评论,请登录

Hendrix Roa的更多文章

社区洞察

其他会员也浏览了