Created
December 13, 2021 00:52
-
-
Save Flet/69d2a1b489bf29132f151712514f0ebe to your computer and use it in GitHub Desktop.
tape nock setup - filters sensitive request body data and de-gzips responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tape = require('tape') | |
const path = require('path') | |
const zlib = require('zlib') | |
const bodyFilters = [ | |
[ | |
/client_secret=[^\\<&"]+/g, 'client_secret=XXX' | |
] | |
] | |
const test = require('tape-nock')(tape, { | |
fixtures: path.join(__dirname, '..', 'fixtures'), | |
defaultTestOptions: { | |
afterRecord: function (scopes) { | |
// avoid exposing client secret in the fixtures | |
let scopesString = JSON.stringify(scopes, null, 2) | |
console.log('scopesString', scopesString) | |
for (const bodyFilter of bodyFilters) { | |
scopesString = scopesString.replace(bodyFilter[0], bodyFilter[1]) | |
} | |
let newScopes = JSON.parse(scopesString) | |
// decode gzipped bodies | |
newScopes = newScopes.map(scope => { | |
console.log('scope', scope) | |
if (scope.rawHeaders.includes('gzip')) { | |
const hexResponse = Buffer.from(scope.response[0], 'hex') | |
scope.response = JSON.parse(zlib.gunzipSync(hexResponse).toString('utf8')) | |
scope.rawHeaders = scope.rawHeaders.filter(h => h.toLowerCase() !== 'content-encoding' && h.toLowerCase() !== 'gzip') | |
} | |
return scope | |
}) | |
return newScopes | |
}, | |
after: function (scope) { | |
// when running test, switch client secret to XXX to match fixtures | |
for (const bodyFilter of bodyFilters) { | |
scope.filteringRequestBody(bodyFilter[0], bodyFilter[1]) | |
} | |
// can also add logic to handle scope.filteringRequestPath to get query params | |
} | |
} | |
}) | |
module.exports = test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment