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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,10 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- `GET /wp-json/headless/v1/search`: the site search in one shape, with front-end addresses (`headless/search/args` filter).
- `GET /wp-json/headless/v1/forms` and `/forms/{provider}/{id}`: forms and how to send them, from Contact Form 7 (`headless/forms/providers` filter for other plugins).
- `X-GraphQL-Preview` among the request headers CORS allows.
- `wp headless doctor`: checks on the running site, with the fix for each finding.
- `rest_plugins`: load only the listed plugins on REST requests (advanced, off by default).
- `tests/E2E/run.sh`: the contract checked over real HTTP.
- Fixed: a wrong `hl.` token was served as an anonymous request instead of answering 401 (WordPress works the user out lazily).
- Fixed: `wp headless theme install` was refused by WP-CLI (the action was not in the command's synopsis).
- Security review of the package, with these fixes: a redirect rule can no longer send a visitor to another site through `$1` (`/go/(.*)` to `/$1`), rules that repeat a repetition (`(a+)+`) are refused, the resolve route takes paths of 512 characters at most, the front gate sees `/wp-admin/../` as the home page, a rotated token never outlives the expiry it had, a preview token only opens posts of the site that made it (multisite), `preview.secret` must have 32 characters at least (the site refuses to start with a shorter one), search pages stop at 100.
- mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer.
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo
| --- | --- |
| Front gate | A request for a public page is redirected to the same path on your front end (302 by default), answered with a holding page, or with JSON. The administration, the login, `/wp-json`, `/graphql`, the cron, the uploads, `xmlrpc.php`, the sitemap and `robots.txt` are never touched; you add more with `allow`. |
| Head clean-up | Removes the generator, RSD, shortlink, feeds, emoji, oEmbed and REST discovery from the page head and the headers, and turns XML-RPC and the pingback header off. |
| Public surface | Feeds answer 404, the core sitemap is off (its URLs are WordPress's), and the WordPress host tells search engines not to index it (`X-Robots-Tag`, `robots.txt`, robots meta). |
| Public surface | Feeds answer 404 (a visitor of the WordPress host is first sent to the front end like for any page), the core sitemap is off (its URLs are WordPress's), and the WordPress host tells search engines not to index it (`X-Robots-Tag`, `robots.txt`, robots meta). |
| Empty theme | `wp headless theme install --activate` installs the one empty theme WordPress needs: without a valid theme it falls into recovery mode for administrators. |
| Status | `wp headless status` shows the setup and what looks wrong (no front URL, a front on the same host, no theme, WP-Cron). |
| CORS | WordPress answers any origin and allows credentials. The package answers the listed origins only (the front-end URL is always one), never `*`, with `Vary: Origin`, `https://*.example.com` patterns and preflight. |
Expand Down Expand Up @@ -267,7 +267,19 @@ Contact Form 7 is supported and verified against the real plugin in CI. A checkb

## Quality

The repository follows the [Pollora harness](https://github.com/Pollora/harness) (profile `core`): `composer qa` runs every gate.
The repository follows the [Pollora harness](https://github.com/Pollora/harness) (profile `core`): `composer qa` runs every gate. `tests/E2E/run.sh` (Docker) starts a throwaway WordPress with the package as a mu-plugin and checks the contract over real HTTP with `curl`: the gate, CORS, caching, tokens, preview, search, the doctor.

## What it costs

Measured on a throwaway WordPress with Yoast SEO, Polylang and WPGraphQL active (median of 60 requests, `rest_do_request` inside PHP, so without the network): the list of ten posts in full goes from 64 ms to 72 ms (the links in each content are rewritten), the same list with `_fields=id,title,link` from 4.4 ms to 4.7 ms, and a single post is unchanged (6.0 ms to 5.6 ms). Indicative: measure your own site.

## Doctor

`wp headless doctor` looks at the running site and says what exposes it or breaks the front end, with the fix for each finding (`--format=json` for a script; it exits with an error when a check fails): the front-end URL and HTTPS, CORS, the users route as a visitor sees it, a locked REST API, plain permalinks, preview, revalidation and its cron, WPGraphQL introspection, redirect loops and chains, the theme, displayed PHP errors.

## Loading fewer plugins on REST requests

Advanced and off by default: `rest_plugins => ['enabled' => true, 'keep' => ['advanced-custom-fields', 'wordpress-seo/wp-seo.php']]` loads only the listed plugins (a folder or a file) when the request is for `/wp-json/`. The API gets faster, but a plugin left out loses every route, post type, field and login it adds on those requests: list each one that adds any. Classic WordPress and Bedrock only (the mu-plugin reads it before the plugins load); plugins activated for a whole network are not touched.

## License

Expand Down
8 changes: 8 additions & 0 deletions config/headless.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,12 @@
'forms' => [
'enabled' => true,
],

// Advanced, off by default. On REST requests, load only these plugins (a file `acf/acf.php` or a folder `acf`): the API gets faster, but
// a plugin left out loses every route, type, field and login it adds on those requests. List each plugin that adds one. Classic WordPress
// and Bedrock only (read from the mu-plugin before the plugins load); plugins activated for a whole network are not touched.
'rest_plugins' => [
'enabled' => false,
'keep' => [],
],
];
2 changes: 1 addition & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ parameters:
- vendor/wpsyntex/polylang-stubs/polylang-stubs.php
ignoreErrors:
# Action Scheduler is a plugin, not part of the WordPress stubs: the package uses its functions only after checking they exist
- '#Function as_[a-z_]+ not found#'
- '#Function (as_[a-z_]+|get_graphql_setting) not found#'
# WPGraphQL is a plugin too: its error class exists only while it is active, and the guard runs from its own filter
- '#GraphQL\\Error\\UserError#'
# Contact Form 7 too: the adapter runs only once it checked the plugin is active
Expand Down
14 changes: 12 additions & 2 deletions src/Application/Preview/PreviewService.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,11 @@ public function linkToken(int $userId, int $postId, int $siteId): string
* @throws PreviewForbiddenException when the user can no longer edit the post
* @throws PreviewNotFoundException when the post is gone
*/
public function exchange(string $linkToken): PreviewSession
public function exchange(string $linkToken, ?int $siteId = null): PreviewSession
{
$claims = TokenSigner::verify($linkToken, $this->key, ($this->clock)(), PreviewTokenType::Link);
$this->checkAudience($claims);
$this->checkSite($claims, $siteId);

// Burn before anything else: a token that fails the checks below is spent too
if (! $this->store->burn($claims->id)) {
Expand All @@ -94,14 +95,15 @@ public function exchange(string $linkToken): PreviewSession
* @throws PreviewForbiddenException
* @throws PreviewNotFoundException
*/
public function authorize(string $sessionToken, int $postId): PreviewClaims
public function authorize(string $sessionToken, int $postId, ?int $siteId = null): PreviewClaims
{
if (! str_starts_with($sessionToken, 'hlp.')) {
throw PreviewTokenInvalidException::raise();
}

$claims = TokenSigner::verify(substr($sessionToken, 4), $this->key, ($this->clock)(), PreviewTokenType::Session);
$this->checkAudience($claims);
$this->checkSite($claims, $siteId);

if ($claims->postId !== $postId) {
throw PreviewForbiddenException::raise();
Expand All @@ -117,6 +119,14 @@ private function claims(PreviewTokenType $type, int $userId, int $postId, int $s
return new PreviewClaims($type, $userId, $postId, $siteId, $this->audience, ($this->clock)() + $ttl, bin2hex(($this->random)(16)));
}

/** The keys come from the salts of the whole network: a token made on one site must not open a post of another. */
private function checkSite(PreviewClaims $claims, ?int $siteId): void
{
if ($siteId !== null && $claims->siteId !== $siteId) {
throw PreviewTokenInvalidException::raise();
}
}

private function checkAudience(PreviewClaims $claims): void
{
if (! hash_equals($this->audience, $claims->audience)) {
Expand Down
3 changes: 2 additions & 1 deletion src/Application/Token/TokenService.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ public function rotate(int $userId, string $id, int $grace): IssuedToken
$old = $this->owned($userId, $id);
$issued = $this->create($userId, $old->name, $old->scopes, $old->routes, $old->expiresAt === null ? null : max(0, $old->expiresAt - ($this->clock)()));

$this->store->save($old->expiringAt(($this->clock)() + $grace));
// The grace period never makes a token outlive the expiry it already had
$this->store->save($old->expiringAt(min($old->expiresAt ?? PHP_INT_MAX, ($this->clock)() + $grace)));

return $issued;
}
Expand Down
23 changes: 22 additions & 1 deletion src/Domain/Front/RequestTarget.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function __construct(
public static function fromUri(string $uri, string $method = 'GET', string $basePath = ''): self
{
$parts = explode('?', $uri, 2);
$path = '/'.ltrim($parts[0], '/');
$path = self::resolveDots('/'.ltrim($parts[0], '/'));
$basePath = '/'.trim($basePath, '/');

if ($basePath !== '/' && ($path === $basePath || str_starts_with($path, $basePath.'/'))) {
Expand All @@ -37,6 +37,27 @@ public static function fromUri(string $uri, string $method = 'GET', string $base
return new self($path, $parts[1] ?? '', strtoupper($method));
}

/**
* `/wp-admin/../` is the home page, whatever the allow-list sees in the raw address: web servers collapse the dots before WordPress runs.
*/
private static function resolveDots(string $path): string
{
$segments = [];

foreach (explode('/', str_ireplace('%2e', '.', $path)) as $segment) {
if ($segment === '..') {
array_pop($segments);
} elseif ($segment !== '.') {
$segments[] = $segment;
}
}

$resolved = implode('/', $segments);
$resolved = '/'.ltrim($resolved, '/');

return str_ends_with($path, '/..') || str_ends_with($path, '/.') ? rtrim($resolved, '/').'/' : $resolved;
}

/** The path, with the query string when there is one. */
public function pathAndQuery(bool $withQuery = true): string
{
Expand Down
57 changes: 57 additions & 0 deletions src/Domain/Plugin/PluginFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Plugin;

/**
* Which active plugins a REST request loads, when the site keeps only the ones it needs there.
*
* Most plugins do nothing for the REST API but cost time on every request (their hooks, their options, their
* scripts). Loading only the ones that register routes, types, fields or authentication makes the API faster,
* but a plugin left out loses everything it adds: that is why the list is the site's own and the filter is off by default.
*/
final readonly class PluginFilter
{
/**
* @param list<string> $keep plugins to load on REST requests: a file (`acf/acf.php`) or a folder (`acf`)
*/
public function __construct(private array $keep) {}

/**
* @param array<mixed> $active the plugin files WordPress would load (`folder/file.php`)
* @return list<string>
*/
public function filter(array $active): array
{
$kept = [];

foreach ($active as $plugin) {
if (is_string($plugin) && $this->keeps($plugin)) {
$kept[] = $plugin;
}
}

return $kept;
}

public function keeps(string $plugin): bool
{
$folder = str_contains($plugin, '/') ? explode('/', $plugin, 2)[0] : $plugin;

return in_array($plugin, $this->keep, true) || in_array($folder, $this->keep, true);
}

/**
* Whether a request is one for the REST API, from its address alone, because it must be known before the plugins load.
*
* @param string $requestUri `$_SERVER['REQUEST_URI']`
* @param bool $hasRestRoute whether the query string has `rest_route` (plain permalinks)
*/
public static function isRestRequest(string $requestUri, bool $hasRestRoute = false): bool
{
$path = (string) parse_url($requestUri, PHP_URL_PATH);

return $hasRestRoute || preg_match('#(?:^|/)wp-json(?:/|$)#', $path) === 1;
}
}
16 changes: 14 additions & 2 deletions src/Domain/Redirect/Redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function __construct(
throw InvalidRedirectException::badTarget($to);
}

if ($regex && ! self::compiles(self::pattern($from))) {
if ($regex && (! self::compiles(self::pattern($from)) || self::backtracksTooMuch($from))) {
throw InvalidRedirectException::badPattern($from);
}

Expand All @@ -59,7 +59,10 @@ public function resolve(string $path): ?string
return null;
}

return (string) preg_replace_callback('/\$(\d{1,2})/', static fn (array $reference): string => $matches[(int) $reference[1]] ?? '', $this->to);
$to = (string) preg_replace_callback('/\$(\d{1,2})/', static fn (array $reference): string => $matches[(int) $reference[1]] ?? '', $this->to);

// What a visitor's path put into the destination must still be a destination: `/$1` with `/go//evil.com` would leave the site
return self::isDestination($to) && ! str_starts_with($to, '/\\') ? $to : null;
}

/**
Expand Down Expand Up @@ -104,6 +107,15 @@ private static function compiles(string $pattern): bool
}
}

/**
* Whether a pattern repeats a repetition (`(a+)+`, `(.*)*`): such a pattern can take exponential time on a path that almost matches,
* and the resolve route runs every pattern on what a visitor sends.
*/
private static function backtracksTooMuch(string $from): bool
{
return preg_match('/[+*}]\)?[+*{]|\([^()]*[+*}]\)[+*{]/', $from) === 1;
}

/** A path without its trailing slash: `/about` and `/about/` are the same page. */
private static function normalise(string $path): string
{
Expand Down
5 changes: 4 additions & 1 deletion src/Domain/Search/SearchQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

public const int DEFAULT_PER_PAGE = 10;

/** Deep pages cost a scan of every result before them, and nobody reads page 5000 of a search */
public const int MAX_PAGE = 100;

/**
* @param list<string> $types the content types to look in: the ones asked for that the site exposes, or all of those it exposes
*/
Expand Down Expand Up @@ -47,7 +50,7 @@ public static function fromRequest(string $term, string $types, ?string $languag
mb_substr($term, 0, self::MAX_LENGTH),
$kept,
$language,
max(1, $page),
min(max(1, $page), self::MAX_PAGE),
min(max(1, $perPage > 0 ? $perPage : self::DEFAULT_PER_PAGE), max(1, $maxPerPage)),
);
}
Expand Down
26 changes: 25 additions & 1 deletion src/Infrastructure/Config/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ private function __construct(
public ?GraphQlPolicy $graphql,
public bool $search,
public bool $forms,
public bool $restPluginFilter,
) {}

/**
Expand Down Expand Up @@ -121,7 +122,7 @@ public static function fromArray(array $config, string $backendUrl): self
languageFronts: self::languageFronts($config['frontend_urls'] ?? []),
apiTokens: self::bool(is_array($config['tokens'] ?? null) ? $config['tokens'] : [], 'enabled', true),
previewUrl: self::previewUrl($preview, $front),
previewSecret: self::string($preview, 'secret') !== '' ? self::string($preview, 'secret') : null,
previewSecret: self::secret($preview),
previewLinkTtl: max(30, self::int($preview, 'link_ttl', 300)),
previewSessionTtl: max(60, self::int($preview, 'session_ttl', 1800)),
revalidationTargets: self::targets($revalidation),
Expand All @@ -138,9 +139,32 @@ public static function fromArray(array $config, string $backendUrl): self
graphql: self::graphql($config['graphql'] ?? null),
search: $front instanceof Origin && self::bool(is_array($config['search'] ?? null) ? $config['search'] : [], 'enabled', true),
forms: self::bool(is_array($config['forms'] ?? null) ? $config['forms'] : [], 'enabled', true),
restPluginFilter: self::bool(is_array($config['rest_plugins'] ?? null) ? $config['rest_plugins'] : [], 'enabled', false),
);
}

/**
* The signing secret of the preview, null when it is left to the salts of the site.
*
* @param array<string, mixed> $preview
*
* @throws InvalidSettingsException when it is too short to resist guessing
*/
private static function secret(array $preview): ?string
{
$secret = self::string($preview, 'secret');

if ($secret === '') {
return null;
}

if (strlen($secret) < 32) {
throw InvalidSettingsException::tooShort('preview.secret', 32);
}

return $secret;
}

/**
* The WPGraphQL settings to impose, or null when the module is off. A key set to null leaves that setting to WPGraphQL.
*/
Expand Down
12 changes: 11 additions & 1 deletion src/Infrastructure/Config/SettingsLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ final class SettingsLoader
* @param int $siteId the current site of a multisite network (1 on a single site): `sites` overrides the settings of one site
*/
public static function load(string $backendUrl, int $siteId = 1): Settings
{
return Settings::fromArray(self::config($siteId), $backendUrl);
}

/**
* The settings as an array, before they are checked: usable before WordPress can tell its own address.
*
* @return array<string, mixed>
*/
public static function config(int $siteId = 1): array
{
$config = defined('HEADLESS_CONFIG') && is_array(HEADLESS_CONFIG) ? HEADLESS_CONFIG : [];
// The short form of a single revalidation target
Expand All @@ -38,7 +48,7 @@ public static function load(string $backendUrl, int $siteId = 1): Settings
$config['preview'] = [...(is_array($config['preview'] ?? null) ? $config['preview'] : []), 'secret' => HEADLESS_SECRET];
}

return Settings::fromArray(self::merge($config, $frontendUrl, $siteId), $backendUrl);
return self::merge($config, $frontendUrl, $siteId);
}

/**
Expand Down
5 changes: 5 additions & 0 deletions src/Infrastructure/Exceptions/InvalidSettingsException.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ public static function forValue(string $key, string $value, array $allowed): sel
return new self(sprintf('"%s" is not a valid value for "%s" (expected one of: %s).', $value, $key, implode(', ', $allowed)));
}

public static function tooShort(string $key, int $length): self
{
return new self(sprintf('"%s" must be at least %d characters long.', $key, $length));
}

public static function missing(string $key): self
{
return new self(sprintf('"%s" is required and is empty.', $key));
Expand Down
26 changes: 26 additions & 0 deletions src/Infrastructure/Status/Check.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Infrastructure\Status;

/**
* The result of one check of `wp headless doctor`: what was looked at, how it went, and what to do about it.
*/
final readonly class Check
{
public function __construct(
public string $id,
public CheckLevel $level,
public string $message,
public string $fix = '',
) {}

/**
* @return array<string, string>
*/
public function toArray(): array
{
return ['id' => $this->id, 'level' => $this->level->value, 'message' => $this->message, 'fix' => $this->fix];
}
}
15 changes: 15 additions & 0 deletions src/Infrastructure/Status/CheckLevel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Infrastructure\Status;

/**
* How serious the result of a check is.
*/
enum CheckLevel: string
{
case Ok = 'ok';
case Warning = 'warning';
case Fail = 'fail';
}
Loading
Loading