Skip to content

Commit

Permalink
fix: relative protocol urls
Browse files Browse the repository at this point in the history
  • Loading branch information
adamdbradley committed Apr 20, 2023
1 parent 6039e46 commit 09190b7
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/qwik-city/middleware/node/http.ts
Expand Up @@ -20,7 +20,17 @@ function getOrigin(req: IncomingMessage) {

export function getUrl(req: IncomingMessage) {
const origin = ORIGIN ?? getOrigin(req);
return new URL((req as any).originalUrl || req.url || '/', origin);
return normalizeUrl((req as any).originalUrl || req.url || '/', origin);
}

const DOUBLE_SLASH_REG = /\/\/|\\\\/g;

export function normalizeUrl(url: string, base: string) {
// do not allow the url to have a relative protocol url
// which could bypass of CSRF protections
// for example: new URL("//attacker.com", "https://qwik.build.io")
// would return "https://attacker.com" when it should be "https://qwik.build.io/attacker.com"
return new URL(url.replace(DOUBLE_SLASH_REG, '/'), base);
}

export async function fromNodeHttp(
Expand Down
37 changes: 37 additions & 0 deletions packages/qwik-city/middleware/node/http.unit.ts
@@ -0,0 +1,37 @@
import { test } from 'uvu';
import { equal } from 'uvu/assert';
import { normalizeUrl } from './http';

[
{
url: '/',
base: 'https://qwik.dev',
expect: 'https://qwik.dev/',
},
{
url: '/attacker.com',
base: 'https://qwik.dev',
expect: 'https://qwik.dev/attacker.com',
},
{
url: '//attacker.com',
base: 'https://qwik.dev',
expect: 'https://qwik.dev/attacker.com',
},
{
url: '\\\\attacker.com',
base: 'https://qwik.dev',
expect: 'https://qwik.dev/attacker.com',
},
{
url: '/some-path//attacker.com',
base: 'https://qwik.dev',
expect: 'https://qwik.dev/some-path/attacker.com',
},
].forEach((t) => {
test(`normalizeUrl(${t.url}, ${t.base})`, () => {
equal(normalizeUrl(t.url, t.base).href, t.expect);
});
});

test.run();

0 comments on commit 09190b7

Please sign in to comment.