Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions docs/routing-examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-16
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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

<!-- None: no existing spec covers request headers. -->

## 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.
Original file line number Diff line number Diff line change
@@ -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`
Loading
Loading