From fa1ea2024914f97319d1342003d62db97ff642f9 Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Tue, 24 Nov 2026 17:06:23 +0100 Subject: [PATCH 1/3] fix(client): security hardening Security hardening of the HTTP layer, with both HTTP clients, and improved error handling. --- src/api/reports/reports.js | 7 +- src/services/errors.js | 12 + src/services/http.js | 360 ++++++++++++-- test/errors/determineError-unit.js | 67 +++ test/http/responsePolicy.js | 762 +++++++++++++++++++++++++++++ 5 files changed, 1155 insertions(+), 53 deletions(-) create mode 100644 test/errors/determineError-unit.js create mode 100644 test/http/responsePolicy.js diff --git a/src/api/reports/reports.js b/src/api/reports/reports.js index ae41557f..4eed5b19 100644 --- a/src/api/reports/reports.js +++ b/src/api/reports/reports.js @@ -63,8 +63,8 @@ export default class Reports { * * @memberof Reports * @param {string} id The ID of the report that the file belongs to. - * @param {Object} fileId The ID of the file to retrieve. - * @return {Promise} A promise to the Reports response. + * @param {string} fileId The ID of the file to retrieve. + * @return {Promise} A promise to the content of the file. * @throws {ValueError} If id or fileId is undefined, null, empty, "." or "..", or contains "/", * "\", an ASCII control character or an unpaired surrogate. */ @@ -73,7 +73,8 @@ export default class Reports { const response = await get( this.config.httpClient, `${this.config.host}/${REPORTS_PATH}/${encodePathSegment(id, 'id')}/${FILES_PATH}/${encodePathSegment(fileId, 'fileId')}`, - { ...this.config, csv: true }, + // The file is served from another location: one 302 to it is followed (see http.js downloadFile). + { ...this.config, csv: true, fileDownload: true }, this.config.sk ); return await response.csv; diff --git a/src/services/errors.js b/src/services/errors.js index c6976513..2a8c692e 100644 --- a/src/services/errors.js +++ b/src/services/errors.js @@ -174,7 +174,19 @@ export class ValueError extends Error { } } +/** + * Map an error thrown by the HTTP layer to the SDK error the caller receives. + * + * @param {*} err An SDK error (returned unchanged), a `{ status, json }` error response or a + * client error. + * @return {Promise} The SDK error. + * @throws {ValueError} When err is a ValueError. + */ export const determineError = async (err) => { + // Already an SDK error thrown by the HTTP layer (every one sets http_code): keep its type and body + if (err instanceof Error && Object.hasOwn(err, 'http_code')) { + return err; + } if ( err instanceof ApiTimeout || diff --git a/src/services/http.js b/src/services/http.js index de28057b..65b6fc72 100644 --- a/src/services/http.js +++ b/src/services/http.js @@ -8,6 +8,7 @@ import { SANDBOX_ACCESS_URL, } from '../config.js'; import Environment from '../Environment.js'; +import { ApiError, ApiTimeout, AuthenticationError, determineError } from './errors.js'; import pjson from '../../package.json' with { type: 'json' }; @@ -178,6 +179,238 @@ export const storeAccessToken = (config, body) => { }); }; +const isRedirect = (status) => status >= 300 && status < 400; + +// Statuses returned as a response: the ones the application's axios default accepts (axios +// accepts every status when it has none), never a 3xx. +const acceptStatus = (status) => { + if (isRedirect(status)) { + return false; + } + const { validateStatus } = axios.defaults; + return typeof validateStatus === 'function' ? validateStatus(status) : true; +}; + +// axios options of every SDK request: redirects are not followed (see acceptStatus). +const AXIOS_RESPONSE_POLICY = { + maxRedirects: 0, + validateStatus: acceptStatus, +}; + +// The OAuth token request and the file request accept a 2xx only: any other status is an error, +// whatever the application's axios default. +const AXIOS_SUCCESS_ONLY_POLICY = { + ...AXIOS_RESPONSE_POLICY, + validateStatus: (status) => status >= 200 && status < 300, +}; + +// Body of the errors of the response policy: the status, and the request id when the API sent one. +const statusOnlyBody = (status, requestId) => (requestId ? { status, request_id: requestId } : { status }); + +const requestIdOf = (headers) => { + const get = (name) => (typeof headers?.get === 'function' ? headers.get(name) : headers?.[name]); + const value = get(REQUEST_ID_HEADER) || get('request-id'); + return Array.isArray(value) ? value[0] : value || undefined; +}; + +// A 3xx response: an ApiError with the status only. +const redirectStatusError = (status, requestId) => new ApiError(status, statusOnlyBody(status, requestId)); + +// A 3xx response to the token request: an AuthenticationError with the status only. +const tokenRedirectError = (status) => new AuthenticationError({ status }, 'Unexpected token response status'); + +// The body of a response that is not used is discarded, so fetch releases the connection. +const discardBody = async (response) => { + try { + await response.body?.cancel(); + } catch { + // nothing to release + } +}; + +// The SDK error determineError gives for an error status. +const statusError = (status, json) => determineError({ status, json: json ?? {} }); + +// The client's error without the request it was sending (axios errors keep the request config, +// body and headers included): name, message and code, and the same for its own cause. +const clientErrorCause = (error, depth = 0) => { + const cause = new Error(error?.message); + cause.name = error?.name ?? 'Error'; + // fetch reports the network code on its own cause: it is kept at the top too. + const code = error?.code ?? error?.cause?.code; + if (code !== undefined) { + cause.code = code; + } + if (depth < 1 && error?.cause instanceof Error) { + cause.cause = clientErrorCause(error.cause, depth + 1); + } + return cause; +}; + +// No HTTP response: ApiError without http_code, `body` as its body and the client's error as cause. +const connectionError = (body, error) => { + const err = new ApiError(undefined, body); + Object.defineProperty(err, 'cause', { + value: clientErrorCause(error), + writable: true, + configurable: true, + enumerable: false, + }); + return err; +}; + +// The URL of a request without its user information. A URL that is not an http(s) URL the WHATWG +// parser accepts is cut after its last '@', so nothing written before it is repeated. +const withoutUserinfo = (url) => { + const text = String(url); + try { + const parsed = new URL(text); + if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { + if (!parsed.username && !parsed.password) { + return text; + } + parsed.username = ''; + parsed.password = ''; + return parsed.href; + } + } catch { + // not a URL: handled below + } + const at = text.lastIndexOf('@'); + return at === -1 ? text : text.slice(at + 1); +}; + +const connectionReason = (url, error) => `request to ${withoutUserinfo(url)} failed, reason: ${error.message}`; + +// Input validation: when fetch cannot build a request (a header value or URL it rejects) it throws +// a TypeError that names the input; that error is replaced by a fixed one. Its network failures +// ('fetch failed') and any other error keep their message. +const fetchFailure = (error) => + error instanceof TypeError && error.message !== 'fetch failed' + ? new TypeError('the request could not be built') + : error; + +const isTimeout = (error) => + error.code === 'ECONNABORTED' || error.name === 'AbortError' || error.message?.includes('timeout'); + +const isLoopbackHost = (hostname) => + hostname === 'localhost' || hostname === '[::1]' || /^127(\.\d{1,3}){3}$/.test(hostname); + +// The file location of a report download: https, or http for a loopback host (local tests). +const fileDownloadUrl = (location, base) => { + let url; + try { + url = new URL(location, base); + } catch { + return undefined; + } + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) { + return undefined; + } + url.username = ''; + url.password = ''; + return url.href; +}; + +// Headers never sent to the file location (the HTTP clients also drop the first three when they +// follow a response to another host). +const FILE_DOWNLOAD_DROPPED_HEADERS = ['authorization', 'proxy-authorization', 'cookie', 'referer']; + +// Headers of the file request: the API request headers without the ones above and the SDK's Cko- +// headers. +const isDroppedFileHeader = (name) => { + const lower = name.toLowerCase(); + return FILE_DOWNLOAD_DROPPED_HEADERS.includes(lower) || lower.startsWith('cko-'); +}; + +const fileDownloadHeaders = (headers) => + Object.fromEntries(Object.entries(headers).filter(([name, value]) => value != null && !isDroppedFileHeader(name))); + +// axios adds the application's default headers and auth after the request headers are set: the +// same headers are removed from the merged headers of the file request, and auth is not used. +const dropFileHeaderDefaults = (data, headers) => { + Object.keys(headers.toJSON()).filter(isDroppedFileHeader).forEach((name) => headers.delete(name)); + return data; +}; + +const followsFileDownload = (config, method, status) => config.fileDownload === true && method === 'GET' && status === 302; + +// The only redirect followed: one 302 of a report file download, as a GET without a body (see +// fileDownloadUrl and fileDownloadHeaders). Its own 3xx is not followed; an error status keeps +// the SDK error type with the status only. Errors name the API request, not the file location. +const downloadFile = async (httpClient, config, path, location, headers, requestId) => { + const url = location ? fileDownloadUrl(location, path) : undefined; + if (!url) { + throw redirectStatusError(302, requestId); + } + const fileHeaders = fileDownloadHeaders(headers); + + if (httpClient === 'axios') { + let response; + try { + response = await axios({ + url, + method: 'GET', + headers: fileHeaders, + auth: null, + transformRequest: [dropFileHeaderDefaults], + timeout: config.timeout, + httpsAgent: config.agent, + ...AXIOS_SUCCESS_ONLY_POLICY, + }); + } catch (error) { + if (isTimeout(error)) { + throw new ApiTimeout(); + } + if (error.response) { + const { status } = error.response; + throw isRedirect(status) + ? redirectStatusError(status, requestId) + : await statusError(status, statusOnlyBody(status, requestId)); + } + throw connectionError(connectionReason(path, error), error); + } + return buildAxiosResponse(config, response); + } + + const fetchOptions = { method: 'GET', headers: fileHeaders, redirect: 'manual' }; + if (typeof config.agent !== 'undefined') { + fetchOptions.agent = config.agent; + } + let response; + try { + response = await fetch(url, fetchOptions); + } catch (error) { + if (isTimeout(error)) { + throw new ApiTimeout(); + } + const failure = fetchFailure(error); + throw connectionError(connectionReason(path, failure), failure); + } + if (isRedirect(response.status)) { + await discardBody(response); + throw redirectStatusError(response.status, requestId); + } + if (!response.ok) { + await discardBody(response); + throw await statusError(response.status, statusOnlyBody(response.status, requestId)); + } + return buildResponse(config, response); +}; + +/** + * Request an OAuth access token, with the SDK's response policy. + * + * @param {Object} config SDK configuration. + * @param {string} httpClient 'axios', or anything else for fetch. + * @param {Object} [body] Token request body; client credentials from the config by default. + * @return {Promise} status and json of the token response. + * @throws {AuthenticationError} On an unexpected response status (body `{ status }`), a 401 or a + * 400 OAuth error. + * @throws {ApiTimeout} When the axios client times out. + * @throws {Error} On any other error status, the SDK error of that status (as determineError); + * without a response, an ApiError without http_code and with the client's error as cause. + */ export const createAccessToken = async (config, httpClient, body) => { const requestBody = body || { grant_type: 'client_credentials', @@ -198,53 +431,65 @@ export const createAccessToken = async (config, httpClient, body) => { switch (httpClient) { case 'axios': - access = await axios({ - url: accessUrl, - method: 'post', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - Accept: 'application/json', - }, - data: new URLSearchParams(requestBody), - timeout: config.timeout, - httpsAgent: config.agent, - }) - .catch(async (error) => { - if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) { - const { ApiTimeout } = await import('./errors.js'); - throw new ApiTimeout(); - } - if (error.response) { - throw { - status: error.response.status, - json: error.response.data, - }; - } - throw new Error(`request to ${accessUrl} failed, reason: ${error.message}`); - }) - .then((response) => ({ - status: response.status, - json: response.data, - })); - return access; - - default: - access = await fetch( - accessUrl, - { - method: 'POST', - timeout: config.timeout, - agent: config.agent, - body: new URLSearchParams(requestBody), + try { + access = await axios({ + url: accessUrl, + method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', }, + data: new URLSearchParams(requestBody), + timeout: config.timeout, + httpsAgent: config.agent, + ...AXIOS_SUCCESS_ONLY_POLICY, + }); + } catch (error) { + if (isTimeout(error)) { + throw new ApiTimeout(); + } + if (error.response) { + const { status, data } = error.response; + throw isRedirect(status) ? tokenRedirectError(status) : await statusError(status, data); + } + throw connectionError(connectionReason(accessUrl, error), error); + } + return { + status: access.status, + json: access.data, + }; + + default: + try { + access = await fetch( + accessUrl, + { + method: 'POST', + timeout: config.timeout, + agent: config.agent, + redirect: 'manual', + body: new URLSearchParams(requestBody), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json', + }, + } + ); + } catch (error) { + if (isTimeout(error)) { + throw new ApiTimeout(); } - ); + // Same body as before for this client: the client's message. + const failure = fetchFailure(error); + throw connectionError(failure.message, failure); + } + if (isRedirect(access.status)) { + await discardBody(access); + throw tokenRedirectError(access.status); + } if (!access.ok) { const json = await bodyParser(access); - throw { status: access.status, json }; + throw await statusError(access.status, json); } return access.text().then((text) => { @@ -295,23 +540,28 @@ const httpRequest = async (httpClient, verb, path, config, auth, request, idempo data: config.formData ? request : JSON.stringify(request), timeout: config.timeout, httpsAgent: config.agent, + ...AXIOS_RESPONSE_POLICY, }); return buildAxiosResponse(config, response); } catch (error) { - if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) { - const { ApiTimeout } = await import('./errors.js'); + if (isTimeout(error)) { throw new ApiTimeout(); } if (error.response) { + const { status, headers: responseHeaders } = error.response; + if (isRedirect(status)) { + const requestId = requestIdOf(responseHeaders); + if (followsFileDownload(config, method, status)) { + return downloadFile(httpClient, config, path, responseHeaders?.location, headers, requestId); + } + throw redirectStatusError(status, requestId); + } throw { - status: error.response.status, + status, json: error.response.data, }; } - if (error.request) { - throw new Error(`request to ${path} failed, reason: ${error.message}`); - } - throw new Error(`request to ${path} failed, reason: ${error.message}`); + throw connectionError(connectionReason(path, error), error); } default: @@ -325,6 +575,7 @@ const httpRequest = async (httpClient, verb, path, config, auth, request, idempo method, body, headers, + redirect: 'manual', }; if (typeof config.agent !== 'undefined') { fetchOptions.agent = config.agent; @@ -332,13 +583,22 @@ const httpRequest = async (httpClient, verb, path, config, auth, request, idempo try { response = await fetch(path, fetchOptions); } catch (error) { - if (error.name === 'AbortError' || error.message?.includes('timeout')) { - const { ApiTimeout } = await import('./errors.js'); + if (isTimeout(error)) { throw new ApiTimeout(); } - throw new Error(`request to ${path} failed, reason: ${error.message}`); + const failure = fetchFailure(error); + throw connectionError(connectionReason(path, failure), failure); } + if (isRedirect(response.status)) { + const requestId = requestIdOf(response.headers); + const location = response.headers.get('location'); + await discardBody(response); + if (followsFileDownload(config, method, response.status)) { + return downloadFile(httpClient, config, path, location, headers, requestId); + } + throw redirectStatusError(response.status, requestId); + } if (!response.ok) { const json = await bodyParser(response); throw { status: response.status, json }; diff --git a/test/errors/determineError-unit.js b/test/errors/determineError-unit.js new file mode 100644 index 00000000..01c16d89 --- /dev/null +++ b/test/errors/determineError-unit.js @@ -0,0 +1,67 @@ +import { + ActionNotAllowed, + ApiError, + ApiTimeout, + AuthenticationError, + BadGateway, + determineError, + ErrorWithBody, + NotFoundError, + TooManyRequestsError, + UrlAlreadyRegistered, + ValidationError, +} from '../../src/services/errors.js'; +import { expect } from 'chai'; + +describe('determineError', () => { + describe('returns an SDK error unchanged', () => { + const errors = [ + new AuthenticationError({ status: 307 }, 'Unexpected token response status'), + new ActionNotAllowed({ a: 1 }), + new UrlAlreadyRegistered({ a: 1 }), + new NotFoundError({ a: 1 }), + new ValidationError({ a: 1 }), + new TooManyRequestsError({ a: 1 }), + new ErrorWithBody(418, { a: 1 }, 'Teapot'), + new BadGateway(), + new ApiError(0, 'request to https://example.com failed, reason: socket hang up'), + ]; + + errors.forEach((error) => { + it(`${error.constructor.name}`, async () => { + expect(await determineError(error)).to.equal(error); + }); + }); + + it('ApiTimeout', async () => { + const error = new ApiTimeout(); + expect(await determineError(error)).to.equal(error); + }); + }); + + describe('maps a thrown status object as before', () => { + it('400 invalid_client to AuthenticationError', async () => { + const err = await determineError({ status: 400, json: { error: 'invalid_client' } }); + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ error: 'invalid_client' }); + }); + + it('400 without an OAuth error to ApiError 400', async () => { + const err = await determineError({ status: 400, json: { error_codes: ['x'] } }); + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(400); + }); + + it('422 to ValidationError', async () => { + const err = await determineError({ status: 422, json: { error_codes: ['x'] } }); + expect(err).to.be.instanceOf(ValidationError); + }); + + it('a plain Error to ApiError without http_code, the message as body', async () => { + const err = await determineError(new Error('request to https://x failed, reason: boom')); + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(undefined); + expect(err.body).to.equal('request to https://x failed, reason: boom'); + }); + }); +}); diff --git a/test/http/responsePolicy.js b/test/http/responsePolicy.js new file mode 100644 index 00000000..4906b131 --- /dev/null +++ b/test/http/responsePolicy.js @@ -0,0 +1,762 @@ +import axios from 'axios'; +import http from 'http'; +import nock from 'nock'; +import { inspect } from 'util'; +import { expect } from 'chai'; +import { Checkout } from '../../src/index.js'; +import { + ActionNotAllowed, + ApiError, + AuthenticationError, + ValidationError, +} from '../../src/services/errors.js'; + +const SK = 'sk_test_0b9b5db6-f223-49d0-b68f-f6643dd4f808'; +const CLIENT = 'ack_test_client'; +const CLIENT_CREDENTIAL = 'test_client_credential_value_1234567890'; +const CARD_NUMBER = '4242424242424242'; +const CARD_CVV = '100'; +const CLIENTS = ['axios', 'fetch']; +const STATUSES_3XX = [301, 302, 303, 307, 308]; +const TOKEN = { access_token: 'token_value', token_type: 'Bearer', expires_in: 3600 }; + +// A local HTTP server that records every request it receives and answers with `handler`. +const startServer = async () => { + const server = { + requests: [], + handler: (req, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end('{}'); + }, + }; + server.http = http.createServer((req, res) => { + const chunks = []; + req.on('data', (chunk) => chunks.push(chunk)); + req.on('end', () => { + server.requests.push({ + method: req.method, + url: req.url, + headers: req.headers, + body: Buffer.concat(chunks).toString(), + }); + server.handler(req, res); + }); + }); + await new Promise((resolve) => server.http.listen(0, '127.0.0.1', resolve)); + server.origin = `http://127.0.0.1:${server.http.address().port}`; + return server; +}; + +const stopServer = (server) => new Promise((resolve) => server.http.close(resolve)); + +const respond = (status, headers = {}, body = '') => (req, res) => { + res.writeHead(status, headers); + res.end(body); +}; + +const json = (status, body) => respond(status, { 'Content-Type': 'application/json' }, JSON.stringify(body)); + +// Every place an error can carry text: message, stack, JSON, body and hidden properties (cause). +const serialize = (err) => + `${String(err)} ${err.message} ${err.stack} ${JSON.stringify(err)} ${JSON.stringify(err.body)} ${inspect(err, { depth: 6, showHidden: true })}`; + +const expectNoCredentials = (err, ...values) => { + const text = serialize(err); + [SK, CLIENT_CREDENTIAL, 'client_secret', CARD_NUMBER, ...values].forEach((value) => { + expect(text).to.not.include(value); + }); +}; + +const catchError = async (promise) => { + try { + await promise; + } catch (err) { + return err; + } + throw new Error('expected the request to fail'); +}; + +const withClient = (httpClient) => (httpClient === 'axios' ? { httpClient } : {}); + +const skClient = (httpClient, api) => { + const cko = new Checkout(SK, { subdomain: '123456789', ...withClient(httpClient) }); + cko.config.host = api.origin; + cko.config.forwardUrl = api.origin; + return cko; +}; + +const oauthClient = (httpClient, api) => { + const cko = new Checkout(CLIENT_CREDENTIAL, { + client: CLIENT, + scope: ['gateway'], + environment: 'sandbox', + subdomain: '123456789', + ...withClient(httpClient), + }); + cko.config.host = api.origin; + cko.config.environmentSubdomain = { getOAuthAuthorizationApi: () => `${api.origin}/connect/token` }; + return cko; +}; + +// Requests whose response is handled by the SDK, each with the path the API answers on. +const REQUESTS = [ + { + name: 'payments.request (POST)', + path: '/payments', + call: (cko) => + cko.payments.request({ + source: { type: 'card', number: CARD_NUMBER, cvv: CARD_CVV, expiry_month: 1, expiry_year: 2030 }, + amount: 100, + currency: 'USD', + }), + }, + { name: 'payments.get (GET)', path: '/payments/pay_123', call: (cko) => cko.payments.get('pay_123') }, + { + name: 'forward.forwardRequest (POST)', + path: '/forward', + call: (cko) => + cko.forward.forwardRequest({ + source: { type: 'id', id: 'src_123' }, + destination_request: { + url: 'https://example.com/pay', + method: 'POST', + headers: { raw: { Authorization: 'third_party_value' } }, + body: '{}', + }, + }), + secret: 'third_party_value', + }, + { + name: 'forward.createSecret (POST)', + path: '/secrets', + call: (cko) => cko.forward.createSecret({ name: 'n', value: 'secret_value_123' }), + secret: 'secret_value_123', + }, + { + name: 'issuing.requestCardholderAccessToken (POST)', + path: '/issuing/access/connect/token', + call: (cko) => + cko.issuing.requestCardholderAccessToken({ + grant_type: 'client_credentials', + client_id: 'cli_1', + client_secret: 'cardholder_value_123', + cardholder_id: 'crh_1', + }), + secret: 'cardholder_value_123', + }, + { + name: 'webhooks.registerWebhook (POST)', + path: '/webhooks', + call: (cko) => + cko.webhooks.registerWebhook({ url: 'https://example.com/hook', headers: { authorization: 'hook_value_123' } }), + secret: 'hook_value_123', + }, +]; + +describe('HTTP response policy', () => { + let api; + let other; + + before(async () => { + nock.restore(); + nock.enableNetConnect(); + api = await startServer(); + other = await startServer(); + }); + + after(async () => { + await stopServer(api); + await stopServer(other); + nock.activate(); + }); + + beforeEach(() => { + api.requests = []; + other.requests = []; + other.handler = json(200, TOKEN); + }); + + const targets = () => [ + { name: 'same host', location: `${api.origin}/moved` }, + { name: 'other host', location: `${other.origin}/moved` }, + ]; + + describe('does not follow redirects', () => { + CLIENTS.forEach((httpClient) => { + REQUESTS.forEach((request) => { + STATUSES_3XX.forEach((status) => { + ['same host', 'other host'].forEach((targetName) => { + it(`${httpClient}: ${request.name} ${status} to the ${targetName} gives ApiError with the status only`, async () => { + const target = targets().find((t) => t.name === targetName); + api.handler = (req, res) => + req.url === request.path + ? respond(status, { Location: target.location }, `moved to ${target.location}`)(req, res) + : json(200, TOKEN)(req, res); + + const err = await catchError(request.call(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(status); + expect(err.body).to.deep.equal({ status }); + expect(api.requests.map((r) => r.url)).to.deep.equal([request.path]); + expect(other.requests).to.deep.equal([]); + expectNoCredentials(err, target.location, ...(request.secret ? [request.secret] : [])); + }); + }); + }); + }); + }); + }); + + describe('status-only errors', () => { + CLIENTS.forEach((httpClient) => { + [300, 304].forEach((status) => { + it(`${httpClient}: a ${status} gives ApiError with the status only`, async () => { + api.handler = respond(status); + + const err = await catchError(skClient(httpClient, api).payments.get('pay_123')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(status); + expect(err.body).to.deep.equal({ status }); + }); + }); + + it(`${httpClient}: the error keeps the request id of the response`, async () => { + api.handler = respond(307, { Location: `${other.origin}/moved`, 'Cko-Request-Id': 'req_123' }); + + const err = await catchError(skClient(httpClient, api).payments.get('pay_123')); + + expect(err.body).to.deep.equal({ status: 307, request_id: 'req_123' }); + expect(other.requests).to.deep.equal([]); + }); + }); + }); + + describe('OAuth token request', () => { + CLIENTS.forEach((httpClient) => { + STATUSES_3XX.forEach((status) => { + ['same host', 'other host'].forEach((targetName) => { + it(`${httpClient}: ${status} to the ${targetName} gives AuthenticationError with the status only`, async () => { + const target = targets().find((t) => t.name === targetName); + api.handler = respond(status, { Location: target.location }); + const cko = oauthClient(httpClient, api); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ status }); + expect(api.requests.map((r) => r.url)).to.deep.equal(['/connect/token']); + expect(other.requests).to.deep.equal([]); + expect(cko.config.access.token).to.equal(undefined); + expectNoCredentials(err, target.location); + }); + }); + }); + + it(`${httpClient}: access.request 307 gives AuthenticationError with the status only`, async () => { + api.handler = respond(307, { Location: `${other.origin}/moved` }); + const cko = oauthClient(httpClient, api); + + const err = await catchError( + cko.access.request({ + grant_type: 'client_credentials', + client_id: CLIENT, + client_secret: CLIENT_CREDENTIAL, + scope: 'gateway', + }) + ); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ status: 307 }); + expect(other.requests).to.deep.equal([]); + expectNoCredentials(err); + }); + }); + }); + + describe('report file download', () => { + const FILE_PATH = '/reports/rpt_1/files/file_1'; + const getFile = (cko) => cko.reports.getReportFile('rpt_1', 'file_1'); + + CLIENTS.forEach((httpClient) => { + it(`${httpClient}: follows one 302 as a GET without Authorization, Cko- headers, Referer or body`, async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv?X-Signature=abc` }); + other.handler = respond(200, { 'Content-Type': 'text/csv' }, 'a,b\n1,2\n'); + + const csv = await getFile(skClient(httpClient, api)); + + expect(csv.toString()).to.equal('a,b\n1,2\n'); + expect(other.requests).to.have.length(1); + const [download] = other.requests; + expect(download.method).to.equal('GET'); + expect(download.url).to.equal('/file.csv?X-Signature=abc'); + expect(download.body).to.equal(''); + expect(download.headers).to.not.have.property('authorization'); + expect(download.headers).to.not.have.property('referer'); + expect(Object.keys(download.headers).filter((name) => name.startsWith('cko-'))).to.deep.equal([]); + expect(api.requests[0].headers.authorization).to.equal(SK); + }); + + it(`${httpClient}: the file request has no Cookie or Proxy-Authorization, other configured headers are kept`, async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv` }); + other.handler = respond(200, { 'Content-Type': 'text/csv' }, 'a\n'); + const cko = new Checkout(SK, { + subdomain: '123456789', + headers: { Cookie: 'session=1', 'Proxy-Authorization': 'Basic abc', 'X-Merchant': 'kept' }, + ...withClient(httpClient), + }); + cko.config.host = api.origin; + + await getFile(cko); + + const [download] = other.requests; + expect(download.headers).to.not.have.property('cookie'); + expect(download.headers).to.not.have.property('proxy-authorization'); + expect(download.headers['x-merchant']).to.equal('kept'); + expect(api.requests[0].headers.cookie).to.equal('session=1'); + }); + + [301, 303, 307, 308].forEach((status) => { + it(`${httpClient}: a ${status} on the file request is not followed`, async () => { + api.handler = respond(status, { Location: `${other.origin}/file.csv` }); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(status); + expect(err.body).to.deep.equal({ status }); + expect(other.requests).to.deep.equal([]); + }); + }); + + [ + 'http://example.invalid/file.csv', + 'http://localhost.example/file.csv', + 'http://127.0.0.1.nip.io/file.csv', + 'http://0.0.0.0/file.csv', + 'ftp://127.0.0.1/file.csv', + 'ws://127.0.0.1/file.csv', + 'file:///etc/hosts', + 'https://exa%00mple.com/file.csv', + '//example.invalid/file.csv', + ].forEach((location) => { + it(`${httpClient}: a 302 to ${location} is not followed`, async () => { + api.handler = respond(302, { Location: location }); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(302); + expect(err.body).to.deep.equal({ status: 302 }); + expectNoCredentials(err, location); + }); + }); + + it(`${httpClient}: a 302 without Location is not followed`, async () => { + api.handler = respond(302); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(302); + expect(err.body).to.deep.equal({ status: 302 }); + expect(api.requests).to.have.length(1); + expect(other.requests).to.deep.equal([]); + }); + + it(`${httpClient}: configured Cko- and Referer headers are not sent to the file location`, async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv` }); + other.handler = respond(200, { 'Content-Type': 'text/csv' }, 'a\n'); + const cko = new Checkout(SK, { + subdomain: '123456789', + headers: { 'Cko-Custom': 'api-only', Referer: 'https://merchant.example/page' }, + ...withClient(httpClient), + }); + cko.config.host = api.origin; + + await getFile(cko); + + const [download] = other.requests; + expect(download.headers).to.not.have.property('cko-custom'); + expect(download.headers).to.not.have.property('referer'); + expect(api.requests[0].headers['cko-custom']).to.equal('api-only'); + }); + + it(`${httpClient}: a 302 to the same host is followed without Authorization`, async () => { + api.handler = (req, res) => + req.url === FILE_PATH + ? respond(302, { Location: '/file.csv' })(req, res) + : respond(200, { 'Content-Type': 'text/csv' }, 'same\n')(req, res); + + const csv = await getFile(skClient(httpClient, api)); + + expect(csv.toString()).to.equal('same\n'); + expect(api.requests.map((r) => r.url)).to.deep.equal([FILE_PATH, '/file.csv']); + expect(api.requests[1].headers).to.not.have.property('authorization'); + }); + + it(`${httpClient}: user information in the file location is not sent`, async () => { + const location = other.origin.replace('http://', 'http://user:location_password_123@'); + api.handler = respond(302, { Location: `${location}/file.csv` }); + other.handler = respond(200, { 'Content-Type': 'text/csv' }, 'a\n'); + + await getFile(skClient(httpClient, api)); + + const [download] = other.requests; + expect(download.headers).to.not.have.property('authorization'); + expect(download.url).to.equal('/file.csv'); + }); + + it(`${httpClient}: an error of the file location keeps the request id of the API response`, async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv`, 'Cko-Request-Id': 'req_file_1' }); + other.handler = respond(404, {}, 'missing'); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err.http_code).to.equal(404); + expect(err.body).to.deep.equal({ status: 404, request_id: 'req_file_1' }); + }); + + it(`${httpClient}: a second 302 from the file location is not followed`, async () => { + api.handler = (req, res) => + req.url === FILE_PATH + ? respond(302, { Location: `${other.origin}/file.csv` })(req, res) + : respond(200, {}, 'again')(req, res); + other.handler = respond(302, { Location: `${api.origin}/again` }); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(302); + expect(err.body).to.deep.equal({ status: 302 }); + expect(api.requests.map((r) => r.url)).to.deep.equal([FILE_PATH]); + expect(other.requests).to.have.length(1); + }); + + it(`${httpClient}: an error status of the file location keeps the SDK error type with the status only`, async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv?X-Signature=abc` }); + other.handler = respond(403, { 'Content-Type': 'application/xml' }, 'X-Signature=abc'); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ActionNotAllowed); + expect(err.body).to.deep.equal({ status: 403 }); + expectNoCredentials(err, 'X-Signature', 'abc'); + }); + + it(`${httpClient}: other CSV downloads do not follow a 302`, async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv` }); + + const err = await catchError(skClient(httpClient, api).reconciliation.getStatementCsv('stm_1')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(302); + expect(other.requests).to.deep.equal([]); + }); + }); + }); + + describe('axios client, response processing', () => { + it('a CSV response the SDK cannot read keeps the request URL in the error body, as before', async () => { + api.handler = json(200, 5); + + const err = await catchError(skClient('axios', api).reconciliation.getStatementCsv('stm_1')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.body).to.match( + /^request to http:\/\/127\.0\.0\.1:\d+\/reporting\/statements\/stm_1\/payments\/download failed, reason: / + ); + }); + }); + + describe('axios client with a permissive validateStatus default', () => { + let saved; + + beforeEach(() => { + saved = axios.defaults.validateStatus; + axios.defaults.validateStatus = () => true; + }); + + afterEach(() => { + axios.defaults.validateStatus = saved; + }); + + it('an error status is returned as the response, as without the response policy', async () => { + api.handler = json(422, { error_codes: ['url_invalid'] }); + + const body = await skClient('axios', api).webhooks.registerWebhook({ url: 'https://example.com/hook' }); + + expect(body).to.deep.equal({ error_codes: ['url_invalid'] }); + }); + + it('a 307 on an API request is still an error and is not followed', async () => { + api.handler = respond(307, { Location: `${other.origin}/moved` }); + + const err = await catchError(REQUESTS[0].call(skClient('axios', api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(307); + expect(other.requests).to.deep.equal([]); + }); + + it('a 307 on the OAuth token request is still an error, no token is stored', async () => { + api.handler = respond(307, { Location: `${other.origin}/moved` }); + const cko = oauthClient('axios', api); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ status: 307 }); + expect(api.requests.map((r) => r.url)).to.deep.equal(['/connect/token']); + expect(cko.config.access.token).to.equal(undefined); + }); + + it('an error status on the OAuth token request is still an error, no API request is sent', async () => { + api.handler = json(401, { error: 'invalid_client' }); + const cko = oauthClient('axios', api); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ error: 'invalid_client' }); + expectNoCredentials(err); + expect(api.requests.map((r) => r.url)).to.deep.equal(['/connect/token']); + expect(cko.config.access.token).to.equal(undefined); + }); + + it('an error status of the file location is still an error, without the body of that response', async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv`, 'Cko-Request-Id': 'req_1' }); + other.handler = respond(403, { 'Content-Type': 'text/csv' }, 'file location error body'); + + const err = await catchError(skClient('axios', api).reports.getReportFile('rpt_1', 'file_1')); + + expect(err).to.be.instanceOf(ActionNotAllowed); + expect(err.body).to.deep.equal({ status: 403, request_id: 'req_1' }); + expect(JSON.stringify(err)).to.not.include('file location error body'); + }); + }); + + describe('axios client with application default headers', () => { + let saved; + + beforeEach(() => { + saved = { common: { ...axios.defaults.headers.common }, get: { ...axios.defaults.headers.get }, auth: axios.defaults.auth }; + axios.defaults.headers.common.Authorization = 'Bearer application'; + axios.defaults.headers.common.Cookie = 'application=1'; + axios.defaults.headers.common['Proxy-Authorization'] = 'Basic application'; + axios.defaults.headers.common['Cko-Application'] = 'application'; + axios.defaults.headers.get.Referer = 'https://application.example/'; + axios.defaults.headers.common['X-Application'] = 'kept'; + axios.defaults.auth = { username: 'application', password: 'application' }; + }); + + afterEach(() => { + axios.defaults.headers.common = saved.common; + axios.defaults.headers.get = saved.get; + axios.defaults.auth = saved.auth; + }); + + it('the file request has none of the headers the file location never receives', async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv` }); + other.handler = respond(200, { 'Content-Type': 'text/csv' }, 'a\n'); + + await skClient('axios', api).reports.getReportFile('rpt_1', 'file_1'); + + const [download] = other.requests; + expect(download.headers).to.not.have.property('authorization'); + expect(download.headers).to.not.have.property('cookie'); + expect(download.headers).to.not.have.property('proxy-authorization'); + expect(download.headers).to.not.have.property('cko-application'); + expect(download.headers).to.not.have.property('referer'); + expect(download.headers['x-application']).to.equal('kept'); + }); + }); + + describe('axios client with other application defaults', () => { + let saved; + + beforeEach(() => { + saved = { maxRedirects: axios.defaults.maxRedirects, adapter: axios.defaults.adapter }; + }); + + afterEach(() => { + axios.defaults.maxRedirects = saved.maxRedirects; + axios.defaults.adapter = saved.adapter; + }); + + it('a maxRedirects default does not make a 307 followed', async () => { + axios.defaults.maxRedirects = 5; + api.handler = respond(307, { Location: `${other.origin}/moved` }); + + const err = await catchError(REQUESTS[0].call(skClient('axios', api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(307); + expect(other.requests).to.deep.equal([]); + }); + + it('the fetch adapter as default does not make a 307 followed', async () => { + axios.defaults.adapter = 'fetch'; + api.handler = respond(307, { Location: `${other.origin}/moved` }); + + const err = await catchError(REQUESTS[0].call(skClient('axios', api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(307); + expect(other.requests).to.deep.equal([]); + }); + }); + + describe('without the axios validateStatus default', () => { + let saved; + + beforeEach(() => { + saved = axios.defaults.validateStatus; + axios.defaults.validateStatus = null; + }); + + afterEach(() => { + axios.defaults.validateStatus = saved; + }); + + it('a 422 is returned as the response, as axios does without validateStatus', async () => { + api.handler = json(422, { error_codes: ['url_invalid'] }); + + const body = await skClient('axios', api).webhooks.registerWebhook({ url: 'https://example.com/hook' }); + + expect(body).to.deep.equal({ error_codes: ['url_invalid'] }); + }); + }); + + describe('error statuses keep their SDK error type', () => { + CLIENTS.forEach((httpClient) => { + it(`${httpClient}: 422 gives ValidationError`, async () => { + api.handler = json(422, { error_codes: ['url_invalid'] }); + + const err = await catchError(skClient(httpClient, api).webhooks.registerWebhook({ url: 'https://example.com/hook' })); + + expect(err).to.be.instanceOf(ValidationError); + expect(err.body).to.deep.equal({ error_codes: ['url_invalid'] }); + }); + + it(`${httpClient}: OAuth token 401 gives AuthenticationError with the response body`, async () => { + api.handler = json(401, { error: 'invalid_client' }); + + const err = await catchError(oauthClient(httpClient, api).payments.get('pay_123')); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ error: 'invalid_client' }); + expectNoCredentials(err); + }); + + it(`${httpClient}: OAuth token 500 with a JSON null body gives ApiError 500`, async () => { + api.handler = respond(500, { 'Content-Type': 'application/json' }, 'null'); + + const err = await catchError(oauthClient(httpClient, api).payments.get('pay_123')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(500); + expectNoCredentials(err); + }); + }); + }); + + describe('connection errors', () => { + let closedOrigin; + + before(async () => { + const server = await startServer(); + closedOrigin = server.origin; + await stopServer(server); + }); + + const closedApi = () => ({ origin: closedOrigin }); + + CLIENTS.forEach((httpClient) => { + it(`${httpClient}: an API request gives ApiError without http_code, with the client error as cause`, async () => { + const url = `${closedOrigin}/payments`; + + const err = await catchError(REQUESTS[0].call(skClient(httpClient, closedApi()))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(undefined); + expect(err.cause).to.be.instanceOf(Error); + expect(err.body).to.equal(`request to ${url} failed, reason: ${err.cause.message}`); + expect(err.cause.code).to.equal('ECONNREFUSED'); + expect(Object.keys(err)).to.not.include('cause'); + expectNoCredentials(err, '"cvv"'); + }); + + it(`${httpClient}: the OAuth token request gives ApiError without http_code, with the client error as cause`, async () => { + const url = `${closedOrigin}/connect/token`; + + const err = await catchError(oauthClient(httpClient, closedApi()).payments.get('pay_123')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(undefined); + expect(err.cause).to.be.instanceOf(Error); + expect(err.body).to.equal( + httpClient === 'axios' ? `request to ${url} failed, reason: ${err.cause.message}` : err.cause.message + ); + expect(err.cause.code).to.equal('ECONNREFUSED'); + expectNoCredentials(err); + }); + + it(`${httpClient}: input validation: a configured value the client rejects`, async () => { + const cko = new Checkout(`${SK}\r\nX-Extra: 1`, { subdomain: '123456789', ...withClient(httpClient) }); + cko.config.host = closedOrigin; + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(undefined); + expectNoCredentials(err, 'X-Extra'); + }); + + it(`${httpClient}: input validation: a configured header value the client rejects`, async () => { + const cko = new Checkout(SK, { + subdomain: '123456789', + headers: { 'X-Merchant-Key': 'merchant_value_123\u0000' }, + ...withClient(httpClient), + }); + cko.config.host = closedOrigin; + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(ApiError); + expectNoCredentials(err, 'merchant_value_123'); + }); + + it(`${httpClient}: input validation: a host with user information`, async () => { + const cko = skClient(httpClient, { origin: closedOrigin.replace('http://', 'http://user:host_password_123@') }); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.body).to.match(/^request to http:\/\/127\.0\.0\.1:\d+\/payments\/pay_123 failed, reason: /); + expectNoCredentials(err, 'host_password_123'); + }); + + [ + 'http://user:host_password_123@127.0.0.1:99999', + 'http://user:host_password_123@exa mple.com', + 'user:host_password_123@127.0.0.1:1', + '//user:host_password_123@127.0.0.1:1', + '\thttp://user:host_password_123@127.0.0.1:99999', + 'http:\\\\user:host_password_123@127.0.0.1:99999', + 'ht tp://user:host_password_123@127.0.0.1:1', + 'http://user:host/pass?word#123_host_password_123@127.0.0.1:99999', + ].forEach((origin) => { + it(`${httpClient}: input validation: a host with user information that is not a valid URL (${JSON.stringify(origin)})`, async () => { + const cko = skClient(httpClient, { origin }); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(Error); + expectNoCredentials(err, 'host_password_123', 'pass?word'); + }); + }); + }); + }); +}); From 4df3d9711b7df587e110205bd71be6787c1ba307 Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Tue, 24 Nov 2026 21:33:04 +0100 Subject: [PATCH 2/3] fix(client): security hardening Helpers per HTTP client in the HTTP layer, more tests, and type declarations aligned. --- src/services/http.js | 388 +++++++++++++--------------- test/http/responsePolicy.js | 122 +++++++++ types/dist/api/reports/reports.d.ts | 2 +- types/dist/services/errors.d.ts | 2 + 4 files changed, 302 insertions(+), 212 deletions(-) diff --git a/src/services/http.js b/src/services/http.js index 65b6fc72..07acdeae 100644 --- a/src/services/http.js +++ b/src/services/http.js @@ -207,11 +207,8 @@ const AXIOS_SUCCESS_ONLY_POLICY = { // Body of the errors of the response policy: the status, and the request id when the API sent one. const statusOnlyBody = (status, requestId) => (requestId ? { status, request_id: requestId } : { status }); -const requestIdOf = (headers) => { - const get = (name) => (typeof headers?.get === 'function' ? headers.get(name) : headers?.[name]); - const value = get(REQUEST_ID_HEADER) || get('request-id'); - return Array.isArray(value) ? value[0] : value || undefined; -}; +// The request id of a 3xx response: both clients give its headers with get(). +const requestIdOf = (headers) => headers?.get?.(REQUEST_ID_HEADER) || headers?.get?.('request-id') || undefined; // A 3xx response: an ApiError with the status only. const redirectStatusError = (status, requestId) => new ApiError(status, statusOnlyBody(status, requestId)); @@ -293,18 +290,61 @@ const fetchFailure = (error) => const isTimeout = (error) => error.code === 'ECONNABORTED' || error.name === 'AbortError' || error.message?.includes('timeout'); +// A request without a response: ApiTimeout, or a connection error whose body is `reason(error)`. +const noResponseError = (error, reason) => (isTimeout(error) ? new ApiTimeout() : connectionError(reason(error), error)); + +// One axios request. A response the request options refuse goes to `onRefused`, which returns the +// result or throws; `onSuccess` runs in the same try, so an error reading the response is a +// connection error, as for any error without a response. +const axiosRequest = async (options, reason, onRefused, onSuccess = (response) => response) => { + try { + return onSuccess(await axios(options)); + } catch (error) { + if (error.response) { + return onRefused(error.response); + } + throw noResponseError(error, reason); + } +}; + +// One fetch request; without a response, ApiTimeout or a connection error (see fetchFailure). +const fetchRequest = async (url, options, reason) => { + try { + return await fetch(url, options); + } catch (error) { + throw noResponseError(fetchFailure(error), reason); + } +}; + +// A fetch response that is not used: its body is discarded and `error` is thrown. +const refuseResponse = async (response, error) => { + await discardBody(response); + throw await error; +}; + +const withAgent = (options, agent) => (agent === undefined ? options : { ...options, agent }); + const isLoopbackHost = (hostname) => hostname === 'localhost' || hostname === '[::1]' || /^127(\.\d{1,3}){3}$/.test(hostname); -// The file location of a report download: https, or http for a loopback host (local tests). -const fileDownloadUrl = (location, base) => { - let url; +const parseUrl = (value, base) => { try { - url = new URL(location, base); + return new URL(value, base); } catch { return undefined; } - if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) { +}; + +// http is accepted for a loopback file location only when the API base is loopback too (local +// tests). +const isDownloadScheme = (url, base) => + url.protocol === 'https:' || + (url.protocol === 'http:' && isLoopbackHost(url.hostname) && isLoopbackHost(parseUrl(base)?.hostname)); + +// The file location of a report download, without user information (see isDownloadScheme). +const fileDownloadUrl = (location, base) => { + const url = parseUrl(location, base); + if (!url || !isDownloadScheme(url, base)) { return undefined; } url.username = ''; @@ -314,13 +354,13 @@ const fileDownloadUrl = (location, base) => { // Headers never sent to the file location (the HTTP clients also drop the first three when they // follow a response to another host). -const FILE_DOWNLOAD_DROPPED_HEADERS = ['authorization', 'proxy-authorization', 'cookie', 'referer']; +const FILE_DOWNLOAD_DROPPED_HEADERS = new Set(['authorization', 'proxy-authorization', 'cookie', 'referer']); // Headers of the file request: the API request headers without the ones above and the SDK's Cko- // headers. const isDroppedFileHeader = (name) => { const lower = name.toLowerCase(); - return FILE_DOWNLOAD_DROPPED_HEADERS.includes(lower) || lower.startsWith('cko-'); + return FILE_DOWNLOAD_DROPPED_HEADERS.has(lower) || lower.startsWith('cko-'); }; const fileDownloadHeaders = (headers) => @@ -337,65 +377,92 @@ const followsFileDownload = (config, method, status) => config.fileDownload === // The only redirect followed: one 302 of a report file download, as a GET without a body (see // fileDownloadUrl and fileDownloadHeaders). Its own 3xx is not followed; an error status keeps -// the SDK error type with the status only. Errors name the API request, not the file location. -const downloadFile = async (httpClient, config, path, location, headers, requestId) => { - const url = location ? fileDownloadUrl(location, path) : undefined; +// the SDK error type with the status only. Errors name the API request (`api`: method, path and +// headers), not the file location. +const downloadFile = async (httpClient, config, api, location, requestId) => { + const url = location ? fileDownloadUrl(location, api.path) : undefined; if (!url) { throw redirectStatusError(302, requestId); } - const fileHeaders = fileDownloadHeaders(headers); + const headers = fileDownloadHeaders(api.headers); + const reason = (error) => connectionReason(api.path, error); + const statusFailure = (status) => + isRedirect(status) ? redirectStatusError(status, requestId) : statusError(status, statusOnlyBody(status, requestId)); if (httpClient === 'axios') { - let response; - try { - response = await axios({ - url, - method: 'GET', - headers: fileHeaders, - auth: null, - transformRequest: [dropFileHeaderDefaults], - timeout: config.timeout, - httpsAgent: config.agent, - ...AXIOS_SUCCESS_ONLY_POLICY, - }); - } catch (error) { - if (isTimeout(error)) { - throw new ApiTimeout(); - } - if (error.response) { - const { status } = error.response; - throw isRedirect(status) - ? redirectStatusError(status, requestId) - : await statusError(status, statusOnlyBody(status, requestId)); - } - throw connectionError(connectionReason(path, error), error); - } + const options = { + url, + method: 'GET', + headers, + auth: null, + transformRequest: [dropFileHeaderDefaults], + timeout: config.timeout, + httpsAgent: config.agent, + ...AXIOS_SUCCESS_ONLY_POLICY, + }; + const response = await axiosRequest(options, reason, async ({ status }) => { + throw await statusFailure(status); + }); return buildAxiosResponse(config, response); } - const fetchOptions = { method: 'GET', headers: fileHeaders, redirect: 'manual' }; - if (typeof config.agent !== 'undefined') { - fetchOptions.agent = config.agent; + const response = await fetchRequest(url, withAgent({ method: 'GET', headers, redirect: 'manual' }, config.agent), reason); + if (!response.ok) { + await refuseResponse(response, statusFailure(response.status)); } - let response; - try { - response = await fetch(url, fetchOptions); - } catch (error) { - if (isTimeout(error)) { - throw new ApiTimeout(); + return buildResponse(config, response); +}; + +const TOKEN_REQUEST_HEADERS = { + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json', +}; + +const axiosAccessToken = async (config, accessUrl, requestBody) => { + const options = { + url: accessUrl, + method: 'post', + headers: TOKEN_REQUEST_HEADERS, + data: new URLSearchParams(requestBody), + timeout: config.timeout, + httpsAgent: config.agent, + ...AXIOS_SUCCESS_ONLY_POLICY, + }; + const access = await axiosRequest( + options, + (error) => connectionReason(accessUrl, error), + async ({ status, data }) => { + throw isRedirect(status) ? tokenRedirectError(status) : await statusError(status, data); } - const failure = fetchFailure(error); - throw connectionError(connectionReason(path, failure), failure); + ); + return { + status: access.status, + json: access.data, + }; +}; + +const fetchAccessToken = async (config, accessUrl, requestBody) => { + const options = { + method: 'POST', + timeout: config.timeout, + agent: config.agent, + redirect: 'manual', + body: new URLSearchParams(requestBody), + headers: TOKEN_REQUEST_HEADERS, + }; + // Same body as before for this client: the client's message. + const access = await fetchRequest(accessUrl, options, (error) => error.message); + if (isRedirect(access.status)) { + await refuseResponse(access, tokenRedirectError(access.status)); } - if (isRedirect(response.status)) { - await discardBody(response); - throw redirectStatusError(response.status, requestId); + if (!access.ok) { + throw await statusError(access.status, await bodyParser(access)); } - if (!response.ok) { - await discardBody(response); - throw await statusError(response.status, statusOnlyBody(response.status, requestId)); - } - return buildResponse(config, response); + const text = await access.text(); + return { + status: access.status, + json: text ? JSON.parse(text) : {}, + }; }; /** @@ -420,89 +487,21 @@ export const createAccessToken = async (config, httpClient, body) => { }; // Use environmentSubdomain if exists, otherwise use environment - let accessUrl; - if (config.environmentSubdomain) { - accessUrl = config.environmentSubdomain.getOAuthAuthorizationApi(); - } else { - accessUrl = config.environment.getOAuthAuthorizationApi(); - } - - let access; - - switch (httpClient) { - case 'axios': - try { - access = await axios({ - url: accessUrl, - method: 'post', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - Accept: 'application/json', - }, - data: new URLSearchParams(requestBody), - timeout: config.timeout, - httpsAgent: config.agent, - ...AXIOS_SUCCESS_ONLY_POLICY, - }); - } catch (error) { - if (isTimeout(error)) { - throw new ApiTimeout(); - } - if (error.response) { - const { status, data } = error.response; - throw isRedirect(status) ? tokenRedirectError(status) : await statusError(status, data); - } - throw connectionError(connectionReason(accessUrl, error), error); - } - return { - status: access.status, - json: access.data, - }; + const accessUrl = (config.environmentSubdomain || config.environment).getOAuthAuthorizationApi(); - default: - try { - access = await fetch( - accessUrl, - { - method: 'POST', - timeout: config.timeout, - agent: config.agent, - redirect: 'manual', - body: new URLSearchParams(requestBody), - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - Accept: 'application/json', - }, - } - ); - } catch (error) { - if (isTimeout(error)) { - throw new ApiTimeout(); - } - // Same body as before for this client: the client's message. - const failure = fetchFailure(error); - throw connectionError(failure.message, failure); - } - if (isRedirect(access.status)) { - await discardBody(access); - throw tokenRedirectError(access.status); - } - if (!access.ok) { - const json = await bodyParser(access); - throw await statusError(access.status, json); - } + return httpClient === 'axios' + ? axiosAccessToken(config, accessUrl, requestBody) + : fetchAccessToken(config, accessUrl, requestBody); +}; - return access.text().then((text) => { - const data = text ? JSON.parse(text) : {}; - return { - status: access.status, - json: data, - }; - }); +// A 3xx answer to an API request: the report file download, or an error with the status only. +const redirected = (httpClient, config, api, status, location, requestId) => { + if (followsFileDownload(config, api.method, status)) { + return downloadFile(httpClient, config, api, location, requestId); } + throw redirectStatusError(status, requestId); }; - const httpRequest = async (httpClient, verb, path, config, auth, request, idempotencyKey) => { // fetch only normalises the case of DELETE, GET, HEAD, OPTIONS, POST and PUT, so a // lowercase "patch" goes out as-is and the API answers 400. Send every verb uppercase. @@ -527,85 +526,52 @@ const httpRequest = async (httpClient, verb, path, config, auth, request, idempo } const headers = getRequestHeaders(config, request, authHeader, idempotencyKey); + const api = { method, path, headers }; + const reason = (error) => connectionReason(path, error); - let response; - - switch (httpClient) { - case 'axios': - try { - response = await axios({ - url: path, - method, - headers, - data: config.formData ? request : JSON.stringify(request), - timeout: config.timeout, - httpsAgent: config.agent, - ...AXIOS_RESPONSE_POLICY, - }); - return buildAxiosResponse(config, response); - } catch (error) { - if (isTimeout(error)) { - throw new ApiTimeout(); - } - if (error.response) { - const { status, headers: responseHeaders } = error.response; - if (isRedirect(status)) { - const requestId = requestIdOf(responseHeaders); - if (followsFileDownload(config, method, status)) { - return downloadFile(httpClient, config, path, responseHeaders?.location, headers, requestId); - } - throw redirectStatusError(status, requestId); - } - throw { - status, - json: error.response.data, - }; - } - throw connectionError(connectionReason(path, error), error); - } - - default: - let body; - if (config.formData && request && typeof request.getHeaders === 'function') { - body = await formDataToBuffer(request); - } else { - body = config.formData ? request : JSON.stringify(request); - } - const fetchOptions = { - method, - body, - headers, - redirect: 'manual', - }; - if (typeof config.agent !== 'undefined') { - fetchOptions.agent = config.agent; - } - try { - response = await fetch(path, fetchOptions); - } catch (error) { - if (isTimeout(error)) { - throw new ApiTimeout(); + if (httpClient === 'axios') { + const options = { + url: path, + method, + headers, + data: config.formData ? request : JSON.stringify(request), + timeout: config.timeout, + httpsAgent: config.agent, + ...AXIOS_RESPONSE_POLICY, + }; + return axiosRequest( + options, + reason, + ({ status, headers: responseHeaders, data }) => { + if (isRedirect(status)) { + return redirected(httpClient, config, api, status, responseHeaders?.location, requestIdOf(responseHeaders)); } - const failure = fetchFailure(error); - throw connectionError(connectionReason(path, failure), failure); - } + throw { status, json: data }; + }, + (response) => buildAxiosResponse(config, response) + ); + } - if (isRedirect(response.status)) { - const requestId = requestIdOf(response.headers); - const location = response.headers.get('location'); - await discardBody(response); - if (followsFileDownload(config, method, response.status)) { - return downloadFile(httpClient, config, path, location, headers, requestId); - } - throw redirectStatusError(response.status, requestId); - } - if (!response.ok) { - const json = await bodyParser(response); - throw { status: response.status, json }; - } + let body; + if (config.formData && request && typeof request.getHeaders === 'function') { + body = await formDataToBuffer(request); + } else { + body = config.formData ? request : JSON.stringify(request); + } + const response = await fetchRequest(path, withAgent({ method, body, headers, redirect: 'manual' }, config.agent), reason); - return buildResponse(config, response); + if (isRedirect(response.status)) { + const requestId = requestIdOf(response.headers); + const location = response.headers.get('location'); + await discardBody(response); + return redirected(httpClient, config, api, response.status, location, requestId); + } + if (!response.ok) { + const json = await bodyParser(response); + throw { status: response.status, json }; } + + return buildResponse(config, response); }; export const get = async (httpClient, path, config, auth) => diff --git a/test/http/responsePolicy.js b/test/http/responsePolicy.js index 4906b131..71e47fd0 100644 --- a/test/http/responsePolicy.js +++ b/test/http/responsePolicy.js @@ -151,8 +151,42 @@ const REQUESTS = [ cko.webhooks.registerWebhook({ url: 'https://example.com/hook', headers: { authorization: 'hook_value_123' } }), secret: 'hook_value_123', }, + { + name: 'webhooks.updateWebhook (PUT)', + path: '/webhooks/wh_1', + call: (cko) => + cko.webhooks.updateWebhook('wh_1', { url: 'https://example.com/hook', headers: { authorization: 'hook_value_put' } }), + secret: 'hook_value_put', + }, + { + name: 'webhooks.partiallyUpdateWebhook (PATCH)', + path: '/webhooks/wh_1', + call: (cko) => cko.webhooks.partiallyUpdateWebhook('wh_1', { headers: { authorization: 'hook_value_patch' } }), + secret: 'hook_value_patch', + }, + { + name: 'forward.updateSecret (PATCH)', + path: '/secrets/n', + call: (cko) => cko.forward.updateSecret('n', { value: 'secret_value_patch' }), + secret: 'secret_value_patch', + }, + { name: 'webhooks.removeWebhook (DELETE)', path: '/webhooks/wh_1', call: (cko) => cko.webhooks.removeWebhook('wh_1') }, + { name: 'forward.deleteSecret (DELETE)', path: '/secrets/n', call: (cko) => cko.forward.deleteSecret('n') }, ]; +// Values a header must never repeat in an error, each appended to a value the test looks for. +const HOSTILE_VALUES = { + 'a tab': '\t', + DEL: '\u007f', + NEL: '\u0085', + 'a line separator': '\u2028', + 'a right-to-left override': '\u202e', + 'full-width characters': '\uff53\uff4b', + 'non-ASCII characters': '\u00e9', + 'Bearer and CR/LF': 'Bearer \r\n', + 'a value over the header size limit': 'x'.repeat(20000), +}; + describe('HTTP response policy', () => { let api; let other; @@ -445,6 +479,68 @@ describe('HTTP response policy', () => { expectNoCredentials(err, 'X-Signature', 'abc'); }); + [ + (port) => `http://127.0.0.1:${port}/file.csv`, + (port) => `http://127.1:${port}/file.csv`, + (port) => `http://localhost:${port}/file.csv`, + (port) => `HTTP://127.0.0.1:${port}/file.csv`, + (port) => `http://[::1]:${port}/file.csv`, + ].forEach((locationOf) => { + it(`${httpClient}: an http file location (${locationOf('')}) is not followed when the API is not on a loopback host`, async () => { + const location = locationOf(other.http.address().port); + api.handler = respond(302, { Location: location }); + const cko = skClient(httpClient, api); + cko.config.host = api.origin.replace('127.0.0.1', '0.0.0.0'); + + const err = await catchError(getFile(cko)); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(302); + expect(err.body).to.deep.equal({ status: 302 }); + expect(api.requests).to.have.length(1); + expect(other.requests).to.deep.equal([]); + }); + }); + + ['http://127.0.0.1%E2%80%AE.example/file.csv', 'http://ex\u00e4mple.invalid/file.csv'].forEach((location) => { + it(`${httpClient}: a 302 to ${JSON.stringify(location)} is not followed`, async () => { + api.handler = respond(302, { Location: location }); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.body).to.deep.equal({ status: 302 }); + expect(other.requests).to.deep.equal([]); + }); + }); + + it(`${httpClient}: a connection error of the file location names the API request, not the file location`, async () => { + const closed = await startServer(); + await stopServer(closed); + api.handler = respond(302, { Location: `${closed.origin}/file.csv?X-Signature=signature_value_123` }); + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(undefined); + expect(err.body).to.equal(`request to ${api.origin}${FILE_PATH} failed, reason: ${err.cause.message}`); + expectNoCredentials(err, 'file.csv', 'X-Signature', 'signature_value_123'); + }); + + it(`${httpClient}: a truncated file response is an error without the file location`, async () => { + api.handler = respond(302, { Location: `${other.origin}/file.csv?X-Signature=signature_value_123` }); + other.handler = (req, res) => { + res.writeHead(200, { 'Content-Type': 'text/csv', 'Content-Length': '100' }); + res.write('a,b'); + res.destroy(); + }; + + const err = await catchError(getFile(skClient(httpClient, api))); + + expect(err).to.be.instanceOf(Error); + expectNoCredentials(err, 'file.csv', 'X-Signature', 'signature_value_123'); + }); + it(`${httpClient}: other CSV downloads do not follow a 302`, async () => { api.handler = respond(302, { Location: `${other.origin}/file.csv` }); @@ -728,6 +824,32 @@ describe('HTTP response policy', () => { expectNoCredentials(err, 'merchant_value_123'); }); + Object.entries(HOSTILE_VALUES).forEach(([name, chars]) => { + it(`${httpClient}: input validation: a configured header value with ${name}`, async () => { + const cko = new Checkout(SK, { + subdomain: '123456789', + headers: { 'X-Merchant-Key': `merchant_value_123${chars}` }, + ...withClient(httpClient), + }); + cko.config.host = closedOrigin; + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(Error); + expectNoCredentials(err, 'merchant_value_123'); + }); + + it(`${httpClient}: input validation: a secret key with ${name}`, async () => { + const cko = new Checkout(`${SK}${chars}`, { subdomain: '123456789', ...withClient(httpClient) }); + cko.config.host = closedOrigin; + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(Error); + expectNoCredentials(err); + }); + }); + it(`${httpClient}: input validation: a host with user information`, async () => { const cko = skClient(httpClient, { origin: closedOrigin.replace('http://', 'http://user:host_password_123@') }); diff --git a/types/dist/api/reports/reports.d.ts b/types/dist/api/reports/reports.d.ts index 7c6a2d35..1312b13a 100644 --- a/types/dist/api/reports/reports.d.ts +++ b/types/dist/api/reports/reports.d.ts @@ -5,5 +5,5 @@ export default class Reports { getAllReports: (parameters: Object) => Promise; getReportDetails: (id: string) => Promise; - getReportFile: (id: string, fileId: string) => Promise; + getReportFile: (id: string, fileId: string) => Promise; } diff --git a/types/dist/services/errors.d.ts b/types/dist/services/errors.d.ts index 063f6ea3..27a4b0ce 100644 --- a/types/dist/services/errors.d.ts +++ b/types/dist/services/errors.d.ts @@ -117,6 +117,8 @@ export class ApiError extends Error { constructor(http_code: any, message: any); http_code: any; body: any; + /** On a connection error: the HTTP client's error, with its name, message and code only. */ + cause?: Error; } /** * ValueError From c5eb1edfbbab9682d7c6e20c0801ca98e998e8a1 Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Wed, 25 Nov 2026 15:04:18 +0100 Subject: [PATCH 3/3] fix(client): security hardening HTTP layer response handling aligned across clients, with more tests. --- src/services/http.js | 62 ++++++++---- test/http/responsePolicy.js | 191 ++++++++++++++++++++++++++++++++++-- 2 files changed, 224 insertions(+), 29 deletions(-) diff --git a/src/services/http.js b/src/services/http.js index 07acdeae..11b654ab 100644 --- a/src/services/http.js +++ b/src/services/http.js @@ -191,9 +191,11 @@ const acceptStatus = (status) => { return typeof validateStatus === 'function' ? validateStatus(status) : true; }; -// axios options of every SDK request: redirects are not followed (see acceptStatus). +// axios options of every SDK request: redirects are not followed (see acceptStatus), and axios's +// built-in http/https transport is used whatever the application's transport default. const AXIOS_RESPONSE_POLICY = { maxRedirects: 0, + transport: null, validateStatus: acceptStatus, }; @@ -216,6 +218,16 @@ const redirectStatusError = (status, requestId) => new ApiError(status, statusOn // A 3xx response to the token request: an AuthenticationError with the status only. const tokenRedirectError = (status) => new AuthenticationError({ status }, 'Unexpected token response status'); +// A token response the SDK cannot use: an AuthenticationError with the status only. +const tokenResponseError = (status) => new AuthenticationError({ status }, 'Invalid access token response'); + +// A token the SDK can send: a non-empty string access_token and token_type (RFC 6749, 5.1). +const isUsableToken = (body) => + typeof body?.access_token === 'string' && + body.access_token !== '' && + typeof body.token_type === 'string' && + body.token_type !== ''; + // The body of a response that is not used is discarded, so fetch releases the connection. const discardBody = async (response) => { try { @@ -352,24 +364,20 @@ const fileDownloadUrl = (location, base) => { return url.href; }; -// Headers never sent to the file location (the HTTP clients also drop the first three when they -// follow a response to another host). -const FILE_DOWNLOAD_DROPPED_HEADERS = new Set(['authorization', 'proxy-authorization', 'cookie', 'referer']); +// The only API request headers sent to the file location. +const FILE_DOWNLOAD_HEADERS = new Set(['user-agent', 'accept']); -// Headers of the file request: the API request headers without the ones above and the SDK's Cko- -// headers. -const isDroppedFileHeader = (name) => { - const lower = name.toLowerCase(); - return FILE_DOWNLOAD_DROPPED_HEADERS.has(lower) || lower.startsWith('cko-'); -}; +const isFileHeader = (name) => FILE_DOWNLOAD_HEADERS.has(name.toLowerCase()); const fileDownloadHeaders = (headers) => - Object.fromEntries(Object.entries(headers).filter(([name, value]) => value != null && !isDroppedFileHeader(name))); + Object.fromEntries(Object.entries(headers).filter(([name, value]) => value != null && isFileHeader(name))); // axios adds the application's default headers and auth after the request headers are set: the -// same headers are removed from the merged headers of the file request, and auth is not used. +// merged headers of the file request keep only the ones above too, and auth is not used. const dropFileHeaderDefaults = (data, headers) => { - Object.keys(headers.toJSON()).filter(isDroppedFileHeader).forEach((name) => headers.delete(name)); + Object.keys(headers.toJSON()) + .filter((name) => !isFileHeader(name)) + .forEach((name) => headers.delete(name)); return data; }; @@ -377,8 +385,9 @@ const followsFileDownload = (config, method, status) => config.fileDownload === // The only redirect followed: one 302 of a report file download, as a GET without a body (see // fileDownloadUrl and fileDownloadHeaders). Its own 3xx is not followed; an error status keeps -// the SDK error type with the status only. Errors name the API request (`api`: method, path and -// headers), not the file location. +// the SDK error type with the status only. The SDK's error text names the API request path, never +// the file path or query; a connection error keeps the client's reason, which can name the file +// host. const downloadFile = async (httpClient, config, api, location, requestId) => { const url = location ? fileDownloadUrl(location, api.path) : undefined; if (!url) { @@ -395,6 +404,7 @@ const downloadFile = async (httpClient, config, api, location, requestId) => { method: 'GET', headers, auth: null, + params: null, transformRequest: [dropFileHeaderDefaults], timeout: config.timeout, httpsAgent: config.agent, @@ -432,7 +442,11 @@ const axiosAccessToken = async (config, accessUrl, requestBody) => { options, (error) => connectionReason(accessUrl, error), async ({ status, data }) => { - throw isRedirect(status) ? tokenRedirectError(status) : await statusError(status, data); + if (isRedirect(status)) { + throw tokenRedirectError(status); + } + // A 2xx axios refuses (a body its parsing options reject) is not a usable token response. + throw status >= 200 && status < 300 ? tokenResponseError(status) : await statusError(status, data); } ); return { @@ -459,9 +473,16 @@ const fetchAccessToken = async (config, accessUrl, requestBody) => { throw await statusError(access.status, await bodyParser(access)); } const text = await access.text(); + let body = {}; + try { + // An empty body is an empty object, as before for this client. + body = text ? JSON.parse(text) : body; + } catch { + throw tokenResponseError(access.status); + } return { status: access.status, - json: text ? JSON.parse(text) : {}, + json: body, }; }; @@ -472,8 +493,8 @@ const fetchAccessToken = async (config, accessUrl, requestBody) => { * @param {string} httpClient 'axios', or anything else for fetch. * @param {Object} [body] Token request body; client credentials from the config by default. * @return {Promise} status and json of the token response. - * @throws {AuthenticationError} On an unexpected response status (body `{ status }`), a 401 or a - * 400 OAuth error. + * @throws {AuthenticationError} On an unexpected response status or a 2xx body the client cannot + * parse (body `{ status }`), a 401 or a 400 OAuth error. * @throws {ApiTimeout} When the axios client times out. * @throws {Error} On any other error status, the SDK error of that status (as determineError); * without a response, an ApiError without http_code and with the client's error as cause. @@ -519,6 +540,9 @@ const httpRequest = async (httpClient, verb, path, config, auth, request, idempo authHeader = `${config.access.type} ${config.access.token}`; } else { const access = await createAccessToken(config, httpClient); + if (!isUsableToken(access.json)) { + throw tokenResponseError(access.status); + } authHeader = `${access.json.token_type} ${access.json.access_token}`; storeAccessToken(config, access.json); diff --git a/test/http/responsePolicy.js b/test/http/responsePolicy.js index 71e47fd0..d832c576 100644 --- a/test/http/responsePolicy.js +++ b/test/http/responsePolicy.js @@ -306,6 +306,79 @@ describe('HTTP response policy', () => { expect(other.requests).to.deep.equal([]); expectNoCredentials(err); }); + + [ + ['a body that is not JSON', { 'Content-Type': 'text/html' }, 'token_body_value'], + ['a JSON null body', { 'Content-Type': 'application/json' }, 'null'], + ['an empty JSON object', { 'Content-Type': 'application/json' }, '{}'], + ['a JSON array', { 'Content-Type': 'application/json' }, '["token_body_value"]'], + ['a JSON string', { 'Content-Type': 'application/json' }, '"token_body_value"'], + ['an empty body', { 'Content-Type': 'application/json' }, ''], + ['a truncated JSON body', { 'Content-Type': 'application/json' }, '{"access_token":"token_body_value"'], + ['no token_type', { 'Content-Type': 'application/json' }, '{"access_token":"token_body_value"}'], + ['an access_token that is not a string', { 'Content-Type': 'application/json' }, '{"access_token":12345,"token_type":"Bearer","refresh":"token_body_value"}'], + ['an empty access_token', { 'Content-Type': 'application/json' }, '{"access_token":"","token_type":"Bearer","refresh":"token_body_value"}'], + ['an empty token_type', { 'Content-Type': 'application/json' }, '{"access_token":"token_body_value","token_type":""}'], + ].forEach(([name, headers, body]) => { + it(`${httpClient}: a 200 with ${name} gives AuthenticationError with the status only, no API request is sent`, async () => { + api.handler = respond(200, headers, body); + const cko = oauthClient(httpClient, api); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ status: 200 }); + expect(api.requests.map((r) => r.url)).to.deep.equal(['/connect/token']); + expect(cko.config.access.token).to.equal(undefined); + expectNoCredentials(err, 'token_body_value', '12345'); + }); + }); + + const accessRequest = (cko) => + cko.access.request({ + grant_type: 'client_credentials', + client_id: CLIENT, + client_secret: CLIENT_CREDENTIAL, + scope: 'gateway', + }); + + it(`${httpClient}: access.request with a 200 JSON object without a token returns it, as before`, async () => { + api.handler = json(200, { token_type: 'Bearer' }); + + const body = await accessRequest(oauthClient(httpClient, api)); + + expect(body).to.deep.equal({ token_type: 'Bearer' }); + }); + + [ + ['a JSON null', 'null', null], + ['a JSON array', '[1]', [1]], + ['a JSON string', '"s"', 's'], + ].forEach(([name, body, expected]) => { + it(`${httpClient}: access.request with a 200 with ${name} returns it, as before`, async () => { + api.handler = respond(200, { 'Content-Type': 'application/json' }, body); + + expect(await accessRequest(oauthClient(httpClient, api))).to.deep.equal(expected); + }); + }); + + if (httpClient === 'fetch') { + it('fetch: access.request with a 200 that is not JSON gives AuthenticationError with the status only', async () => { + api.handler = respond(200, { 'Content-Type': 'text/html' }, 'token_body_value'); + + const err = await catchError(accessRequest(oauthClient(httpClient, api))); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ status: 200 }); + expectNoCredentials(err, 'token_body_value'); + }); + } else { + it('axios: access.request with a 200 that is not JSON returns the text, as before', async () => { + api.handler = respond(200, { 'Content-Type': 'text/html' }, 'a'); + + expect(await accessRequest(oauthClient(httpClient, api))).to.equal('a'); + }); + } }); }); @@ -332,12 +405,18 @@ describe('HTTP response policy', () => { expect(api.requests[0].headers.authorization).to.equal(SK); }); - it(`${httpClient}: the file request has no Cookie or Proxy-Authorization, other configured headers are kept`, async () => { + it(`${httpClient}: the file request sends no configured header other than User-Agent and Accept`, async () => { api.handler = respond(302, { Location: `${other.origin}/file.csv` }); other.handler = respond(200, { 'Content-Type': 'text/csv' }, 'a\n'); const cko = new Checkout(SK, { subdomain: '123456789', - headers: { Cookie: 'session=1', 'Proxy-Authorization': 'Basic abc', 'X-Merchant': 'kept' }, + headers: { + Cookie: 'session=1', + 'Proxy-Authorization': 'Basic abc', + 'X-Api-Key': 'merchant_key_value', + 'X-Merchant': 'merchant_value', + Accept: 'text/csv', + }, ...withClient(httpClient), }); cko.config.host = api.origin; @@ -345,9 +424,12 @@ describe('HTTP response policy', () => { await getFile(cko); const [download] = other.requests; - expect(download.headers).to.not.have.property('cookie'); - expect(download.headers).to.not.have.property('proxy-authorization'); - expect(download.headers['x-merchant']).to.equal('kept'); + ['cookie', 'proxy-authorization', 'x-api-key', 'x-merchant', 'cache-control', 'pragma', 'content-type'].forEach( + (name) => expect(download.headers).to.not.have.property(name) + ); + expect(download.headers['user-agent']).to.match(/^checkout-sdk-node\//); + expect(download.headers.accept).to.equal('text/csv'); + expect(api.requests[0].headers['x-api-key']).to.equal('merchant_key_value'); expect(api.requests[0].headers.cookie).to.equal('session=1'); }); @@ -643,7 +725,7 @@ describe('HTTP response policy', () => { axios.defaults.headers.common['Proxy-Authorization'] = 'Basic application'; axios.defaults.headers.common['Cko-Application'] = 'application'; axios.defaults.headers.get.Referer = 'https://application.example/'; - axios.defaults.headers.common['X-Application'] = 'kept'; + axios.defaults.headers.common['X-Application'] = 'application'; axios.defaults.auth = { username: 'application', password: 'application' }; }); @@ -665,7 +747,7 @@ describe('HTTP response policy', () => { expect(download.headers).to.not.have.property('proxy-authorization'); expect(download.headers).to.not.have.property('cko-application'); expect(download.headers).to.not.have.property('referer'); - expect(download.headers['x-application']).to.equal('kept'); + expect(download.headers).to.not.have.property('x-application'); }); }); @@ -673,12 +755,101 @@ describe('HTTP response policy', () => { let saved; beforeEach(() => { - saved = { maxRedirects: axios.defaults.maxRedirects, adapter: axios.defaults.adapter }; + saved = { + maxRedirects: axios.defaults.maxRedirects, + adapter: axios.defaults.adapter, + transport: axios.defaults.transport, + params: axios.defaults.params, + transitional: axios.defaults.transitional, + responseType: axios.defaults.responseType, + }; }); afterEach(() => { - axios.defaults.maxRedirects = saved.maxRedirects; - axios.defaults.adapter = saved.adapter; + Object.assign(axios.defaults, saved); + }); + + // An application transport that records its use. + const recordingTransport = () => { + const transport = { + calls: 0, + request: (options, callback) => { + transport.calls += 1; + return http.request(options, callback); + }, + }; + return transport; + }; + + it('an application transport default is not used for an API request', async () => { + const transport = recordingTransport(); + axios.defaults.transport = transport; + api.handler = respond(307, { Location: `${other.origin}/moved` }); + + const err = await catchError(REQUESTS[0].call(skClient('axios', api))); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(307); + expect(other.requests).to.deep.equal([]); + expect(transport.calls).to.equal(0); + }); + + it('an application transport default is not used for the OAuth token request', async () => { + const transport = recordingTransport(); + axios.defaults.transport = transport; + api.handler = respond(307, { Location: `${other.origin}/moved` }); + other.handler = json(200, TOKEN); + const cko = oauthClient('axios', api); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ status: 307 }); + expect(other.requests).to.deep.equal([]); + expect(cko.config.access.token).to.equal(undefined); + expect(transport.calls).to.equal(0); + }); + + it('an application transport default is not used for the file request', async () => { + const transport = recordingTransport(); + axios.defaults.transport = transport; + api.handler = (req, res) => + req.url === '/reports/rpt_1/files/file_1' + ? respond(302, { Location: `${other.origin}/file.csv` })(req, res) + : respond(200, {}, 'again')(req, res); + other.handler = respond(302, { Location: `${api.origin}/again` }); + + const err = await catchError(skClient('axios', api).reports.getReportFile('rpt_1', 'file_1')); + + expect(err).to.be.instanceOf(ApiError); + expect(err.http_code).to.equal(302); + expect(api.requests.map((r) => r.url)).to.deep.equal(['/reports/rpt_1/files/file_1']); + expect(other.requests).to.have.length(1); + expect(transport.calls).to.equal(0); + }); + + it('strict JSON parsing defaults: a token 200 that is not JSON gives AuthenticationError with the status only', async () => { + axios.defaults.transitional = { ...axios.defaults.transitional, silentJSONParsing: false }; + axios.defaults.responseType = 'json'; + api.handler = respond(200, { 'Content-Type': 'text/html' }, 'token_body_value'); + const cko = oauthClient('axios', api); + + const err = await catchError(cko.payments.get('pay_123')); + + expect(err).to.be.instanceOf(AuthenticationError); + expect(err.body).to.deep.equal({ status: 200 }); + expect(api.requests.map((r) => r.url)).to.deep.equal(['/connect/token']); + expectNoCredentials(err, 'token_body_value'); + }); + + it('a params default is not added to the file location', async () => { + axios.defaults.params = { application: 'application_param' }; + api.handler = respond(302, { Location: `${other.origin}/file.csv?X-Signature=abc` }); + other.handler = respond(200, { 'Content-Type': 'text/csv' }, 'a\n'); + + await skClient('axios', api).reports.getReportFile('rpt_1', 'file_1'); + + expect(other.requests.map((r) => r.url)).to.deep.equal(['/file.csv?X-Signature=abc']); }); it('a maxRedirects default does not make a 307 followed', async () => {