Skip to content

Commit

Permalink
fix: Handle malformed pathnames in middleware (amannn#1353)
Browse files Browse the repository at this point in the history
  • Loading branch information
amannn authored Sep 19, 2024
1 parent c2992bf commit 9440cc2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .size-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const config: SizeLimitConfig = [
},
{
path: 'dist/production/middleware.js',
limit: '9.61 KB'
limit: '9.625 KB'
},
{
path: 'dist/production/routing.js',
Expand Down
7 changes: 7 additions & 0 deletions src/middleware/middleware.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,13 @@ describe('prefix-based routing', () => {
);
});

it('handles malformed urls', () => {
middleware(createMockRequest('/a%'));
middleware(createMockRequest('/en/a%'));
middleware(createMockRequest('/en/about/a%'));
expect(MockedNextResponse.next).toHaveBeenCalledTimes(3);
});

describe('base path', () => {
it('redirects non-prefixed requests for the default locale', () => {
middleware(withBasePath(createMockRequest('/')));
Expand Down
11 changes: 9 additions & 2 deletions src/middleware/middleware.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,15 @@ export default function createMiddleware<
};

return function middleware(request: NextRequest) {
// Resolve potential foreign symbols (e.g. /ja/%E7%B4%84 → /ja/約))
const unsafeExternalPathname = decodeURI(request.nextUrl.pathname);
let unsafeExternalPathname: string;
try {
// Resolve potential foreign symbols (e.g. /ja/%E7%B4%84 → /ja/約))
unsafeExternalPathname = decodeURI(request.nextUrl.pathname);
} catch (e) {
// In case an invalid pathname is encountered, forward
// it to Next.js which in turn responds with a 400
return NextResponse.next();
}

// Sanitize malicious URIs to prevent open redirect attacks due to
// decodeURI doesn't escape encoded backslashes ('%5C' & '%5c')
Expand Down

0 comments on commit 9440cc2

Please sign in to comment.