Skip to content
Merged
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
49 changes: 33 additions & 16 deletions src/HttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,16 @@ const RedirectStatusCodes = [
// https://fetch.spec.whatwg.org/#http-redirect-fetch
const CrossOriginSensitiveHeaders = new Set(['authorization', 'cookie', 'proxy-authorization']);

function omitHeaders(headers: IncomingHttpHeaders | undefined, omit: (name: string) => boolean): IncomingHttpHeaders {
const retained: IncomingHttpHeaders = {};
for (const name in headers) {
if (!omit(name.toLowerCase())) {
retained[name] = headers[name];
}
}
return retained;
}

export class HttpClient extends EventEmitter {
#defaultArgs?: RequestOptions;
#dispatcher?: Dispatcher;
Expand Down Expand Up @@ -592,9 +602,7 @@ export class HttpClient extends EventEmitter {
} else {
query = querystring.stringify(args.data);
}
// reset the requestUrl
const href = requestUrl.href;
requestUrl = new URL(href + (href.includes('?') ? '&' : '?') + query);
requestUrl.search += (requestUrl.search ? '&' : '?') + query;
}
} else {
if (isStringOrBufferOrReadable) {
Expand Down Expand Up @@ -702,18 +710,26 @@ export class HttpClient extends EventEmitter {
let redirectOptions = options;
// Do not forward credential-bearing headers to a different origin.
if (nextUrl.origin !== requestUrl.origin) {
const cleanedHeaders: IncomingHttpHeaders = {};
if (options?.headers) {
for (const name in options.headers) {
if (!CrossOriginSensitiveHeaders.has(name.toLowerCase())) {
cleanedHeaders[name] = options.headers[name];
}
}
}
// Clone so the caller's options object is never mutated, and drop
// credentials so they are not re-applied on the new origin,
// including Basic/digest auth inherited from the client's defaultArgs.
redirectOptions = { ...options, headers: cleanedHeaders, auth: undefined, digestAuth: undefined };
redirectOptions = {
...options,
headers: omitHeaders(originalHeaders, (name) => CrossOriginSensitiveHeaders.has(name)),
auth: undefined,
digestAuth: undefined,
};
}
if (res.statusCode === 303 && requestOptions.method !== 'GET' && requestOptions.method !== 'HEAD') {
// Explicitly override body options so client defaults cannot restore the payload.
redirectOptions = {
...redirectOptions,
method: 'GET',
type: undefined,
headers: omitHeaders(redirectOptions?.headers, (name) => name.startsWith('content-')),
data: undefined,
content: undefined,
contentType: undefined,
files: undefined,
stream: undefined,
};
}
debug(
'Request#%d got response, status: %s, headers: %j, timing: %j, redirect to %s',
Expand All @@ -723,7 +739,8 @@ export class HttpClient extends EventEmitter {
res.timing,
nextUrl.href,
);
return await this.#requestInternal(nextUrl.href, redirectOptions, requestContext);
// The target handles its own retries. A target error must not replay the original request.
return this.#requestInternal(nextUrl.href, redirectOptions, requestContext);
}
}

Expand Down
17 changes: 10 additions & 7 deletions test/options.data.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,15 @@ describe('options.data.test.ts', () => {
assert.equal(url.searchParams.get('data'), '哈哈');
});

it('should not mutate a passed URL object when setting query string', async () => {
const url = new URL(_url);
assert.equal(url.searchParams.get('param1'), null);
await urllib.request(url, {
it('should send GET data before the fragment and preserve the original URL', async () => {
const href = `${_url}ok#fragment?ignored`;
const url = new URL(href);
const response = await urllib.request(url, {
data: { param1: 'val1' },
dataType: 'json',
});
assert.equal(url.searchParams.get('param1'), null);
assert.equal(response.data.url, '/ok?param1=val1');
assert.equal(url.href, href);
});

it('should GET with data work on nestedQuerystring=true', async () => {
Expand Down Expand Up @@ -142,8 +144,8 @@ describe('options.data.test.ts', () => {
assert.deepEqual(query.foo, { bar: 'bar value', array: ['1', '2', '3'] });
});

it('should HEAD with data and auto convert to query string', async () => {
const response = await urllib.request(_url, {
it('should append HEAD data to the existing query before the fragment', async () => {
const response = await urllib.request(`${_url}?existing=1#frag`, {
method: 'HEAD',
data: {
sql: 'SELECT * from table',
Expand All @@ -157,6 +159,7 @@ describe('options.data.test.ts', () => {
assert(response.url.startsWith(_url));
assert(!response.redirected);
const url = new URL(response.headers['x-href'] as string);
assert.equal(url.searchParams.get('existing'), '1');
assert.equal(url.searchParams.get('sql'), 'SELECT * from table');
assert.equal(url.searchParams.get('data'), '哈哈');
});
Expand Down
46 changes: 46 additions & 0 deletions test/options.followRedirect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,52 @@ describe('options.followRedirect.test.ts', () => {
assert.equal(response.requestUrls.length, 2);
});

it('should follow a 303 after POST with a GET without form data or body headers', async () => {
const httpClient = new HttpClient({ defaultArgs: { data: { a: 1 } } });
const { data } = await httpClient.request(`${_url}redirect-to?status=303&url=/result?from=303`, {
type: 'post',
dataType: 'json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': '3',
'X-Trace': 'redirect',
},
});
assert.equal(data.method, 'GET');
assert.equal(data.url, '/result?from=303');
assert.equal(data.requestBody, '');
assert.equal(data.headers['content-type'], undefined);
assert.equal(data.headers['content-length'], undefined);
assert.equal(data.headers['x-trace'], 'redirect');
});

it('should follow a 303 after a file upload with a GET', async () => {
const { data } = await urllib.request(`${_url}redirect-to?status=303&url=/result`, {
files: Buffer.from('file contents'),
dataType: 'json',
});
assert.equal(data.method, 'GET');
assert.equal(data.requestBody, '');
});

it('should keep HEAD when following a 303', async () => {
const { headers } = await urllib.request(`${_url}redirect-to?status=303&url=/result`, { method: 'HEAD' });
assert.equal(headers['x-method'], 'HEAD');
});

it('should retry only the GET if the 303 target closes the socket', async () => {
const httpClient = new HttpClient();
const methods: string[] = [];
httpClient.on('request', ({ args }) => methods.push(args.method));
await assert.rejects(
httpClient.request(`${_url}redirect-to?status=303&url=/error`, {
method: 'POST',
data: { a: 1 },
}),
);
assert.deepEqual(methods, ['POST', 'GET', 'GET']);
});

it('should follow redirect on writeStream ', async () => {
const requestURL = `${_url}redirect`;
const httpClient = new HttpClient({
Expand Down
Loading