ldc-cocotte/tests/Feature/App/Http/Middleware/TrustProxiesTest.php

63 lines
1.9 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace Tests\Feature\App\Http\Middleware;
use Illuminate\Http\Request;
use Webmozart\Assert\Assert;
describe('TrustProxies and clientIp resolution', function (): void {
it('resolves clientIp from valid X-Real-Ip header when present', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$request = Request::create('/', 'GET', [], [], [], [
'HTTP_X_REAL_IP' => '203.0.113.42',
'HTTP_X_FORWARDED_FOR' => '198.51.100.10',
]);
$this->app->instance('request', $request);
$this->app->forgetInstance('clientIp');
// WHEN
$clientIp = $this->app->make('clientIp');
// THEN
Assert::string($clientIp);
expect($clientIp)->toBe('203.0.113.42');
});
it('falls back to request ip when X-Real-Ip is invalid or absent', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$request = Request::create('/', 'GET', [], [], [], [
'HTTP_X_REAL_IP' => 'not-an-ip',
'REMOTE_ADDR' => '198.51.100.25',
]);
$this->app->instance('request', $request);
$this->app->forgetInstance('clientIp');
// WHEN
$clientIp = $this->app->make('clientIp');
// THEN
Assert::string($clientIp);
expect($clientIp)->toBe('198.51.100.25');
});
it('trusts X-Forwarded-For and ignores RFC 7239 Forwarded header', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$response = $this->withHeaders([
'X-Forwarded-For' => '203.0.113.99',
'Forwarded' => 'for=198.51.100.77',
])->get('/');
// WHEN
$resolvedIp = request()->ip();
// THEN
$response->assertStatus(200);
expect($resolvedIp)->toBe('203.0.113.99');
});
});