From 3704bc6e7a53b18e2087090f02b95c63a2918da1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Mon, 23 Nov 2026 11:45:11 +0300 Subject: [PATCH 1/2] docs: fix the proxy, CORS and redirect-cookie recipes - Proxy recipe: case-insensitive hop-by-hop removal (including headers named in `Connection`, and `Trailer`), derive `Host` from the upstream URI, cache only credential-free GET responses - CORS recipe: echo `Origin` only when it is on an allow-list - Redirect recipe: add `Secure` to the session cookie --- docs/Recipe-JSON-Response.md | 22 ++++++++++------ docs/Recipe-Proxying-Requests.md | 44 +++++++++++++++++++++++--------- docs/Recipe-Redirect.md | 4 ++- 3 files changed, 49 insertions(+), 21 deletions(-) diff --git a/docs/Recipe-JSON-Response.md b/docs/Recipe-JSON-Response.md index 0c0b0fd..2114d38 100644 --- a/docs/Recipe-JSON-Response.md +++ b/docs/Recipe-JSON-Response.md @@ -95,14 +95,20 @@ $response = (new Response(200, [ use Psr\Http\Message\ServerRequestInterface; function jsonHandler(ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface { - $origin = $request->getHeaderLine('Origin') ?: '*'; - - $cors = [ - 'Access-Control-Allow-Origin' => $origin, - 'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS', - 'Access-Control-Allow-Headers' => 'Content-Type, Authorization', - 'Vary' => 'Origin', - ]; + // Echo the Origin back only when it is on your allow-list. Reflecting any + // Origin is the same as "*", and becomes a hole the moment you add + // Access-Control-Allow-Credentials. For other origins, send no CORS headers. + $allowedOrigins = ['https://app.example.com']; + $origin = $request->getHeaderLine('Origin'); + + $cors = ['Vary' => 'Origin']; + if (in_array($origin, $allowedOrigins, true)) { + $cors += [ + 'Access-Control-Allow-Origin' => $origin, + 'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS', + 'Access-Control-Allow-Headers' => 'Content-Type, Authorization', + ]; + } if ($request->getMethod() === 'OPTIONS') { return new \InitPHP\HTTP\Message\Response(204, $cors); diff --git a/docs/Recipe-Proxying-Requests.md b/docs/Recipe-Proxying-Requests.md index d19baf2..f90369e 100644 --- a/docs/Recipe-Proxying-Requests.md +++ b/docs/Recipe-Proxying-Requests.md @@ -16,26 +16,43 @@ $upstreamUri = $incoming->getUri() ->withHost('upstream.internal') ->withPort(443); -// 2) Strip hop-by-hop headers that MUST NOT be forwarded. -$hopByHop = ['Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', - 'TE', 'Trailers', 'Transfer-Encoding', 'Upgrade']; -$headers = array_diff_key($incoming->getHeaders(), array_flip($hopByHop)); +// 2) Hop-by-hop headers MUST NOT be forwarded. Header names are +// case-insensitive ("transfer-encoding" is the same header), and any header +// named in "Connection: a, b" is hop-by-hop as well. +function hopByHopNames(\Psr\Http\Message\MessageInterface $message): array +{ + $names = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', + 'te', 'trailer', 'transfer-encoding', 'upgrade']; + foreach (explode(',', $message->getHeaderLine('Connection')) as $name) { + $names[] = strtolower(trim($name)); + } + + return $names; +} -// 3) Build the upstream request from the incoming body verbatim. +// 3) Build the upstream request from the incoming body verbatim. "Host" is not +// copied either: the Request derives it from $upstreamUri, so the upstream +// sees its own host and not the one the client chose. +$skip = [...hopByHopNames($incoming), 'host']; $outgoing = new Request( $incoming->getMethod(), $upstreamUri, - $headers, + [], $incoming->getBody(), $incoming->getProtocolVersion() ); +foreach ($incoming->getHeaders() as $name => $values) { + if (!in_array(strtolower((string) $name), $skip, true)) { + $outgoing = $outgoing->withHeader((string) $name, $values); + } +} // 4) Ship it. $client = (new Client())->withTimeout(30); $response = $client->sendRequest($outgoing); // 5) Strip hop-by-hop on the way out, then emit. -foreach ($hopByHop as $h) { +foreach (hopByHopNames($response) as $h) { $response = $response->withoutHeader($h); } @@ -73,13 +90,16 @@ $outgoing = $outgoing ### Caching -The PSR-18 client gives you the `ResponseInterface` directly — wrap it in any cache decorator before emitting: +The PSR-18 client gives you the `ResponseInterface` directly — wrap it in any cache decorator before emitting. Only cache what is identical for every caller: a `GET` that carries no credentials. A response fetched with an `Authorization` or `Cookie` header belongs to one user, and a cache key that ignores those headers would hand it to the next: ```php -$response = $cache->fetchOrStore( - cacheKey($outgoing), - fn () => $client->sendRequest($outgoing) -); +$cacheable = $outgoing->getMethod() === 'GET' + && !$outgoing->hasHeader('Authorization') + && !$outgoing->hasHeader('Cookie'); + +$response = $cacheable + ? $cache->fetchOrStore((string) $outgoing->getUri(), fn () => $client->sendRequest($outgoing)) + : $client->sendRequest($outgoing); ``` The package itself ships no caching layer; that's deliberate. diff --git a/docs/Recipe-Redirect.md b/docs/Recipe-Redirect.md index 8f13d12..e0863d2 100644 --- a/docs/Recipe-Redirect.md +++ b/docs/Recipe-Redirect.md @@ -56,12 +56,14 @@ PSR-7 leaves cookie handling to your session middleware; preserve the session by $response = (new Response()) ->redirect('/dashboard', 302) ->withAddedHeader('Set-Cookie', sprintf( - '%s=%s; Path=/; HttpOnly; SameSite=Lax', + '%s=%s; Path=/; Secure; HttpOnly; SameSite=Lax', session_name(), session_id() )); ``` +Keep `Secure` and `HttpOnly` on a session cookie: without `Secure` the id is also sent over plain HTTP, and without `HttpOnly` a script injected into the page can read it. (Serve the site over HTTPS; for plain-HTTP local development, drop `Secure` there only.) + ## Validation `redirect()` raises `InvalidArgumentException` if you pass anything that isn't a string or `Psr\Http\Message\UriInterface`: From 361fedf3ee6ecd6d35b237385f388f6675ffa7d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 08:02:57 +0300 Subject: [PATCH 2/2] docs: state the conditions for caching proxied responses - Replace the cache snippet with the conditions under which a proxied response may be shared (request, key, response, stored data) - Fix the stale reference to $headers in the authentication note --- docs/Recipe-Proxying-Requests.md | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/docs/Recipe-Proxying-Requests.md b/docs/Recipe-Proxying-Requests.md index f90369e..6513cbf 100644 --- a/docs/Recipe-Proxying-Requests.md +++ b/docs/Recipe-Proxying-Requests.md @@ -80,7 +80,7 @@ $response = $response->withHeader('X-Trace-Id', $traceId); ### Authentication -Add upstream auth on the way out (the incoming request's own `Authorization` header was already in `$headers`; strip it if you're using different credentials per leg): +Add upstream auth on the way out (the incoming request's own `Authorization` header was already copied to `$outgoing`; strip it if you're using different credentials per leg): ```php $outgoing = $outgoing @@ -90,19 +90,14 @@ $outgoing = $outgoing ### Caching -The PSR-18 client gives you the `ResponseInterface` directly — wrap it in any cache decorator before emitting. Only cache what is identical for every caller: a `GET` that carries no credentials. A response fetched with an `Authorization` or `Cookie` header belongs to one user, and a cache key that ignores those headers would hand it to the next: +The PSR-18 client gives you the `ResponseInterface` directly, so you can put any PSR-16 cache or cache decorator around `sendRequest()`. The package ships no caching layer, and the recipe above is **not** safe to cache as it stands: it forwards nearly every client header, so a cached response can carry one client's identity or influence to the next. Cache only when all of these hold: -```php -$cacheable = $outgoing->getMethod() === 'GET' - && !$outgoing->hasHeader('Authorization') - && !$outgoing->hasHeader('Cookie'); - -$response = $cacheable - ? $cache->fetchOrStore((string) $outgoing->getUri(), fn () => $client->sendRequest($outgoing)) - : $client->sendRequest($outgoing); -``` +- **The request is shared by construction.** Use `GET`, and build the upstream request from scratch with an allow-list of headers (for example only `Accept`) instead of copying the client's. Never cache a request that carries `Authorization`, `Cookie`, an API-key header or any other credential, and do not forward `X-Forwarded-Host` or other values derived from the client's `Host`: the upstream may put them into links or redirects in a response that everyone then receives. +- **The cache key covers everything that shapes the response**: the upstream URI plus the value of every header you forward. +- **The response is shareable.** Store only a `200` that has no `Set-Cookie` (a cached `Set-Cookie` hands one visitor's session id to all the others), whose `Cache-Control` does not contain `private`, `no-store` or `no-cache`, and whose `Vary` is absent or names only headers you put in the key (never `*`). +- **You store plain data**, such as the status code, the headers and the body as a string, not the `ResponseInterface` with its stream. -The package itself ships no caching layer; that's deliberate. +If any of these is not true, send the request through without caching it. ### Streaming proxy