From 461722d64cfd3bee0d26a7b6c76176987ecf3c5b Mon Sep 17 00:00:00 2001 From: Malte Legenhausen Date: Sun, 21 Apr 2024 14:56:11 +0200 Subject: [PATCH] doc: correct unsafe URL example in http docs 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: https://github.com/nodejs/node/pull/52555 Reviewed-By: Luigi Pinca Reviewed-By: Paolo Insogna --- doc/api/http.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/doc/api/http.md b/doc/api/http.md index 48aee202a14eb5..890f1fdbf665df 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -2886,24 +2886,23 @@ 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' }, @@ -2911,6 +2910,10 @@ URL { } ``` +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`