From 7aabb896018f462bab291c50295ce613c8d840f3 Mon Sep 17 00:00:00 2001 From: Chuoke Date: Fri, 27 Sep 2024 23:09:52 +0800 Subject: [PATCH] [11.x] Fixes trust proxy `REMOTE_ADDR` not working in Swoole (#52889) * fix: trust proxy REMOTE_ADDR not working in Swoole * formatting * add test case for trusted proxy with REMOTE_ADDR --------- Co-authored-by: Taylor Otwell --- src/Illuminate/Http/Middleware/TrustProxies.php | 8 +++++++- tests/Http/Middleware/TrustProxiesTest.php | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Http/Middleware/TrustProxies.php b/src/Illuminate/Http/Middleware/TrustProxies.php index 0d3c747ba6d3..59f6866c5a57 100644 --- a/src/Illuminate/Http/Middleware/TrustProxies.php +++ b/src/Illuminate/Http/Middleware/TrustProxies.php @@ -90,7 +90,13 @@ protected function setTrustedProxyIpAddresses(Request $request) */ protected function setTrustedProxyIpAddressesToSpecificIps(Request $request, array $trustedIps) { - $request->setTrustedProxies($trustedIps, $this->getTrustedHeaderNames()); + $request->setTrustedProxies(array_reduce($trustedIps, function ($ips, $trustedIp) use ($request) { + $ips[] = $trustedIp === 'REMOTE_ADDR' + ? $request->server->get('REMOTE_ADDR') + : $trustedIp; + + return $ips; + }, []), $this->getTrustedHeaderNames()); } /** diff --git a/tests/Http/Middleware/TrustProxiesTest.php b/tests/Http/Middleware/TrustProxiesTest.php index 7ad01d1b98cf..3d964fb06e9d 100644 --- a/tests/Http/Middleware/TrustProxiesTest.php +++ b/tests/Http/Middleware/TrustProxiesTest.php @@ -79,6 +79,20 @@ public function test_trusted_proxy_sets_trusted_proxies_with_double_wildcard_for }); } + /** + * Test the next most typical usage of TrustedProxies: + * Trusted X-Forwarded-For header, REMOTE_ADDR for TrustedProxies. + */ + public function test_trusted_proxy_sets_trusted_proxies_with_REMOTE_ADDR() + { + $trustedProxy = $this->createTrustedProxy($this->headerAll, 'REMOTE_ADDR'); + $request = $this->createProxiedRequest(); + + $trustedProxy->handle($request, function ($request) { + $this->assertSame('173.174.200.38', $request->getClientIp(), 'Assert trusted proxy x-forwarded-for header used with REMOTE_ADDR proxy setting'); + }); + } + /** * Test the most typical usage of TrustProxies: * Trusted X-Forwarded-For header.