Remove Authorization header value from Axios error response

Viewed 1225

I send an HTTP request using Axios which results in an error. When I print the error object it prints the request including the secret in the Authorization header.

E.g.

axios.get('https://test.com/404', { headers: { Authorization: 'secret' } }).catch(err => console.log(err));

This prints the secret in the log message in a few places:

Error: Request failed with status code 463
    at createError (/code/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/code/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/code/node_modules/axios/lib/adapters/http.js:236:11)
    at IncomingMessage.emit (events.js:215:7)
    at IncomingMessage.EventEmitter.emit (domain.js:475:20)
    at endReadableNT (_stream_readable.js:1184:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  config: {
  ...
    url: 'https://test.com/404',
    method: 'get',
    headers: {
      Accept: 'application/json, text/plain, */*',
      Authorization: 'secret',
      'User-Agent': 'axios/0.19.2'
    },
  },
  ...
  request: ClientRequest {
    _header: 'GET /404 HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Authorization: secret\r\n' +
      'User-Agent: axios/0.19.2\r\n' +
      'Host: www.test.com\r\n' +
      'Connection: close\r\n' +
      '\r\n',
  },
  ...
  response: {
    ...
    request: ClientRequest {
      _header: 'GET /404 HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Authorization: secret\r\n' +
        'User-Agent: axios/0.19.2\r\n' +
        'Host: www.test.com\r\n' +
        'Connection: close\r\n' +
        '\r\n',
    },
  },
}

I don't want to print my secret in the log message. Is there a way to avoid it?

2 Answers

I ended up using interceptors

axios.interceptors.response.use(_.identity, (error) => {
  delete error.config.headers.Authorization;
  delete error.request._header;
  return Promise.reject(error);
});

This is coupled with the inner objects of axios, so it's brittle and may break, but it solves my problem for now.

It's not fancy, but why not just run a regular expression over the message before you output it?

const ReRemoveSecret = new RegExp('secret', 'g');

.catch(msg => {
  console.log(msg.replace($ReRemoveSecret, ''));
});
Related