UNPKG

@case-contract-testing/case

Version:

Next-generation contract testing suite

48 lines (47 loc) 2.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpBasicAuthMatcher = void 0; const entities_1 = require("../../entities"); const context_1 = require("../../entities/context"); const results_1 = require("../../entities/results"); const encode = (username, password) => { if (username.includes(':')) { throw new entities_1.CaseConfigurationError(`The username for basic auth was: '${username}', but it must not contain a ':' (See RFC 7617)`); } return Buffer.from(`${username}:${password}`).toString('base64'); }; const check = async (matcher, matchContext, actual) => { if (typeof actual !== 'string') { return (0, results_1.makeResults)((0, results_1.matchingError)(matcher, `${(0, results_1.actualToString)(actual)} is not a string; so can't use it as basic auth`, actual, matchContext)); } let decoded; try { decoded = Buffer.from(actual, 'base64').toString('utf8'); } catch { return (0, results_1.makeResults)((0, results_1.matchingError)(matcher, `${(0, results_1.actualToString)(actual)} failed to decode from base64 to utf8`, actual, matchContext)); } if (!decoded.includes(':')) { return (0, results_1.makeResults)((0, results_1.matchingError)(matcher, `Basic auth value decoded to ${decoded}, which doesn't contain a ':'`, actual, matchContext)); } const pivot = decoded.indexOf(':'); const actualUsername = decoded.substring(0, pivot); const actualPassword = decoded.substring(pivot + 1); return (0, results_1.combineResultPromises)(matchContext.descendAndCheck(matcher['case:matcher:username'], (0, context_1.addLocation)('username', matchContext), actualUsername), matchContext.descendAndCheck(matcher['case:matcher:password'], (0, context_1.addLocation)('password', matchContext), actualPassword)); }; const strip = (matcher, matchContext) => { const username = matchContext.descendAndStrip(matcher['case:matcher:username'], matchContext); const password = matchContext.descendAndStrip(matcher['case:matcher:password'], matchContext); if (typeof username !== 'string') { throw new entities_1.CaseConfigurationError("The username for basic auth didn't resolve to a string, please check the definition"); } if (typeof password !== 'string') { throw new entities_1.CaseConfigurationError("The password for basic auth didn't resolve to a string, please check the definition"); } return encode(username, password); }; exports.HttpBasicAuthMatcher = { describe: (matcher, matchContext) => `http basic auth with username='${matchContext.descendAndDescribe(matcher['case:matcher:username'], (0, context_1.addLocation)('username', matchContext))}' and password=${matchContext.descendAndDescribe(matcher['case:matcher:password'], (0, context_1.addLocation)('password', matchContext))}`, check, strip, };