Skip to content
Open
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
13 changes: 13 additions & 0 deletions public/assets/js/ajax.utils.js
Original file line number Diff line number Diff line change
@@ -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){
Expand Down
2 changes: 1 addition & 1 deletion resources/js/admin/edit_user/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
2 changes: 1 addition & 1 deletion resources/js/admin/edit_user/edit_user.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
2 changes: 1 addition & 1 deletion resources/js/oauth2/profile/clients/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
4 changes: 2 additions & 2 deletions resources/js/oauth2/profile/edit_client/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}) => {
Expand Down Expand Up @@ -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) => {
Expand Down
12 changes: 6 additions & 6 deletions resources/js/profile/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
4 changes: 2 additions & 2 deletions resources/js/profile/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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) => {
Expand Down
1 change: 1 addition & 0 deletions resources/views/admin/server-config.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<div class="row">
<div class="col-md-6">
<form method="POST" id="form-server-configuration">
@csrf
<legend>General Configuration</legend>
<div class="form-group">
<label for="general-max-failed-login-attempts">MaximunFailed Login Attempts&nbsp;<span class="glyphicon glyphicon-info-sign accordion-toggle" aria-hidden="true" title="in seconds"></span></label>
Expand Down
1 change: 1 addition & 0 deletions resources/views/layout.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<base href="{!! Config::get('app.url') !!}" target="_blank">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="{!! Config::get('app.tenant_favicon') !!}"/>
<meta name="csrf-token" content="{{ csrf_token() }}">
@yield('meta')
{!! style_to('assets/css/index.css') !!}
{!! style_to('assets/css/main.css') !!}
Expand Down
117 changes: 117 additions & 0 deletions tests/js/csrf_actions.test.js
Original file line number Diff line number Diff line change
@@ -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');
}
});
});
65 changes: 65 additions & 0 deletions tests/js/csrf_token.test.js
Original file line number Diff line number Diff line change
@@ -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 = `<meta name="csrf-token" content="${TOKEN}">`;
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();
});
});
Loading