Skip to content

fix(router): securely check path for proper destination #1133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
42 changes: 26 additions & 16 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,41 @@ export async function getTarget(req, config) {
}

function getTargetFromProxyTable(req, table) {
let result;
const host = req.headers.host;
const path = req.url;

const hostAndPath = host + path;
let hostMatch;

for (const [key, value] of Object.entries(table)) {
if (containsPath(key)) {
if (hostAndPath.indexOf(key) > -1) {
// match 'localhost:3000/api'
result = value;
debug('match: "%s" -> "%s"', key, result);
break;
}
} else {
// host-only rule
if (!containsPath(key)) {
if (key === host) {
// match 'localhost:3000'
result = value;
debug('match: "%s" -> "%s"', host, result);
break;
hostMatch = value;
}
continue;
}

// If key starts with '/', it's a path-only rule.
if (key.startsWith('/')) {
if (path.startsWith(key)) {
debug('path-only match: "%s" -> "%s"', key, value);
return value;
}
}
// If key contains a '/' but doesn't start with one, it's a host+path rule.
else {
const hostAndPath = host + path;
if (hostAndPath.startsWith(key)) {
debug('host+path match: "%s" -> "%s"', key, value);
return value;
}
}
}

return result;
// If we finished the loop with no path-involved matches, use the host-only match.
if (hostMatch) {
debug('host-only fallback: "%s" -> "%s"', host, hostMatch);
}
return hostMatch;
}

function containsPath(v) {
Expand Down
14 changes: 14 additions & 0 deletions test/unit/router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,5 +157,19 @@ describe('router unit test', () => {
return expect(result).resolves.toBe('http://localhost:6006');
});
});

describe('exact path tests, rather than partial match', () => {
it('should NOT match route key from query string parameters', () => {
fakeReq.url = '/foobar?a=1&b=/rest';
result = getTarget(fakeReq, proxyOptionWithRouter);
return expect(result).resolves.toBeUndefined();
});

it('should match from the start of the path and not a substring', () => {
fakeReq.url = '/some/path/that/also/contains/rest';
result = getTarget(fakeReq, proxyOptionWithRouter);
return expect(result).resolves.toBe('http://localhost:6007');
});
});
});
});