Skip to content

feat(middleware): add TrustedProxyMiddleware for reverse-proxy deploy…#3453

Open
ErfanMomeniii wants to merge 1 commit into
slimphp:5.xfrom
ErfanMomeniii:add-trust-proxy
Open

feat(middleware): add TrustedProxyMiddleware for reverse-proxy deploy…#3453
ErfanMomeniii wants to merge 1 commit into
slimphp:5.xfrom
ErfanMomeniii:add-trust-proxy

Conversation

@ErfanMomeniii
Copy link
Copy Markdown
Contributor

@ErfanMomeniii ErfanMomeniii commented Jun 6, 2026

Summary

Adds TrustedProxyMiddleware (PSR-15), which resolves the real client IP and external URI when Slim runs behind a reverse proxy. Without it, REMOTE_ADDR and the request URI reflect the proxy rather than the client, silently corrupting rate limiting, audit logs, geo-blocking, and absolute URL generation in any non-trivial deployment.

Behavior

  • Parses RFC 7239 Forwarded first; falls back to X-Forwarded-For/Proto/Host/Port.
  • Walks the for chain right-to-left past trusted hops; returns the first untrusted address as the originating client.
  • Publishes the result as the client_ip request attribute and rewrites the URI scheme/host/port via PSR-7 withUri().
  • Accepts trusted proxies as individual IPs or CIDR ranges, IPv4 or IPv6.

Safety

Forwarded headers are honored only when REMOTE_ADDR matches the configured trusted-proxy whitelist. The list is empty by default, so the middleware is a no-op until explicitly opted in — it cannot introduce a spoofing vector through being installed.

Usage

$app->add(
    (new TrustedProxyMiddleware())->withTrustedProxies(['10.0.0.0/8', '172.16.0.0/12'])
);

// Downstream:
$ip  = $request->getAttribute('client_ip');

@ErfanMomeniii
Copy link
Copy Markdown
Contributor Author

Hi @odan @akrabat, please review it. Thanks

@coveralls
Copy link
Copy Markdown

Coverage Status

coverage: 95.291% (-1.1%) from 96.432% — ErfanMomeniii:add-trust-proxy into slimphp:5.x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants