承接 yiisoft/proxy-middleware 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

yiisoft/proxy-middleware

Composer 安装命令:

composer require yiisoft/proxy-middleware

包简介

Yii Proxy Middleware

README 文档

README

Yii

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)
        };
    }
}

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

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

yiisoft/proxy-middleware 适用场景与选型建议

yiisoft/proxy-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.55k 次下载、GitHub Stars 达 7, 最近一次更新时间为 2023 年 06 月 30 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「framework」 「middleware」 「yii」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 yiisoft/proxy-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 yiisoft/proxy-middleware 我们能提供哪些服务?
定制开发 / 二次开发

基于 yiisoft/proxy-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.55k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 7
  • 点击次数: 13
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 7
  • Watchers: 12
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2023-06-30