mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-07 20:51:23 +00:00
Gateway: harden trusted proxy X-Forwarded-For parsing (#22429)
This commit is contained in:
@@ -145,12 +145,21 @@ describe("resolveGatewayClientIp", () => {
|
||||
it("returns forwarded client IP when the remote is a trusted proxy", () => {
|
||||
const ip = resolveGatewayClientIp({
|
||||
remoteAddr: "127.0.0.1",
|
||||
forwardedFor: "10.0.0.2, 127.0.0.1",
|
||||
forwardedFor: "127.0.0.1, 10.0.0.2",
|
||||
trustedProxies: ["127.0.0.1"],
|
||||
});
|
||||
expect(ip).toBe("10.0.0.2");
|
||||
});
|
||||
|
||||
it("does not trust the left-most X-Forwarded-For value when behind a trusted proxy", () => {
|
||||
const ip = resolveGatewayClientIp({
|
||||
remoteAddr: "127.0.0.1",
|
||||
forwardedFor: "198.51.100.99, 10.0.0.9, 127.0.0.1",
|
||||
trustedProxies: ["127.0.0.1"],
|
||||
});
|
||||
expect(ip).toBe("127.0.0.1");
|
||||
});
|
||||
|
||||
it("fails closed when trusted proxy headers are missing", () => {
|
||||
const ip = resolveGatewayClientIp({
|
||||
remoteAddr: "127.0.0.1",
|
||||
|
||||
@@ -147,7 +147,11 @@ function stripOptionalPort(ip: string): string {
|
||||
}
|
||||
|
||||
export function parseForwardedForClientIp(forwardedFor?: string): string | undefined {
|
||||
const raw = forwardedFor?.split(",")[0]?.trim();
|
||||
const entries = forwardedFor
|
||||
?.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
const raw = entries?.at(-1);
|
||||
if (!raw) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user