Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

fix(http-client): do not reuse cookies of the previous hop on same-origin redirects (#4154)

Jindřich Bärbeaf123a6393
diff --git a/packages/http-client/src/base-http-client.ts b/packages/http-client/src/base-http-client.ts
index eb98b85df..921285985 100644
--- a/packages/http-client/src/base-http-client.ts
+++ b/packages/http-client/src/base-http-client.ts
@@ -200,9 +200,8 @@ export abstract class BaseHttpClient implements BaseHttpClientInterface {
currentRequest = initialRequest.clone();
while (true) {
- await this.applyCookies(currentRequest, cookieJar);
-
- const response = await this.fetch(currentRequest, {
+ // Like `fetch`, set the jar cookies on a copy, so that the next redirect hop does not inherit them
+ const response = await this.fetch(await this.applyCookies(new Request(currentRequest), cookieJar), {
signal,
proxyUrl,
cookieJar,
diff --git a/test/core/base-http-client.test.ts b/test/core/base-http-client.test.ts
index 0e12b9171..562cc7c99 100644
--- a/test/core/base-http-client.test.ts
+++ b/test/core/base-http-client.test.ts
@@ -180,6 +180,8 @@ describe('BaseHttpClient credentials on redirects', () => {
res.writeHead(302, { location: `${targetUrl}/echo` }).end();
} else if (pathname === '/same-origin') {
res.writeHead(302, { location: '/echo' }).end();
+ } else if (pathname === '/set-cookie') {
+ res.writeHead(302, { 'location': '/echo', 'set-cookie': 'session=new' }).end();
} else {
echoCredentials(req, res);
}
@@ -217,6 +219,24 @@ describe('BaseHttpClient credentials on redirects', () => {
expect(await response.json()).toEqual(credentials);
});
+
+ test('sends cookies updated by a same-origin redirect', async () => {
+ const cookieJar = new CookieJar();
+ await cookieJar.setCookie('session=old', redirectorUrl);
+
+ const response = await httpClient.sendRequest(new Request(`${redirectorUrl}/set-cookie`), { cookieJar });
+
+ expect(await response.json()).toMatchObject({ cookie: 'session=new' });
+ });
+
+ test('does not send cookies scoped to the path of the previous request on a same-origin redirect', async () => {
+ const cookieJar = new CookieJar();
+ await cookieJar.setCookie('session=secret; Path=/same-origin', redirectorUrl);
+
+ const response = await httpClient.sendRequest(new Request(`${redirectorUrl}/same-origin`), { cookieJar });
+
+ expect(await response.json()).toMatchObject({ cookie: null });
+ });
});
describe('BaseHttpClient TLS error handling', () => {