Skip to content

Commit 6bb12c1

Browse files
sapirbaruchjasonsaaymancubic-dev-ai[bot]claude
authored
fix: custom auth headers not stripped on cross-origin redirects (#10892)
Co-authored-by: Jason Saayman <[email protected]> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 <[email protected]>
1 parent 550f0d8 commit 6bb12c1

8 files changed

Lines changed: 291 additions & 5 deletions

File tree

‎PRE_RELEASE_CHANGELOG.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,26 @@
22

33
## Unreleased
44

5+
## Security Fixes
6+
7+
- **HTTP Adapter Redirects:** Added a Node.js `sensitiveHeaders` request config option that strips caller-selected custom secret headers from cross-origin redirects. (**#10892**)
8+
9+
## Docs updates
10+
11+
- docs/pages/misc/security.md LN29 : | [`sensitiveHeaders`](/pages/advanced/request-config#sensitiveheaders) | Custom authentication headers such as `X-API-Key` can be forwarded to a different origin when a trusted server redirects there. | List custom secret-bearing headers in `sensitiveHeaders` so the Node.js adapter strips them on cross-origin redirects. |
12+
- docs/pages/advanced/request-config.md LN269 : | ### `sensitiveHeaders` <Badge type="warning" text="Node.js only" />
13+
14+
The `sensitiveHeaders` property is an optional array of custom secret-bearing header names to remove when axios follows a redirect to a different origin. Matching is case-insensitive. Same-origin redirects keep these headers.
15+
16+
This only applies to redirects followed by the Node.js HTTP adapter. If `maxRedirects` is set to 0, `sensitiveHeaders` is not used.
17+
18+
```js
19+
axios.get('https://api.example.com/users', {
20+
headers: { 'X-API-Key': 'secret' },
21+
sensitiveHeaders: ['X-API-Key']
22+
});
23+
```
24+
525
## New Features
626

727
- **HTTP Adapter - Zstandard:** Added automatic zstd decompression on Node.js versions that support it. `zstd` is only advertised in the default `Accept-Encoding` header when `transitional.advertiseZstdAcceptEncoding: true` is set. (**#6792**)

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,12 @@ These config options are available for requests. Only `url` is required. Request
898898
// If set to 0, Axios follows no redirects.
899899
maxRedirects: 21, // default
900900

901+
// `sensitiveHeaders` (Node only option) lists custom secret-bearing headers
902+
// to remove from cross-origin redirects. Matching is case-insensitive.
903+
// Same-origin redirects keep these headers. If `maxRedirects` is 0, this
904+
// option is not used.
905+
sensitiveHeaders: ['X-API-Key'],
906+
901907
// `beforeRedirect` defines a function that Axios calls before redirect.
902908
// Use this to adjust the request options upon redirecting,
903909
// to inspect the latest response headers,

‎THREATMODEL.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ The runtime model is general by design. axios is a transport library and cannot
104104
| **Description** | Caller sets `Authorization: Bearer …` and requests `https://api.trusted.com/x`. Server responds `302 Location: https://evil.com/`. Does the bearer token go to evil.com? |
105105
| **Likelihood** | Medium |
106106
| **Impact** | High (full credential theft) |
107-
| **Mitigations** | • Node adapter delegates to `follow-redirects@^1.15.11`, which strips `Authorization`, `Cookie`, and `Proxy-Authorization` on cross-host redirects and on HTTPS to HTTP downgrades. <br>• `maxRedirects` defaults to 5; set to `0` to handle redirects manually. <br>• `beforeRedirect` callback allows custom inspection. <br>• Browser adapters (XHR/fetch) delegate to the browser, which applies its own cross-origin credential rules. |
108-
| **Residual risk** | Low. We inherit `follow-redirects`' security posture. It is a critical transitive dependency, and its CVEs are our CVEs. |
107+
| **Mitigations** | • Node adapter delegates to `follow-redirects@^1.16.0`, which strips `Authorization`, `Cookie`, and `Proxy-Authorization` on cross-host redirects and on HTTPS→HTTP downgrades. <br>• `sensitiveHeaders` lets callers list custom secret-bearing headers (for example `X-API-Key`) that axios strips on cross-origin redirects. <br>• `maxRedirects` defaults to 5; set to `0` to handle redirects manually. <br>• `beforeRedirect` callback allows custom inspection. <br>• Browser adapters (XHR/fetch) delegate to the browser, which applies its own cross-origin credential rules. |
108+
| **Residual risk** | Low for standard credential headers and configured custom secret headers. We inherit `follow-redirects`' security posture - it is a critical transitive dependency and its CVEs are our CVEs. Callers must list any custom secret headers they want stripped. |
109109

110110
---
111111

‎index.d.cts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,7 @@ declare namespace axios {
559559
};
560560
formDataHeaderPolicy?: 'legacy' | 'content-only';
561561
redact?: string[];
562+
sensitiveHeaders?: string[];
562563
}
563564

564565
// Alias

‎index.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,7 @@ export interface AxiosRequestConfig<D = any> {
452452
};
453453
formDataHeaderPolicy?: 'legacy' | 'content-only';
454454
redact?: string[];
455+
sensitiveHeaders?: string[];
455456
}
456457

457458
// Alias

‎lib/adapters/http.js‎

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ const flushOnFinish = (stream, [throttled, flush]) => {
154154
const http2Sessions = new Http2Sessions();
155155

156156
/**
157-
* If the proxy, auth, or config beforeRedirects functions are defined, call them
158-
* with the options object.
157+
* If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
158+
* call them with the options object.
159159
*
160160
* @param {Object<string, any>} options - The options object that was passed to the request.
161161
*
@@ -168,11 +168,39 @@ function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
168168
if (options.beforeRedirects.auth) {
169169
options.beforeRedirects.auth(options);
170170
}
171+
if (options.beforeRedirects.sensitiveHeaders) {
172+
options.beforeRedirects.sensitiveHeaders(options, requestDetails);
173+
}
171174
if (options.beforeRedirects.config) {
172175
options.beforeRedirects.config(options, responseDetails, requestDetails);
173176
}
174177
}
175178

179+
function stripMatchingHeaders(headers, sensitiveSet) {
180+
if (!headers) {
181+
return;
182+
}
183+
184+
Object.keys(headers).forEach((header) => {
185+
if (sensitiveSet.has(header.toLowerCase())) {
186+
delete headers[header];
187+
}
188+
});
189+
}
190+
191+
function isSameOriginRedirect(redirectOptions, requestDetails) {
192+
if (!requestDetails) {
193+
return false;
194+
}
195+
196+
try {
197+
return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
198+
} catch (e) {
199+
// If origin comparison fails, treat the redirect as unsafe.
200+
return false;
201+
}
202+
}
203+
176204
/**
177205
* If the proxy or config afterRedirects functions are defined, call them with the options
178206
*
@@ -864,6 +892,7 @@ export default isHttpAdapterSupported &&
864892
transport = isHttpsRequest ? https : http;
865893
isNativeTransport = true;
866894
} else {
895+
options.sensitiveHeaders = [];
867896
if (config.maxRedirects) {
868897
options.maxRedirects = config.maxRedirects;
869898
}
@@ -888,6 +917,45 @@ export default isHttpAdapterSupported &&
888917
}
889918
};
890919
}
920+
const sensitiveHeaders = own('sensitiveHeaders');
921+
if (sensitiveHeaders != null) {
922+
if (!utils.isArray(sensitiveHeaders)) {
923+
return reject(
924+
new AxiosError(
925+
'sensitiveHeaders must be an array of strings',
926+
AxiosError.ERR_BAD_OPTION_VALUE,
927+
config
928+
)
929+
);
930+
}
931+
932+
const sensitiveSet = new Set();
933+
for (const header of sensitiveHeaders) {
934+
if (!utils.isString(header)) {
935+
return reject(
936+
new AxiosError(
937+
'sensitiveHeaders must be an array of strings',
938+
AxiosError.ERR_BAD_OPTION_VALUE,
939+
config
940+
)
941+
);
942+
}
943+
944+
sensitiveSet.add(header.toLowerCase());
945+
}
946+
947+
if (sensitiveSet.size) {
948+
options.sensitiveHeaders = Array.from(sensitiveSet);
949+
options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(
950+
redirectOptions,
951+
requestDetails
952+
) {
953+
if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
954+
stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
955+
}
956+
};
957+
}
958+
}
891959
transport = isHttpsRequest ? httpsFollow : httpFollow;
892960
}
893961
}
@@ -1254,3 +1322,4 @@ export default isHttpAdapterSupported &&
12541322
};
12551323

12561324
export const __setProxy = setProxy;
1325+
export const __isSameOriginRedirect = isSameOriginRedirect;

‎tests/unit/adapters/http.test.js‎

Lines changed: 161 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
} from '../../setup/server.js';
1111
import axios from '../../../index.js';
1212
import AxiosError from '../../../lib/core/AxiosError.js';
13-
import { __setProxy } from '../../../lib/adapters/http.js';
13+
import { __isSameOriginRedirect, __setProxy } from '../../../lib/adapters/http.js';
1414
import HttpsProxyAgent from 'https-proxy-agent';
1515
import http from 'http';
1616
import https from 'https';
@@ -632,6 +632,166 @@ describe('supports http with nodejs', () => {
632632
await stopHTTPServer(proxy);
633633
});
634634

635+
it('should strip sensitiveHeaders on cross-origin redirect', async () => {
636+
let capturedHeaders;
637+
638+
// destination server — different port means different origin
639+
const destination = await startHTTPServer((req, res) => {
640+
capturedHeaders = req.headers;
641+
res.statusCode = 200;
642+
res.end('ok');
643+
});
644+
645+
// origin server — redirects to destination (cross-origin)
646+
const origin = await startHTTPServer((req, res) => {
647+
res.setHeader('Location', `http://localhost:${destination.address().port}/dest`);
648+
res.statusCode = 302;
649+
res.end();
650+
});
651+
652+
try {
653+
await axios.get(`http://localhost:${origin.address().port}/src`, {
654+
maxRedirects: 5,
655+
headers: { 'X-API-Key': 'secret', 'X-Other': 'keep' },
656+
sensitiveHeaders: ['X-API-Key'],
657+
});
658+
659+
assert.strictEqual(capturedHeaders['x-api-key'], undefined, 'X-API-Key should be stripped');
660+
assert.strictEqual(capturedHeaders['x-other'], 'keep', 'X-Other should be preserved');
661+
} finally {
662+
await stopHTTPServer(origin);
663+
await stopHTTPServer(destination);
664+
}
665+
});
666+
667+
it('should preserve sensitiveHeaders on same-origin redirect', async () => {
668+
let capturedHeaders;
669+
let requestCount = 0;
670+
671+
const server = await startHTTPServer((req, res) => {
672+
requestCount++;
673+
if (requestCount === 1) {
674+
res.setHeader('Location', '/dest');
675+
res.statusCode = 302;
676+
res.end();
677+
} else {
678+
capturedHeaders = req.headers;
679+
res.statusCode = 200;
680+
res.end('ok');
681+
}
682+
});
683+
684+
try {
685+
await axios.get(`http://localhost:${server.address().port}/src`, {
686+
maxRedirects: 5,
687+
headers: { 'X-API-Key': 'secret' },
688+
sensitiveHeaders: ['X-API-Key'],
689+
});
690+
691+
assert.strictEqual(capturedHeaders['x-api-key'], 'secret', 'X-API-Key should be preserved on same-origin redirect');
692+
} finally {
693+
await stopHTTPServer(server);
694+
}
695+
});
696+
697+
it('should strip sensitiveHeaders case-insensitively on cross-origin redirect', async () => {
698+
let capturedHeaders;
699+
700+
const destination = await startHTTPServer((req, res) => {
701+
capturedHeaders = req.headers;
702+
res.statusCode = 200;
703+
res.end('ok');
704+
});
705+
706+
const origin = await startHTTPServer((req, res) => {
707+
res.setHeader('Location', `http://localhost:${destination.address().port}/dest`);
708+
res.statusCode = 302;
709+
res.end();
710+
});
711+
712+
try {
713+
await axios.get(`http://localhost:${origin.address().port}/src`, {
714+
maxRedirects: 5,
715+
// Header sent with mixed casing; sensitiveHeaders list uses different casing
716+
headers: { 'X-Api-Key': 'secret' },
717+
sensitiveHeaders: ['x-api-key'],
718+
});
719+
720+
assert.strictEqual(capturedHeaders['x-api-key'], undefined, 'X-Api-Key should be stripped case-insensitively');
721+
} finally {
722+
await stopHTTPServer(origin);
723+
await stopHTTPServer(destination);
724+
}
725+
});
726+
727+
it('should strip sensitiveHeaders configured on an instance', async () => {
728+
let capturedHeaders;
729+
730+
const destination = await startHTTPServer((req, res) => {
731+
capturedHeaders = req.headers;
732+
res.statusCode = 200;
733+
res.end('ok');
734+
});
735+
736+
const origin = await startHTTPServer((req, res) => {
737+
res.setHeader('Location', `http://localhost:${destination.address().port}/dest`);
738+
res.statusCode = 302;
739+
res.end();
740+
});
741+
742+
const client = axios.create({
743+
headers: { 'X-API-Key': 'secret', 'X-Other': 'keep' },
744+
sensitiveHeaders: ['X-API-Key'],
745+
});
746+
747+
try {
748+
await client.get(`http://localhost:${origin.address().port}/src`, {
749+
maxRedirects: 5,
750+
});
751+
752+
assert.strictEqual(capturedHeaders['x-api-key'], undefined, 'X-API-Key should be stripped');
753+
assert.strictEqual(capturedHeaders['x-other'], 'keep', 'X-Other should be preserved');
754+
} finally {
755+
await stopHTTPServer(origin);
756+
await stopHTTPServer(destination);
757+
}
758+
});
759+
760+
it('should reject invalid sensitiveHeaders config', async () => {
761+
await assert.rejects(
762+
axios.get('http://localhost:1/', { sensitiveHeaders: 'X-API-Key' }),
763+
(error) => {
764+
assert.strictEqual(error.code, AxiosError.ERR_BAD_OPTION_VALUE);
765+
assert.strictEqual(error.message, 'sensitiveHeaders must be an array of strings');
766+
return true;
767+
}
768+
);
769+
770+
await assert.rejects(
771+
axios.get('http://localhost:1/', { sensitiveHeaders: [null] }),
772+
(error) => {
773+
assert.strictEqual(error.code, AxiosError.ERR_BAD_OPTION_VALUE);
774+
assert.strictEqual(error.message, 'sensitiveHeaders must be an array of strings');
775+
return true;
776+
}
777+
);
778+
});
779+
780+
it('should fail closed when sensitiveHeaders redirect origin cannot be parsed', () => {
781+
assert.strictEqual(
782+
__isSameOriginRedirect(
783+
{ href: 'http://localhost/final' },
784+
{ url: 'http://localhost/start' }
785+
),
786+
true
787+
);
788+
assert.strictEqual(
789+
__isSameOriginRedirect({ href: 'http://[::1' }, { url: 'http://localhost/start' }),
790+
false
791+
);
792+
assert.strictEqual(__isSameOriginRedirect({ href: 'http://localhost/final' }), false);
793+
});
794+
635795
it('should wrap HTTP errors and keep stack', async () => {
636796
const server = await startHTTPServer(
637797
(req, res) => {

‎tests/unit/prototypePollution.test.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ describe('Prototype Pollution Protection', () => {
2828
delete Object.prototype.baseURL;
2929
delete Object.prototype.socketPath;
3030
delete Object.prototype.beforeRedirect;
31+
delete Object.prototype.sensitiveHeaders;
3132
delete Object.prototype.insecureHTTPParser;
3233
delete Object.prototype.adapter;
3334
delete Object.prototype.httpAgent;
@@ -498,6 +499,34 @@ describe('Prototype Pollution Protection', () => {
498499
}
499500
}, 10000);
500501

502+
it('should not pick up Object.prototype.sensitiveHeaders during redirects', async () => {
503+
Object.prototype.sensitiveHeaders = ['X-Secret'];
504+
let capturedHeaders;
505+
506+
const target = await startServer((req, res) => {
507+
capturedHeaders = req.headers;
508+
res.writeHead(200, { 'Content-Type': 'application/json' });
509+
res.end('{"ok":true}');
510+
});
511+
const { port: targetPort } = target.address();
512+
513+
const redirector = await startServer((req, res) => {
514+
res.writeHead(302, { Location: `http://127.0.0.1:${targetPort}/final` });
515+
res.end();
516+
});
517+
const { port: redirectorPort } = redirector.address();
518+
519+
try {
520+
await axios.get(`http://127.0.0.1:${redirectorPort}/start`, {
521+
headers: { 'X-Secret': 'keep' },
522+
});
523+
assert.strictEqual(capturedHeaders['x-secret'], 'keep');
524+
} finally {
525+
await stopServer(redirector);
526+
await stopServer(target);
527+
}
528+
}, 10000);
529+
501530
it('should not enable insecureHTTPParser via Object.prototype', async () => {
502531
// A raw TCP server emits a response that uses LF-only line terminators
503532
// instead of CRLF. Node's strict HTTP parser rejects this payload with

0 commit comments

Comments
 (0)