From 78982cb56a21be9d7f483bef3c803faf89f50639 Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Wed, 2 Dec 2026 17:18:59 +0100 Subject: [PATCH 1/2] fix(client): security hardening Security hardening of the request headers, on fetch and on axios. updatePaymentInstrumentDetails takes the ETag as an explicit ifMatch parameter, sent as the If-Match header and not sent when undefined or null. --- src/api/platforms/payment-instruments.js | 19 +- src/api/platforms/platforms.js | 5 +- src/services/http.js | 52 ++- src/services/utils.js | 18 + test/http/requestHeaders.js | 326 ++++++++++++++++++ .../payment-instruments-unit.js | 3 +- .../api/platforms/payment-instruments.d.ts | 14 +- types/dist/api/platforms/platforms.d.ts | 2 +- 8 files changed, 415 insertions(+), 24 deletions(-) create mode 100644 test/http/requestHeaders.js diff --git a/src/api/platforms/payment-instruments.js b/src/api/platforms/payment-instruments.js index 962c5254..199bedcd 100644 --- a/src/api/platforms/payment-instruments.js +++ b/src/api/platforms/payment-instruments.js @@ -48,27 +48,34 @@ export default class PaymentInstruments { * * The API reads the ETag only from the If-Match HTTP header: without it the update fails with * 428 Precondition Required, and with a stale one with 412 Precondition Failed. Pass the ETag - * from the ETag header of the GET in body.headers['if-match']; every key of body.headers is - * sent as an HTTP header. - * - body.label: [Optional] string, 1 to 50 characters. + * from the ETag header of the GET in ifMatch. The body is sent as it is, as JSON; none of its + * keys is sent as an HTTP header. + * - body.label: [Optional] string, 1 to 50 characters. A reference that you can use to identify + * the payment instrument. * - body.default: [Optional] boolean. Deprecated by the API: for scheduled payouts the first * payment instrument created for a currency is used; to change it, update the payout * schedule. - * - body.headers: { 'if-match': etag }, [Required] by the API. * * @param {string} entityId Sub-entity id. * @param {string} id Payment instrument's id. * @param {Object} body The update, as described above. + * @param {string} ifMatch The ETag of the payment instrument (e.g. Y3Y9MCZydj0w), sent as the + * If-Match header; [Required] by the API. Not sent when undefined or null. * @return {Promise} A promise to the Platforms response: the instrument id and _links. * @throws {ValueError} If entityId or id is undefined, null, empty, "." or "..", or contains * "/", "\", an ASCII control character or an unpaired surrogate. */ - async updatePaymentInstrumentDetails(entityId, id, body) { + async updatePaymentInstrumentDetails(entityId, id, body, ifMatch) { try { + const config = + ifMatch === undefined || ifMatch === null + ? this.config + : { ...this.config, headers: { ...(this.config.headers || {}), 'If-Match': ifMatch } }; + const response = await patch( this.config.httpClient, `${this.config.host}/${ACCOUNTS_PATH}/${ENTITIES_PATH}/${encodePathSegment(entityId, 'entityId')}/${PAYMENT_INSTRUMENTS_PATH}/${encodePathSegment(id, 'id')}`, - this.config, + config, this.config.sk, body ); diff --git a/src/api/platforms/platforms.js b/src/api/platforms/platforms.js index b42849de..641e6186 100644 --- a/src/api/platforms/platforms.js +++ b/src/api/platforms/platforms.js @@ -70,8 +70,9 @@ export default class Platforms { return this.paymentInstruments.getPaymentInstrumentDetails(entityId, id); } - async updatePaymentInstrumentDetails(entityId, id, body) { - return this.paymentInstruments.updatePaymentInstrumentDetails(entityId, id, body); + /** Update a payment instrument's details, with its ETag in ifMatch. See PaymentInstruments.updatePaymentInstrumentDetails. */ + async updatePaymentInstrumentDetails(entityId, id, body, ifMatch) { + return this.paymentInstruments.updatePaymentInstrumentDetails(entityId, id, body, ifMatch); } async createPaymentInstrument(id, body) { diff --git a/src/services/http.js b/src/services/http.js index 11b654ab..9baf290e 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 { setHeader } from './utils.js'; import { ApiError, ApiTimeout, AuthenticationError, determineError } from './errors.js'; import pjson from '../../package.json' with { type: 'json' }; @@ -55,27 +56,60 @@ function buildJsonResponse(response) { }); } +// axios reads `common` and per-method keys of the request headers as header groups and merges +// them with the headers (axios lib/core/Axios.js, lib/core/methodList.js). +const AXIOS_HEADER_GROUPS = ['common', 'get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'purge', 'link', 'unlink', 'query']; + +// Replaces every object under a header group key (in any case, as axios merges the keys) with a +// plain copy without the given names (compared as axios compares them), read once, so no group +// can change the headers the SDK sets, whatever kind of object it is. +const withoutNamesInGroups = (headers, names) => { + Object.keys(headers) + .filter((key) => AXIOS_HEADER_GROUPS.includes(key.toLowerCase())) + .filter((key) => headers[key] !== null && typeof headers[key] === 'object') + .forEach((key) => { + headers[key] = Object.fromEntries( + Object.entries(headers[key]).filter(([name]) => !names.includes(name.trim().toLowerCase())) + ); + }); + return headers; +}; + +/** + * Headers of an API request: the configured headers (options.headers and the ones SDK methods + * add from their parameters) and the SDK's own. The request body is never read for headers: a + * body is only ever sent as the body. + * + * @param {Object} config SDK configuration. + * @param {Object} [request] Request body; only the multipart form the SDK builds for file uploads + * (config.formData) adds its content type. + * @param {string} authHeader Authorization value. + * @param {string} [idempotencyKey] Cko-Idempotency-Key value. + * @return {Object} The headers. Authorization, Content-Type (multipart and text/csv included) and + * Cko-Idempotency-Key, when the SDK sets them, are the SDK's values whatever the configured + * headers hold; a configured Cko-Idempotency-Key is kept when no idempotency key is passed. + */ function getRequestHeaders(config, request, authHeader, idempotencyKey) { - let headers = { + const headers = { ...config.headers, - Authorization: authHeader, 'Cache-Control': 'no-cache', pragma: 'no-cache', 'user-agent': `checkout-sdk-node/${pjson.version}`, }; - - if (request && request.headers) { - headers = { ...headers, ...request.headers }; - } + withoutNamesInGroups( + headers, + idempotencyKey === undefined ? ['authorization', 'content-type'] : ['authorization', 'content-type', 'cko-idempotency-key'] + ); + setHeader(headers, 'Authorization', authHeader); if (!config.formData) { - headers['Content-Type'] = config.csv ? 'text/csv' : 'application/json'; + setHeader(headers, 'Content-Type', config.csv ? 'text/csv' : 'application/json'); } else if (request && typeof request.getHeaders === 'function') { - headers = { ...headers, ...request.getHeaders() }; + Object.entries(request.getHeaders()).forEach(([name, value]) => setHeader(headers, name, value)); } if (idempotencyKey !== undefined) { - headers['Cko-Idempotency-Key'] = idempotencyKey; + setHeader(headers, 'Cko-Idempotency-Key', idempotencyKey); } return headers; diff --git a/src/services/utils.js b/src/services/utils.js index 535b3217..33974289 100644 --- a/src/services/utils.js +++ b/src/services/utils.js @@ -69,3 +69,21 @@ export const encodePathSegment = (value, name) => { return encodeURIComponent(segment); }; + +/** + * Set a header so that it is the only one of its name: another configured header with the same + * name, as HTTP clients compare names, is removed first. + * + * @param {Object} headers Plain object of headers, changed in place. + * @param {string} name The header name, in the case to send. + * @param {*} value The header value. + * @return {Object} The same headers object. + */ +export const setHeader = (headers, name, value) => { + const lowerName = name.toLowerCase(); + Object.keys(headers) + .filter((key) => key.trim().toLowerCase() === lowerName) + .forEach((key) => delete headers[key]); + headers[name] = value; + return headers; +}; diff --git a/test/http/requestHeaders.js b/test/http/requestHeaders.js new file mode 100644 index 00000000..5be46c02 --- /dev/null +++ b/test/http/requestHeaders.js @@ -0,0 +1,326 @@ +import { Checkout } from '../../src/index.js'; +import { ApiError } from '../../src/services/errors.js'; +import { expect } from 'chai'; +import nock from 'nock'; +import { AxiosHeaders } from 'axios'; +import vm from 'vm'; + +const SK = 'sk_test_0b9b5db6-f223-49d0-b68f-f6643dd4f808'; +const API = 'https://123456789.api.sandbox.checkout.com'; +const ACCESS = 'https://123456789.access.sandbox.checkout.com'; +const ENTITY = 'ent_wxglze3wwywujg4nna5fb7ldli'; +const INSTRUMENT = 'ppi_qn4nis4k3ykpzzu7cvtuvhqqga'; +const INSTRUMENT_PATH = `/accounts/entities/${ENTITY}/payment-instruments/${INSTRUMENT}`; + +const payment = (extra) => ({ + source: { type: 'token', token: 'tok_pmjyslgaam4uzmvaiwqyhovvsy' }, + amount: 100, + currency: 'USD', + ...extra, +}); + +// Records the headers and the body of the next request to `path`. +const capture = (method, path, reply = { id: 'pay_1' }) => { + const seen = {}; + nock(API) + .intercept(path, method) + .reply(function (_uri, body) { + seen.headers = this.req.headers; + seen.body = body; + return [200, reply]; + }); + return seen; +}; + +const capturePayment = () => capture('POST', '/payments'); +const capturePatch = () => capture('PATCH', INSTRUMENT_PATH, { id: INSTRUMENT }); + +['fetch', 'axios'].forEach((httpClient) => { + const clientOptions = httpClient === 'axios' ? { httpClient: 'axios' } : {}; + const client = (options = {}) => new Checkout(SK, { subdomain: '123456789', ...clientOptions, ...options }); + + describe(`Request headers (${httpClient})`, () => { + afterEach(() => nock.cleanAll()); + + it('sends the SDK and configured headers only, for a body with a headers field', async () => { + const seen = capturePayment(); + + await client().payments.request( + payment({ headers: { Authorization: 'Bearer other', 'X-Test': 'value' } }) + ); + + expect(seen.headers.authorization).to.equal(SK); + expect(seen.headers).to.not.have.property('x-test'); + }); + + ['authorization', 'AUTHORIZATION', 'aUtHoRiZaTiOn'].forEach((name, index) => { + it(`sends the SDK Authorization for a body headers key in any case (${index + 1})`, async () => { + const seen = capturePayment(); + + await client().payments.request(payment({ headers: { [name]: 'Bearer other' } })); + + expect(seen.headers.authorization).to.equal(SK); + }); + }); + + it('sends the SDK Content-Type and Cko-Idempotency-Key whatever the body holds', async () => { + const seen = capturePayment(); + + await client().payments.request( + payment({ headers: { 'content-type': 'text/plain', 'cko-idempotency-key': 'other' } }), + 'idem-1' + ); + + expect(seen.headers['content-type']).to.equal('application/json'); + expect(seen.headers['cko-idempotency-key']).to.equal('idem-1'); + }); + + it('still sends the body whole, headers object included, as JSON', async () => { + const seen = capturePayment(); + + await client().payments.request(payment({ reference: 'ORD-1', headers: { 'X-Test': 'value' } })); + + expect(seen.body.reference).to.equal('ORD-1'); + expect(seen.body.headers).to.deep.equal({ 'X-Test': 'value' }); + }); + + [ + { 'X-Test': 'v\r\nX-Other: value' }, + 'ab', + ['a', 'b'], + ].forEach((headers, index) => { + it(`sends the request with the SDK headers only for any body headers field (${index + 1})`, async () => { + const seen = capturePayment(); + + await client().payments.request(payment({ headers })); + + expect(seen.headers.authorization).to.equal(SK); + expect(Object.keys(seen.headers).filter((name) => /^(x-test|x-other|0|1)$/.test(name))).to.deep.equal([]); + }); + }); + }); + + describe(`SDK and configured headers (${httpClient})`, () => { + afterEach(() => nock.cleanAll()); + + it('sends one Authorization, Content-Type and Cko-Idempotency-Key, the SDK values', async () => { + const seen = capturePayment(); + + await client({ + headers: { + authorization: 'Bearer configured', + 'CONTENT-TYPE': 'text/plain', + 'cko-idempotency-key': 'configured', + 'x-merchant': 'kept', + }, + }).payments.request(payment(), 'idem-2'); + + expect(seen.headers.authorization).to.equal(SK); + expect(seen.headers['content-type']).to.equal('application/json'); + expect(seen.headers['cko-idempotency-key']).to.equal('idem-2'); + expect(seen.headers['x-merchant']).to.equal('kept'); + }); + + [' Authorization', 'Authorization\t', 'Authorization\u00a0'].forEach((name, index) => { + it(`sends the SDK Authorization and Cko-Idempotency-Key for configured names written differently (${index + 1})`, async () => { + const seen = capturePayment(); + + await client({ + headers: { [name]: 'Bearer configured', [name.replace('Authorization', 'Cko-Idempotency-Key')]: 'configured' }, + }).payments.request(payment(), 'idem-3'); + + expect(seen.headers.authorization).to.equal(SK); + expect(seen.headers['cko-idempotency-key']).to.equal('idem-3'); + }); + }); + + [ + () => ({ common: { ' Authorization': 'Bearer configured' }, post: { 'Cko-Idempotency-Key ': 'configured' } }), + () => ({ common: { Authorization: false, 'Content-Type': false, 'Cko-Idempotency-Key': false } }), + () => ({ common: new AxiosHeaders({ Authorization: false, 'Content-Type': false, 'Cko-Idempotency-Key': false }) }), + () => + vm.runInNewContext( + "({ common: { Authorization: false, 'Content-Type': false }, post: { 'Cko-Idempotency-Key': false } })" + ), + () => ({ Common: { Authorization: false, 'Content-Type': false }, POST: { 'Cko-Idempotency-Key': false } }), + () => { + class Group extends AxiosHeaders { + get [Symbol.toStringTag]() { + return 'Group'; + } + } + return { Post: new Group({ Authorization: false, 'Content-Type': false, 'Cko-Idempotency-Key': false }) }; + }, + () => { + let reads = 0; + return { + common: new Proxy( + { Authorization: false, 'Content-Type': false, 'Cko-Idempotency-Key': false }, + { getPrototypeOf: () => (reads++ === 0 ? Array.prototype : Object.prototype) } + ), + }; + }, + ].forEach((headers, index) => { + it(`sends the SDK Authorization, Content-Type and Cko-Idempotency-Key for configured header groups (${index + 1})`, async () => { + const seen = capturePayment(); + + await client({ headers: headers() }).payments.request(payment(), 'idem-4'); + + expect(seen.headers.authorization).to.equal(SK); + expect(seen.headers['content-type']).to.equal('application/json'); + expect(seen.headers['cko-idempotency-key']).to.equal('idem-4'); + }); + }); + + it('keeps a configured header group without the SDK headers unchanged', async () => { + const seen = capturePayment(); + const headers = { common: { 'X-Group': 'kept', authorization: 'Bearer configured' } }; + + await client({ headers }).payments.request(payment()); + + expect(seen.headers.authorization).to.equal(SK); + expect(headers.common).to.deep.equal({ 'X-Group': 'kept', authorization: 'Bearer configured' }); + }); + + it('keeps a configured Cko-Idempotency-Key when no idempotency key is passed', async () => { + const seen = capturePayment(); + + await client({ headers: { 'cko-idempotency-key': 'configured' } }).payments.request(payment()); + + expect(seen.headers['cko-idempotency-key']).to.equal('configured'); + }); + + it('sends the multipart content type of a file upload whatever the configured Content-Type', async () => { + const seen = capture('POST', '/files', { id: 'file_1' }); + + await client({ headers: { 'Content-Type': 'application/json' } }).files.upload({ + file: 'https://example.com/evidence.pdf', + purpose: 'dispute_evidence', + }); + + expect(seen.headers['content-type']).to.match(/^multipart\/form-data; boundary=[-\w]+$/); + }); + + it('sends text/csv for a CSV download whatever the configured Content-Type', async () => { + let contentType; + nock(API) + .get('/reporting/statements/stm_1/payments/download') + .reply(function () { + contentType = this.req.headers['content-type']; + return [200, 'a,b\n1,2\n', { 'Content-Type': 'text/csv' }]; + }); + + await client({ headers: { 'content-type': 'application/json' } }).reconciliation.getStatementCsv('stm_1'); + + expect(contentType).to.equal('text/csv'); + }); + + it('sends the OAuth token as Authorization whatever the configured authorization', async () => { + nock(ACCESS).post('/connect/token').reply(201, { + access_token: '1234', + expires_in: 3600, + token_type: 'Bearer', + scope: 'gateway', + }); + const seen = capturePayment(); + + await new Checkout('client_secret_value', { + client: 'ack_vvzhoai466su3j3vbxb47ts5oe', + scope: ['gateway'], + environment: 'sandbox', + subdomain: '123456789', + headers: { AUTHORIZATION: 'Bearer configured' }, + ...clientOptions, + }).payments.request(payment()); + + expect(seen.headers.authorization).to.equal('Bearer 1234'); + }); + }); + + describe(`Payment instrument update If-Match (${httpClient})`, () => { + afterEach(() => nock.cleanAll()); + + const update = (body, ifMatch) => + client().platforms.updatePaymentInstrumentDetails(ENTITY, INSTRUMENT, body, ifMatch); + + it('sends the ifMatch parameter as the If-Match header', async () => { + const seen = capturePatch(); + + await update({ label: 'Renamed account' }, '"Y3Y9MCZydj0w"'); + + expect(seen.headers['if-match']).to.equal('"Y3Y9MCZydj0w"'); + expect(seen.body).to.deep.equal({ label: 'Renamed account' }); + }); + + it('sends body.headers only inside the body, not as the If-Match header', async () => { + const seen = capturePatch(); + const body = { label: 'Renamed account', headers: { 'if-match': '"Y3Y9MCZydj0w"' } }; + + await update(body); + + expect(seen.headers).to.not.have.property('if-match'); + expect(seen.body).to.deep.equal(body); + }); + + [undefined, null].forEach((ifMatch) => { + it(`sends no If-Match when ifMatch is ${ifMatch}`, async () => { + const seen = capturePatch(); + + await update({ label: 'Renamed account' }, ifMatch); + + expect(seen.headers).to.not.have.property('if-match'); + }); + }); + + ['a\r\nX-Other: value', 'a\nX-Other: value', 'a\u0000b', 'a\u007fb', '\u200b', 'a\u202eb', 'a\u2028b', '\uff21'].forEach( + (ifMatch, index) => { + const outcome = httpClient === 'fetch' ? 'fails with an ApiError' : 'adds no other header'; + it(`${outcome} for an ifMatch that is not a valid header value (${index + 1})`, async () => { + const seen = capturePatch(); + + if (httpClient === 'fetch') { + let error; + try { + await update({ label: 'Renamed account' }, ifMatch); + } catch (e) { + error = e; + } + expect(error).to.be.instanceOf(ApiError); + expect(seen).to.deep.equal({}); + expect(JSON.stringify({ message: error.message, body: error.body })).to.not.include(SK); + } else { + // axios drops the characters it cannot send; no other header is added. + await update({ label: 'Renamed account' }, ifMatch); + expect(seen.headers).to.not.have.property('x-other'); + expect(seen.headers.authorization).to.equal(SK); + } + }); + } + ); + + it('requests one OAuth token for two updates', async () => { + nock(ACCESS).post('/connect/token').once().reply(201, { + access_token: '1234', + expires_in: 3600, + token_type: 'Bearer', + scope: 'accounts', + }); + const first = capturePatch(); + const second = capturePatch(); + const cko = new Checkout('client_secret_value', { + client: 'ack_vvzhoai466su3j3vbxb47ts5oe', + scope: ['accounts'], + environment: 'sandbox', + subdomain: '123456789', + ...clientOptions, + }); + + await cko.platforms.updatePaymentInstrumentDetails(ENTITY, INSTRUMENT, { label: 'One' }, '"e1"'); + await cko.platforms.updatePaymentInstrumentDetails(ENTITY, INSTRUMENT, { label: 'Two' }, '"e2"'); + + expect([first.headers.authorization, second.headers.authorization]).to.deep.equal(['Bearer 1234', 'Bearer 1234']); + expect([first.headers['if-match'], second.headers['if-match']]).to.deep.equal(['"e1"', '"e2"']); + expect(nock.isDone()).to.equal(true); + }); + }); +}); diff --git a/test/platforms/payment-instruments/payment-instruments-unit.js b/test/platforms/payment-instruments/payment-instruments-unit.js index 817b2570..e9fda484 100644 --- a/test/platforms/payment-instruments/payment-instruments-unit.js +++ b/test/platforms/payment-instruments/payment-instruments-unit.js @@ -139,7 +139,8 @@ describe('Platforms - Payment Instruments', () => { const instrument = await cko.platforms.updatePaymentInstrumentDetails( 'ent_wxglze3wwywujg4nna5fb7ldli', 'ppi_qn4nis4k3ykpzzu7cvtuvhqqga', - { label: 'Renamed account', headers: { 'if-match': '"Y3Y9MCZydj0w"' } } + { label: 'Renamed account' }, + '"Y3Y9MCZydj0w"' ); expect(instrument.id).to.equal('ppi_qn4nis4k3ykpzzu7cvtuvhqqga'); diff --git a/types/dist/api/platforms/payment-instruments.d.ts b/types/dist/api/platforms/payment-instruments.d.ts index ae52a5b7..39adba53 100644 --- a/types/dist/api/platforms/payment-instruments.d.ts +++ b/types/dist/api/platforms/payment-instruments.d.ts @@ -1,12 +1,15 @@ import {config} from '../../Checkout'; -/** PATCH body (PlatformsPaymentInstrumentUpdate). headers is sent as HTTP headers, not in the body. */ +/** PATCH body (PlatformsPaymentInstrumentUpdate), sent as it is as JSON; the ETag goes in ifMatch. */ export type UpdatePaymentInstrumentRequest = { + /** [Optional] A reference that you can use to identify the payment instrument; 1 to 50 characters. */ label?: string; - /** Deprecated by the API. */ + /** + * [Optional] Whether the payment instrument should be set as the default payout destination. + * @deprecated Deprecated by the API: for scheduled payouts the first payment instrument created + * for a currency is used; to change it, update the payout schedule. + */ default?: boolean; - /** The ETag from the GET; the API answers 428 without it and 412 when it does not match. */ - headers?: { 'if-match': string; [key: string]: string }; [key: string]: any; }; @@ -14,7 +17,8 @@ export default class PaymentInstruments { constructor(config: config); getPaymentInstrumentDetails: (entityId: string, id: string) => Promise; - updatePaymentInstrumentDetails: (entityId: string, id: string, body: UpdatePaymentInstrumentRequest | Object) => Promise; + /** @param ifMatch The ETag from the GET, sent as the If-Match header; the API answers 428 without it and 412 when it does not match; not sent when undefined or null. */ + updatePaymentInstrumentDetails: (entityId: string, id: string, body: UpdatePaymentInstrumentRequest | Object, ifMatch: string) => Promise; createPaymentInstrument: (id: string, body: Object) => Promise; addPaymentInstrument: (id: string, body: Object) => Promise; queryPaymentInstruments: (id: string, status?: string) => Promise; diff --git a/types/dist/api/platforms/platforms.d.ts b/types/dist/api/platforms/platforms.d.ts index e6717405..06959f87 100644 --- a/types/dist/api/platforms/platforms.d.ts +++ b/types/dist/api/platforms/platforms.d.ts @@ -25,7 +25,7 @@ export default class Platforms { updateSubEntityDetails: (id: string, body: OnboardSubEntityRequest, schemaVersion?: string) => Promise; reinviteSubEntityMember: (entityId: string, userId: string, body: Object) => Promise; getPaymentInstrumentDetails: (entityId: string, id: string) => Promise; - updatePaymentInstrumentDetails: (entityId: string, id: string, body: Object) => Promise; + updatePaymentInstrumentDetails: (entityId: string, id: string, body: Object, ifMatch: string) => Promise; createPaymentInstrument: (id: string, body: Object) => Promise; addPaymentInstrument: (id: string, body: Object) => Promise; queryPaymentInstruments: (id: string, status?: string) => Promise; From c32b9688f0d394fef202e8a61dbed644deba634e Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Thu, 3 Dec 2026 14:27:53 +0100 Subject: [PATCH 2/2] fix(platforms): warn when the payment instrument ETag is in the body updatePaymentInstrumentDetails emits a runtime warning when ifMatch is not given and body.headers holds an if-match key, the form earlier versions read the ETag from. The key is still sent only inside the body. The types and the method docs describe label, default and ifMatch as in the API reference, and the header group list is exported for its test. --- src/api/platforms/payment-instruments.js | 39 +++++++---- src/services/http.js | 2 +- test/http/requestHeaders.js | 65 ++++++++++++++++++- .../api/platforms/payment-instruments.d.ts | 11 ++-- 4 files changed, 99 insertions(+), 18 deletions(-) diff --git a/src/api/platforms/payment-instruments.js b/src/api/platforms/payment-instruments.js index 199bedcd..d212d8b5 100644 --- a/src/api/platforms/payment-instruments.js +++ b/src/api/platforms/payment-instruments.js @@ -1,6 +1,6 @@ import { determineError } from '../../services/errors.js'; import { get, patch, post } from '../../services/http.js'; -import { buildQueryParams, encodePathSegment } from '../../services/utils.js'; +import { buildQueryParams, encodePathSegment, setHeader } from '../../services/utils.js'; // Path segments appended to the API base (config.host). const ACCOUNTS_PATH = 'accounts'; @@ -8,6 +8,15 @@ const ENTITIES_PATH = 'entities'; const INSTRUMENTS_PATH = 'instruments'; const PAYMENT_INSTRUMENTS_PATH = 'payment-instruments'; +// Whether a request body still carries an if-match key in body.headers, the form earlier versions +// read the ETag from; it is only detected, to warn, never sent as a header. +const hasIfMatchInBodyHeaders = (body) => + body !== null && + typeof body === 'object' && + body.headers !== null && + typeof body.headers === 'object' && + Object.keys(body.headers).some((name) => name.trim().toLowerCase() === 'if-match'); + /** * Payment instruments for sub-entities (payouts). * @@ -50,27 +59,35 @@ export default class PaymentInstruments { * 428 Precondition Required, and with a stale one with 412 Precondition Failed. Pass the ETag * from the ETag header of the GET in ifMatch. The body is sent as it is, as JSON; none of its * keys is sent as an HTTP header. - * - body.label: [Optional] string, 1 to 50 characters. A reference that you can use to identify - * the payment instrument. - * - body.default: [Optional] boolean. Deprecated by the API: for scheduled payouts the first - * payment instrument created for a currency is used; to change it, update the payout - * schedule. + * - body.label: string. A reference that you can use to identify the payment instrument. + * [Optional] max 50 characters, min 1 characters. + * - body.default: boolean. Whether the payment instrument should be set as the default payout + * destination. [Optional] Deprecated by the API: for ad-hoc payouts the payment instrument is + * given in the payout request; for scheduled payouts the first payment instrument created for + * a currency is used; to change it, update the payout schedule. * * @param {string} entityId Sub-entity id. * @param {string} id Payment instrument's id. * @param {Object} body The update, as described above. * @param {string} ifMatch The ETag of the payment instrument (e.g. Y3Y9MCZydj0w), sent as the - * If-Match header; [Required] by the API. Not sent when undefined or null. + * If-Match header; [Required] by the API: without it (undefined or null) no If-Match header is + * sent, the API answers 428, and a warning is emitted when body.headers holds an if-match. * @return {Promise} A promise to the Platforms response: the instrument id and _links. * @throws {ValueError} If entityId or id is undefined, null, empty, "." or "..", or contains * "/", "\", an ASCII control character or an unpaired surrogate. */ async updatePaymentInstrumentDetails(entityId, id, body, ifMatch) { try { - const config = - ifMatch === undefined || ifMatch === null - ? this.config - : { ...this.config, headers: { ...(this.config.headers || {}), 'If-Match': ifMatch } }; + const ifMatchGiven = ifMatch !== undefined && ifMatch !== null; + if (!ifMatchGiven && hasIfMatchInBodyHeaders(body)) { + process.emitWarning( + 'updatePaymentInstrumentDetails: body.headers is sent only inside the request body, ' + + 'not as HTTP headers. Pass the ETag in the ifMatch parameter to send the If-Match header.' + ); + } + const config = ifMatchGiven + ? { ...this.config, headers: setHeader({ ...(this.config.headers || {}) }, 'If-Match', ifMatch) } + : this.config; const response = await patch( this.config.httpClient, diff --git a/src/services/http.js b/src/services/http.js index 9baf290e..823106a6 100644 --- a/src/services/http.js +++ b/src/services/http.js @@ -58,7 +58,7 @@ function buildJsonResponse(response) { // axios reads `common` and per-method keys of the request headers as header groups and merges // them with the headers (axios lib/core/Axios.js, lib/core/methodList.js). -const AXIOS_HEADER_GROUPS = ['common', 'get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'purge', 'link', 'unlink', 'query']; +export const AXIOS_HEADER_GROUPS = ['common', 'get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'purge', 'link', 'unlink', 'query']; // Replaces every object under a header group key (in any case, as axios merges the keys) with a // plain copy without the given names (compared as axios compares them), read once, so no group diff --git a/test/http/requestHeaders.js b/test/http/requestHeaders.js index 5be46c02..fa5cf5c8 100644 --- a/test/http/requestHeaders.js +++ b/test/http/requestHeaders.js @@ -1,8 +1,10 @@ import { Checkout } from '../../src/index.js'; import { ApiError } from '../../src/services/errors.js'; +import { AXIOS_HEADER_GROUPS } from '../../src/services/http.js'; import { expect } from 'chai'; import nock from 'nock'; import { AxiosHeaders } from 'axios'; +import methodList from 'axios/unsafe/core/methodList.js'; import vm from 'vm'; const SK = 'sk_test_0b9b5db6-f223-49d0-b68f-f6643dd4f808'; @@ -252,16 +254,71 @@ const capturePatch = () => capture('PATCH', INSTRUMENT_PATH, { id: INSTRUMENT }) expect(seen.body).to.deep.equal({ label: 'Renamed account' }); }); + it('sends the ifMatch parameter as the only If-Match header whatever the configured if-match', async () => { + const seen = capturePatch(); + + await client({ headers: { 'if-match': '"stale"' } }).platforms.updatePaymentInstrumentDetails( + ENTITY, + INSTRUMENT, + { label: 'Renamed account' }, + '"Y3Y9MCZydj0w"' + ); + + expect(seen.headers['if-match']).to.equal('"Y3Y9MCZydj0w"'); + }); + it('sends body.headers only inside the body, not as the If-Match header', async () => { const seen = capturePatch(); const body = { label: 'Renamed account', headers: { 'if-match': '"Y3Y9MCZydj0w"' } }; - await update(body); + await warningsDuring(() => update(body)); expect(seen.headers).to.not.have.property('if-match'); expect(seen.body).to.deep.equal(body); }); + const warningsDuring = async (action) => { + const warnings = []; + const original = process.emitWarning; + process.emitWarning = (warning) => warnings.push(String(warning)); + try { + await action(); + } finally { + process.emitWarning = original; + } + return warnings; + }; + + [undefined, null].forEach((ifMatch) => { + it(`warns once and sends no If-Match when ifMatch is ${ifMatch} and body.headers holds an if-match`, async () => { + const seen = capturePatch(); + const body = { label: 'Renamed account', headers: { 'If-Match': '"Y3Y9MCZydj0w"' } }; + + const warnings = await warningsDuring(() => update(body, ifMatch)); + + expect(warnings).to.have.lengthOf(1); + expect(warnings[0]).to.include('ifMatch'); + expect(warnings[0]).to.not.include('Y3Y9MCZydj0w'); + expect(seen.headers).to.not.have.property('if-match'); + expect(seen.body).to.deep.equal(body); + }); + }); + + [ + [{ label: 'Renamed account' }, undefined], + [{ label: 'Renamed account', headers: { 'X-Other': 'value' } }, undefined], + [{ label: 'Renamed account', headers: 'if-match' }, undefined], + [{ label: 'Renamed account', headers: { 'if-match': '"Y3Y9MCZydj0w"' } }, '"Y3Y9MCZydj0w"'], + ].forEach(([body, ifMatch], index) => { + it(`does not warn without an if-match in body.headers or with ifMatch given (${index + 1})`, async () => { + capturePatch(); + + const warnings = await warningsDuring(() => update(body, ifMatch)); + + expect(warnings).to.deep.equal([]); + }); + }); + [undefined, null].forEach((ifMatch) => { it(`sends no If-Match when ifMatch is ${ifMatch}`, async () => { const seen = capturePatch(); @@ -324,3 +381,9 @@ const capturePatch = () => capture('PATCH', INSTRUMENT_PATH, { id: INSTRUMENT }) }); }); }); + +describe('axios header groups', () => { + it('covers every axios method header group and common', () => { + expect(AXIOS_HEADER_GROUPS).to.include.members([...methodList, 'common']); + }); +}); diff --git a/types/dist/api/platforms/payment-instruments.d.ts b/types/dist/api/platforms/payment-instruments.d.ts index 39adba53..0b14df63 100644 --- a/types/dist/api/platforms/payment-instruments.d.ts +++ b/types/dist/api/platforms/payment-instruments.d.ts @@ -2,12 +2,13 @@ import {config} from '../../Checkout'; /** PATCH body (PlatformsPaymentInstrumentUpdate), sent as it is as JSON; the ETag goes in ifMatch. */ export type UpdatePaymentInstrumentRequest = { - /** [Optional] A reference that you can use to identify the payment instrument; 1 to 50 characters. */ + /** A reference that you can use to identify the payment instrument. [Optional] max 50 characters, min 1 characters. */ label?: string; /** - * [Optional] Whether the payment instrument should be set as the default payout destination. - * @deprecated Deprecated by the API: for scheduled payouts the first payment instrument created - * for a currency is used; to change it, update the payout schedule. + * Whether the payment instrument should be set as the default payout destination. [Optional] + * @deprecated Deprecated by the API: for ad-hoc payouts the payment instrument is given in the + * payout request; for scheduled payouts the first payment instrument created for a currency is + * used; to change it, update the payout schedule. */ default?: boolean; [key: string]: any; @@ -17,7 +18,7 @@ export default class PaymentInstruments { constructor(config: config); getPaymentInstrumentDetails: (entityId: string, id: string) => Promise; - /** @param ifMatch The ETag from the GET, sent as the If-Match header; the API answers 428 without it and 412 when it does not match; not sent when undefined or null. */ + /** @param ifMatch The ETag from the GET, sent as the If-Match header; [Required] by the API, which answers 428 without it and 412 when it does not match. */ updatePaymentInstrumentDetails: (entityId: string, id: string, body: UpdatePaymentInstrumentRequest | Object, ifMatch: string) => Promise; createPaymentInstrument: (id: string, body: Object) => Promise; addPaymentInstrument: (id: string, body: Object) => Promise;