Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions modules/sdk-hmac/src/hmac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends string | Buffer = string>({
urlPath,
text,
timestamp,
statusCode,
method,
authVersion,
}: CalculateHmacSubjectOptions<T>): T {
export function calculateHMACSubject<T extends string | Buffer = string>(
{ urlPath, text, timestamp, statusCode, method, authVersion }: CalculateHmacSubjectOptions<T>,
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)) {
Expand Down
29 changes: 29 additions & 0 deletions modules/sdk-hmac/test/hmac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down