From 9c9bbf4601e72a3683f6264fae4cb7212faf5f0b Mon Sep 17 00:00:00 2001 From: Sajeeb Ahamed Date: Mon, 16 Nov 2026 18:10:43 +0600 Subject: [PATCH] Allow middleware to set headers on the request Request exposed headers for reading only, so middleware had no way to attach a tenant, trace id or similar header for the controller to read. Request gains set_header(), with_headers(), remove_header() and has_header(). Names are normalised the same way get_header() reads them. Scalars are stored as strings, arrays of scalars as multiple values, null removes a header, and any other value throws InvalidArgumentException without touching the existing header. with_headers() merges and keeps headers it does not name. Only the header bag changes: server parameters and ip() are untouched, so setting X-Forwarded-For or CF-Connecting-IP cannot spoof the client address. $headers now defaults to [] so a fresh Request works. Framework\Contracts\Request declares the four methods. A class that implements the contract directly, rather than extending Http\Request, must add them. Includes the http-request-headers spec, the archived OpenSpec change, docs in routing-examples.md section 13 and a 3.3.4 CHANGELOG entry. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + docs/routing-examples.md | 34 +++ .../.openspec.yaml | 2 + .../design.md | 43 ++++ .../proposal.md | 32 +++ .../specs/http-request-headers/spec.md | 179 ++++++++++++++ .../tasks.md | 31 +++ openspec/specs/http-request-headers/spec.md | 179 ++++++++++++++ src/Contracts/Request.php | 49 ++++ src/Http/Request.php | 91 ++++++- tests/Unit/Http/RequestHeaderTest.php | 224 ++++++++++++++++++ tests/Unit/RouteMiddlewareTest.php | 47 ++++ 12 files changed, 922 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/archive/2026-11-16-add-request-header-mutation/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-16-add-request-header-mutation/design.md create mode 100644 openspec/changes/archive/2026-11-16-add-request-header-mutation/proposal.md create mode 100644 openspec/changes/archive/2026-11-16-add-request-header-mutation/specs/http-request-headers/spec.md create mode 100644 openspec/changes/archive/2026-11-16-add-request-header-mutation/tasks.md create mode 100644 openspec/specs/http-request-headers/spec.md create mode 100644 tests/Unit/Http/RequestHeaderTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 4943aaa..6c8f584 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.3.4] + +### Added + +- `Request` can now set headers, so middleware can attach them for the + controller: `set_header()`, `with_headers()`, `remove_header()` and + `has_header()`. Values are stored as strings, `null` removes a header, and + server parameters (and so `ip()`) are never changed. +- `Framework\Contracts\Request` declares the four new methods. A class that + implements the contract directly, rather than extending `Http\Request`, must + add them. + ## [3.3.3] ### Changed diff --git a/docs/routing-examples.md b/docs/routing-examples.md index 19a6d41..6da0c27 100644 --- a/docs/routing-examples.md +++ b/docs/routing-examples.md @@ -650,6 +650,40 @@ class CheckoutRequest extends FormRequest > CSRF is not built-in for v1. Verify nonces in a Form Request or custom middleware with `wp_verify_nonce()`. +### Setting request headers from middleware + +Middleware receives the same `Request` instance the controller (or closure) gets, so headers set on it are visible to the handler: + +```php +class TenantMiddleware implements Middleware +{ + public function handle(RequestContract $request, callable $next) + { + $request->set_header('X-Tenant', resolve_tenant_slug()); + + $request->with_headers([ + 'X-Trace-Id' => wp_generate_uuid4(), + 'X-Debug' => null, // null removes the header + ]); + + if ($request->has_header('X-Legacy-Auth')) { + $request->remove_header('X-Legacy-Auth'); + } + + return $next($request); + } +} + +// In the controller: +$tenant = $request->header('X-Tenant'); +``` + +- `set_header($name, $value)` replaces any existing values. Scalars are stored as strings (`42` → `'42'`), an array of scalars is stored as multiple values (`header()` returns the first, `get_headers()` returns them all), and `null` removes the header. Any other value throws `InvalidArgumentException`. +- `with_headers(array)` applies `set_header()` per entry and leaves other headers untouched. Entries are applied in order, so an invalid entry throws after the earlier ones are already set. +- `remove_header($name)` is a no-op when the header is absent. `has_header($name)` reports presence. +- Names match the way `header()` reads them: `X-Tenant`, `x-tenant` and `x_tenant` are the same header. +- Only the request's header bag changes. Server parameters are not touched, so setting `X-Forwarded-For` or `CF-Connecting-IP` does **not** change `$request->ip()`, and the underlying `WP_REST_Request` is not updated. + --- diff --git a/openspec/changes/archive/2026-11-16-add-request-header-mutation/.openspec.yaml b/openspec/changes/archive/2026-11-16-add-request-header-mutation/.openspec.yaml new file mode 100644 index 0000000..90080a9 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-add-request-header-mutation/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/archive/2026-11-16-add-request-header-mutation/design.md b/openspec/changes/archive/2026-11-16-add-request-header-mutation/design.md new file mode 100644 index 0000000..4857af3 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-add-request-header-mutation/design.md @@ -0,0 +1,43 @@ +## Context + +See proposal.md — Why. Relevant current state: + +- `Request::$headers` holds `normalised_name => [value, ...]`. It is filled from `WP_REST_Request::get_headers()` (REST) or `extract_headers($server)` (raw HTTP). It has no default, so on a fresh `new Request()` it is `null`. +- `prepare_header_name()` lowercases a name and turns `-` into `_`, which matches WordPress's `WP_REST_Request::canonicalize_header_name()`. `get_header()` normalises the name and returns `[0]`. +- `ip()` reads `$this->server` (falling back to `Superglobals::server()`), never `$this->headers`. +- The middleware pipeline (`Route::build_middleware_pipeline`) passes one `Request` instance through, and the REST path keeps it as `resolved_request` for the controller. Instance mutation is therefore enough. `RouteMiddlewareTest::test_middleware_mutations_reach_controller` already proves this for attributes. + +## Goals / Non-Goals + +**Goals:** +- Give middleware a small, predictable way to write headers, built on the storage shape and normalisation that already exist. + +**Non-Goals:** +- Writing headers back to `WP_REST_Request`, `$_SERVER`, or `$this->server`. +- Immutable/`with*`-returns-a-clone semantics (PSR-7 style). The framework mutates `Request` in place everywhere else (`merge`, `set_route_params`, `__set`). +- Changes to `Response` or `Client\Request` header APIs, despite the inconsistent meaning of `with_headers` across them. + +## Decisions + +**1. `set_header` delegates to a single normaliser.** `set_header` normalises the name via `prepare_header_name()`. It then hands `null` to `remove_header()`. Otherwise it converts the value to a list of strings and assigns `$this->headers[$name] = $values`. `with_headers` is a `foreach` over `set_header`, so per-key behaviour can't drift. +*Alternative:* `array_merge` the normalised map in `with_headers`. Rejected because it would skip casting, null removal and validation. + +**2. Validate the whole value before writing.** The value-to-list conversion checks every element (scalar only) before any assignment. A rejected value then leaves the header untouched, as the spec requires. Booleans cast with `(string)` (`true` → `'1'`, `false` → `''`), which is how PHP would serialise them. +*Note:* `with_headers` is not atomic across keys. If a later entry is invalid, earlier entries are already applied. The spec only requires per-header atomicity, and doing more would mean a validate-all pre-pass for no real use case. Document this in the docblock. + +**3. Exception type.** `InvalidArgumentException` is already imported in `Request.php` and already used there via `throw_if` in `route()`. Use the same `throw_unless(..., InvalidArgumentException::class)` helper style. + +**4. `has_header` uses `array_key_exists` on the normalised name**, not `isset`. A header set to `false` stores `['']`, which is present. `has()` uses `isset` for attributes, but that would be wrong here only for a `null` slot, and `null` is never stored, so either works. `array_key_exists` states the intent. + +**5. `$headers` defaults to `[]`.** The property declaration changes to `protected $headers = [];`. The docblock `@var array` already claims this. Both `make_request` and `make_from_http` still overwrite it. + +**6. Contract addition.** The four signatures are added to `Framework\Contracts\Request` (user decision). `set_header(string $name, $value)`, `with_headers(array $headers)`, `remove_header(string $name)` and `has_header(string $name)` have no return type declarations, matching the rest of the contract and class. + +**7. Docblocks** carry `@since 3.3.4` (user decision), with `@throws InvalidArgumentException` on `set_header` and `with_headers`. + +## Risks / Trade-offs + +- [Downstream implementers of `Contracts\Request` fatally error on upgrade] → Call it out in the CHANGELOG under 3.3.4. Nothing in this repo or the scoped `example/` implements the contract besides `Http\Request`. Consumers that extend `Http\Request` (the normal pattern) are unaffected. +- [Middleware sets `X-Forwarded-For` / `CF-Connecting-IP` expecting `ip()` to change] → By design it won't (spec: isolation requirement). Say so in the docs subsection. +- [Header names that differ only in `-` vs `_` collide] → This already happens when reading, and WordPress does the same. No change. +- [Partial application on an invalid entry in `with_headers`] → Documented, per decision 2. diff --git a/openspec/changes/archive/2026-11-16-add-request-header-mutation/proposal.md b/openspec/changes/archive/2026-11-16-add-request-header-mutation/proposal.md new file mode 100644 index 0000000..64e00ff --- /dev/null +++ b/openspec/changes/archive/2026-11-16-add-request-header-mutation/proposal.md @@ -0,0 +1,32 @@ +## Why + +`Framework\Http\Request` exposes request headers for reading (`get_header`, `header`, `get_headers`) but offers no way to write them. Middleware is the natural place to enrich a request — resolving a tenant, attaching a trace or correlation id, normalising an auth header — and today it has nowhere to put that information on the header bag the controller reads from. Because the middleware pipeline already passes the same `Request` instance through to the controller, the only missing piece is a mutation API. + +## What Changes + +- Add `set_header($name, $value)` to `Framework\Http\Request`: replaces the stored values of a header. Scalars are cast to string and stored as a single value; an array of scalars is stored as multiple values; `null` removes the header; any other type throws `InvalidArgumentException`. +- Add `with_headers(array $headers)`: merges many headers at once by applying `set_header` per key, leaving headers not named in the array untouched (a `null` entry removes that header). +- Add `remove_header($name)`: removes a header; a no-op when absent. +- Add `has_header($name)`: reports whether a header is present. +- All four normalise the name exactly as `get_header` does (`X-Tenant` ≡ `x-tenant` ≡ `x_tenant`); the setters return `$this` for chaining. +- Mutations touch the header bag only. `$server`, `ip()` and the originating `WP_REST_Request` are not affected, so middleware cannot alter the client address by setting `X-Forwarded-For`. +- Initialise `Request::$headers` to `[]` so the API works on a freshly constructed request. +- **BREAKING** (for implementers only): the four methods are declared on `Framework\Contracts\Request`. Any downstream class that implements the contract directly must add them. Inside this repository only `Framework\Http\Request` implements it. The change ships as 3.3.4 by decision; callers of the API are unaffected. + +## Capabilities + +### New Capabilities + +- `http-request-headers`: reading and mutating the headers carried by an incoming framework `Request`, including name normalisation, value handling, merge semantics, and the guarantee that header mutation does not affect server parameters or client address resolution. + +### Modified Capabilities + + + +## Impact + +- `src/Http/Request.php` — four new public methods, `$headers` default. +- `src/Contracts/Request.php` — four new method declarations (implementer-facing BC break). +- `tests/Unit/Http/` — new unit tests; `tests/Unit/RouteMiddlewareTest.php` (or a sibling) — a pipeline test proving a middleware-set header reaches the controller. +- `docs/routing-examples.md` §13 — new subsection with a middleware example. +- `CHANGELOG.md` — `[3.3.4]` "Added" entry, noting the contract addition. diff --git a/openspec/changes/archive/2026-11-16-add-request-header-mutation/specs/http-request-headers/spec.md b/openspec/changes/archive/2026-11-16-add-request-header-mutation/specs/http-request-headers/spec.md new file mode 100644 index 0000000..84c5b6a --- /dev/null +++ b/openspec/changes/archive/2026-11-16-add-request-header-mutation/specs/http-request-headers/spec.md @@ -0,0 +1,179 @@ +## Purpose + +Defines how code handling an incoming framework request — middleware in particular — reads, sets, merges, and removes the headers the request carries, and guarantees that doing so never changes server parameters or how the client address is resolved. + +## ADDED Requirements + +### Requirement: Header names are matched case- and separator-insensitively + +Every header operation on the request (read, set, merge, remove, presence check) SHALL treat a header name case-insensitively and SHALL treat `-` and `_` as equivalent, so that `X-Tenant`, `x-tenant`, and `x_tenant` all refer to the same header. + +#### Scenario: Set with one spelling, read with another + +- **WHEN** a header is set as `X-Tenant` with value `acme` +- **THEN** reading `x_tenant` MUST return `acme` +- **AND** reading `x-tenant` MUST return `acme` + +#### Scenario: Presence check uses the same matching + +- **WHEN** a header is set as `X-Tenant` +- **THEN** checking for `x_tenant` MUST report it present + +### Requirement: Setting a single header replaces its values + +The request SHALL allow a single header to be set. Setting a header MUST replace any values previously held for it. A scalar value (string, integer, float, or boolean) MUST be stored as one string value. An array of scalars MUST be stored as that many string values, in order. The operation MUST return the request itself so calls can be chained. + +#### Scenario: Setting a new header + +- **WHEN** a header `X-Trace` that is not present is set to `abc` +- **THEN** reading `X-Trace` MUST return `abc` + +#### Scenario: Setting an existing header replaces it + +- **WHEN** the request carries `X-Trace` with value `a` +- **AND** `X-Trace` is set to `b` +- **THEN** reading `X-Trace` MUST return `b` +- **AND** the full header list MUST hold exactly one value, `b`, for `X-Trace` + +#### Scenario: Scalar values are stored as strings + +- **WHEN** `X-User-Id` is set to the integer `42` +- **THEN** reading `X-User-Id` MUST return the string `42` + +#### Scenario: Array values are stored as multiple values + +- **WHEN** `Accept` is set to the array `['text/html', 'application/json']` +- **THEN** the full header list MUST hold the values `text/html` and `application/json` for `Accept`, in that order +- **AND** reading `Accept` MUST return `text/html` + +#### Scenario: Setting returns the request for chaining + +- **WHEN** two headers are set in one chained expression +- **THEN** both headers MUST be present on the request + +### Requirement: Setting a header to null removes it + +Setting a header to `null` SHALL remove that header from the request, with the same effect as removing it explicitly. + +#### Scenario: Null removes an existing header + +- **WHEN** the request carries `X-Debug` +- **AND** `X-Debug` is set to `null` +- **THEN** the request MUST report `X-Debug` as not present + +#### Scenario: Null on an absent header is harmless + +- **WHEN** `X-Debug` is not present +- **AND** `X-Debug` is set to `null` +- **THEN** no error MUST be raised +- **AND** `X-Debug` MUST remain not present + +### Requirement: Invalid header values are rejected + +Setting a header to a value that is not `null`, a scalar, or an array whose every element is a scalar SHALL fail with an invalid-argument error, and MUST leave the request's headers unchanged. + +#### Scenario: Object value is rejected + +- **WHEN** a header is set to an object +- **THEN** an invalid-argument error MUST be raised +- **AND** the request's headers MUST be unchanged + +#### Scenario: Nested array value is rejected + +- **WHEN** a header is set to an array containing an array +- **THEN** an invalid-argument error MUST be raised +- **AND** the request's headers MUST be unchanged + +### Requirement: Merging many headers keeps unrelated headers + +The request SHALL allow several headers to be set in one call from a name-to-value map. Each entry MUST behave exactly as setting that header individually (replace, cast, `null` removes, invalid values rejected). Headers already on the request that are not named in the map MUST be left unchanged. The operation MUST return the request itself. + +#### Scenario: Merge adds and replaces while keeping others + +- **WHEN** the request carries `Accept` and `X-Trace: a` +- **AND** the map `X-Trace => b, X-Tenant => acme` is merged +- **THEN** `Accept` MUST be unchanged +- **AND** reading `X-Trace` MUST return `b` +- **AND** reading `X-Tenant` MUST return `acme` + +#### Scenario: Merge with a null entry removes that header + +- **WHEN** the request carries `X-Debug` +- **AND** the map `X-Debug => null` is merged +- **THEN** the request MUST report `X-Debug` as not present + +### Requirement: Removing a header + +The request SHALL allow a header to be removed. Removing a header that is not present MUST be a no-op. The operation MUST return the request itself. + +#### Scenario: Remove an existing header + +- **WHEN** the request carries `Authorization` +- **AND** `Authorization` is removed +- **THEN** the request MUST report `Authorization` as not present +- **AND** reading `Authorization` with a default MUST return the default + +#### Scenario: Remove an absent header + +- **WHEN** `X-Missing` is not present +- **AND** `X-Missing` is removed +- **THEN** no error MUST be raised + +### Requirement: Checking header presence + +The request SHALL report whether a header is present, using the name matching defined above. + +#### Scenario: Present and absent headers + +- **WHEN** the request carries `Content-Type` and not `X-Missing` +- **THEN** checking `content-type` MUST report present +- **AND** checking `X-Missing` MUST report not present + +### Requirement: Header mutation works on a request built from any source + +Setting, merging, removing, and checking headers SHALL work identically on a request built from a WordPress REST request, a request captured from raw HTTP input, and a freshly constructed request with no headers. + +#### Scenario: Fresh request accepts headers + +- **WHEN** a request is constructed with no input +- **AND** `X-Tenant` is set to `acme` +- **THEN** reading `X-Tenant` MUST return `acme` + +#### Scenario: Request from raw HTTP input + +- **WHEN** a request is built from server parameters carrying `HTTP_ACCEPT` +- **AND** `X-Tenant` is set to `acme` +- **THEN** both `Accept` and `X-Tenant` MUST be present + +### Requirement: Header mutation is isolated from server parameters and client address + +Changing headers on the request SHALL NOT change the request's server parameters, and SHALL NOT change the client address the request resolves. In particular, setting a forwarded-address header MUST NOT affect client address resolution, whether or not trusted proxies are configured. + +#### Scenario: Setting X-Forwarded-For does not change the client address + +- **WHEN** a request has a connecting address of `10.0.0.5` +- **AND** `X-Forwarded-For` is set to `1.2.3.4` on the request +- **THEN** the resolved client address MUST still be `10.0.0.5` + +#### Scenario: Setting X-Forwarded-For with a trusted proxy still has no effect + +- **WHEN** the connecting address `10.0.0.5` is a configured trusted proxy +- **AND** the original server parameters carry no forwarded-address header +- **AND** `X-Forwarded-For` is set to `1.2.3.4` on the request +- **THEN** the resolved client address MUST still be `10.0.0.5` + +### Requirement: Headers set by middleware reach the route handler + +A header set on the request by route middleware SHALL be visible to the controller or closure that handles that route, on both REST and site routes. + +#### Scenario: Middleware-set header visible in a REST controller + +- **WHEN** a REST route's middleware sets `X-Tenant` to `acme` on the request +- **AND** the route's controller reads `X-Tenant` from the request it receives +- **THEN** the controller MUST see `acme` + +#### Scenario: Middleware-set header visible in a closure route + +- **WHEN** a route's middleware sets `X-Tenant` to `acme` +- **AND** the route is handled by a closure that reads `X-Tenant` +- **THEN** the closure MUST see `acme` diff --git a/openspec/changes/archive/2026-11-16-add-request-header-mutation/tasks.md b/openspec/changes/archive/2026-11-16-add-request-header-mutation/tasks.md new file mode 100644 index 0000000..3e7ee8d --- /dev/null +++ b/openspec/changes/archive/2026-11-16-add-request-header-mutation/tasks.md @@ -0,0 +1,31 @@ +## 1. Tests first (red) + +- [x] 1.1 Create `tests/Unit/Http/RequestHeaderTest.php` (extends `Framework\Tests\Unit\TestCase`) covering name normalisation: set as `X-Tenant`, read as `x_tenant` / `x-tenant`; `has_header` with alternate spelling +- [x] 1.2 Add tests for `set_header`: new header, replacing an existing one (exactly one value left), int → `'42'`, bool casting, array → multiple ordered values with `header()` returning the first, chaining returns the same instance +- [x] 1.3 Add tests for `null` handling: `set_header(..., null)` removes an existing header; on an absent header it is a no-op without error +- [x] 1.4 Add tests for invalid values: object and nested array throw `InvalidArgumentException` and leave the existing header value unchanged +- [x] 1.5 Add tests for `with_headers`: adds and replaces while keeping unrelated headers; a `null` entry removes; returns the same instance +- [x] 1.6 Add tests for `remove_header` (existing → absent, `header()` returns default; absent → no error) and `has_header` (present / absent) +- [x] 1.7 Add tests for sources: fresh `new Request()` accepts `set_header`; a request from `make_from_http()` with `HTTP_ACCEPT` keeps `Accept` and gains `X-Tenant`; a request from `make_request(WP_REST_Request)` accepts mutation +- [x] 1.8 Add isolation tests: `set_header('X-Forwarded-For', '1.2.3.4')` leaves `ip()` at `REMOTE_ADDR`, both without trusted proxies and with `REMOTE_ADDR` configured in `app.trusted_proxies` +- [x] 1.9 In `tests/Unit/RouteMiddlewareTest.php`, add a header-setting middleware double and tests that a middleware-set `X-Tenant` is visible in a REST controller and in a closure route (mirroring `test_middleware_mutations_reach_controller` / `_closure`) +- [x] 1.10 Run `composer test:unit -- --filter 'RequestHeaderTest|RouteMiddlewareTest'` → verify the new tests fail for the missing methods + +## 2. Implementation + +- [x] 2.1 `src/Contracts/Request.php`: declare `set_header(string $name, $value)`, `with_headers(array $headers)`, `remove_header(string $name)`, `has_header(string $name)` with full docblocks (`@param`, `@return`, `@throws` where applicable, `@since 3.3.4`) +- [x] 2.2 `src/Http/Request.php`: default `protected $headers = [];` +- [x] 2.3 `src/Http/Request.php`: add `has_header()` and `remove_header()` next to `get_header()`/`header()`, normalising via `prepare_header_name()` +- [x] 2.4 `src/Http/Request.php`: add `set_header()`: normalise the name; on `null` delegate to `remove_header()`; otherwise validate the whole value (scalar or array of scalars) before writing, cast to a list of strings, assign; throw `InvalidArgumentException` via `throw_unless` on invalid values; return `$this` +- [x] 2.5 `src/Http/Request.php`: add `with_headers()` as a loop over `set_header()`; the docblock notes that entries before an invalid one are already applied; return `$this` +- [x] 2.6 Run `composer test:unit -- --filter 'RequestHeaderTest|RouteMiddlewareTest'` → verify all new tests pass + +## 3. Docs and changelog + +- [x] 3.1 `docs/routing-examples.md` §13: add a "Setting request headers from middleware" subsection with a middleware example using `set_header` / `with_headers` / `remove_header` / `has_header`, stating that `ip()` and server parameters are unaffected; update the table of contents if subsections are listed +- [x] 3.2 `CHANGELOG.md`: add a `## [3.3.4]` section with an "Added" entry for the four methods and a note that `Framework\Contracts\Request` gained them (implementers must add them) + +## 4. Verification + +- [x] 4.1 Run `composer phpcs && composer test:unit` → verify both pass with no new warnings +- [x] 4.2 Run `openspec validate add-request-header-mutation --strict` → verify the change is valid diff --git a/openspec/specs/http-request-headers/spec.md b/openspec/specs/http-request-headers/spec.md new file mode 100644 index 0000000..7c5ae6a --- /dev/null +++ b/openspec/specs/http-request-headers/spec.md @@ -0,0 +1,179 @@ +## Purpose + +Defines how code handling an incoming framework request — middleware in particular — reads, sets, merges, and removes the headers the request carries, and guarantees that doing so never changes server parameters or how the client address is resolved. + +## Requirements + +### Requirement: Header names are matched case- and separator-insensitively + +Every header operation on the request (read, set, merge, remove, presence check) SHALL treat a header name case-insensitively and SHALL treat `-` and `_` as equivalent, so that `X-Tenant`, `x-tenant`, and `x_tenant` all refer to the same header. + +#### Scenario: Set with one spelling, read with another + +- **WHEN** a header is set as `X-Tenant` with value `acme` +- **THEN** reading `x_tenant` MUST return `acme` +- **AND** reading `x-tenant` MUST return `acme` + +#### Scenario: Presence check uses the same matching + +- **WHEN** a header is set as `X-Tenant` +- **THEN** checking for `x_tenant` MUST report it present + +### Requirement: Setting a single header replaces its values + +The request SHALL allow a single header to be set. Setting a header MUST replace any values previously held for it. A scalar value (string, integer, float, or boolean) MUST be stored as one string value. An array of scalars MUST be stored as that many string values, in order. The operation MUST return the request itself so calls can be chained. + +#### Scenario: Setting a new header + +- **WHEN** a header `X-Trace` that is not present is set to `abc` +- **THEN** reading `X-Trace` MUST return `abc` + +#### Scenario: Setting an existing header replaces it + +- **WHEN** the request carries `X-Trace` with value `a` +- **AND** `X-Trace` is set to `b` +- **THEN** reading `X-Trace` MUST return `b` +- **AND** the full header list MUST hold exactly one value, `b`, for `X-Trace` + +#### Scenario: Scalar values are stored as strings + +- **WHEN** `X-User-Id` is set to the integer `42` +- **THEN** reading `X-User-Id` MUST return the string `42` + +#### Scenario: Array values are stored as multiple values + +- **WHEN** `Accept` is set to the array `['text/html', 'application/json']` +- **THEN** the full header list MUST hold the values `text/html` and `application/json` for `Accept`, in that order +- **AND** reading `Accept` MUST return `text/html` + +#### Scenario: Setting returns the request for chaining + +- **WHEN** two headers are set in one chained expression +- **THEN** both headers MUST be present on the request + +### Requirement: Setting a header to null removes it + +Setting a header to `null` SHALL remove that header from the request, with the same effect as removing it explicitly. + +#### Scenario: Null removes an existing header + +- **WHEN** the request carries `X-Debug` +- **AND** `X-Debug` is set to `null` +- **THEN** the request MUST report `X-Debug` as not present + +#### Scenario: Null on an absent header is harmless + +- **WHEN** `X-Debug` is not present +- **AND** `X-Debug` is set to `null` +- **THEN** no error MUST be raised +- **AND** `X-Debug` MUST remain not present + +### Requirement: Invalid header values are rejected + +Setting a header to a value that is not `null`, a scalar, or an array whose every element is a scalar SHALL fail with an invalid-argument error, and MUST leave the request's headers unchanged. + +#### Scenario: Object value is rejected + +- **WHEN** a header is set to an object +- **THEN** an invalid-argument error MUST be raised +- **AND** the request's headers MUST be unchanged + +#### Scenario: Nested array value is rejected + +- **WHEN** a header is set to an array containing an array +- **THEN** an invalid-argument error MUST be raised +- **AND** the request's headers MUST be unchanged + +### Requirement: Merging many headers keeps unrelated headers + +The request SHALL allow several headers to be set in one call from a name-to-value map. Each entry MUST behave exactly as setting that header individually (replace, cast, `null` removes, invalid values rejected). Headers already on the request that are not named in the map MUST be left unchanged. The operation MUST return the request itself. + +#### Scenario: Merge adds and replaces while keeping others + +- **WHEN** the request carries `Accept` and `X-Trace: a` +- **AND** the map `X-Trace => b, X-Tenant => acme` is merged +- **THEN** `Accept` MUST be unchanged +- **AND** reading `X-Trace` MUST return `b` +- **AND** reading `X-Tenant` MUST return `acme` + +#### Scenario: Merge with a null entry removes that header + +- **WHEN** the request carries `X-Debug` +- **AND** the map `X-Debug => null` is merged +- **THEN** the request MUST report `X-Debug` as not present + +### Requirement: Removing a header + +The request SHALL allow a header to be removed. Removing a header that is not present MUST be a no-op. The operation MUST return the request itself. + +#### Scenario: Remove an existing header + +- **WHEN** the request carries `Authorization` +- **AND** `Authorization` is removed +- **THEN** the request MUST report `Authorization` as not present +- **AND** reading `Authorization` with a default MUST return the default + +#### Scenario: Remove an absent header + +- **WHEN** `X-Missing` is not present +- **AND** `X-Missing` is removed +- **THEN** no error MUST be raised + +### Requirement: Checking header presence + +The request SHALL report whether a header is present, using the name matching defined above. + +#### Scenario: Present and absent headers + +- **WHEN** the request carries `Content-Type` and not `X-Missing` +- **THEN** checking `content-type` MUST report present +- **AND** checking `X-Missing` MUST report not present + +### Requirement: Header mutation works on a request built from any source + +Setting, merging, removing, and checking headers SHALL work identically on a request built from a WordPress REST request, a request captured from raw HTTP input, and a freshly constructed request with no headers. + +#### Scenario: Fresh request accepts headers + +- **WHEN** a request is constructed with no input +- **AND** `X-Tenant` is set to `acme` +- **THEN** reading `X-Tenant` MUST return `acme` + +#### Scenario: Request from raw HTTP input + +- **WHEN** a request is built from server parameters carrying `HTTP_ACCEPT` +- **AND** `X-Tenant` is set to `acme` +- **THEN** both `Accept` and `X-Tenant` MUST be present + +### Requirement: Header mutation is isolated from server parameters and client address + +Changing headers on the request SHALL NOT change the request's server parameters, and SHALL NOT change the client address the request resolves. In particular, setting a forwarded-address header MUST NOT affect client address resolution, whether or not trusted proxies are configured. + +#### Scenario: Setting X-Forwarded-For does not change the client address + +- **WHEN** a request has a connecting address of `10.0.0.5` +- **AND** `X-Forwarded-For` is set to `1.2.3.4` on the request +- **THEN** the resolved client address MUST still be `10.0.0.5` + +#### Scenario: Setting X-Forwarded-For with a trusted proxy still has no effect + +- **WHEN** the connecting address `10.0.0.5` is a configured trusted proxy +- **AND** the original server parameters carry no forwarded-address header +- **AND** `X-Forwarded-For` is set to `1.2.3.4` on the request +- **THEN** the resolved client address MUST still be `10.0.0.5` + +### Requirement: Headers set by middleware reach the route handler + +A header set on the request by route middleware SHALL be visible to the controller or closure that handles that route, on both REST and site routes. + +#### Scenario: Middleware-set header visible in a REST controller + +- **WHEN** a REST route's middleware sets `X-Tenant` to `acme` on the request +- **AND** the route's controller reads `X-Tenant` from the request it receives +- **THEN** the controller MUST see `acme` + +#### Scenario: Middleware-set header visible in a closure route + +- **WHEN** a route's middleware sets `X-Tenant` to `acme` +- **AND** the route is handled by a closure that reads `X-Tenant` +- **THEN** the closure MUST see `acme` diff --git a/src/Contracts/Request.php b/src/Contracts/Request.php index 6e14941..2e4fc13 100644 --- a/src/Contracts/Request.php +++ b/src/Contracts/Request.php @@ -52,6 +52,55 @@ public function get_headers(); */ public function get_header(string $name, $default = null); + /** + * Set a single HTTP header on the request, replacing any existing values. + * + * @param string $name The name. + * @param mixed $value A scalar, an array of scalars, or null to remove the header. + * + * @return $this + * + * @throws \InvalidArgumentException When the value is neither null, a scalar, nor an array of scalars. + * + * @since 3.3.4 + */ + public function set_header(string $name, $value); + + /** + * Set several HTTP headers on the request, keeping headers that are not named. + * + * @param array $headers The headers, keyed by name. + * + * @return $this + * + * @throws \InvalidArgumentException When a value is neither null, a scalar, nor an array of scalars. + * + * @since 3.3.4 + */ + public function with_headers(array $headers); + + /** + * Remove an HTTP header from the request. + * + * @param string $name The name. + * + * @return $this + * + * @since 3.3.4 + */ + public function remove_header(string $name); + + /** + * Determine whether the request carries an HTTP header. + * + * @param string $name The name. + * + * @return bool + * + * @since 3.3.4 + */ + public function has_header(string $name); + /** * Get all request input attributes. * diff --git a/src/Http/Request.php b/src/Http/Request.php index 1e4ebc0..774d35e 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -72,7 +72,7 @@ class Request implements RequestContract, Arrayable * * @since 1.0.0 */ - protected $headers; + protected $headers = []; /** * The server parameters the request was built from. @@ -654,6 +654,95 @@ public function header(string $name, $default = null) return $this->get_header($name, $default); } + /** + * Set a single HTTP header on the request, replacing any existing values. + * + * Only the header bag changes. Server parameters, and therefore the client address resolved + * by `ip()`, are left alone so that a forwarded-address header set here cannot spoof it. + * + * @param string $name The name. + * @param mixed $value A scalar, an array of scalars, or null to remove the header. + * + * @return $this + * + * @throws InvalidArgumentException When the value is neither null, a scalar, nor an array of scalars. + * + * @since 3.3.4 + */ + public function set_header(string $name, $value) + { + if (is_null($value)) { + return $this->remove_header($name); + } + + $values = is_array($value) ? array_values($value) : [$value]; + + foreach ($values as $item) { + throw_unless( + is_scalar($item), + sprintf('The value of the "%s" header must be a scalar or an array of scalars.', $name), + InvalidArgumentException::class + ); + } + + $this->headers[$this->prepare_header_name($name)] = array_map('strval', $values); + + return $this; + } + + /** + * Set several HTTP headers on the request, keeping headers that are not named. + * + * Each entry is applied as `set_header()` would apply it, in order, so an invalid entry + * throws after the entries before it have already been applied. + * + * @param array $headers The headers, keyed by name. + * + * @return $this + * + * @throws InvalidArgumentException When a value is neither null, a scalar, nor an array of scalars. + * + * @since 3.3.4 + */ + public function with_headers(array $headers) + { + foreach ($headers as $name => $value) { + $this->set_header((string) $name, $value); + } + + return $this; + } + + /** + * Remove an HTTP header from the request. + * + * @param string $name The name. + * + * @return $this + * + * @since 3.3.4 + */ + public function remove_header(string $name) + { + unset($this->headers[$this->prepare_header_name($name)]); + + return $this; + } + + /** + * Determine whether the request carries an HTTP header. + * + * @param string $name The name. + * + * @return bool + * + * @since 3.3.4 + */ + public function has_header(string $name) + { + return array_key_exists($this->prepare_header_name($name), $this->headers); + } + /** * Get all cookies sent by the client. * diff --git a/tests/Unit/Http/RequestHeaderTest.php b/tests/Unit/Http/RequestHeaderTest.php new file mode 100644 index 0000000..8868ed4 --- /dev/null +++ b/tests/Unit/Http/RequestHeaderTest.php @@ -0,0 +1,224 @@ +set_header('X-Tenant', 'acme'); + + $this->assertSame('acme', $request->header('x_tenant')); + $this->assertSame('acme', $request->header('x-tenant')); + $this->assertTrue($request->has_header('x_tenant')); + } + + public function test_set_header_adds_a_new_header(): void + { + $request = (new Request())->set_header('X-Trace', 'abc'); + + $this->assertSame('abc', $request->get_header('X-Trace')); + } + + public function test_set_header_replaces_existing_values(): void + { + $request = (new Request())->set_header('X-Trace', 'a'); + $request->set_header('X-Trace', 'b'); + + $this->assertSame('b', $request->header('X-Trace')); + $this->assertSame(['b'], $request->get_headers()['x_trace']); + } + + public function test_set_header_casts_scalars_to_strings(): void + { + $request = (new Request()) + ->set_header('X-User-Id', 42) + ->set_header('X-Ratio', 1.5) + ->set_header('X-Yes', true) + ->set_header('X-No', false); + + $this->assertSame('42', $request->header('X-User-Id')); + $this->assertSame('1.5', $request->header('X-Ratio')); + $this->assertSame('1', $request->header('X-Yes')); + $this->assertSame('', $request->header('X-No')); + $this->assertTrue($request->has_header('X-No')); + } + + public function test_set_header_stores_array_values_in_order(): void + { + $request = (new Request())->set_header('Accept', ['text/html', 'application/json']); + + $this->assertSame(['text/html', 'application/json'], $request->get_headers()['accept']); + $this->assertSame('text/html', $request->header('Accept')); + } + + public function test_set_header_returns_the_same_request(): void + { + $request = new Request(); + $result = $request->set_header('X-One', '1')->set_header('X-Two', '2'); + + $this->assertSame($request, $result); + $this->assertTrue($request->has_header('X-One')); + $this->assertTrue($request->has_header('X-Two')); + } + + public function test_setting_null_removes_an_existing_header(): void + { + $request = (new Request())->set_header('X-Debug', '1'); + $request->set_header('X-Debug', null); + + $this->assertFalse($request->has_header('X-Debug')); + } + + public function test_setting_null_on_an_absent_header_is_harmless(): void + { + $request = (new Request())->set_header('X-Debug', null); + + $this->assertFalse($request->has_header('X-Debug')); + } + + public function test_object_value_is_rejected_and_header_kept(): void + { + $request = (new Request())->set_header('X-Trace', 'a'); + + try { + $request->set_header('X-Trace', new stdClass()); + $this->fail('Expected InvalidArgumentException.'); + } catch (InvalidArgumentException $exception) { + $this->assertSame(['a'], $request->get_headers()['x_trace']); + } + } + + public function test_nested_array_value_is_rejected_and_header_kept(): void + { + $request = (new Request())->set_header('X-Trace', 'a'); + + try { + $request->set_header('X-Trace', ['b', ['c']]); + $this->fail('Expected InvalidArgumentException.'); + } catch (InvalidArgumentException $exception) { + $this->assertSame(['a'], $request->get_headers()['x_trace']); + } + } + + public function test_with_headers_merges_and_keeps_unrelated_headers(): void + { + $request = (new Request()) + ->set_header('Accept', 'text/html') + ->set_header('X-Trace', 'a'); + + $result = $request->with_headers(['X-Trace' => 'b', 'X-Tenant' => 'acme']); + + $this->assertSame($request, $result); + $this->assertSame('text/html', $request->header('Accept')); + $this->assertSame('b', $request->header('X-Trace')); + $this->assertSame('acme', $request->header('X-Tenant')); + } + + public function test_with_headers_null_entry_removes_header(): void + { + $request = (new Request())->set_header('X-Debug', '1'); + $request->with_headers(['X-Debug' => null]); + + $this->assertFalse($request->has_header('X-Debug')); + } + + public function test_with_headers_rejects_invalid_values(): void + { + $this->expectException(InvalidArgumentException::class); + + (new Request())->with_headers(['X-Bad' => new stdClass()]); + } + + public function test_remove_header_removes_an_existing_header(): void + { + $request = (new Request())->set_header('Authorization', 'Bearer x'); + $result = $request->remove_header('authorization'); + + $this->assertSame($request, $result); + $this->assertFalse($request->has_header('Authorization')); + $this->assertSame('none', $request->header('Authorization', 'none')); + } + + public function test_remove_header_on_an_absent_header_is_harmless(): void + { + $request = (new Request())->remove_header('X-Missing'); + + $this->assertFalse($request->has_header('X-Missing')); + } + + public function test_has_header_reports_presence(): void + { + $request = (new Request())->make_from_http([], [], [], [ + 'REQUEST_METHOD' => 'GET', + 'CONTENT_TYPE' => 'application/json', + ]); + + $this->assertTrue($request->has_header('content-type')); + $this->assertFalse($request->has_header('X-Missing')); + } + + public function test_fresh_request_accepts_headers(): void + { + $request = new Request(); + + $this->assertSame([], $request->get_headers()); + + $request->set_header('X-Tenant', 'acme'); + + $this->assertSame('acme', $request->header('X-Tenant')); + } + + public function test_request_from_http_input_keeps_existing_headers(): void + { + $request = (new Request())->make_from_http([], [], [], [ + 'REQUEST_METHOD' => 'GET', + 'HTTP_ACCEPT' => 'text/html', + ]); + + $request->set_header('X-Tenant', 'acme'); + + $this->assertSame('text/html', $request->header('Accept')); + $this->assertSame('acme', $request->header('X-Tenant')); + } + + public function test_request_from_rest_request_accepts_mutation(): void + { + $rest_request = new WP_REST_Request('GET', '/test', [], ['accept' => ['text/html']]); + $request = Request::from_wp_rest_request($rest_request); + + $request->set_header('X-Tenant', 'acme'); + + $this->assertSame('text/html', $request->header('Accept')); + $this->assertSame('acme', $request->header('X-Tenant')); + $this->assertSame(['accept' => ['text/html']], $rest_request->get_headers()); + } + + public function test_setting_forwarded_for_does_not_change_the_client_address(): void + { + $request = (new ConfigurableRequest())->with_server(['REMOTE_ADDR' => '10.0.0.5']); + + $request->set_header('X-Forwarded-For', '1.2.3.4'); + + $this->assertSame('10.0.0.5', $request->ip()); + } + + public function test_setting_forwarded_for_with_a_trusted_proxy_has_no_effect(): void + { + $request = (new ConfigurableRequest()) + ->with_server(['REMOTE_ADDR' => '10.0.0.5']) + ->trust(['10.0.0.5']); + + $request->set_header('X-Forwarded-For', '1.2.3.4'); + $request->set_header('CF-Connecting-IP', '1.2.3.4'); + + $this->assertSame('10.0.0.5', $request->ip()); + } +} diff --git a/tests/Unit/RouteMiddlewareTest.php b/tests/Unit/RouteMiddlewareTest.php index 3b1ea27..953be21 100644 --- a/tests/Unit/RouteMiddlewareTest.php +++ b/tests/Unit/RouteMiddlewareTest.php @@ -112,6 +112,35 @@ public function test_middleware_mutations_reach_closure(): void $this->assertSame('mutated', $result); } + public function test_middleware_set_header_reaches_controller(): void + { + $route = Route::get('ping', [RouteMiddlewareTestHeaderController::class, 'show']) + ->middleware([RouteMiddlewareTestHeaderMiddleware::class]); + + $rest_request = $this->make_rest_request(); + $this->invoke_route_method($route, 'resolve_permission_callback', $rest_request); + + $callback = $this->invoke_route_method($route, 'resolve_route'); + $result = $callback($rest_request); + + $this->assertSame('acme', $result); + } + + public function test_middleware_set_header_reaches_closure(): void + { + $route = Route::get('ping', function (RequestContract $request) { + return $request->get_header('x_tenant'); + })->middleware([RouteMiddlewareTestHeaderMiddleware::class]); + + $rest_request = $this->make_rest_request(); + $this->invoke_route_method($route, 'resolve_permission_callback', $rest_request); + + $callback = $this->invoke_route_method($route, 'resolve_route'); + $result = $callback($rest_request); + + $this->assertSame('acme', $result); + } + public function test_model_binding_runs_in_callback_not_permission(): void { $wpdb = $this->bootstrap_model_testing(['prefix' => 'wp_']); @@ -273,6 +302,24 @@ public function handle($request, callable $next) } } +class RouteMiddlewareTestHeaderMiddleware implements Middleware +{ + public function handle($request, callable $next) + { + $request->set_header('X-Tenant', 'acme'); + + return $next($request); + } +} + +class RouteMiddlewareTestHeaderController +{ + public function show(RequestContract $request) + { + return $request->header('X-Tenant'); + } +} + class RouteMiddlewareTestController { public function show(RequestContract $request)