Skip to content

Commit

Permalink
fix(request): handle "double dots" in URL (#124)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Jan 21, 2024
1 parent 8cea466 commit dd9b9a9
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
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)
})
})

0 comments on commit dd9b9a9

Please # to comment.