diff --git a/modules/sdk-hmac/src/hmac.ts b/modules/sdk-hmac/src/hmac.ts index d6b9941bf1..2de379b0ae 100644 --- a/modules/sdk-hmac/src/hmac.ts +++ b/modules/sdk-hmac/src/hmac.ts @@ -28,22 +28,23 @@ export function calculateHMAC(key: string | BinaryLike | KeyObject, message: str * @param statusCode Only set for HTTP responses, leave blank for requests * @param method request method * @param authVersion authentication version (2 or 3) + * @param useOriginalPath whether to use the original urlPath without parsing (default false) * @returns {string | Buffer} */ -export function calculateHMACSubject({ - urlPath, - text, - timestamp, - statusCode, - method, - authVersion, -}: CalculateHmacSubjectOptions): T { +export function calculateHMACSubject( + { urlPath, text, timestamp, statusCode, method, authVersion }: CalculateHmacSubjectOptions, + useOriginalPath = false +): T { /* Normalize legacy 'del' to 'delete' for backward compatibility */ if (method === 'del') { method = 'delete'; } - const urlDetails = urlLib.parse(urlPath); - const queryPath = urlDetails.query && urlDetails.query.length > 0 ? urlDetails.path : urlDetails.pathname; + + let queryPath: string | null = urlPath; + if (!useOriginalPath) { + const urlDetails = urlLib.parse(urlPath); + queryPath = urlDetails.query && urlDetails.query.length > 0 ? urlDetails.path : urlDetails.pathname; + } let prefixedText: string; if (statusCode !== undefined && isFinite(statusCode) && Number.isInteger(statusCode)) { diff --git a/modules/sdk-hmac/test/hmac.ts b/modules/sdk-hmac/test/hmac.ts index 6645095e57..fb2d6a009a 100644 --- a/modules/sdk-hmac/test/hmac.ts +++ b/modules/sdk-hmac/test/hmac.ts @@ -61,6 +61,35 @@ describe('HMAC Utility Functions', () => { ).to.equal(expectedSubject); }); + it('should calculate the correct subject for a request with a trailing ? when useOriginalPath is true', () => { + const expectedSubject = 'GET|1672531200000|3.0|/api/test?|body-content'; + expect( + calculateHMACSubject( + { + urlPath: '/api/test?', + text: 'body-content', + timestamp: MOCK_TIMESTAMP, + method: 'get', + authVersion: 3, + }, + true + ) + ).to.equal(expectedSubject); + }); + + it('should calculate the correct subject for a request with a trailing ? when useOriginalPath is false', () => { + const expectedSubject = 'GET|1672531200000|3.0|/api/test|body-content'; + expect( + calculateHMACSubject({ + urlPath: '/api/test?', + text: 'body-content', + timestamp: MOCK_TIMESTAMP, + method: 'get', + authVersion: 3, + }) + ).to.equal(expectedSubject); + }); + it('should include statusCode for a response', () => { const expectedSubject = 'GET|1672531200000|/api/test|200|response-body'; expect(