Skip to content

Commit

Permalink
fix(request): CHECKOUT-8092 Check if request is made from same domain
Browse files Browse the repository at this point in the history
  • Loading branch information
animesh1987 committed Mar 4, 2024
1 parent 0d28ea2 commit 7491e8a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
36 changes: 36 additions & 0 deletions src/request-sender.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,42 @@ describe('RequestSender', () => {
}));
});

it('appends xsrf token if request url matches the parent domain', () => {
const originalHostname = window.location.hostname;

Object.defineProperty(window, 'location', {
value: { hostname: 'foobar.com' },
writable: true,
});

const options = {
encodeParams: true,
headers: {
Accept: 'text/plain',
Authorization: 'Basic YWxhZGRpbjpvcGVuc2VzYW1l',
},
method: 'POST',
};

const mockFn = (key: string) => key === 'XSRF-TOKEN' ? 'abc' : undefined;
url = 'http://foobar.com/script.js?time=123';

jest.spyOn(cookie, 'get').mockImplementationOnce(mockFn as typeof cookie.get);

requestSender.sendRequest(url, options);

Object.defineProperty(window, 'location', {
value: { hostname: originalHostname },
writable: true,
});

expect(requestFactory.createRequest).toHaveBeenCalledWith(url, expect.objectContaining({
headers: expect.objectContaining({
'X-XSRF-TOKEN': 'abc',
}),
}));
});

it('does not create a HTTP request with CSRF token for asset requests even if it exists', () => {
const mockFn = (key: string) => key === 'XSRF-TOKEN' ? 'abc' : undefined;

Expand Down
10 changes: 9 additions & 1 deletion src/request-sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export default class RequestSender {

const csrfToken = this._cookie.get('XSRF-TOKEN');

if (csrfToken && defaultOptions.headers && !this._isAssetRequest(url, options)) {
if (csrfToken && defaultOptions.headers && !this._isAssetRequest(url, options) && this._isLocalRequest(url)) {
defaultOptions.headers['X-XSRF-TOKEN'] = csrfToken;
}

Expand Down Expand Up @@ -140,4 +140,12 @@ export default class RequestSender {

return /\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(url.split('?')[0]);
}

private _isLocalRequest(url: string) {
if (url.match(new RegExp('^(https?:)?\/\/' + window.location.hostname))) {
return true;
}

return !url.match(new RegExp('^(htttps?:)?\/\/'));
}
}

0 comments on commit 7491e8a

Please sign in to comment.