From f1e35d43695f914677fcf8b2b4550a3c58cdcf10 Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Tue, 28 Apr 2026 14:42:07 +0200 Subject: Add IP address normalization, add support for X-Forwarded-For Tests written by Junie AI --- tests/Inc/GetClientIpTest.php | 89 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 tests/Inc/GetClientIpTest.php (limited to 'tests/Inc/GetClientIpTest.php') diff --git a/tests/Inc/GetClientIpTest.php b/tests/Inc/GetClientIpTest.php new file mode 100644 index 00000000..22287ff3 --- /dev/null +++ b/tests/Inc/GetClientIpTest.php @@ -0,0 +1,89 @@ +assertSame('1.2.3.4', Util::getClientIp()); + } + + public function testGetClientIpTrustedProxy(): void + { + $_SERVER['REMOTE_ADDR'] = '10.0.0.1'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '1.2.3.4'; + Property::$values['webinterface.proxies-trusted'] = json_encode(['10.0.0.1' => true]); + + $this->assertSame('1.2.3.4', Util::getClientIp()); + } + + public function testGetClientIpUntrustedProxy(): void + { + $_SERVER['REMOTE_ADDR'] = '10.2'; // Not in trusted list + $_SERVER['HTTP_X_FORWARDED_FOR'] = '1.2.3.4'; + Property::$values['webinterface.proxies-trusted'] = json_encode(['10.0.0.1' => true]); + + $this->assertSame('10.0.0.2', Util::getClientIp()); + } + + public function testGetClientIpChain(): void + { + // Chain: Client (1.1.1.1) -> Proxy1 (2.2.2.2) -> Proxy2 (3.3.3.3) -> WebServer + $_SERVER['REMOTE_ADDR'] = '::ffff:3.3.3.3'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '1.1.1.1, 2.2.2.2'; + Property::$values['webinterface.proxies-trusted'] = json_encode([ + '3.3.3.3' => true, + '2.2.2.2' => true + ]); + + // We want it to return '1.1.1.1' + $this->assertSame('1.1.1.1', Util::getClientIp()); + } + + public function testGetClientIpLongChain(): void + { + // Chain: Client (1.1.1.1) -> UntrustedProxy (4.4.4.4) -> Proxy1 (2.2.2.2) -> Proxy2 (3.3.3.3) -> WebServer + $_SERVER['REMOTE_ADDR'] = '3.3.3.3'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '9.9.9.9, 1.1.1.1, 4.4.4.4, ::ffff:2.2.2.2'; + Property::$values['webinterface.proxies-trusted'] = json_encode([ + '1.1.1.1' => true, + '3.3.3.3' => true, + '2.2.2.2' => true + ]); + + // Should return 4.4.4.4 because it's the first untrusted from the right + $this->assertSame('4.4.4.4', Util::getClientIp()); + } + + public function testGetClientIpIpv6Mapping(): void + { + $_SERVER['REMOTE_ADDR'] = '::ffff:10.0.0.1'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '::ffff:1.2.3.4'; + Property::$values['webinterface.proxies-trusted'] = json_encode(['10.0.0.1' => true]); + + $this->assertSame('1.2.3.4', Util::getClientIp()); + } + + public function testGetClientIpIpv6MappingInChain(): void + { + $_SERVER['REMOTE_ADDR'] = '3.3.3.3'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '9.9.9.9, ::ffff:1.1.1.1, ::ffff:2.2.2.2'; + Property::$values['webinterface.proxies-trusted'] = json_encode([ + '3.3.3.3' => true, + '2.2.2.2' => true + ]); + + $this->assertSame('1.1.1.1', Util::getClientIp()); + } +} -- cgit v1.2.3-55-g7522