-
-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a custom CORS proxy for our clients
- Loading branch information
Showing
10 changed files
with
213 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
import { Readable } from 'stream'; | ||
import { ReadableStream } from 'stream/web'; | ||
|
||
import { Context } from 'koa'; | ||
import { Duration } from 'luxon'; | ||
|
||
import { BadRequestException, ValidationException } from '../../../support/exceptions'; | ||
import { currentConfig } from '../../../support/app-async-context'; | ||
|
||
/** | ||
* Headers of the remote server response that we want to pass to the client | ||
*/ | ||
const headersToPass = ['Location', 'Content-Type', 'Content-Length']; | ||
|
||
const fallbackTimeoutMs = 1000; | ||
|
||
export async function proxy(ctx: Context) { | ||
const { | ||
timeout: timeoutString, | ||
allowedOrigins, | ||
allowedURlPrefixes, | ||
allowLocalhostOrigins, | ||
} = currentConfig().corsProxy; | ||
|
||
const { origin } = ctx.headers; | ||
|
||
if (typeof origin !== 'string') { | ||
// If the client is hosted at the same origin as the server, the browser | ||
// will not send the Origin header. The 'none' value is used to allow these | ||
// types of requests. | ||
if (!allowedOrigins.includes('none')) { | ||
throw new BadRequestException('Missing origin'); | ||
} | ||
} else if ( | ||
// Origin header is present, check it validity | ||
!( | ||
allowedOrigins.includes(origin) || | ||
(allowLocalhostOrigins && /^https?:\/localhost(:\d+)?$/.test(origin)) | ||
) | ||
) { | ||
throw new BadRequestException('Origin not allowed'); | ||
} | ||
|
||
let { url } = ctx.request.query; | ||
|
||
if (Array.isArray(url)) { | ||
// When there is more than one 'url' parameter, use the first one | ||
[url] = url; | ||
} | ||
|
||
if (typeof url !== 'string') { | ||
throw new ValidationException("Missing 'url' parameter"); | ||
} | ||
|
||
// Check if the URL has allowed prefix | ||
if (!allowedURlPrefixes.some((prefix) => url.startsWith(prefix))) { | ||
throw new ValidationException('URL not allowed'); | ||
} | ||
|
||
const timeoutDuration = Duration.fromISO(timeoutString); | ||
const timeoutMs = timeoutDuration.isValid ? timeoutDuration.toMillis() : fallbackTimeoutMs; | ||
|
||
// Perform the request with timeout | ||
const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }); | ||
|
||
// Copying to the client: | ||
// 1. The response status code | ||
ctx.status = response.status; | ||
|
||
// 2. Some of response headers (`headersToPass` list) | ||
for (const header of headersToPass) { | ||
if (response.headers.has(header)) { | ||
ctx.set(header, response.headers.get(header)!); | ||
} | ||
} | ||
|
||
// 3. And the response body itself | ||
ctx.body = response.body ? Readable.fromWeb(response.body as ReadableStream) : null; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import type Router from '@koa/router'; | ||
|
||
import { proxy } from '../../../controllers/api/v2/CorsProxyController'; | ||
|
||
export default function addRoutes(app: Router) { | ||
app.get('/cors-proxy', proxy); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
import { after, before, describe, it } from 'mocha'; | ||
import expect from 'unexpected'; | ||
import { Context } from 'koa'; | ||
|
||
import { withModifiedConfig } from '../helpers/with-modified-config'; | ||
|
||
import { performJSONRequest, MockHTTPServer } from './functional_test_helper'; | ||
|
||
const server = new MockHTTPServer((ctx: Context) => { | ||
const { | ||
request: { url }, | ||
} = ctx; | ||
|
||
if (url === '/example.txt') { | ||
ctx.status = 200; | ||
ctx.response.type = 'text/plain'; | ||
ctx.body = 'Example text'; | ||
} else { | ||
ctx.status = 404; | ||
ctx.response.type = 'text/plain'; | ||
ctx.body = 'Not found'; | ||
} | ||
}); | ||
|
||
describe('CORS proxy', () => { | ||
before(() => server.start()); | ||
after(() => server.stop()); | ||
|
||
withModifiedConfig(() => ({ | ||
corsProxy: { | ||
allowedOrigins: ['none', 'http://localhost:3000'], | ||
allowedURlPrefixes: [`${server.origin}/example`], | ||
}, | ||
})); | ||
|
||
it(`should return error if called without url`, async () => { | ||
const resp = await performJSONRequest('GET', '/v2/cors-proxy'); | ||
expect(resp, 'to equal', { __httpCode: 422, err: "Missing 'url' parameter" }); | ||
}); | ||
|
||
it(`should return error if called with not allowed url`, async () => { | ||
const url = `${server.origin}/index.html`; | ||
const resp = await performJSONRequest('GET', `/v2/cors-proxy?url=${encodeURIComponent(url)}`); | ||
expect(resp, 'to equal', { __httpCode: 422, err: 'URL not allowed' }); | ||
}); | ||
|
||
it(`should return error if called with invalid origin`, async () => { | ||
const url = `${server.origin}/example.txt`; | ||
const resp = await performJSONRequest( | ||
'GET', | ||
`/v2/cors-proxy?url=${encodeURIComponent(url)}`, | ||
null, | ||
{ Origin: 'https://badorigin.net' }, | ||
); | ||
expect(resp, 'to equal', { __httpCode: 400, err: 'Origin not allowed' }); | ||
}); | ||
|
||
it(`should call with allowed url and without origin`, async () => { | ||
const url = `${server.origin}/example.txt`; | ||
const resp = await performJSONRequest('GET', `/v2/cors-proxy?url=${encodeURIComponent(url)}`); | ||
expect(resp, 'to satisfy', { __httpCode: 200, textResponse: 'Example text' }); | ||
}); | ||
|
||
it(`should call with allowed (but non-existing) url and without origin`, async () => { | ||
const url = `${server.origin}/example.pdf`; | ||
const resp = await performJSONRequest('GET', `/v2/cors-proxy?url=${encodeURIComponent(url)}`); | ||
expect(resp, 'to satisfy', { __httpCode: 404, textResponse: 'Not found' }); | ||
}); | ||
|
||
it(`should call with allowed url and origin`, async () => { | ||
const url = `${server.origin}/example.txt`; | ||
const resp = await performJSONRequest( | ||
'GET', | ||
`/v2/cors-proxy?url=${encodeURIComponent(url)}`, | ||
null, | ||
{ Origin: 'http://localhost:3000' }, | ||
); | ||
expect(resp, 'to satisfy', { __httpCode: 200, textResponse: 'Example text' }); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters