Visitar URL original
feat: check Content-Length header early when size limit is set by singhvishalkr · Pull Request #1889 · node-fetch/node-fetch · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,20 @@ export default async function fetch(url, options_) {
});
}

// Check Content-Length against size limit early (issue #879)
// This allows rejecting responses that are too large before consuming any body data
if (request.size > 0) {
const contentLength = headers.get('Content-Length');
if (contentLength !== null) {
const length = Number(contentLength);
if (!Number.isNaN(length) && length > request.size) {
reject(new FetchError(`content size at ${request.url} over limit: ${request.size}`, 'max-size'));
finalize();
return;
}
}
}

let body = pump(response_, new PassThrough(), error => {
if (error) {
reject(error);
Expand Down
22 changes: 21 additions & 1 deletion src/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,14 +293,34 @@ export const getNodeRequestOptions = request => {

const search = getSearch(parsedURL);

// HTTP-network fetch step 5
// Prepend Host header if not already present, ensuring it appears first
// like browsers and other HTTP libraries do (issue #1570)
if (!headers.has('Host')) {
headers.set('Host', parsedURL.host);
}

// Build headers object with Host first to match browser behavior
const rawHeaders = headers[Symbol.for('nodejs.util.inspect.custom')]();
const headersWithHostFirst = {};
if ('host' in rawHeaders) {
headersWithHostFirst.host = rawHeaders.host;
}

for (const key of Object.keys(rawHeaders)) {
if (key !== 'host') {
headersWithHostFirst[key] = rawHeaders[key];
}
}

// Pass the full URL directly to request(), but overwrite the following
// options:
const options = {
// Overwrite search to retain trailing ? (issue #776)
path: parsedURL.pathname + search,
// The following options are not expressed in the URL
method: request.method,
headers: headers[Symbol.for('nodejs.util.inspect.custom')](),
headers: headersWithHostFirst,
insecureHTTPParser: request.insecureHTTPParser,
agent
};
Expand Down
10 changes: 10 additions & 0 deletions test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -1805,6 +1805,16 @@ describe('node-fetch', () => {
.and.have.property('type', 'max-size');
});

it('should reject early when Content-Length exceeds size limit', async () => {
const url = `${base}size/content-length`;
const options = {
size: 5
};
return expect(fetch(url, options)).to.eventually.be.rejected
.and.be.an.instanceOf(FetchError)
.and.have.property('type', 'max-size');
});

it('should allow piping response body as stream', async () => {
const url = `${base}hello`;
const res = await fetch(url);
Expand Down
27 changes: 27 additions & 0 deletions test/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import FormData from 'form-data';
import Blob from 'fetch-blob';

import {Request} from '../src/index.js';
import {getNodeRequestOptions} from '../src/request.js';
import TestServer from './utils/server.js';

const {expect} = chai;
Expand Down Expand Up @@ -312,4 +313,30 @@ describe('Request', () => {
data: ''
});
}));

it('should send Host header as the first header', () => {
const request = new Request('https://example.com/path', {
headers: {
'X-Custom': 'value',
'Accept': 'application/json'
}
});
const {options} = getNodeRequestOptions(request);
const headerKeys = Object.keys(options.headers);
expect(headerKeys[0]).to.equal('host');
expect(options.headers.host).to.equal('example.com');
});

it('should preserve custom Host header as first', () => {
const request = new Request('https://example.com/path', {
headers: {
'Host': 'custom.example.com',
'X-Custom': 'value'
}
});
const {options} = getNodeRequestOptions(request);
const headerKeys = Object.keys(options.headers);
expect(headerKeys[0]).to.equal('host');
expect(options.headers.host).to.equal('custom.example.com');
});
});
7 changes: 7 additions & 0 deletions test/utils/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,13 @@ export default class TestServer {
res.end('testtest');
}

if (p === '/size/content-length') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', '1000');
res.end('short');
}

if (p === '/redirect/301') {
res.statusCode = 301;
res.setHeader('Location', '/inspect');
Expand Down