Skip to content

Commit

Permalink
doc: correct unsafe URL example in http docs
Browse files Browse the repository at this point in the history
The previous documentation example for converting `request.url` to an
`URL` object was unsafe, as it could allow a server crash through
malformed URL inputs and potentially enable host header attacks.

This commit revises the example to use string concatenation over the
usage of the `baseUrl` and removes the usage of the `req.headers.host`
as the authority part of the url, mitigating both the crash and security
risks by ensuring the host part of the URL remains controlled and
predictable.

Fixes #52494

Co-authored-by: @astlouisf
Co-authored-by: @samhh
PR-URL: #52555
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
  • Loading branch information
mlegenhausen authored and aduh95 committed Apr 29, 2024
1 parent c83526a commit eeb80ad
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -2886,31 +2886,34 @@ Accept: text/plain
To parse the URL into its parts:

```js
new URL(request.url, `http://${request.headers.host}`);
new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
```
When `request.url` is `'/status?name=ryan'` and `request.headers.host` is
`'localhost:3000'`:
When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined:
```console
$ node
> new URL(request.url, `http://${request.headers.host}`)
> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
URL {
href: 'http://localhost:3000/status?name=ryan',
origin: 'http://localhost:3000',
href: 'http://localhost/status?name=ryan',
origin: 'http://localhost',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
host: 'localhost',
hostname: 'localhost',
port: '3000',
port: '',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
```
Ensure that you set `process.env.HOST` to the server's host name, or consider
replacing this part entirely. If using `req.headers.host`, ensure proper
validation is used, as clients may specify a custom `Host` header.
## Class: `http.OutgoingMessage`
<!-- YAML
Expand Down

0 comments on commit eeb80ad

Please sign in to comment.