Skip to content

Commit

Permalink
fix(remix): Correctly parse X-Forwarded-For Http header (#7329)
Browse files Browse the repository at this point in the history
Handle white spaces more robustly when splitting forwarded-for http header values
  • Loading branch information
Lms24 committed Mar 6, 2023
1 parent 0e63e3a commit 697f95b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/remix/src/utils/getIpAddress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function getClientIPAddress(headers: Headers): string | null {
return parseForwardedHeader(value);
}

return value?.split(', ');
return value?.split(',').map((v: string) => v.trim());
});

// Flatten the array and filter out any falsy entries
Expand Down
42 changes: 42 additions & 0 deletions packages/remix/test/utils/getIpAddress.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { getClientIPAddress } from '../../src/utils/getIpAddress';

class Headers {
private _headers: Record<string, string> = {};

get(key: string): string | null {
return this._headers[key] ?? null;
}

set(key: string, value: string): void {
this._headers[key] = value;
}
}

describe('getClientIPAddress', () => {
it.each([
[
'2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5,2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5, 141.101.69.35',
'2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5',
],
[
'2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5, 2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5, 141.101.69.35',
'2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5',
],
[
'2a01:cb19:8350:ed00:d0dd:INVALID_IP_ADDR:8be5,141.101.69.35,2a01:cb19:8350:ed00:d0dd:fa5b:de31:8be5',
'141.101.69.35',
],
[
'2b01:cb19:8350:ed00:d0dd:fa5b:nope:8be5, 2b01:cb19:NOPE:ed00:d0dd:fa5b:de31:8be5, 141.101.69.35 ',
'141.101.69.35',
],
['2b01:cb19:8350:ed00:d0 dd:fa5b:de31:8be5, 141.101.69.35', '141.101.69.35'],
])('should parse the IP from the X-Forwarded-For header %s', (headerValue, expectedIP) => {
const headers = new Headers();
headers.set('X-Forwarded-For', headerValue);

const ip = getClientIPAddress(headers as any);

expect(ip).toEqual(expectedIP);
});
});

0 comments on commit 697f95b

Please sign in to comment.