From ce5cd188daf8b10d15946dde36a684a067c230eb Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Fri, 13 Nov 2026 16:33:38 -0600 Subject: [PATCH] Test detection ordering around redirects and login requests --- docs/hook-order-compatibility.md | 89 +++++++++++++++++ tests/wp-compat/README.md | 12 +++ tests/wp-compat/hook-order-request.php | 131 +++++++++++++++++++++++++ tests/wp-compat/hook-order.py | 78 +++++++++++++++ 4 files changed, 310 insertions(+) create mode 100644 docs/hook-order-compatibility.md create mode 100644 tests/wp-compat/hook-order-request.php create mode 100644 tests/wp-compat/hook-order.py diff --git a/docs/hook-order-compatibility.md b/docs/hook-order-compatibility.md new file mode 100644 index 0000000..a621a57 --- /dev/null +++ b/docs/hook-order-compatibility.md @@ -0,0 +1,89 @@ +# Detection and redirect ordering + +Focused check on 2026-11-13: WebDecoy 2.11.4 at `92a92da`, PHP 8.5.10, +WordPress 7.1.4 hook dispatcher. Fourteen request cases passed. + +The general front-end check is registered on `init` at priority 1. A callback +that exits before it runs prevents detection of that request. Later redirects +do not erase an already recorded detection. + +| Request path / competing callback | Local detection | Result | +| --- | --- | --- | +| Ordinary bot request, monitor mode | Yes | Request continues | +| Reserved `WebDecoy-Test/` control | Yes | Labeled test, HTTP 403 | +| Must-use plugin exits before ordinary plugins | No | Redirect ends request | +| `plugins_loaded` exits | No | Redirect ends request | +| `init` priority 0 exits | No | Redirect ends request | +| `init` priority 1 registered before WebDecoy exits | No | Registration order wins the tie | +| `init` priority 1 registered after WebDecoy exits | Yes | Detection precedes redirect | +| `init` priority 2 or 10 exits | Yes | Detection precedes redirect | +| `wp_loaded` or `template_redirect` exits | Yes | Detection precedes redirect | +| Login request with `login_init` redirect | Yes | Detection precedes redirect | +| Admin / admin-AJAX request | No general front-end record | Intentional early-check exclusions | + +Admin/AJAX exclusions do not mean their separate protection hooks are absent. +The fixture also verifies registration of the login authentication filter and +the unauthenticated client-detection AJAX handler. It does not exercise their +nonce, authentication, or enforcement behavior. + +## Current companion sources reviewed + +These are source reviews, **not installed-plugin compatibility certifications**: + +- Redirection 5.10.1: `includes/module/class-plugin.php` registers canonical + redirects and initialization at default `init` priority 10, with page + redirects on `template_redirect`. These are after WebDecoy's general check. +- WPS Hide Login 1.9.20: `classes/plugin.php` registers `init_block_access` at + default `init` priority 10 and its main login handling on `wp_loaded`. + Its earlier `plugins_loaded` handler rewrites login request paths and + `$pagenow`; consequently WebDecoy may inspect the rewritten path rather than + the original login URL. Complete mixed-plugin behavior remains untested. +- Wordfence 9.1.1 has earlier bootstrap protection and later hooks. Its optimized + firewall runs before WordPress. Requests it ends before WebDecoy runs are + outside this plugin's observation window; no complete Wordfence coexistence + or Extended Protection installation was tested. + +Official packages reviewed: +[Redirection](https://downloads.wordpress.org/plugin/redirection.5.10.1.zip), +[WPS Hide Login](https://downloads.wordpress.org/plugin/wps-hide-login.1.9.20.zip), +[Wordfence](https://downloads.wordpress.org/plugin/wordfence.9.1.1.zip). +See also [WordPress action ordering](https://developer.wordpress.org/plugins/hooks/actions/) +and [Wordfence firewall optimization](https://www.wordfence.com/help/firewall/optimizing-the-firewall/). + +## Scope and implications + +This is a hook-order regression fixture, not a complete WordPress HTTP test. +It loads real WordPress hook functions and unmodified WebDecoy constructor, +scoring, reserved-test, and logging methods. Options, caching and SQL storage +are in-memory adapters. Unrelated trap rules are disabled; monitor mode is on, +and no cloud key is supplied. The ordinary cases use `python-requests`, not +reserved test-trigger traffic. No actual SQL writes, cloud reporting, reverse +proxy, cache, theme, or full companion-plugin installation is validated here. + +An early redirect ends the request; this check does **not** demonstrate access +to a protected action or a security bypass. A CDN/cache response or firewall +block before WordPress is likewise not something this WordPress plugin can +observe. Analytics describe requests that reach its execution point, not all +requests received by the host. Do not disable another firewall to make counts +match. + +Do not move the detector to an earlier lifecycle hook solely to change these +counts. Its dependencies load on `plugins_loaded`, and an early move needs +separate boot-order, options, enforcement and companion-plugin integration +validation. The Playground issue is fixed in the demo's isolated request. + +## Repeat the check + +Use an existing WordPress source checkout; no installation or downloads occur: + +```sh +python3 tests/wp-compat/hook-order.py /path/to/wordpress/wp-includes php +``` + +Each case is a fresh PHP process because real redirects and the reserved-test +handler exit. A failure, unexpected row/redirect, PHP fatal, or timeout fails +the runner. Supply the same WordPress version's core hook files together. +The initial run used a network-denied, read-only macOS sandbox, an empty +environment, 128 MB PHP memory, 15 CPU seconds, 20 seconds wall time per case, +64 file descriptors and 16 processes; target code could not write files or +spawn subprocesses. Only dummy IP `192.0.2.42` and `fixture.invalid` were used. diff --git a/tests/wp-compat/README.md b/tests/wp-compat/README.md index a06d9b5..b10b8ab 100644 --- a/tests/wp-compat/README.md +++ b/tests/wp-compat/README.md @@ -36,3 +36,15 @@ resolved (`mod_remoteip` switched off, so `REMOTE_ADDR` is the proxy), where the notice must show and its button must open the trusted-proxies field; and with that proxy configured as trusted. 2.10.4 fails it on the false notice and the button's 403; the script restores `mod_remoteip` on exit. + +## Detection hook ordering + +`hook-order.py` checks redirect timing and intentional admin/AJAX exclusions +without a database or live site. Supply existing WordPress core hook files: + +```sh +python3 tests/wp-compat/hook-order.py /path/to/wordpress/wp-includes php +``` + +This supplements the Docker smoke tests; it is not a full plugin-stack test. +See [scope and measured results](../../docs/hook-order-compatibility.md). diff --git a/tests/wp-compat/hook-order-request.php b/tests/wp-compat/hook-order-request.php new file mode 100644 index 0000000..d85185a --- /dev/null +++ b/tests/wp-compat/hook-order-request.php @@ -0,0 +1,131 @@ + $case, 'rows' => [], 'redirect' => null, 'reached' => []]; +define('ABSPATH', __DIR__.'/'); +define('WP_PLUGIN_DIR', dirname($repo)); +define('WPMU_PLUGIN_DIR', __DIR__ . '/mu'); +$wp_plugin_paths = []; +require $wpIncludes . '/plugin.php'; + +// Stand-ins for WordPress services outside the hook dispatcher. +function wp_normalize_path($p) { return str_replace('\\','/',$p); } +function trailingslashit($p) { return rtrim($p,'/').'/'; } +function plugins_url($p='',$file='') { return 'https://fixture.invalid/plugins/'.$p; } +function get_option($key, $default = false) { + if ($key !== 'webdecoy_options') { + return $default; + } + return [ + 'monitor_mode' => true, + 'tripwire_enabled' => false, + 'traps_fake_plugins' => false, + 'traps_xmlrpc' => false, + 'honeytoken_enabled' => false, + 'rate_limit_enabled' => false, + 'filter_rules' => [], + 'api_key' => '', + ]; +} +function is_admin() { return in_array($GLOBALS['case'],['admin','ajax'],true); } +function wp_doing_ajax() { return $GLOBALS['case']==='ajax'; } +function is_user_logged_in() { return false; } +function wp_doing_cron() { return false; } +function sanitize_text_field($v) { return strip_tags((string)$v); } +function wp_unslash($v) { return $v; } +function wp_json_encode($v) { return json_encode($v); } +function nocache_headers() {} +function status_header($c) { http_response_code($c); } +function __($s,$domain='') { return $s; } +function wp_cache_get($k,$g='') { return false; } +function wp_cache_set($k,$v,$g='',$ttl=0) { return true; } +function esc_sql($v) { return $v; } +function esc_url_raw($v) { return $v; } +function get_transient($k) { return false; } +function set_transient($k,$v,$ttl=0) { return true; } +function delete_transient($k) { return true; } +function get_current_user_id() { return 0; } +function wp_parse_url($url,$component=-1) { return parse_url($url,$component); } +function home_url($p='') { return 'https://fixture.invalid'.$p; } +function site_url($p='') { return 'https://fixture.invalid'.$p; } +class FixtureDatabase { + public $prefix='wp_'; public $insert_id=0; + function insert($t,$row) { $GLOBALS['state']['rows'][]=['table'=>$t,'row'=>$row];$this->insert_id++;return 1; } + function prepare($q,...$a) { return $q; } + function get_var($q) { return null; } + function get_col($q) { return []; } + function get_row($q) { return null; } + function get_results($q,$mode=null) { return []; } + function query($q) { return 0; } +} +$wpdb=new FixtureDatabase(); +$_COOKIE=[]; $_REQUEST=[]; +$_SERVER = [ + 'REMOTE_ADDR' => '192.0.2.42', + 'REQUEST_URI' => '/compat-check/', + 'REQUEST_METHOD' => 'GET', + 'HTTP_HOST' => 'fixture.invalid', + 'SERVER_NAME' => 'fixture.invalid', + 'SERVER_PORT' => '443', + 'HTTPS' => 'on', + 'HTTP_USER_AGENT' => 'python-requests/2.32.3', +]; +if ($case==='reserved-test') $_SERVER['HTTP_USER_AGENT']='WebDecoy-Test/1.0 Compatibility'; +if ($case==='login') $_SERVER['REQUEST_URI']='/wp-login.php'; +if ($case==='admin') $_SERVER['REQUEST_URI']='/wp-admin/index.php'; +if ($case==='ajax') $_SERVER['REQUEST_URI']='/wp-admin/admin-ajax.php'; +ob_start(); +register_shutdown_function(static function () { + $body = ob_get_clean(); + $summary = $GLOBALS['state']; + $summary['status'] = http_response_code(); + $summary['body_is_reserved_test'] = strpos($body, 'webdecoy_test') !== false; + $error = error_get_last(); + if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_COMPILE_ERROR], true)) { + $summary['fatal'] = $error['message']; + } + echo json_encode($summary, JSON_UNESCAPED_SLASHES) . "\n"; +}); +$redirect = static function () { + $GLOBALS['state']['redirect'] = 'https://fixture.invalid/destination/'; + http_response_code(302); + exit; +}; +if($case==='mu-plugin-exit') { $redirect(); } +if($case==='plugins-loaded-exit') add_action('plugins_loaded',$redirect,10); +if($case==='init-0-exit') add_action('init',$redirect,0); +if($case==='init-1-before-exit') add_action('init',$redirect,1); +require $repo.'/includes/class-webdecoy-runtime-config.php'; +require $repo.'/webdecoy.php'; +require $repo.'/includes/class-webdecoy-blocker.php'; +require $repo.'/includes/class-webdecoy-detector.php'; +// Only this plugin's bootstrap callbacks are omitted: companion classes have +// already been required above. The actual constructor, detection methods and +// WordPress hook dispatcher are unmodified. +if($case==='plugins-loaded-exit') do_action('plugins_loaded'); +$state['login_filter_registered'] = has_filter('authenticate', [webdecoy(), 'check_login']) === 30; +$state['ajax_handler_registered'] = has_action('wp_ajax_nopriv_webdecoy_client_detection', [webdecoy(), 'ajax_client_detection']) !== false; +if($case==='init-1-after-exit') add_action('init',$redirect,1); +if($case==='init-2-exit') add_action('init',$redirect,2); +if($case==='init-10-exit') add_action('init',$redirect,10); +if($case==='wp-loaded-exit') add_action('wp_loaded',$redirect,10); +if($case==='template-redirect-exit') add_action('template_redirect',$redirect,0); +if($case==='login') add_action('login_init',$redirect,10); +do_action('init'); +$state['reached'][] = 'after_init'; +do_action('wp_loaded'); +$state['reached'][] = 'after_wp_loaded'; +if($case==='login')do_action('login_init'); +if(!is_admin()&&$case!=='login')do_action('template_redirect'); diff --git a/tests/wp-compat/hook-order.py b/tests/wp-compat/hook-order.py new file mode 100644 index 0000000..c547477 --- /dev/null +++ b/tests/wp-compat/hook-order.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Run isolated hook-order requests. No downloads or live site access. + +Usage: python3 tests/wp-compat/hook-order.py /path/to/wordpress/wp-includes [php] +Supply matching plugin.php, class-wp-hook.php and companion core hook classes. +""" +import json +from pathlib import Path +import subprocess +import sys + +CASES = { + "baseline": (1, False), + "reserved-test": (1, False), + "mu-plugin-exit": (0, True), + "plugins-loaded-exit": (0, True), + "init-0-exit": (0, True), + "init-1-before-exit": (0, True), + "init-1-after-exit": (1, True), + "init-2-exit": (1, True), + "init-10-exit": (1, True), + "wp-loaded-exit": (1, True), + "template-redirect-exit": (1, True), + "login": (1, True), + "admin": (0, False), + "ajax": (0, False), +} + + +def main(): + if len(sys.argv) not in (2, 3): + print(__doc__, file=sys.stderr) + return 2 + includes = Path(sys.argv[1]).resolve() + php = sys.argv[2] if len(sys.argv) == 3 else "php" + fixture = Path(__file__).with_name("hook-order-request.php") + failures = 0 + for case, (count, redirect) in CASES.items(): + try: + result = subprocess.run( + [php, "-n", "-d", "memory_limit=128M", "-d", "max_execution_time=10", + str(fixture), case, str(includes)], + capture_output=True, text=True, timeout=20, check=False, + ) + data = json.loads(result.stdout) + assert result.returncode == 0, result.stderr or data.get("fatal", "PHP failed") + assert "fatal" not in data, data.get("fatal") + assert len(data["rows"]) == count, data + assert bool(data["redirect"]) == redirect, data + if redirect: + assert data["status"] == 302, data + if count: + row = data["rows"][0] + assert row["table"] == "wp_webdecoy_detections", row + assert row["row"]["source"] == "wordpress_plugin", row + assert row["row"]["ip_address"] == "192.0.2.42", row + flags = json.loads(row["row"]["flags"]) + if case == "reserved-test": + assert flags["metadata"]["test"] is True, flags + assert "test_trigger" in flags["flags"], flags + assert data["status"] == 403 and data["body_is_reserved_test"], data + else: + assert "cli_tool" in flags["flags"], flags + assert "test_trigger" not in flags["flags"], flags + assert row["row"]["score"] >= 40, row + if case in ("login", "admin", "ajax"): + assert data["login_filter_registered"] is True, data + assert data["ajax_handler_registered"] is True, data + print(f"PASS {case}: rows={count}, redirect={redirect}") + except (AssertionError, ValueError, KeyError, subprocess.TimeoutExpired) as error: + failures += 1 + print(f"FAIL {case}: {error}", file=sys.stderr) + print(f"{len(CASES) - failures}/{len(CASES)} hook-order cases passed") + return 1 if failures else 0 + + +if __name__ == "__main__": + raise SystemExit(main())