raman20
raman20

Reputation: 11

AxiosError - Unable to verify the first certificate on AWS Lambda NodeJS

I am trying to connect with REST API using P12/PFX client certificate on AWS Lambda (Runtime: NodeJS). P12 certificate works fine with curl command and in Java application so the certificate is valid and good. I am trying to do this using Axios library on AWS Lambda (Runtime: NodeJS). If I use 'rejectUnauthorized: false', it works fine. But if I comment out that line, it fails with below error. I read that rejectUnauthorized: false should NOT be used in production environment. It seems like I am missing something in the httpsAgent config. Please advise on how to fix this. Also I notice that it works fine with SOAP API (i.e, commenting out 'rejectUnauthorized: false' works fine), it's just an issue with REST API.

Error: AxiosError: unable to verify the first certificate 
cause: Error: unable to verify the first certificate
  at TLSSocket.onConnectSecure (node:_tls_wrap:1539:34)
  at TLSSocket.emit (node:events:513:28)
  at TLSSocket.emit (node:domain:489:12)
  at TLSSocket._finishInit (node:_tls_wrap:953:8)
  at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:734:12) {
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
}

This below is what I attempted in Node.js. I get the above axios error. 

const axios = require("axios"); 
const https = require('https');
const fs = require('fs');

const url = `https://example.com/test`;

let httpsAgent = new https.Agent({
   pfx: fs.readFileSync('./src/example.p12'),
   passphrase: 'Test123',
       maxVersion: 'TLSv1.2',
       //rejectUnauthorized: false
})
const axiosConfig = {
 httpsAgent: httpsAgent,
};
 axios.get(url, axiosConfig)
  .then((response: any) => {
    console.log('Response:', response.data);
   }).catch((error: any) => {
    console.error('Error:', error);
  });

Upvotes: 0

Views: 653

Answers (1)

raman20
raman20

Reputation: 11

It turns out the issue is related to server side configuration (REST API server) - based on this - Error: unable to verify the first certificate in nodejs

I was able to make it work by adding the https agent ca: attribute config and including the intermediate and root ca certificates like below.

   let httpsAgent = new https.Agent({
      pfx: fs.readFileSync('./src/example.p12'),
      passphrase: 'Test123',
      maxVersion: 'TLSv1.2',
      rejectUnauthorized: true,
      ca: [fs.readFileSync('./src/example_Intermediate.crt'),
          fs.readFileSync('./src/example_ROOT.crt')] 
     })

Upvotes: 0

Related Questions