|
| 1 | +import assert from 'node:assert/strict'; |
| 2 | +import { test } from 'node:test'; |
| 3 | + |
| 4 | +import { refuse_cross_site_form } from './cross_site_forms'; |
| 5 | + |
| 6 | +const ORIGIN = 'https://auth.syntax.fm'; |
| 7 | + |
| 8 | +function form_post(path: string, headers: Record<string, string> = {}, method = 'POST') { |
| 9 | + const url = new URL(path, ORIGIN); |
| 10 | + const request = new Request(url, { |
| 11 | + method, |
| 12 | + headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers }, |
| 13 | + body: 'grant_type=authorization_code' |
| 14 | + }); |
| 15 | + return refuse_cross_site_form(request, url); |
| 16 | +} |
| 17 | + |
| 18 | +test('a native client may post forms to the token and revocation endpoints with no Origin', () => { |
| 19 | + assert.equal(form_post('/api/auth/oauth2/token'), null); |
| 20 | + assert.equal(form_post('/api/auth/oauth2/revoke'), null); |
| 21 | + assert.equal(form_post('/api/auth/oauth2/token', { origin: 'https://evil.example' }), null); |
| 22 | +}); |
| 23 | + |
| 24 | +test('every other path still refuses a form post from another site or with no Origin, as SvelteKit did', async () => { |
| 25 | + for (const [path, headers] of [ |
| 26 | + ['/api/auth/oauth2/token/', {}], |
| 27 | + ['/api/auth/oauth2/consent', {}], |
| 28 | + ['/api/auth/sign-out', { origin: 'https://evil.example' }], |
| 29 | + ['/consent', { origin: 'null' }] |
| 30 | + ] as const) { |
| 31 | + const refusal = form_post(path, headers); |
| 32 | + assert.equal(refusal?.status, 403, path); |
| 33 | + assert.equal(await refusal?.text(), 'Cross-site POST form submissions are forbidden'); |
| 34 | + } |
| 35 | + |
| 36 | + for (const content_type of [ |
| 37 | + 'multipart/form-data; boundary=x', |
| 38 | + 'TEXT/PLAIN', |
| 39 | + 'application/x-sveltekit-formdata' |
| 40 | + ]) { |
| 41 | + assert.equal( |
| 42 | + form_post('/consent', { 'content-type': content_type })?.status, |
| 43 | + 403, |
| 44 | + content_type |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + const json_refusal = form_post('/consent', { accept: 'application/json' }, 'DELETE'); |
| 49 | + assert.equal(json_refusal?.status, 403); |
| 50 | + assert.deepEqual(await json_refusal?.json(), { |
| 51 | + message: 'Cross-site DELETE form submissions are forbidden' |
| 52 | + }); |
| 53 | +}); |
| 54 | + |
| 55 | +test('same-site form posts, other content types, and GETs go on', () => { |
| 56 | + assert.equal(form_post('/api/auth/sign-out', { origin: ORIGIN }), null); |
| 57 | + assert.equal(form_post('/consent', { 'content-type': 'application/json' }), null); |
| 58 | + |
| 59 | + const url = new URL('/consent', ORIGIN); |
| 60 | + assert.equal(refuse_cross_site_form(new Request(url), url), null); |
| 61 | +}); |
0 commit comments