diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index f0a5433..7de5b50 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -1,15 +1,22 @@ name: tests on: [push, pull_request] +permissions: + contents: read + jobs: testing: runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [18.x, 20.x, 22.x, 24.x] steps: - - uses: actions/checkout@v1 - - name: Setup Environment (Using NodeJS 16.x) - uses: actions/setup-node@v1 + - uses: actions/checkout@v4 + - name: Setup Environment (Using NodeJS ${{ matrix.node-version }}) + uses: actions/setup-node@v4 with: - node-version: 16.x + node-version: ${{ matrix.node-version }} - name: Install dependencies run: npm install @@ -18,4 +25,4 @@ jobs: run: npx standard - name: Run tests - run: npm run test \ No newline at end of file + run: npm run test diff --git a/README.md b/README.md index e765a8c..a3e32f0 100644 --- a/README.md +++ b/README.md @@ -53,13 +53,14 @@ Please see: https://github.com/jkyberneees/nodejs-proxy-benchmarks ### Options #### `base` Set the base URL for all the forwarded requests. +> When `base` is set, requests can only be forwarded to its origin (protocol + host + port). The path of `base` is not a restriction, see [Request target validation](#request-target-validation). #### cacheURLs The number of parsed URLs that will be cached. Default: 100. > Use value = `0` to disable the caching mechanism #### requests.http and requests.https -Allows to optionally overwrite the internal `http` and `https` client agents implementation. Defaults: [`http`](https://nodejs.org/api/http.html#http_http) and [`https`](https://nodejs.org/api/https.html#https_https). +Allows to optionally overwrite the internal `http` and `https` client implementation. Defaults: [`http`](https://nodejs.org/api/http.html#http_http) and [`https`](https://nodejs.org/api/https.html#https_https). For example, this could be used to add support for following redirects, like so: @@ -88,6 +89,15 @@ self-signed certificates. #### Extended configurations Other supported configurations in https://nodejs.org/api/http.html#http_new_agent_options can also be part of the `opts` object. +For example, `timeout` defines the maximum time (in milliseconds) the remote server connection can stay idle while a request is in flight: +```js +const { proxy, close } = require('fast-proxy-lite')({ + base: 'http://127.0.0.1:3000', + timeout: 30000 +}) +``` +> There is no timeout by default: a remote server that never responds keeps the client request open. Setting `timeout` here, or per request using `opts.request.timeout`, is strongly recommended. + ### close Optional _"on `close` resource release"_ strategy. You can link this to your application shutdown hook as an example. @@ -119,6 +129,9 @@ if (!res.socket || res.socket.destroyed || res.writableEnded) { return onClientConnectionTerminated(res, err, response) } ``` +- The request to the remote server is aborted as soon as the client connection is terminated. In such case `err.code` is `ECONNRESET` and `response` is `undefined`. +- If the remote server responded anyway, `response` is defined and `err` is `null`. The response stream is destroyed right after the callback returns, unless the callback starts consuming it. +- If the client connection was already terminated when `proxy` was invoked, nothing is sent to the remote server. ##### rewriteRequestHeaders(req, headers) Called to rewrite the headers of the request, before them being sent to the downstream server. @@ -134,7 +147,64 @@ Extended options supported by `http[s].request` method (https://nodejs.org/api/h > The following options are dynamically assigned: `method, port, path, hostname, headers, agent`. ##### queryString -Replaces the original querystring of the request with what is specified. +Replaces the original querystring of the request with what is specified. Accepts a string or an object. +> If `source` has no querystring and this option is not set, the querystring of the original request (`req.url`) is forwarded. + +## Behavior + +### Request body +`GET` and `HEAD` requests are always forwarded without a payload. For any other method, the payload is taken from `req.body` when a body parser already consumed the request: + +| `req.body` | Forwarded payload | Default `content-type` | +|---|---|---| +| `undefined` / `null` | the request stream | - | +| `Stream` | the given stream, using chunked transfer encoding | - | +| `string` | as is | `text/plain` | +| `Buffer` / typed array | as is | `application/octet-stream` | +| object, and the request `content-type` is `application/x-www-form-urlencoded` | URL encoded | `application/x-www-form-urlencoded` | +| anything else | JSON | `application/json` | + +> An empty object (`{}`) on a request whose payload was not consumed is considered as "not parsed" (this is what `body-parser` assigns for content types it does not handle), the request stream is forwarded instead. + +The `content-length`/`transfer-encoding` headers of the forwarded request are always (re)defined by the proxy, they are never copied blindly from the client request: +- A custom `Stream` is never framed using the `content-length` of the client request, as it does not describe it (e.g: a decompressed payload). If its length is known, `rewriteRequestHeaders` can replace `transfer-encoding` with `content-length`. +- If `rewriteRequestHeaders` returns both headers, `content-length` is dropped. +- `content-encoding` is not forwarded when the payload was decoded by a body parser. + +A `req.body` that can't be serialized (cyclic structures, `BigInt` values...) is rejected with `400 Bad Request`. + +### Headers +- Request: hop-by-hop headers (`connection`, `keep-alive`, `proxy-connection`, `proxy-authorization`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `http2-settings`) and `expect` are not forwarded. `host` is set to the remote host, the original value is forwarded as `x-forwarded-host`. +- Response: hop-by-hop headers (`connection`, `keep-alive`, `proxy-connection`, `proxy-authenticate`, `te`, `trailer`, `transfer-encoding`, `upgrade`, `http2-settings`), the headers nominated by the remote `connection` header, and `host` are not forwarded. + +> Protocol upgrades (e.g: WebSockets) are not supported. + +### Request target validation +The request is rejected with `400 Bad Request`, and nothing is sent to the remote server, when: +- The `host` header is missing. +- The method is not upper case. HTTP/2 servers accept `delete` as a method, HTTP clients would send it as `DELETE`. +- The target URL can't be parsed, or its protocol is not `http:` or `https:`. +- `base` is set and the target resolves to a different origin. +- The target path starts with `//`, contains `.` or `..` segments (also in their `%2e` encoded form), backslashes or control characters, or the target starts/ends with a space. URL parsers rewrite those, the path sent to the remote server would be different than the one your router and access control logic have seen (e.g: `/public/../admin` matching a `/public/*` route, `//admin` not matching an `/admin` rule). +- The request can't be represented as a valid HTTP request (e.g: invalid header values returned by `rewriteRequestHeaders`). + +`CONNECT` requests are rejected with `405 Method Not Allowed`. + +> When `base` is not set, `source` must be an absolute URL and no origin restriction applies. Never build it from untrusted input. + +> Anything else is forwarded as received: `/public/..;/admin`, `/public/..%2fadmin` or `/public//admin` are valid paths that reach the remote server untouched. If the remote server applies further normalization (matrix parameters, double decoding, slash merging...), access control has to take it into account. + +### Errors +| Condition | Response | +|---|---| +| Remote server refused the connection (`ECONNREFUSED`) | `503 Service Unavailable` | +| Remote server timeout or connection reset (`ETIMEDOUT`, `ECONNRESET`) | `504 Gateway Timeout` | +| Any other failure, including invalid responses | `502 Bad Gateway` | +| `rewriteHeaders`, `onResponse` or `onClientConnectionTerminated` threw | `500 Internal Server Error` | + +If the remote server fails after the response headers were sent to the client, the client connection (HTTP/2: the stream) is terminated so the response is not mistaken with a complete one. + +Errors thrown by `rewriteHeaders`, `onResponse` and `onClientConnectionTerminated` can't be propagated to the caller, they are reported using [`process.emitWarning`](https://nodejs.org/api/process.html#processemitwarningwarning-options). Errors thrown by `rewriteRequestHeaders` are propagated to the caller of `proxy`. ## Related topics - http-agent: https://nodejs.org/api/http.html#http_new_agent_options diff --git a/index.d.ts b/index.d.ts index 653f9bb..9e66f7c 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,45 +1,66 @@ import * as Http from 'http'; +import * as Http2 from 'http2'; import * as Https from 'https'; -import { Stream } from 'pump'; -export type Options = { +/** + * HTTP client implementation, e.g: the `http`/`https` core modules or + * `follow-redirects/http`/`follow-redirects/https`. + */ +export type RequestClient = { + request(options: Https.RequestOptions, ...args: any[]): any; +}; + +/** + * Besides the options described here, any option supported by the `http.Agent` + * and `https.Agent` constructors is accepted (`maxFreeSockets`, `timeout`...). + */ +export type Options = Https.AgentOptions & { base?: string; cacheURLs?: number; requests?: { - http?: Http.Agent; - https?: Https.Agent; + http?: RequestClient; + https?: RequestClient; }; keepAliveMsecs?: number; maxSockets?: number; rejectUnauthorized?: boolean; }; +export type ProxyRequest = Http.IncomingMessage | Http2.Http2ServerRequest; +export type ProxyResponse = Http.ServerResponse | Http2.Http2ServerResponse; + export type ProxyRequestResponse = { - statusCode: Number; - headers: Http.OutgoingHttpHeaders; - stream: Stream; + statusCode: number; + headers: Http.IncomingHttpHeaders; + stream: Http.IncomingMessage; }; export type ProxyOptions = { base?: string; - onClientConnectionTerminated?(res: Http.ServerResponse, err: Error, response: ProxyRequestResponse): void; - onResponse?(req: Http.IncomingMessage, res: Http.ServerResponse, stream: Stream): void; - rewriteRequestHeaders?(req: Http.IncomingMessage, headers: Http.IncomingHttpHeaders): Http.IncomingHttpHeaders; + /** + * Called when the client connection is terminated before the remote + * response could be delivered. `response` is only defined if the remote + * server responded, in such case its stream is destroyed after this callback + * returns, unless it is being consumed. + */ + onClientConnectionTerminated?(res: ProxyResponse, err: Error | null, response?: ProxyRequestResponse): void; + onResponse?(req: ProxyRequest, res: ProxyResponse, stream: Http.IncomingMessage): void; + rewriteRequestHeaders?(req: ProxyRequest, headers: Http.IncomingHttpHeaders): Http.IncomingHttpHeaders; rewriteHeaders?(headers: Http.OutgoingHttpHeaders): Http.OutgoingHttpHeaders; - request?: Http.RequestOptions; - queryString?: string; + request?: Https.RequestOptions; + queryString?: string | URLSearchParams | Record; } export type FastProxy = { proxy( - originReq: Http.IncomingMessage, - originRes: Http.ServerResponse, - source: string, + originReq: ProxyRequest, + originRes: ProxyResponse, + source?: string | null, opts?: ProxyOptions ): void; close(): void; } -declare function fastProxy(options?: Options): FastProxy +export declare function fastProxy(options?: Options): FastProxy export default fastProxy diff --git a/index.js b/index.js index ce1a9b3..41a8836 100644 --- a/index.js +++ b/index.js @@ -6,14 +6,22 @@ const Stream = require('stream') const buildRequest = require('./lib/request') const { - filterPseudoHeaders, + buildRequestHeaders, copyHeaders, stripHttp1ConnectionHeaders, - filterHeaders, + isValidContentLength, + isFormUrlEncoded, + isEmptyPlainObject, + toFormUrlEncoded, buildURL, populateHeaders } = require('./lib/utils') +const { createError } = buildRequest + +const LOWER_CASE = /[a-z]/ +const NGHTTP2_INTERNAL_ERROR = 0x02 + function fastProxy (opts = {}) { const { request, close } = buildRequest({ ...opts @@ -21,6 +29,7 @@ function fastProxy (opts = {}) { const cache = getCacheStorage(opts.cacheURLs) const base = opts.base + const baseCachePrefix = getCachePrefix(base) return { close, @@ -32,18 +41,51 @@ function fastProxy (opts = {}) { const rewriteHeaders = opts.rewriteHeaders || rewriteHeadersNoOp const rewriteRequestHeaders = opts.rewriteRequestHeaders || rewriteRequestHeadersNoOp + if (isClientGone(res)) { + // nobody is waiting for a response, e.g: the client went away while + // asynchronous middlewares were running. The 'close' event was + // already emitted, the remote request could not be aborted later on. + onClientConnectionTerminated(res, createError('Client connection terminated', 'ECONNRESET')) + + return + } + + const method = req.method + if (method === 'CONNECT') { + // tunnels are not supported + sendError(res, 405, 'Method Not Allowed') + + return + } + if (LOWER_CASE.test(method)) { + // Methods are case-sensitive, but http clients send them in upper case. + // HTTP/2 servers do accept "delete" as a method name: forwarding it as + // "DELETE" would bypass any method based access control. + sendError(res, 400, 'Bad Request') + + return + } + let url try { - url = getReqUrl(source || req.url, cache, base, opts) + url = opts.base + ? getReqUrl(source || req.url, cache, opts.base, getCachePrefix(opts.base)) + : getReqUrl(source || req.url, cache, base, baseCachePrefix) } catch (err) { - res.statusCode = 400 - res.end('Bad Request') + sendError(res, 400, 'Bad Request') + return } + + const reqHeaders = req.headers const sourceHttp2 = req.httpVersionMajor === 2 - let headers = { ...sourceHttp2 ? filterPseudoHeaders(req.headers) : req.headers } - if (!headers.host) { + // An intermediary that converts an HTTP/2 request to HTTP/1.1 + // MUST create a Host header field if one is not present in a request + // by copying the value of the :authority pseudo-header field. + // see: https://httpwg.org/specs/rfc7540.html + const host = reqHeaders.host || (sourceHttp2 ? reqHeaders[':authority'] : undefined) + if (!host) { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host // @TODO: Should add performance-aware host header value validation(regex-based) as a further step? res.statusCode = 400 @@ -52,94 +94,202 @@ function fastProxy (opts = {}) { return } - headers['x-forwarded-host'] = headers.host - headers.host = url.hostname - if (url.port) { - headers.host += `:${url.port}` - } - - const qs = getQueryString(url.search, req.url, opts) + let headers = buildRequestHeaders(reqHeaders) + headers.host = url.host + headers['x-forwarded-host'] = host let body = null + let streaming = false // according to https://tools.ietf.org/html/rfc2616#section-4.3 // proxy should ignore message body when it's a GET or HEAD request - // when proxy this request, we should reset the content-length to make it a valid http request - if (req.method === 'GET' || req.method === 'HEAD') { - if (headers['content-length']) { - headers = filterHeaders(headers, 'content-length') + // when proxy this request, the message framing headers are not forwarded to make it a valid http request + if (method !== 'GET' && method !== 'HEAD') { + body = req.body + if (body === undefined || body === null) { + body = req + } else if (body instanceof Stream) { + // forwarded as is + } else if (typeof body === 'object' && req.readableEnded === false && isEmptyPlainObject(body)) { + // body parsers commonly assign an empty object as "req.body" when the + // request payload was not parsed (e.g: unsupported content-type), in + // such case the payload is still unread and has to be streamed + body = req + } else { + try { + body = serializeBody(body, headers, reqHeaders) + } catch (err) { + // the payload can't be serialized: BigInt values, cyclic structures... + sendError(res, 400, 'Bad Request') + + return + } } - } else { - if (req.body) { - if (req.body instanceof Stream) { - body = req.body - } else if (typeof req.body === 'string') { - body = req.body - populateHeaders(headers, body, 'text/plain') - } else if (headers['content-type'] === 'application/x-www-form-urlencoded') { - body = new URLSearchParams(req.body).toString() - populateHeaders(headers, body, 'application/x-www-form-urlencoded') + + if (body instanceof Stream) { + // The framing of the remote request is explicitly defined here, it + // must never be left to the http client defaults: a body written to + // a request with neither "content-length" nor "transfer-encoding" + // is sent unframed, and would be parsed as a second (smuggled) + // request by the remote server. + if (body !== req) { + // The framing headers of the client request describe the client + // payload, not this stream (e.g: a decompressed version of it). + // Bytes exceeding a wrong content-length would be parsed as a + // second request by the remote server. + headers['transfer-encoding'] = 'chunked' + streaming = true + } else if (req.readableEnded === true) { + // an already consumed request has nothing left to forward + body = null + } else if (reqHeaders['transfer-encoding'] !== undefined) { + // the incoming server already decoded the chunked payload + headers['transfer-encoding'] = 'chunked' + streaming = true + } else if (isValidContentLength(reqHeaders['content-length'])) { + headers['content-length'] = reqHeaders['content-length'] + streaming = true + } else if (!sourceHttp2) { + // an HTTP/1 request with no framing headers has no payload + body = null } else { - body = JSON.stringify(req.body) - populateHeaders(headers, body, 'application/json') + headers['transfer-encoding'] = 'chunked' + streaming = true } - } else { - body = req } } + headers = rewriteRequestHeaders(req, headers) || headers + if (headers['transfer-encoding'] !== undefined) { + // both headers must never be sent, "transfer-encoding" takes precedence + if (headers['content-length'] !== undefined) { + delete headers['content-length'] + } + } else if (streaming && !hasFramingHeaders(headers)) { + headers['transfer-encoding'] = 'chunked' + } + const reqParams = { - method: req.method, + method, url, - qs, - headers: rewriteRequestHeaders(req, headers), + qs: getQueryString(url.search, req.url, opts), + headers, body, request: reqOpts } - request(reqParams, (err, response) => { - if (!res.socket || res.socket.destroyed || res.writableEnded) { - return onClientConnectionTerminated(res, err, response) - } - if (err) { - if (err.code === 'ECONNREFUSED') { - res.statusCode = 503 - res.end('Service Unavailable') - } else if ( - err.code === 'ECONNRESET' || - err.code === 'UND_ERR_HEADERS_TIMEOUT' || - err.code === 'UND_ERR_BODY_TIMEOUT') { - res.statusCode = 504 - res.end('Gateway Timeout') - } else { - res.statusCode = 500 - res.end('Bad Gateway') + let settled = false + let abort + try { + abort = request(reqParams, (err, response) => { + settled = true + + // remote response headers already copied to the client response + let copiedHeaders = null + + try { + if (isClientGone(res)) { + try { + onClientConnectionTerminated(res, err, response) + } finally { + // an unconsumed response would hold the remote connection forever + if (response && response.stream && response.stream.readableFlowing === null) { + response.stream.destroy() + } + } + + return + } + + if (err) { + if (err.code === 'ECONNREFUSED') { + sendError(res, 503, 'Service Unavailable') + } else if ( + err.code === 'ECONNRESET' || + err.code === 'ETIMEDOUT' || + err.code === 'ESOCKETTIMEDOUT' || + err.code === 'UND_ERR_HEADERS_TIMEOUT' || + err.code === 'UND_ERR_BODY_TIMEOUT') { + sendError(res, 504, 'Gateway Timeout') + } else { + sendError(res, 502, 'Bad Gateway') + } + + return + } + + // destructing response from remote + const { headers, statusCode, stream } = response + + if (!isValidStatusCode(statusCode)) { + stream.destroy() + sendError(res, 502, 'Bad Gateway') + + return + } + + // Strip hop-by-hop headers for all responses (HTTP/1.1 and HTTP/2). + // Per RFC 7230 §6.1, hop-by-hop headers MUST NOT be forwarded by proxies. + const safeHeaders = stripHttp1ConnectionHeaders(headers) + const resHeaders = rewriteHeaders(safeHeaders) || safeHeaders + + try { + // set origin response code + res.statusCode = statusCode + copiedHeaders = resHeaders + copyHeaders(resHeaders, res) + } catch (err) { + // the remote response can't be represented to the client, e.g: + // invalid header values, status codes not allowed in HTTP/2 + stream.destroy() + removeHeaders(resHeaders, res) + sendError(res, 502, 'Bad Gateway') + + return + } + + if (onResponse) { + onResponse(req, res, stream) + } else { + if (sourceHttp2) { + resetHttp2StreamOnFailure(stream, res) + } + pump(stream, res) + } + } catch (err) { + // A hook threw. This callback runs outside of the caller stack, the + // error can't be propagated: it would be an uncaught exception. + if (response && response.stream && !response.stream.destroyed) { + response.stream.destroy() + } + if (!isClientGone(res)) { + if (copiedHeaders !== null) { + // The remote headers describe the remote payload, not the error + // sent here: a stale "content-length" would desynchronize the + // client connection, "cache-control" would make the error cacheable. + removeHeaders(copiedHeaders, res) + } + sendError(res, 500, 'Internal Server Error') + } + process.emitWarning(err instanceof Error ? err : String(err)) } + }) + } catch (err) { + // the request can't be represented to the remote server: + // invalid header name/value, invalid path characters... + settled = true + sendError(res, 400, 'Bad Request') - return - } - - // destructing response from remote - const { headers, statusCode, stream } = response - - // Strip hop-by-hop headers for all responses (HTTP/1.1 and HTTP/2). - // Per RFC 7230 §6.1, hop-by-hop headers MUST NOT be forwarded by proxies. - const safeHeaders = stripHttp1ConnectionHeaders(headers) - - if (sourceHttp2) { - copyHeaders(rewriteHeaders(safeHeaders), res) - } else { - copyHeaders(rewriteHeaders(safeHeaders), res) - } - - // set origin response code - res.statusCode = statusCode + return + } - if (onResponse) { - onResponse(req, res, stream) - } else { - pump(stream, res) - } - }) + if (!settled) { + // do not keep the remote server busy when nobody is waiting for the response + res.on('close', () => { + if (!settled) { + abort(createError('Client connection terminated', 'ECONNRESET')) + } + }) + } } } } @@ -155,12 +305,119 @@ function getQueryString (search, reqUrl, opts) { const queryIndex = reqUrl.indexOf('?') if (queryIndex > 0) { - return reqUrl.slice(queryIndex) + const hashIndex = reqUrl.indexOf('#') + if (hashIndex === -1) { + return reqUrl.slice(queryIndex) + } + if (hashIndex > queryIndex) { + return reqUrl.slice(queryIndex, hashIndex) + } } return '' } +function serializeBody (body, headers, reqHeaders) { + if (typeof body === 'string') { + populateHeaders(headers, body, 'text/plain') + } else if (Buffer.isBuffer(body) || ArrayBuffer.isView(body)) { + if (!Buffer.isBuffer(body)) { + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength) + } + populateHeaders(headers, body, 'application/octet-stream') + + // Raw payloads are either untouched, or decoded by the body parser. The + // "content-encoding" header only applies to the former, in which case the + // payload length still matches the one announced by the client. + const contentLength = reqHeaders['content-length'] + if (!isValidContentLength(contentLength) || Number(contentLength) === body.length) { + return body + } + } else if (typeof body === 'object' && isFormUrlEncoded(headers['content-type'])) { + body = toFormUrlEncoded(body) + populateHeaders(headers, body, 'application/x-www-form-urlencoded') + } else { + body = JSON.stringify(body) || '' + populateHeaders(headers, body, 'application/json') + } + + // the payload was decoded by a body parser, it is forwarded as plain content + if (headers['content-encoding'] !== undefined) { + delete headers['content-encoding'] + } + + return body +} + +// When the remote response fails midway, the HTTP/2 stream has to be reset. +// Destroying the response (what pump does) ends the stream gracefully, the +// client would not be able to tell that the payload is incomplete. +function resetHttp2StreamOnFailure (stream, res) { + const reset = () => { + const http2Stream = res.stream + if (http2Stream && !http2Stream.destroyed) { + http2Stream.close(NGHTTP2_INTERNAL_ERROR) + } + } + + stream.once('aborted', reset) + stream.once('error', reset) +} + +function hasFramingHeaders (headers) { + if (headers['content-length'] !== undefined || headers['transfer-encoding'] !== undefined) { + return true + } + + // slow path: header names in a different case + const keys = Object.keys(headers) + let name + for (let i = 0; i < keys.length; i++) { + name = keys[i].toLowerCase() + if (name === 'content-length' || name === 'transfer-encoding') { + return true + } + } + + return false +} + +function isClientGone (res) { + return !res.socket || res.socket.destroyed || res.writableEnded +} + +function isValidStatusCode (statusCode) { + return (statusCode | 0) === statusCode && statusCode >= 100 && statusCode <= 999 +} + +function sendError (res, statusCode, message) { + if (res.headersSent) { + // the response was already started, the only way to signal the failure is + // to terminate the connection. Writing here would corrupt the payload. + res.destroy() + + return + } + + res.statusCode = statusCode + res.end(message) +} + +function removeHeaders (headers, res) { + if (res.headersSent) { + return + } + + const headersKeys = Object.keys(headers) + for (let i = 0; i < headersKeys.length; i++) { + try { + res.removeHeader(headersKeys[i]) + } catch (err) { + // invalid header name, it was never set + } + } +} + function rewriteHeadersNoOp (headers) { return headers } @@ -181,24 +438,44 @@ function getCacheStorage (size) { return lru(size || 100) } -function getReqUrl (source, cache, base, opts) { - const reqBase = opts.base || base - let url +// The cache key must not allow two different (base, source) pairs to collide, +// the base is therefore length-prefixed. Sources used without a base are only +// cached when they are valid absolute URLs, which can't start with a digit. +function getCachePrefix (reqBase) { + return reqBase ? reqBase.length + ':' + reqBase : '' +} - if (cache) { - const cacheKey = reqBase + source - url = cache.get(cacheKey) - if (!url) { - url = buildURL(source, reqBase) - cache.set(cacheKey, url) - } - } else { - url = buildURL(source, reqBase) +function getReqUrl (source, cache, reqBase, cachePrefix) { + if (cache === null) { + return toTarget(buildURL(source, reqBase)) + } + + const cacheKey = cachePrefix + source + let url = cache.get(cacheKey) + if (url === undefined) { + url = toTarget(buildURL(source, reqBase)) + cache.set(cacheKey, url) } return url } +// URL getters are computed on every access, the request target is cached as a +// plain object instead. +function toTarget (url) { + const hostname = url.hostname + + return { + protocol: url.protocol, + host: url.host, + // IPv6 literals: brackets belong to the URL syntax, not to the address + hostname: hostname.charCodeAt(0) === 91 ? hostname.slice(1, -1) : hostname, + port: url.port, + pathname: url.pathname, + search: url.search + } +} + module.exports = fastProxy module.exports.default = fastProxy module.exports.fastProxy = fastProxy diff --git a/lib/request.js b/lib/request.js index 59575fa..19f379d 100644 --- a/lib/request.js +++ b/lib/request.js @@ -23,38 +23,81 @@ function buildRequest (opts) { } } + /** + * Sends the request to the remote server. + * "done" is guaranteed to be invoked at most once: either with the error + * that prevented a response from being received, or with the response. + * Returns a function that aborts the request. + */ function handleHttp1Req (requests, agents) { return (opts, done) => { - const req = requests[opts.url.protocol].request({ + const url = opts.url + let settled = false + + const finish = (err, response) => { + if (settled) { + return + } + settled = true + done(err, response) + } + const onProtocolSwitch = (res, socket) => { + // the connection can't be reused + socket.destroy() + finish(createError('Unexpected protocol switch from remote server', 'ERR_UNEXPECTED_PROTOCOL_SWITCH')) + } + + const req = requests[url.protocol].request({ ...opts.request, method: opts.method, - port: opts.url.port, - path: opts.url.pathname + opts.qs, - hostname: opts.url.hostname, + port: url.port, + path: url.pathname + opts.qs, + hostname: url.hostname, headers: opts.headers, - agent: agents[opts.url.protocol] + agent: agents[url.protocol] }) - req.on('error', done) - req.on('timeout', () => req.abort()) + // this listener must remain attached for the whole request lifecycle, + // errors raised after a response was received are reported by the + // response stream itself + req.on('error', finish) + req.on('timeout', () => destroy(req, createError('Remote server timeout', 'ETIMEDOUT'))) + // protocol switching and tunnels are not supported, without these + // listeners the request would never be settled + req.on('upgrade', onProtocolSwitch) + req.on('connect', onProtocolSwitch) req.on('response', res => { - setImmediate(() => done(null, { statusCode: res.statusCode, headers: res.headers, stream: res })) + if (settled) { + // nobody is going to consume this response + res.destroy() + + return + } + finish(null, { statusCode: res.statusCode, headers: res.headers, stream: res }) }) - end(req, opts.body, done) + end(req, opts.body, finish) + + return err => { + finish(err) + destroy(req, err) + } } } function agentOption (opts) { + // "base", "cacheURLs" and "requests" are not agent/socket options + const { base, cacheURLs, requests, ...agentOpts } = opts + return { keepAlive: true, keepAliveMsecs: 60 * 1000, // 1 minute maxSockets: 2048, maxFreeSockets: 2048, - ...opts + ...agentOpts } } function end (req, body, cb) { - if (!body || typeof body === 'string') { + if (!body || typeof body === 'string' || Buffer.isBuffer(body)) { req.end(body) } else { pump(body, req, err => { @@ -64,4 +107,20 @@ function buildRequest (opts) { } } +function createError (message, code) { + const err = new Error(message) + err.code = code + + return err +} + +function destroy (req, err) { + if (typeof req.destroy === 'function') { + req.destroy(err) + } else { + req.abort() + } +} + module.exports = buildRequest +module.exports.createError = createError diff --git a/lib/utils.js b/lib/utils.js index 6e2e5e6..8173513 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,5 +1,37 @@ 'use strict' +const FORM_URLENCODED = 'application/x-www-form-urlencoded' + +// Maximum nesting honoured when serializing a parsed body back to +// application/x-www-form-urlencoded. Guards against cyclic structures. +const FORM_MAX_DEPTH = 16 + +// Matches request paths that the WHATWG URL parser would silently rewrite into +// a different hierarchy than the one the caller (router, ACL middleware...) +// has seen: +// - "\" is treated as "/" for http(s) URLs +// - TAB, LF and CR are removed from anywhere in the input, any other control +// character is not allowed in a request target either +// - "." and ".." segments (also "%2e" encoded, case-insensitive) are resolved +// Forwarding the rewritten path would allow escaping a route prefix +// (e.g. "/public/../admin" matching a "/public/*" route but reaching "/admin"). +// eslint-disable-next-line no-control-regex +const UNSAFE_PATH = /[\\\x00-\x1f\x7f]|(?:^|\/)(?:\.|%2[eE]){1,2}(?:\/|$)/ + +const DIGITS_ONLY = /^\d+$/ + +let lastBase = null +let lastBaseOrigin = null + +function getBaseOrigin (reqBase) { + if (reqBase !== lastBase) { + lastBaseOrigin = new URL(reqBase).origin + lastBase = reqBase + } + + return lastBaseOrigin +} + function populateHeaders (headers, body, contentType) { headers['content-length'] = Buffer.byteLength(body) @@ -9,24 +41,55 @@ function populateHeaders (headers, body, contentType) { } } -function filterPseudoHeaders (headers) { +/** + * Builds the headers to be sent to the remote server from the incoming + * request headers. A new object is always returned. + * + * The following headers are never forwarded: + * - HTTP/2 pseudo headers + * - hop-by-hop headers (RFC 9110 §7.6.1). Forwarding "upgrade"/"connection" + * lets a client switch the upstream connection to a protocol the proxy + * does not relay, "connection: close" defeats upstream connection reuse. + * - "expect": the expectation was already handled by the incoming server + * - message framing headers ("content-length", "transfer-encoding"): framing + * of the upstream request is decided by the proxy, never by the client. + * Forwarding both, or none for a request with a body, enables HTTP request + * smuggling. + * + * Headers nominated by the client "Connection" header are intentionally NOT + * removed: honouring them would allow a client to strip headers that were + * added by trusted middlewares (auth context, x-forwarded-*...). + */ +function buildRequestHeaders (reqHeaders) { const dest = {} - const headersKeys = Object.keys(headers) - - // An intermediary that converts an HTTP/2 request to HTTP/1.1 - // MUST create a Host header field if one is not present in a request - // by copying the value of the :authority pseudo-header field. - // see: https://httpwg.org/specs/rfc7540.html - if (!headers.host && headers[':authority']) { - dest.host = headers[':authority'] - } + const keys = Object.keys(reqHeaders) - let header + let key + let name let i - for (i = 0; i < headersKeys.length; i++) { - header = headersKeys[i] - if (header.charCodeAt(0) !== 58) { // fast path for indexOf(':') === 0 - dest[header.toLowerCase()] = headers[header] + for (i = 0; i < keys.length; i++) { + key = keys[i] + if (key.charCodeAt(0) === 58) { // fast path for indexOf(':') === 0 + continue + } + + name = key.toLowerCase() + switch (name) { + case 'connection': + case 'keep-alive': + case 'proxy-connection': + case 'proxy-authorization': + case 'te': + case 'trailer': + case 'transfer-encoding': + case 'upgrade': + case 'http2-settings': + case 'expect': + case 'content-length': + break + default: + dest[name] = reqHeaders[key] + break } } @@ -37,85 +100,203 @@ function copyHeaders (headers, res) { const headersKeys = Object.keys(headers) let header + let value let i for (i = 0; i < headersKeys.length; i++) { header = headersKeys[i] if (header.charCodeAt(0) !== 58) { // fast path for indexOf(':') === 0 - res.setHeader(header, headers[header]) + value = headers[header] + if (value !== undefined && value !== null) { + res.setHeader(header, value) + } } } } +/** + * Removes from the remote response all the headers that are only meaningful + * for the proxy <-> remote connection (RFC 9110 §7.6.1), including the ones + * nominated by the remote "Connection" header. + */ function stripHttp1ConnectionHeaders (headers) { const headersKeys = Object.keys(headers) const dest = {} + let connection + let key let header let i for (i = 0; i < headersKeys.length; i++) { - header = headersKeys[i].toLowerCase() + key = headersKeys[i] + header = key.toLowerCase() switch (header) { case 'connection': + connection = headers[key] + break case 'upgrade': case 'http2-settings': case 'te': + case 'trailer': case 'transfer-encoding': case 'proxy-connection': + case 'proxy-authenticate': case 'keep-alive': case 'host': break default: - dest[header] = headers[header] + dest[header] = headers[key] break } } + + if (connection !== undefined && connection !== 'keep-alive' && connection !== 'close') { + removeConnectionTokens(dest, connection) + } + return dest } -function filterHeaders (headers, filter) { - const headersKeys = Object.keys(headers) - const dest = {} +function removeConnectionTokens (dest, connection) { + const tokens = String(connection).split(',') - let header + let token let i - for (i = 0; i < headersKeys.length; i++) { - header = headersKeys[i].toLowerCase() - if (header !== filter) { - dest[header] = headers[header] + for (i = 0; i < tokens.length; i++) { + token = tokens[i].trim().toLowerCase() + if (token.length > 0 && token in dest) { + delete dest[token] + } + } +} + +function isValidContentLength (value) { + return typeof value === 'string' && DIGITS_ONLY.test(value) +} + +function isFormUrlEncoded (contentType) { + if (contentType === FORM_URLENCODED) { + return true + } + if (typeof contentType !== 'string') { + return false + } + + // media type parameters, e.g: "application/x-www-form-urlencoded; charset=UTF-8" + const paramsIndex = contentType.indexOf(';') + const mediaType = paramsIndex === -1 ? contentType : contentType.slice(0, paramsIndex) + + return mediaType.trim().toLowerCase() === FORM_URLENCODED +} + +function isEmptyPlainObject (value) { + const proto = Object.getPrototypeOf(value) + if (proto !== Object.prototype && proto !== null) { + return false + } + + // eslint-disable-next-line no-unreachable-loop + for (const key in value) { // eslint-disable-line no-unused-vars + return false + } + + return true +} + +/** + * Serializes an already parsed body back to application/x-www-form-urlencoded. + * Arrays are sent as repeated keys ("a=1&a=2") and nested objects using the + * bracket notation ("a[b]=1"), which is what "qs"/"body-parser" understand. + */ +function toFormUrlEncoded (body) { + const params = new URLSearchParams() + const keys = Object.keys(body) + + for (let i = 0; i < keys.length; i++) { + appendFormValue(params, keys[i], body[keys[i]], 0) + } + + return params.toString() +} + +function appendFormValue (params, key, value, depth) { + if (value === undefined || value === null) { + params.append(key, '') + } else if (value instanceof Date) { + params.append(key, value.toISOString()) + } else if (typeof value !== 'object' || depth >= FORM_MAX_DEPTH) { + params.append(key, String(value)) + } else if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + if (value[i] !== null && typeof value[i] === 'object') { + appendFormValue(params, key + '[' + i + ']', value[i], depth + 1) + } else { + appendFormValue(params, key, value[i], depth + 1) + } + } + } else { + const keys = Object.keys(value) + for (let i = 0; i < keys.length; i++) { + appendFormValue(params, key + '[' + keys[i] + ']', value[keys[i]], depth + 1) } } - return dest } function buildURL (source = '', reqBase) { + if (typeof source !== 'string') { + throw new TypeError('The proxy source must be a string') + } + + // only the path is inspected, query string and fragment are free-form + let pathEnd = source.indexOf('?') + const hashIndex = source.indexOf('#') + if (hashIndex !== -1 && (pathEnd === -1 || hashIndex < pathEnd)) { + pathEnd = hashIndex + } + if (UNSAFE_PATH.test(pathEnd === -1 ? source : source.slice(0, pathEnd))) { + throw new Error('Unsafe path: dot segments, backslashes and control characters are not allowed') + } + + // leading and trailing spaces are removed by the URL parser, a trailing + // ".. " would be resolved as a dot segment + if (source.charCodeAt(0) === 32 || source.charCodeAt(source.length - 1) === 32) { + throw new Error('Unsafe path: leading and trailing spaces are not allowed') + } + + // Sources starting with "//" are network-path references: the URL parser + // reads the first segment as the host (SSRF). Collapsing the slashes would + // forward a path different than the one seen by the caller ("//admin" does + // not match an "/admin" access control rule, but would reach "/admin"). // issue ref: https://github.com/fastify/fast-proxy/issues/42, https://github.com/fastify/fast-proxy/issues/76 - let i = 0 - while (source[i] === '/') { - i++ + if (source.charCodeAt(0) === 47 && source.charCodeAt(1) === 47) { + throw new Error('Unsafe path: multiple leading slashes are not allowed') } - const cleanSource = i > 0 ? '/' + source.substring(i) : source - const url = new URL(cleanSource, reqBase) + const url = new URL(source, reqBase) + + // only protocols the proxy is able to speak are allowed + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error('Unsupported protocol') + } // SSRF prevention: validate that the resolved URL stays within the // configured base origin. Absolute-form HTTP requests (RFC 7230 §5.3.2) // set req.url to the full URL, which bypasses base via the URL constructor. - if (reqBase) { - const baseUrl = new URL(reqBase) - if (url.origin !== baseUrl.origin) { - throw new Error('SSRF prevention: source "' + source + '" resolves to origin "' + url.origin + '" but base origin is "' + baseUrl.origin + '"') - } + if (reqBase && url.origin !== getBaseOrigin(reqBase)) { + throw new Error('SSRF prevention: source resolves to an origin different than the base origin') } return url } module.exports = { + buildRequestHeaders, copyHeaders, stripHttp1ConnectionHeaders, - filterPseudoHeaders, - filterHeaders, + isValidContentLength, + isFormUrlEncoded, + isEmptyPlainObject, + toFormUrlEncoded, buildURL, populateHeaders } diff --git a/package.json b/package.json index 8bf0ff3..de35359 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fast-proxy-lite", - "version": "1.1.3", + "version": "1.2.0", "description": "Forward your HTTP request to another server.", "main": "index.js", "types": "index.d.ts", diff --git a/test/10.build-url.test.js b/test/10.build-url.test.js index e717ba2..8ef1048 100644 --- a/test/10.build-url.test.js +++ b/test/10.build-url.test.js @@ -43,19 +43,11 @@ describe('buildURL', () => { expect(url.href).to.equal('http://localhost/hi') }) - it('should sanitize invalid source (2 params) - //10.0.0.10/hi', function () { - const url = buildURL('//10.0.0.10/hi', 'http://localhost') - - expect(url.origin).to.equal('http://localhost') - expect(url.pathname).to.equal('/10.0.0.10/hi') - expect(url.href).to.equal('http://localhost/10.0.0.10/hi') + it('should reject invalid source (2 params) - //10.0.0.10/hi', function () { + expect(() => buildURL('//10.0.0.10/hi', 'http://localhost')).to.throw(/Unsafe path/) }) - it('should sanitize invalid source (2 params) - //httpbin.org/hi', function () { - const url = buildURL('//httpbin.org/hi', 'http://localhost') - - expect(url.origin).to.equal('http://localhost') - expect(url.pathname).to.equal('/httpbin.org/hi') - expect(url.href).to.equal('http://localhost/httpbin.org/hi') + it('should reject invalid source (2 params) - //httpbin.org/hi', function () { + expect(() => buildURL('//httpbin.org/hi', 'http://localhost')).to.throw(/Unsafe path/) }) }) diff --git a/test/13.security.test.js b/test/13.security.test.js index e246b6f..7943249 100644 --- a/test/13.security.test.js +++ b/test/13.security.test.js @@ -28,9 +28,8 @@ describe('Security: buildURL SSRF prevention', () => { expect(url.href).to.equal('http://target.com/api') }) - it('should sanitize protocol-relative within base', () => { - const url = buildURL('//evil.com/hi', 'http://localhost') - expect(url.origin).to.equal('http://localhost') + it('should block protocol-relative sources', () => { + expect(() => buildURL('//evil.com/hi', 'http://localhost')).to.throw(/Unsafe path/) }) }) diff --git a/test/14.hardening.test.js b/test/14.hardening.test.js new file mode 100644 index 0000000..b1ebbc4 --- /dev/null +++ b/test/14.hardening.test.js @@ -0,0 +1,1466 @@ +/* global describe, it, before, after */ +'use strict' + +const { expect } = require('chai') +const http = require('http') +const http2 = require('http2') +const net = require('net') +const { EventEmitter } = require('events') +const { PassThrough } = require('stream') +const bodyParser = require('body-parser') +const fastProxy = require('../index') + +function listen (server, host = '127.0.0.1') { + return new Promise(resolve => server.listen(0, host, () => resolve(server.address().port))) +} + +// tracks the raw connections of a server, so it can always be closed +function track (server) { + server.sockets = new Set() + server.on('connection', socket => { + server.sockets.add(socket) + socket.on('close', () => server.sockets.delete(socket)) + }) + + return server +} + +function closeServer (server) { + return new Promise(resolve => { + server.close(resolve) + if (server.closeAllConnections) server.closeAllConnections() + if (server.sockets) server.sockets.forEach(socket => socket.destroy()) + }) +} + +// echoes request data as plain text, never as markup +function echo (res, text) { + res.setHeader('content-type', 'text/plain; charset=utf-8') + res.setHeader('x-content-type-options', 'nosniff') + res.end(text) +} + +function sleep (ms) { + return new Promise(resolve => setTimeout(resolve, ms)) +} + +// sends a raw payload and resolves with everything received until the +// connection is closed by the peer, or the timeout expires +function raw (port, payload, timeout = 1000) { + return new Promise(resolve => { + const socket = net.connect(port, '127.0.0.1', () => socket.write(Buffer.from(payload, 'latin1'))) + let data = '' + let closedByPeer = false + const timer = setTimeout(() => socket.destroy(), timeout) + socket.on('data', chunk => { data += chunk.toString('latin1') }) + socket.on('end', () => { closedByPeer = true }) + socket.on('error', () => { closedByPeer = true }) + socket.on('close', () => { + clearTimeout(timer) + resolve({ data, closedByPeer, status: +data.slice(9, 12), body: data.slice(data.indexOf('\r\n\r\n') + 4) }) + }) + }) +} + +// remote server that records the exact bytes it receives +function wireServer (reply = 'HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok') { + const state = { wire: '' } + const server = track(net.createServer(socket => { + socket.on('error', () => {}) + socket.on('data', chunk => { + state.wire += chunk.toString('latin1') + clearTimeout(socket.timer) + socket.timer = setTimeout(() => socket.write(reply), 50) + }) + })) + state.server = server + + return state +} + +describe('Hardening: request target validation', () => { + const { buildURL } = require('../lib/utils') + + it('should reject dot segments', () => { + const sources = [ + '/service/../admin', + '/service/..', + '/service/./admin', + '/service/.', + '/service/%2e%2e/admin', + '/service/%2E%2E/admin', + '/service/.%2e/admin', + '/service/%2e./admin', + '/service/%2e/admin', + '../admin', + '..', + '.', + 'http://localhost/service/../admin' + ] + for (const source of sources) { + expect(() => buildURL(source, 'http://localhost'), source).to.throw(/Unsafe path/) + } + }) + + it('should reject backslashes and control characters in the path', () => { + for (const source of ['/service\\admin', '/service/x\\..\\..\\admin', '\\\\evil.com/x', '/\\evil.com', '/ser\tvice', '/.\n./admin', '/a\r/b']) { + expect(() => buildURL(source, 'http://localhost'), JSON.stringify(source)).to.throw(/Unsafe path/) + } + }) + + it('should reject multiple leading slashes', () => { + for (const source of ['//admin', '///admin/secret', '//evil.com/x', '//']) { + expect(() => buildURL(source, 'http://localhost'), source).to.throw(/Unsafe path/) + } + }) + + it('should reject control characters and surrounding spaces', () => { + for (const source of ['/public/..\f', '/public/..\v', '/public/..\x00', '/public/..\x1f', '/public/.. ', ' /public', '/pub\x7flic']) { + expect(() => buildURL(source, 'http://localhost'), JSON.stringify(source)).to.throw(/Unsafe path/) + } + }) + + it('should not reject safe paths', () => { + const sources = { + '/.well-known/security.txt': '/.well-known/security.txt', + '/a/..b/c': '/a/..b/c', + '/a/.../c': '/a/.../c', + '/a/b..': '/a/b..', + '/a/%2e%2ehidden': '/a/%2e%2ehidden', + '/a?next=/../b&c=\\d': '/a', + '/a#/../b': '/a', + '/a%2f..%2fb': '/a%2f..%2fb', + '/a%5c..%5cb': '/a%5c..%5cb', + '/a//b': '/a//b', + '/a b/.. c': '/a%20b/..%20c', + '': '/' + } + for (const source of Object.keys(sources)) { + expect(buildURL(source, 'http://localhost').pathname, source).to.equal(sources[source]) + } + }) + + it('should keep the query string untouched', () => { + expect(buildURL('/a?next=/../b&c=\\d', 'http://localhost').search).to.equal('?next=/../b&c=\\d') + }) + + it('should reject unsupported protocols', () => { + for (const source of ['ftp://example.com/x', 'file:///etc/passwd', 'ws://example.com/', 'javascript:alert(1)', 'data:text/plain,hi']) { + expect(() => buildURL(source), source).to.throw() + } + expect(() => buildURL('/x', 'ftp://example.com')).to.throw(/Unsupported protocol/) + }) + + it('should reject non string sources', () => { + expect(() => buildURL({ toString: () => '/x' }, 'http://localhost')).to.throw(TypeError) + }) + + it('should block origin escapes', () => { + const sources = [ + 'http://localhost@evil.com/', + 'http://localhost:81/', + 'https://localhost/', + ' //evil.com/x', + 'http:evil.com', + '//evil.com' + ] + for (const source of sources) { + let origin + try { + origin = buildURL(source, 'http://localhost').origin + } catch (err) { + continue + } + expect(origin, source).to.equal('http://localhost') + } + }) + + it('should allow same origin absolute sources', () => { + expect(buildURL('http://localhost/hi', 'http://localhost').href).to.equal('http://localhost/hi') + }) +}) + +describe('Hardening: utils', () => { + const utils = require('../lib/utils') + + it('should not forward hop-by-hop, framing and pseudo request headers', () => { + const headers = utils.buildRequestHeaders({ + ':method': 'GET', + ':path': '/', + host: 'gateway', + connection: 'upgrade, x-custom', + 'keep-alive': 'timeout=5', + 'proxy-connection': 'keep-alive', + 'proxy-authorization': 'Basic Zm9v', + te: 'trailers', + trailer: 'x-checksum', + 'transfer-encoding': 'chunked', + Upgrade: 'websocket', + 'http2-settings': 'AAMAAABkAAQCAAAAAAIAAAAA', + expect: '100-continue', + 'Content-Length': '10', + 'x-custom': 'kept', + Authorization: 'Bearer token', + cookie: 'a=1' + }) + + expect(headers).to.deep.equal({ + host: 'gateway', + 'x-custom': 'kept', + authorization: 'Bearer token', + cookie: 'a=1' + }) + }) + + it('should not let clients remove headers through the Connection header', () => { + const headers = utils.buildRequestHeaders({ connection: 'x-user-id', 'x-user-id': '1' }) + + expect(headers).to.deep.equal({ 'x-user-id': '1' }) + }) + + it('should strip hop-by-hop response headers, including the ones nominated by Connection', () => { + const headers = utils.stripHttp1ConnectionHeaders({ + Connection: 'Keep-Alive, X-Internal , , constructor', + 'Keep-Alive': 'timeout=5', + 'X-Internal': 'secret', + Trailer: 'x-checksum', + 'Proxy-Authenticate': 'Basic', + 'Transfer-Encoding': 'chunked', + 'Content-Type': 'text/plain', + 'set-cookie': ['a=1', 'b=2'] + }) + + expect(headers).to.deep.equal({ 'content-type': 'text/plain', 'set-cookie': ['a=1', 'b=2'] }) + }) + + it('should preserve values of mixed case response headers', () => { + expect(utils.stripHttp1ConnectionHeaders({ 'X-Mixed': 'Case', connection: 'close' })).to.deep.equal({ 'x-mixed': 'Case' }) + }) + + it('should skip empty header values when copying', () => { + const set = {} + utils.copyHeaders({ a: '1', b: undefined, c: null, ':status': 200 }, { setHeader: (name, value) => { set[name] = value } }) + + expect(set).to.deep.equal({ a: '1' }) + }) + + it('should detect form urlencoded content type', () => { + expect(utils.isFormUrlEncoded('application/x-www-form-urlencoded')).to.equal(true) + expect(utils.isFormUrlEncoded('application/x-www-form-urlencoded; charset=UTF-8')).to.equal(true) + expect(utils.isFormUrlEncoded('Application/X-WWW-Form-Urlencoded ;charset=utf-8')).to.equal(true) + expect(utils.isFormUrlEncoded('application/x-www-form-urlencoded-not')).to.equal(false) + expect(utils.isFormUrlEncoded('application/json')).to.equal(false) + expect(utils.isFormUrlEncoded(undefined)).to.equal(false) + }) + + it('should serialize form urlencoded payloads', () => { + expect(utils.toFormUrlEncoded({ a: '1', b: ['2', '3'], c: { d: 'x y', e: { f: true } }, g: null, h: [{ i: 1 }], j: new Date(0) })) + .to.equal('a=1&b=2&b=3&c%5Bd%5D=x+y&c%5Be%5D%5Bf%5D=true&g=&h%5B0%5D%5Bi%5D=1&j=1970-01-01T00%3A00%3A00.000Z') + }) + + it('should not overflow on cyclic form payloads', () => { + const body = { a: 1 } + body.self = body + + expect(utils.toFormUrlEncoded(body)).to.be.a('string') + }) + + it('should detect empty plain objects', () => { + expect(utils.isEmptyPlainObject({})).to.equal(true) + expect(utils.isEmptyPlainObject(Object.create(null))).to.equal(true) + expect(utils.isEmptyPlainObject({ a: 1 })).to.equal(false) + expect(utils.isEmptyPlainObject([])).to.equal(false) + expect(utils.isEmptyPlainObject(new Date())).to.equal(false) + }) + + it('should validate content-length values', () => { + expect(utils.isValidContentLength('0')).to.equal(true) + expect(utils.isValidContentLength('1024')).to.equal(true) + expect(utils.isValidContentLength('10, 10')).to.equal(false) + expect(utils.isValidContentLength('-1')).to.equal(false) + expect(utils.isValidContentLength('0x10')).to.equal(false) + expect(utils.isValidContentLength('')).to.equal(false) + expect(utils.isValidContentLength(undefined)).to.equal(false) + }) +}) + +describe('Hardening: invalid targets do not crash the process', () => { + let gateway, port, proxy, close + + before(async () => { + ({ proxy, close } = fastProxy({})) + gateway = http.createServer((req, res) => proxy(req, res, req.url, {})) + port = await listen(gateway) + }) + + after(async () => { + close() + await closeServer(gateway) + }) + + it('should 400 on unsupported protocol (absolute-form request, no base)', async () => { + for (const target of ['ftp://example.com/x', 'file:///etc/passwd', 'ws://example.com/x']) { + const res = await raw(port, `GET ${target} HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n`) + expect(res.status, target).to.equal(400) + } + }) + + it('should 405 on CONNECT', async () => { + const { proxy, close } = fastProxy({ base: 'http://127.0.0.1:1' }) + const gateway = http.createServer() + // CONNECT requests are not emitted as regular requests by the http server + gateway.on('connect', (req, socket) => { + const res = new http.ServerResponse(req) + res.assignSocket(socket) + res.on('finish', () => socket.end()) + proxy(req, res, '/x', {}) + }) + const res = await raw(await listen(gateway), 'CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n') + + expect(res.status).to.equal(405) + + close() + await closeServer(gateway) + }) + + it('should 400 on relative source when base is not set', async () => { + const res = await raw(port, 'GET /hi HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n') + expect(res.status).to.equal(400) + }) +}) + +describe('Hardening: route prefix escape', () => { + let gateway, service, port, proxy, close + + before(async () => { + service = http.createServer((req, res) => echo(res, req.url)) + const servicePort = await listen(service); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + servicePort })) + gateway = http.createServer((req, res) => { + if (req.url.startsWith('/admin') || (!req.url.startsWith('/public/') && !req.url.startsWith('//'))) { + res.statusCode = 403 + res.end() + } else { + proxy(req, res, req.url, {}) + } + }) + port = await listen(gateway) + }) + + after(async () => { + close() + await closeServer(gateway) + await closeServer(service) + }) + + it('should not forward requests escaping the routed prefix', async () => { + const targets = [ + '/public/../admin', + '/public/%2e%2e/admin', + '/public/.%2E/admin', + '/public/x/..\\..\\admin', + '/public/./../admin', + '/public/x/../../admin?a=1', + '//admin', + '///admin/secret' + ] + for (const target of targets) { + const res = await raw(port, `GET ${target} HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n`) + expect(res.status, target).to.equal(400) + } + }) + + it('should forward regular requests', async () => { + const res = await raw(port, 'GET /public/..hidden/.x?path=/../y HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n') + expect(res.status).to.equal(200) + expect(res.body).to.equal('/public/..hidden/.x?path=/../y') + }) +}) + +describe('Hardening: request headers and framing (HTTP/1 source)', () => { + let gateway, parsedGateway, remote, port, parsedPort, proxy, close + + before(async () => { + remote = wireServer() + const remotePort = await listen(remote.server); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + remotePort })) + + gateway = http.createServer((req, res) => proxy(req, res, req.url, {})) + port = await listen(gateway) + + const parsers = [bodyParser.json(), bodyParser.urlencoded({ extended: true }), bodyParser.raw(), bodyParser.text()] + parsedGateway = http.createServer((req, res) => { + let i = 0 + const next = () => i < parsers.length ? parsers[i++](req, res, next) : proxy(req, res, req.url, {}) + next() + }) + parsedPort = await listen(parsedGateway) + }) + + after(async () => { + close() + await closeServer(gateway) + await closeServer(parsedGateway) + await closeServer(remote.server) + }) + + async function send (gatewayPort, payload) { + remote.wire = '' + const res = await raw(gatewayPort, payload) + const [head, ...body] = remote.wire.split('\r\n\r\n') + + return { res, head: head.toLowerCase(), body: body.join('\r\n\r\n'), wire: remote.wire } + } + + it('should not forward hop-by-hop request headers', async () => { + const { res, head } = await send(port, 'GET /x HTTP/1.1\r\nHost: a\r\nConnection: close, x-secret\r\nKeep-Alive: timeout=1\r\nTE: trailers\r\nTrailer: x-sum\r\nProxy-Authorization: Basic Zm9v\r\nProxy-Connection: close\r\nX-Secret: kept\r\n\r\n') + + expect(res.status).to.equal(200) + expect(head).to.include('connection: keep-alive') + expect(head).to.not.include('connection: close') + expect(head).to.not.include('timeout=1') + expect(head).to.not.include('te:') + expect(head).to.not.include('trailer:') + expect(head).to.not.include('proxy-authorization') + expect(head).to.not.include('proxy-connection') + expect(head).to.include('x-secret: kept') + }) + + it('should not forward upgrade requests to the remote', async () => { + const { res, head } = await send(port, 'GET /x HTTP/1.1\r\nHost: a\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n') + + expect(res.status).to.equal(200) + expect(head).to.not.include('upgrade') + }) + + it('should not forward Expect header', async () => { + const { res, head, body } = await send(port, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nExpect: 100-continue\r\nContent-Length: 5\r\n\r\nhello') + + expect(res.data).to.include('200 OK') + expect(head).to.not.include('expect') + expect(body).to.equal('hello') + }) + + it('should ignore payload and framing headers on GET', async () => { + const { res, head, body } = await send(port, 'GET /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n') + + expect(res.status).to.equal(200) + expect(head).to.not.include('transfer-encoding') + expect(head).to.not.include('content-length') + expect(body).to.equal('') + }) + + it('should stream content-length delimited payloads', async () => { + const { res, head, body } = await send(port, 'DELETE /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Length: 5\r\n\r\nhello') + + expect(res.status).to.equal(200) + expect(head).to.include('content-length: 5') + expect(head).to.not.include('transfer-encoding') + expect(body).to.equal('hello') + }) + + it('should re-frame chunked payloads', async () => { + for (const method of ['POST', 'DELETE', 'OPTIONS', 'PATCH']) { + const { res, head, body } = await send(port, `${method} /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nhel\r\n2\r\nlo\r\n0\r\n\r\n`) + + expect(res.status, method).to.equal(200) + expect(head, method).to.include('transfer-encoding: chunked') + expect(head, method).to.not.include('content-length') + expect(body.replace(/\r\n/g, '|'), method).to.match(/^(?:[0-9a-f]+\|[a-z]+\|)+0\|\|$/) + expect(body.replace(/[0-9a-f]+\r\n|\r\n/g, ''), method).to.equal('hello') + } + }) + + it('should not send a payload for requests without one', async () => { + const post = await send(port, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n') + expect(post.res.status).to.equal(200) + expect(post.head).to.include('content-length: 0') + expect(post.head).to.not.include('transfer-encoding') + expect(post.body).to.equal('') + + const del = await send(port, 'DELETE /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n') + expect(del.res.status).to.equal(200) + expect(del.head).to.not.include('transfer-encoding') + expect(del.body).to.equal('') + }) + + it('should never send both content-length and transfer-encoding (parsed chunked payload)', async () => { + const { res, head, body } = await send(parsedPort, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n7\r\n{"a":1}\r\n0\r\n\r\n') + + expect(res.status).to.equal(200) + expect(head).to.include('content-length: 7') + expect(head).to.not.include('transfer-encoding') + expect(body).to.equal('{"a":1}') + }) + + it('should forward form urlencoded payloads having media type parameters', async () => { + const payload = 'a=1&b=2' + const { head, body } = await send(parsedPort, `POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded; charset=UTF-8\r\nContent-Length: ${payload.length}\r\n\r\n${payload}`) + + expect(head).to.include('content-type: application/x-www-form-urlencoded; charset=utf-8') + expect(body).to.equal('a=1&b=2') + }) + + it('should forward nested form urlencoded payloads', async () => { + const payload = 'a[b]=1&c=2&c=3' + const { body } = await send(parsedPort, `POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: ${payload.length}\r\n\r\n${payload}`) + + expect(decodeURIComponent(body)).to.equal('a[b]=1&c=2&c=3') + }) + + it('should forward binary payloads untouched', async () => { + const { head, body } = await send(parsedPort, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/octet-stream\r\nContent-Length: 4\r\n\r\n\x00\x01\xfe\xff') + + expect(head).to.include('content-length: 4') + expect(head).to.include('content-type: application/octet-stream') + expect(body).to.equal('\x00\x01\xfe\xff') + }) + + it('should not forward content-encoding of payloads decoded by the body parsers', async () => { + const zlib = require('zlib') + const json = zlib.gzipSync('{"hello":"world"}').toString('latin1') + const parsed = await send(parsedPort, `POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Encoding: gzip\r\nContent-Length: ${json.length}\r\n\r\n${json}`) + + expect(parsed.head).to.not.include('content-encoding') + expect(parsed.head).to.include('content-length: 17') + expect(parsed.body).to.equal('{"hello":"world"}') + + const binary = zlib.gzipSync('binary payload').toString('latin1') + const raw = await send(parsedPort, `POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/octet-stream\r\nContent-Encoding: gzip\r\nContent-Length: ${binary.length}\r\n\r\n${binary}`) + + expect(raw.head).to.not.include('content-encoding') + expect(raw.body).to.equal('binary payload') + + // not decoded: streamed as received + const streamed = await send(port, `POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Encoding: gzip\r\nContent-Length: ${json.length}\r\n\r\n${json}`) + + expect(streamed.head).to.include('content-encoding: gzip') + expect(streamed.body).to.equal(json) + }) + + it('should stream payloads the body parsers did not handle', async () => { + const { head, body } = await send(parsedPort, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: text/xml\r\nContent-Length: 8\r\n\r\n1') + + expect(head).to.include('content-length: 8') + expect(body).to.equal('1') + }) + + it('should forward parsed empty JSON objects', async () => { + const { head, body } = await send(parsedPort, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}') + + expect(head).to.include('content-length: 2') + expect(body).to.equal('{}') + }) + + it('should forward parsed text payloads', async () => { + const { head, body } = await send(parsedPort, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Type: text/plain\r\nContent-Length: 6\r\n\r\nh\xc3\xa9llo') + + expect(head).to.include('content-length: 6') + expect(body).to.equal('h\xc3\xa9llo') + }) +}) + +describe('Hardening: request body shapes', () => { + let gateway, remote, port, proxy, close, prepare, proxyOpts + + before(async () => { + remote = wireServer() + const remotePort = await listen(remote.server); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + remotePort })) + + gateway = http.createServer((req, res) => { + prepare(req, () => proxy(req, res, req.url, proxyOpts)) + }) + port = await listen(gateway) + }) + + after(async () => { + close() + await closeServer(gateway) + await closeServer(remote.server) + }) + + async function send (prepareFn, opts = {}) { + remote.wire = '' + prepare = prepareFn + proxyOpts = opts + const res = await raw(port, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Length: 5\r\n\r\nhello') + const [head, ...body] = remote.wire.split('\r\n\r\n') + + return { res, head: head.toLowerCase(), body: body.join('\r\n\r\n') } + } + + it('should forward typed arrays', async () => { + const { head, body } = await send((req, next) => { + req.body = new Uint8Array([104, 105]) + next() + }) + + expect(head).to.include('content-length: 2') + expect(body).to.equal('hi') + }) + + it('should forward empty strings', async () => { + const { head, body } = await send((req, next) => { + req.body = '' + next() + }) + + expect(head).to.include('content-length: 0') + expect(body).to.equal('') + }) + + it('should forward JSON primitives', async () => { + const { head, body } = await send((req, next) => { + req.body = 0 + next() + }) + + expect(head).to.include('content-length: 1') + expect(head).to.include('content-type: application/json') + expect(body).to.equal('0') + }) + + it('should never frame custom streams using the client content-length', async () => { + // e.g: a decompressed version of the client payload, the client + // content-length (5) does not describe it + const smuggled = 'hello' + 'GET /admin HTTP/1.1\r\nHost: internal\r\n\r\n' + const { head, body } = await send((req, next) => { + req.body = new PassThrough() + req.body.end(smuggled) + next() + }) + + expect(head).to.include('transfer-encoding: chunked') + expect(head).to.not.include('content-length') + expect(body).to.equal(smuggled.length.toString(16) + '\r\n' + smuggled + '\r\n0\r\n\r\n') + }) + + it('should let hooks define the length of custom streams', async () => { + const { head, body } = await send((req, next) => { + req.body = new PassThrough() + req.body.end('custom') + next() + }, { + rewriteRequestHeaders: (req, headers) => { + delete headers['transfer-encoding'] + headers['content-length'] = '6' + + return headers + } + }) + + expect(head).to.include('content-length: 6') + expect(head).to.not.include('transfer-encoding') + expect(body).to.equal('custom') + }) + + it('should never send both framing headers when a hook adds transfer-encoding', async () => { + const { head, body } = await send((req, next) => next(), { + rewriteRequestHeaders: (req, headers) => { + headers['transfer-encoding'] = 'chunked' + + return headers + } + }) + + expect(head).to.include('transfer-encoding: chunked') + expect(head).to.not.include('content-length') + expect(body).to.equal('5\r\nhello\r\n0\r\n\r\n') + }) + + it('should keep content-encoding of raw payloads that were not decoded', async () => { + const { head, body } = await send((req, next) => { + req.headers['content-encoding'] = 'gzip' + req.body = Buffer.from('12345') + next() + }) + + expect(head).to.include('content-encoding: gzip') + expect(body).to.equal('12345') + }) + + it('should 400 on payloads that can not be serialized', async () => { + const cyclic = {} + cyclic.self = cyclic + for (const payload of [{ id: BigInt(10) }, cyclic, { toJSON () { throw new Error('boom') } }]) { + const { res } = await send((req, next) => { + req.body = payload + next() + }) + + expect(res.status).to.equal(400) + expect(remote.wire).to.equal('') + } + }) + + it('should not send a payload when the request was already consumed', async () => { + const { res, head, body } = await send((req, next) => { + req.resume() + req.on('end', () => setImmediate(next)) + }) + + expect(res.status).to.equal(200) + expect(head).to.include('content-length: 0') + expect(body).to.equal('') + }) + + it('should keep the request framed when a hook removes the framing headers', async () => { + const { head, body } = await send((req, next) => next(), { + rewriteRequestHeaders: (req, headers) => { + delete headers['content-length'] + + return headers + } + }) + + expect(head).to.include('transfer-encoding: chunked') + expect(body).to.equal('5\r\nhello\r\n0\r\n\r\n') + }) + + it('should respect framing headers set by a hook using a different case', async () => { + const { head, body } = await send((req, next) => next(), { + rewriteRequestHeaders: (req, headers) => { + delete headers['content-length'] + headers['Content-Length'] = '5' + + return headers + } + }) + + expect(head).to.include('content-length: 5') + expect(head).to.not.include('transfer-encoding') + expect(body).to.equal('hello') + }) + + it('should tolerate hooks returning nothing', async () => { + const { res, body } = await send((req, next) => next(), { + rewriteRequestHeaders: () => {}, + rewriteHeaders: () => {} + }) + + expect(res.status).to.equal(200) + expect(body).to.equal('hello') + }) + + it('should 400 when the request can not be represented to the remote', async () => { + const { res } = await send((req, next) => next(), { + rewriteRequestHeaders: (req, headers) => { + headers['x-invalid'] = 'line\r\nbreak' + + return headers + } + }) + + expect(res.status).to.equal(400) + expect(remote.wire).to.equal('') + }) +}) + +describe('Hardening: request smuggling (HTTP/2 source)', () => { + let gateway, remote, client, proxy, close + + before(async () => { + remote = wireServer('HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\nKeep-Alive: timeout=5\r\nX-Remote: 1\r\n\r\nok') + const remotePort = await listen(remote.server); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + remotePort })) + + gateway = http2.createServer((req, res) => proxy(req, res, req.url, {})) + const port = await listen(gateway) + client = http2.connect('http://127.0.0.1:' + port) + }) + + after(async () => { + close() + await new Promise(resolve => client.close(resolve)) + await closeServer(gateway) + await closeServer(remote.server) + }) + + function send (headers, payload) { + remote.wire = '' + + return new Promise((resolve, reject) => { + const req = client.request(headers, { endStream: payload === undefined }) + let status + let resHeaders + let body = '' + req.on('response', h => { + status = h[':status'] + resHeaders = h + }) + req.on('data', chunk => { body += chunk }) + req.on('end', () => resolve({ status, headers: resHeaders, body, wire: remote.wire })) + req.on('error', reject) + if (payload !== undefined) req.end(payload) + }) + } + + it('should frame payloads having no content-length', async () => { + const smuggled = 'GET /admin HTTP/1.1\r\nHost: internal\r\n\r\n' + for (const method of ['DELETE', 'OPTIONS', 'POST', 'PUT']) { + const res = await send({ ':method': method, ':path': '/x' }, smuggled) + const [head, ...rest] = res.wire.split('\r\n\r\n') + const body = rest.join('\r\n\r\n') + + expect(res.status, method).to.equal(200) + expect(head.toLowerCase(), method).to.include('transfer-encoding: chunked') + // the payload must be chunk encoded, not written as a second request + expect(body.startsWith(smuggled.length.toString(16) + '\r\n' + smuggled), method).to.equal(true) + expect(body.endsWith('\r\n0\r\n\r\n'), method).to.equal(true) + } + }) + + it('should forward content-length delimited payloads', async () => { + const res = await send({ ':method': 'DELETE', ':path': '/x', 'content-length': '5' }, 'hello') + const [head, body] = res.wire.split('\r\n\r\n') + + expect(res.status).to.equal(200) + expect(head.toLowerCase()).to.include('content-length: 5') + expect(head.toLowerCase()).to.not.include('transfer-encoding') + expect(body).to.equal('hello') + }) + + it('should reject methods that are not upper case', async () => { + for (const method of ['delete', 'Delete', 'get', 'post', 'connect']) { + const res = await send({ ':method': method, ':path': '/x' }) + + expect(res.status, method).to.equal(400) + expect(res.wire, method).to.equal('') + } + }) + + it('should 502 on remote status codes not allowed in HTTP/2', async () => { + for (const statusLine of ['HTTP/1.1 600 Weird', 'HTTP/1.1 999 Weird']) { + const remote = track(net.createServer(socket => { + socket.on('error', () => {}) + socket.once('data', () => socket.end(statusLine + '\r\nContent-Length: 2\r\nX-Remote: 1\r\n\r\nok')) + })) + const { proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + await listen(remote) }) + const gateway = http2.createServer((req, res) => proxy(req, res, req.url, {})) + const client = http2.connect('http://127.0.0.1:' + await listen(gateway)) + const res = await new Promise((resolve, reject) => { + const req = client.request({ ':path': '/x' }) + req.on('response', headers => resolve(headers)) + req.on('error', reject) + req.resume() + }) + + expect(res[':status'], statusLine).to.equal(502) + expect(res['x-remote'], statusLine).to.equal(undefined) + + close() + await new Promise(resolve => client.close(resolve)) + await closeServer(gateway) + await closeServer(remote) + } + }) + + it('should reset the stream when the remote response is truncated', async () => { + const replies = [ + 'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n', + 'HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\nhello' + ] + for (const reply of replies) { + const remote = track(net.createServer(socket => { + socket.on('error', () => {}) + socket.once('data', () => { + socket.write(reply) + setTimeout(() => socket.destroy(), 50) + }) + })) + const { proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + await listen(remote) }) + const gateway = http2.createServer((req, res) => proxy(req, res, req.url, {})) + const client = http2.connect('http://127.0.0.1:' + await listen(gateway)) + const res = await new Promise(resolve => { + const req = client.request({ ':path': '/x' }) + let body = '' + let error = null + req.on('data', chunk => { body += chunk }) + req.on('error', err => { error = err }) + req.on('close', () => resolve({ body, error, rstCode: req.rstCode })) + }) + + expect(res.body, reply).to.equal('hello') + expect(res.rstCode, reply).to.not.equal(0) + expect(res.error, reply).to.not.equal(null) + + close() + await new Promise(resolve => client.close(resolve)) + await closeServer(gateway) + await closeServer(remote) + } + }) + + it('should build host from :authority and strip connection headers from the response', async () => { + const res = await send({ ':method': 'GET', ':path': '/x?a=1' }) + + expect(res.status).to.equal(200) + expect(res.body).to.equal('ok') + expect(res.headers['x-remote']).to.equal('1') + expect(res.headers.connection).to.equal(undefined) + expect(res.headers['keep-alive']).to.equal(undefined) + expect(res.wire).to.match(/^GET \/x\?a=1 HTTP\/1\.1\r\n/) + expect(res.wire.toLowerCase()).to.match(/x-forwarded-host: 127\.0\.0\.1:\d+/) + }) +}) + +describe('Hardening: remote failures', () => { + let gateway, port, proxy, close, remote, remotePort, behavior, terminated + + before(async () => { + remote = track(net.createServer(socket => { + socket.on('error', () => {}) + socket.once('data', () => behavior(socket)) + })) + remotePort = await listen(remote); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + remotePort })) + + gateway = http.createServer((req, res) => proxy(req, res, req.url, { + request: { timeout: 200 }, + onClientConnectionTerminated: () => { terminated++ } + })) + port = await listen(gateway) + }) + + after(async () => { + close() + await closeServer(gateway) + await closeServer(remote) + }) + + const GET = 'GET /x HTTP/1.1\r\nHost: a\r\n\r\n' + + it('should not corrupt the response when the remote fails after sending the headers', async () => { + terminated = 0 + behavior = socket => { + socket.write('HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\npartial-body') + setTimeout(() => socket.destroy(), 50) + } + const res = await raw(port, GET, 2000) + + expect(res.status).to.equal(200) + expect(res.body).to.equal('partial-body') + // the truncated response must be signaled by terminating the connection + expect(res.closedByPeer).to.equal(true) + expect(terminated).to.equal(0) + }) + + it('should not corrupt the response when the remote times out after sending the headers', async () => { + behavior = socket => { + socket.write('HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n') + } + const res = await raw(port, GET, 2000) + + expect(res.status).to.equal(200) + expect(res.body).to.equal('5\r\nhello\r\n') + expect(res.closedByPeer).to.equal(true) + }) + + it('should 504 when the remote does not respond in time', async () => { + behavior = () => {} + const res = await raw(port, GET.replace('\r\n\r\n', '\r\nConnection: close\r\n\r\n'), 2000) + + expect(res.status).to.equal(504) + expect(res.body).to.equal('Gateway Timeout') + }) + + it('should 502 on invalid status code', async () => { + for (const statusLine of ['HTTP/1.1 099 Weird', 'HTTP/1.1 000 Zero']) { + behavior = socket => socket.end(statusLine + '\r\nContent-Length: 2\r\nX-Remote: 1\r\n\r\nhi') + const res = await raw(port, GET.replace('\r\n\r\n', '\r\nConnection: close\r\n\r\n'), 2000) + + expect(res.status, statusLine).to.equal(502) + expect(res.body, statusLine).to.equal('Bad Gateway') + expect(res.data.toLowerCase(), statusLine).to.not.include('x-remote') + } + }) + + it('should 502 on malformed response', async () => { + behavior = socket => socket.end('NOT HTTP\r\n\r\n') + const res = await raw(port, GET.replace('\r\n\r\n', '\r\nConnection: close\r\n\r\n'), 2000) + + expect(res.status).to.equal(502) + expect(res.body).to.equal('Bad Gateway') + }) + + it('should 502 instead of hanging when the remote switches protocols', async () => { + behavior = socket => socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n') + const res = await raw(port, GET.replace('\r\n\r\n', '\r\nConnection: close\r\n\r\n'), 2000) + + expect(res.status).to.equal(502) + }) + + it('should 503 when the remote is not available, also for requests having a payload', async () => { + const { proxy, close } = fastProxy({ base: 'http://127.0.0.1:1' }) + const gateway = http.createServer((req, res) => proxy(req, res, req.url, {})) + const port = await listen(gateway) + + const res = await raw(port, 'POST /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\nContent-Length: 5\r\n\r\nhello', 2000) + expect(res.status).to.equal(503) + expect(res.body).to.equal('Service Unavailable') + + close() + await closeServer(gateway) + }) +}) + +describe('Hardening: client connection terminated', () => { + let gateway, port, proxy, close, remote, remoteRequests, remoteClosed, terminated, hook + + before(async () => { + remote = http.createServer((req, res) => { + remoteRequests++ + req.socket.once('close', () => { remoteClosed++ }) + if (req.url === '/slow') { + // never responds + } else { + res.end(Buffer.alloc(1024 * 1024)) + } + }) + const remotePort = await listen(remote); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + remotePort })) + + gateway = http.createServer((req, res) => { + const forward = () => proxy(req, res, req.url, { + onClientConnectionTerminated: (res, err, response) => { + terminated.push({ err, response }) + if (hook) hook(response) + } + }) + + if (req.url === '/late') { + // the client is gone before the request is forwarded + res.on('close', forward) + } else { + forward() + } + }) + port = await listen(gateway) + }) + + after(async () => { + close() + await closeServer(gateway) + await closeServer(remote) + }) + + function reset () { + remoteRequests = 0 + remoteClosed = 0 + terminated = [] + hook = null + } + + it('should abort the remote request when the client goes away', async () => { + reset() + await raw(port, 'GET /slow HTTP/1.1\r\nHost: a\r\n\r\n', 100) + await sleep(200) + + expect(remoteRequests).to.equal(1) + expect(remoteClosed).to.equal(1) + expect(terminated.length).to.equal(1) + expect(terminated[0].err.code).to.equal('ECONNRESET') + expect(terminated[0].response).to.equal(undefined) + }) + + it('should not forward requests of clients that are already gone', async () => { + reset() + await raw(port, 'GET /late HTTP/1.1\r\nHost: a\r\n\r\n', 50) + await raw(port, 'POST /late HTTP/1.1\r\nHost: a\r\nContent-Length: 100\r\n\r\nhello', 50) + await sleep(200) + + expect(remoteRequests).to.equal(0) + expect(terminated.length).to.equal(2) + expect(terminated[0].err.code).to.equal('ECONNRESET') + expect(terminated[0].response).to.equal(undefined) + }) + + it('should abort the remote request when the client goes away while uploading', async () => { + reset() + await raw(port, 'POST /slow HTTP/1.1\r\nHost: a\r\nContent-Length: 100\r\n\r\nhello', 100) + await sleep(200) + + expect(remoteClosed).to.equal(remoteRequests) + expect(terminated.length).to.equal(1) + }) +}) + +describe('Hardening: remote response received after the client is gone', () => { + // the client connection is destroyed right after the request is forwarded, + // the remote response is received before the 'close' event is emitted + async function run (hook) { + const stream = new PassThrough() + stream.statusCode = 200 + stream.headers = {} + const client = { + request () { + const req = new EventEmitter() + req.end = () => process.nextTick(() => { + req.emit('response', stream) + stream.end('payload') + }) + req.destroy = () => {} + + return req + } + } + const terminated = [] + const { proxy, close } = fastProxy({ base: 'http://example.com', requests: { http: client } }) + const gateway = http.createServer((req, res) => { + proxy(req, res, req.url, { + onClientConnectionTerminated: (res, err, response) => { + terminated.push({ err, response }) + if (hook) hook(response) + } + }) + res.socket.destroy() + }) + const port = await listen(gateway) + await raw(port, 'GET /x HTTP/1.1\r\nHost: a\r\n\r\n', 200) + close() + await closeServer(gateway) + + return { terminated, stream } + } + + it('should destroy the response when it is not consumed', async () => { + const { terminated, stream } = await run() + + expect(terminated.length).to.equal(1) + expect(terminated[0].err).to.equal(null) + expect(terminated[0].response.statusCode).to.equal(200) + expect(stream.destroyed).to.equal(true) + }) + + it('should not destroy the response when the hook consumes it', async () => { + let received = '' + let ended = false + const { terminated } = await run(response => { + response.stream.on('data', chunk => { received += chunk }) + response.stream.on('end', () => { ended = true }) + }) + + expect(terminated.length).to.equal(1) + expect(ended).to.equal(true) + expect(received).to.equal('payload') + }) +}) + +describe('Hardening: failing hooks', () => { + let gateway, remote, port, proxy, close, proxyOpts, warnings, remoteClosed + + const onWarning = warning => warnings.push(warning) + + before(async () => { + remote = http.createServer((req, res) => { + req.socket.once('close', () => { remoteClosed++ }) + res.setHeader('x-remote', 'true') + res.setHeader('cache-control', 'public, max-age=3600') + res.end(Buffer.alloc(1024 * 1024)) + }) + const remotePort = await listen(remote); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + remotePort })) + gateway = http.createServer((req, res) => proxy(req, res, req.url, proxyOpts)) + port = await listen(gateway) + process.on('warning', onWarning) + }) + + after(async () => { + process.removeListener('warning', onWarning) + close() + await closeServer(gateway) + await closeServer(remote) + }) + + async function send (opts, timeout) { + warnings = [] + remoteClosed = 0 + proxyOpts = opts + const res = await raw(port, 'GET /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n', timeout) + await sleep(100) + + return res + } + + it('should 500 when rewriteHeaders throws', async () => { + const res = await send({ rewriteHeaders: () => { throw new Error('boom rewriteHeaders') } }) + + expect(res.status).to.equal(500) + expect(res.body).to.equal('Internal Server Error') + expect(remoteClosed).to.equal(1) + expect(warnings.map(w => w.message)).to.deep.equal(['boom rewriteHeaders']) + }) + + it('should 500 when onResponse throws', async () => { + const res = await send({ onResponse: () => { throw new Error('boom onResponse') } }) + + expect(res.status).to.equal(500) + expect(remoteClosed).to.equal(1) + expect(warnings.map(w => w.message)).to.deep.equal(['boom onResponse']) + }) + + it('should not send the remote response headers when onResponse throws', async () => { + const res = await send({ onResponse: () => { throw new Error('boom onResponse') } }) + + expect(res.status).to.equal(500) + expect(res.body).to.include('Internal Server Error') + // the remote "content-length" (1MB) does not describe the error payload + const head = res.data.slice(0, res.data.indexOf('\r\n\r\n')).toLowerCase() + expect(head).to.not.include('content-length') + expect(head).to.not.include('x-remote') + expect(head).to.not.include('cache-control') + }) + + it('should release the remote connection when onClientConnectionTerminated throws', async () => { + const stream = new PassThrough() + stream.statusCode = 200 + stream.headers = {} + const client = { + request () { + const req = new EventEmitter() + req.end = () => process.nextTick(() => req.emit('response', stream)) + req.destroy = () => {} + + return req + } + } + const { proxy, close } = fastProxy({ base: 'http://example.com', requests: { http: client } }) + const gateway = http.createServer((req, res) => { + proxy(req, res, req.url, { onClientConnectionTerminated: () => { throw 'boom terminated' } }) // eslint-disable-line no-throw-literal + res.socket.destroy() + }) + warnings = [] + await raw(await listen(gateway), 'GET /x HTTP/1.1\r\nHost: a\r\n\r\n', 200) + close() + await closeServer(gateway) + + expect(stream.destroyed).to.equal(true) + expect(warnings.map(w => w.message)).to.deep.equal(['boom terminated']) + }) +}) + +describe('Hardening: custom request clients', () => { + // minimal http client double + function fakeClient (handler) { + const calls = [] + + return { + calls, + request (options) { + calls.push(options) + const req = new EventEmitter() + req.end = () => setImmediate(() => handler(req, options)) + req.destroy = () => {} + + return req + } + } + } + + async function run (client, base, requestLine = 'GET /x HTTP/1.1') { + const { proxy, close } = fastProxy({ base, requests: { http: client, https: client } }) + const gateway = http.createServer((req, res) => proxy(req, res, req.url, {})) + const port = await listen(gateway) + const res = await raw(port, requestLine + '\r\nHost: a\r\nConnection: close\r\n\r\n', 2000) + close() + await closeServer(gateway) + + return res + } + + function respond (req, statusCode, headers, body = '') { + const stream = new PassThrough() + stream.statusCode = statusCode + stream.headers = headers + req.emit('response', stream) + stream.end(body) + } + + it('should connect to IPv6 literals without brackets, keeping them in the Host header', async () => { + const client = fakeClient(req => respond(req, 200, {}, 'ok')) + const res = await run(client, 'http://[::1]:3000') + + expect(res.status).to.equal(200) + expect(client.calls[0].hostname).to.equal('::1') + expect(client.calls[0].port).to.equal('3000') + expect(client.calls[0].headers.host).to.equal('[::1]:3000') + }) + + it('should map default ports and hostnames', async () => { + const client = fakeClient(req => respond(req, 200, {}, 'ok')) + await run(client, 'https://example.com') + + expect(client.calls[0].hostname).to.equal('example.com') + expect(client.calls[0].port).to.equal('') + expect(client.calls[0].headers.host).to.equal('example.com') + expect(client.calls[0].path).to.equal('/x') + }) + + it('should forward mixed case response headers', async () => { + const client = fakeClient(req => respond(req, 201, { 'X-Mixed': 'Case', Connection: 'x-hop', 'X-Hop': '1', 'x-undefined': undefined }, 'ok')) + const res = await run(client, 'http://example.com') + + expect(res.status).to.equal(201) + expect(res.data).to.include('x-mixed: Case') + expect(res.data.toLowerCase()).to.not.include('x-hop') + expect(res.data.toLowerCase()).to.not.include('x-undefined') + expect(res.body).to.equal('2\r\nok\r\n0\r\n\r\n') + }) + + it('should 502 on response headers that can not be sent to the client', async () => { + const client = fakeClient(req => respond(req, 200, { 'x-ok': '1', 'x-invalid': 'line\r\nbreak' }, 'ok')) + const res = await run(client, 'http://example.com') + + expect(res.status).to.equal(502) + expect(res.body).to.equal('Bad Gateway') + expect(res.data.toLowerCase()).to.not.include('x-ok') + }) + + it('should 502 on non numeric status codes', async () => { + const client = fakeClient(req => respond(req, '200 OK', {}, 'ok')) + const res = await run(client, 'http://example.com') + + expect(res.status).to.equal(502) + }) + + it('should map error codes to status codes', async () => { + const codes = { ECONNREFUSED: 503, ECONNRESET: 504, ETIMEDOUT: 504, ENOTFOUND: 502, EPIPE: 502, undefined: 502 } + for (const code of Object.keys(codes)) { + const client = fakeClient(req => { + const err = new Error('sensitive internal details') + if (code !== 'undefined') err.code = code + req.emit('error', err) + }) + const res = await run(client, 'http://example.com') + + expect(res.status, code).to.equal(codes[code]) + expect(res.data, code).to.not.include('sensitive') + } + }) + + it('should ignore errors and responses received after the request was settled', async () => { + let lateResponse + const client = fakeClient(req => { + req.emit('error', Object.assign(new Error('first'), { code: 'ECONNREFUSED' })) + req.emit('error', Object.assign(new Error('second'), { code: 'ECONNRESET' })) + lateResponse = new PassThrough() + lateResponse.statusCode = 200 + lateResponse.headers = {} + req.emit('response', lateResponse) + }) + const res = await run(client, 'http://example.com') + + expect(res.status).to.equal(503) + expect(res.body).to.equal('Service Unavailable') + expect(lateResponse.destroyed).to.equal(true) + }) + + it('should abort using abort() when the client does not support destroy()', async () => { + let aborted = false + const client = { + request () { + const req = new EventEmitter() + req.end = () => setImmediate(() => req.emit('timeout')) + req.abort = () => { + aborted = true + req.emit('error', Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' })) + } + + return req + } + } + const res = await run(client, 'http://example.com') + + expect(aborted).to.equal(true) + expect(res.status).to.equal(504) + }) + + it('should not pass proxy options down to the agents', () => { + const { Agent } = http + const seen = [] + http.Agent = function (options) { + seen.push(options) + + return new Agent(options) + } + try { + fastProxy({ base: 'http://example.com', cacheURLs: 10, requests: {}, maxSockets: 5 }).close() + } finally { + http.Agent = Agent + } + + expect(seen[0]).to.deep.equal({ keepAlive: true, keepAliveMsecs: 60000, maxSockets: 5, maxFreeSockets: 2048 }) + }) +}) + +describe('Hardening: query string and URL cache', () => { + let gateway, service, port, proxy, close, servicePort, handler + + before(async () => { + service = http.createServer((req, res) => echo(res, req.headers.host + req.url)) + servicePort = await listen(service); + ({ proxy, close } = fastProxy({ base: 'http://127.0.0.1:' + servicePort })) + gateway = http.createServer((req, res) => handler(req, res)) + port = await listen(gateway) + }) + + after(async () => { + close() + await closeServer(gateway) + await closeServer(service) + }) + + const get = target => raw(port, `GET ${target} HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n`) + + it('should append the original query string to sources having none', async () => { + handler = (req, res) => proxy(req, res, '/rewritten', {}) + + expect((await get('/x?a=1&b=2')).body).to.equal(`127.0.0.1:${servicePort}/rewritten?a=1&b=2`) + expect((await get('/x')).body).to.equal(`127.0.0.1:${servicePort}/rewritten`) + }) + + it('should not forward fragments', async () => { + handler = (req, res) => { + req.url = req.headers['x-url'] + proxy(req, res, '/rewritten', {}) + } + const send = url => raw(port, `GET / HTTP/1.1\r\nHost: a\r\nX-Url: ${url}\r\nConnection: close\r\n\r\n`) + + expect((await send('/x?a=1#frag')).body).to.equal(`127.0.0.1:${servicePort}/rewritten?a=1`) + expect((await send('/x#frag?a=1')).body).to.equal(`127.0.0.1:${servicePort}/rewritten`) + }) + + it('should prefer the source query string and the queryString option', async () => { + handler = (req, res) => proxy(req, res, '/rewritten?c=3', {}) + expect((await get('/x?a=1')).body).to.equal(`127.0.0.1:${servicePort}/rewritten?c=3`) + + handler = (req, res) => proxy(req, res, '/rewritten?c=3', { queryString: 'd=4&e=5' }) + expect((await get('/x?a=1')).body).to.equal(`127.0.0.1:${servicePort}/rewritten?d=4&e=5`) + }) + + it('should not mix cached URLs of different bases', async () => { + const other = http.createServer((req, res) => echo(res, 'other' + req.url)) + const otherPort = await listen(other) + const globalBase = 'http://127.0.0.1:' + servicePort + const otherBase = 'http://127.0.0.1:' + otherPort + + // a request target crafted to look like the cache key of another base + const crafted = otherBase.length + ':' + otherBase + '/x' + handler = (req, res) => proxy(req, res, req.headers['x-source'], { base: req.headers['x-base'] }) + const send = (source, base) => raw(port, `GET / HTTP/1.1\r\nHost: a\r\nX-Source: ${source}\r\n${base ? 'X-Base: ' + base + '\r\n' : ''}Connection: close\r\n\r\n`) + + try { + expect((await send(crafted)).body).to.equal(`127.0.0.1:${servicePort}/${crafted}`) + expect((await send('/x', otherBase)).body).to.equal('other/x') + expect((await send('/x')).body).to.equal(`127.0.0.1:${servicePort}/x`) + expect((await send('/x', otherBase)).body).to.equal('other/x') + // "base + source" concatenations that are equal as plain strings + expect((await send('/x', globalBase + '/a')).body).to.equal(`127.0.0.1:${servicePort}/x`) + expect((await send('/a/x', globalBase)).body).to.equal(`127.0.0.1:${servicePort}/a/x`) + expect((await send('/x', globalBase + '/a')).body).to.equal(`127.0.0.1:${servicePort}/x`) + } finally { + await closeServer(other) + } + }) +})