Skip to content

fix(request): handle "double dots" in URL #124

New issue

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

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

Already on GitHub? # to your account

Merged
merged 1 commit into from
Jan 21, 2024
Merged
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
9 changes: 8 additions & 1 deletion src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import type { IncomingMessage } from 'node:http'
import type { Http2ServerRequest } from 'node:http2'
import { resolve } from 'node:path'
import { Readable } from 'node:stream'

const newRequestFromIncoming = (
Expand Down Expand Up @@ -41,7 +42,13 @@ const requestPrototype: Record<string | symbol, any> = {
},

get url() {
return `http://${this[incomingKey].headers.host}${this[incomingKey].url}`
let path = this[incomingKey]['path']
if (!path) {
const originalPath = this[incomingKey].url
path = /\.\./.test(originalPath) ? resolve(originalPath) : originalPath
this[incomingKey]['path'] = path
}
return `http://${this[incomingKey].headers.host}${path}`
},

[getRequestCache]() {
Expand Down
1 change: 1 addition & 0 deletions test/assets/secret.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
secret
13 changes: 13 additions & 0 deletions test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,17 @@ describe('Request', () => {
expect(req.url).toBe('http://localhost/')
expect(req.headers.get('host')).toBe('localhost')
})

it('Should resolve double dots in URL', async () => {
const req = newRequest({
headers: {
host: 'localhost',
},
url: '/static/../foo.txt',
} as IncomingMessage)
expect(req).toBeInstanceOf(global.Request)
expect(req.url).toBe('http://localhost/foo.txt')
// Check if cached value is returned correctly
expect(req.url).toBe('http://localhost/foo.txt')
})
})
5 changes: 5 additions & 0 deletions test/serve-static.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,9 @@ describe('Serve Static Middleware', () => {
'./not-found/on-not-found/foo.txt is not found, request to /on-not-found/foo.txt'
)
})

it('Should handle double dots in URL', async () => {
const res = await request(server).get('/static/../secret.txt')
expect(res.status).toBe(404)
})
})