/proxy-middleware

Middleware to set request parameters based on headers provided by proxy

Primary LanguagePHPBSD 3-Clause "New" or "Revised" LicenseBSD-3-Clause

Yii Proxy Middleware


Latest Stable Version Total Downloads Build status Code Coverage Mutation testing badge static analysis type-coverage psalm-level

The package provides proxy related middleware classes that implement PSR-15:

For other miscellaneous middleware, there is a separate package - Yii Middleware.

For more information on how to use middleware in the Yii Framework, see the Yii middleware guide.

Requirements

  • PHP 8.0 or higher.

Installation

The package could be installed with composer:

composer require yiisoft/proxy-middleware

General usage

TrustedHeaderProtocolResolver

Trusted header protocol resolver sets a server request protocol based on special header you trust such as X-Forwarded-Proto.

You can use it if your server is behind a trusted load balancer or a proxy that's always setting the special header itself discarding any header values provided by user.

use Yiisoft\Yii\Middleware\TrustedHeaderProtocolResolver;

/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 * @var Psr\Http\Server\RequestHandlerInterface $handler
 */

$middleware = new TrustedHeaderProtocolResolver();

$middleware = $middleware->withAddedProtocolHeader('x-forwarded-proto', [
    'http' => ['http'],
    'https' => ['https', 'on'],
]);
// Disable earlier settings:
$middleware = $middleware->withoutProtocolHeader('x-forwarded-proto');

$response = $middleware->process($request, $handler);

TrustedHostsNetworkResolver

Scans the entire connection chain and resolves the data from forwarded headers taking into account trusted IPs. Additionally, all items' structure is thoroughly validated because headers' data can't be trusted. The following data is resolved:

  • IP.
  • Protocol
  • Host.
  • Port.
  • IP identifier - unknown or obfuscated. Used with Forwarded RFC header.

The typical use case is having an application behind a load balancer.

Trusted IPs

A list of trusted IPs from connection chain.

Proxies' IPs including the one in $_SERVER['REMOTE_ADDR'] must be specified here. For example, for $_SERVER['REMOTE_ADDR'] with value 18.18.18.18 and 2 other proxies - 2.2.2.2 and 8.8.8.8, the configuration will be:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withTrustedIps([['8.8.8.8', '2.2.2.2', '18.18.18.18']]);

The order of IPs is not important.

Forwarded header groups

Header groups to parse the data from. By including headers in this list, they are trusted automatically.

The default is:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([    
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,           
]);

which is an alternative/shorter way of writing this:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([    
    'forwarded',
    [
        'ip' => 'x-forwarded-for',
        'protocol' => 'x-forwarded-proto',
        'host' => 'x-forwarded-host',
        'port' => 'x-forwarded-port',    
    ],           
]);

The accepted values are:

  • TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC string constant. Parse all data from single Forwarded header according to RFC 7239.
  • Array. Parse data from separate forwarded headers with "X" prefix. Unlike with RFC variation, each header stores only one data unit (for example, IP). Headers with "X" prefix are quite common despite being non-standard:

The header groups are processed in the order they are defined. If the header containing IP is present and is non-empty, this group will be selected and further ones will be ignored.

You can add support for custom headers and/or change priority:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([    
    [
        'ip' => 'y-forwarded-for',
        'protocol' => 'y-forwarded-proto',
        'host' => 'y-forwarded-host',
        'port' => 'y-forwarded-port',    
    ],
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,    
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,               
]);

For protocol, it's also possible to resolve non-standard values via mapping:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,    
    [
        'ip' => 'y-forwarded-for',
        'protocol' => [
            'front-end-https', 
            ['on' => 'https'],
        ],
        'host' => 'y-forwarded-host',
        'port' => 'y-forwarded-port',    
    ],
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,               
]);

or via callable:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,    
    [
        'ip' => 'y-forwarded-for',
        'protocol' => [
            'front-end-https', 
            static fn (string $protocol): ?string => $protocol === 'On' ? 'https': 'http',,
        ],
        'host' => 'y-forwarded-host',
        'port' => 'y-forwarded-port',    
    ],
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,               
]);

It's also a good idea to limit default header groups to the only guaranteed sources of data:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([    
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,           
]);

Typical forwarded headers

List of headers that are considered related to forwarding.

The default is:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withTypicalForwardedHeaders([
    // RFC
    'forwarded',

    // "X" prefix
    'x-forwarded-for',
    'x-forwarded-host',
    'x-forwarded-proto',
    'x-forwarded-port',

    // Microsoft
    'front-end-https',
]);

The headers that are present in this list but missing in a matching forwarded header group will be deleted from request because they are potentially not secure and likely were not passed by a proxy server.

For example, with default forwarded header groups' setup used as well:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,
]);

and with the following request headers passed:

[
    'Forwarded' => [
        'for="9.9.9.9:8013";proto=http;host=example13.com',
        'for="8.8.8.8:8012";proto=http;host=example12.com',
        'for="2.2.2.2:8011";proto=http;host=example11.com',
    ],
    'X-Forwarded-For' => 'not-secure',
    'X-Forwarded-Host' => 'not-secure',
    'X-Forwarded-Proto' => 'not-secure',
    'X-Forwarded-Port' => 'not-secure',
    'Front-End-Https' => 'not-secure',
    'Non-Forwarded' => 'not-typical',
];

middleware will remove these headers from request:

  • x-forwarded-for.
  • x-forwarded-host.
  • x-forwarded-proto.
  • x-forwarded-port.
  • front-end-https.

because RFC group is matching and the rest can't be trusted. The headers that are not declared as typical forwarded headers will be left as is (Non-Forwarded in the example above).

Accessing resolved data

Resolved IP is saved to a special request's attribute:

use Psr\Http\Message\ServerRequestInterface;

/** @var ServerRequestInterface $request */
$ip = $request->getAttribute(TrustedHostsNetworkResolver::ATTRIBUTE_REQUEST_CLIENT_IP);

There is an additional attribute allowing to retrieve all previous validated and trusted connection chain items. It needs explicit configuration:

use Psr\Http\Message\ServerRequestInterface;
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withConnectionChainItemsAttribute('connectionChainItems');
// ...
/** @var ServerRequestInterface $request */
$connectionChainItems = $request->getAttribute('connectionChainItems');

An example of contents:

[
    [
        'ip' => '18.18.18.18',
        'protocol' => null,
        'host' => null,
        'port' => null,
        'ipIdentifier' => null,
    ],
    [
        'ip' => '2.2.2.2',
        'protocol' => 'http',
        'host' => 'example1.com',
        'port' => null,
        'ipIdentifier' => '_obfuscated1',
    ]
],

Reverse-obfuscating IP identifier

You may extend middleware class and provide reverse-obfuscating logic for obfuscated IP identifiers:

use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

class MyTrustedHostsNetworkResolver extends TrustedHostsNetworkResolver
{
    protected function reverseObfuscateIpIdentifier(
        string $ipIdentifier,
        array $validatedConnectionChainItems,
        array $remainingConnectionChainItems,
        RequestInterface $request,
    ): ?array
    {
        return match ($ipIdentifier) {
            '_obfuscated1' => ['2.2.2.2', null], // Without port
            '_obfuscated2' => ['5.5.5.5', '8082'], // With port
            default => null, // Unable to resolve (default)
        };
    }
}

Testing

Unit testing

The package is tested with PHPUnit. To run tests:

./vendor/bin/phpunit

Mutation testing

The package tests are checked with Infection mutation framework with Infection Static Analysis Plugin. To run it:

./vendor/bin/roave-infection-static-analysis-plugin

Static analysis

The code is statically analyzed with Psalm. To run static analysis:

./vendor/bin/psalm

Code style

Use Rector to make codebase follow some specific rules or use either newest or any specific version of PHP:

./vendor/bin/rector

Dependencies

Use ComposerRequireChecker to detect transitive Composer dependencies.

License

The Yii Proxy Middleware is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack