diff --git a/public/assets/js/ajax.utils.js b/public/assets/js/ajax.utils.js index 70bc53f38..a745e2635 100644 --- a/public/assets/js/ajax.utils.js +++ b/public/assets/js/ajax.utils.js @@ -1,3 +1,16 @@ +// Send the CSRF token on every same-origin state-changing jQuery request. +// The token is never attached to cross-origin requests. +if (window.jQuery) { + jQuery.ajaxPrefilter(function (options, originalOptions, jqXHR) { + var method = (options.type || options.method || 'GET').toUpperCase(); + if (options.crossDomain || method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return; + var meta = document.head.querySelector('meta[name="csrf-token"]'); + if (meta && meta.content) { + jqXHR.setRequestHeader('X-CSRF-TOKEN', meta.content); + } + }); +} + function ajaxError(jqXHR, textStatus, errorThrown){ var HTTP_status = jqXHR.status; if(HTTP_status != 200){ diff --git a/resources/js/admin/edit_user/actions.js b/resources/js/admin/edit_user/actions.js index ca278dcd5..f023fee9a 100644 --- a/resources/js/admin/edit_user/actions.js +++ b/resources/js/admin/edit_user/actions.js @@ -76,7 +76,7 @@ export const save = async (entity, pic, token) => { return putRawRequest(window.SAVE_PROFILE_ENDPOINT)(normalizeEntity(entity), {} ,{'X-CSRF-TOKEN': token}) .then((res) => { if (pic) { - return putFile(window.SAVE_PIC_ENDPOINT)(pic, 'pic', {'X-CSRF-TOKEN': token}); + return putFile(window.SAVE_PIC_ENDPOINT)(pic, 'pic', {}, {'X-CSRF-TOKEN': token}); } return Promise.resolve() } diff --git a/resources/js/admin/edit_user/edit_user.js b/resources/js/admin/edit_user/edit_user.js index ca6adf34a..42861aed6 100644 --- a/resources/js/admin/edit_user/edit_user.js +++ b/resources/js/admin/edit_user/edit_user.js @@ -99,7 +99,7 @@ const EditUserPage = ({ confirmButtonText: 'Yes, revoke it!' }).then((result) => { if (result.value) { - revokeToken(value, 'access-token').then(() => { + revokeToken(value, 'access-token', csrfToken).then(() => { Swal(`Access token revoked`, `The access token has been revoked successfully`, "success"); setAccessTokensListRefresh(!accessTokensListRefresh); }).catch((err) => { diff --git a/resources/js/oauth2/profile/clients/actions.js b/resources/js/oauth2/profile/clients/actions.js index 43e1714eb..ecbda49dc 100644 --- a/resources/js/oauth2/profile/clients/actions.js +++ b/resources/js/oauth2/profile/clients/actions.js @@ -55,7 +55,7 @@ export const getClients = async (page = 1, order = 'updated_at', orderDir = 'des } export const addClient = async (entity, token) => { - return postRawRequest(window.ADD_CLIENT_ENDPOINT)(normalizeEntity(entity), {}, {'X-CSRF-TOKEN': token}); + return postRawRequest(window.ADD_CLIENT_ENDPOINT)(normalizeEntity(entity), {'X-CSRF-TOKEN': token}); } export const deleteClient = async (id, token) => { diff --git a/resources/js/oauth2/profile/edit_client/actions.js b/resources/js/oauth2/profile/edit_client/actions.js index 94de1dbef..12150f4aa 100644 --- a/resources/js/oauth2/profile/edit_client/actions.js +++ b/resources/js/oauth2/profile/edit_client/actions.js @@ -11,7 +11,7 @@ export const ClientEntitySection = { export const regenerateClientSecret = async (clientId) => { return putRawRequest(window.REGENERATE_CLIENT_SECRET_ENDPOINT - .replace('@client_id', clientId))({'X-CSRF-TOKEN': window.CSFR_TOKEN}); + .replace('@client_id', clientId))(null, {}, {'X-CSRF-TOKEN': window.CSFR_TOKEN}); } export const getAccessTokens = async (clientId, page = 1, perPage = PAGE_SIZE, order = 'created_at', orderDir = 'desc', filters = {}) => { @@ -72,7 +72,7 @@ export const removeScope = async (clientId, scopeId) => { export const addPublicKey = async (clientId, entity) => { return postRawRequest(window.ADD_PUBLIC_KEY_ENDPOINT - .replace('@client_id', clientId))(normalizeEntity(entity, ClientEntitySection.PUBLIC_KEYS), {}, {'X-CSRF-TOKEN': window.CSFR_TOKEN}); + .replace('@client_id', clientId))(normalizeEntity(entity, ClientEntitySection.PUBLIC_KEYS), {'X-CSRF-TOKEN': window.CSFR_TOKEN}); } export const getPublicKeys = async (clientId, page = 1, perPage = PAGE_SIZE) => { diff --git a/resources/js/profile/actions.js b/resources/js/profile/actions.js index c1c6c2f08..34bcfeb13 100644 --- a/resources/js/profile/actions.js +++ b/resources/js/profile/actions.js @@ -68,23 +68,23 @@ export const getUserAccessTokens = async (page = 1, order = 'created_at', orderD export const save = async (entity, pic, token) => { - return putRawRequest(window.SAVE_PROFILE_ENDPOINT)(normalizeEntity(entity), {'X-CSRF-TOKEN': token}).then(() => { + return putRawRequest(window.SAVE_PROFILE_ENDPOINT)(normalizeEntity(entity), {}, {'X-CSRF-TOKEN': token}).then(() => { if (pic) { - return putFile(window.SAVE_PIC_ENDPOINT)(pic, 'pic', {'X-CSRF-TOKEN': token}); + return putFile(window.SAVE_PIC_ENDPOINT)(pic, 'pic', {}, {'X-CSRF-TOKEN': token}); } return Promise.resolve(); }); } -export const revokeToken = async (value, hint) => { +export const revokeToken = async (value, hint, token) => { return deleteRawRequest(window.REVOKE_ACCESS_TOKENS_ENDPOINT .replace('@value', value) .replace('%40hint', hint) - )({'X-CSRF-TOKEN': window.CSFR_TOKEN}); + )({'X-CSRF-TOKEN': token}); } -export const revokeAllTokens = async () => { - return deleteRawRequest(window.REVOKE_ALL_TOKENS_ENDPOINT)({'X-CSRF-TOKEN': window.CSFR_TOKEN}); +export const revokeAllTokens = async (token) => { + return deleteRawRequest(window.REVOKE_ALL_TOKENS_ENDPOINT)({'X-CSRF-TOKEN': token}); } const normalizeEntity = (entity) => { diff --git a/resources/js/profile/profile.js b/resources/js/profile/profile.js index a2d2be411..383796efc 100644 --- a/resources/js/profile/profile.js +++ b/resources/js/profile/profile.js @@ -97,7 +97,7 @@ const ProfilePage = ({ confirmButtonText: 'Yes, sign out all devices!' }).then((result) => { if (result.value) { - revokeAllTokens().then(() => { + revokeAllTokens(csrfToken).then(() => { Swal('Signed out', 'All other sessions and tokens have been revoked.', 'success'); setAccessTokensListRefresh(!accessTokensListRefresh); }).catch((err) => { @@ -117,7 +117,7 @@ const ProfilePage = ({ confirmButtonText: 'Yes, revoke it!' }).then((result) => { if (result.value) { - revokeToken(value, 'access-token').then(() => { + revokeToken(value, 'access-token', csrfToken).then(() => { Swal(`Access token revoked`, `The access token has been revoked successfully`, "success"); setAccessTokensListRefresh(!accessTokensListRefresh); }).catch((err) => { diff --git a/resources/views/admin/server-config.blade.php b/resources/views/admin/server-config.blade.php index 9aab097af..349ce00b8 100644 --- a/resources/views/admin/server-config.blade.php +++ b/resources/views/admin/server-config.blade.php @@ -9,6 +9,7 @@
+ @csrf General Configuration
diff --git a/resources/views/layout.blade.php b/resources/views/layout.blade.php index 6bdac12c0..3b0bc8c48 100644 --- a/resources/views/layout.blade.php +++ b/resources/views/layout.blade.php @@ -5,6 +5,7 @@ + @yield('meta') {!! style_to('assets/css/index.css') !!} {!! style_to('assets/css/main.css') !!} diff --git a/tests/js/csrf_actions.test.js b/tests/js/csrf_actions.test.js new file mode 100644 index 000000000..37b099dfa --- /dev/null +++ b/tests/js/csrf_actions.test.js @@ -0,0 +1,117 @@ +/** + * @jest-environment jsdom + */ + +// Every state-changing call of the admin / profile React pages must send the CSRF token as the +// X-CSRF-TOKEN *header*: Laravel's VerifyCsrfToken only reads the `_token` input or that header, +// so a token passed as a JSON body field, a query parameter or a multipart field answers 419. +// superagent is mocked so the test sees exactly what each action puts on the wire, independently +// of the argument order of the base_actions helpers. + +const mockRequests = []; + +jest.mock('superagent', () => { + const build = (method) => (url) => { + const req = {method, url: String(url), headers: {}, body: undefined, fields: {}, files: {}}; + mockRequests.push(req); + const chain = { + set: (h) => { Object.assign(req.headers, h); return chain; }, + send: (b) => { req.body = b; return chain; }, + field: (k, v) => { req.fields[k] = v; return chain; }, + attach: (k, f) => { req.files[k] = f; return chain; }, + timeout: () => Promise.resolve({body: {}}), + }; + return chain; + }; + return {get: build('GET'), post: build('POST'), put: build('PUT'), delete: build('DELETE')}; +}); + +import * as profile from '../../resources/js/profile/actions'; +import * as editUser from '../../resources/js/admin/edit_user/actions'; +import * as clients from '../../resources/js/oauth2/profile/clients/actions'; +import * as editClient from '../../resources/js/oauth2/profile/edit_client/actions'; + +const TOKEN = 'tok-123'; +const PIC = new Blob(['x'], {type: 'image/png'}); + +const profileEntity = () => ({first_name: 'a'}); +const adminUserEntity = () => ({first_name: 'a', post_code: 1824, groups: ['1']}); + +beforeAll(() => { + Object.assign(window, { + CSFR_TOKEN: TOKEN, + SAVE_PROFILE_ENDPOINT: '/admin/api/v1/users/me', + SAVE_PIC_ENDPOINT: '/admin/api/v1/users/me/pic', + REVOKE_ACCESS_TOKENS_ENDPOINT: '/admin/api/v1/users/me/tokens/@value?hint=%40hint', + REVOKE_ALL_TOKENS_ENDPOINT: '/admin/api/v1/users/me/tokens', + ADD_CLIENT_ENDPOINT: '/admin/api/v1/clients', + DELETE_CLIENT_ENDPOINT: '/admin/api/v1/clients/@id', + ACTIVATE_CLIENT_ENDPOINT: '/admin/api/v1/clients/@id/active', + DEACTIVATE_CLIENT_ENDPOINT: '/admin/api/v1/clients/@id/active', + REGENERATE_CLIENT_SECRET_ENDPOINT: '/admin/api/v1/clients/@client_id/secret', + REVOKE_TOKENS_ENDPOINT: '/admin/api/v1/clients/@client_id/token/@value/@hint', + UPDATE_CLIENT_DATA_ENDPOINT: '/admin/api/v1/clients/@client_id', + ADD_CLIENT_SCOPE_ENDPOINT: '/admin/api/v1/clients/@client_id/scopes/@scope_id', + REMOVE_CLIENT_SCOPE_ENDPOINT: '/admin/api/v1/clients/@client_id/scopes/@scope_id', + ADD_PUBLIC_KEY_ENDPOINT: '/admin/api/v1/clients/@client_id/public_keys', + REMOVE_PUBLIC_KEY_ENDPOINT: '/admin/api/v1/clients/@client_id/public_keys/@public_key_id', + CLIENT_TYPES: {}, APP_TYPES: {}, + }); +}); + +beforeEach(() => { mockRequests.length = 0; }); + +const CASES = [ + ['profile: save with picture', () => profile.save(profileEntity(), PIC, TOKEN), 2], + ['profile: revoke token', () => profile.revokeToken('v', 'access_token', TOKEN), 1], + ['profile: revoke all tokens', () => profile.revokeAllTokens(TOKEN), 1], + ['admin edit user: save with picture', () => editUser.save(adminUserEntity(), PIC, TOKEN), 2], + ['clients: add', () => clients.addClient({app_name: 'x'}, TOKEN), 1], + ['clients: delete', () => clients.deleteClient(1, TOKEN), 1], + ['clients: activate', () => clients.activateClient(1, TOKEN), 1], + ['clients: deactivate', () => clients.deactivateClient(1, TOKEN), 1], + ['edit client: regenerate secret', () => editClient.regenerateClientSecret(1), 1], + ['edit client: revoke token', () => editClient.revokeToken(1, 'v', 'access_token'), 1], + ['edit client: update data', () => editClient.updateClientData(1, {app_name: 'x'}, editClient.ClientEntitySection.OAUTH), 1], + ['edit client: add scope', () => editClient.addScope(1, 2), 1], + ['edit client: remove scope', () => editClient.removeScope(1, 2), 1], + ['edit client: add public key', () => editClient.addPublicKey(1, {kid: 'k'}), 1], + ['edit client: remove public key', () => editClient.removePublicKey(1, 2), 1], +]; + +// admin/edit-user.blade.php does not set window.CSFR_TOKEN, yet that page calls profile's revokeToken: +// the profile actions must take the token from the caller, never from that global. +describe('profile token revocation without window.CSFR_TOKEN (admin edit-user page)', () => { + let saved; + beforeEach(() => { saved = window.CSFR_TOKEN; delete window.CSFR_TOKEN; }); + afterEach(() => { window.CSFR_TOKEN = saved; }); + + it.each([ + ['revokeToken', () => profile.revokeToken('v', 'access-token', TOKEN)], + ['revokeAllTokens', () => profile.revokeAllTokens(TOKEN)], + ])('%s sends the token it is given', async (name, run) => { + await run(); + expect(mockRequests).toHaveLength(1); + expect(mockRequests[0].headers['X-CSRF-TOKEN']).toBe(TOKEN); + }); +}); + +describe.each(CASES)('%s', (name, run, expectedRequests) => { + it('sends X-CSRF-TOKEN as a header on every request', async () => { + await run(); + expect(mockRequests).toHaveLength(expectedRequests); + for (const req of mockRequests) { + expect(req.method).not.toBe('GET'); + expect(req.headers['X-CSRF-TOKEN']).toBe(TOKEN); + } + }); + + it('does not leak the token into the body, query string or multipart fields', async () => { + await run(); + for (const req of mockRequests) { + expect(req.url).not.toContain(TOKEN); + expect(JSON.stringify(req.body ?? null)).not.toContain(TOKEN); + expect(req.fields).not.toHaveProperty('X-CSRF-TOKEN'); + } + }); +}); diff --git a/tests/js/csrf_token.test.js b/tests/js/csrf_token.test.js new file mode 100644 index 000000000..afdaa0548 --- /dev/null +++ b/tests/js/csrf_token.test.js @@ -0,0 +1,65 @@ +/** + * @jest-environment jsdom + */ +import $ from 'jquery'; + +jest.mock('../../resources/js/base_actions', () => ({ + putRawRequest: jest.fn(() => jest.fn(() => Promise.resolve())), + putFile: jest.fn(() => jest.fn(() => Promise.resolve())), + deleteRawRequest: jest.fn(() => jest.fn(() => Promise.resolve())), + getRawRequest: jest.fn(), +})); + +import { putRawRequest, putFile } from '../../resources/js/base_actions'; +import { save } from '../../resources/js/profile/actions'; + +const TOKEN = 'tok-123'; + +describe('profile save', () => { + it('sends the CSRF token as a header, not as a query parameter', async () => { + const put = jest.fn(() => Promise.resolve()); + putRawRequest.mockReturnValue(put); + putFile.mockReturnValue(jest.fn(() => Promise.resolve())); + + await save({first_name: 'a'}, null, TOKEN); + + // putRawRequest(endpoint)(payload, params, headers) + const [, params, headers] = put.mock.calls[0]; + expect(params).toEqual({}); + expect(headers).toEqual({'X-CSRF-TOKEN': TOKEN}); + }); +}); + +describe('jQuery CSRF prefilter (public/assets/js/ajax.utils.js)', () => { + let requests; + + beforeEach(() => { + jest.resetModules(); + document.head.innerHTML = ``; + window.jQuery = window.$ = $; + requests = []; + $.ajaxTransport('+*', (options) => ({ + send: (headers, complete) => { + requests.push({type: options.type, url: options.url, headers: {...headers}}); + complete(200, 'OK', {text: '{}'}); + }, + abort: () => {}, + })); + require('../../public/assets/js/ajax.utils.js'); + }); + + it.each(['POST', 'PUT', 'DELETE'])('adds X-CSRF-TOKEN to same-origin %s', async (type) => { + await $.ajax({url: '/admin/api/v1/x', type}); + expect(requests[0].headers['X-CSRF-TOKEN']).toBe(TOKEN); + }); + + it('does not add the token to GET requests', async () => { + await $.ajax({url: '/admin/api/v1/x', type: 'GET'}); + expect(requests[0].headers['X-CSRF-TOKEN']).toBeUndefined(); + }); + + it('never leaks the token to another origin', async () => { + await $.ajax({url: 'https://evil.example/x', type: 'POST', crossDomain: true}); + expect(requests[0].headers['X-CSRF-TOKEN']).toBeUndefined(); + }); +});