diff --git a/.gitattributes b/.gitattributes index af3ad1281..78644f7db 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,5 @@ /.yarn/releases/* binary /.yarn/plugins/**/* binary /.pnp.* binary linguist-generated +/.githooks/* text eol=lf +/.github/scripts/*.sh text eol=lf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 000000000..60aabe10a --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,18 @@ +#!/bin/sh + +set -eu + +cd "$(git rev-parse --show-toplevel)" + +if git diff --cached --quiet -- readme.txt changelog.txt; then + exit 0 +fi + +if ! git diff --quiet -- changelog.txt; then + echo "Stage or restore changes in changelog.txt before committing." >&2 + exit 1 +fi + +php_binary=$(git config --get hcaptcha.phpPath || echo php) +"$php_binary" .github/scripts/update-changelog.php --staged +git add -- changelog.txt diff --git a/.githooks/pre-push b/.githooks/pre-push deleted file mode 100644 index e65b10c0b..000000000 --- a/.githooks/pre-push +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -.github/scripts/update-changelog.sh - -# Intercept exit code from the previous command. -exitCode="$?" - -echo '' -exit $exitCode diff --git a/.githooks/setup.php b/.githooks/setup.php new file mode 100644 index 000000000..c86e142a2 --- /dev/null +++ b/.githooks/setup.php @@ -0,0 +1,35 @@ +getMessage() . "\n" ); + + return 1; + } + + echo "Changelog generated from readme.txt.\n"; + + return 0; +} + +if ( isset( $argv[0] ) && realpath( $argv[0] ) === __FILE__ ) { + exit( hcaptcha_update_changelog( array_slice( $argv, 1 ) ) ); +} diff --git a/.github/scripts/update-changelog.sh b/.github/scripts/update-changelog.sh index a9ddb6ae1..21db1ef0e 100755 --- a/.github/scripts/update-changelog.sh +++ b/.github/scripts/update-changelog.sh @@ -1,54 +1,6 @@ -#!/bin/bash +#!/bin/sh -# Check if readme.txt exists -if [ ! -f readme.txt ]; then - echo "readme.txt file not found!" - exit 1 -fi +set -eu -# Determine the latest changelog version in readme.txt -latest_version=$(sed -n 's/^= \([0-9]\+\.[0-9]\+\.[0-9]\+\) =$/\1/p' readme.txt | head -n 1) - -if [ -z "$latest_version" ]; then - echo "No latest version found in readme.txt!" - exit 0 -fi - -# Get the latest changelog section from readme.txt -latest_section=$(sed -n "/^= $latest_version =$/,/^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/ { /^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/!p; }" readme.txt) -latest_section="= ${latest_version} =\n${latest_section}\n" - -# Remove the latest changelog section from changelog.txt -sed -i "/^= $latest_version =$/,/^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/ {/^= $latest_version =$/d; /^= [0-9]\+\.[0-9]\+\.[0-9]\+ =$/!d;}" changelog.txt - -# Append the latest changelog section from readme.txt to changelog.txt -{ echo -e "$latest_section"; cat changelog.txt; } > temp.txt && mv temp.txt changelog.txt - -# Generate the file without changing Git configuration, committing, or pushing. -if [ "${1:-}" = "--generate-only" ]; then - echo "Changelog generated from readme.txt." - exit 0 -fi - -# Check if there are changes in changelog.txt -if git diff --quiet changelog.txt; then - echo "No changes in changelog.txt." - exit 0 -fi - -# Configure Git commit information -git config --global user.email "gha@hcaptcha.com" -git config --global user.name "hCaptcha GHA" - -# Add, commit, and push changes -git add changelog.txt -git commit -m "Update changelog from readme.txt" - -# Check if running in CI environment -if [ -n "$CI" ]; then - # Push changes if in CI environment - git push - echo "Changelog successfully updated and pushed to the repository." -else - echo "Changelog updated locally. Skipping push." -fi +php_binary=$(git config --get hcaptcha.phpPath || echo php) +"$php_binary" "$(dirname "$0")/update-changelog.php" "$@" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd826cb72..da793b5e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,20 +5,32 @@ on: paths: - '**/*.php' - 'composer.*' + - '.php-scoper/**' - 'package.json' - 'yarn.lock' - 'src/**' - 'tests/**' - '.github/workflows/**' + - '.github/scripts/**' + - '.githooks/**' + - '.gitattributes' + - 'readme.txt' + - 'changelog.txt' pull_request: paths: - '**/*.php' - 'composer.*' + - '.php-scoper/**' - 'package.json' - 'yarn.lock' - 'src/**' - 'tests/**' - '.github/workflows/**' + - '.github/scripts/**' + - '.githooks/**' + - '.gitattributes' + - 'readme.txt' + - 'changelog.txt' # 1. SECURITY: Default to read-only permissions for the workflow permissions: @@ -32,7 +44,7 @@ concurrency: jobs: phpcs: name: PHPCS - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: wp-plugin-directory: wordpress/wp-content/plugins/hcaptcha-wordpress-plugin @@ -49,8 +61,6 @@ jobs: path: ${{ env.wp-plugin-directory }} persist-credentials: false - # MOVED: The "Update changelog" step has been moved to the specific job below - # to prevent giving 'contents: write' permissions to this testing job. - name: Setup PHP 8.5 uses: hCaptcha/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # v2.37.0 with: @@ -69,7 +79,7 @@ jobs: js: name: JS lint and tests - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 if: | github.event_name == 'workflow_dispatch' || @@ -105,7 +115,7 @@ jobs: php_versions: name: Resolve PHP versions - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 if: | github.event_name == 'workflow_dispatch' || @@ -116,14 +126,8 @@ jobs: matrix: ${{ steps.resolve.outputs.matrix }} env: - FULL_PHP_MATRIX: >- - ${{ - github.event_name == 'push' && - ( - github.ref == 'refs/heads/master' || - contains(github.event.head_commit.message || '', '[all]') - ) - }} + # Temporarily test every supported PHP version on all branch pushes. + FULL_PHP_MATRIX: ${{ github.event_name == 'push' }} steps: - name: Resolve PHP versions @@ -137,7 +141,7 @@ jobs: unit: name: Unit tests on PHP ${{ matrix.php-version }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: php_versions strategy: @@ -172,7 +176,7 @@ jobs: integration: name: WP integration tests on PHP ${{ matrix.php-version }} (${{ matrix.shard }}/2) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 needs: php_versions strategy: @@ -220,8 +224,8 @@ jobs: extensions: json, mysqli, mbstring, zip ini-values: register_argc_argv=On - - name: Detect Really Simple CAPTCHA support - id: really_simple_captcha + - name: Detect Contact Form 7 support + id: cf7 run: | if php -r 'exit(version_compare(PHP_VERSION, "8.3", ">=") ? 0 : 1);'; then echo "supported=true" >> "$GITHUB_OUTPUT" @@ -304,8 +308,10 @@ jobs: working-directory: ${{ env.wp-directory }} env: SHARD_DEPENDENCIES: ${{ steps.shard_dependencies.outputs.json }} + CF7_SUPPORTED: ${{ steps.cf7.outputs.supported }} + PHP_VERSION: ${{ matrix.php-version }} run: | - mapfile -t plugins < <(jq -r '.public_plugins[]' <<< "$SHARD_DEPENDENCIES") + mapfile -t plugins < <(jq -r --arg supported "$CF7_SUPPORTED" --arg php "$PHP_VERSION" '.public_plugins[] | select(. != "contact-form-7" or $supported == "true") | select(. != "easy-digital-downloads" or $php != "7.4")' <<< "$SHARD_DEPENDENCIES") mapfile -t themes < <(jq -r '.public_themes[]' <<< "$SHARD_DEPENDENCIES") if (( ${#plugins[@]} )); then @@ -315,13 +321,19 @@ jobs: done fi + # EDD 3.7+ requires PHP 8.0; keep the PHP 7.4 job on its last compatible release. + if [[ "$PHP_VERSION" == "7.4" ]] && jq -e '.public_plugins | index("easy-digital-downloads") != null' <<< "$SHARD_DEPENDENCIES" > /dev/null; then + wp plugin install easy-digital-downloads --version=3.6.9.1 + wp plugin is-installed easy-digital-downloads + fi + for theme in "${themes[@]}"; do wp theme install "$theme" wp theme is-installed "$theme" done - name: Install Really Simple CAPTCHA - if: steps.really_simple_captcha.outputs.supported == 'true' && steps.shard_dependencies.outputs.needs_really_simple_captcha == 'true' + if: steps.cf7.outputs.supported == 'true' && steps.shard_dependencies.outputs.needs_really_simple_captcha == 'true' working-directory: ${{ env.wp-directory }} run: | wp plugin install really-simple-captcha @@ -374,9 +386,9 @@ jobs: wp plugin is-installed bb-plugin echo "available=true" >> "$GITHUB_OUTPUT" - - name: Generate changelog for tests + - name: Check changelog for tests working-directory: ${{ env.wp-plugin-directory }} - run: .github/scripts/update-changelog.sh --generate-only + run: composer changelog:check - name: Run WP tests with private test plugins if: steps.test_plugins.outputs.available == 'true' @@ -384,14 +396,19 @@ jobs: run: | integration_args=() - if [[ "${{ steps.really_simple_captcha.outputs.supported }}" != "true" ]]; then - integration_args+=(--skip-group cf7-really-simple-captcha) + if [[ "${{ steps.cf7.outputs.supported }}" != "true" ]]; then + integration_args+=(--skip-group cf7) fi if [[ "${{ steps.beaver_builder.outputs.available }}" != "true" ]]; then integration_args+=(--skip-group beaver-builder) fi + # Codeception 4 cannot bootstrap WordPress in PHPUnit's isolated PHP 7.4 process. + if [[ "${{ matrix.php-version }}" == "7.4" ]]; then + integration_args+=(--skip-group process-isolation-php74) + fi + composer integration:parallel -- --shard=${{ matrix.shard }}/2 --env github-actions "${integration_args[@]}" - name: Run WP tests without private test plugins @@ -400,8 +417,13 @@ jobs: run: | integration_args=(--skip-group acfe --skip-group avada --skip-group beaver-builder --skip-group divi --skip-group elementor-pro --skip-group gravityforms --skip-group ultimate-addons) - if [[ "${{ steps.really_simple_captcha.outputs.supported }}" != "true" ]]; then - integration_args+=(--skip-group cf7-really-simple-captcha) + if [[ "${{ steps.cf7.outputs.supported }}" != "true" ]]; then + integration_args+=(--skip-group cf7) + fi + + # Codeception 4 cannot bootstrap WordPress in PHPUnit's isolated PHP 7.4 process. + if [[ "${{ matrix.php-version }}" == "7.4" ]]; then + integration_args+=(--skip-group process-isolation-php74) fi composer integration:parallel -- --shard=${{ matrix.shard }}/2 --env github-actions "${integration_args[@]}" @@ -410,30 +432,3 @@ jobs: if: matrix.shard == 1 working-directory: ${{ env.wp-plugin-directory }} run: composer integration:multisite -- --env github-actions - - update_changelog: - name: Update Changelog - runs-on: ubuntu-latest - - # 2. SECURITY: Only run on PUSH, never on Pull Requests - if: github.event_name == 'push' - needs: [ phpcs, js, unit, integration ] - - # 3. SECURITY: Grant write permission ONLY to this job - permissions: - contents: write - - env: - wp-plugin-directory: wordpress/wp-content/plugins/hcaptcha-wordpress-plugin - - steps: - - name: Checkout code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - path: ${{ env.wp-plugin-directory }} - # Check out the branch ref to ensure we can push back to it - ref: ${{ github.ref }} - - - name: Update changelog - working-directory: ${{ env.wp-plugin-directory }} - run: .github/scripts/update-changelog.sh diff --git a/.github/workflows/create-zip.yml b/.github/workflows/create-zip.yml index 6d15817d1..7be7ee12b 100644 --- a/.github/workflows/create-zip.yml +++ b/.github/workflows/create-zip.yml @@ -11,7 +11,7 @@ permissions: jobs: build-zip: name: New zip file - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # Security: 1. Check for [zip] tag. 2. Check if user is authorized. if: | diff --git a/.github/workflows/deploy-readme-assets-to-wp-org.yml b/.github/workflows/deploy-readme-assets-to-wp-org.yml index 690c851e7..4bd72b50b 100644 --- a/.github/workflows/deploy-readme-assets-to-wp-org.yml +++ b/.github/workflows/deploy-readme-assets-to-wp-org.yml @@ -9,7 +9,7 @@ permissions: jobs: trunk: name: Push to trunk - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Checkout code uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 diff --git a/.github/workflows/deploy-to-wp-org.yml b/.github/workflows/deploy-to-wp-org.yml index 72cc0c5c8..7b987d9ca 100644 --- a/.github/workflows/deploy-to-wp-org.yml +++ b/.github/workflows/deploy-to-wp-org.yml @@ -9,7 +9,7 @@ jobs: tag: name: New release - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # Security: 1. Check if user is authorized. if: contains(fromJson('["kagg-design", "e271828-"]'), github.actor) diff --git a/.gitignore b/.gitignore index cacd06d94..f7820ba01 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ assets/js/**/*.min.js.map build/ CLAUDE-SECURITY-*/ coverage/ +docs/security/ docs/tasks/ node_modules/ vendor/ diff --git a/.php-scoper/composer.json b/.php-scoper/composer.json index 7a8542cbf..254546efe 100644 --- a/.php-scoper/composer.json +++ b/.php-scoper/composer.json @@ -2,9 +2,6 @@ "require": { "humbug/php-scoper": "0.17.5 - 0.18.18" }, - "require-dev": { - "roave/security-advisories": "dev-latest" - }, "minimum-stability": "dev", "prefer-stable": true, "config": { diff --git a/.php-scoper/hcaptcha-wordpress-plugin-scoper.php b/.php-scoper/hcaptcha-wordpress-plugin-scoper.php index f08838d0c..e1a5061e7 100644 --- a/.php-scoper/hcaptcha-wordpress-plugin-scoper.php +++ b/.php-scoper/hcaptcha-wordpress-plugin-scoper.php @@ -53,9 +53,13 @@ static function ( string $file_path, string $prefix, string $content ): string { } if ( false !== strpos( $file_path, 'matthiasmullie/minify/src/JS.php' ) ) { + // Match the entire unscoped literal to avoid prefixing an already scoped callback. return str_replace( - '\\\MatthiasMullie\\\Minify\\\Minify', - '\\' . $prefix . '\MatthiasMullie\Minify\Minify', + [ + "'\\\\MatthiasMullie\\\\Minify\\\\Minify'", + "'\\MatthiasMullie\\Minify\\Minify'", + ], + "'" . $prefix . "\\MatthiasMullie\\Minify\\Minify'", $content ); } diff --git a/AGENTS.md b/AGENTS.md index 90da7fea0..e1fa1253a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,4 +60,5 @@ $subject->shouldAllowMockingProtectedMethods(); ## Changelog - When adding release notes about completed work, update the current version under `== Changelog ==` in `readme.txt`. -- Do not edit `changelog.txt` manually. CI generates and updates it from the changelog in `readme.txt`. +- Do not edit `changelog.txt` manually. The pre-commit Git hook generates and stages it from the staged changelog in `readme.txt`. Composer install/update enables the hooks; run `composer hooks:install` when using an existing checkout or a new worktree without installing dependencies. +- Before testing uncommitted release-note changes, run `composer changelog`. CI checks that `changelog.txt` is current without changing or pushing it. diff --git a/README.md b/README.md index 8b953b77f..d044ba26a 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,15 @@ yarn yarn dev ``` +Composer install/update enables the repository's Git hooks in local checkouts and +worktrees. For an existing checkout, or a cloud environment that reuses installed +dependencies, run `composer hooks:install` during environment setup. + +The pre-commit hook generates and stages `changelog.txt` from the staged release notes +in `readme.txt`, so both files are included in the same commit. Before running tests +with uncommitted release-note changes, run `composer changelog`. CI verifies the +generated file with `composer changelog:check`. + 1. Sign up at [hCaptcha.com](https://www.hcaptcha.com/) to get a site key and secret. 2. Activate the plugin through the 'Plugins' menu in WordPress 3. Enter your Site Key and SECRET in the Settings -> hCaptcha menu in WordPress diff --git a/assets/css/advanced.css b/assets/css/advanced.css new file mode 100644 index 000000000..4cecd7f04 --- /dev/null +++ b/assets/css/advanced.css @@ -0,0 +1,286 @@ +#hcaptcha-options.hcaptcha-advanced h3 { + display: flex; + justify-content: space-between; + max-width: 760px; + box-sizing: border-box; + padding: 15px 20px; + margin: 1.5em 0 0; + background: #fff; + color: #5c6f8a; + cursor: pointer; +} + +#hcaptcha-options.hcaptcha-advanced h3.disabled, +#hcaptcha-options.hcaptcha-advanced h3.disabled + table { + opacity: 0.6; +} + +#hcaptcha-options.hcaptcha-advanced h3 + table { + max-width: 760px; + margin-top: 0; + position: relative; +} + +#hcaptcha-options.hcaptcha-advanced h3 + table::before { + content: ''; + position: absolute; + top: 0; + width: calc(100% - 40px); + max-width: 720px; + margin: 0 20px; + border-bottom: 1px solid #c3c4c7; +} + +#hcaptcha-options.hcaptcha-advanced h3 + table tbody { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + padding: 15px 20px; + background: #fff; +} + +#hcaptcha-options.hcaptcha-advanced h3 + table tbody tr { + display: grid; + align-self: start; +} + +#hcaptcha-options.hcaptcha-advanced h3 + table tbody th { + width: auto; + padding: 0 0 10px; + color: #5c6f8a; +} + +#hcaptcha-options.hcaptcha-advanced h3 + table tbody th:empty { + padding: 0; +} + +#hcaptcha-options.hcaptcha-advanced h3 + table tbody td input[type="text"], +#hcaptcha-options.hcaptcha-advanced h3 + table tbody td input[type="number"], +#hcaptcha-options.hcaptcha-advanced h3 + table tbody td textarea { + width: 100%; + box-sizing: border-box; +} + +#hcaptcha-options.hcaptcha-advanced .hcaptcha-section-header-toggle::after { + content: "\f142"; + font: normal 20px dashicons; + -webkit-font-smoothing: antialiased; +} + +#hcaptcha-options.hcaptcha-advanced h3.closed .hcaptcha-section-header-toggle::after { + content: "\f140"; +} + +/* Section Enterprise */ +.hcaptcha-section-enterprise + table tbody { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 10px 20px; + padding: 15px 20px; +} + +.hcaptcha-section-enterprise + table tbody th { + width: auto; +} + +.hcaptcha-section-enterprise + table tbody tr th { + padding: 0 0 10px 0; +} + +.hcaptcha-section-enterprise + table tbody tr td input { + width: 100%; +} + +/* Section Protect Content */ +.hcaptcha-section-content + table tbody { + display: grid; + grid-template-columns: repeat(2, 1fr); + grid-template-areas: + "content protected-urls"; + gap: 0 20px; + padding: 15px 20px; +} + +.hcaptcha-section-content + table tbody tr.hcaptcha-advanced-content { + grid-area: content; +} + +.hcaptcha-section-content + table tbody tr.hcaptcha-advanced-protected-urls { + grid-area: protected-urls; +} + +.hcaptcha-section-content + table tbody tr th { + padding: 0 0 10px 0; + width: auto; +} + +.hcaptcha-section-content + table tbody tr td { + width: max-content; +} + +.hcaptcha-section-content + table tbody tr.hcaptcha-advanced-protected-urls td { + width: auto; +} + +.hcaptcha-section-content + table tbody tr td textarea, +.hcaptcha-section-content + table tbody tr td input { + width: 100%; +} + + +/* Section Other */ +.hcaptcha-section-other + table tbody { + display: grid; + grid-template-columns: repeat(2, 1fr); + grid-template-areas: + "logged delay" + "recaptcha delay" + "cleanup-on-uninstall ajax" + ". network"; + gap: 0 20px; + padding: 15px 20px; +} + +.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-delay { + grid-area: delay; +} + +.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-off-when-logged-in { + grid-area: logged; +} + +.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-ajax-forms { + grid-area: ajax; +} + +.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-recaptcha-compat-off { + grid-area: recaptcha; +} + +.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-cleanup-on-uninstall { + grid-area: cleanup-on-uninstall; +} + +.hcaptcha-section-other + table tbody tr.hcaptcha-advanced--network-wide { + grid-area: network; +} + +.hcaptcha-section-other + table tbody tr th { + padding: 0 0 10px 0; + width: auto; +} + +.hcaptcha-section-other + table tbody tr td { + width: max-content; +} + +.hcaptcha-section-other + table tbody tr.hcaptcha-advanced-delay td { + width: auto; +} + +.hcaptcha-section-other + table tbody tr td input { + width: 100%; +} + +/* Section Statistics */ +.hcaptcha-section-statistics + table tbody { + display: grid; + grid-template-columns: repeat(2, 1fr); + grid-template-areas: + "statistics collect-ip" + "anonymous collect-ua"; + gap: 0 20px; + padding: 15px 20px; +} + +.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics { + grid-area: statistics; +} + +.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-anonymous { + grid-area: anonymous; +} + +.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-collect-ip { + grid-area: collect-ip; +} + +.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-collect-ua { + grid-area: collect-ua; +} + +.hcaptcha-section-statistics + table tbody tr th { + padding: 0 0 10px 0; + width: auto; +} + +.hcaptcha-section-statistics + table tbody tr td { + width: max-content; +} + +.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics td { + width: max-content; + min-width: 0; +} + +.hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics .helper-content { + max-width: calc(100vw - 40px); + white-space: normal; + overflow-wrap: anywhere; + line-height: 1.5; +} + +@media (max-width: 600px) { + #hcaptcha-options.hcaptcha-advanced h3 + table tbody { + grid-template-columns: minmax(0, 1fr); + } + .hcaptcha-section-enterprise + table tbody { + grid-template-columns: repeat(1, 1fr) !important; + } + + .hcaptcha-section-enterprise + table tbody tr td { + width: unset !important; + } + + .hcaptcha-section-content + table tbody { + grid-template-columns: repeat(1, 1fr); + grid-template-areas: + "content" + "protected-urls"; + } + + .hcaptcha-section-content + table tbody tr td { + width: unset !important; + } + + .hcaptcha-section-other + table tbody { + grid-template-columns: repeat(1, 1fr) !important; + grid-template-areas: + "delay" + "logged" + "recaptcha" + "cleanup-on-uninstall" + "ajax" + "network"; + } + + .hcaptcha-section-other + table tbody tr td { + width: unset !important; + } + + .hcaptcha-section-statistics + table tbody { + grid-template-columns: repeat(1, 1fr); + grid-template-areas: + "statistics" + "anonymous" + "collect-ip" + "collect-ua"; + } + + .hcaptcha-section-statistics + table tbody tr td { + width: unset !important; + } + + .hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics td { + width: max-content !important; + } +} diff --git a/assets/css/general.css b/assets/css/general.css index 585d9a3dc..e620e1f28 100644 --- a/assets/css/general.css +++ b/assets/css/general.css @@ -13,6 +13,10 @@ align-self: start; } +#hcaptcha-options table tbody tr.hidden { + display: none; +} + #hcaptcha-options table tbody tr th { color: #5c6f8a; } @@ -83,7 +87,8 @@ h3.closed .hcaptcha-section-header-toggle:after { grid-template-columns: repeat(4, 1fr); grid-template-areas: "site-key site-key secret-key secret-key" - "sample-hcaptcha sample-hcaptcha check-config reset-notifications"; + "sample-hcaptcha sample-hcaptcha mode mode" + "check-config check-config reset-notifications reset-notifications"; gap: 10px 20px; padding: 15px 20px; } @@ -96,6 +101,15 @@ h3.closed .hcaptcha-section-header-toggle:after { grid-area: site-key; } +.hcaptcha-section-keys + table tbody tr.hcaptcha-general-mode { + grid-area: mode; +} + +.hcaptcha-section-keys + table tbody tr.hcaptcha-general-mode td select { + width: 100%; + max-width: none; +} + .hcaptcha-section-keys + table tbody tr.hcaptcha-general-secret-key { grid-area: secret-key; } @@ -108,10 +122,20 @@ h3.closed .hcaptcha-section-header-toggle:after { grid-area: check-config; } -.hcaptcha-section-keys + table tbody tr.hcaptcha-reset-notifications { +.hcaptcha-section-keys + table tbody tr.hcaptcha-general-reset-notifications { grid-area: reset-notifications; } +.hcaptcha-section-keys + table tbody tr.hcaptcha-general-check-config th, +.hcaptcha-section-keys + table tbody tr.hcaptcha-general-reset-notifications th { + display: none; +} + +.hcaptcha-section-keys + table tbody tr.hcaptcha-general-check-config td, +.hcaptcha-section-keys + table tbody tr.hcaptcha-general-reset-notifications td { + padding: 0; +} + .hcaptcha-section-keys + table tbody tr.hcaptcha-general-site-key .helper, .hcaptcha-section-keys + table tbody tr.hcaptcha-general-secret-key .helper { display: none; @@ -135,10 +159,10 @@ h3.closed .hcaptcha-section-header-toggle:after { /* Section Appearance */ .hcaptcha-section-appearance + table tbody { display: grid; - grid-template-columns: repeat(4, 1fr); + grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-areas: - "theme size language mode" - "force force position position"; + "theme size language" + "force position ."; gap: 10px 20px; padding: 15px 20px; } @@ -155,10 +179,6 @@ h3.closed .hcaptcha-section-header-toggle:after { grid-area: language; } -.hcaptcha-section-appearance + table tbody tr.hcaptcha-general-mode { - grid-area: mode; -} - .hcaptcha-section-appearance + table tbody tr.hcaptcha-general-force { grid-area: force; } @@ -1031,177 +1051,6 @@ h3.closed .hcaptcha-section-header-toggle:after { background: var(--hcap-verify-fill); } -/* Section Enterprise */ -.hcaptcha-section-enterprise + table tbody { - display: grid; - grid-template-columns: repeat(2, 1fr); - gap: 10px 20px; - padding: 15px 20px; -} - -.hcaptcha-section-enterprise + table tbody th { - width: auto; -} - -.hcaptcha-section-enterprise + table tbody tr th { - padding: 0 0 10px 0; -} - -.hcaptcha-section-enterprise + table tbody tr td input { - width: 100%; -} - -/* Section Protect Content */ -.hcaptcha-section-content + table tbody { - display: grid; - grid-template-columns: repeat(2, 1fr); - grid-template-areas: - "content protected-urls"; - gap: 0 20px; - padding: 15px 20px; -} - -.hcaptcha-section-content + table tbody tr.hcaptcha-general-content { - grid-area: content; -} - -.hcaptcha-section-content + table tbody tr.hcaptcha-general-protected-urls { - grid-area: protected-urls; -} - -.hcaptcha-section-content + table tbody tr th { - padding: 0 0 10px 0; - width: auto; -} - -.hcaptcha-section-content + table tbody tr td { - width: max-content; -} - -.hcaptcha-section-content + table tbody tr.hcaptcha-general-protected-urls td { - width: auto; -} - -.hcaptcha-section-content + table tbody tr td textarea, -.hcaptcha-section-content + table tbody tr td input { - width: 100%; -} - - -/* Section Other */ -.hcaptcha-section-other + table tbody { - display: grid; - grid-template-columns: repeat(2, 1fr); - grid-template-areas: - "logged delay" - "recaptcha delay" - "cleanup-on-uninstall ajax" - ". network"; - gap: 0 20px; - padding: 15px 20px; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general-delay { - grid-area: delay; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general-off-when-logged-in { - grid-area: logged; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general-ajax-forms { - grid-area: ajax; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general-recaptcha-compat-off { - grid-area: recaptcha; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general-cleanup-on-uninstall { - grid-area: cleanup-on-uninstall; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general--network-wide { - grid-area: network; -} - -.hcaptcha-section-other + table tbody tr th { - padding: 0 0 10px 0; - width: auto; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general-ajax-forms th, -.hcaptcha-section-other + table tbody tr.hcaptcha-general-recaptcha-compat-off th, -.hcaptcha-section-other + table tbody tr.hcaptcha-general-cleanup-on-uninstall th, -.hcaptcha-section-other + table tbody tr.hcaptcha-general--network-wide th { - padding: 0; -} - -.hcaptcha-section-other + table tbody tr td { - width: max-content; -} - -.hcaptcha-section-other + table tbody tr.hcaptcha-general-delay td { - width: auto; -} - -.hcaptcha-section-other + table tbody tr td input { - width: 100%; -} - -/* Section Statistics */ -.hcaptcha-section-statistics + table tbody { - display: grid; - grid-template-columns: repeat(2, 1fr); - grid-template-areas: - "statistics collect-ip" - "anonymous collect-ua"; - gap: 0 20px; - padding: 15px 20px; -} - -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics { - grid-area: statistics; -} - -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-anonymous { - grid-area: anonymous; -} - -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-collect-ip { - grid-area: collect-ip; -} - -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-collect-ua { - grid-area: collect-ua; -} - -.hcaptcha-section-statistics + table tbody tr th { - padding: 0 0 10px 0; - width: auto; -} - -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-anonymous th, -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-collect-ua th { - padding: 0; -} - -.hcaptcha-section-statistics + table tbody tr td { - width: max-content; -} - -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics td { - width: max-content; - min-width: 0; -} - -.hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics .helper-content { - max-width: calc(100vw - 40px); - white-space: normal; - overflow-wrap: anywhere; - line-height: 1.5; -} - @media (max-width: 900px) { .hcaptcha-theme-editor { top: 52px; @@ -1245,6 +1094,7 @@ h3.closed .hcaptcha-section-header-toggle:after { "site-key site-key" "secret-key secret-key" "sample-hcaptcha sample-hcaptcha" + "mode mode" "check-config reset-notifications"; } @@ -1252,7 +1102,7 @@ h3.closed .hcaptcha-section-header-toggle:after { grid-template-columns: repeat(2, 1fr) !important; grid-template-areas: "theme size" - "language mode" + "language ." "force force" "position position"; } @@ -1338,54 +1188,4 @@ h3.closed .hcaptcha-section-header-toggle:after { justify-content: flex-start; } - .hcaptcha-section-enterprise + table tbody { - grid-template-columns: repeat(1, 1fr) !important; - } - - .hcaptcha-section-enterprise + table tbody tr td { - width: unset !important; - } - - .hcaptcha-section-content + table tbody { - grid-template-columns: repeat(1, 1fr); - grid-template-areas: - "content" - "protected-urls"; - } - - .hcaptcha-section-content + table tbody tr td { - width: unset !important; - } - - .hcaptcha-section-other + table tbody { - grid-template-columns: repeat(1, 1fr) !important; - grid-template-areas: - "delay" - "logged" - "recaptcha" - "cleanup-on-uninstall" - "ajax" - "network"; - } - - .hcaptcha-section-other + table tbody tr td { - width: unset !important; - } - - .hcaptcha-section-statistics + table tbody { - grid-template-columns: repeat(1, 1fr); - grid-template-areas: - "statistics" - "anonymous" - "collect-ip" - "collect-ua"; - } - - .hcaptcha-section-statistics + table tbody tr td { - width: unset !important; - } - - .hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics td { - width: max-content !important; - } } diff --git a/assets/css/integrations.css b/assets/css/integrations.css index dfd884c32..e19879e58 100644 --- a/assets/css/integrations.css +++ b/assets/css/integrations.css @@ -1,12 +1,3 @@ -.form-table:first-of-type tr { - background: none; - padding: 10px 0; -} - -.form-table:first-of-type tr th { - display: none; -} - #hcaptcha-options p { margin: 0.5em 0; } @@ -252,19 +243,6 @@ display: none; } -/* Antispam indicators toggle */ -#hcaptcha-options .hcaptcha-integrations-show-antispam-coverage td { - width: max-content; -} - -#hcaptcha-options .hcaptcha-integrations-show-antispam-coverage fieldset:disabled { - color: #a9a9a9; -} - -#hcaptcha-options .hcaptcha-integrations-show-antispam-coverage fieldset:disabled+.helper::before { - opacity: 0.7; -} - /* Antispam indicators help icon */ .hcaptcha-antispam-help { font-size: 18px; diff --git a/assets/css/notifications.css b/assets/css/notifications.css index f67165d1a..1bf1e883e 100644 --- a/assets/css/notifications.css +++ b/assets/css/notifications.css @@ -43,6 +43,14 @@ border-bottom: 1px solid #c3c4c7; } +#hcaptcha-notifications .hcaptcha-notification.notice-warning { + border-left: 4px solid #dba617; +} + +#hcaptcha-notifications.hcaptcha-setup-notice #hcaptcha-navigation { + display: none; +} + .hcaptcha-notification .hcaptcha-notification-title { margin: 7px 0; padding: 2px; diff --git a/assets/css/onboarding-wizard.css b/assets/css/onboarding-wizard.css index fd0a5a129..f43d31baa 100644 --- a/assets/css/onboarding-wizard.css +++ b/assets/css/onboarding-wizard.css @@ -129,6 +129,12 @@ margin-bottom: 8px; } +.hcap-onb-tip .hcap-onb-signup-link, +.hcap-onb-tip .hcap-onb-signup-link:hover, +.hcap-onb-tip .hcap-onb-signup-link:focus { + color: #fff; +} + .hcap-onb-tip .hcap-onb-done { margin-top: 4px; background: #4de1d2; diff --git a/assets/css/settings-admin.css b/assets/css/settings-admin.css index cb4c63de5..eb688b372 100644 --- a/assets/css/settings-admin.css +++ b/assets/css/settings-admin.css @@ -1,6 +1,7 @@ #toplevel_page_hcaptcha img { width: 20px; filter: grayscale(1); + opacity: 1 !important; } #toplevel_page_hcaptcha.wp-menu-open img { diff --git a/assets/css/settings-base.css b/assets/css/settings-base.css index c643d9b4c..4b514093b 100644 --- a/assets/css/settings-base.css +++ b/assets/css/settings-base.css @@ -103,6 +103,7 @@ body.settings_page_hcaptcha { justify-content: flex-end; gap: 10px; flex-wrap: wrap; + transform: translateY(-1px); } .hcaptcha-help-button { @@ -298,20 +299,18 @@ body.settings_page_hcaptcha { } #hcaptcha-message { - display: flex; - align-items: center; - justify-content: space-between; + display: block; + position: relative; + box-sizing: border-box; padding: 8px 12px; + padding-inline-end: 40px; } #hcaptcha-message .notice-dismiss { - position: relative; - top: unset; - right: unset; -} - -#hcaptcha-message { - box-sizing: border-box; + position: absolute; + top: 50%; + right: 1px; + transform: translateY(-50%); } #hcaptcha-message > p { diff --git a/assets/images/rest-api-protection.png b/assets/images/rest-api-protection.png new file mode 100644 index 000000000..36982ff87 Binary files /dev/null and b/assets/images/rest-api-protection.png differ diff --git a/assets/js/admin-wordfence.js b/assets/js/admin-wordfence.js index 1f190dcc1..6940769c4 100644 --- a/assets/js/admin-wordfence.js +++ b/assets/js/admin-wordfence.js @@ -35,10 +35,10 @@ const wordfence = window.hCaptchaWordfence || ( function( document, window, $ ) notice.classList.add( 'wfls-block-list', 'hcaptcha-wordfence-notice' ); noticeLabel.textContent = HCaptchaWordfenceObject.noticeLabel; - noticeDescription.innerHTML = HCaptchaWordfenceObject.noticeDescription; + noticeDescription.textContent = HCaptchaWordfenceObject.noticeDescription; noticeItem.append( noticeLabel, noticeDescription ); notice.append( noticeItem ); - $settings.find( '.wfls-block-content' ).empty().append( notice ); + $settings.find( '.wfls-block-content' ).prepend( notice ); }, getLocationHref() { diff --git a/assets/js/general.js b/assets/js/general.js index c68d4ff6d..a6d487a38 100644 --- a/assets/js/general.js +++ b/assets/js/general.js @@ -66,13 +66,10 @@ const general = function( $ ) { const $themeEditorPreviewNote = $themeEditor.find( '[data-theme-editor-preview-note]' ); const $themeEditorPreviewDefaultContent = $themeEditorPreviewNote.contents().clone(); const $themeEditorOpen = $themeEditorLauncher.find( '[data-theme-editor-open]' ); - const $enterpriseInputs = $( '.hcaptcha-section-enterprise + table input' ); - const $recaptchaCompatOff = $( '[name="hcaptcha_settings[recaptcha_compat_off][]"]' ); const $submit = $form.find( '#submit' ); const modes = {}; let siteKeyInitVal = $siteKey.val(); let secretKeyInitVal = $secretKey.val(); - let enterpriseInitValues = getEnterpriseValues(); let defaultTheme = {}; let lastValidConfigParams = {}; let initialNormalizedConfigParams = null; @@ -87,7 +84,6 @@ const general = function( $ ) { modes[ HCaptchaGeneralObject.modeTestEnterpriseBotDetected ] = HCaptchaGeneralObject.modeTestEnterpriseBotDetectedSiteKey; let credentialsChanged = false; - let enterpriseSettingsChanged = false; let consoleLogs = []; @@ -169,22 +165,6 @@ const general = function( $ ) { return logs.join( '\n' ); } - function getValues( $inputs ) { - const values = {}; - - $inputs.each( function() { - const $input = $( this ); - const name = $input.attr( 'name' ).replace( /hcaptcha_settings\[(.+)]/, '$1' ); - values[ name ] = $input.val(); - } ); - - return values; - } - - function getEnterpriseValues() { - return getValues( $enterpriseInputs ); - } - function clearMessage() { $message.remove(); // Concat below to avoid an inspection message. @@ -956,9 +936,6 @@ const general = function( $ ) { secretKeyInitVal = $secretKey.val(); credentialsChanged = false; - enterpriseInitValues = getValues( $enterpriseInputs ); - enterpriseSettingsChanged = false; - showSuccessMessage( response.data ); $submit.attr( 'disabled', false ); } ) @@ -985,16 +962,6 @@ const general = function( $ ) { } } - function checkChangeEnterpriseSettings() { - if ( JSON.stringify( getEnterpriseValues() ) === JSON.stringify( enterpriseInitValues ) ) { - enterpriseSettingsChanged = false; - clearMessage(); - } else if ( ! enterpriseSettingsChanged ) { - enterpriseSettingsChanged = true; - showErrorMessage( HCaptchaGeneralObject.checkConfigNotice ); - } - } - /** * Set readonly and blocked state for key inputs. * @@ -1008,7 +975,7 @@ const general = function( $ ) { .attr( 'aria-disabled', 'true' ) .on( 'keydown.hcaptchaHelper paste.hcaptchaHelper drop.hcaptchaHelper', ( e ) => e.preventDefault() ); } else { - $el.removeAttr( 'readonly' ) + $el.prop( 'readOnly', false ) .removeAttr( 'aria-disabled' ) .off( 'keydown.hcaptchaHelper paste.hcaptchaHelper drop.hcaptchaHelper' ); } @@ -1139,7 +1106,7 @@ const general = function( $ ) { } ); $submit.on( 'click', function( event ) { - if ( ! ( credentialsChanged || enterpriseSettingsChanged ) ) { + if ( ! credentialsChanged ) { return; } @@ -1529,84 +1496,6 @@ const general = function( $ ) { setThemePreviewView( $( this ).attr( 'data-theme-preview-view' ) ); } ); - function forceHttps( host ) { - host = host.replace( /(http|https):\/\//, '' ); - - const url = new URL( 'https://' + host ); - - return 'https://' + url.host; - } - - function scriptUpdate() { - const params = { - onload: 'hCaptchaOnLoad', - render: 'explicit', - }; - - if ( $recaptchaCompatOff.prop( 'checked' ) ) { - params.recaptchacompat = 'off'; - } - - if ( $customThemes.prop( 'checked' ) ) { - params.custom = 'true'; - } - - const enterpriseParams = { - asset_host: 'assethost', - endpoint: 'endpoint', - host: 'host', - image_host: 'imghost', - report_api: 'reportapi', - sentry: 'sentry', - }; - - const enterpriseValues = getEnterpriseValues(); - - for ( const enterpriseParam in enterpriseParams ) { - const value = enterpriseValues[ enterpriseParam ].trim(); - - if ( value ) { - params[ enterpriseParams[ enterpriseParam ] ] = encodeURIComponent( forceHttps( value ) ); - } - } - - /** - * @param enterpriseValues.api_host - */ - let apiHost = enterpriseValues.api_host.trim(); - apiHost = apiHost ? apiHost : 'js.hcaptcha.com'; - apiHost = forceHttps( apiHost ) + '/1/api.js'; - - const url = new URL( apiHost ); - - for ( const name in params ) { - url.searchParams.append( name, params[ name ] ); - } - - // Remove the existing API script. - document.getElementById( 'hcaptcha-api' ).remove(); - // noinspection JSUnresolvedReference - delete global.hcaptcha; - - // Remove sample hCaptcha. - $sampleHCaptcha.html( '' ); - - // Re-create the API script. - const t = document.getElementsByTagName( 'head' )[ 0 ]; - const s = document.createElement( 'script' ); - - s.type = 'text/javascript'; - s.id = 'hcaptcha-api'; - s.src = url.href; - - t.appendChild( s ); - } - - $enterpriseInputs.on( 'change', function() { - scriptUpdate(); - checkChangeEnterpriseSettings(); - } ); - // Prevent saving values of some form elements. $checkConfig.removeAttr( 'name' ); $resetNotifications.removeAttr( 'name' ); diff --git a/assets/js/hcaptcha-acfe.js b/assets/js/hcaptcha-acfe.js index 9ec35b828..8e697a4cc 100644 --- a/assets/js/hcaptcha-acfe.js +++ b/assets/js/hcaptcha-acfe.js @@ -1,4 +1,5 @@ /* global acf, jQuery */ +// noinspection JSUnusedGlobalSymbols const hCaptchaACFE = window.hCaptchaACFE || ( function( window, $ ) { const app = { @@ -67,7 +68,7 @@ const hCaptchaACFE = window.hCaptchaACFE || ( function( window, $ ) { document.querySelectorAll( '.acfe-field-recaptcha iframe' ).forEach( ( el ) => { const src = el.getAttribute( 'src' ) || ''; const title = el.getAttribute( 'title' ) || ''; - const isRecaptcha = ( src + title ).toLowerCase().includes( 'recaptcha' ); + const isRecaptcha = app.isRecaptchaUrl( src ) || title.toLowerCase().includes( 'recaptcha' ); if ( ! isRecaptcha ) { return; @@ -127,7 +128,15 @@ const hCaptchaACFE = window.hCaptchaACFE || ( function( window, $ ) { window.hCaptchaOnLoad(); }, - ajaxCompleteHandler() { + ajaxCompleteHandler( event, xhr, settings ) { + const data = settings?.data; + const action = typeof data === 'string' ? new URLSearchParams( data ).get( 'action' ) : data?.action; + + // Keep verified tokens until ACF completes the final submission. + if ( action === 'acf/validate_save_post' && xhr?.responseJSON?.success && xhr.responseJSON.data?.valid === 1 ) { + return; + } + // ACFE may perform AJAX validation; simply re-bind safely after requests. if ( typeof window.hCaptchaBindEvents === 'function' ) { window.hCaptchaBindEvents(); diff --git a/assets/js/hcaptcha-fst.js b/assets/js/hcaptcha-fst.js index bdeb59878..c84357067 100644 --- a/assets/js/hcaptcha-fst.js +++ b/assets/js/hcaptcha-fst.js @@ -53,7 +53,41 @@ const fst = window.hCaptchaFST || ( function( document ) { }; let currentToken = getStoredToken(); + let tokenExpiresAt = 0; let pendingRequest = null; + let issueError = ''; + const pendingSubmissions = new WeakMap(); + const messages = { + loading: 'Preparing the form. Please wait.', + error: 'Unable to prepare the form. Please check your connection and try submitting again.', + rateLimited: 'Too many requests (429). Please refresh the page and try again.', + ...HCaptchaFSTObject.messages, + }; + + /** + * Show a form preparation status outside the widget that is re-rendered. + * + * @param {HTMLElement} form Protected form or container. + * @param {string} message Message. + * @param {boolean} error Whether preparation failed. + */ + const showMessage = ( form, message = '', error = false ) => { + let element = form.querySelector( '.hcaptcha-fst-message' ); + + if ( ! message ) { + element?.remove(); + return; + } + + if ( ! element ) { + element = document.createElement( 'div' ); + element.className = 'hcaptcha-fst-message'; + form.appendChild( element ); + } + + element.setAttribute( 'role', error ? 'alert' : 'status' ); + element.textContent = message; + }; /** * Update all form timing fields together. @@ -78,6 +112,106 @@ const fst = window.hCaptchaFST || ( function( document ) { document.addEventListener( 'hCaptchaAfterBindEvents', function() { app.getToken(); } ); + + document.addEventListener( 'click', app.handleClick, true ); + document.addEventListener( 'submit', app.handleSubmit, true ); + }, + + isReady( form ) { + return ! pendingRequest && currentToken && Date.now() < tokenExpiresAt && + form.querySelector( '[name="hcap_fst_token"]' )?.value === currentToken; + }, + + runWhenReady( form, callback, submitter = null ) { + if ( pendingSubmissions.has( form ) ) { + return pendingSubmissions.get( form ); + } + + if ( app.isReady( form ) ) { + showMessage( form ); + callback(); + return Promise.resolve( true ); + } + + const disabled = submitter?.disabled; + const busy = form.getAttribute( 'aria-busy' ); + + if ( submitter && 'disabled' in submitter ) { + submitter.disabled = true; + } + + form.setAttribute( 'aria-busy', 'true' ); + showMessage( form, messages.loading ); + + const submission = app.getToken().then( () => { + pendingSubmissions.delete( form ); + + if ( submitter && 'disabled' in submitter ) { + submitter.disabled = disabled; + } + + if ( busy === null ) { + form.removeAttribute( 'aria-busy' ); + } else { + form.setAttribute( 'aria-busy', busy ); + } + + if ( ! form.isConnected ) { + return false; + } + + if ( ! app.isReady( form ) ) { + showMessage( form, issueError || messages.error, true ); + return false; + } + + showMessage( form ); + callback(); + return true; + } ); + + pendingSubmissions.set( form, submission ); + return submission; + }, + + handleClick( event ) { + if ( ! ( event.target instanceof Element ) ) { + return; + } + + const button = event.target.closest( window.hCaptcha?.submitButtonSelector || '[type="submit"]' ); + const form = button?.closest( window.hCaptcha?.formSelector || 'form' ) || button?.form; + + if ( ! form?.querySelector( '[name="hcap_fst_token"]' ) || app.isReady( form ) ) { + return; + } + + event.preventDefault(); + event.stopImmediatePropagation(); + app.runWhenReady( form, () => button.click(), button ); + }, + + handleSubmit( event ) { + const form = event.target; + + if ( ! form.querySelector( '[name="hcap_fst_token"]' ) || app.isReady( form ) ) { + return; + } + + event.preventDefault(); + event.stopImmediatePropagation(); + + const submitter = event.submitter; + + app.runWhenReady( form, () => { + if ( form.requestSubmit ) { + form.requestSubmit( submitter || undefined ); + } else if ( submitter ) { + submitter.click(); + } else if ( form.dispatchEvent( new Event( 'submit', { bubbles: true, cancelable: true } ) ) ) { + HTMLFormElement.prototype.submit.call( form ); + } + }, submitter ); }, getToken() { @@ -87,7 +221,10 @@ const fst = window.hCaptchaFST || ( function( document ) { pendingRequest = ( async function() { const formBody = new URLSearchParams(); - let issueError = ''; + const controller = new AbortController(); + // The timer is cleared in finally, including after a successful return. + let timeout = setTimeout( () => controller.abort(), 10000 ); + issueError = ''; formBody.set( 'action', HCaptchaFSTObject.issueTokenAction ); formBody.set( 'nonce', HCaptchaFSTObject.issueTokenNonce ); @@ -98,22 +235,39 @@ const fst = window.hCaptchaFST || ( function( document ) { formBody.set( 'replaceToken', currentToken ); } + const requestToken = () => fetch( HCaptchaFSTObject.ajaxUrl, { + method: 'POST', + credentials: 'same-origin', + cache: 'no-store', + signal: controller.signal, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + }, + body: formBody.toString(), + } ); + let requestedAt = Date.now(); + try { - const res = await fetch( HCaptchaFSTObject.ajaxUrl, { - method: 'POST', - credentials: 'same-origin', - cache: 'no-store', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', - }, - body: formBody.toString(), - } ); - - const body = await res.json(); + let res = await requestToken(); + let body = await res.json(); + const freshNonce = body?.data?.nonce; + + if ( 403 === res.status && 'fst-invalid-nonce' === body?.data?.code && 'string' === typeof freshNonce && freshNonce ) { + HCaptchaFSTObject.issueTokenNonce = freshNonce; + formBody.set( 'nonce', freshNonce ); + clearTimeout( timeout ); + timeout = setTimeout( () => controller.abort(), 10000 ); + requestedAt = Date.now(); + res = await requestToken(); + body = await res.json(); + } const token = body?.data?.token ?? ''; if ( res.ok && body?.success && token ) { + const ttl = Number( body?.data?.ttl ); + const secondsLeft = Number.isFinite( ttl ) && ttl > 0 ? Math.max( ttl - 5, 1 ) : 55; + tokenExpiresAt = requestedAt + ( secondsLeft * 1000 ); currentToken = token; storeToken( currentToken ); setToken( currentToken ); @@ -122,19 +276,24 @@ const fst = window.hCaptchaFST || ( function( document ) { } if ( 429 === res.status && 'fst-rate-limited' === body?.data?.code ) { - issueError = rateLimitedToken; + issueError = messages.rateLimited; } } catch { // The server may have replaced the prior token before the response failed. } finally { - pendingRequest = null; + clearTimeout( timeout ); } currentToken = ''; + tokenExpiresAt = 0; storeToken( currentToken ); - setToken( issueError ); + setToken( issueError === messages.rateLimited ? rateLimitedToken : '' ); }() ); + pendingRequest = pendingRequest.finally( () => { + pendingRequest = null; + } ); + return pendingRequest; }, }; diff --git a/assets/js/hcaptcha-givewp.js b/assets/js/hcaptcha-givewp.js index 2aba7e152..d6984a6d5 100644 --- a/assets/js/hcaptcha-givewp.js +++ b/assets/js/hcaptcha-givewp.js @@ -42,15 +42,19 @@ const hCaptchaGiveWP = window.hCaptchaGiveWP || ( function( window ) { const url = typeof resource === 'string' ? resource : ( resource?.url || '' ); let route = ''; + let paypalOrder = false; try { const u = new URL( url, window.location.href ); route = u.searchParams.get( 'givewp-route' ) || ''; + paypalOrder = u.origin === window.location.origin && + u.pathname.endsWith( '/wp-admin/admin-ajax.php' ) && + ( u.searchParams.get( 'action' ) || body.get( 'action' ) ) === 'give_paypal_commerce_create_order'; } catch { // ignore } - if ( route !== 'donate' ) { + if ( route !== 'donate' && ! paypalOrder ) { return; } @@ -73,12 +77,15 @@ const hCaptchaGiveWP = window.hCaptchaGiveWP || ( function( window ) { const sigInput = giveWPForm.querySelector( `[name="${ sigName }"]` ); const hcapHp = giveWPForm.querySelector( `[id^="hcap_hp_"]` ); - body.set( responseName, response?.value ); - body.set( widgetName, widgetId?.value ); - body.set( nonceName, nonce?.value ); - body.set( tokenName, tokenInput?.value ); - body.set( sigName, sigInput?.value ); - body.set( hcapHp.id, hcapHp.value ?? '' ); + body.set( responseName, response?.value ?? '' ); + body.set( widgetName, widgetId?.value ?? '' ); + body.set( nonceName, nonce?.value ?? '' ); + body.set( tokenName, tokenInput?.value ?? '' ); + body.set( sigName, sigInput?.value ?? '' ); + + if ( hcapHp ) { + body.set( hcapHp.id, hcapHp.value ?? '' ); + } config.body = body; args[ 1 ] = config; diff --git a/assets/js/hcaptcha-otter.js b/assets/js/hcaptcha-otter.js index 968aa0c12..b55e32d77 100644 --- a/assets/js/hcaptcha-otter.js +++ b/assets/js/hcaptcha-otter.js @@ -67,12 +67,14 @@ const hCaptchaOtter = window.hCaptchaOtter || ( function( window ) { const responseName = 'h-captcha-response'; const widgetName = 'hcaptcha-widget-id'; const nonceName = 'hcaptcha_otter_nonce'; + const formNonceName = 'hcaptcha_otter_form_nonce'; const tokenName = 'hcap_fst_token'; const sigName = 'hcap_hp_sig'; const response = form.querySelector( `[name="${ responseName }"]` )?.value ?? ''; const widget = form.querySelector( `[name="${ widgetName }"]` )?.value ?? ''; const nonce = form.querySelector( `[name="${ nonceName }"]` )?.value ?? ''; + const formNonce = form.querySelector( `[name="${ formNonceName }"]` )?.value ?? ''; const token = form.querySelector( `[name="${ tokenName }"]` )?.value ?? ''; const sig = form.querySelector( `[name="${ sigName }"]` )?.value ?? ''; const hcapHp = form.querySelector( `[id^="hcap_hp_"]` ); @@ -89,6 +91,8 @@ const hCaptchaOtter = window.hCaptchaOtter || ( function( window ) { formData[ nonceName ] = nonce; } + formData[ formNonceName ] = formNonce; + if ( token ) { formData[ tokenName ] = token; } diff --git a/assets/js/hcaptcha-wc-stripe-express.js b/assets/js/hcaptcha-wc-stripe-express.js new file mode 100644 index 000000000..3b719c488 --- /dev/null +++ b/assets/js/hcaptcha-wc-stripe-express.js @@ -0,0 +1,315 @@ +// noinspection JSUnusedGlobalSymbols + +( function() { + if ( window.hCaptchaWCStripeExpress ) { + return; + } + + const settings = window.HCaptchaWCStripeExpressObject || {}; + const nonceName = settings.nonceName || 'hcaptcha_wc_checkout_nonce'; + const missingProofMessage = settings.missingProofMessage || 'Complete hCaptcha before express checkout.'; + const wrapperSelector = '.hcaptcha-wc-stripe-express-proof'; + const maxProofAge = 90 * 1000; + const proofStates = new WeakMap(); + const controllerGates = new WeakMap(); + const controllers = new Set(); + const contexts = [ 'product', 'cart', 'minicart', 'express_checkout' ]; + + function getRoots( context ) { + if ( 'express_checkout' === context ) { + return [ ...document.querySelectorAll( 'form.checkout .hcaptcha-wc-checkout-proof' ) ]; + } + + return [ ...document.querySelectorAll( `${ wrapperSelector }[data-context="${ context }"]` ) ]; + } + + function getField( root, name ) { + return root.querySelector( `[name="${ name }"]` ); + } + + function getResponse( root ) { + return getField( root, 'h-captcha-response' )?.value || ''; + } + + function hasChallenge( root ) { + return !! root.querySelector( 'h-captcha.h-captcha' ); + } + + function isReady( root ) { + if ( ! root?.isConnected || ! getField( root, 'hcaptcha-widget-id' )?.value ) { + return false; + } + + // The form may be explicitly exempted, but its signed identity is still required. + if ( ! hasChallenge( root ) ) { + return true; + } + + const state = proofStates.get( root ); + const response = getResponse( root ); + + return !! response && + ! state?.spent && + state?.token === response && + Date.now() - state?.createdAt < maxProofAge; + } + + function getReadyRoot( context ) { + return getRoots( context ).find( isReady ) || null; + } + + function syncController( controller ) { + const context = controller?.context?.getPage?.(); + + if ( ! contexts.includes( context ) || 'expressCheckout' !== controller?.gateway?.elementType ) { + return; + } + + let gate = controllerGates.get( controller ); + + if ( ! gate ) { + gate = { + nativeEnabled: controller.gateway._isDisabled !== true, + enable: controller.enablePaymentElement.bind( controller ), + disable: controller.disablePaymentElement.bind( controller ), + }; + controllerGates.set( controller, gate ); + controller.enablePaymentElement = ( ...args ) => { + gate.nativeEnabled = true; + + return getReadyRoot( context ) ? gate.enable( ...args ) : gate.disable(); + }; + controller.disablePaymentElement = ( ...args ) => { + gate.nativeEnabled = false; + + return gate.disable( ...args ); + }; + } + + controllers.add( controller ); + + if ( ! getReadyRoot( context ) ) { + gate.disable(); + } else if ( gate.nativeEnabled ) { + gate.enable(); + } + } + + function syncControllers( context ) { + for ( const controller of controllers ) { + if ( context === controller.context?.getPage?.() ) { + syncController( controller ); + } + } + } + + function syncAllControllers() { + for ( const controller of controllers ) { + syncController( controller ); + } + } + + function forgetProof( root ) { + const state = proofStates.get( root ); + + if ( state ) { + clearTimeout( state.timeout ); + proofStates.delete( root ); + } + } + + function recordSolved( context, token ) { + if ( ! token ) { + return false; + } + + let matched = false; + + for ( const root of getRoots( context ) ) { + if ( ! hasChallenge( root ) || getResponse( root ) !== token ) { + continue; + } + + const previous = proofStates.get( root ); + + if ( previous?.token === token ) { + matched = matched || ! previous.spent; + continue; + } + + forgetProof( root ); + const state = { token, createdAt: Date.now(), spent: false }; + state.timeout = setTimeout( () => { + if ( proofStates.get( root ) === state ) { + proofStates.delete( root ); + syncControllers( context ); + } + }, maxProofAge ); + proofStates.set( root, state ); + matched = true; + } + + if ( matched ) { + syncControllers( context ); + } + + return matched; + } + + function onSolved( context, token ) { + if ( ! recordSolved( context, token ) ) { + // hCaptcha can invoke the callback before updating its response field. + setTimeout( () => recordSolved( context, token ), 0 ); + } + } + + function onExpired( context ) { + for ( const root of getRoots( context ) ) { + forgetProof( root ); + } + + syncControllers( context ); + } + + function getProofFields( root ) { + const hpInput = root.querySelector( 'input[id^="hcap_hp_"]' ); + const names = [ + 'h-captcha-response', + 'hcaptcha-widget-id', + nonceName, + hpInput?.name, + 'hcap_hp_sig', + 'hcap_fst_token', + ]; + const fields = {}; + + for ( const name of names ) { + if ( ! name ) { + continue; + } + + const field = getField( root, name ); + + if ( field ) { + fields[ name ] = field.value; + } + } + + return fields; + } + + function isStripeCheckout( options ) { + if ( 'POST' !== String( options?.method || '' ).toUpperCase() ) { + return false; + } + + if ( typeof options.url !== 'string' ) { + return '/wc-stripe/v1/cart/checkout' === options.path; + } + + let url; + + try { + url = new URL( options.url, window.location.href ); + } catch { + return false; + } + + if ( url.origin !== window.location.origin ) { + return false; + } + + if ( 'wc_stripe_frontend_request' === url.searchParams.get( 'wc-ajax' ) ) { + return '/wc-stripe/v1/cart/checkout' === url.searchParams.get( 'path' ); + } + + if ( '/wc-stripe/v1/cart/checkout' === url.searchParams.get( 'rest_route' ) ) { + return true; + } + + return url.pathname.replace( /\/+$/, '' ).endsWith( '/wp-json/wc-stripe/v1/cart/checkout' ); + } + + function resetProof( root, context ) { + const widget = root.querySelector( 'h-captcha.h-captcha' ); + forgetProof( root ); + + if ( widget && typeof window.hCaptchaReset === 'function' ) { + window.hCaptchaReset( widget ); + } + + syncControllers( context ); + } + + function addProof( options, next ) { + if ( ! isStripeCheckout( options ) ) { + return next( options ); + } + + const data = options.data; + const context = data?.context; + + if ( ! data || Array.isArray( data ) || 'object' !== typeof data || ! contexts.includes( context ) ) { + return Promise.reject( new Error( missingProofMessage ) ); + } + + const root = getReadyRoot( context ); + + if ( ! root ) { + return Promise.reject( new Error( missingProofMessage ) ); + } + + const fields = getProofFields( root ); + const state = proofStates.get( root ); + + if ( state ) { + state.spent = true; + clearTimeout( state.timeout ); + syncControllers( context ); + } + + let result; + + try { + result = next( { ...options, data: { ...data, ...fields } } ); + } catch ( error ) { + resetProof( root, context ); + throw error; + } + + return Promise.resolve( result ).then( + ( response ) => { + resetProof( root, context ); + return response; + }, + ( error ) => { + resetProof( root, context ); + throw error; + }, + ); + } + + // noinspection UnnecessaryLocalVariableJS + const app = { + onProductSolved: ( token ) => onSolved( 'product', token ), + onCartSolved: ( token ) => onSolved( 'cart', token ), + onMinicartSolved: ( token ) => onSolved( 'minicart', token ), + onProductExpired: () => onExpired( 'product' ), + onCartExpired: () => onExpired( 'cart' ), + onMinicartExpired: () => onExpired( 'minicart' ), + }; + + window.hCaptchaWCStripeExpress = app; + wp.hooks.addFilter( 'hcaptcha.formSelector', 'hcaptcha-wc-stripe-express', ( selector ) => `${ selector }, ${ wrapperSelector }` ); + wp.apiFetch.use( addProof ); + window.wcStripe?.actions?.addAction( 'payment_element_ready', syncController ); + window.wcStripe?.actions?.addAction( 'express_element_ready', ( availableMethods, gateway ) => { + syncController( gateway?.controller ); + } ); + if ( window.MutationObserver && document.body ) { + new MutationObserver( syncAllControllers ).observe( document.body, { childList: true, subtree: true } ); + } + document.addEventListener( 'hCaptchaSubmitted', ( event ) => { + onSolved( 'express_checkout', event.detail?.token ); + } ); +}() ); diff --git a/assets/js/integrations.js b/assets/js/integrations.js index 2da75db3f..0e22417ef 100644 --- a/assets/js/integrations.js +++ b/assets/js/integrations.js @@ -39,8 +39,6 @@ const integrations = function( $ ) { const $wpWrap = $( '#wpwrap' ); const $adminmenuwrap = $( '#adminmenuwrap' ); const $search = $( '#hcaptcha-integrations-search' ); - const $showAntispamCoverage = $( '#show_antispam_coverage_1' ); - const $antispamLegend = $( '#hcaptcha-antispam-legend' ); function clearMessage() { $message.remove(); @@ -94,7 +92,7 @@ const integrations = function( $ ) { } function isActiveTable( $table ) { - return $table.is( jQuery( '.form-table' ).eq( 1 ) ); + return $table.is( jQuery( '.form-table' ).eq( 0 ) ); } function swapThemes( activate, entity, newTheme ) { @@ -103,7 +101,7 @@ const integrations = function( $ ) { } const $tables = $( '.form-table' ); - const $fromTable = $tables.eq( activate ? 1 : 2 ); + const $fromTable = $tables.eq( activate ? 0 : 1 ); const dataLabel = activate ? '' : '[data-label="' + newTheme + '"]'; const $img = $fromTable.find( '.hcaptcha-integrations-logo img[data-entity="theme"]' + dataLabel ); @@ -112,7 +110,7 @@ const integrations = function( $ ) { return; } - const $toTable = $tables.eq( activate ? 2 : 1 ); + const $toTable = $tables.eq( activate ? 1 : 0 ); const $tr = $img.closest( 'tr' ); insertIntoTable( $toTable, $img.attr( 'data-label' ), $tr ); @@ -150,79 +148,6 @@ const integrations = function( $ ) { } } - // Set up antispam helper - function setupHelper( $label ) { - let $helper = $label.next( '.helper' ); - - // If a helper doesn't exist immediately after, insert it - if ( ! $helper.length ) { - $helper = $( document.createElement( 'span' ) ).addClass( 'helper' ); - $label.after( $helper ); - } - - // Rebuild helper icons based on helper data-* attributes. - // The helper may have several data-antispam-* attributes (e.g., data-antispam-honeypot, data-antispam-fst). - // We insert corresponding nodes like , inside the helper. - ( function populateHelperIcons() { - // Remove previously added antispam icons to avoid duplicates. - $helper.find( 'i[class^="antispam"]' ).remove(); - - const attrs = $label.get( 0 )?.attributes ?? []; - const classes = []; - - for ( let i = 0; i < attrs.length; i++ ) { - const name = attrs[ i ].name; - - // Ignore 'data-antispam' as it is a general marker for the helper. - if ( name.indexOf( 'data-antispam-' ) === 0 ) { - // Convert attribute name to class name by stripping the 'data-' prefix. - const className = name.replace( /^data-/, '' ); - - if ( classes.indexOf( className ) === -1 ) { - classes.push( className ); - } - } - } - - // Append images for each discovered class. - classes.forEach( function( cls ) { - const $icon = $( document.createElement( 'i' ) ).addClass( cls ); - - $helper.prepend( $icon ); - } ); - }() ); - - return $helper; - } - - function setupHelpers() { - const disabled = $showAntispamCoverage.prop( 'disabled' ); - - if ( disabled ) { - return; - } - - const checked = $showAntispamCoverage.prop( 'checked' ); - - // Find all labels that declare the antispam marker - $( 'label[data-antispam]' ).each( function() { - const $helper = setupHelper( $( this ) ); - - if ( checked ) { - $helper.css( 'display', 'inline-flex' ); - } else { - $helper.hide(); - } - } ); - - // Toggle legend visibility. - if ( checked ) { - $antispamLegend.show(); - } else { - $antispamLegend.hide(); - } - } - /** * Suggest an entity for activation. */ @@ -251,11 +176,6 @@ const integrations = function( $ ) { }; } - // Handle Show Antispam Indicators checkbox change: insert/clear helper spans after labels - $showAntispamCoverage.on( 'change', function() { - setupHelpers(); - } ); - const latestPlanRequests = new WeakMap(); $( '.form-table img' ).on( 'click', function( event ) { @@ -544,7 +464,7 @@ const integrations = function( $ ) { } if ( currStatus !== status ) { - const $toTable = $tables.eq( status ? 1 : 2 ); + const $toTable = $tables.eq( status ? 0 : 1 ); const alt = $logo.find( 'img' ).attr( 'alt' ); insertIntoTable( $toTable, alt, $tr ); @@ -607,7 +527,7 @@ const integrations = function( $ ) { return; } - const $table = $( '.form-table' ).eq( activate ? 1 : 2 ); + const $table = $( '.form-table' ).eq( activate ? 0 : 1 ); swapThemes( activate, entity, newTheme ); insertIntoTable( $table, alt, $tr ); @@ -817,7 +737,7 @@ const integrations = function( $ ) { 100, ) ); - $( '#hcaptcha-options' ).keydown( + $( '#hcaptcha-options' ).on( 'keydown', function( e ) { if ( $( e.target ).is( $search ) && e.which === 13 ) { e.preventDefault(); @@ -825,7 +745,6 @@ const integrations = function( $ ) { }, ); - setupHelpers(); suggestActivate(); }; diff --git a/assets/js/notifications.js b/assets/js/notifications.js index ca986f972..840195f5e 100644 --- a/assets/js/notifications.js +++ b/assets/js/notifications.js @@ -27,6 +27,7 @@ const notifications = ( $ ) => { const navSelectors = navPrevSelector + ', ' + navNextSelector; const buttonsSelector = '.hcaptcha-notification-buttons'; const resetBtnSelector = 'button#reset_notifications'; + const resetRowSelector = 'tr.hcaptcha-general-reset-notifications'; const footerSelector = '#hcaptcha-notifications-footer'; let $notifications; @@ -150,6 +151,7 @@ const notifications = ( $ ) => { $notification.remove(); $next.show(); + $( resetRowSelector ).removeClass( 'hidden' ); setNavStatus(); setButtons(); @@ -208,13 +210,17 @@ const notifications = ( $ ) => { $.post( { url: HCaptchaNotificationsObject.ajaxUrl, data, - } ).success( function( response ) { + } ).done( function( response ) { if ( ! response.success ) { return; } - $( notificationsSelector ).remove(); - $( response.data ).insertBefore( sectionKeysSelector ); + $( resetRowSelector ).addClass( 'hidden' ); + + if ( ! $( notificationsSelector ).hasClass( 'hcaptcha-setup-notice' ) ) { + $( notificationsSelector ).remove(); + $( response.data ).insertBefore( sectionKeysSelector ); + } setButtons(); normalizeNotificationHeight(); diff --git a/assets/js/onboarding-wizard.js b/assets/js/onboarding-wizard.js index b2402c139..1548581c8 100644 --- a/assets/js/onboarding-wizard.js +++ b/assets/js/onboarding-wizard.js @@ -2,6 +2,7 @@ /** * @param HCaptchaOnboardingObject.ajaxUrl + * @param HCaptchaOnboardingObject.antispamUrl * @param HCaptchaOnboardingObject.autoSetupNonce * @param HCaptchaOnboardingObject.autoSetupParam * @param HCaptchaOnboardingObject.currentStep @@ -25,14 +26,16 @@ * @param HCaptchaOnboardingObject.nonceParam * @param HCaptchaOnboardingObject.page * @param HCaptchaOnboardingObject.selectors - * @param HCaptchaOnboardingObject.selectors.general.antispam * @param HCaptchaOnboardingObject.selectors.general.check_config * @param HCaptchaOnboardingObject.selectors.general.force * @param HCaptchaOnboardingObject.selectors.general.mode * @param HCaptchaOnboardingObject.selectors.general.save * @param HCaptchaOnboardingObject.selectors.general.site_key + * @param HCaptchaOnboardingObject.selectors.antispam.bot_detection + * @param HCaptchaOnboardingObject.selectors.antispam.save * @param HCaptchaOnboardingObject.selectors.integrations.integrations_list * @param HCaptchaOnboardingObject.selectors.integrations.save + * @param HCaptchaOnboardingObject.signupUrl * @param HCaptchaOnboardingObject.stepNonce * @param HCaptchaOnboardingObject.stepParam * @param HCaptchaOnboardingObject.steps @@ -53,8 +56,9 @@ const onboarding = function( $ ) { // Steps by page const stepsByPage = { - general: [ 1, 2, 3, 4, 5, 6 ], - integrations: [ 7, 8 ], + general: [ 1, 2, 3, 4, 5 ], + antispam: [ 6, 7 ], + integrations: [ 8, 9 ], }; // Targets map per step @@ -63,10 +67,11 @@ const onboarding = function( $ ) { 2: { page: 'general', selector: cfg.selectors.general.mode }, 3: { page: 'general', selector: cfg.selectors.general.check_config }, 4: { page: 'general', selector: cfg.selectors.general.force }, - 5: { page: 'general', selector: cfg.selectors.general.antispam }, - 6: { page: 'general', selector: cfg.selectors.general.save }, - 7: { page: 'integrations', selector: cfg.selectors.integrations.integrations_list }, - 8: { page: 'integrations', selector: cfg.selectors.integrations.save }, + 5: { page: 'general', selector: cfg.selectors.general.save }, + 6: { page: 'antispam', selector: cfg.selectors.antispam.bot_detection }, + 7: { page: 'antispam', selector: cfg.selectors.antispam.save }, + 8: { page: 'integrations', selector: cfg.selectors.integrations.integrations_list }, + 9: { page: 'integrations', selector: cfg.selectors.integrations.save }, }; let $tooltip; @@ -88,16 +93,27 @@ const onboarding = function( $ ) { return m ? parseInt( m[ 1 ], 10 ) : 1; } - function nextStep( current ) { - const n = stepNumber( current ); - - return 'step ' + ( n + 1 ); - } - function inArray( needle, arr ) { return arr.indexOf( needle ) !== -1; } + function appendStepText( $container, step ) { + if ( step !== 1 ) { + $container.text( cfg.steps[ step ] ); + + return; + } + + /* language=HTML */ + $container.append( $( '' ) + .attr( { + href: cfg.signupUrl, + target: '_blank', + rel: 'noopener noreferrer', + } ) + .text( cfg.steps[ step ] ) ); + } + function setLocationHref( url ) { if ( typeof onboarding.setLocationHref === 'function' ) { // For testing purposes. @@ -144,8 +160,8 @@ const onboarding = function( $ ) { removeTooltip(); - if ( form && typeof form.submit === 'function' ) { - form.submit(); + if ( form ) { + submitSettingsForm( autoSetupUrl ); return; } @@ -205,15 +221,18 @@ const onboarding = function( $ ) { /* language=HTML */ const $list = $( '
    ' ); - for ( let i = 1; i <= 8; i++ ) { + for ( let i = 1; i <= 9; i++ ) { /* language=HTML */ const $li = $( '
  1. ' ) - .text( cfg.steps[ i ] ) .attr( 'data-step', i ) - .attr( 'role', 'button' ) - .attr( 'tabindex', '0' ) .addClass( 'hcap-onb-step' ); + appendStepText( $li, i ); + + if ( i !== 1 ) { + $li.attr( 'role', 'button' ).attr( 'tabindex', '0' ); + } + if ( 'step ' + i === current ) { $li.addClass( 'current' ); } @@ -438,7 +457,7 @@ const onboarding = function( $ ) { }, 0 ); } - // Build congrats/rating popup shown after completion (step 8) + // Build congrats/rating popup shown after completion (step 9) function buildCongratsModal( onDismiss = undefined ) { /* language=HTML */ const $overlay = $( '
    ' ); @@ -569,27 +588,8 @@ const onboarding = function( $ ) { return; } - const next = nextStep( 'step ' + step ); - - if ( step === 6 && cfg.page === 'general' ) { - // Last General step → go Integrations - cfg.currentStep = next; // 'step 7' - - postUpdate( next ).always( function() { - setLocationHref( cfg.integrationsUrl ); - } ); - - return; - } - - if ( step >= 8 ) { - // Completed via the Done button — show congrats popup - postUpdate( 'completed' ).always( function() { - buildCongratsModal( function() { - removeTooltip(); - $( '.hcap-onb-panel' ).remove(); - } ); - } ); + if ( [ 5, 7, 9 ].includes( step ) ) { + $( '#hcaptcha-options #submit' ).trigger( 'click' ); return; } @@ -600,10 +600,11 @@ const onboarding = function( $ ) { /* language=HTML */ $tooltip = $( '' ); - const tipText = cfg.steps[ step ]; - /* language=HTML */ - $tooltip.append( $( '
    ' ).text( tipText ) ); + const $tipText = $( '
    ' ); + + appendStepText( $tipText, step ); + $tooltip.append( $tipText ); // For step 1 add a second line with a video link if ( step === 1 ) { @@ -697,8 +698,13 @@ const onboarding = function( $ ) { // Navigation helper must be available regardless of early returns below function goToStep( n ) { - const isGeneral = inArray( n, stepsByPage.general ); - const base = isGeneral ? cfg.generalUrl : cfg.integrationsUrl; + let base = cfg.integrationsUrl; + + if ( inArray( n, stepsByPage.general ) ) { + base = cfg.generalUrl; + } else if ( inArray( n, stepsByPage.antispam ) ) { + base = cfg.antispamUrl; + } setLocationHref( buildUrl( base, { [ cfg.stepParam ]: n, @@ -710,6 +716,10 @@ const onboarding = function( $ ) { $( document ).off( '.hcapOnbNav' ); $( document ).on( 'click.hcapOnbNav', '.hcap-onb-list li.hcap-onb-step', function( e ) { + if ( $( e.target ).closest( 'a' ).length ) { + return; + } + e.preventDefault(); const n = parseInt( $( this ).attr( 'data-step' ), 10 ); @@ -720,6 +730,10 @@ const onboarding = function( $ ) { } ); $( document ).on( 'keydown.hcapOnbNav', '.hcap-onb-list li.hcap-onb-step', function( e ) { + if ( $( e.target ).closest( 'a' ).length ) { + return; + } + if ( e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar' ) { e.preventDefault(); @@ -738,25 +752,51 @@ const onboarding = function( $ ) { } } ); - // Also advance on real Save for steps 6 (General) and 8 (Integrations) - // For step 8 we first show the congrats popup, then proceed with submitting. + function submitSettingsForm( fallbackUrl = '' ) { + const form = $( '#hcaptcha-options' ).get( 0 ); + + if ( ! form ) { + return; + } + + try { + if ( typeof form.submit === 'function' ) { + form.submit(); + } else { + HTMLFormElement.prototype.submit.call( form ); + } + } catch { + if ( fallbackUrl ) { + setLocationHref( fallbackUrl ); + } else { + $( '#hcaptcha-options #submit' ).trigger( 'click' ); + } + } + } + + // Save each page before advancing to the next one. $( document ).on( 'submit', '#hcaptcha-options', function( e ) { const n = stepNumber( cfg.currentStep || 'step 1' ); - if ( n === 6 && cfg.page === 'general' ) { - const next = 'step 7'; + if ( ( n === 5 && cfg.page === 'general' ) || ( n === 7 && cfg.page === 'antispam' ) ) { + e.preventDefault(); - cfg.currentStep = next; - postUpdate( next ); + const next = n === 5 ? 'step 6' : 'step 8'; + const storageKey = n === 5 ? 'hcapOnbGoAntiSpam' : 'hcapOnbGoIntegrations'; - try { - if ( window.sessionStorage ) { - sessionStorage.setItem( 'hcapOnbGoIntegrations', '1' ); + cfg.currentStep = next; + postUpdate( next ).always( function() { + try { + if ( window.sessionStorage ) { + sessionStorage.setItem( storageKey, '1' ); + } + } catch { + // no-op } - } catch { - // no-op - } - } else if ( n === 8 && cfg.page === 'integrations' ) { + + submitSettingsForm(); + } ); + } else if ( n === 9 && cfg.page === 'integrations' ) { if ( hcapOnbSubmitting ) { return; // allow natural submit a second time } @@ -770,12 +810,7 @@ const onboarding = function( $ ) { // After closing the modal, submit the form at once hcapOnbSubmitting = true; - try { - $( '#hcaptcha-options' ).get( 0 ).submit(); - } catch { - // fallback: trigger a click on the `submit` button - $( '#hcaptcha-options [type="submit"]' ).first().trigger( 'click' ); - } + submitSettingsForm(); } ); } ); } @@ -788,15 +823,32 @@ const onboarding = function( $ ) { // Determine current numeric step const num = stepNumber( current ); - if ( num === 8 && sessionStorage.getItem( 'hcapOnbAutoSetup' ) === '1' ) { + let autoSetupCompleted = false; + + try { + autoSetupCompleted = num === 9 && sessionStorage.getItem( 'hcapOnbAutoSetup' ) === '1'; + + if ( autoSetupCompleted ) { + sessionStorage.removeItem( 'hcapOnbAutoSetup' ); + } + } catch { + // no-op + } + + if ( autoSetupCompleted ) { postUpdate( 'completed' ).always( function() { buildCongratsModal(); } ); } - // If we just saved on the last General step, redirect to Integrations + // Redirect after saving General or Anti-Spam settings. try { - if ( cfg.page === 'general' && num === 7 ) { + if ( cfg.page === 'general' && num === 6 ) { + if ( window.sessionStorage && sessionStorage.getItem( 'hcapOnbGoAntiSpam' ) === '1' ) { + sessionStorage.removeItem( 'hcapOnbGoAntiSpam' ); + setLocationHref( cfg.antispamUrl ); + } + } else if ( cfg.page === 'antispam' && num === 8 ) { if ( window.sessionStorage && sessionStorage.getItem( 'hcapOnbGoIntegrations' ) === '1' ) { sessionStorage.removeItem( 'hcapOnbGoIntegrations' ); setLocationHref( cfg.integrationsUrl ); diff --git a/changelog.txt b/changelog.txt index 1c0eb6367..e7570efcf 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,3 +1,39 @@ += 5.5.0 = +* Added compatibility with Contact Form 7 6.2.0. +* Added support for Icegram Express Max. +* Added safe entry data processing across supported integrations, including native form payloads and email addresses. +* Protected configured content in WordPress REST post, page, collection, and search responses. +* Required hCaptcha for native WordPress REST comment creation. +* Blocked REST password attempts that bypassed the protected post and page password form. +* Extended signed hCaptcha widget ID verification to integrations and form paths that previously skipped it. +* Preserved WPForms spam checks and submission-time validation when hCaptcha replaces its native CAPTCHA. +* Preserved the visible hCaptcha widget in Essential Addons registration after its form markup is sanitized. +* Kept wpDiscuz comment reCAPTCHA active when hCaptcha protects subscriptions only. +* Avoided duplicate CAPTCHA challenges on Wordfence-protected WordPress registration forms. +* Simplified the settings screen with keys and setup guidance first, an optional setup wizard, and an Advanced tab for less common options. +* Recovered form submissions on long-open pages by refreshing expired timing tokens and retrying token requests with a fresh nonce. +* Removed the Show Anti-Spam Indicators setting and indicators from the Integrations page, because all integrations now use the Anti-Spam protection. +* Fixed error responses for rejected hCaptcha checks in WooCommerce Store API checkout. +* Fixed Easy Digital Downloads checkout to show hCaptcha errors in its standard notices. +* Fixed content protection on sites using plain permalinks. +* Fixed adaptive hCaptcha after failed login attempts in Fluent Forms, Simple Membership, Ultimate Member, Beaver Builder, and Ultimate Addons. +* Fixed rendering and validation of existing Ninja Forms hCaptcha fields alongside the plugin's own field. +* Fixed hCaptcha rendering in Brevo signup widgets. +* Fixed hCaptcha rendering in Formidable Forms when the CAPTCHA field label is set to "None". +* Fixed Kadence form CAPTCHA settings changing when saving content. +* Fixed adaptive hCaptcha on Theme My Login AJAX login forms. +* Fixed multisite settings being saved to the wrong scope during background updates. +* Fixed missing Events entries for requests with long User-Agent values. +* Fixed content protection URL patterns and preserved regular expressions in settings. +* Fixed Automatic Verification on forms with nonstandard action URLs. +* Fixed hCaptcha disappearing from ACF Extended forms after page load. +* Fixed "Token replayed or expired" errors during ACF Extended form submissions. +* Fixed "Signature mismatch" errors when guests submit custom Auto-Verification forms with Form Submit Time enabled. +* Fixed a fatal error when rendering the "Theme My Login" login form. +* Fixed form submission while a Form Submit Time token is loading and added retryable connection error messages. +* Fixed automatic verification rejecting forms with nested or array input names. +* Fixed Simple Download Monitor downloads with WordPress script debugging (`SCRIPT_DEBUG`) enabled by loading its source script as a module. + = 5.4.1 = * Fixed WordPress login authentication when login integrations have different protection settings. * Improved Auto-Verification compatibility with forms on query-based page URLs and Brevo forms, while simplifying form registration storage. diff --git a/codeception.yml b/codeception.yml index 0a71e7788..1b1d679d6 100644 --- a/codeception.yml +++ b/codeception.yml @@ -20,6 +20,3 @@ coverage: low_limit: 35 high_limit: 90 show_only_summary: true - include: - - ./src/php/* - - ./hcaptcha.php diff --git a/composer.json b/composer.json index d5c515497..0bfb95097 100644 --- a/composer.json +++ b/composer.json @@ -72,8 +72,17 @@ "scripts": { "pre-autoload-dump": "HCaptcha\\Scoper\\Scoper::pre_autoload_dump", "post-cmd": "HCaptcha\\Scoper\\Scoper::post_cmd", - "post-install-cmd": "@post-cmd", - "post-update-cmd": "@post-cmd", + "post-install-cmd": [ + "@post-cmd", + "@hooks:install" + ], + "post-update-cmd": [ + "@post-cmd", + "@hooks:install" + ], + "hooks:install": "@php .githooks/setup.php", + "changelog": "@php .github/scripts/update-changelog.php", + "changelog:check": "@php .github/scripts/update-changelog.php --check", "phpcs": "vendor/bin/phpcs --colors --standard=phpcs.xml", "integration": "codecept run integration -c codeception.yml", "integration:multisite": "codecept run multisite -c codeception.yml", diff --git a/hcaptcha.php b/hcaptcha.php index 7801713c4..fd281f471 100644 --- a/hcaptcha.php +++ b/hcaptcha.php @@ -10,7 +10,7 @@ * Plugin Name: hCaptcha for WP * Plugin URI: https://www.hcaptcha.com/ * Description: hCaptcha keeps out bots and spam while putting privacy first. It is a drop-in replacement for reCAPTCHA. - * Version: 5.4.1 + * Version: 5.5.0 * Requires at least: 6.0 * Requires PHP: 7.4 * Author: hCaptcha @@ -39,7 +39,7 @@ /** * Plugin version. */ -const HCAPTCHA_VERSION = '5.4.1'; +const HCAPTCHA_VERSION = '5.5.0'; /** * Path to the plugin dir. diff --git a/readme.txt b/readme.txt index 15f6955dd..a7bb4ce1a 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Tags: captcha, hcaptcha, recaptcha, antispam, spam Requires at least: 6.0 Tested up to: 7.1 Requires PHP: 7.4 -Stable tag: 5.4.1 +Stable tag: 5.5.0 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html @@ -15,6 +15,8 @@ Works with 60+ integrations: Contact Form 7, Elementor, WooCommerce, Divi, etc. The strongest CAPTCHA. Switch from reCAPTCHA and Turnstile for free. +**Unique REST API protection:** In our October 2026 review of the 10 most-installed WordPress.org plugins tagged `captcha`, none offered this combination: hCaptcha protects selected content in WordPress REST post, page, collection, and search responses; requires hCaptcha for native REST comments; and blocks REST post-password attempts. Each safeguard applies when its corresponding protection is enabled. + A built-in Migration Wizard helps you move from Google reCAPTCHA or Cloudflare Turnstile to hCaptcha in just a few clicks. [hCaptcha](https://www.hcaptcha.com/) is a drop-in replacement for reCAPTCHA that puts user privacy first. @@ -41,6 +43,7 @@ hCaptcha for WP [makes security easy](https://www.hcaptcha.com/integration-hcapt * **Pro and Enterprise:** Supports Pro and Enterprise versions of hCaptcha. * **No Challenge Modes:** 99.9% passive and passive modes in Pro and Enterprise versions reduce user friction. * **Protect Site Content:** Protects selected site URLs from bots with hCaptcha. Works best with Pro 99.9% passive mode. +* **REST API Protection:** Keeps protected posts and pages out of WordPress REST responses and search, verifies native REST comments, and blocks REST post-password attempts when the corresponding protections are enabled. * **Logged-in Users:** Optionally turn off hCaptcha for logged-in users. * **Delayed API Loading:** Load the hCaptcha API instantly or on user interaction for zero page loading impact. * **IP Access Control:** Allowlist trusted IPs to skip hCaptcha and denylist abusive IPs to block form submissions. @@ -351,6 +354,12 @@ if ( null !== $result ) { } ` += How to honor per-form protection exemptions in custom handlers = + +Custom verification helpers always require a valid CAPTCHA response unless the server supplies the expected form identity. To honor a per-form `hcap_protect_form` exemption, pass the same server-selected `source` and `form_id` used to render the widget: `API::verify_post( $nonce_name, $nonce_action, $expected_id )`, `API::verify_post_html( $nonce_name, $nonce_action, $expected_id )`, or `API::verify_post_data( $nonce_name, $nonce_action, $post_data, $expected_id )`. For `API::verify_request()` and `API::verify()`, use the entry's `expected_id` key. Derive that identity from the native form being processed, independently of the submitted `hcaptcha-widget-id`. + +When a handler cannot identify the submitted form independently, set `mandatory` to `true` in the arguments passed to `HCaptcha::form()` or `HCaptcha::form_display()`. This keeps the required challenge and nonce visible even when a per-form exemption is configured. Asgaros, Passster, and PayPal order creation use this mode; PayPal also requires the checkout widget it shares. Icegram's generic form without a native form ID requires the challenge too. Other forms with a matching server-selected identity retain their per-form exemptions. + = How to automatically verify an arbitrary form = Arbitrary user forms can be verified easily. Just add `auto="true"` or `auto="1"` to the shortcode: @@ -515,8 +524,8 @@ Events Manager `$source: 'events-manager/events-manager.php'` `$form_id: event_id` -Icegram Express -`$source: 'email-subscribers/email-subscribers.php'` +Icegram Express (including Max) +`$source: [ 'email-subscribers-premium/email-subscribers-premium.php', 'email-subscribers/email-subscribers.php' ]` `$form_id: form_id` Customer Reviews for WooCommerce @@ -940,6 +949,8 @@ With the default configuration, this plugin does not: * send any data to external servers; * use cookies. +If you enable CAPTCHA protection for native WordPress password-protected posts, the plugin sets a first-party `hcaptcha_postpass_` cookie after successful verification. It contains signed proof of the password scope without the password itself and follows the native post-password cookie lifetime, including session cookies. Existing post-password cookies without this proof require another password-form submission with CAPTCHA. REST password attempts are rejected while this protection is enabled; editor authorization remains available. + Once you activate this plugin, the hCaptcha-answering user's IP address and browser data may be sent to the hCaptcha service on pages where you have activated hCaptcha protection. However, hCaptcha is designed to minimize data used, process it very close to the user, and rapidly discard it after analysis. For more details, please see the hCaptcha privacy policy at: @@ -1053,6 +1064,42 @@ Instructions for popular native integrations are below: == Changelog == += 5.5.0 = +* Added compatibility with Contact Form 7 6.2.0. +* Added support for Icegram Express Max. +* Added safe entry data processing across supported integrations, including native form payloads and email addresses. +* Protected configured content in WordPress REST post, page, collection, and search responses. +* Required hCaptcha for native WordPress REST comment creation. +* Blocked REST password attempts that bypassed the protected post and page password form. +* Extended signed hCaptcha widget ID verification to integrations and form paths that previously skipped it. +* Preserved WPForms spam checks and submission-time validation when hCaptcha replaces its native CAPTCHA. +* Preserved the visible hCaptcha widget in Essential Addons registration after its form markup is sanitized. +* Kept wpDiscuz comment reCAPTCHA active when hCaptcha protects subscriptions only. +* Avoided duplicate CAPTCHA challenges on Wordfence-protected WordPress registration forms. +* Simplified the settings screen with keys and setup guidance first, an optional setup wizard, and an Advanced tab for less common options. +* Recovered form submissions on long-open pages by refreshing expired timing tokens and retrying token requests with a fresh nonce. +* Removed the Show Anti-Spam Indicators setting and indicators from the Integrations page, because all integrations now use the Anti-Spam protection. +* Fixed error responses for rejected hCaptcha checks in WooCommerce Store API checkout. +* Fixed Easy Digital Downloads checkout to show hCaptcha errors in its standard notices. +* Fixed content protection on sites using plain permalinks. +* Fixed adaptive hCaptcha after failed login attempts in Fluent Forms, Simple Membership, Ultimate Member, Beaver Builder, and Ultimate Addons. +* Fixed rendering and validation of existing Ninja Forms hCaptcha fields alongside the plugin's own field. +* Fixed hCaptcha rendering in Brevo signup widgets. +* Fixed hCaptcha rendering in Formidable Forms when the CAPTCHA field label is set to "None". +* Fixed Kadence form CAPTCHA settings changing when saving content. +* Fixed adaptive hCaptcha on Theme My Login AJAX login forms. +* Fixed multisite settings being saved to the wrong scope during background updates. +* Fixed missing Events entries for requests with long User-Agent values. +* Fixed content protection URL patterns and preserved regular expressions in settings. +* Fixed Automatic Verification on forms with nonstandard action URLs. +* Fixed hCaptcha disappearing from ACF Extended forms after page load. +* Fixed "Token replayed or expired" errors during ACF Extended form submissions. +* Fixed "Signature mismatch" errors when guests submit custom Auto-Verification forms with Form Submit Time enabled. +* Fixed a fatal error when rendering the "Theme My Login" login form. +* Fixed form submission while a Form Submit Time token is loading and added retryable connection error messages. +* Fixed automatic verification rejecting forms with nested or array input names. +* Fixed Simple Download Monitor downloads with WordPress script debugging (`SCRIPT_DEBUG`) enabled by loading its source script as a module. + = 5.4.1 = * Fixed WordPress login authentication when login integrations have different protection settings. * Improved Auto-Verification compatibility with forms on query-based page URLs and Brevo forms, while simplifying form registration storage. diff --git a/src/js/hcaptcha/hcaptcha.js b/src/js/hcaptcha/hcaptcha.js index 7796beefc..b95f111ee 100644 --- a/src/js/hcaptcha/hcaptcha.js +++ b/src/js/hcaptcha/hcaptcha.js @@ -734,7 +734,27 @@ class HCaptcha { return; } - const { formElement, submitButtonElement } = this.currentForm; + const currentForm = this.currentForm; + const { formElement, submitButtonElement } = currentForm; + + if ( window.hCaptchaFST && formElement.querySelector( '[name="hcap_fst_token"]' ) ) { + return window.hCaptchaFST.runWhenReady( + formElement, + () => this.submitForm( currentForm ), + submitButtonElement, + ); + } + + this.submitForm( currentForm ); + } + + /** + * Resume submission with the form selected before waiting for its timing token. + * + * @param {Object} currentForm Form being submitted. + */ + submitForm( currentForm ) { + const { formElement, submitButtonElement } = currentForm; if ( 'form' !== formElement.tagName.toLowerCase() || diff --git a/src/php/ACFE/Form.php b/src/php/ACFE/Form.php index 60378a753..7903377eb 100644 --- a/src/php/ACFE/Form.php +++ b/src/php/ACFE/Form.php @@ -52,6 +52,13 @@ class Form { */ private bool $captcha_added = false; + /** + * Verification result shared by callbacks in one validation stage. + * + * @var array|null + */ + private ?array $form_validation = null; + /** * Form constructor. */ @@ -66,6 +73,7 @@ public function __construct() { */ public function init_hooks(): void { add_action( 'acfe/form/render/before_fields', [ $this, 'before_fields' ] ); + add_action( 'acfe/form/validate_form', [ $this, 'validate_form' ] ); add_action( self::RENDER_HOOK, [ $this, 'remove_recaptcha_render' ], 8 ); add_action( self::RENDER_HOOK, [ $this, 'add_hcaptcha' ], 11 ); add_filter( self::VALIDATION_HOOK, [ $this, 'remove_recaptcha_verify' ], 9, 4 ); @@ -153,6 +161,33 @@ public function remove_recaptcha_verify( $valid, string $value, array $field, st return $valid; } + /** + * Verify forms with a required CAPTCHA even when its field is omitted from POST. + * + * @param array $form Registered ACFE form. + * + * @return void + * @noinspection PhpUndefinedFunctionInspection + */ + public function validate_form( array $form ): void { + if ( ! $this->has_required_recaptcha( $form ) ) { + return; + } + + $this->form_validation = null; + $result = $this->verify( true, '', [ 'required' => true ], '' ); + $this->form_validation = [ + 'form_id' => (int) ( $form['ID'] ?? 0 ), + 'submission' => $this->get_transient_name( wp_unslash( $_POST ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- ACFE verifies its form nonce before this hook. + 'result' => $result, + 'ajax' => wp_doing_ajax(), + ]; + + if ( true !== $result ) { + acf_add_validation_error( '', $result ); + } + } + /** * Verify request. * @@ -169,14 +204,53 @@ public function verify( $valid, string $value, array $field, string $input ) { return $valid; } - if ( is_admin() ) { + $form = $this->get_form(); + + if ( is_admin() && ( ! wp_doing_ajax() || ! $form ) ) { // In admin, the recaptcha field is required and $valid set to false in the acf_validate_value(). // So, we fix it. return true; } - $form = $this->get_form(); - $this->form_id = $form['ID'] ?? 0; + $this->form_id = (int) ( $form['ID'] ?? 0 ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $post_data = wp_unslash( $_POST ); + + if ( + null !== $this->form_validation && + $this->form_id === $this->form_validation['form_id'] && + $this->get_transient_name( $post_data ) === $this->form_validation['submission'] && + wp_doing_ajax() === $this->form_validation['ajax'] + ) { + return $this->form_validation['result']; + } + + $result = $this->verify_submission( $post_data ); + + if ( wp_doing_ajax() ) { + // API::verify() clears the consumed proof from POST; bind the in-request result to that state. + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $validated_data = wp_unslash( $_POST ); + $this->form_validation = [ + 'form_id' => $this->form_id, + 'submission' => $this->get_transient_name( $validated_data ), + 'result' => $result, + 'ajax' => true, + ]; + } + + return $result; + } + + /** + * Verify the current ACFE submission across its AJAX and final POST stages. + * + * @param array $post_data Unslashed POST data. + * + * @return bool|string + */ + private function verify_submission( array $post_data ) { + $transient_name = $this->get_transient_name( $post_data ); // ACFE uses a two-step submission flow: AJAX field validation first, then a direct POST submission. // The token/honeypot can only be verified once, @@ -184,18 +258,16 @@ public function verify( $valid, string $value, array $field, string $input ) { // On the subsequent direct POST, we retrieve the cached result instead of verifying again // (which would fail on a consumed token). if ( wp_doing_ajax() ) { - // phpcs:ignore WordPress.Security.NonceVerification.Missing - $post_data = wp_unslash( $_POST ); - $result = API::verify( $this->get_entry( $post_data ) ) ?: true; + $result = API::verify( $this->get_entry( $post_data ) ) ?: true; - set_transient( self::TRANSIENT, [ $this->form_id, $result ], 30 ); + set_transient( $transient_name, [ $this->form_id, $result ], 30 ); return $result; } - $transient = get_transient( self::TRANSIENT ); + $transient = get_transient( $transient_name ); - delete_transient( self::TRANSIENT ); + delete_transient( $transient_name ); $form_id = $transient[0] ?? false; $result = $transient[1] ?? false; @@ -206,12 +278,27 @@ public function verify( $valid, string $value, array $field, string $input ) { // Some ACFE forms submit directly without the AJAX validation step. // In that case, verify the current POST once instead of requiring a transient. - // phpcs:ignore WordPress.Security.NonceVerification.Missing - $post_data = wp_unslash( $_POST ); - return API::verify( $this->get_entry( $post_data ) ) ?: true; } + /** + * Bind the cached validation result to the same tokens and submitted answers. + * + * @param array $post_data Post data. + * + * @return string + */ + private function get_transient_name( array $post_data ): string { + $submission = [ + $this->form_id, + $post_data['h-captcha-response'] ?? '', + $post_data['hcap_fst_token'] ?? '', + $post_data['acf'] ?? [], + ]; + + return self::TRANSIENT . '_' . hash( 'sha256', wp_json_encode( $submission ) ); + } + /** * Get entry. * @@ -374,6 +461,40 @@ private function get_form() { return $form ?: false; } + /** + * Find required CAPTCHA fields from the form's registered field groups. + * + * @param array $form Registered ACFE form. + * + * @return bool + * @noinspection PhpUndefinedFunctionInspection + */ + private function has_required_recaptcha( array $form ): bool { + $field_groups = acfe_as_array( $form['field_groups'] ?? [] ); + + if ( ! empty( $form['post_field_groups'] ) ) { + $field_groups = wp_list_pluck( acf_get_field_groups( [ 'post_id' => $form['post_field_groups'] ] ), 'key' ); + } + + foreach ( $field_groups as $group_key ) { + $fields = acf_get_fields( $group_key ); + + if ( ! $fields ) { + continue; + } + + foreach ( acfe_get_fields_details_recursive( $fields ) as $details ) { + $field = $details['field']; + + if ( $this->is_recaptcha( $field ) && ! empty( $field['required'] ) ) { + return true; + } + } + } + + return false; + } + /** * Enqueue scripts. * diff --git a/src/php/Abilities/Abilities.php b/src/php/Abilities/Abilities.php index 1790e225a..87861de90 100644 --- a/src/php/Abilities/Abilities.php +++ b/src/php/Abilities/Abilities.php @@ -60,6 +60,11 @@ class Abilities { */ private const ABILITY_IMPORT_SETTINGS = 'hcaptcha/import-settings'; + /** + * Maximum number of bytes read from an imported settings file. + */ + private const MAX_IMPORT_FILE_BYTES = 1024 * 1024; + /** * Maximum number of top offenders to return in a threat snapshot. */ @@ -636,25 +641,11 @@ public function import_settings( $input ) { unset( $payload['allow_keys'], $payload['dry_run'], $payload['input_file'] ); if ( '' !== $input_file ) { - if ( ! file_exists( $input_file ) || ! is_readable( $input_file ) ) { - return new WP_Error( - 'hcaptcha_invalid_payload', - __( 'Input file not found or unreadable.', 'hcaptcha-for-forms-and-more' ) - ); - } - - // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents - $json = file_get_contents( $input_file ); - $data = Utils::json_decode_arr( $json ); + $payload = $this->read_import_file( $input_file ); - if ( ! $data || JSON_ERROR_NONE !== json_last_error() ) { - return new WP_Error( - 'hcaptcha_invalid_payload', - __( 'Invalid JSON in input file.', 'hcaptcha-for-forms-and-more' ) - ); + if ( is_wp_error( $payload ) ) { + return $payload; } - - $payload = $data; } if ( ! is_array( $payload ) || empty( $payload ) ) { @@ -705,6 +696,52 @@ public function import_settings( $input ) { ]; } + /** + * Read a regular settings file within the import size limit. + * + * @param string|false $input_file Canonical file path or failed resolution. + * + * @return array|WP_Error + */ + private function read_import_file( $input_file ) { + if ( ! is_string( $input_file ) || ! is_file( $input_file ) || ! is_readable( $input_file ) ) { + return new WP_Error( + 'hcaptcha_invalid_payload', + __( 'Input file not found or unreadable.', 'hcaptcha-for-forms-and-more' ) + ); + } + + $file_size = filesize( $input_file ); + + if ( false === $file_size || self::MAX_IMPORT_FILE_BYTES < $file_size ) { + return new WP_Error( + 'hcaptcha_invalid_payload', + __( 'Input file is too large.', 'hcaptcha-for-forms-and-more' ) + ); + } + + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents + $json = file_get_contents( $input_file, false, null, 0, self::MAX_IMPORT_FILE_BYTES + 1 ); + + if ( false === $json || self::MAX_IMPORT_FILE_BYTES < strlen( $json ) ) { + return new WP_Error( + 'hcaptcha_invalid_payload', + __( 'Input file is too large or cannot be read.', 'hcaptcha-for-forms-and-more' ) + ); + } + + $data = Utils::json_decode_arr( $json ); + + if ( ! $data || JSON_ERROR_NONE !== json_last_error() ) { + return new WP_Error( + 'hcaptcha_invalid_payload', + __( 'Invalid JSON in input file.', 'hcaptcha-for-forms-and-more' ) + ); + } + + return $data; + } + /** * Convert a window string (e.g., 5m) to seconds. * @@ -1299,13 +1336,8 @@ private function get_offender_blocks(): array { $raw = get_option( self::OPTION_OFFENDER_BLOCKS, [] ); $raw = is_array( $raw ) ? $raw : []; - $blocks = $this->prune_offender_blocks( $raw, time() ); - - if ( $blocks !== $raw ) { - $this->set_offender_blocks( $blocks ); - } - - return $blocks; + // Public lookups must not overwrite bans added after this snapshot was read. + return $this->prune_offender_blocks( $raw, time() ); } /** diff --git a/src/php/Abstracts/CommentBase.php b/src/php/Abstracts/CommentBase.php index 4ce3d161d..21261a330 100644 --- a/src/php/Abstracts/CommentBase.php +++ b/src/php/Abstracts/CommentBase.php @@ -12,6 +12,7 @@ use HCaptcha\Helpers\HCaptcha; use HCaptcha\Helpers\Request; use WP_Error; +use WP_REST_Request; /** * Class CommentBase @@ -56,6 +57,61 @@ protected function init_hooks(): void { add_filter( 'pre_comment_approved', [ $this, 'pre_comment_approved' ], 20, 2 ); } + /** + * Verify a native REST comment before WordPress processes approval. + * + * @param array|WP_Error $prepared_comment Prepared comment or an earlier error. + * @param WP_REST_Request $request REST request. + * + * @return array|WP_Error + */ + public function verify_rest_comment( $prepared_comment, WP_REST_Request $request ) { + if ( + ! $request->is_method( 'POST' ) || + '/wp/v2/comments' !== strtolower( $request->get_route() ) || + 'note' === $request['type'] || + is_wp_error( $prepared_comment ) + ) { + return $prepared_comment; + } + + $comment_data = wp_parse_args( + (array) $prepared_comment, + [ + 'comment_author' => '', + 'comment_author_email' => '', + 'comment_author_url' => '', + 'comment_content' => '', + 'comment_author_IP' => '', + 'comment_agent' => '', + ] + ); + $this->form_id = (int) ( $comment_data['comment_post_ID'] ?? 0 ); + $comment_data['comment_author_IP'] = hcap_get_user_ip(); + $entry = $this->get_entry( $comment_data ); + $entry['post_data'] = $request->get_params(); + $entry['nonce_name'] = static::NONCE; + $entry['nonce_action'] = static::ACTION; + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Restore unrelated POST data after checking this REST request. + $original_post = $_POST; + + // REST proof must come from this request, not from an outer form or batch request. + $_POST = []; + + try { + $this->result = API::verify( $entry ); + } finally { + $_POST = $original_post; + } + + if ( null !== $this->result ) { + return new WP_Error( 'invalid_hcaptcha', (string) $this->result, [ 'status' => 400 ] ); + } + + return $prepared_comment; + } + /** * Get signature. * @@ -84,8 +140,10 @@ public function display_signature(): void { public function verify( $comment_data ): array { $comment_data = (array) $comment_data; - if ( ! Request::is_frontend() ) { - // Do not work in ajax mode. It is served by WPDiscuz. + if ( ! Request::is_frontend() && ! $this->is_native_comment_submission() ) { + // Skip other transports; WPDiscuz handles its own AJAX comment submissions. + $this->result = null; + return $comment_data; } @@ -117,6 +175,28 @@ public function verify( $comment_data ): array { return $comment_data; } + /** + * Whether WordPress itself is handling the submitted comment. + * + * WooCommerce may define DOING_AJAX from a query argument even when the + * request is still handled by the core comment submission script. + * + * @return bool + */ + private function is_native_comment_submission(): bool { + // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Server-provided filesystem path must retain its separators. + $script = $_SERVER['SCRIPT_FILENAME'] ?? ''; + + if ( ! is_string( $script ) || '' === $script ) { + return false; + } + + $core_script = realpath( ABSPATH . 'wp-comments-post.php' ); + $request_script = realpath( $script ); + + return false !== $core_script && $core_script === $request_script; + } + /** * Pre-approve comment. * diff --git a/src/php/Abstracts/FormOwnerBase.php b/src/php/Abstracts/FormOwnerBase.php index 126ddaf23..12648812b 100644 --- a/src/php/Abstracts/FormOwnerBase.php +++ b/src/php/Abstracts/FormOwnerBase.php @@ -51,7 +51,7 @@ public function claim_request_owner( $owner, array $id ) { return $owner; } - return $this->get_expected_id() === $id ? static::class : $owner; + return $this->get_expected_id() === $id && $this->can_handle_request() ? static::class : $owner; } /** @@ -105,6 +105,15 @@ protected function get_request_ownership(): ?bool { return static::class === $owner; } + /** + * Whether this verifier can handle the submitted form. + * + * @return bool + */ + protected function can_handle_request(): bool { + return true; + } + /** * Whether the current request has the expected WordPress login action. * diff --git a/src/php/Abstracts/LoginBase.php b/src/php/Abstracts/LoginBase.php index 8441f9449..86f1bc410 100644 --- a/src/php/Abstracts/LoginBase.php +++ b/src/php/Abstracts/LoginBase.php @@ -113,19 +113,28 @@ public function __construct() { */ protected function init_hooks(): void { add_action( 'hcap_signature', [ $this, 'display_signature' ] ); - add_action( 'login_form', [ $this, 'display_signature' ], PHP_INT_MAX ); + add_action( 'login_form', [ $this, 'display_signature' ], PHP_INT_MAX, 0 ); add_filter( 'login_form_middle', [ $this, 'add_signature' ], PHP_INT_MAX, 2 ); add_filter( 'wp_authenticate_user', [ $this, 'check_signature' ], PHP_INT_MAX, 2 ); add_filter( 'authenticate', [ $this, 'hide_login_error' ], 100, 3 ); add_filter( 'hcap_auto_verify_unmatched_form', [ $this, 'defer_auto_verification' ], 10, 3 ); add_filter( 'hcap_wp_login_can_skip_verification', [ $this, 'allow_wp_login_skip_verification' ] ); - add_action( 'wp_login', [ $this, 'login' ], 10, 2 ); - add_action( 'wp_login_failed', [ $this, 'login_failed' ] ); + $this->init_login_attempt_hooks(); add_action( 'hcap_delay_api', [ $this, 'delay_api' ], 0 ); } + /** + * Register adaptive login counters for integrations with custom hooks. + * + * @return void + */ + protected function init_login_attempt_hooks(): void { + add_action( 'wp_login', [ $this, 'login' ], 10, 2 ); + add_action( 'wp_login_failed', [ $this, 'login_failed' ] ); + } + /** * Display signature. * @@ -391,6 +400,11 @@ public function login( string $user_login, WP_User $user ): void { * @noinspection PhpMissingParamTypeInspection */ public function login_failed( string $username, $error = null ): void { + // Simple Membership may call wp_signon after its own successful login. + if ( doing_action( 'wp_login_failed' ) && doing_action( 'swpm_after_login_authentication' ) ) { + return; + } + if ( doing_action( 'wp_login_failed' ) ) { $action_count = did_action( 'wp_login_failed' ); diff --git a/src/php/Abstracts/LostPasswordBase.php b/src/php/Abstracts/LostPasswordBase.php index af36646ab..f06931a91 100644 --- a/src/php/Abstracts/LostPasswordBase.php +++ b/src/php/Abstracts/LostPasswordBase.php @@ -11,6 +11,7 @@ use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; use WP_Error; +use WP_User; /** * Class LostPasswordBase @@ -39,7 +40,7 @@ protected function init_hooks(): void { $this->init_auto_verify_hooks(); add_action( static::ADD_CAPTCHA_ACTION, [ $this, 'add_captcha' ] ); - add_action( 'lostpassword_post', [ $this, 'verify' ] ); + add_action( 'lostpassword_post', [ $this, 'verify' ], 10, 2 ); } /** @@ -60,11 +61,12 @@ public function add_captcha(): void { /** * Verify a lost password form. * - * @param WP_Error|mixed $errors Error. + * @param WP_Error|mixed $errors Error. + * @param WP_User|false|null $user Native resolved recovery recipient. * * @return void */ - public function verify( $errors ): void { + public function verify( $errors, $user = null ): void { if ( ! $this->can_handle_request() ) { // This class cannot handle a submitted lost password form. return; @@ -82,18 +84,17 @@ public function verify( $errors ): void { return; } - $error_message = API::verify( - [ - 'nonce_name' => static::NONCE, - 'nonce_action' => static::ACTION, - 'data' => EntryData::from_post( - [ - 'username' => [ 'user_login', 'user_email' ], - ] - ), - 'expected_id' => $this->get_expected_id(), - ] - ); + $entry = [ + 'nonce_name' => static::NONCE, + 'nonce_action' => static::ACTION, + 'data' => EntryData::from_post( + [ + 'username' => [ 'user_login', 'user_email' ], + ] + ), + 'expected_id' => $this->get_expected_id(), + ]; + $error_message = API::verify( EntryData::with_emails( $entry, $user instanceof WP_User ? [ $user->user_email ] : [] ) ); HCaptcha::add_error_message( $errors, $error_message ); } @@ -116,7 +117,16 @@ protected function get_expected_id(): array { * @return bool */ protected function is_owner_action(): bool { - return $this->is_wp_login_action( 'lostpassword' ) && $this->can_handle_request(); + return $this->is_lost_password_action() && $this->can_handle_request(); + } + + /** + * Whether the current request uses a native WordPress recovery action. + * + * @return bool + */ + protected function is_lost_password_action(): bool { + return $this->is_wp_login_action( 'lostpassword' ) || $this->is_wp_login_action( 'retrievepassword' ); } /** @@ -124,7 +134,7 @@ protected function is_owner_action(): bool { * * @return bool */ - private function can_handle_request(): bool { + protected function can_handle_request(): bool { // Nonce is verified later by the owning form integration. // phpcs:disable WordPress.Security.NonceVerification.Missing $post_value = isset( $_POST[ static::POST_KEY ] ) ? diff --git a/src/php/Abstracts/RegisterBase.php b/src/php/Abstracts/RegisterBase.php index d14815e63..89044a2e6 100644 --- a/src/php/Abstracts/RegisterBase.php +++ b/src/php/Abstracts/RegisterBase.php @@ -33,6 +33,6 @@ protected function init_hooks(): void { * @return bool */ protected function is_owner_action(): bool { - return $this->is_wp_login_action( 'register' ); + return $this->is_wp_login_action( 'register' ) && $this->can_handle_request(); } } diff --git a/src/php/Admin/Events/Events.php b/src/php/Admin/Events/Events.php index 4a35ba34f..4d197f875 100644 --- a/src/php/Admin/Events/Events.php +++ b/src/php/Admin/Events/Events.php @@ -12,7 +12,7 @@ use HCaptcha\Helpers\HCaptcha; use HCaptcha\Migrations\Migrations; use HCaptcha\Settings\General; -use HCaptcha\Settings\PluginSettingsBase; +use HCaptcha\Settings\SettingsStorage; use Throwable; /** @@ -95,11 +95,11 @@ class Events { ]; /** - * Saved flag. + * Whether this request has already attempted event collection. * * @var bool */ - private bool $saved = false; + private bool $save_attempted = false; /** * Class constructor. @@ -140,11 +140,11 @@ private function init_hooks(): void { public function save_event( $result, array $deprecated, object $error_info ) { global $wpdb; - if ( $this->saved ) { + if ( $this->save_attempted ) { return $result; } - $this->saved = true; + $this->save_attempted = true; if ( ! ( is_string( $result ) || is_null( $result ) ) ) { return $result; @@ -162,9 +162,9 @@ public function save_event( $result, array $deprecated, object $error_info ) { return $result; } - $event = self::prepare_event( $event_id, $error_info, $settings ); - try { + $event = self::prepare_event( $event_id, $error_info, $settings ); + if ( ! self::acquire_write_lock() ) { return $result; } @@ -177,7 +177,9 @@ public function save_event( $result, array $deprecated, object $error_info ) { } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery - $wpdb->insert( $wpdb->prefix . self::TABLE_NAME, $event ); + if ( false === $wpdb->insert( $wpdb->prefix . self::TABLE_NAME, $event ) ) { + return $result; + } } finally { self::release_write_lock(); } @@ -199,6 +201,8 @@ public function save_event( $result, array $deprecated, object $error_info ) { * @return array */ private static function prepare_event( array $event_id, object $error_info, object $settings ): array { + global $wpdb; + $ip = ''; $user_agent = ''; @@ -209,6 +213,10 @@ private static function prepare_event( array $event_id, object $error_info, obje if ( $settings->is_on( 'anonymous' ) ) { $user_agent = wp_hash( $user_agent ); } + + // Normalize after hashing, using the actual column's charset and character limit. + $user_agent = $wpdb->strip_invalid_text_for_column( $wpdb->prefix . self::TABLE_NAME, 'user_agent', $user_agent ); + $user_agent = is_wp_error( $user_agent ) ? '' : $user_agent; } if ( $settings->is_on( 'collect_ip' ) ) { @@ -529,9 +537,8 @@ public static function create_table( bool $force = false ): void { * @return bool */ public static function table_exists(): bool { - $settings = hcaptcha()->settings(); - $raw = $settings ? $settings->get_raw_settings() : get_option( PluginSettingsBase::OPTION_NAME, [] ); - $raw = is_array( $raw ) ? $raw : []; + // The table marker belongs to the current blog's database prefix. + $raw = SettingsStorage::get( false ); return 'on' === ( $raw[ self::TABLE_CREATED_OPTION_NAME ] ?? '' ); } @@ -562,12 +569,7 @@ private static function database_table_exists(): bool { * @return void */ private static function mark_table_created(): void { - $option = get_option( PluginSettingsBase::OPTION_NAME, [] ); - $option = is_array( $option ) ? $option : []; - - $option[ self::TABLE_CREATED_OPTION_NAME ] = 'on'; - - update_option( PluginSettingsBase::OPTION_NAME, $option ); + SettingsStorage::update( [ self::TABLE_CREATED_OPTION_NAME => 'on' ], [], false ); } /** @@ -576,15 +578,13 @@ private static function mark_table_created(): void { * @return void */ private static function unmark_table_created(): void { - $option = get_option( PluginSettingsBase::OPTION_NAME, [] ); + $option = SettingsStorage::get( false ); - if ( ! is_array( $option ) || ! array_key_exists( self::TABLE_CREATED_OPTION_NAME, $option ) ) { + if ( ! array_key_exists( self::TABLE_CREATED_OPTION_NAME, $option ) ) { return; } - unset( $option[ self::TABLE_CREATED_OPTION_NAME ] ); - - update_option( PluginSettingsBase::OPTION_NAME, $option ); + SettingsStorage::update( [], [ self::TABLE_CREATED_OPTION_NAME ], false ); } /** @@ -651,6 +651,7 @@ public static function cleanup_trash(): void { * Whether the Events table has the retention schema. * * @return bool + * @noinspection PhpCastIsUnnecessaryInspection */ public static function is_retention_schema_ready(): bool { global $wpdb; @@ -708,6 +709,7 @@ private static function cleanup_expired_rows(): void { * @param int $days Retention in days. * * @return void + * @noinspection PhpCastIsUnnecessaryInspection */ private static function delete_expired_rows( string $status, string $date_column, string $index, int $days ): void { global $wpdb; @@ -791,7 +793,7 @@ private static function has_capacity(): bool { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $result = $wpdb->query( $wpdb->prepare( - "SELECT id FROM $table_name FORCE INDEX (PRIMARY) ORDER BY id LIMIT %d, 1", + "SELECT id FROM $table_name FORCE INDEX (`PRIMARY`) ORDER BY id LIMIT %d, 1", $max_rows - 1 ) ); diff --git a/src/php/Admin/Notifications.php b/src/php/Admin/Notifications.php index 50fc5e858..b67dc0245 100644 --- a/src/php/Admin/Notifications.php +++ b/src/php/Admin/Notifications.php @@ -85,25 +85,23 @@ protected function get_notifications(): array { $notifications = [ 'register' => [ - 'title' => __( 'Get your hCaptcha site keys', 'hcaptcha-for-forms-and-more' ), - 'message' => sprintf( - /* translators: 1: hCaptcha link, 2: register link. */ - __( 'To use %1$s, please register %2$s to get your site and secret keys.', 'hcaptcha-for-forms-and-more' ), - sprintf( - '%2$s', - $urls['hcaptcha'], - __( 'hCaptcha', 'hcaptcha-for-forms-and-more' ) - ), + 'title' => __( 'Set up hCaptcha', 'hcaptcha-for-forms-and-more' ), + 'message' => sprintf( + /* translators: %s: Link to create an hCaptcha account. */ + __( 'To use the plugin, %s and get your keys. Then select Live mode below and enter your keys.', 'hcaptcha-for-forms-and-more' ), sprintf( - '%2$s', - $urls['register'], - __( 'here', 'hcaptcha-for-forms-and-more' ) + '%2$s', + esc_url( $urls['register'] ), + esc_html__( 'create an hCaptcha account', 'hcaptcha-for-forms-and-more' ) ) ), - 'button' => [ - 'url' => $urls['register'], - 'text' => __( 'Get site keys', 'hcaptcha-for-forms-and-more' ), + 'button' => [ + 'url' => $urls['onboarding'], + 'text' => __( 'Show Setup Wizard', 'hcaptcha-for-forms-and-more' ), + 'target' => '_self', ], + 'notice_type' => 'warning', + 'dismissible' => false, ], 'pro-free-trial' => [ 'title' => __( 'Try Pro for free', 'hcaptcha-for-forms-and-more' ), @@ -373,6 +371,15 @@ protected function get_notifications(): array { 'text' => __( 'Review headers', 'hcaptcha-for-forms-and-more' ), ], ], + // Added in 5.5.0. + 'rest-api-protection' => [ + 'title' => __( 'Unique REST API Protection', 'hcaptcha-for-forms-and-more' ), + 'message' => __( 'hCaptcha now protects selected content in WordPress REST responses and search, verifies native REST comments, and blocks REST post-password attempts when the corresponding protections are enabled. No other plugin in our October 2026 review of the 10 most-installed WordPress.org plugins tagged captcha offered all three.', 'hcaptcha-for-forms-and-more' ), + 'button' => [ + 'url' => $urls['protect_content'], + 'text' => __( 'Configure Content Protection', 'hcaptcha-for-forms-and-more' ), + ], + ], ]; $notifications = $this->select_active_notifications( $notifications ); @@ -422,24 +429,19 @@ private function cf7_admin_notification(): array { /** * Show notifications. * + * @param bool $setup_only Whether to show only the setup notification. + * * @return void */ - public function show(): void { - $notifications = $this->get_notifications(); - - $user = wp_get_current_user(); - $user_id = $user->ID ?? 0; - - // phpcs:ignore Generic.Commenting.DocComment.MissingShort - $dismissed = get_user_meta( $user_id, self::HCAPTCHA_DISMISSED_META_KEY, true ) ?: []; - $notifications = array_diff_key( $notifications, array_flip( $dismissed ) ); + public function show( bool $setup_only = false ): void { + $notifications = $this->get_visible_notifications( $setup_only ); if ( ! $notifications ) { return; } ?> -
    +
    @@ -466,6 +468,9 @@ public function show(): void { $button_url = $notification['button']['url']; $button_text = $notification['button']['text']; $button_lightbox = $notification['button']['lightbox']; + $button_target = $notification['button']['target']; + $notice_type = $notification['notice_type']; + $dismissible = $notification['dismissible']; $lightbox_class = $button_lightbox ? ' hcaptcha-lightbox' : ''; ob_start(); @@ -479,7 +484,7 @@ public function show(): void { + target=""> " // We need the 'inline' class below to prevent moving the 'notice' div after h2 by common.js script in WP Core. ?>
    @@ -523,6 +528,53 @@ class="hcaptcha-notification notice notice-info is-dismissible inline" get_notifications(); + + if ( $setup_only ) { + return array_intersect_key( $notifications, [ 'register' => true ] ); + } + + $user = wp_get_current_user(); + $user_id = $user->ID ?? 0; + + // phpcs:ignore Generic.Commenting.DocComment.MissingShort + $dismissed = get_user_meta( $user_id, self::HCAPTCHA_DISMISSED_META_KEY, true ) ?: []; + + return array_diff_key( $notifications, array_flip( $dismissed ) ); + } + + /** + * Whether the current user has dismissed an active notification. + * + * @return bool + */ + public function has_dismissed_notifications(): bool { + $user = wp_get_current_user(); + $dismissed = get_user_meta( $user->ID ?? 0, self::HCAPTCHA_DISMISSED_META_KEY, true ); + + if ( ! is_array( $dismissed ) || ! $dismissed ) { + return false; + } + + $notifications = $this->get_notifications(); + + foreach ( $dismissed as $id ) { + if ( is_string( $id ) && isset( $notifications[ $id ] ) && ( $notifications[ $id ]['dismissible'] ?? true ) ) { + return true; + } + } + + return false; + } + /** * Enqueue class scripts. * @@ -702,6 +754,9 @@ private function validate_notification( array $notification ): array { $notification['button']['url'] = $notification['button']['url'] ?? ''; $notification['button']['text'] = $notification['button']['text'] ?? ''; $notification['button']['lightbox'] = $notification['button']['lightbox'] ?? ''; + $notification['button']['target'] = $notification['button']['target'] ?? '_blank'; + $notification['notice_type'] = $notification['notice_type'] ?? 'info'; + $notification['dismissible'] = $notification['dismissible'] ?? true; return $notification; } @@ -732,7 +787,7 @@ private function select_active_notifications( array $notifications ): array { } } - if ( ! empty( $settings->get_site_key() ) && ! empty( $settings->get_secret_key() ) ) { + if ( ! empty( $settings->get( 'site_key' ) ) && ! empty( $settings->get( 'secret_key' ) ) ) { unset( $notifications['register'] ); } diff --git a/src/php/Admin/NotificationsBase.php b/src/php/Admin/NotificationsBase.php index 288d35533..0c08c3a44 100644 --- a/src/php/Admin/NotificationsBase.php +++ b/src/php/Admin/NotificationsBase.php @@ -7,6 +7,7 @@ namespace HCaptcha\Admin; +use HCaptcha\Settings\Advanced; use HCaptcha\Settings\AntiSpamPage; use HCaptcha\Settings\EventsPage; use HCaptcha\Settings\FormsPage; @@ -42,60 +43,62 @@ protected function prepare_urls(): array { $utm_sk = $utm . 'sk'; $utm_not = $utm . 'not'; - $urls['general'] = $settings->tab_url( General::class ); - $urls['anti_spam_page'] = $settings->tab_url( AntiSpamPage::class ); - $urls['integrations'] = $settings->tab_url( Integrations::class ); - $urls['forms'] = $settings->tab_url( FormsPage::class ); - $urls['events'] = $settings->tab_url( EventsPage::class ); - $urls['tools'] = $settings->tab_url( Tools::class ); - $urls['hcaptcha'] = 'https://www.hcaptcha.com' . $utm_sk; - $urls['register'] = 'https://www.hcaptcha.com/signup-interstitial' . $utm_sk; - $urls['pro'] = 'https://www.hcaptcha.com/pro' . $utm_not; - $urls['dashboard'] = 'https://dashboard.hcaptcha.com' . $utm_not; - $urls['post_leadership'] = 'https://www.hcaptcha.com/post/hcaptcha-named-a-technology-leader-in-bot-management' . $utm_not; - $urls['rate'] = 'https://wordpress.org/support/plugin/hcaptcha-for-forms-and-more/reviews/#new-post'; - $urls['search_integrations'] = $urls['integrations'] . '#hcaptcha-integrations-search'; - $urls['enterprise_features'] = 'https://www.hcaptcha.com/#enterprise-features' . $utm_not; - $urls['statistics'] = $urls['general'] . '#statistics_1'; - $urls['force'] = $urls['general'] . '#force_1'; - $urls['elementor_edit_form'] = HCAPTCHA_URL . '/assets/images/elementor-edit-form.png'; - $urls['size'] = $urls['general'] . '#size'; - $urls['passive_mode_demo'] = HCAPTCHA_URL . '/assets/images/demo/passive-mode.gif'; - $urls['protect_content'] = $urls['general'] . '#protect_content_1'; - $urls['protect_content_demo'] = HCAPTCHA_URL . '/assets/images/demo/protect-content.gif'; - $urls['antispam'] = $urls['general'] . '#antispam_1'; - $urls['antispam_demo'] = HCAPTCHA_URL . '/assets/images/demo/antispam.gif'; - $urls['token'] = $urls['general'] . '#set_min_submit_time_1'; - $urls['honeypot'] = $urls['general'] . '#honeypot_1'; - $urls['honeypot_demo'] = HCAPTCHA_URL . '/assets/images/demo/honeypot.png'; - $urls['onboarding'] = add_query_arg( + $urls['general'] = $settings->tab_url( General::class ); + $urls['advanced'] = $settings->tab_url( Advanced::class ); + $urls['anti_spam_page'] = $settings->tab_url( AntiSpamPage::class ); + $urls['integrations'] = $settings->tab_url( Integrations::class ); + $urls['forms'] = $settings->tab_url( FormsPage::class ); + $urls['events'] = $settings->tab_url( EventsPage::class ); + $urls['tools'] = $settings->tab_url( Tools::class ); + $urls['hcaptcha'] = 'https://www.hcaptcha.com' . $utm_sk; + $urls['register'] = 'https://www.hcaptcha.com/signup-interstitial' . $utm_sk; + $urls['pro'] = 'https://www.hcaptcha.com/pro' . $utm_not; + $urls['dashboard'] = 'https://dashboard.hcaptcha.com' . $utm_not; + $urls['post_leadership'] = 'https://www.hcaptcha.com/post/hcaptcha-named-a-technology-leader-in-bot-management' . $utm_not; + $urls['rate'] = 'https://wordpress.org/support/plugin/hcaptcha-for-forms-and-more/reviews/#new-post'; + $urls['search_integrations'] = $urls['integrations'] . '#hcaptcha-integrations-search'; + $urls['enterprise_features'] = 'https://www.hcaptcha.com/#enterprise-features' . $utm_not; + $urls['statistics'] = $urls['advanced'] . '#statistics_1'; + $urls['force'] = $urls['general'] . '#force_1'; + $urls['elementor_edit_form'] = HCAPTCHA_URL . '/assets/images/elementor-edit-form.png'; + $urls['size'] = $urls['general'] . '#size'; + $urls['passive_mode_demo'] = HCAPTCHA_URL . '/assets/images/demo/passive-mode.gif'; + $urls['protect_content'] = $urls['advanced'] . '#protect_content_1'; + $urls['protect_content_demo'] = HCAPTCHA_URL . '/assets/images/demo/protect-content.gif'; + $urls['antispam'] = $urls['general'] . '#antispam_1'; + $urls['antispam_demo'] = HCAPTCHA_URL . '/assets/images/demo/antispam.gif'; + $urls['token'] = $urls['general'] . '#set_min_submit_time_1'; + $urls['honeypot'] = $urls['general'] . '#honeypot_1'; + $urls['honeypot_demo'] = HCAPTCHA_URL . '/assets/images/demo/honeypot.png'; + $urls['onboarding'] = add_query_arg( [ OnboardingWizard::STEP_PARAM => 1, OnboardingWizard::NONCE_PARAM => wp_create_nonce( OnboardingWizard::STEP_ACTION ), ], $urls['general'] ); - $urls['onboarding_demo'] = HCAPTCHA_URL . '/assets/images/demo/onboarding.gif'; - $urls['ai_abilities'] = 'https://wordpress.org/plugins/hcaptcha-for-forms-and-more/#how%20do%20i%20use%20the%20new%20ai%20/%20abilities%20features%3F'; - $urls['ai_abilities_img'] = HCAPTCHA_URL . '/assets/images/ai-abilities.png'; - $urls['export_import_img'] = HCAPTCHA_URL . '/assets/images/export-import.png'; - $urls['country_access'] = $urls['general'] . '#blacklisted_countries'; - $urls['country_access_img'] = HCAPTCHA_URL . '/assets/images/country-access.png'; - $urls['migration_wizard'] = $urls['tools'] . '#hcaptcha-migration-wizard'; - $urls['migration_wizard_img'] = HCAPTCHA_URL . '/assets/images/migration-wizard.png'; - $urls['trusted_ip_headers'] = $urls['anti_spam_page'] . '#trusted_address_headers'; - $urls['trusted_ip_headers_img'] = HCAPTCHA_URL . '/assets/images/trusted-ip-headers.png'; - $urls['forms_events_trash'] = $urls['forms']; - $urls['forms_events_trash_img'] = HCAPTCHA_URL . '/assets/images/forms-events-trash.png'; - $urls['events_dashboard_img'] = HCAPTCHA_URL . '/assets/images/events-dashboard.png'; - $urls['paypal_payments'] = $urls['integrations'] . '#paypal_payments_status_1'; - $urls['paypal_payments_img'] = HCAPTCHA_URL . '/assets/images/woocommerce-paypal-payments.png'; - $urls['command_palette'] = $urls['general']; - $urls['command_palette_img'] = HCAPTCHA_URL . '/assets/images/magnifying-glass.svg'; - $urls['theme_editor'] = $urls['general'] . '#config_params'; - $urls['theme_editor_img'] = HCAPTCHA_URL . '/assets/images/advanced-theme-editor.jpg'; - $urls['anti_spam_checks'] = $urls['anti_spam_page'] . '#antispam_1'; - $urls['anti_spam_checks_img'] = HCAPTCHA_URL . '/assets/images/smarter-anti-spam-checks.png'; + $urls['onboarding_demo'] = HCAPTCHA_URL . '/assets/images/demo/onboarding.gif'; + $urls['ai_abilities'] = 'https://wordpress.org/plugins/hcaptcha-for-forms-and-more/#how%20do%20i%20use%20the%20new%20ai%20/%20abilities%20features%3F'; + $urls['ai_abilities_img'] = HCAPTCHA_URL . '/assets/images/ai-abilities.png'; + $urls['export_import_img'] = HCAPTCHA_URL . '/assets/images/export-import.png'; + $urls['country_access'] = $urls['general'] . '#blacklisted_countries'; + $urls['country_access_img'] = HCAPTCHA_URL . '/assets/images/country-access.png'; + $urls['migration_wizard'] = $urls['tools'] . '#hcaptcha-migration-wizard'; + $urls['migration_wizard_img'] = HCAPTCHA_URL . '/assets/images/migration-wizard.png'; + $urls['trusted_ip_headers'] = $urls['anti_spam_page'] . '#trusted_address_headers'; + $urls['trusted_ip_headers_img'] = HCAPTCHA_URL . '/assets/images/trusted-ip-headers.png'; + $urls['forms_events_trash'] = $urls['forms']; + $urls['forms_events_trash_img'] = HCAPTCHA_URL . '/assets/images/forms-events-trash.png'; + $urls['events_dashboard_img'] = HCAPTCHA_URL . '/assets/images/events-dashboard.png'; + $urls['paypal_payments'] = $urls['integrations'] . '#paypal_payments_status_1'; + $urls['paypal_payments_img'] = HCAPTCHA_URL . '/assets/images/woocommerce-paypal-payments.png'; + $urls['command_palette'] = $urls['general']; + $urls['command_palette_img'] = HCAPTCHA_URL . '/assets/images/magnifying-glass.svg'; + $urls['theme_editor'] = $urls['general'] . '#config_params'; + $urls['theme_editor_img'] = HCAPTCHA_URL . '/assets/images/advanced-theme-editor.jpg'; + $urls['anti_spam_checks'] = $urls['anti_spam_page'] . '#antispam_1'; + $urls['anti_spam_checks_img'] = HCAPTCHA_URL . '/assets/images/smarter-anti-spam-checks.png'; + $urls['rest_api_protection_img'] = HCAPTCHA_URL . '/assets/images/rest-api-protection.png'; } return $urls; diff --git a/src/php/Admin/OnboardingWizard.php b/src/php/Admin/OnboardingWizard.php index 02f3f0a99..96ffd3cee 100644 --- a/src/php/Admin/OnboardingWizard.php +++ b/src/php/Admin/OnboardingWizard.php @@ -8,6 +8,7 @@ namespace HCaptcha\Admin; use HCaptcha\Helpers\Request; +use HCaptcha\Settings\AntiSpamPage; use HCaptcha\Settings\General; use HCaptcha\Settings\Integrations; use HCaptcha\Settings\PluginSettingsBase; @@ -79,6 +80,13 @@ class OnboardingWizard { */ private PluginSettingsBase $general_tab; + /** + * Anti-Spam tab instance. + * + * @var PluginSettingsBase + */ + private PluginSettingsBase $antispam_tab; + /** * Integration tab instance. * @@ -112,6 +120,7 @@ public function __construct( PluginSettingsBase $tab ) { public function init(): void { $this->settings = hcaptcha()->settings(); $this->general_tab = $this->settings->get_tab( General::class ); + $this->antispam_tab = $this->settings->get_tab( AntiSpamPage::class ); $this->integrations_tab = $this->settings->get_tab( Integrations::class ); $this->init_wizard_state(); @@ -152,10 +161,10 @@ public function maybe_handle_direct_step(): void { return; } - // Accept a numeric step only: onb=1..8. + // Accept a numeric step only: onb=1..9. $num = (int) $step; - if ( $num < 1 || $num > 8 ) { + if ( $num < 1 || $num > 9 ) { $num = 1; } @@ -163,9 +172,15 @@ public function maybe_handle_direct_step(): void { $this->set_wizard_state( 'step ' . $num ); // Determine the target page by step. - $url = ( $num <= 6 ) - ? $this->tab->tab_url( $this->general_tab ) - : $this->tab->tab_url( $this->integrations_tab ); + if ( $num <= 5 ) { + $target_tab = $this->general_tab; + } elseif ( $num <= 7 ) { + $target_tab = $this->antispam_tab; + } else { + $target_tab = $this->integrations_tab; + } + + $url = $this->tab->tab_url( $target_tab ); $this->redirect_after_direct_step( $url ); } @@ -218,8 +233,8 @@ public function admin_enqueue_scripts(): void { $wizard = $this->get_wizard_state(); - // Start the wizard if the key is absent or its value is not 'completed'. - if ( 'completed' === $wizard ) { + // Show the wizard only after the user explicitly starts it. + if ( ! preg_match( '/^step [1-9]$/', $wizard ) ) { return; } @@ -231,13 +246,19 @@ public function admin_enqueue_scripts(): void { // @codeCoverageIgnoreEnd } - $min = hcap_min_suffix(); + $min = hcap_min_suffix(); + $script_version = constant( 'HCAPTCHA_VERSION' ); + + if ( '' === $min ) { + $script_mtime = filemtime( constant( 'HCAPTCHA_PATH' ) . '/assets/js/onboarding-wizard.js' ); + $script_version .= false === $script_mtime ? '' : '-' . $script_mtime; + } wp_enqueue_script( self::HANDLE, constant( 'HCAPTCHA_URL' ) . "/assets/js/onboarding-wizard$min.js", [ 'jquery', $this->tab::HANDLE ], - constant( 'HCAPTCHA_VERSION' ), + $script_version, true ); @@ -262,9 +283,12 @@ public function admin_enqueue_scripts(): void { 'set_min_submit_time' => '#set_min_submit_time_1', 'antispam_check' => '#antispam_1', 'antispam_provider' => 'select[name="hcaptcha_settings[antispam_provider]"]', - 'antispam' => '.hcaptcha-section-antispam+table', 'save' => '#hcaptcha-options #submit', ], + 'antispam' => [ + 'bot_detection' => '.hcaptcha-section-bot-detection+table', + 'save' => '#hcaptcha-options #submit', + ], 'integrations' => [ 'integrations_list' => '.hcaptcha-enabled-section+h3+table tr:first-child', 'save' => '#hcaptcha-options #submit', @@ -277,14 +301,21 @@ public function admin_enqueue_scripts(): void { 2 => __( 'Switch Mode to Live', 'hcaptcha-for-forms-and-more' ), 3 => __( 'Enter keys, solve hCaptcha and Check Config', 'hcaptcha-for-forms-and-more' ), 4 => __( 'Enable Force (recommended)', 'hcaptcha-for-forms-and-more' ), - 5 => __( 'Enable Anti-spam options (recommended)', 'hcaptcha-for-forms-and-more' ), - 6 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ), - 7 => __( 'Enable hCaptcha for installed plugins', 'hcaptcha-for-forms-and-more' ), - 8 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ), + 5 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ), + 6 => __( 'Review bot detection options', 'hcaptcha-for-forms-and-more' ), + 7 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ), + 8 => __( 'Enable hCaptcha for installed plugins', 'hcaptcha-for-forms-and-more' ), + 9 => __( 'Save settings', 'hcaptcha-for-forms-and-more' ), ]; // Detect which settings page we are on by looking at the body class via the section title echoing into form class. - $page = $this->tab === $this->integrations_tab ? 'integrations' : 'general'; + if ( $this->tab === $this->integrations_tab ) { + $page = 'integrations'; + } elseif ( $this->tab === $this->antispam_tab ) { + $page = 'antispam'; + } else { + $page = 'general'; + } wp_localize_script( self::HANDLE, @@ -300,7 +331,9 @@ public function admin_enqueue_scripts(): void { 'currentStep' => $current_step, 'selectors' => $selectors, 'steps' => $steps, + 'signupUrl' => 'https://www.hcaptcha.com/signup-interstitial/?r=wp&utm_source=wordpress&utm_medium=wpplugin&utm_campaign=sk', 'generalUrl' => $settings->tab_url( General::class ), + 'antispamUrl' => $settings->tab_url( AntiSpamPage::class ), 'integrationsUrl' => $settings->tab_url( Integrations::class ), 'stepParam' => self::STEP_PARAM, 'stepNonce' => wp_create_nonce( self::STEP_ACTION ), @@ -311,7 +344,7 @@ public function admin_enqueue_scripts(): void { 'done' => __( 'Done', 'hcaptcha-for-forms-and-more' ), 'choiceTitle' => __( 'How would you like to continue?', 'hcaptcha-for-forms-and-more' ), 'choiceBody' => __( 'Your keys are configured and verified. We can now apply the recommended setup automatically, or you can continue step by step.', 'hcaptcha-for-forms-and-more' ), - 'choiceAutoBody' => __( 'Automatic setup will enable Force, apply the recommended anti-spam options, enable hCaptcha for installed plugins and themes, and save your settings.', 'hcaptcha-for-forms-and-more' ), + 'choiceAutoBody' => __( 'Automatic setup will enable Force, Honeypot, and minimum submit time, apply available reCAPTCHA migrations, and save your settings.', 'hcaptcha-for-forms-and-more' ), 'choiceAutoCta' => __( 'Apply recommended setup automatically', 'hcaptcha-for-forms-and-more' ), 'choiceManualCta' => __( 'Continue step by step', 'hcaptcha-for-forms-and-more' ), 'close' => __( 'Close', 'hcaptcha-for-forms-and-more' ), diff --git a/src/php/Admin/WhatsNew.php b/src/php/Admin/WhatsNew.php index a95953f3a..72658b062 100644 --- a/src/php/Admin/WhatsNew.php +++ b/src/php/Admin/WhatsNew.php @@ -809,6 +809,39 @@ protected function whats_new_5_4_0(): void { $this->show_block( $block_anti_spam ); } + /** + * What's New 5.5.0 content. + * + * @return void + * @noinspection HtmlUnknownTarget + * @noinspection PhpUnused + */ + protected function whats_new_5_5_0(): void { + $urls = $this->prepare_urls(); + + $block_rest_api_protection = [ + 'type' => 'left', + 'badge' => __( 'New Feature', 'hcaptcha-for-forms-and-more' ), + 'title' => __( 'Unique REST API Protection', 'hcaptcha-for-forms-and-more' ), + 'message' => sprintf( + '

    %1$s

    %2$s

    %3$s

    ', + __( 'Protect Content now keeps selected posts and pages out of WordPress REST responses, collections, and search until the visitor passes hCaptcha.', 'hcaptcha-for-forms-and-more' ), + __( 'When the corresponding integrations are enabled, native REST comments require hCaptcha and REST post-password attempts are blocked.', 'hcaptcha-for-forms-and-more' ), + __( 'In our October 2026 review of the 10 most-installed WordPress.org plugins tagged captcha, none offered all three protections.', 'hcaptcha-for-forms-and-more' ) + ), + 'button' => [ + 'url' => $urls['protect_content'], + 'text' => __( 'Configure Content Protection', 'hcaptcha-for-forms-and-more' ), + ], + 'image' => [ + 'url' => $urls['rest_api_protection_img'], + 'lightbox' => true, + ], + ]; + + $this->show_block( $block_rest_api_protection ); + } + /** * Show block. * diff --git a/src/php/Affiliates/Register.php b/src/php/Affiliates/Register.php index c7d23e692..8051780ef 100644 --- a/src/php/Affiliates/Register.php +++ b/src/php/Affiliates/Register.php @@ -8,6 +8,7 @@ namespace HCaptcha\Affiliates; use HCaptcha\Helpers\API; +use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; /** @@ -88,10 +89,7 @@ public function after_section( string $current_section_key ): void { $args = [ 'action' => self::ACTION, 'name' => self::NONCE, - 'id' => [ - 'source' => HCaptcha::get_class_source( __CLASS__ ), - 'form_id' => 'register', - ], + 'id' => $this->get_expected_id(), ]; $search = 'error_message = API::verify_post( self::NONCE, self::ACTION ); + // A logged-in affiliate registers with the stored address, not the readonly POST field. + $email = ''; + + // phpcs:disable WordPress.Security.NonceVerification.Missing -- The API verifies the nonce below. + if ( is_user_logged_in() ) { + $email = wp_get_current_user()->user_email; + } elseif ( isset( $_POST['user_email'] ) && is_scalar( $_POST['user_email'] ) ) { + $email = sanitize_email( wp_unslash( (string) $_POST['user_email'] ) ); + } + // phpcs:enable WordPress.Security.NonceVerification.Missing + + $this->error_message = API::verify_post( + self::NONCE, + self::ACTION, + $this->get_expected_id(), + EntryData::with_emails( [], [ $email ] ) + ); return null !== $this->error_message; } @@ -139,4 +153,16 @@ private function show_error(): void {
    HCaptcha::get_class_source( __CLASS__ ), + 'form_id' => 'register', + ]; + } } diff --git a/src/php/AntiSpam/DisposableEmail.php b/src/php/AntiSpam/DisposableEmail.php index 237b13a12..e9c2edce7 100644 --- a/src/php/AntiSpam/DisposableEmail.php +++ b/src/php/AntiSpam/DisposableEmail.php @@ -7,6 +7,8 @@ namespace HCaptcha\AntiSpam; +use HCaptcha\Helpers\EntryData; + /** * Class DisposableEmail. */ @@ -81,21 +83,21 @@ private function init_hooks(): void { * @return string|null */ public function verify( array $entry ): ?string { - $email = $entry['data']['email'] ?? ''; - - if ( ! is_email( $email ) ) { - return true; + foreach ( EntryData::get_emails( $entry ) as $email ) { + /** + * Filters the disposable email status. + * + * @param bool $is_disposable Whether the email is disposable. + * @param string $email Email address. + */ + $disposable = (bool) apply_filters( 'hcap_is_disposable_email', $this->is_disposable_email( $email ), $email ); + + if ( $disposable ) { + return false; + } } - /** - * Filters the disposable email status. - * - * @param bool $is_disposable Whether the email is disposable. - * @param string $email Email address. - */ - $disposable = (bool) apply_filters( 'hcap_is_disposable_email', $this->is_disposable_email( $email ), $email ); - - return ! $disposable; + return true; } /** @@ -162,18 +164,15 @@ protected function read_file( string $file ) { * @return bool */ public function is_disposable_email( string $email ): bool { - if ( false === strpos( $email, '@' ) ) { - return false; - } - - $parts = explode( '@', trim( $email ) ); + $email = trim( $email ); + $separator = strrpos( $email, '@' ); - if ( count( $parts ) < 2 || '' === $parts[1] ) { + if ( false === $separator || strlen( $email ) - 1 === $separator ) { return false; } $to_lower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower'; - $domain = $to_lower( $parts[1] ); + $domain = $to_lower( substr( $email, $separator + 1 ) ); $domain_parts = explode( '.', $domain ); $blocklist = $this->get_blocklist(); $count = count( $domain_parts ); @@ -262,6 +261,7 @@ public function update_blocklist(): void { * Schedule the recurring blocklist update via Action Scheduler. * * @return void + * @noinspection PhpUndefinedFunctionInspection */ protected function schedule_update(): void { if ( ! function_exists( 'as_schedule_recurring_action' ) ) { @@ -282,6 +282,7 @@ protected function schedule_update(): void { * Unschedule the recurring blocklist update. * * @return void + * @noinspection PhpUndefinedFunctionInspection */ protected function unschedule_update(): void { if ( ! function_exists( 'as_unschedule_all_actions' ) ) { diff --git a/src/php/Asgaros/Base.php b/src/php/Asgaros/Base.php index 7f883fb71..7d1636490 100644 --- a/src/php/Asgaros/Base.php +++ b/src/php/Asgaros/Base.php @@ -50,15 +50,13 @@ public function add_captcha( $output, string $tag, $attr, array $m ) { return $output; } - $form_id = isset( $attr['id'] ) ? (int) $attr['id'] : 0; + $form_id = $this->get_form_id(); $search = '
    '; $args = [ - 'action' => static::ACTION, - 'name' => static::NAME, - 'id' => [ - 'source' => HCaptcha::get_class_source( static::class ), - 'form_id' => $form_id, - ], + 'mandatory' => true, + 'action' => static::ACTION, + 'name' => static::NAME, + 'id' => $this->get_id( $form_id ), ]; return str_replace( @@ -83,7 +81,7 @@ public function add_captcha( $output, string $tag, $attr, array $m ) { public function verify( $verified ) { global $asgarosforum; - $error_message = API::verify_post( static::NAME, static::ACTION ); + $error_message = API::verify_post( static::NAME, static::ACTION, $this->get_id( $this->get_form_id() ) ); if ( null !== $error_message ) { $asgarosforum->add_notice( $error_message ); @@ -94,6 +92,33 @@ public function verify( $verified ) { return $verified; } + /** + * Get the forum selected by the native request. + * + * @return int + */ + private function get_form_id(): int { + global $asgarosforum; + + $forum_id = $asgarosforum->current_forum ?? 0; + + return is_scalar( $forum_id ) ? absint( $forum_id ) : 0; + } + + /** + * Get the widget identity for an Asgaros forum. + * + * @param int $forum_id Forum ID. + * + * @return array + */ + private function get_id( int $forum_id ): array { + return [ + 'source' => HCaptcha::get_class_source( static::class ), + 'form_id' => $forum_id, + ]; + } + /** * Print inline styles. * diff --git a/src/php/AutoVerify/AutoVerify.php b/src/php/AutoVerify/AutoVerify.php index a350afe25..74cd16f40 100644 --- a/src/php/AutoVerify/AutoVerify.php +++ b/src/php/AutoVerify/AutoVerify.php @@ -10,6 +10,7 @@ use HCaptcha\Helpers\API; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Helpers\Request; +use WP_Query; use WP_Widget_Block; /** @@ -27,6 +28,11 @@ class AutoVerify { */ private const OPTION_PREFIX = 'hcaptcha_auto_verify_form_'; + /** + * Public WordPress query variables selecting a single post. + */ + private const QUERY_SELECTORS = [ 'page_id', 'p', 'pagename', 'name', 'attachment_id', 'subpost_id', 'attachment', 'subpost' ]; + /** * Legacy transient size limit, retained for compatibility. * @@ -286,13 +292,19 @@ private function get_registered_form_for_request(): ?array { return $registered_form; } - $canonical_path = $this->get_canonical_request_path(); + foreach ( $this->get_canonical_request_keys() as $canonical_key ) { + if ( ! $canonical_key || $canonical_key === $path || $canonical_key === $target_key ) { + continue; + } - if ( ! $canonical_path || $canonical_path === $path ) { - return null; + $registered_form = $this->get_registered_form( $canonical_key ); + + if ( null !== $registered_form ) { + return $registered_form; + } } - return $this->get_registered_form( $canonical_path ); + return null; } /** @@ -326,13 +338,20 @@ private function verify_submission( array $registered_form ): ?string { * @return array */ private function get_entry( string $name, string $action, array $expected_id ): array { - return [ + $entry = [ 'nonce_name' => $name, 'nonce_action' => $action, 'h-captcha-response' => Request::filter_input( INPUT_POST, 'h-captcha-response' ), 'data' => $this->get_data(), 'expected_id' => $expected_id, ]; + + /** + * Filter entry data for the server-registered automatic form. + * + * @param array $entry Verification entry with the registered form identity. + */ + return (array) apply_filters( 'hcap_auto_verify_entry', $entry ); } /** @@ -417,17 +436,214 @@ protected function register_forms( array $forms ): void { * @return string */ private function get_form_action( string $form ): string { - $form_action = ''; + $form_action = $this->get_form_action_attribute( $form ); + $form_action = trim( str_replace( [ "\t", "\r", "\n" ], '', $form_action ), "\x00..\x20" ); - if ( preg_match( '##', $form, $m ) ) { - $form_action = $m[1]; + if ( '' === $form_action ) { + $form_action = $this->get_request_uri(); + } else { + $form_action = $this->resolve_form_action( $form_action ); } - $form_action = $form_action ?: $this->get_request_uri(); - return $this->get_target_key( $form_action ); } + /** + * Read the first action attribute from the form's opening tag. + * + * @param string $form Form. + * + * @return string + */ + private function get_form_action_attribute( string $form ): string { + + // Read only the opening tag, consuming quoted values before inspecting the next attribute. + if ( preg_match( '#])(?:[^>"\']|"[^"]*"|\'[^\']*\')*>#i', $form, $tag ) ) { + preg_match_all( + '#([^\x09\x0a\x0c\x0d\x20=/>]+)(?:[\x09\x0a\x0c\x0d\x20]*=[\x09\x0a\x0c\x0d\x20]*(?:"([^"]*)"|\'([^\']*)\'|([^\x09\x0a\x0c\x0d\x20>]*)))?#', + substr( $tag[0], 5, -1 ), + $attributes, + PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL + ); + + foreach ( $attributes as $attribute ) { + if ( 'action' !== strtolower( $attribute[1] ) ) { + continue; + } + + // Browsers use the first duplicate attribute and decode its entities once. + return $this->decode_action_attribute( $attribute[2] ?? $attribute[3] ?? $attribute[4] ?? '' ); + } + } + + return ''; + } + + /** + * Decode HTML attribute references once, including browser forms without semicolons. + * + * @param string $value Attribute value. + * + * @return string + */ + private function decode_action_attribute( string $value ): string { + $legacy = [ 'AMP', 'COPY', 'GT', 'LT', 'QUOT', 'REG', 'amp', 'gt', 'lt', 'quot' ]; + + foreach ( get_html_translation_table( HTML_ENTITIES, ENT_QUOTES | ENT_HTML401 ) as $character => $entity ) { + if ( preg_match( '/^(?:\xc2[\xa0-\xbf]|\xc3[\x80-\xbf])$/', $character ) ) { + $legacy[] = substr( $entity, 1, -1 ); + } + } + + return preg_replace_callback( + '/&#(?:[xX][0-9a-fA-F]+|[0-9]+);?|&([a-zA-Z][a-zA-Z0-9]*)(;|(?![a-zA-Z0-9=]))/', + function ( array $matches ) use ( $legacy ): string { + if ( 0 === strpos( $matches[0], '&#' ) ) { + return $this->decode_numeric_reference( $matches[0] ); + } + + if ( ';' !== $matches[2] && ! in_array( $matches[1], $legacy, true ) ) { + return $matches[0]; + } + + return html_entity_decode( '&' . $matches[1] . ';', ENT_QUOTES | ENT_HTML5, 'UTF-8' ); + }, + $value + ); + } + + /** + * Decode a numeric reference with HTML's replacement and legacy control mapping. + * + * @param string $reference Numeric character reference. + * + * @return string + */ + private function decode_numeric_reference( string $reference ): string { + $number = substr( rtrim( $reference, ';' ), 2 ); + $code = 'x' === strtolower( $number[0] ) ? hexdec( substr( $number, 1 ) ) : (float) $number; + + if ( 0 === (int) $code || $code > 0x10ffff || ( $code >= 0xd800 && $code <= 0xdfff ) ) { + return "\xef\xbf\xbd"; + } + + $controls = [ + 0x80 => 0x20ac, + 0x82 => 0x201a, + 0x83 => 0x0192, + 0x84 => 0x201e, + 0x85 => 0x2026, + 0x86 => 0x2020, + 0x87 => 0x2021, + 0x88 => 0x02c6, + 0x89 => 0x2030, + 0x8a => 0x0160, + 0x8b => 0x2039, + 0x8c => 0x0152, + 0x8e => 0x017d, + 0x91 => 0x2018, + 0x92 => 0x2019, + 0x93 => 0x201c, + 0x94 => 0x201d, + 0x95 => 0x2022, + 0x96 => 0x2013, + 0x97 => 0x2014, + 0x98 => 0x02dc, + 0x99 => 0x2122, + 0x9a => 0x0161, + 0x9b => 0x203a, + 0x9c => 0x0153, + 0x9e => 0x017e, + 0x9f => 0x0178, + ]; + $code = $controls[ (int) $code ] ?? (int) $code; + + if ( $code < 0x80 ) { + return chr( $code ); + } + + if ( $code < 0x800 ) { + return chr( 0xc0 | ( $code >> 6 ) ) . chr( 0x80 | ( $code & 0x3f ) ); + } + + if ( $code < 0x10000 ) { + return chr( 0xe0 | ( $code >> 12 ) ) . chr( 0x80 | ( ( $code >> 6 ) & 0x3f ) ) . chr( 0x80 | ( $code & 0x3f ) ); + } + + return chr( 0xf0 | ( $code >> 18 ) ) . chr( 0x80 | ( ( $code >> 12 ) & 0x3f ) ) . chr( 0x80 | ( ( $code >> 6 ) & 0x3f ) ) . chr( 0x80 | ( $code & 0x3f ) ); + } + + /** + * Resolve an action against the current document before decoding URL path octets. + * + * @param string $action Form action. + * + * @return string + */ + private function resolve_form_action( string $action ): string { + // Backslashes are path separators in browser HTTP URLs, but not in their queries. + $action = preg_replace_callback( + '/^[^?#]*/', + static function ( array $matches ): string { + return str_replace( '\\', '/', $matches[0] ); + }, + $action + ); + $parts = (array) wp_parse_url( $action ); + $base = (array) wp_parse_url( $this->get_request_uri() ); + $origin = isset( $parts['host'] ) || isset( $parts['scheme'] ); + $path = $parts['path'] ?? ''; + + if ( $origin ) { + $path = '' === $path ? '/' : $path; + } elseif ( '' === $path ) { + $path = $base['path'] ?? '/'; + } elseif ( '/' !== $path[0] ) { + $base_path = $base['path'] ?? '/'; + $path = substr( $base_path, 0, (int) strrpos( $base_path, '/' ) + 1 ) . $path; + } + + $query = $this->get_action_query( $parts, $base, $origin ); + + return $this->normalize_action_path( $path ) . ( '' !== $query ? '?' . $query : '' ); + } + + /** + * A pathless relative action inherits the document query unless it supplies one. + * + * @param array $parts Action URL parts. + * @param array $base Document URL parts. + * @param bool $origin Whether the action specifies an origin. + * + * @return string + */ + private function get_action_query( array $parts, array $base, bool $origin ): string { + return $parts['query'] ?? ( ! $origin && ! isset( $parts['path'] ) ? ( $base['query'] ?? '' ) : '' ); + } + + /** + * Remove browser dot segments while retaining empty segments and encoded separators. + * + * @param string $path Action path. + * + * @return string + */ + private function normalize_action_path( string $path ): string { + $segments = []; + + foreach ( explode( '/', ltrim( $path, '/' ) ) as $segment ) { + $dot_segment = str_ireplace( '%2e', '.', $segment ); + + if ( '..' === $dot_segment ) { + array_pop( $segments ); + } elseif ( '.' !== $dot_segment ) { + $segments[] = $segment; + } + } + + return '/' . implode( '/', $segments ); + } + /** * Distinguish WordPress query routes sharing the same URL path. * @@ -449,16 +665,21 @@ private function get_target_key( string $url ): string { } parse_str( $query, $query_vars ); - $post_id = $this->get_query_post_id( $query_vars ); - if ( ! $post_id ) { + if ( ! array_filter( array_intersect_key( $query_vars, array_flip( self::QUERY_SELECTORS ) ) ) ) { return $path; } $home_path = $this->get_path( home_url( '/' ) ); $index_path = ( '/' === $home_path ? '' : $home_path ) . '/index.php'; - return $path === $home_path || $path === $index_path ? 'post:' . $post_id . ':' . $path : $path; + if ( $path !== $home_path && $path !== $index_path ) { + return $path; + } + + $post_id = $this->get_query_post_id( $query_vars ); + + return $post_id ? 'post:' . $post_id . ':' . $path : $path; } /** @@ -469,21 +690,22 @@ private function get_target_key( string $url ): string { * @return int */ private function get_query_post_id( array $query_vars ): int { - foreach ( [ 'page_id', 'p' ] as $key ) { - $value = $query_vars[ $key ] ?? null; + $query_vars = array_intersect_key( $query_vars, array_flip( array_merge( self::QUERY_SELECTORS, [ 'post_type' ] ) ) ); - if ( is_scalar( $value ) && ctype_digit( (string) $value ) ) { - return (int) $value; - } + if ( ! array_filter( array_intersect_key( $query_vars, array_flip( self::QUERY_SELECTORS ) ) ) ) { + return 0; } - if ( ! empty( $query_vars['pagename'] ) && is_string( $query_vars['pagename'] ) ) { - $page = get_page_by_path( $query_vars['pagename'] ); - - return $page->ID ?? 0; - } + // Use the installed core's selector normalization, aliases and precedence. + $query = new WP_Query( + $query_vars + [ + 'posts_per_page' => 1, + 'no_found_rows' => true, + ] + ); - return 0; + // Retain page-qualified action keys even when a numeric target does not exist yet. + return $query->get_queried_object_id() ?: (int) ( $query->query_vars['page_id'] ?: $query->query_vars['p'] ); } /** @@ -504,36 +726,50 @@ private function get_widget_id_value( string $form ): string { } /** - * Get the canonical path of the current WordPress request. + * Get equivalent registration keys for the current WordPress page. * - * @return string + * @return array */ - private function get_canonical_request_path(): string { - $post_id = url_to_postid( Request::current_url() ); - - if ( ! $post_id ) { - $pagename = Request::filter_input( INPUT_GET, 'pagename' ); + private function get_canonical_request_keys(): array { + // The native login script does not route page selectors through WordPress's main query. + if ( 'wp-login.php' === basename( Request::filter_input( INPUT_SERVER, 'SCRIPT_NAME' ) ) ) { + return []; + } - if ( is_string( $pagename ) && '' !== $pagename ) { - $page = get_page_by_path( $pagename ); + $query_vars = []; - if ( $page ) { - $post_id = $page->ID; - } - } + foreach ( array_merge( self::QUERY_SELECTORS, [ 'post_type' ] ) as $key ) { + // Preserve WordPress's input and POST-before-GET precedence. WP_Query validates these selectors. + // Nonce is verified later, in API::verify(). + // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + $query_vars[ $key ] = $_POST[ $key ] ?? $_GET[ $key ] ?? ''; } + $post_id = $this->get_query_post_id( $query_vars ); + $post_id = $post_id ?: url_to_postid( Request::current_url() ); + if ( ! $post_id ) { - return ''; + return []; } $permalink = get_permalink( $post_id ); if ( ! is_string( $permalink ) ) { - return ''; + return []; } - return $this->get_path( $permalink ); + $home_path = $this->get_path( home_url( '/' ) ); + $index_path = ( '/' === $home_path ? '' : $home_path ) . '/index.php'; + + // Existing registrations can use either plain permalink entry point. + return array_unique( + [ + $this->get_target_key( $permalink ), + 'post:' . $post_id . ':' . $home_path, + 'post:' . $post_id . ':' . $index_path, + $this->get_path( $permalink ), + ] + ); } /** @@ -543,7 +779,7 @@ private function get_canonical_request_path(): string { */ private function get_request_uri(): string { return isset( $_SERVER['REQUEST_URI'] ) ? - (string) filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_FULL_SPECIAL_CHARS ) : + (string) filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_URL ) : ''; } @@ -796,16 +1032,80 @@ private function is_same_registered_form_identity( array $registered_form, array * Whether a request matches the registered form structure. * * @param array $registered_form Registered form. - * @param array $post_keys Submitted input names. + * @param array $post Submitted form data. * @param string $widget_id Submitted widget ID. * * @return bool */ - private function is_same_registered_form( array $registered_form, array $post_keys, string $widget_id ): bool { + private function is_same_registered_form( array $registered_form, array $post, string $widget_id ): bool { $inputs = (array) ( $registered_form['inputs'] ?? [] ); $registered_widget_id = (string) ( $registered_form['widget_id'] ?? '' ); - return $widget_id && $registered_widget_id === $widget_id && ! array_diff( $inputs, $post_keys ); + if ( ! $widget_id || $registered_widget_id !== $widget_id ) { + return false; + } + + foreach ( $inputs as $input ) { + if ( ! $this->has_input( $input, $post ) ) { + return false; + } + } + + return true; + } + + /** + * Check a registered HTML input name against PHP's parsed submission. + * + * @param string $name Input name. + * @param array $post Submitted form data. + * + * @return bool + */ + private function has_input( string $name, array $post ): bool { + // Let PHP normalize the root key without interpreting name characters as query separators. + parse_str( rawurlencode( $name ) . '=1', $parsed ); + + if ( ! $parsed ) { + return false; + } + + preg_match_all( '/\[([^\]]*)\]/', $name, $matches ); + $keys = array_merge( [ array_key_first( $parsed ) ], $matches[1] ); + + return $this->has_input_path( $post, $keys ); + } + + /** + * Resolve named array keys, treating empty brackets as any submitted array element. + * + * @param mixed $value Submitted value. + * @param array $keys Remaining input name keys. + * + * @return bool + */ + private function has_input_path( $value, array $keys ): bool { + if ( ! $keys ) { + return true; + } + + if ( ! is_array( $value ) ) { + return false; + } + + $key = array_shift( $keys ); + + if ( '' !== $key ) { + return array_key_exists( $key, $value ) && $this->has_input_path( $value[ $key ], $keys ); + } + + foreach ( $value as $item ) { + if ( $this->has_input_path( $item, $keys ) ) { + return true; + } + } + + return false; } /** @@ -874,12 +1174,12 @@ protected function get_registered_form( string $path ): ?array { // Nonce is verified later, in \HCaptcha\Helpers\API::verify(). // phpcs:ignore WordPress.Security.NonceVerification.Missing - $post_keys = array_keys( $_POST ); + $post = $_POST; $widget_id = Request::filter_input( INPUT_POST, HCaptcha::HCAPTCHA_WIDGET_ID ); $widget_id = is_string( $widget_id ) ? $widget_id : ''; foreach ( $action_forms as $registered_form ) { - if ( $this->is_same_registered_form( (array) $registered_form, $post_keys, $widget_id ) ) { + if ( $this->is_same_registered_form( (array) $registered_form, $post, $widget_id ) ) { return $registered_form; } } @@ -937,19 +1237,47 @@ private function process_content( $content ): string { return $content; } - if ( - preg_match_all( - '#
    #', - $content, - $matches, - PREG_PATTERN_ORDER - ) - ) { - $forms = $matches[0]; + $forms = $this->get_content_forms( $content ); + if ( $forms ) { $this->register_forms( $forms ); } return $content; } + + /** + * Find complete form elements without treating raw text or comments as markup. + * + * @param string $content Rendered content. + * + * @return array + */ + private function get_content_forms( string $content ): array { + $tag = '(?:[^>"\']|"[^"]*"|\'[^\']*\')*>'; + preg_match_all( + '#|<(script|style|textarea|title)(?=[\x09\x0a\x0c\x0d\x20/>])' . $tag . '[\S\s]*?|])' . $tag . '#i', + $content, + $matches, + PREG_OFFSET_CAPTURE + ); + $forms = []; + $start = null; + + foreach ( $matches[0] as [ $markup, $offset ] ) { + if ( null === $start && 0 === stripos( $markup, 'get_entry( $form_data ) ); + // Avada selects the submitted form from this field, not from formData keys. + $form_id = Request::filter_input( INPUT_POST, 'form_id' ); + $form_id = is_string( $form_id ) ? absint( $form_id ) : 0; + + $result = $form_id + ? API::verify( $this->get_entry( $form_data, $form_id ) ) + : hcap_get_error_messages()['bad-signature']; if ( null === $result ) { return $demo_mode; @@ -176,20 +182,11 @@ public function enqueue_scripts(): void { * Get entry. * * @param array $form_data Form data. + * @param int $form_id Form ID selected by Avada's submission handler. * * @return array */ - private function get_entry( array $form_data ): array { - $form_id = 0; - - foreach ( $form_data as $key => $value ) { - if ( 0 === strpos( $key, 'fusion-form-nonce-' ) ) { - $form_id = (int) str_replace( 'fusion-form-nonce-', '', $key ); - - break; - } - } - + private function get_entry( array $form_data, int $form_id ): array { $form = get_post( $form_id ); $entry = [ @@ -197,12 +194,9 @@ private function get_entry( array $form_data ): array { 'form_date_gmt' => $form->post_modified_gmt ?? null, 'post_data' => $form_data, 'data' => [], + 'expected_id' => $this->get_expected_id( $form_id ), ]; - if ( $form_id ) { - $entry['expected_id'] = $this->get_expected_id( $form_id ); - } - $field_types = Utils::json_decode_arr( Request::filter_input( INPUT_POST, 'field_types' ) ); foreach ( $form_data as $key => $value ) { diff --git a/src/php/BackInStockNotifier/Form.php b/src/php/BackInStockNotifier/Form.php index 7f89cdac5..5501fcf57 100644 --- a/src/php/BackInStockNotifier/Form.php +++ b/src/php/BackInStockNotifier/Form.php @@ -8,6 +8,7 @@ namespace HCaptcha\BackInStockNotifier; use HCaptcha\Helpers\API; +use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; /** @@ -87,12 +88,10 @@ public function after_submit_button( int $product_id, int $variation_id ): void $output = ob_get_clean(); $args = [ - 'action' => self::ACTION, - 'name' => self::NONCE, - 'id' => [ - 'source' => HCaptcha::get_class_source( __CLASS__ ), - 'form_id' => $this->form_id, - ], + 'mandatory' => $this->form_id <= 0, + 'action' => self::ACTION, + 'name' => self::NONCE, + 'id' => $this->get_id( $this->form_id ), ]; $search = '#', (string) $html, $m ) ) { return $html; } @@ -252,6 +252,14 @@ private function get_data( array $fields, array $values ): array { $field_id = $field->id; $val = $values['item_meta'][ $field_id ] ?? ''; + if ( 'email' === $field->type ) { + if ( is_array( $val ) && 1 === count( $val ) && isset( $val[0] ) ) { + $val = reset( $val ); + } + if ( is_scalar( $val ) ) { + $val = trim( (string) $val ); + } + } if ( null === $val || '' === $val ) { continue; diff --git a/src/php/Forminator/Form.php b/src/php/Forminator/Form.php index 65580473c..bf7f7d8fa 100644 --- a/src/php/Forminator/Form.php +++ b/src/php/Forminator/Form.php @@ -373,31 +373,32 @@ private function get_entry( array $fields, int $form_id ): array { 'expected_id' => $this->get_expected_id( $form_id ), ]; - $name = []; + $name = []; + $emails = []; foreach ( $fields as $field ) { $id = $field->raw['element_id']; $type = $field->raw['type']; $label = $field->raw['field_label']; + $value = Request::filter_input( INPUT_POST, $id ) ?? ''; + + if ( 'email' === $type ) { + $emails[] = $value; + } + if ( ! EntryData::is_content_field_type( (string) $type ) || EntryData::has_sensitive_field( (string) $label, (string) $id ) ) { continue; } - $value = Request::filter_input( INPUT_POST, $id ) ?? ''; - if ( 'name' === $type ) { $name[] = $value; } - if ( 'email' === $type ) { - $entry['data']['email'] = $value; - } - EntryData::add_field( $entry['data'], (string) $label, $value, (string) $id ); } EntryData::add_name( $entry['data'], $name ); - return $entry; + return EntryData::with_emails( $entry, $emails ); } } diff --git a/src/php/GiveWP/Base.php b/src/php/GiveWP/Base.php index dd9bff187..f463314e6 100644 --- a/src/php/GiveWP/Base.php +++ b/src/php/GiveWP/Base.php @@ -13,6 +13,7 @@ namespace HCaptcha\GiveWP; use Give\DonationForms\ValueObjects\DonationFormErrorTypes; +use Give\Helpers\Form\Utils as FormUtils; use HCaptcha\Helpers\API; use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; @@ -56,6 +57,9 @@ public function __construct() { private function init_hooks(): void { add_action( static::ADD_CAPTCHA_HOOK, [ $this, 'add_captcha' ] ); add_action( static::VERIFY_HOOK, [ $this, 'verify' ] ); + add_action( 'wp_ajax_give_paypal_commerce_create_order', [ $this, 'verify_paypal_order' ], 0 ); + add_action( 'wp_ajax_nopriv_give_paypal_commerce_create_order', [ $this, 'verify_paypal_order' ], 0 ); + add_action( 'hcap_givewp_paypal_cleanup', [ PayPalGrant::class, 'cleanup' ] ); add_action( 'template_redirect', [ $this, 'verify_block' ], 9 ); @@ -102,20 +106,13 @@ public function add_captcha( int $form_id ): void { /** * Verify captcha. * - * @param bool|array $valid_data Validate fields. + * @param bool|array|null $valid_data Validate fields on legacy callbacks. * * @return void * @noinspection PhpUndefinedFunctionInspection * @noinspection PhpUnusedParameterInspection */ - public function verify( $valid_data ): void { - // phpcs:ignore WordPress.Security.NonceVerification.Missing - $action = isset( $_POST['action'] ) ? sanitize_text_field( wp_unslash( $_POST['action'] ) ) : ''; - - if ( 'give_process_donation' !== $action ) { - return; - } - + public function verify( $valid_data = null ): void { $error_message = $this->verify_entry(); if ( null !== $error_message ) { @@ -124,26 +121,67 @@ public function verify( $valid_data ): void { } /** - * Verify hCaptcha in the GiveWP block. + * Verify the native GiveWP nonce and hCaptcha before PayPal creates an order. * * @return void + * @noinspection ForgottenDebugOutputInspection + * @noinspection PhpUndefinedFunctionInspection */ - public function verify_block(): void { - if ( ! Request::is_post() ) { + public function verify_paypal_order(): void { + $form_id = absint( Request::filter_input( INPUT_POST, 'give-form-id' ) ); + $form_hash = Request::filter_input( INPUT_POST, 'give-form-hash' ); + + if ( + ! $form_id || + ! is_string( $form_hash ) || + ! function_exists( 'give_verify_donation_form_nonce' ) || + ! give_verify_donation_form_nonce( $form_hash, $form_id ) + ) { + wp_die(); + } + + $block = class_exists( FormUtils::class ) && method_exists( FormUtils::class, 'isV3Form' ) && FormUtils::isV3Form( $form_id ); + $entry = $this->get_entry(); + + if ( ! HCaptcha::is_protection_enabled( $entry['expected_id'] ) ) { return; } + $binding = $this->get_paypal_binding( $form_id, $block, true ); + + if ( null === $binding ) { + $this->reject_paypal_order( hcap_get_error_messages()['fail'] ); + } + + $error = API::verify( $entry ); + + if ( null !== $error ) { + $this->reject_paypal_order( $error ); + } + + $siteverify = API::get_siteverify_response(); + + if ( + true !== ( $siteverify['success'] ?? false ) || + ! PayPalGrant::issue( $binding['response'], $binding, $siteverify ) + ) { + $this->reject_paypal_order( hcap_get_error_messages()['fail'] ); + } + } + + /** + * Verify hCaptcha in the GiveWP block. + * + * @return void + */ + public function verify_block(): void { // phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended $givewp_route = isset( $_GET['givewp-route'] ) ? sanitize_text_field( wp_unslash( $_GET['givewp-route'] ) ) : ''; - - $givewp_route_signature_id = isset( $_GET['givewp-route-signature-id'] ) - ? sanitize_text_field( wp_unslash( $_GET['givewp-route-signature-id'] ) ) - : ''; // phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended - if ( 'donate' !== $givewp_route || 'givewp-donate' !== $givewp_route_signature_id ) { + if ( 'donate' !== $givewp_route ) { return; } @@ -169,7 +207,169 @@ public function verify_block(): void { * @return string|null */ private function verify_entry( bool $check_nonce = true ): ?string { - return API::verify( $this->get_entry( $check_nonce ) ); + $entry = $this->get_entry( $check_nonce ); + $block = ! $check_nonce; + + if ( $this->is_paypal_order_donation( $block ) && HCaptcha::is_protection_enabled( $entry['expected_id'] ) ) { + $form_id = $this->get_form_id( $block ); + $binding = $this->get_paypal_binding( $form_id, $block, false ); + $proof = null === $binding ? null : PayPalGrant::redeem( $binding['response'], $binding ); + + return null === $proof + ? hcap_get_error_messages()['fail'] + : API::verify_preverified( $entry, $proof ); + } + + return API::verify( $entry ); + } + + /** + * Identify the final, one-time PayPal order flow. + * + * @param bool $block Whether this is a block donation. + * + * @return bool + */ + private function is_paypal_order_donation( bool $block ): bool { + $gateway = $block ? $this->request_value( 'gatewayId' ) : Request::filter_input( INPUT_POST, 'give-gateway' ); + + if ( 'paypal-commerce' !== $gateway ) { + return false; + } + + if ( $block ) { + $gateway_data = $this->request_value( 'gatewayData' ); + + return is_array( $gateway_data ) && ! empty( $gateway_data['payPalOrderId'] ); + } + + return '' !== Request::filter_input( INPUT_POST, 'payPalOrderId' ); + } + + /** + * Bind one CAPTCHA response to the same donor, amount and signed form. + * + * @param int $form_id Native form ID. + * @param bool $block Whether the form is a v3 block. + * @param bool $preflight Whether this is the createOrder request. + * + * @return array|null Canonical binding or null on malformed input. + * @noinspection PhpUndefinedFunctionInspection + */ + private function get_paypal_binding( int $form_id, bool $block, bool $preflight ): ?array { + $email = $preflight || ! $block ? Request::filter_input( INPUT_POST, 'give_email' ) : $this->request_value( 'email' ); + $amount = $preflight ? Request::filter_input( INPUT_POST, 'amount' ) : $this->request_value( 'amount' ); + $amount = $block + ? $amount + : Request::filter_input( INPUT_POST, 'give-amount' ); + $response = Request::filter_input( INPUT_POST, 'h-captcha-response' ); + $widget = Request::filter_input( INPUT_POST, HCaptcha::HCAPTCHA_WIDGET_ID ); + $fst = Request::filter_input( INPUT_POST, 'hcap_fst_token' ); + $mode = Request::filter_input( INPUT_POST, 'give_payment_mode' ); + + if ( + ! $form_id || + ! is_string( $email ) || '' === $email || + ! is_string( $amount ) || '' === $amount || + ! is_string( $response ) || '' === $response || + ! is_string( $widget ) || '' === $widget || + ! is_string( $fst ) || + ( $preflight && '' !== $mode && 'paypal-commerce' !== $mode ) + ) { + return null; + } + + if ( $preflight && ! $this->has_paypal_preflight_identity( $form_id, $email, $block ) ) { + return null; + } + + $amount = give_maybe_sanitize_amount( $amount, [ 'currency' => give_get_currency( $form_id ) ] ); + + if ( ! is_numeric( $amount ) || (float) $amount <= 0 ) { + return null; + } + + $session = is_user_logged_in() && function_exists( 'wp_get_session_token' ) ? wp_get_session_token() : ''; + $settings = hcaptcha()->settings(); + $fst_on = $settings->is_on( 'set_min_submit_time' ); + + return [ + 'form_id' => $form_id, + 'email' => $email, + 'amount' => (string) $amount, + 'gateway' => 'paypal-commerce', + 'widget' => $widget, + 'response' => $response, + 'fst' => $fst, + 'fst_on' => $fst_on, + 'fst_min' => $fst_on ? $settings->get( 'min_submit_time' ) : '', + 'user_id' => get_current_user_id(), + 'session' => $session, + ]; + } + + /** + * Match GiveWP's native identity and gateway before PayPal order creation. + * + * @param int $form_id Native form ID. + * @param string $email Donor email. + * @param bool $block Whether the form is a v3 block. + * + * @return bool Whether native PayPal fields match the signed form. + */ + private function has_paypal_preflight_identity( int $form_id, string $email, bool $block ): bool { + if ( ! $block ) { + return $this->has_legacy_paypal_gateway(); + } + + $native_email = Request::filter_input( INPUT_POST, 'email' ); + $native_form = absint( Request::filter_input( INPUT_POST, 'formId' ) ); + $gateway = Request::filter_input( INPUT_POST, 'gatewayId' ); + + return $email === $native_email && $form_id === $native_form && 'paypal-commerce' === $gateway; + } + + /** + * Match GiveWP's native legacy gateway fields at PayPal order creation. + * + * @return bool Whether the native gateway is PayPal Commerce. + */ + private function has_legacy_paypal_gateway(): bool { + $gateway = Request::filter_input( INPUT_POST, 'give-gateway' ); + $mode = Request::filter_input( INPUT_POST, 'payment-mode' ); + + return 'paypal-commerce' === $gateway && ( '' === $mode || 'paypal-commerce' === $mode ); + } + + /** + * Read GiveWP's merged v3 request field. + * + * @param string $name Field name. + * + * @return array|string + */ + private function request_value( string $name ) { + // GiveWP merges form fields into this request before routing donations. + // phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + $value = $_REQUEST[ $name ] ?? ''; + // phpcs:enable WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + + if ( is_array( $value ) ) { + return map_deep( wp_unslash( $value ), 'sanitize_text_field' ); + } + + return is_scalar( $value ) ? sanitize_text_field( wp_unslash( $value ) ) : ''; + } + + /** + * Return a native-compatible AJAX error before GiveWP reaches PayPal. + * + * @param string $message Error message. + * + * @return void + */ + private function reject_paypal_order( string $message ): void { + wp_send_json_error( [ 'error' => $message ], 403 ); } /** @@ -180,19 +380,34 @@ private function verify_entry( bool $check_nonce = true ): ?string { * @return array */ private function get_entry( bool $check_nonce = true ): array { - return [ + $data = EntryData::from_post( + [ + 'email' => $check_nonce ? [ 'give_email', 'email' ] : [ 'email', 'give_email' ], + 'first_name' => [ 'give_first', 'firstName' ], + 'last_name' => [ 'give_last', 'lastName' ], + ] + ); + + // The block route validates the canonical email from GiveWP's merged request data. + // The nonce is checked by API::verify() after this data is collected. + $emails = []; + // phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended + if ( ! $check_nonce && array_key_exists( 'email', $_REQUEST ) ) { + $emails[] = is_scalar( $_REQUEST['email'] ) + ? sanitize_text_field( wp_unslash( $_REQUEST['email'] ) ) + : ''; + } + // phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended + + $entry = [ 'nonce_name' => $check_nonce ? static::NAME : null, 'nonce_action' => $check_nonce ? static::ACTION : null, 'h-captcha-response' => Request::filter_input( INPUT_POST, 'h-captcha-response' ), - 'data' => EntryData::from_post( - [ - 'email' => [ 'give_email', 'email' ], - 'first_name' => [ 'give_first', 'firstName' ], - 'last_name' => [ 'give_last', 'lastName' ], - ] - ), - 'expected_id' => $this->get_expected_id( $this->get_form_id() ), + 'data' => $data, + 'expected_id' => $this->get_expected_id( $this->get_form_id( ! $check_nonce ) ), ]; + + return $check_nonce ? $entry : EntryData::with_emails( $entry, $emails ); } /** @@ -210,11 +425,21 @@ private function get_expected_id( int $form_id ): array { } /** - * Get form id. + * Get form id. The block donation route uses formId as its canonical form identity. + * + * @param bool $block Whether this is a block donation request. * * @return int */ - private function get_form_id(): int { + private function get_form_id( bool $block = false ): int { + if ( $block ) { + // GiveWP reads merged request data, where POST formId overrides GET formId. + // phpcs:ignore WordPress.Security.NonceVerification.Missing + return isset( $_POST['formId'] ) + ? absint( Request::filter_input( INPUT_POST, 'formId' ) ) + : absint( Request::filter_input( INPUT_GET, 'formId' ) ); + } + $form_id = absint( Request::filter_input( INPUT_POST, 'give-form-id' ) ); if ( $form_id ) { diff --git a/src/php/GiveWP/Form.php b/src/php/GiveWP/Form.php index d1700f0e7..15f2c1a8c 100644 --- a/src/php/GiveWP/Form.php +++ b/src/php/GiveWP/Form.php @@ -31,5 +31,5 @@ class Form extends Base { /** * Verify hook. */ - protected const VERIFY_HOOK = 'give_checkout_error_checks'; + protected const VERIFY_HOOK = 'give_pre_process_donation'; } diff --git a/src/php/GiveWP/PayPalGrant.php b/src/php/GiveWP/PayPalGrant.php new file mode 100644 index 000000000..2b2b5c5ae --- /dev/null +++ b/src/php/GiveWP/PayPalGrant.php @@ -0,0 +1,194 @@ + self::binding_hash( $binding ), + 'siteverify' => $siteverify, + ] + ); + + if ( ! is_string( $payload ) ) { + return false; + } + + $value = sprintf( '%010d', $expires ) . '|' . $payload; + + // A unique option_name makes grant issuance atomic; add_option() can update duplicates. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery + $stored = $wpdb->insert( + $wpdb->options, + [ + 'option_name' => self::option_name( $response ), + 'option_value' => $value, + 'autoload' => 'no', + ], + [ '%s', '%s', '%s' ] + ); + + if ( 1 !== $stored ) { + return false; + } + + if ( ! wp_next_scheduled( 'hcap_givewp_paypal_cleanup' ) ) { + wp_schedule_event( time() + HOUR_IN_SECONDS, 'hourly', 'hcap_givewp_paypal_cleanup' ); + } + + return true; + } + + /** + * Atomically consume a matching grant before final donation processing. + * + * @param string $response hCaptcha response token. + * @param array $binding Canonical donation identity. + * + * @return array|null Verified siteverify response, or null on failure. + */ + public static function redeem( string $response, array $binding ): ?array { + global $wpdb; + + if ( '' === $response ) { + return null; + } + + $name = self::option_name( $response ); + // Read the database directly so a stale option cache cannot resurrect a claimed grant. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + $value = $wpdb->get_var( + $wpdb->prepare( + "SELECT option_value FROM $wpdb->options WHERE option_name = %s", + $name + ) + ); + + if ( ! is_string( $value ) || strlen( $value ) < 12 || '|' !== $value[10] ) { + return null; + } + + $expires = substr( $value, 0, 10 ); + try { + $grant = json_decode( substr( $value, 11 ), true, 512, JSON_THROW_ON_ERROR ); + } catch ( JsonException $e ) { + $grant = null; + } + + if ( + ! is_array( $grant ) || + ! is_string( $grant['binding'] ?? null ) || + true !== ( $grant['siteverify']['success'] ?? false ) || + ! ctype_digit( $expires ) || + (int) $expires < time() || + ! hash_equals( $grant['binding'], self::binding_hash( $binding ) ) + ) { + return null; + } + + // The exact-value predicate allows only one concurrent claimant to succeed. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + $claimed = $wpdb->delete( + $wpdb->options, + [ + 'option_name' => $name, + 'option_value' => $value, + ], + [ '%s', '%s' ] + ); + + return 1 === $claimed ? $grant['siteverify'] : null; + } + + /** + * Remove at most 50 expired grants per invocation. + * + * @return void + */ + public static function cleanup(): void { + global $wpdb; + + // Bypass option cache for the bounded expired-row sweep. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + $expired = $wpdb->get_results( + $wpdb->prepare( + "SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE %s AND LEFT(option_value, 10) <= %s LIMIT 50", + $wpdb->esc_like( self::PREFIX ) . '%', + sprintf( '%010d', time() ) + ) + ); + + foreach ( $expired as $grant ) { + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + $wpdb->delete( + $wpdb->options, + [ + 'option_name' => $grant->option_name, + 'option_value' => $grant->option_value, + ], + [ '%s', '%s' ] + ); + } + } + + /** + * Derive a private option name without persisting the response token. + * + * @param string $response hCaptcha response token. + * + * @return string + */ + private static function option_name( string $response ): string { + return self::PREFIX . hash_hmac( 'sha256', $response, wp_salt() ); + } + + /** + * Hash the donor and form binding so options contain no personal data. + * + * @param array $binding Canonical donation identity. + * + * @return string + */ + private static function binding_hash( array $binding ): string { + return hash_hmac( 'sha256', wp_json_encode( $binding ), wp_salt() ); + } +} diff --git a/src/php/GravityForms/Form.php b/src/php/GravityForms/Form.php index 2f94bc02f..0bfdf87b0 100644 --- a/src/php/GravityForms/Form.php +++ b/src/php/GravityForms/Form.php @@ -493,32 +493,34 @@ private function get_entry( array $fields, int $form_id ): array { 'expected_id' => $this->get_expected_id( $form_id ), ]; - $name = []; + $name = []; + $emails = []; foreach ( $fields as $field ) { $type = $field->type; $label = $field->label; + $email = 'email' === $type ? $this->get_value( $field ) : null; + + if ( null !== $email ) { + $emails[] = $email; + } if ( ! EntryData::is_content_field_type( (string) $type ) || EntryData::has_sensitive_field( (string) $label ) ) { continue; } - $value = $this->get_value( $field ); + $value = $email ?? $this->get_value( $field ); if ( 'name' === $type ) { $name[] = $value; } - if ( 'email' === $type ) { - $entry['data']['email'] = $value; - } - EntryData::add_field( $entry['data'], (string) $label, $value, (string) $field->id ); } EntryData::add_name( $entry['data'], $name ); - return $entry; + return EntryData::with_emails( $entry, $emails ); } /** diff --git a/src/php/HTMLForms/Form.php b/src/php/HTMLForms/Form.php index 51ecf652d..e6146396a 100644 --- a/src/php/HTMLForms/Form.php +++ b/src/php/HTMLForms/Form.php @@ -13,6 +13,7 @@ namespace HCaptcha\HTMLForms; use HCaptcha\Helpers\API; +use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; /** @@ -109,10 +110,7 @@ public function add_captcha( $html, \HTML_Forms\Form $form ): string { $args = [ 'action' => self::ACTION, 'name' => self::NONCE, - 'id' => [ - 'source' => HCaptcha::get_class_source( __CLASS__ ), - 'form_id' => $form_id, - ], + 'id' => $this->get_expected_id( $form_id ), ]; return preg_replace( @@ -146,11 +144,27 @@ public function add_to_fields( \HTML_Forms\Form $form ): void { * * @return string * @noinspection PhpUnusedParameterInspection + * @noinspection PhpUndefinedFunctionInspection */ public function verify( $error_code, \HTML_Forms\Form $form, array $data ): string { $error_code = (string) $error_code; - $this->error_message = API::verify_post( self::NONCE, self::ACTION ); + $emails = []; + + foreach ( $form->get_email_fields() as $field_name ) { + $value = hf_array_get( $data, $field_name ); + + if ( is_string( $value ) ) { + $emails[] = html_entity_decode( trim( wp_unslash( $value ) ), ENT_NOQUOTES ); + } + } + + $this->error_message = API::verify_post( + self::NONCE, + self::ACTION, + $this->get_expected_id( (int) ( $form->ID ?? 0 ) ), + EntryData::with_emails( [ 'data' => EntryData::without_sensitive_fields( wp_unslash( $data ) ) ], $emails ) + ); if ( null !== $this->error_message ) { return self::HCAPTCHA_ERROR; @@ -159,6 +173,20 @@ public function verify( $error_code, \HTML_Forms\Form $form, array $data ): stri return $error_code; } + /** + * Get the native HTML Forms form identity. + * + * @param int $form_id Form id. + * + * @return array + */ + private function get_expected_id( int $form_id ): array { + return [ + 'source' => HCaptcha::get_class_source( __CLASS__ ), + 'form_id' => $form_id, + ]; + } + /** * Filter inserted post data. * Remove
    from the content. diff --git a/src/php/Helpers/API.php b/src/php/Helpers/API.php index dff0ea787..e63dc3ebb 100644 --- a/src/php/Helpers/API.php +++ b/src/php/Helpers/API.php @@ -15,10 +15,20 @@ * Class Request. */ class API { + /** + * Common field names used by integrations without a form-specific entry map. + */ + private const ENTRY_FIELD_MAP = [ + 'username' => [ 'username', 'user_login', 'log', 'edd_user_login', 'user_name' ], + 'first_name' => [ 'first_name', 'billing_first_name' ], + 'last_name' => [ 'last_name', 'billing_last_name' ], + ]; + /** * Result of the hCaptcha widget verification. * * @var string|null + * @noinspection PhpPropertyOnlyWrittenInspection */ private static ?string $result = null; @@ -26,6 +36,7 @@ class API { * Error codes of the hCaptcha widget verification. * * @var array + * @noinspection PhpPropertyOnlyWrittenInspection */ private static array $error_codes = []; @@ -36,6 +47,61 @@ class API { */ private static array $siteverify_response = []; + /** + * Context of the last completed verification in this request. + * + * @var array + */ + private static array $request_context = []; + + /** + * Guard and remote proof outcomes, independent of per-entry policy and result filters. + * + * @var array + */ + private static array $request_result = []; + + /** + * Server-owned proof from a previously verified, single-use integration request. + * + * @var array + */ + private static array $preverified_context = []; + + /** + * Recheck local policy after a trusted integration atomically redeems remote proof. + * + * @param array $entry Verification entry. + * @param array $siteverify_response Normalized, successful siteverify response. + * + * @return null|string Null on success, error message on failure. + */ + public static function verify_preverified( array $entry, array $siteverify_response ): ?string { + if ( true !== ( $siteverify_response['success'] ?? false ) ) { + return hcap_get_error_messages()['fail']; + } + + $proof = [ + 'expected_id' => (array) ( $entry['expected_id'] ?? [] ), + // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized + 'widget_id' => wp_unslash( $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] ?? '' ), + 'response' => self::get_hcaptcha_response_sanitized( $entry['h-captcha-response'] ?? null ), + 'siteverify' => self::normalize_siteverify_response( $siteverify_response ), + ]; + + if ( '' === $proof['response'] || ! is_string( $proof['widget_id'] ) || '' === $proof['widget_id'] ) { + return hcap_get_error_messages()['fail']; + } + + self::$preverified_context = $proof; + + try { + return self::verify( $entry ); + } finally { + self::$preverified_context = []; + } + } + /** * Verify hCaptcha and AntiSpam response. * @@ -44,6 +110,8 @@ class API { * @return null|string Null on success, error message on failure. */ public static function verify( array $entry = [] ): ?string { + $entry = self::add_submission_data( $entry ); + $entry = wp_parse_args( $entry, [ @@ -59,6 +127,10 @@ public static function verify( array $entry = [] ): ?string { $entry['data'] = EntryData::without_sensitive_fields( (array) $entry['data'] ); + if ( array_key_exists( 'email_addresses', $entry ) ) { + $entry = EntryData::with_emails( $entry, EntryData::get_emails( $entry ) ); + } + self::set_global_post_data( $entry ); $result = self::verify_widget_id( $entry['expected_id'] ); @@ -79,16 +151,56 @@ public static function verify( array $entry = [] ): ?string { return $result; } + + /** + * Add safe submitted fields while preserving data selected by the integration. + * + * @param array $entry Verification entry. + * + * @return array + */ + private static function add_submission_data( array $entry ): array { + $has_data = array_key_exists( 'data', $entry ); + $data = $has_data ? (array) $entry['data'] : []; + $content_fields = array_diff( array_keys( EntryData::without_sensitive_fields( $data ) ), [ 'email' ] ); + + if ( $content_fields ) { + return $entry; + } + + $submitted_data = array_key_exists( 'post_data', $entry ) + ? EntryData::from_array( (array) $entry['post_data'], self::ENTRY_FIELD_MAP ) + : EntryData::from_post( self::ENTRY_FIELD_MAP ); + + // Keep an unselected email as form content, not as the address for email policy checks. + if ( isset( $submitted_data['email'] ) ) { + $email = $submitted_data['email']; + unset( $submitted_data['email'] ); + + if ( ! EntryData::get_emails( $entry ) ) { + EntryData::add_field( $submitted_data, 'submitted_email', $email, 'email' ); + } + } + $entry['data'] = array_replace( $submitted_data, $data ); + + if ( ! $has_data && ! array_key_exists( 'email_addresses', $entry ) ) { + $entry = EntryData::with_emails( $entry, [] ); + } + + return $entry; + } /** * Verify POST and return an error message as HTML. * - * @param string $name Nonce field name. - * @param string $action Nonce action name. + * @param string $name Nonce field name. + * @param string $action Nonce action name. + * @param array $expected_id Server-selected form identity. + * @param array $entry Verification entry with native form data. * * @return null|string Null on success, error message on failure. */ - public static function verify_post_html( string $name = HCAPTCHA_NONCE, string $action = HCAPTCHA_ACTION ): ?string { - $message = self::verify_post( $name, $action ); + public static function verify_post_html( string $name = HCAPTCHA_NONCE, string $action = HCAPTCHA_ACTION, array $expected_id = [], array $entry = [] ): ?string { + $message = self::verify_post( $name, $action, $expected_id, $entry ); if ( null === $message ) { return null; @@ -111,39 +223,39 @@ public static function verify_post_html( string $name = HCAPTCHA_NONCE, string $ /** * Verify POST data. * - * @param string $name Nonce field name. - * @param string $action Nonce action name. - * @param array $post_data Post data. + * @param string $name Nonce field name. + * @param string $action Nonce action name. + * @param array $post_data Post data. + * @param array $expected_id Server-selected form identity. + * @param array $entry Verification entry with native form data. * * @return null|string Null on success, error message on failure. */ - public static function verify_post_data( string $name = HCAPTCHA_NONCE, string $action = HCAPTCHA_ACTION, array $post_data = [] ): ?string { - $entry = [ - 'nonce_name' => $name, - 'post_data' => $post_data, - ]; - - self::set_global_post_data( $entry ); + public static function verify_post_data( string $name = HCAPTCHA_NONCE, string $action = HCAPTCHA_ACTION, array $post_data = [], array $expected_id = [], array $entry = [] ): ?string { + $entry['nonce_name'] = $name; + $entry['nonce_action'] = $action; + $entry['post_data'] = $post_data; + $entry['expected_id'] = $expected_id; - $result = self::verify_post( $name, $action ); - - self::unset_global_post_data( $entry ); - - return $result; + return self::verify( $entry ); } /** * Verify POST. * - * @param string $name Nonce field name. - * @param string $action Nonce action name. + * @param string $name Nonce field name. + * @param string $action Nonce action name. + * @param array $expected_id Server-selected form identity. + * @param array $entry Verification entry with native form data. * * @return null|string Null on success, error message on failure. */ - public static function verify_post( string $name = HCAPTCHA_NONCE, string $action = HCAPTCHA_ACTION ): ?string { - $result = self::verify_nonce( $name, $action ); + public static function verify_post( string $name = HCAPTCHA_NONCE, string $action = HCAPTCHA_ACTION, array $expected_id = [], array $entry = [] ): ?string { + $entry['nonce_name'] = $name; + $entry['nonce_action'] = $action; + $entry['expected_id'] = $expected_id; - return $result ?? self::verify_request(); + return self::verify( $entry ); } /** @@ -249,6 +361,7 @@ private static function verify_widget_id( array $expected_id = [] ): ?string { return null; } + // phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh /** * Verify hCaptcha request. * @@ -260,13 +373,112 @@ private static function verify_widget_id( array $expected_id = [] ): ?string { */ public static function verify_request( $hcaptcha_response = null, array $entry = [] ): ?string { $expected_id = (array) ( $entry['expected_id'] ?? [] ); - // Do not make a remote request more than once. - if ( hcaptcha()->has_result ) { - return self::filtered_result( self::$result, self::$error_codes, $expected_id, self::$siteverify_response ); + $result = self::verify_widget_id( $expected_id ); + + if ( null !== $result ) { + return $result; + } + + $hcaptcha_response = self::get_hcaptcha_response_sanitized( $hcaptcha_response ); + $context = [ + 'expected_id' => $expected_id, + // This value is compared only, never interpreted as a trusted identity. + // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized + 'widget_id' => wp_unslash( $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] ?? '' ), + 'response' => $hcaptcha_response, + ]; + $preverified = self::$preverified_context; + + if ( $preverified && array_intersect_key( $preverified, $context ) !== $context ) { + return self::filtered_result( hcap_get_error_messages()['fail'], [ 'fail' ], $expected_id ); + } + + if ( $preverified || ! hcaptcha()->has_result || ! self::can_reuse_request_result( $context ) ) { + hcaptcha()->has_result = true; + self::$request_context = $context; + self::$request_result = self::verify_request_once( $hcaptcha_response, $entry, (bool) $preverified ); + } + + // Email policy belongs to this entry, while timing and remote proof are single-use. + $verify_email = self::$request_result['verify_email']; + + if ( $expected_id !== self::$request_context['expected_id'] ) { + $verify_email = HCaptcha::is_protection_enabled( $expected_id ); + } + + if ( $verify_email && ! self::check_disposable_email( $entry ) ) { + return self::filtered_result( + hcap_get_error_messages()['disposable-email'], + [ 'disposable-email' ], + $expected_id, + self::$request_result['siteverify'] + ); + } + + if ( self::$request_result['remote_pending'] ) { + self::$request_result = array_merge( + self::$request_result, + $preverified + ? self::verification_outcome( null, [], $preverified['siteverify'] ) + : self::process_request( self::get_params( $hcaptcha_response ) ), + [ + 'verify_email' => true, + 'remote_pending' => false, + ] + ); + } + + return self::filtered_result( + self::$request_result['result'], + self::$request_result['error_codes'], + self::$request_result['expected_id'] ?? $expected_id, + self::$request_result['siteverify'] + ); + } + // phpcs:enable Generic.Metrics.CyclomaticComplexity.TooHigh + + /** + * Reuse a result only for its form, or the same remotely verified challenge. + * + * @param array $context Current verification context. + * + * @return bool + */ + private static function can_reuse_request_result( array $context ): bool { + if ( ! self::$request_result ) { + return false; + } + + if ( $context === self::$request_context ) { + return true; } - hcaptcha()->has_result = true; - $fst_check = self::check_fst_token(); + // An exemption has no remote proof and must stay bound to its expected form. + if ( true !== ( self::$request_result['siteverify']['success'] ?? false ) ) { + return false; + } + + $previous = self::$request_context; + unset( $context['expected_id'], $previous['expected_id'] ); + + return $context === $previous; + } + + /** + * Verify one form's local guards after validating its identity. + * + * @param string $hcaptcha_response Sanitized hCaptcha response. + * @param array $entry Entry data. + * @param bool $preverified Whether a trusted integration redeemed remote proof. + * + * @return array + */ + private static function verify_request_once( string $hcaptcha_response, array $entry, bool $preverified = false ): array { + $expected_id = (array) ( $entry['expected_id'] ?? [] ); + + // Apply the form's protection settings before checking its timing token. + $protection_enabled = HCaptcha::is_protection_enabled( $expected_id ); + $fst_check = self::check_fst_token( $preverified ); /** * Filters the user IP to check whether it is denylisted. @@ -282,12 +494,12 @@ public static function verify_request( $hcaptcha_response = null, array $entry = $result = hcap_get_error_messages()['fail']; $error_codes = [ 'fail' ]; - return self::filtered_result( $result, $error_codes, $expected_id ); + return self::verification_outcome( $result, $error_codes ); } // Protection is not enabled. - if ( ! HCaptcha::is_protection_enabled() ) { - return self::filtered_result( null, [], $expected_id ); + if ( ! $protection_enabled ) { + return self::verification_outcome( null, [] ); } $settings = hcaptcha()->settings(); @@ -296,7 +508,7 @@ public static function verify_request( $hcaptcha_response = null, array $entry = if ( '' === $settings->get_site_key() || '' === $settings->get_secret_key() ) { $error_codes = [ 'missing-keys' ]; - return self::filtered_result( hcap_get_error_messages()['missing-keys'], $error_codes ); + return self::verification_outcome( hcap_get_error_messages()['missing-keys'], $error_codes ) + [ 'expected_id' => [] ]; } // Check the honeypot field. @@ -304,17 +516,14 @@ public static function verify_request( $hcaptcha_response = null, array $entry = $result = hcap_get_error_messages()['spam']; $error_codes = [ 'spam' ]; - return self::filtered_result( $result, $error_codes, $expected_id ); + return self::verification_outcome( $result, $error_codes ); } - - $hcaptcha_response_sanitized = self::get_hcaptcha_response_sanitized( $hcaptcha_response ); - // The hCaptcha response field is empty. - if ( '' === $hcaptcha_response_sanitized ) { + if ( '' === $hcaptcha_response ) { $result = hcap_get_error_messages()['empty']; $error_codes = [ 'empty' ]; - return self::filtered_result( $result, $error_codes, $expected_id ); + return self::verification_outcome( $result, $error_codes ); } // Check the form submit time token. @@ -322,19 +531,33 @@ public static function verify_request( $hcaptcha_response = null, array $entry = $result = $fst_check->get_error_message(); $error_codes = $fst_check->get_error_codes(); - return self::filtered_result( $result, $error_codes, $expected_id ); + return self::verification_outcome( $result, $error_codes ); } - if ( ! self::check_disposable_email( $entry ) ) { - $result = hcap_get_error_messages()['disposable-email']; - $error_codes = [ 'disposable-email' ]; - - return self::filtered_result( $result, $error_codes, $expected_id ); - } + $outcome = self::verification_outcome( null, [] ); + $outcome['verify_email'] = true; + $outcome['remote_pending'] = true; - $params = self::get_params( $hcaptcha_response_sanitized ); + return $outcome; + } - return self::process_request( $params, $expected_id ); + /** + * Create an unfiltered local or remote verification outcome. + * + * @param string|null $result Result. + * @param array $error_codes Error codes. + * @param array $siteverify_response Normalized remote response. + * + * @return array + */ + private static function verification_outcome( ?string $result, array $error_codes, array $siteverify_response = [] ): array { + return [ + 'result' => $result, + 'error_codes' => $error_codes, + 'siteverify' => $siteverify_response, + 'verify_email' => false, + 'remote_pending' => false, + ]; } /** @@ -367,11 +590,9 @@ public static function get_hp_name( array $arr = [] ): string { * Process request. * * @param array $params Request parameters. - * @param array $expected_id Expected hCaptcha widget id. - * - * @return string|null + * @return array */ - private static function process_request( array $params, array $expected_id ): ?string { + private static function process_request( array $params ): array { // Process API request. $raw_response = wp_remote_post( hcaptcha()->get_verify_url(), @@ -382,7 +603,7 @@ private static function process_request( array $params, array $expected_id ): ?s $result = implode( "\n", $raw_response->get_error_messages() ); $error_codes = $raw_response->get_error_codes(); - return self::filtered_result( $result, $error_codes, $expected_id ); + return self::verification_outcome( $result, $error_codes ); } $raw_body = wp_remote_retrieve_body( $raw_response ); @@ -394,7 +615,7 @@ private static function process_request( array $params, array $expected_id ): ?s $result = $fail_message; $error_codes = [ 'fail' ]; - return self::filtered_result( $result, $error_codes, $expected_id ); + return self::verification_outcome( $result, $error_codes ); } $body = Utils::json_decode_arr( $raw_body ); @@ -407,11 +628,11 @@ private static function process_request( array $params, array $expected_id ): ?s $result = $hcap_error_message ?: $fail_message; $error_codes = $hcap_error_message ? $error_codes : [ 'fail' ]; - return self::filtered_result( $result, $error_codes, $expected_id, $siteverify_response ); + return self::verification_outcome( $result, $error_codes, $siteverify_response ); } // Success. - return self::filtered_result( null, [], $expected_id, $siteverify_response ); + return self::verification_outcome( null, [], $siteverify_response ); } /** @@ -471,7 +692,7 @@ private static function verify_nonce( ?string $name = HCAPTCHA_NONCE, ?string $a // Verify nonce for logged-in users only. if ( is_user_logged_in() && - HCaptcha::is_protection_enabled() && + HCaptcha::is_protection_enabled( $expected_id ) && ! wp_verify_nonce( $nonce, $action ) ) { $errors = hcap_get_error_messages(); @@ -569,9 +790,11 @@ private static function check_honeypot_field(): bool { * The token is consumed before any later verification branch can return, so * every form submission remains single-use, including early failures. * + * @param bool $preverified Whether this is an atomically redeemed second check. + * * @return true|WP_Error */ - private static function check_fst_token() { + private static function check_fst_token( bool $preverified = false ) { if ( ! hcaptcha()->settings()->is_on( 'set_min_submit_time' ) ) { return true; } @@ -589,6 +812,10 @@ private static function check_fst_token() { $min_submit_time = hcaptcha()->settings()->get( 'min_submit_time' ); + if ( $preverified ) { + return apply_filters( 'hcap_verify_fst_token', true ); + } + /** * Filters the result of the Form Submit Time token verification. * diff --git a/src/php/Helpers/EntryData.php b/src/php/Helpers/EntryData.php index b0ca59ed1..d23747d19 100644 --- a/src/php/Helpers/EntryData.php +++ b/src/php/Helpers/EntryData.php @@ -11,6 +11,71 @@ * Maps submitted, non-secret form fields to anti-spam entry data. */ class EntryData { + /** + * Attach email addresses selected and normalized by the native form handler. + * + * The top-level list is separate from submitted field names and labels. + * An explicit empty list identifies an email-free form, even if a text field is named "email". + * + * @param array $entry Verification entry. + * @param array $emails Native email addresses, already unslashed and normalized. + * + * @return array + */ + public static function with_emails( array $entry, array $emails ): array { + $entry['email_addresses'] = self::valid_emails( $emails ); + $entry['data'] = (array) ( $entry['data'] ?? [] ); + unset( $entry['data']['email'] ); + + if ( $entry['email_addresses'] ) { + $entry['data']['email'] = $entry['email_addresses'][0]; + } + + return $entry; + } + + /** + * Get authoritative addresses, with the previous scalar contract as fallback. + * + * @param array $entry Verification entry. + * + * @return string[] + */ + public static function get_emails( array $entry ): array { + if ( array_key_exists( 'email_addresses', $entry ) ) { + return is_array( $entry['email_addresses'] ) ? self::valid_emails( $entry['email_addresses'] ) : []; + } + + $email = $entry['data']['email'] ?? ''; + + return is_string( $email ) && is_email( $email ) ? [ $email ] : []; + } + + /** + * Retain valid scalar addresses without guessing aliases or altering native values. + * + * @param array $emails Native email addresses. + * + * @return string[] + */ + private static function valid_emails( array $emails ): array { + $valid = []; + + foreach ( $emails as $email ) { + if ( ! is_string( $email ) ) { + continue; + } + + $separator = strrpos( $email, '@' ); + + if ( false !== $separator && $separator > 0 && $separator < strlen( $email ) - 1 && ! in_array( $email, $valid, true ) ) { + $valid[] = $email; + } + } + + return $valid; + } + /** * Remove fields identified as credentials, verification tokens, or payment data. * @@ -42,7 +107,7 @@ public static function without_sensitive_fields( array $data ): array { * @return array */ public static function for_antispam( array $entry ): array { - unset( $entry['post_data'] ); + unset( $entry['post_data'], $entry['email_addresses'] ); return self::without_sensitive_fields( $entry ); } @@ -53,6 +118,7 @@ public static function for_antispam( array $entry ): array { * @param string $key Field name. * * @return bool + * @noinspection UnnecessaryCastingInspection */ public static function is_sensitive_field( string $key ): bool { if ( preg_match( '/password|passwd|passcode|pwd|token|nonce|secret|captcha|csrf|cvv|cvc|csc|iban|swift|routing|stripe|paypal|authorization|authentication/i', $key ) ) { diff --git a/src/php/Helpers/FormSubmitTime.php b/src/php/Helpers/FormSubmitTime.php index edd9e5b14..9ffda1996 100644 --- a/src/php/Helpers/FormSubmitTime.php +++ b/src/php/Helpers/FormSubmitTime.php @@ -121,6 +121,7 @@ public function enqueue_scripts(): void { ); DelayedScript::enqueue( self::HANDLE ); + $post_id = (string) absint( get_queried_object_id() ); wp_print_inline_script_tag( @@ -131,6 +132,11 @@ public function enqueue_scripts(): void { 'issueTokenNonce' => wp_create_nonce( self::ISSUE_TOKEN_ACTION ), 'issueTokenContext' => $this->context_from_post_id( $post_id ), 'postId' => $post_id, + 'messages' => [ + 'loading' => __( 'Preparing the form. Please wait.', 'hcaptcha-for-forms-and-more' ), + 'error' => __( 'Unable to prepare the form. Please check your connection and try submitting again.', 'hcaptcha-for-forms-and-more' ), + 'rateLimited' => hcap_get_error_messages()['fst-rate-limited'], + ], ] ) . ';' ); @@ -150,7 +156,21 @@ public function enqueue_scripts(): void { */ public function issue_token(): void { if ( ! check_ajax_referer( self::ISSUE_TOKEN_ACTION, 'nonce', false ) ) { - wp_send_json_error(); + $post_id = $this->validate_issue_context(); + + if ( is_wp_error( $post_id ) ) { + $this->send_issue_error( $post_id->get_error_code(), 400 ); + + return; + } + + wp_send_json_error( + [ + 'code' => 'fst-invalid-nonce', + 'nonce' => wp_create_nonce( self::ISSUE_TOKEN_ACTION ), + ], + 403 + ); return; // For testing purposes. } @@ -236,7 +256,12 @@ public function issue_token(): void { */ $token = (string) apply_filters( 'hcap_fst_token', $token ); - wp_send_json_success( [ 'token' => $token ] ); + wp_send_json_success( + [ + 'token' => $token, + 'ttl' => $ttl, + ] + ); } /** @@ -255,6 +280,13 @@ public function issue_token(): void { public function verify_token( int $min_submit_time, bool $delete_nonce = true ) { $token = Request::filter_input( INPUT_POST, 'hcap_fst_token' ); + if ( '' === $token ) { + return new WP_Error( + 'fst-missing-token', + __( 'Unable to prepare the form. Please check your connection and try submitting again.', 'hcaptcha-for-forms-and-more' ) + ); + } + if ( self::RATE_LIMITED_TOKEN === $token ) { return hcap_get_wp_error( 'fst-rate-limited' ); } diff --git a/src/php/Helpers/HCaptcha.php b/src/php/Helpers/HCaptcha.php index 2f6eb7c2a..8b04e1902 100644 --- a/src/php/Helpers/HCaptcha.php +++ b/src/php/Helpers/HCaptcha.php @@ -16,7 +16,7 @@ use HCaptcha\Helpers\Minify\JS; use HCaptcha\Settings\General; use HCaptcha\Settings\Integrations; -use HCaptcha\Settings\PluginSettingsBase; +use HCaptcha\Settings\SettingsStorage; use WP_Error; /** @@ -132,6 +132,7 @@ public static function form_display( array $args = [] ): void { */ 'id' => [], 'protect' => true, // Protection status. When true, hCaptcha should be added. + 'mandatory' => false, // Render the challenge when the verifier cannot bind a per-form exemption. ] ); @@ -159,17 +160,7 @@ public static function form_display( array $args = [] ): void { hcaptcha()->form_shown = true; - /** - * Filters the protection status of a form. - * - * @param bool $value The protection status of a form. - * @param string[] $source The source of the form (plugin, theme, WordPress Core). - * @param int|string $form_id Form id. - */ - if ( - ! $args['protect'] || - ! apply_filters( 'hcap_protect_form', true, $args['id']['source'], $args['id']['form_id'] ) - ) { + if ( ! self::should_render_challenge( $args ) ) { return; } @@ -197,6 +188,30 @@ class="" self::honeypot_display( self::get_honeypot_override( $args ) ); } + /** + * Match rendering to whether the verifier can honor a per-form exemption. + * + * @param array $args Validated form arguments. + * + * @return bool + */ + private static function should_render_challenge( array $args ): bool { + if ( ! $args['protect'] && ! $args['mandatory'] ) { + return false; + } + + /** + * Filters the protection status of a form. + * + * @param bool $value The protection status of a form. + * @param string[] $source The source of the form (plugin, theme, WordPress Core). + * @param int|string $form_id Form id. + */ + $protect = apply_filters( 'hcap_protect_form', true, $args['id']['source'], $args['id']['form_id'] ); + + return $args['mandatory'] || $protect; + } + /** * Get a honeypot override from form arguments. * @@ -287,7 +302,8 @@ private static function validate_args( array $args ): array { unset( $args['honeypot'] ); } - $args['protect'] = filter_var( $args['protect'], FILTER_VALIDATE_BOOLEAN ); + $args['protect'] = filter_var( $args['protect'], FILTER_VALIDATE_BOOLEAN ); + $args['mandatory'] = filter_var( $args['mandatory'], FILTER_VALIDATE_BOOLEAN ); return $args; } @@ -618,21 +634,40 @@ public static function check_signature( string $class_name, $form_id = null ): ? * Whether form protection is enabled/disabled via hCaptcha widget id. * * Return false (protection disabled) in only one case: - * when $_POST['hcaptcha-widget-id'] contains encoded id with proper hash, - * and hcap_protect_form filter confirms that the form referenced in widget id is not protected. + * when the signed submitted identity matches the server-selected form, + * and hcap_protect_form confirms that this form is not protected. + * Callers without an expected identity always require protection. + * + * @param array $expected_id Server-selected form identity. * * @return bool */ - public static function is_protection_enabled(): bool { + public static function is_protection_enabled( array $expected_id = [] ): bool { $info = self::decode_id_info(); $id = $info['id']; - return ! ( - $info['valid'] && - /** This filter is documented above. */ - ! apply_filters( 'hcap_protect_form', true, $id['source'], $id['form_id'] ) - ); + if ( ! $info['valid'] ) { + return true; + } + + // Preserve the filter's form-specific honeypot and timing side effects. + /** This filter is documented above. */ + $protect = (bool) apply_filters( 'hcap_protect_form', true, $id['source'], $id['form_id'] ); + unset( $id['honeypot'] ); + + // The default decoded identity is not evidence of a submitted signed widget. + // phpcs:ignore WordPress.Security.NonceVerification.Missing + if ( ! $expected_id || empty( $_POST[ self::HCAPTCHA_WIDGET_ID ] ) ) { + return true; + } + + $expected_id = [ + 'source' => (array) ( $expected_id['source'] ?? [] ), + 'form_id' => $expected_id['form_id'] ?? 0, + ]; + + return $expected_id !== $id || $protect; } /** @@ -1390,7 +1425,8 @@ public static function save_license_level(): void { $live_mode = static function () { return General::MODE_LIVE; }; - $option = (array) get_option( PluginSettingsBase::OPTION_NAME, [] ); + $network = SettingsStorage::is_network_wide(); + $option = SettingsStorage::get( $network ); // The saved license belongs to the stored Live credentials, regardless of the active test mode. add_filter( 'hcap_mode', $live_mode, PHP_INT_MAX ); @@ -1399,9 +1435,7 @@ public static function save_license_level(): void { $settings = hcaptcha()->settings(); if ( '' === $settings->get_site_key() || '' === $settings->get_secret_key() ) { - $option['license'] = 'free'; - - update_option( PluginSettingsBase::OPTION_NAME, $option ); + SettingsStorage::update( [ 'license' => 'free' ], [], $network ); return; } @@ -1424,12 +1458,7 @@ public static function save_license_level(): void { $license = 'enterprise'; } - $option['license'] = $license; - - // Save license level in settings. - // We cannot use hcaptcha->settings()->update(...) here, as it cannot update non-existing key. - // The 'license' key does not exist initially. - // The update_options() works properly on multisite due to our pre_update_option hook. - update_option( PluginSettingsBase::OPTION_NAME, $option ); + // The derived license belongs to the same active credentials, without a scope transition. + SettingsStorage::update( [ 'license' => $license ], [], $network ); } } diff --git a/src/php/Helpers/Playground.php b/src/php/Helpers/Playground.php index 64b269d2b..a17b55a10 100644 --- a/src/php/Helpers/Playground.php +++ b/src/php/Helpers/Playground.php @@ -983,7 +983,6 @@ private function setup_settings(): void { $settings['honeypot'] = [ 'on' ]; $settings['set_min_submit_time'] = [ 'on' ]; $settings['min_submit_time'] = '2'; - $settings['show_antispam_coverage'] = [ 'on' ]; update_option( 'hcaptcha_settings', $settings ); } diff --git a/src/php/Helpers/Request.php b/src/php/Helpers/Request.php index d6dc65c27..2bda8317d 100644 --- a/src/php/Helpers/Request.php +++ b/src/php/Helpers/Request.php @@ -85,7 +85,7 @@ public static function is_rest(): bool { $rest_route = self::filter_input( INPUT_GET, 'rest_route' ); $script_name = self::filter_input( INPUT_SERVER, 'SCRIPT_NAME' ); - if ( 0 === strpos( $rest_route, '/' ) && 'index.php' === basename( $script_name ) ) { + if ( is_string( $rest_route ) && is_string( $script_name ) && 0 === strpos( $rest_route, '/' ) && 'index.php' === basename( $script_name ) ) { return true; } @@ -101,12 +101,19 @@ public static function is_rest(): bool { // Case #4. $current_url = (string) wp_parse_url( add_query_arg( [] ), PHP_URL_PATH ); - $rest_url = wp_parse_url( trailingslashit( rest_url() ), PHP_URL_PATH ); + $rest_url = rest_url(); + $rest_path = rtrim( (string) wp_parse_url( $rest_url, PHP_URL_PATH ), '/' ); + $rest_query = wp_parse_url( $rest_url, PHP_URL_QUERY ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $wp_rewrite = $initial_wp_rewrite; - return 0 === strpos( $current_url, $rest_url ); + // Plain permalinks route REST via the query, not the /index.php path. + if ( '' === $rest_path || ( is_string( $rest_query ) && preg_match( '/(?:^|&)rest_route=/', $rest_query ) ) ) { + return false; + } + + return $current_url === $rest_path || 0 === strpos( $current_url, $rest_path . '/' ); } /** @@ -230,7 +237,14 @@ public static function is_ip_in_range( string $ip, string $range ): bool { $ip_dec = @inet_pton( $ip ); // phpcs:enable WordPress.PHP.NoSilencedErrors.Discouraged - return ( $ip_dec >= $start_dec && $ip_dec <= $end_dec ); + if ( + false === $start_dec || false === $end_dec || false === $ip_dec || + strlen( $ip_dec ) !== strlen( $start_dec ) || strlen( $ip_dec ) !== strlen( $end_dec ) + ) { + return false; + } + + return strcmp( $ip_dec, $start_dec ) >= 0 && strcmp( $ip_dec, $end_dec ) <= 0; } // Single IP. diff --git a/src/php/IcegramExpress/Form.php b/src/php/IcegramExpress/Form.php index 0a9875e3b..45ea25dbe 100644 --- a/src/php/IcegramExpress/Form.php +++ b/src/php/IcegramExpress/Form.php @@ -14,6 +14,7 @@ use ES_Forms_Table; use HCaptcha\DelayedScript\DelayedScript; use HCaptcha\Helpers\API; +use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Main; @@ -176,7 +177,18 @@ public function verify( $result, array $form ): array { return $result; } - $error_message = API::verify_request(); + $form_id = isset( $form['esfpx_form_id'] ) && is_scalar( $form['esfpx_form_id'] ) ? (int) $form['esfpx_form_id'] : 0; + $expected_id = $this->get_args( $form_id )['id']; + $email = isset( $form['esfpx_email'] ) && is_scalar( $form['esfpx_email'] ) ? strtolower( sanitize_email( (string) $form['esfpx_email'] ) ) : ''; + $error_message = API::verify( + EntryData::with_emails( + [ + 'expected_id' => $expected_id, + 'data' => EntryData::from_array( $form, [] ), + ], + [ $email ] + ) + ); if ( null !== $error_message ) { $error_code = 'hcaptcha_error'; @@ -298,9 +310,10 @@ private function show_in_popup( int $form_id, ?array $attr ): bool { */ private function get_args( int $form_id = 0 ): array { return [ - 'action' => self::ACTION, - 'name' => self::NONCE, - 'id' => [ + 'mandatory' => $form_id <= 0, + 'action' => self::ACTION, + 'name' => self::NONCE, + 'id' => [ 'source' => HCaptcha::get_class_source( static::class ), 'form_id' => $form_id, ], diff --git a/src/php/Jetpack/Base.php b/src/php/Jetpack/Base.php index bc80e4f4d..0f6410848 100644 --- a/src/php/Jetpack/Base.php +++ b/src/php/Jetpack/Base.php @@ -5,10 +5,17 @@ * @package hcaptcha-wp */ +// phpcs:disable Generic.Commenting.DocComment.MissingShort +/** @noinspection PhpUndefinedClassInspection */ +/** @noinspection PhpUndefinedNamespaceInspection */ +// phpcs:enable Generic.Commenting.DocComment.MissingShort + namespace HCaptcha\Jetpack; +use Automattic\Jetpack\Forms\ContactForm\Contact_Form; use HCaptcha\DelayedScript\DelayedScript; use HCaptcha\Helpers\API; +use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Helpers\Request; use HCaptcha\Helpers\Utils; @@ -59,6 +66,20 @@ abstract class Base { */ protected ?string $error_form_hash = null; + /** + * Form hashes authenticated by Jetpack JWTs in this request. + * + * @var array + */ + private array $jwt_form_hashes = []; + + /** + * Forms selected by Jetpack's verified JWT route in this request. + * + * @var array + */ + private array $jwt_forms = []; + /** * Constructor. */ @@ -82,6 +103,7 @@ private function init_hooks(): void { add_filter( 'widget_text', 'do_shortcode' ); add_filter( 'jetpack_contact_form_is_spam', [ $this, 'verify' ], 100, 2 ); + add_filter( 'jetpack_forms_extra_webhooks', [ $this, 'capture_form_hash' ], PHP_INT_MAX, 2 ); add_action( 'wp_head', [ $this, 'print_inline_styles' ] ); @@ -110,18 +132,26 @@ abstract public function add_hcaptcha( $content ): string; /** * Verify hCaptcha answer from the Jetpack Contact Form. * - * @param bool|mixed $is_spam Is spam. + * @param bool|mixed $is_spam Is spam. + * @param array|mixed $form_data Jetpack's computed spam data. * * @return bool|WP_Error|mixed */ - public function verify( $is_spam = false ) { - $this->error_message = API::verify( $this->get_entry() ); + public function verify( $is_spam = false, $form_data = [] ) { + $submitted_hash = $this->get_submitted_form_hash(); + $verified_hash = $this->get_verified_jwt_form_hash(); + + if ( null !== $verified_hash && ( '' === $verified_hash || ! hash_equals( $verified_hash, $submitted_hash ?? '' ) ) ) { + $this->error_message = hcap_get_error_messages()['bad-signature']; + } else { + $this->error_message = API::verify( $this->get_entry( is_array( $form_data ) ? $form_data : [] ) ); + } if ( null === $this->error_message ) { return $is_spam; } - $this->error_form_hash = $this->get_submitted_form_hash(); + $this->error_form_hash = $verified_hash ?: $submitted_hash; $error = new WP_Error(); @@ -131,6 +161,53 @@ public function verify( $is_spam = false ) { return $error; } + /** + * Retain the hash of the form selected by Jetpack's verified JWT route. + * + * @param mixed $webhooks Extra webhook configurations. + * @param mixed $form Jetpack form selected for this submission. + * + * @return mixed + */ + public function capture_form_hash( $webhooks, $form ) { + $jwt = Request::filter_input( INPUT_POST, 'jetpack_contact_form_jwt' ); + + if ( + $form instanceof Contact_Form && + $form->has_verified_jwt && + is_string( $form->hash ) && + '' !== $form->hash && + is_string( $jwt ) && + '' !== $jwt + ) { + $jwt_key = hash( 'sha256', $jwt ); + $this->jwt_form_hashes[ $jwt_key ] = $form->hash; + $this->jwt_forms[ $jwt_key ] = $form; + } + + return $webhooks; + } + + /** + * Get the hash Jetpack authenticated for the submitted JWT. + * + * Null means a legacy submission without a JWT; an empty string fails closed. + * + * @return string|null + */ + private function get_verified_jwt_form_hash(): ?string { + // phpcs:ignore WordPress.Security.NonceVerification.Missing + if ( ! isset( $_POST['jetpack_contact_form_jwt'] ) ) { + return null; + } + + $jwt = Request::filter_input( INPUT_POST, 'jetpack_contact_form_jwt' ); + + return is_string( $jwt ) && '' !== $jwt + ? $this->jwt_form_hashes[ hash( 'sha256', $jwt ) ] ?? '' + : ''; + } + /** * Print error message. * @@ -432,9 +509,11 @@ protected function is_editing_jetpack_form_post(): bool { /** * Get entry. * + * @param array $form_data Jetpack's computed spam data. + * * @return array */ - private function get_entry(): array { + private function get_entry( array $form_data = [] ): array { $contact_form_id = Request::filter_input( INPUT_POST, 'contact-form-id' ); $form_id = 'g' . $contact_form_id; $post_id = (int) $contact_form_id; @@ -467,9 +546,102 @@ private function get_entry(): array { $entry['data'][ $data_key ] = $value; } + $form = $this->get_native_form(); + + if ( null === $form && ! array_key_exists( 'comment_author_email', $form_data ) ) { + return $entry; + } + + $entry = EntryData::with_emails( $entry, $this->get_native_emails( $form, $form_data ) ); + unset( $entry['email'] ); + + if ( $entry['email_addresses'] ) { + $entry['email'] = $entry['email_addresses'][0]; + } + return $entry; } + /** + * Get the same form instance Jetpack selected for this submission. + * + * @return Contact_Form|null + * @noinspection UnnecessaryCastingInspection + */ + private function get_native_form(): ?Contact_Form { + $verified_hash = $this->get_verified_jwt_form_hash(); + + if ( null !== $verified_hash ) { + $jwt = Request::filter_input( INPUT_POST, 'jetpack_contact_form_jwt' ); + + return is_string( $jwt ) ? $this->jwt_forms[ hash( 'sha256', $jwt ) ] ?? null : null; + } + + $hash = $this->get_submitted_form_hash(); + $hash = null !== $hash ? (string) preg_replace( '/[^\da-f]/i', '', $hash ) : null; + $form = null !== $hash ? Contact_Form::$forms[ $hash ] ?? null : null; + + // Jetpack can rebuild a legacy form from post meta and then select $last + // even when the rebuilt hash differs from the submitted hash. + if ( ! $form && Contact_Form::$last instanceof Contact_Form ) { + $form = Contact_Form::$last; + } + + return $form instanceof Contact_Form ? $form : null; + } + + /** + * Read every visible email field from Jetpack's selected form schema. + * + * @param Contact_Form|null $form Native form, if available. + * @param array $form_data Jetpack's computed spam data. + * + * @return string[] + */ + private function get_native_emails( ?Contact_Form $form, array $form_data ): array { + $author_email = $form_data['comment_author_email'] ?? ''; + + if ( null === $form ) { + return is_string( $author_email ) ? [ $author_email ] : []; + } + + $field_ids = $form->get_field_ids(); + $visibility = method_exists( $form, 'get_resolved_field_visibility' ) ? $form->get_resolved_field_visibility() : []; + $emails = []; + + foreach ( $field_ids['all'] as $field_id ) { + if ( false === ( $visibility[ $field_id ] ?? true ) || 'email' !== $form->fields[ $field_id ]->get_attribute( 'type' ) ) { + continue; + } + + $this->append_native_email_values( $emails, (string) $field_id, $field_ids['email'] ?? null, $author_email ); + } + + return $emails; + } + + /** + * Include both Jetpack's filtered author email and its stored field value. + * + * @param array $emails Native email list. + * @param string $field_id Native field ID. + * @param string|null $author_field_id Native author email field ID. + * @param mixed $author_email Jetpack's computed author email. + * + * @return void + */ + private function append_native_email_values( array &$emails, string $field_id, ?string $author_field_id, $author_email ): void { + if ( $author_field_id === $field_id && is_string( $author_email ) ) { + $emails[] = $author_email; + } + + $value = Request::filter_input( INPUT_POST, $field_id ); + + if ( is_string( $value ) ) { + $emails[] = $value; + } + } + /** * Get expected hCaptcha widget id. * diff --git a/src/php/Kadence/AdvancedForm.php b/src/php/Kadence/AdvancedForm.php index 688266b9d..7830bf914 100644 --- a/src/php/Kadence/AdvancedForm.php +++ b/src/php/Kadence/AdvancedForm.php @@ -55,15 +55,6 @@ public function init_hooks(): void { add_filter( 'render_block', [ $this, 'render_block' ], 10, 3 ); add_filter( 'render_block_data', [ $this, 'render_block_data' ] ); - if ( Request::is_frontend() || Request::is_post() ) { - add_filter( - 'block_parser_class', - static function () { - return BlockParser::class; - } - ); - } - if ( Request::is_frontend() ) { add_action( 'wp_print_footer_scripts', [ $this, 'enqueue_scripts' ], 9 ); add_filter( 'script_loader_tag', [ $this, 'add_type_module' ], 10, 3 ); @@ -106,6 +97,7 @@ static function () use ( $settings ) { * @return string * @noinspection PhpUnusedParameterInspection * @noinspection HtmlUnknownAttribute + * @noinspection UnnecessaryCastingInspection */ public function render_block( $block_content, array $block, WP_Block $instance ): string { $block_content = (string) $block_content; @@ -288,23 +280,26 @@ private function get_entry( array $form_data ): array { $blocks = parse_blocks( $post->post_content ?? '' ); $fields = $this->get_fields( $blocks ); + $emails = []; foreach ( $fields as $field ) { - $this->add_form_field( $entry['data'], $field ); + $this->add_form_field( $entry['data'], $field, $emails, $form_data ); } - return $entry; + return EntryData::with_emails( $entry, $emails ); } /** * Add one submitted advanced form field to the entry. * - * @param array $data Entry data. - * @param array $field Form block. + * @param array $data Entry data. + * @param array $field Form block. + * @param array $emails Native email addresses. + * @param array $form_data Raw native submission data. * * @return void */ - private function add_form_field( array &$data, array $field ): void { + private function add_form_field( array &$data, array $field, array &$emails, array $form_data ): void { if ( ! preg_match( '#kadence/advanced-form-(.+)#', $field['blockName'] ?? '', $matches ) ) { return; } @@ -315,26 +310,29 @@ private function add_form_field( array &$data, array $field ): void { return; } - $attrs = wp_parse_args( + $attrs = wp_parse_args( $field['attrs'] ?? [], [ - 'label' => '', - 'uniqueID' => '', + 'label' => '', + 'uniqueID' => '', + 'inputName' => '', ] ); - $label = (string) $attrs['label']; - $unique_id = (string) $attrs['uniqueID']; + $label = (string) $attrs['label']; + $unique_id = (string) $attrs['uniqueID']; + $input_name = (string) $attrs['inputName']; + $value = Request::filter_input( INPUT_POST, $input_name ?: "field$unique_id" ); + + // Match Kadence sanitize_field(): email is normalized directly from raw POST, without text cleanup or unslashing. + $email = $form_data[ $input_name ?: "field$unique_id" ] ?? ''; + if ( 'email' === $type && is_string( $email ) ) { + $emails[] = sanitize_email( trim( $email ) ); + } if ( EntryData::has_sensitive_field( $label, $unique_id ) ) { return; } - $value = Request::filter_input( INPUT_POST, "field$unique_id" ); - - if ( 'email' === $type ) { - $data['email'] = $value; - } - EntryData::add_field( $data, $label, $value, $unique_id ); } @@ -360,36 +358,13 @@ private function get_expected_id( int $form_id ): array { * @return array */ private function get_fields( array $blocks ): array { - $form_id = Request::filter_input( INPUT_POST, '_kb_adv_form_post_id' ); - $form = $this->get_form( $blocks, $form_id ); - - return $this->get_form_fields( $form['innerBlocks'] ?? [] ); - } - - /** - * Get Kadence form. - * - * @param array $blocks Blocks. - * @param string $block_id Block ID. - * - * @return array - */ - private function get_form( array $blocks, string $block_id ): array { - foreach ( $blocks as $block ) { - $current_block_id = $block['attrs']['uniqueID'] ?? ''; - - if ( 'kadence/advanced-form' === $block['blockName'] && 0 === strpos( $current_block_id, $block_id ) ) { - return $block; - } + $form = $blocks[0] ?? []; - $form = $this->get_form( $block['innerBlocks'] ?? [], $block_id ); - - if ( $form ) { - return $form; - } + if ( 'kadence/advanced-form' !== ( $form['blockName'] ?? '' ) ) { + return []; } - return []; + return $this->get_form_fields( $form['innerBlocks'] ?? [] ); } /** @@ -400,23 +375,21 @@ private function get_form( array $blocks, string $block_id ): array { * @return array */ private function get_form_fields( array $blocks ): array { - $form_fields = []; - $inner_fields = []; + $form_fields = []; foreach ( $blocks as $block ) { - if ( 0 === strpos( $block['blockName'], 'kadence/advanced-form' ) ) { - $form_fields[] = $block; + $inner_blocks = $block['innerBlocks'] ?? []; + if ( $inner_blocks ) { + $form_fields = array_merge( $form_fields, $this->get_form_fields( $inner_blocks ) ); continue; } - $inner_blocks = $block['innerBlocks'] ?? []; - - if ( $inner_blocks ) { - $inner_fields[] = $this->get_form_fields( $inner_blocks ); + if ( 0 === strpos( (string) ( $block['blockName'] ?? '' ), 'kadence/advanced-form-' ) ) { + $form_fields[] = $block; } } - return array_merge( $form_fields, ...$inner_fields ); + return $form_fields; } } diff --git a/src/php/Kadence/Base.php b/src/php/Kadence/Base.php index c35c3cbc5..0ec792e9c 100644 --- a/src/php/Kadence/Base.php +++ b/src/php/Kadence/Base.php @@ -7,6 +7,8 @@ namespace HCaptcha\Kadence; +use HCaptcha\Helpers\Request; + /** * Class Base. */ @@ -26,6 +28,19 @@ class Base { */ public function init_hooks(): void { add_action( 'wp_print_footer_scripts', [ $this, 'dequeue_kadence_captcha_api' ], 8 ); + + $submit_actions = [ 'kb_process_ajax_submit', 'kb_process_advanced_form_submit' ]; + $is_submission = in_array( Request::filter_input( INPUT_POST, 'action' ), $submit_actions, true ) || + in_array( Request::filter_input( INPUT_GET, 'action' ), $submit_actions, true ); + + if ( $is_submission || Request::is_frontend() ) { + add_filter( + 'block_parser_class', + static function () { + return BlockParser::class; + } + ); + } } /** @@ -39,15 +54,19 @@ public function dequeue_kadence_captcha_api(): void { } $handles = [ - 'kadence-blocks-recaptcha', - 'kadence-blocks-google-recaptcha-v2', - 'kadence-blocks-google-recaptcha-v3', - 'kadence-blocks-hcaptcha', + 'form' => [ 'kadence-blocks-google-recaptcha-v2', 'kadence-blocks-google-recaptcha-v3' ], + 'advanced_form' => [ 'kadence-blocks-recaptcha', 'kadence-blocks-hcaptcha' ], ]; - foreach ( $handles as $handle ) { - wp_dequeue_script( $handle ); - wp_deregister_script( $handle ); + foreach ( $handles as $module => $module_handles ) { + if ( ! hcaptcha()->settings()->is( 'kadence_status', $module ) ) { + continue; + } + + foreach ( $module_handles as $handle ) { + wp_dequeue_script( $handle ); + wp_deregister_script( $handle ); + } } } } diff --git a/src/php/Kadence/BlockParser.php b/src/php/Kadence/BlockParser.php index 02637d7ce..aa44756be 100644 --- a/src/php/Kadence/BlockParser.php +++ b/src/php/Kadence/BlockParser.php @@ -34,6 +34,13 @@ class BlockParser extends WP_Block_Parser { public function parse( $document ): array { $output = parent::parse( $document ); + // Runtime CAPTCHA replacement must never change the configuration being saved. + foreach ( [ 'pre_kses', 'content_save_pre', 'content_filtered_save_pre', 'excerpt_save_pre' ] as $filter ) { + if ( doing_filter( $filter ) ) { + return $output; + } + } + foreach ( $output as &$block ) { $this->process_block( $block ); } @@ -79,6 +86,10 @@ private function process_block( array &$block ): void { * @return void */ private function process_form_block( array &$block ): void { + if ( ! hcaptcha()->settings()->is( 'kadence_status', 'form' ) ) { + return; + } + // Disable reCAPTCHA. $block['attrs']['recaptcha'] = false; } @@ -91,6 +102,10 @@ private function process_form_block( array &$block ): void { * @return void */ private function process_advanced_form_block( array &$block ): void { + if ( ! hcaptcha()->settings()->is( 'kadence_status', 'advanced_form' ) ) { + return; + } + self::$form_id = (int) ( $block['attrs']['id'] ?? 0 ); if ( ! ( isset( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) ) { diff --git a/src/php/Kadence/Form.php b/src/php/Kadence/Form.php index 8495728d4..4cfe78412 100644 --- a/src/php/Kadence/Form.php +++ b/src/php/Kadence/Form.php @@ -143,8 +143,11 @@ public static function enqueue_scripts(): void { * @return array */ private function get_entry( array $form_data ): array { - $post_id = isset( $form_data['_kb_form_post_id'] ) ? (int) $form_data['_kb_form_post_id'] : 0; - $post = get_post( $post_id ); + // Match Kadence's post selector before binding the widget and its fields. + $raw_post_id = $form_data['_kb_form_post_id'] ?? ''; + $native_post_id = is_scalar( $raw_post_id ) ? sanitize_text_field( wp_unslash( (string) $raw_post_id ) ) : ''; + $post_id = absint( $native_post_id ); + $post = get_post( $post_id ); $entry = [ 'h-captcha-response' => $form_data['h-captcha-response'] ?? '', @@ -153,8 +156,9 @@ private function get_entry( array $form_data ): array { 'expected_id' => $this->get_expected_id( $post_id ), ]; - $blocks = parse_blocks( $post->post_content ?? '' ); + $blocks = $this->get_form_blocks( $native_post_id ); $fields = $this->get_fields( $blocks ); + $emails = []; foreach ( $fields as $id => $field ) { $field = wp_parse_args( @@ -168,6 +172,11 @@ private function get_entry( array $form_data ): array { $type = $field['type']; $label = (string) $field['label']; + $value = $form_data[ "kb_field_$id" ] ?? ''; + + if ( 'email' === $type && is_string( $value ) ) { + $emails[] = sanitize_email( trim( wp_unslash( $value ) ) ); + } if ( ! array_key_exists( "kb_field_$id", $form_data ) || @@ -177,16 +186,49 @@ private function get_entry( array $form_data ): array { continue; } - $value = $form_data[ "kb_field_$id" ] ?? ''; + EntryData::add_field( $entry['data'], $label, $value, (string) $id ); + } - if ( 'email' === $type ) { - $entry['data']['email'] = $value; - } + return EntryData::with_emails( $entry, $emails ); + } - EntryData::add_field( $entry['data'], $label, $value, (string) $id ); + /** + * Resolve the post or block widget selected by native Kadence processing. + * + * @param string $post_id Native post or widget identifier. + * + * @return array + */ + private function get_form_blocks( string $post_id ): array { + if ( false === strpos( $post_id, 'block' ) ) { + $post = get_post( absint( $post_id ) ); + + return parse_blocks( $post->post_content ?? '' ); + } + + $widgets = (array) get_option( 'widget_block', [] ); + + if ( false === strpos( $post_id, 'block-unknown' ) ) { + $widget_id = absint( preg_replace( '/[^0-9]/', '', $post_id ) ); + + return parse_blocks( $widgets[ $widget_id ]['content'] ?? '' ); + } + + $form_id = Request::filter_input( INPUT_POST, '_kb_form_id' ); + + if ( ! is_string( $form_id ) ) { + return []; + } + + foreach ( $widgets as $widget ) { + $content = is_array( $widget ) ? ( $widget['content'] ?? '' ) : ''; + + if ( is_string( $content ) && false !== strpos( $content, ''; /** * Constructor. @@ -28,6 +34,86 @@ public function __construct() { */ private function init_hooks(): void { add_filter( 'do_shortcode_tag', [ $this, 'do_shortcode_tag' ], 10, 4 ); + add_action( 'woocommerce_order_tracking_form', [ $this, 'display_form' ] ); + add_filter( 'woocommerce_shortcode_order_tracking_order_id', [ $this, 'verify_tracking_request' ] ); + add_filter( 'hcap_auto_verify_entry', [ $this, 'add_email' ] ); + } + + /** + * Display the widget in native order tracking forms, including direct renders. + * + * @return void + */ + public function display_form(): void { + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HCaptcha::form() escapes its generated markup. + echo $this->get_hcap_form(); + } + + /** + * Verify the native tracking request before WooCommerce looks up the order. + * + * @param int|string $order_id Submitted order ID. + * + * @return int|string + * @noinspection ForgottenDebugOutputInspection + * @noinspection PhpUnreachableStatementInspection + */ + public function verify_tracking_request( $order_id ) { + $expected_id = $this->get_expected_id(); + $entry = $this->add_email( [ 'expected_id' => $expected_id ] ); + $message = API::verify_post( HCAPTCHA_NONCE, HCAPTCHA_ACTION, $expected_id, $entry ); + + if ( null !== $message ) { + wp_die( + esc_html( $message ), + 'hCaptcha', + [ + 'back_link' => true, + 'response' => 403, + ] + ); + + // Keep the native lookup closed if a custom die handler returns. + return 0; // For testing purposes. + } + + return $order_id; + } + + /** + * Get the server-selected identity of the native tracking form. + * + * @return array + */ + private function get_expected_id(): array { + return [ + 'source' => HCaptcha::get_class_source( __CLASS__ ), + 'form_id' => 'order_tracking', + ]; + } + + /** + * Add the native tracking email only to the server-registered tracking form. + * + * @param array $entry Automatic verification entry. + * + * @return array + */ + public function add_email( array $entry ): array { + $id = (array) ( $entry['expected_id'] ?? [] ); + + if ( + 'order_tracking' !== ( $id['form_id'] ?? '' ) || + HCaptcha::get_class_source( __CLASS__ ) !== ( $id['source'] ?? [] ) + ) { + return $entry; + } + + // The auto verifier checks its nonce and route; WooCommerce checks the tracking nonce. + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $email = isset( $_REQUEST['order_email'] ) && is_string( $_REQUEST['order_email'] ) ? sanitize_email( wp_unslash( $_REQUEST['order_email'] ) ) : ''; + + return EntryData::with_emails( $entry, [ $email ] ); } /** @@ -46,26 +132,36 @@ public function do_shortcode_tag( $output, string $tag, $attr, array $m ) { return $output; } + if ( false !== strpos( (string) $output, self::FORM_MARKER ) ) { + return $output; + } + + return (string) preg_replace( + '/(

    - -

    - -

    - - - - - - - - -
    -
    - + @@ -329,24 +315,6 @@ describe( 'general.js basics', () => { expect( $( '.hcaptcha-theme-editor-json-status' ).hasClass( 'is-valid' ) ).toBe( true ); } ); - test( 'scriptUpdate: rebuilds API script with params and clears sample', async () => { - bootGeneral(); - // Enable recaptcha compat off and custom themes to get params in URL - $( "input[name='hcaptcha_settings[recaptcha_compat_off][]']" ).prop( 'checked', true ); - $( "input[name='hcaptcha_settings[custom_themes][]']" ).prop( 'checked', true ); - // Change an enterprise input to trigger scriptUpdate - $( "input[name='hcaptcha_settings[asset_host]']" ).val( 'http://assethost.local' ).trigger( 'change' ); - await Promise.resolve(); - const script = document.getElementById( 'hcaptcha-api' ); - expect( script ).toBeTruthy(); - expect( script.src ).toContain( 'onload=hCaptchaOnLoad' ); - expect( script.src ).toContain( 'render=explicit' ); - expect( script.src ).toContain( 'recaptchacompat=off' ); - expect( script.src ).toContain( 'custom=true' ); - // sample cleared - expect( $( '#hcaptcha-options .h-captcha' ).html() ).toBe( '' ); - } ); - test( 'credentials change does not disable submit and checkConfig success re-enables', async () => { // Post resolves success postSpy.mockImplementation( ( opts ) => { @@ -564,39 +532,6 @@ describe( 'checkChangeCredentials revert to initial', () => { } ); } ); -describe( 'checkChangeEnterpriseSettings revert to initial', () => { - jest.useFakeTimers(); - let postSpy; - - beforeEach( () => { - jest.clearAllMocks(); - postSpy = jest.spyOn( $, 'post' ).mockImplementation( ( opts ) => { - const d = $.Deferred(); - opts?.beforeSend?.(); - setTimeout( () => d.resolve( { success: true } ), 0 ); - return d; - } ); - } ); - - afterEach( () => { - postSpy.mockRestore(); - } ); - - test( 'reverts enterpriseSettingsChanged state when enterprise settings return to initial values', () => { - bootGeneral(); - const $asset = $( "[name='hcaptcha_settings[asset_host]']" ); - const $submit = $( '#submit' ); - - // Change enterprise input to trigger enterpriseSettingsChanged. - $asset.val( 'changed.local' ).trigger( 'change' ); - expect( $submit.attr( 'disabled' ) ).toBeUndefined(); - - // Revert to initial value. - $asset.val( 'assethost.local' ).trigger( 'change' ); - expect( $submit.attr( 'disabled' ) ).toBeUndefined(); - } ); -} ); - describe( 'initDisabledKeyInputs helper show/hide', () => { beforeEach( () => { jest.clearAllMocks(); @@ -1211,18 +1146,6 @@ describe( 'remaining branch coverage', () => { expect( $submit.attr( 'disabled' ) ).toBeUndefined(); } ); - test( 'enterprise settings changed twice does not re-show notice', () => { - bootGeneral(); - const $asset = $( "[name='hcaptcha_settings[asset_host]']" ); - const $submit = $( '#submit' ); - - $asset.val( 'changed1.local' ).trigger( 'change' ); - expect( $submit.attr( 'disabled' ) ).toBeUndefined(); - - $asset.val( 'changed2.local' ).trigger( 'change' ); - expect( $submit.attr( 'disabled' ) ).toBeUndefined(); - } ); - test( 'keydown on non-readonly input is not prevented', () => { bootGeneral(); $( "select[name='hcaptcha_settings[mode]']" ).val( 'live' ).trigger( 'change' ); @@ -1231,7 +1154,7 @@ describe( 'remaining branch coverage', () => { $siteKey.trigger( event ); expect( event.isDefaultPrevented() ).toBe( false ); } ); - test( 'clicking Save with changed credentials triggers checkConfig and scrolls', async () => { + test( 'clicking the bottom Save button with changed credentials triggers checkConfig and scrolls', async () => { bootGeneral(); const $site = $( "[name='hcaptcha_settings[site_key]']" ); const $submit = $( '#submit' ); @@ -1258,18 +1181,6 @@ describe( 'remaining branch coverage', () => { offsetSpy.mockRestore(); } ); - test( 'scriptUpdate with empty enterprise values and empty api_host', () => { - bootGeneral(); - // Clear all enterprise inputs. - $( '.hcaptcha-section-enterprise + table input' ).each( function() { - $( this ).val( '' ); - } ); - // Trigger enterprise change to call scriptUpdate. - $( "[name='hcaptcha_settings[asset_host]']" ).trigger( 'change' ); - const script = document.getElementById( 'hcaptcha-api' ); - expect( script.src ).toContain( 'js.hcaptcha.com' ); - } ); - test( 'checkConfig click with solved captcha calls onAction which invokes hCaptchaBindEvents', () => { // Use the default kaggDialog mock that calls onAction. bootGeneral(); @@ -1363,7 +1274,7 @@ describe( 'additional general coverage', () => { expect( editableEvent.preventDefault ).not.toHaveBeenCalled(); } ); - test( 'submit click returns when credentials and enterprise settings are unchanged', () => { + test( 'submit click returns when credentials are unchanged', () => { const event = $.Event( 'click' ); event.preventDefault = jest.fn(); diff --git a/tests/js/assets-js-files/hcaptcha-acfe.test.js b/tests/js/assets-js-files/hcaptcha-acfe.test.js index 20e1d6559..b5c29ae30 100644 --- a/tests/js/assets-js-files/hcaptcha-acfe.test.js +++ b/tests/js/assets-js-files/hcaptcha-acfe.test.js @@ -144,7 +144,8 @@ describe( 'hCaptcha ACFE', () => { document.body.innerHTML = '
    ' + '
    ' + - '' + + '' + '' + '
    '; @@ -164,6 +165,29 @@ describe( 'hCaptcha ACFE', () => { expect( document.querySelector( '.grecaptcha-badge' ) ).toBeNull(); } ); + test.each( [ + 'action=acf%2Fvalidate_save_post', + { action: 'acf/validate_save_post' }, + ] )( 'preserves tokens after successful ACF validation with data %p', ( data ) => { + window.hCaptchaBindEvents.mockClear(); + + window.hCaptchaACFE.ajaxCompleteHandler( {}, { + responseJSON: { success: true, data: { valid: 1, errors: 0 } }, + }, { data } ); + + expect( window.hCaptchaBindEvents ).not.toHaveBeenCalled(); + } ); + + test( 'refreshes widgets after failed ACF validation for another attempt', () => { + window.hCaptchaBindEvents.mockClear(); + + window.hCaptchaACFE.ajaxCompleteHandler( {}, { + responseJSON: { success: true, data: { valid: 0, errors: [ 'Validation failed.' ] } }, + }, { data: 'action=acf%2Fvalidate_save_post' } ); + + expect( window.hCaptchaBindEvents ).toHaveBeenCalled(); + } ); + test( 'direct callbacks and fallback handlers can be invoked', () => { expect( () => acfeRecaptchaField.prototype.initialize() ).not.toThrow(); expect( () => acfeRecaptchaField.prototype.render() ).not.toThrow(); diff --git a/tests/js/assets-js-files/hcaptcha-auto-verify.test.js b/tests/js/assets-js-files/hcaptcha-auto-verify.test.js index 593866dde..5a39f769a 100644 --- a/tests/js/assets-js-files/hcaptcha-auto-verify.test.js +++ b/tests/js/assets-js-files/hcaptcha-auto-verify.test.js @@ -5,6 +5,21 @@ describe( 'hCaptcha auto verify', () => { let addEventListenerSpy; const waitForSubmit = () => new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + const ajaxForm = '
    '; + const commentForm = '
    '; + + async function submitForm( submitter ) { + const event = new Event( 'submit', { bubbles: true, cancelable: true } ); + + if ( submitter ) { + Object.defineProperty( event, 'submitter', { value: submitter } ); + } + + document.querySelector( 'form' ).dispatchEvent( event ); + await waitForSubmit(); + + return document.querySelector( '.autoverify-result' ); + } function loadAutoVerify( html ) { document.body.innerHTML = html; @@ -221,4 +236,86 @@ describe( 'hCaptcha auto verify', () => { expect( fetch ).toHaveBeenCalledTimes( 2 ); expect( fetch.mock.calls[ 1 ][ 1 ].body.get( 'hcap_fst_token' ) ).toBe( 'fresh-token' ); } ); + + test.each( [ + [ 'empty response', ' ', {}, 'The form failed.' ], + [ 'nested JSON message', '{"data":{"message":"Nested error."}}', { 'content-type': 'application/json' }, 'Nested error.' ], + [ 'JSON data string', '{"data":"Data error."}', { 'content-type': 'application/json' }, 'Data error.' ], + [ 'top-level JSON message', '{"message":"Top-level error."}', { 'content-type': 'application/json' }, 'Top-level error.' ], + [ 'invalid JSON', '{broken', { 'content-type': 'application/json' }, 'The form failed.' ], + [ 'non-string JSON message', '{"data":{"message":123}}', { 'content-type': 'application/json' }, 'The form failed.' ], + [ 'empty JSON message', '{"data":{"message":""}}', { 'content-type': 'application/json' }, 'The form failed.' ], + [ 'empty WordPress error', '
    ', {}, 'The form failed.' ], + [ 'full HTML document without an error', 'Private details', {}, 'The form failed.' ], + [ 'plain HTML fragment', '

    Fragment error.

    ', {}, 'Fragment error.' ], + [ 'empty HTML fragment', '

    ', {}, 'The form failed.' ], + ] )( 'displays a safe message for %s', async ( description, body, headers, expectedMessage ) => { + fetch.mockResponseOnce( body, { status: 400, headers } ); + loadAutoVerify( ajaxForm ); + + const result = await submitForm(); + + expect( result.textContent ).toBe( expectedMessage ); + expect( result.getAttribute( 'role' ) ).toBe( 'alert' ); + expect( window.hCaptchaReset ).toHaveBeenCalledWith( document.querySelector( 'form' ) ); + } ); + + test( 'treats a form without a comment post ID as an ordinary ajax form', async () => { + fetch.mockResponseOnce( '', { status: 200 } ); + loadAutoVerify( '
    ' ); + + const result = await submitForm(); + + expect( result.textContent ).toBe( 'Verification succeeded.' ); + expect( window.hCaptchaBindEvents ).toHaveBeenCalledTimes( 1 ); + } ); + + test.each( [ + [ 'non-redirected response', false, 'https://test.test/comment/' ], + [ 'redirect without a destination', true, '' ], + ] )( 'shows a WordPress comment error for %s', async ( description, redirected, url ) => { + fetch.mockResolvedValueOnce( { + ok: true, + redirected, + url, + text: () => Promise.resolve( 'Comment rejected.' ), + headers: { get: () => 'text/plain' }, + } ); + loadAutoVerify( commentForm ); + + const result = await submitForm(); + + expect( result.textContent ).toBe( 'Comment rejected.' ); + expect( window.hCaptchaReset ).toHaveBeenCalledTimes( 1 ); + expect( window.hCaptchaBindEvents ).not.toHaveBeenCalled(); + } ); + + test( 'follows a successful WordPress comment redirect', async () => { + fetch.mockResolvedValueOnce( { + ok: true, + redirected: true, + url: window.location.href, + } ); + loadAutoVerify( commentForm ); + + const result = await submitForm(); + + expect( result.textContent ).toBe( 'Submitting...' ); + expect( document.querySelector( 'form' ).hasAttribute( 'aria-busy' ) ).toBe( false ); + expect( window.hCaptchaReset ).not.toHaveBeenCalled(); + expect( window.hCaptchaBindEvents ).not.toHaveBeenCalled(); + } ); + + test( 'includes the submitter and reenables it after a failed submission', async () => { + fetch.mockResponseOnce( 'Try again.', { status: 400 } ); + loadAutoVerify( '
    ' ); + + const submitter = document.querySelector( 'button' ); + const result = await submitForm( submitter ); + + expect( fetch.mock.calls[ 0 ][ 1 ].body.get( 'action' ) ).toBe( 'save' ); + expect( submitter.disabled ).toBe( false ); + expect( submitter.dataset.hCaptchaDisabled ).toBe( '0' ); + expect( result.textContent ).toBe( 'Try again.' ); + } ); } ); diff --git a/tests/js/assets-js-files/hcaptcha-fst.test.js b/tests/js/assets-js-files/hcaptcha-fst.test.js index c709022d3..47ebbf9cf 100644 --- a/tests/js/assets-js-files/hcaptcha-fst.test.js +++ b/tests/js/assets-js-files/hcaptcha-fst.test.js @@ -1,6 +1,7 @@ // noinspection JSUnresolvedFunction,JSUnresolvedVariable describe( 'hCaptcha FST', () => { + let listenerSpy; const waitForToken = () => new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); const getTokenStorageKey = () => [ 'hcaptcha-fst-token', @@ -8,11 +9,17 @@ describe( 'hCaptcha FST', () => { window.location.pathname, window.location.search, ].join( ':' ); + const tokenResponse = ( token = 'ready-token' ) => ( { + ok: true, + status: 200, + json: () => Promise.resolve( { success: true, data: { token } } ), + } ); beforeEach( () => { jest.resetModules(); fetch.resetMocks(); window.sessionStorage.clear(); + listenerSpy = jest.spyOn( document, 'addEventListener' ); window.HCaptchaFSTObject = { ajaxUrl: 'https://test.test/wp-admin/admin-ajax.php', @@ -27,11 +34,17 @@ describe( 'hCaptcha FST', () => { } ); afterEach( () => { + listenerSpy.mock.calls.forEach( ( [ type, listener, options ] ) => { + document.removeEventListener( type, listener, options ); + } ); + listenerSpy.mockRestore(); delete window.HCaptchaFSTObject; delete window.hCaptchaFST; + delete window.hCaptcha; document.body.className = ''; document.body.innerHTML = ''; window.sessionStorage.clear(); + jest.restoreAllMocks(); } ); test( 'coalesces issuance and atomically refreshes after hCaptcha bind events', async () => { @@ -132,6 +145,104 @@ describe( 'hCaptcha FST', () => { expect( window.sessionStorage.getItem( getTokenStorageKey() ) ).toBeNull(); } ); + test( 'refreshes an aged token before resuming form submission', async () => { + const now = jest.spyOn( Date, 'now' ).mockReturnValue( 100000 ); + + try { + document.body.innerHTML = '
    '; + const form = document.querySelector( 'form' ); + const submit = jest.fn(); + + fetch.mockResponseOnce( JSON.stringify( { + success: true, + data: { token: 'first-token', ttl: 60 }, + } ) ); + fetch.mockResponseOnce( JSON.stringify( { + success: true, + data: { token: 'refreshed-token', ttl: 60 }, + } ) ); + + require( '../../../assets/js/hcaptcha-fst.js' ); + await window.hCaptchaFST.getToken(); + expect( window.hCaptchaFST.isReady( form ) ).toBe( true ); + + now.mockReturnValue( 156000 ); + expect( window.hCaptchaFST.isReady( form ) ).toBe( false ); + + const result = await window.hCaptchaFST.runWhenReady( form, submit ); + + expect( result ).toBe( true ); + expect( submit ).toHaveBeenCalledTimes( 1 ); + expect( fetch ).toHaveBeenCalledTimes( 2 ); + expect( form.querySelector( '[name="hcap_fst_token"]' ).value ).toBe( 'refreshed-token' ); + } finally { + now.mockRestore(); + } + } ); + + test( 'refreshes an invalid nonce and resumes the pending form submission', async () => { + document.body.innerHTML = '
    '; + const form = document.querySelector( 'form' ); + const submit = jest.fn(); + + fetch.mockResponseOnce( + JSON.stringify( { + success: false, + data: { code: 'fst-invalid-nonce', nonce: 'fresh-nonce' }, + } ), + { status: 403 }, + ); + fetch.mockResponseOnce( + JSON.stringify( { + success: true, + data: { token: 'new-token' }, + } ), + ); + + require( '../../../assets/js/hcaptcha-fst.js' ); + const result = await window.hCaptchaFST.runWhenReady( form, submit ); + + expect( result ).toBe( true ); + expect( submit ).toHaveBeenCalledTimes( 1 ); + expect( fetch ).toHaveBeenCalledTimes( 2 ); + expect( new URLSearchParams( fetch.mock.calls[ 0 ][ 1 ].body ).get( 'nonce' ) ).toBe( 'nonce' ); + expect( new URLSearchParams( fetch.mock.calls[ 1 ][ 1 ].body ).get( 'nonce' ) ).toBe( 'fresh-nonce' ); + expect( window.HCaptchaFSTObject.issueTokenNonce ).toBe( 'fresh-nonce' ); + expect( form.querySelector( '[name="hcap_fst_token"]' ).value ).toBe( 'new-token' ); + expect( form.querySelector( '.hcaptcha-fst-message' ) ).toBeNull(); + } ); + + test( 'stops after one nonce retry when the server rejects it again', async () => { + document.body.innerHTML = '
    '; + const form = document.querySelector( 'form' ); + const submit = jest.fn(); + + fetch.mockResponseOnce( + JSON.stringify( { + success: false, + data: { code: 'fst-invalid-nonce', nonce: 'fresh-nonce' }, + } ), + { status: 403 }, + ); + fetch.mockResponseOnce( + JSON.stringify( { + success: false, + data: { code: 'fst-invalid-nonce', nonce: 'another-nonce' }, + } ), + { status: 403 }, + ); + + require( '../../../assets/js/hcaptcha-fst.js' ); + const result = await window.hCaptchaFST.runWhenReady( form, submit ); + + expect( result ).toBe( false ); + expect( submit ).not.toHaveBeenCalled(); + expect( fetch ).toHaveBeenCalledTimes( 2 ); + expect( form.querySelector( '.hcaptcha-fst-message' ).textContent ).toBe( + 'Unable to prepare the form. Please check your connection and try submitting again.', + ); + } ); + test( 'preserves a rate limit error for server-side form validation', async () => { fetch.mockResponseOnce( JSON.stringify( { @@ -151,4 +262,174 @@ describe( 'hCaptcha FST', () => { ); expect( window.sessionStorage.getItem( getTokenStorageKey() ) ).toBeNull(); } ); + + test.each( [ true, false ] )( 'continues when storage is unavailable on a %s token response', async ( success ) => { + jest.spyOn( Storage.prototype, 'getItem' ).mockImplementation( () => { + throw new Error( 'Storage unavailable.' ); + } ); + jest.spyOn( Storage.prototype, 'setItem' ).mockImplementation( () => { + throw new Error( 'Storage unavailable.' ); + } ); + jest.spyOn( Storage.prototype, 'removeItem' ).mockImplementation( () => { + throw new Error( 'Storage unavailable.' ); + } ); + fetch.mockResolvedValueOnce( success ? tokenResponse() : { + ok: false, + status: 400, + json: () => Promise.resolve( { success: false } ), + } ); + + require( '../../../assets/js/hcaptcha-fst.js' ); + await window.hCaptchaFST.getToken(); + + expect( document.querySelector( '[name="hcap_fst_token"]' ).value ).toBe( success ? 'ready-token' : '' ); + } ); + + test( 'runs immediately when the form already has a fresh token', async () => { + document.body.innerHTML = '
    '; + fetch.mockResolvedValueOnce( tokenResponse() ); + require( '../../../assets/js/hcaptcha-fst.js' ); + await window.hCaptchaFST.getToken(); + + const form = document.querySelector( 'form' ); + const callback = jest.fn(); + + await expect( window.hCaptchaFST.runWhenReady( form, callback ) ).resolves.toBe( true ); + expect( callback ).toHaveBeenCalledTimes( 1 ); + expect( fetch ).toHaveBeenCalledTimes( 1 ); + } ); + + test( 'coalesces pending submissions and restores a detached form and submitter', async () => { + let resolveRequest; + fetch.mockImplementationOnce( () => new Promise( ( resolve ) => { + resolveRequest = resolve; + } ) ); + document.body.innerHTML = '
    '; + require( '../../../assets/js/hcaptcha-fst.js' ); + + const form = document.querySelector( 'form' ); + const button = form.querySelector( 'button' ); + const callback = jest.fn(); + const first = window.hCaptchaFST.runWhenReady( form, callback, button ); + const second = window.hCaptchaFST.runWhenReady( form, callback, button ); + + expect( second ).toBe( first ); + expect( button.disabled ).toBe( true ); + expect( form.getAttribute( 'aria-busy' ) ).toBe( 'true' ); + expect( form.querySelector( '.hcaptcha-fst-message' ).getAttribute( 'role' ) ).toBe( 'status' ); + + form.remove(); + resolveRequest( tokenResponse() ); + await expect( first ).resolves.toBe( false ); + + expect( button.disabled ).toBe( false ); + expect( form.getAttribute( 'aria-busy' ) ).toBe( 'waiting' ); + expect( callback ).not.toHaveBeenCalled(); + } ); + + test( 'intercepts an unready external submit button using configured selectors', async () => { + let resolveRequest; + fetch.mockImplementationOnce( () => new Promise( ( resolve ) => { + resolveRequest = resolve; + } ) ); + document.body.innerHTML = '
    '; + window.hCaptcha = { submitButtonSelector: '.custom-submit', formSelector: '.custom-form' }; + require( '../../../assets/js/hcaptcha-fst.js' ); + + const button = document.querySelector( 'button' ); + const click = jest.spyOn( button, 'click' ).mockImplementation( () => {} ); + const event = { target: button, preventDefault: jest.fn(), stopImmediatePropagation: jest.fn() }; + window.hCaptchaFST.handleClick( event ); + + expect( event.preventDefault ).toHaveBeenCalledTimes( 1 ); + expect( button.disabled ).toBe( true ); + resolveRequest( tokenResponse() ); + await waitForToken(); + expect( click ).toHaveBeenCalledTimes( 1 ); + expect( button.disabled ).toBe( false ); + delete window.hCaptcha; + } ); + + test( 'ignores clicks outside protected forms and when the token is ready', async () => { + document.body.innerHTML = '
    '; + fetch.mockResolvedValueOnce( tokenResponse() ); + require( '../../../assets/js/hcaptcha-fst.js' ); + const app = window.hCaptchaFST; + const preventDefault = jest.fn(); + const stopImmediatePropagation = jest.fn(); + const event = { preventDefault, stopImmediatePropagation }; + + app.handleClick( { ...event, target: document } ); + app.handleClick( { ...event, target: document.querySelector( 'button[type="button"]' ) } ); + await app.getToken(); + app.handleClick( { ...event, target: document.querySelector( 'button[type="submit"]' ) } ); + + expect( preventDefault ).not.toHaveBeenCalled(); + expect( fetch ).toHaveBeenCalledTimes( 1 ); + } ); + + test.each( [ + [ 'requestSubmit', true, false, false ], + [ 'submitter click', false, true, false ], + [ 'native submit', false, false, false ], + [ 'canceled native submit', false, false, true ], + ] )( 'resumes a captured form submission through %s', async ( description, hasRequestSubmit, hasSubmitter, cancelNative ) => { + let resolveRequest; + fetch.mockImplementationOnce( () => new Promise( ( resolve ) => { + resolveRequest = resolve; + } ) ); + document.body.innerHTML = '
    '; + require( '../../../assets/js/hcaptcha-fst.js' ); + const form = document.querySelector( 'form' ); + const button = form.querySelector( 'button' ); + const submitter = hasSubmitter ? button : undefined; + const requestSubmit = jest.fn(); + const click = jest.spyOn( button, 'click' ).mockImplementation( () => {} ); + const nativeSubmit = jest.spyOn( HTMLFormElement.prototype, 'submit' ).mockImplementation( () => {} ); + form.requestSubmit = hasRequestSubmit ? requestSubmit : undefined; + if ( cancelNative ) { + form.addEventListener( 'submit', ( submitEvent ) => submitEvent.preventDefault() ); + } + const event = { target: form, submitter, preventDefault: jest.fn(), stopImmediatePropagation: jest.fn() }; + + window.hCaptchaFST.handleSubmit( event ); + expect( event.preventDefault ).toHaveBeenCalledTimes( 1 ); + resolveRequest( tokenResponse() ); + await waitForToken(); + + expect( requestSubmit ).toHaveBeenCalledTimes( hasRequestSubmit ? 1 : 0 ); + expect( click ).toHaveBeenCalledTimes( hasSubmitter && ! hasRequestSubmit ? 1 : 0 ); + expect( nativeSubmit ).toHaveBeenCalledTimes( ! hasRequestSubmit && ! hasSubmitter && ! cancelNative ? 1 : 0 ); + } ); + + test.each( [ false, true ] )( 'aborts a stalled %s token request after ten seconds', async ( retry ) => { + jest.useFakeTimers(); + try { + if ( retry ) { + fetch.mockResolvedValueOnce( { + status: 403, + ok: false, + json: () => Promise.resolve( { data: { code: 'fst-invalid-nonce', nonce: 'fresh-nonce' } } ), + } ); + } + fetch.mockImplementationOnce( ( url, options ) => new Promise( ( resolve, reject ) => { + options.signal.addEventListener( 'abort', () => reject( new Error( 'Timed out.' ) ) ); + } ) ); + + require( '../../../assets/js/hcaptcha-fst.js' ); + if ( retry ) { + for ( let attempt = 0; attempt < 10 && fetch.mock.calls.length < 2; attempt++ ) { + await Promise.resolve(); + } + expect( fetch ).toHaveBeenCalledTimes( 2 ); + } + jest.advanceTimersByTime( 10_000 ); + await window.hCaptchaFST.getToken(); + + expect( document.querySelector( '[name="hcap_fst_token"]' ).value ).toBe( '' ); + expect( fetch.mock.calls[ retry ? 1 : 0 ][ 1 ].signal.aborted ).toBe( true ); + } finally { + jest.useRealTimers(); + } + } ); } ); diff --git a/tests/js/assets-js-files/hcaptcha-givewp.test.js b/tests/js/assets-js-files/hcaptcha-givewp.test.js index a92f3a95a..69659c862 100644 --- a/tests/js/assets-js-files/hcaptcha-givewp.test.js +++ b/tests/js/assets-js-files/hcaptcha-givewp.test.js @@ -1,4 +1,4 @@ -// noinspection JSUnresolvedFunction,JSUnresolvedVariable +// noinspection JSUnresolvedFunction,JSUnresolvedVariable,HttpUrlsUsage describe( 'hCaptcha GiveWP', () => { let helperMock; @@ -119,6 +119,33 @@ describe( 'hCaptcha GiveWP', () => { expect( event.detail.args[ 1 ].body ).toBe( body ); } ); + test( 'adds hCaptcha fields to same-origin PayPal createOrder without a honeypot input', () => { + document.body.innerHTML = ` +
    + + + + + +
    + `; + const body = new FormData(); + const event = fetchEvent( 'hCaptchaFetch:before', '/wp-admin/admin-ajax.php?action=give_paypal_commerce_create_order', body ); + + window.hCaptchaGiveWP.fetchBefore( event ); + + expect( body.get( 'h-captcha-response' ) ).toBe( 'paypal-response' ); + expect( body.get( 'hcaptcha-widget-id' ) ).toBe( 'paypal-widget' ); + expect( body.get( 'hcaptcha_give_wp_form_nonce' ) ).toBe( 'paypal-nonce' ); + expect( body.get( 'hcap_fst_token' ) ).toBe( 'paypal-fst' ); + expect( body.get( 'hcap_hp_sig' ) ).toBe( 'paypal-hp-sig' ); + expect( event.detail.args[ 1 ].body ).toBe( body ); + + const foreignBody = new FormData(); + window.hCaptchaGiveWP.fetchBefore( fetchEvent( 'hCaptchaFetch:before', 'https://other.example/wp-admin/admin-ajax.php?action=give_paypal_commerce_create_order', foreignBody ) ); + expect( foreignBody.has( 'h-captcha-response' ) ).toBe( false ); + } ); + test( 'uses fetch body fallbacks when optional GiveWP inputs are missing values', () => { const fakeForm = { querySelector: jest.fn( ( selector ) => { @@ -135,7 +162,7 @@ describe( 'hCaptcha GiveWP', () => { window.hCaptchaGiveWP.fetchBefore( fetchEvent( 'hCaptchaFetch:before', { url: '/wp-json/givewp/v3?givewp-route=donate' }, body ) ); expect( getElementByIdSpy ).toHaveBeenCalledWith( 'root-givewp-donation-form' ); - expect( body.get( 'h-captcha-response' ) ).toBe( 'undefined' ); + expect( body.get( 'h-captcha-response' ) ).toBe( '' ); expect( body.get( 'hcap_hp_empty' ) ).toBe( '' ); } ); diff --git a/tests/js/assets-js-files/hcaptcha-otter.test.js b/tests/js/assets-js-files/hcaptcha-otter.test.js index 80153e5bc..5f0b52650 100644 --- a/tests/js/assets-js-files/hcaptcha-otter.test.js +++ b/tests/js/assets-js-files/hcaptcha-otter.test.js @@ -14,6 +14,7 @@ describe( 'hCaptcha Otter', () => { + @@ -67,11 +68,26 @@ describe( 'hCaptcha Otter', () => { expect( formData[ 'h-captcha-response' ] ).toBe( 'response-token' ); expect( formData[ 'hcaptcha-widget-id' ] ).toBe( 'widget-id' ); expect( formData.hcaptcha_otter_nonce ).toBe( 'nonce-value' ); + expect( formData.hcaptcha_otter_form_nonce ).toBe( 'bound-form-nonce' ); expect( formData.hcap_fst_token ).toBe( 'fst-token' ); expect( formData.hcap_hp_sig ).toBe( 'hp-sig' ); expect( formData.hcap_hp_test ).toBe( '' ); } ); + test( 'replaces a stale submitted form binding with the rendered one', () => { + const body = new FormData(); + body.set( 'form_data', JSON.stringify( { + payload: { formId: 'fc0b7800' }, + hcaptcha_otter_form_nonce: 'stale-form-nonce', + } ) ); + + window.dispatchEvent( new CustomEvent( 'hCaptchaFetch:before', { + detail: { args: [ '/otter/v1/form/frontend', { body } ] }, + } ) ); + + expect( JSON.parse( body.get( 'form_data' ) ).hcaptcha_otter_form_nonce ).toBe( 'bound-form-nonce' ); + } ); + test( 'binds events again after Otter fetch complete', () => { window.dispatchEvent( new CustomEvent( 'hCaptchaFetch:complete', { diff --git a/tests/js/assets-js-files/hcaptcha-wc-stripe-express.test.js b/tests/js/assets-js-files/hcaptcha-wc-stripe-express.test.js new file mode 100644 index 000000000..2d7917956 --- /dev/null +++ b/tests/js/assets-js-files/hcaptcha-wc-stripe-express.test.js @@ -0,0 +1,406 @@ +// noinspection JSUnresolvedReference + +describe( 'hCaptcha WooCommerce Stripe express checkout', () => { + let middleware; + let actions; + + function loadBridge( html = '', settings = { + nonceName: 'hcaptcha_wc_checkout_nonce', + missingProofMessage: 'Complete the test CAPTCHA.', + } ) { + jest.resetModules(); + document.body.innerHTML = html; + window.wp = { + hooks: { addFilter: jest.fn() }, + apiFetch: { use: jest.fn() }, + }; + global.wp = window.wp; + window.wcStripe = { actions: { addAction: jest.fn() } }; + window.HCaptchaWCStripeExpressObject = settings; + window.hCaptchaReset = jest.fn(); + delete window.hCaptchaWCStripeExpress; + + require( '../../../assets/js/hcaptcha-wc-stripe-express.js' ); + middleware = window.wp.apiFetch.use.mock.calls[ 0 ][ 0 ]; + actions = Object.fromEntries( window.wcStripe.actions.addAction.mock.calls ); + + return window.hCaptchaWCStripeExpress; + } + + function makeRoot( context, { challenge = true } = {} ) { + const root = document.createElement( 'div' ); + root.className = 'hcaptcha-wc-stripe-express-proof'; + root.dataset.context = context; + root.innerHTML = ` + + ${ challenge ? ` + + + + + ` : '' } + `; + document.body.appendChild( root ); + + return root; + } + + function makeController( context ) { + const disablePaymentElement = jest.fn(); + const enablePaymentElement = jest.fn(); + + return { + context: { getPage: () => context }, + gateway: { elementType: 'expressCheckout' }, + disablePaymentElement, + enablePaymentElement, + originalDisable: disablePaymentElement, + originalEnable: enablePaymentElement, + }; + } + + function solve( app, root, context, token ) { + root.querySelector( '[name="h-captcha-response"]' ).value = token; + app[ `on${ context }Solved` ]( token ); + } + + function stripeOptions( context = 'product' ) { + return { + method: 'POST', + url: '/?wc-ajax=wc_stripe_frontend_request&path=%2Fwc-stripe%2Fv1%2Fcart%2Fcheckout', + data: { context, payment_method: 'wc_stripe_applepay', billing_email: 'buyer@example.test' }, + }; + } + + afterEach( () => { + document.body.innerHTML = ''; + delete window.wp; + delete global.wp; + delete window.wcStripe; + delete window.HCaptchaWCStripeExpressObject; + delete window.hCaptchaReset; + delete window.hCaptchaWCStripeExpress; + jest.restoreAllMocks(); + } ); + + test( 'registers only one middleware, selector, and native readiness hooks', () => { + loadBridge(); + jest.resetModules(); + require( '../../../assets/js/hcaptcha-wc-stripe-express.js' ); + + expect( window.wp.apiFetch.use ).toHaveBeenCalledTimes( 1 ); + expect( window.wp.hooks.addFilter ).toHaveBeenCalledTimes( 1 ); + expect( window.wp.hooks.addFilter.mock.calls[ 0 ][ 2 ]( 'form' ) ) + .toBe( 'form, .hcaptcha-wc-stripe-express-proof' ); + expect( Object.keys( actions ) ).toEqual( [ 'payment_element_ready', 'express_element_ready' ] ); + } ); + + test( 'gates each wallet by its context and adds only its fresh proof', async () => { + const app = loadBridge(); + const product = makeRoot( 'product' ); + const minicart = makeRoot( 'minicart' ); + const productController = makeController( 'product' ); + const minicartController = makeController( 'minicart' ); + actions.payment_element_ready( productController ); + actions.express_element_ready( {}, { controller: minicartController } ); + expect( productController.originalDisable ).toHaveBeenCalledTimes( 1 ); + expect( minicartController.originalDisable ).toHaveBeenCalledTimes( 1 ); + + solve( app, product, 'Product', 'product-token' ); + expect( productController.originalEnable ).toHaveBeenCalledTimes( 1 ); + expect( minicartController.originalEnable ).not.toHaveBeenCalled(); + + const next = jest.fn( () => Promise.resolve( { success: true } ) ); + const options = stripeOptions(); + await expect( middleware( options, next ) ).resolves.toEqual( { success: true } ); + expect( next ).toHaveBeenCalledTimes( 1 ); + expect( next.mock.calls[ 0 ][ 0 ].data ).toEqual( { + ...options.data, + 'h-captcha-response': 'product-token', + 'hcaptcha-widget-id': 'signed-product', + hcaptcha_wc_checkout_nonce: 'nonce-product', + hcap_hp_product: '', + hcap_hp_sig: 'hp-signature', + hcap_fst_token: 'fst-token', + } ); + expect( options.data ).toEqual( { + context: 'product', payment_method: 'wc_stripe_applepay', billing_email: 'buyer@example.test', + } ); + expect( window.hCaptchaReset ).toHaveBeenCalledWith( product.querySelector( '.h-captcha' ) ); + expect( minicart.querySelector( '[name="h-captcha-response"]' ).value ).toBe( '' ); + } ); + + test( 'keeps the wallet gated across native updates without overriding native disable', () => { + const app = loadBridge(); + const root = makeRoot( 'product' ); + const controller = makeController( 'product' ); + actions.payment_element_ready( controller ); + + controller.enablePaymentElement(); + expect( controller.originalEnable ).not.toHaveBeenCalled(); + expect( controller.originalDisable ).toHaveBeenCalledTimes( 2 ); + + controller.disablePaymentElement(); + solve( app, root, 'Product', 'first-token' ); + expect( controller.originalEnable ).not.toHaveBeenCalled(); + + controller.enablePaymentElement(); + expect( controller.originalEnable ).toHaveBeenCalledTimes( 1 ); + + app.onProductExpired(); + controller.enablePaymentElement(); + expect( controller.originalEnable ).toHaveBeenCalledTimes( 1 ); + expect( controller.originalDisable ).toHaveBeenCalledTimes( 5 ); + } ); + + test( 'records a callback even when hCaptcha fills the response immediately afterward', () => { + jest.useFakeTimers(); + try { + const app = loadBridge(); + const root = makeRoot( 'cart' ); + const controller = makeController( 'cart' ); + actions.payment_element_ready( controller ); + app.onCartSolved( 'later-token' ); + root.querySelector( '[name="h-captcha-response"]' ).value = 'later-token'; + jest.advanceTimersByTime( 0 ); + expect( controller.originalEnable ).toHaveBeenCalledTimes( 1 ); + } finally { + jest.useRealTimers(); + } + } ); + + test( 'relocks a wallet when an updated checkout fragment replaces its proof', async () => { + loadBridge(); + const form = document.createElement( 'form' ); + form.className = 'checkout'; + form.innerHTML = '
    '; + document.body.appendChild( form ); + const controller = makeController( 'express_checkout' ); + actions.payment_element_ready( controller ); + await Promise.resolve(); + + form.querySelector( '[name="h-captcha-response"]' ).value = 'first-token'; + document.dispatchEvent( new CustomEvent( 'hCaptchaSubmitted', { detail: { token: 'first-token' } } ) ); + expect( controller.originalEnable ).toHaveBeenCalled(); + + const disableCount = controller.originalDisable.mock.calls.length; + form.innerHTML = '
    '; + await Promise.resolve(); + expect( controller.originalDisable.mock.calls.length ).toBeGreaterThan( disableCount ); + + const enableCount = controller.originalEnable.mock.calls.length; + form.querySelector( '[name="h-captcha-response"]' ).value = 'second-token'; + document.dispatchEvent( new CustomEvent( 'hCaptchaSubmitted', { detail: { token: 'second-token' } } ) ); + expect( controller.originalEnable.mock.calls.length ).toBeGreaterThan( enableCount ); + } ); + + test( 'expires the wallet gate at 90 seconds without a click', async () => { + jest.useFakeTimers(); + try { + const app = loadBridge(); + const root = makeRoot( 'cart' ); + const controller = makeController( 'cart' ); + actions.payment_element_ready( controller ); + solve( app, root, 'Cart', 'cart-token' ); + expect( controller.originalEnable ).toHaveBeenCalledTimes( 1 ); + + jest.advanceTimersByTime( 89_000 ); + app.onCartSolved( 'cart-token' ); + const disableCount = controller.originalDisable.mock.calls.length; + jest.advanceTimersByTime( 1_000 ); + expect( controller.originalDisable.mock.calls.length ).toBeGreaterThan( disableCount ); + await expect( middleware( stripeOptions( 'cart' ), jest.fn() ) ) + .rejects.toThrow( 'Complete the test CAPTCHA.' ); + } finally { + jest.useRealTimers(); + } + } ); + + test( 'rejects missing, reused, expired, and stale challenge proofs before next', async () => { + const app = loadBridge(); + const cart = makeRoot( 'cart' ); + const controller = makeController( 'cart' ); + actions.payment_element_ready( controller ); + const next = jest.fn( () => new Promise( () => {} ) ); + + await expect( middleware( stripeOptions( 'cart' ), next ) ) + .rejects.toThrow( 'Complete the test CAPTCHA.' ); + solve( app, cart, 'Cart', 'cart-token' ); + middleware( stripeOptions( 'cart' ), next ); + expect( next ).toHaveBeenCalledTimes( 1 ); + await expect( middleware( stripeOptions( 'cart' ), next ) ) + .rejects.toThrow( 'Complete the test CAPTCHA.' ); + + app.onCartExpired(); + await expect( middleware( stripeOptions( 'cart' ), next ) ) + .rejects.toThrow( 'Complete the test CAPTCHA.' ); + expect( controller.originalDisable ).toHaveBeenCalled(); + + jest.spyOn( Date, 'now' ).mockReturnValueOnce( 1000 ).mockReturnValue( 92_000 ); + solve( app, cart, 'Cart', 'new-token' ); + await expect( middleware( stripeOptions( 'cart' ), next ) ) + .rejects.toThrow( 'Complete the test CAPTCHA.' ); + expect( next ).toHaveBeenCalledTimes( 1 ); + } ); + + test( 'passes unrelated requests unchanged and rejects unknown checkout contexts', async () => { + loadBridge(); + const next = jest.fn( () => Promise.resolve( 'untouched' ) ); + const options = stripeOptions(); + options.url = 'https://different.example.test/?wc-ajax=wc_stripe_frontend_request&path=%2Fwc-stripe%2Fv1%2Fcart%2Fcheckout'; + options.path = '/wc-stripe/v1/cart/checkout'; + await expect( middleware( options, next ) ).resolves.toBe( 'untouched' ); + expect( next ).toHaveBeenCalledWith( options ); + delete options.path; + options.url = '/?wc-ajax=wc_stripe_frontend_request&path=/wc-stripe/v1/cart/other'; + await expect( middleware( options, next ) ).resolves.toBe( 'untouched' ); + options.url = '/?wc-ajax=wc_stripe_frontend_request&path=/wc-stripe/v1/cart/checkout'; + options.data.context = 'order_pay'; + await expect( middleware( options, next ) ).rejects.toThrow( 'Complete the test CAPTCHA.' ); + expect( next ).toHaveBeenCalledTimes( 2 ); + } ); + + test( 'lets a signed-ID-only form exemption reach the server', async () => { + loadBridge(); + const root = makeRoot( 'cart', { challenge: false } ); + const next = jest.fn( () => Promise.resolve( 'server-decides' ) ); + await expect( middleware( stripeOptions( 'cart' ), next ) ).resolves.toBe( 'server-decides' ); + expect( next.mock.calls[ 0 ][ 0 ].data[ 'hcaptcha-widget-id' ] ).toBe( 'signed-cart' ); + expect( next.mock.calls[ 0 ][ 0 ].data[ 'h-captcha-response' ] ).toBeUndefined(); + expect( window.hCaptchaReset ).not.toHaveBeenCalled(); + expect( root.isConnected ).toBe( true ); + } ); + + test( 'records the existing checkout widget for classic banner gating', () => { + loadBridge(); + const form = document.createElement( 'form' ); + form.className = 'checkout'; + form.innerHTML = '
    '; + document.body.appendChild( form ); + const controller = makeController( 'express_checkout' ); + actions.payment_element_ready( controller ); + expect( controller.originalDisable ).toHaveBeenCalledTimes( 1 ); + form.querySelector( '[name="h-captcha-response"]' ).value = 'checkout-token'; + document.dispatchEvent( new CustomEvent( 'hCaptchaSubmitted', { detail: { token: 'checkout-token' } } ) ); + expect( controller.originalEnable ).toHaveBeenCalledTimes( 1 ); + } ); + + test( 'uses default settings and starts without a mutation observer', async () => { + const mutationObserver = window.MutationObserver; + window.MutationObserver = undefined; + try { + loadBridge( '', null ); + const options = stripeOptions(); + options.data = null; + + await expect( middleware( options, jest.fn() ) ).rejects.toThrow( 'Complete hCaptcha before express checkout.' ); + expect( window.wp.hooks.addFilter ).toHaveBeenCalledTimes( 1 ); + } finally { + window.MutationObserver = mutationObserver; + } + } ); + + test( 'ignores controllers outside supported express checkout contexts', () => { + loadBridge(); + actions.payment_element_ready( null ); + actions.payment_element_ready( { context: { getPage: () => 'unknown' }, gateway: { elementType: 'expressCheckout' } } ); + actions.payment_element_ready( { context: { getPage: () => 'product' }, gateway: { elementType: 'other' } } ); + + expect( window.wp.apiFetch.use ).toHaveBeenCalledTimes( 1 ); + } ); + + test( 'rejects a root without a signed widget identity', async () => { + loadBridge(); + const root = makeRoot( 'product', { challenge: false } ); + root.querySelector( '[name="hcaptcha-widget-id"]' ).value = ''; + const next = jest.fn(); + + await expect( middleware( stripeOptions(), next ) ).rejects.toThrow( 'Complete the test CAPTCHA.' ); + expect( next ).not.toHaveBeenCalled(); + } ); + + test.each( [ + [ undefined ], + [ [] ], + [ 'product' ], + [ { context: 'other' } ], + ] )( 'rejects invalid checkout data %p', async ( data ) => { + loadBridge(); + const options = stripeOptions(); + options.data = data; + + await expect( middleware( options, jest.fn() ) ).rejects.toThrow( 'Complete the test CAPTCHA.' ); + } ); + + test.each( [ + [ 'missing method', { url: '/?wc-ajax=wc_stripe_frontend_request' } ], + [ 'GET method', { method: 'GET', url: '/?wc-ajax=wc_stripe_frontend_request' } ], + [ 'different path', { method: 'POST', path: '/other' } ], + [ 'malformed URL', { method: 'POST', url: 'http://[' } ], + [ 'ordinary URL', { method: 'POST', url: '/ordinary/' } ], + ] )( 'passes a %s request through unchanged', async ( description, options ) => { + loadBridge(); + const next = jest.fn( () => 'untouched' ); + + expect( middleware( options, next ) ).toBe( 'untouched' ); + expect( next ).toHaveBeenCalledWith( options ); + } ); + + test.each( [ + [ 'path option', { method: 'POST', path: '/wc-stripe/v1/cart/checkout' } ], + [ 'REST route', { method: 'POST', url: '/?rest_route=%2Fwc-stripe%2Fv1%2Fcart%2Fcheckout' } ], + [ 'pretty REST URL', { method: 'POST', url: '/wp-json/wc-stripe/v1/cart/checkout/' } ], + ] )( 'adds proof for the %s checkout endpoint', async ( description, endpoint ) => { + loadBridge(); + makeRoot( 'cart', { challenge: false } ); + const next = jest.fn( () => 'sent' ); + const options = { ...endpoint, data: { context: 'cart' } }; + + await expect( middleware( options, next ) ).resolves.toBe( 'sent' ); + expect( next.mock.calls[ 0 ][ 0 ].data[ 'hcaptcha-widget-id' ] ).toBe( 'signed-cart' ); + } ); + + test.each( [ + [ 'synchronous error', () => { + throw new Error( 'Transport failed.' ); + } ], + [ 'rejected request', () => Promise.reject( new Error( 'Transport failed.' ) ) ], + ] )( 'resets the spent proof after a %s', async ( description, transport ) => { + const app = loadBridge(); + const root = makeRoot( 'product' ); + solve( app, root, 'Product', 'proof-token' ); + const next = jest.fn( transport ); + + if ( description === 'synchronous error' ) { + expect( () => middleware( stripeOptions(), next ) ).toThrow( 'Transport failed.' ); + } else { + await expect( middleware( stripeOptions(), next ) ).rejects.toThrow( 'Transport failed.' ); + } + expect( window.hCaptchaReset ).toHaveBeenCalledWith( root.querySelector( '.h-captcha' ) ); + await expect( middleware( stripeOptions(), next ) ).rejects.toThrow( 'Complete the test CAPTCHA.' ); + } ); + + test( 'ignores an empty callback token and a stale expiry callback', () => { + jest.useFakeTimers(); + try { + const app = loadBridge(); + const root = makeRoot( 'minicart' ); + const controller = makeController( 'minicart' ); + actions.payment_element_ready( controller ); + app.onMinicartSolved( '' ); + jest.advanceTimersByTime( 0 ); + expect( controller.originalEnable ).not.toHaveBeenCalled(); + + const timer = jest.spyOn( global, 'setTimeout' ); + solve( app, root, 'Minicart', 'proof-token' ); + const expiry = timer.mock.calls.find( ( call ) => call[ 1 ] === 90_000 )[ 0 ]; + expect( controller.originalEnable ).toHaveBeenCalledTimes( 1 ); + app.onMinicartExpired(); + expect( controller.originalDisable ).toHaveBeenCalled(); + expiry(); + timer.mockRestore(); + } finally { + jest.useRealTimers(); + } + } ); +} ); diff --git a/tests/js/assets-js-files/integrations.test.js b/tests/js/assets-js-files/integrations.test.js index ced2faa4b..33a7d1ac7 100644 --- a/tests/js/assets-js-files/integrations.test.js +++ b/tests/js/assets-js-files/integrations.test.js @@ -46,8 +46,6 @@ function getDom() {
    - -
    @@ -96,10 +94,6 @@ function getDom() { - -
    - - ', ); @@ -1332,6 +1264,7 @@ describe( 'integration plan failures and changing dependencies', () => { image.trigger( 'click' ); requests[ 0 ].deferred.resolve( { success: false, data: { message: 'Cannot activate' } } ); + expect( $( '#hcaptcha-message' ).text() ).toContain( 'Cannot activate' ); image.trigger( 'click' ); @@ -1399,6 +1332,7 @@ describe( 'integration plan failures and changing dependencies', () => { test( 'dependency selection updates master state and refreshes when theme changes', () => { window.kaggDialog.confirm.mockImplementation( ( settings ) => { + // language=HTML $( `
    ${ settings.content }
    ` ).appendTo( document.body ); } ); const image = $( '.hcaptcha-integrations-twentytwentyone-theme img' ); @@ -1440,7 +1374,7 @@ describe( 'integration plan failures and changing dependencies', () => { test( 'toggle response handles missing success and moves another active row', () => { const image = $( '.hcaptcha-integrations-acfe-status img' ); - $( '.form-table' ).eq( 2 ).find( 'tbody' ).append( $( '.hcaptcha-integrations-other-plugin' ) ); + $( '.form-table' ).eq( 1 ).find( 'tbody' ).append( $( '.hcaptcha-integrations-other-plugin' ) ); image.trigger( $.Event( 'click', { ctrlKey: true } ) ); requests[ 0 ].deferred.resolve( { data: {} } ); @@ -1452,13 +1386,14 @@ describe( 'integration plan failures and changing dependencies', () => { data: { message: 'Activated', stati: { other_plugin: true } }, } ); expect( $( '.hcaptcha-integrations-other-plugin' ).closest( '.form-table' )[ 0 ] ) - .toBe( $( '.form-table' )[ 1 ] ); + .toBe( $( '.form-table' )[ 0 ] ); } ); test( 'dependency plan tolerates missing items and item names', () => { $( '.hcaptcha-integrations-acfe-status fieldset' ).removeAttr( 'disabled' ); window.HCaptchaIntegrationsObject.dependenciesMsg = null; window.kaggDialog.confirm.mockImplementation( ( settings ) => { + // language=HTML $( `
    ${ settings.content }
    ` ).appendTo( document.body ); } ); diff --git a/tests/js/assets-js-files/notifications.test.js b/tests/js/assets-js-files/notifications.test.js index a110f1750..5331dafbb 100644 --- a/tests/js/assets-js-files/notifications.test.js +++ b/tests/js/assets-js-files/notifications.test.js @@ -1,6 +1,5 @@ // noinspection JSUnresolvedFunction,JSUnresolvedVariable -/* eslint-disable brace-style,space-in-parens,no-unused-vars */ import $ from 'jquery'; global.jQuery = $; @@ -53,7 +52,7 @@ function getDom( { withTwo = true } = {} ) { / - +

    Keys Section

    @@ -79,7 +78,9 @@ describe( 'notifications.js', () => { jest.clearAllMocks(); postSpy = jest.spyOn( $, 'post' ).mockImplementation( () => ( { // jQuery 1.x style alias used by notifications.js in reset path - success( cb ) { return this; }, + done() { + return this; + }, } ) ); } ); @@ -88,15 +89,16 @@ describe( 'notifications.js', () => { } ); test( 'dismiss removes current, shows next, updates nav and clones buttons; posts payload', () => { - bootNotifications( ); + bootNotifications(); // Click dismiss on the first visible notification const firstDismiss = document.querySelector( '.hcaptcha-notification[data-id="n1"] .notice-dismiss' ); - firstDismiss.click( ); + firstDismiss.click(); + expect( document.querySelector( '.hcaptcha-general-reset-notifications' ).classList.contains( 'hidden' ) ).toBe( false ); // After removal: only the second notification remains and is visible const rem1 = document.querySelector( '.hcaptcha-notification[data-id="n1"]' ); - expect( rem1 ).toBeNull( ); + expect( rem1 ).toBeNull(); const second = document.querySelector( '.hcaptcha-notification[data-id="n2"]' ); expect( getComputedStyle( second ).display ).toBe( 'block' ); @@ -107,16 +109,23 @@ describe( 'notifications.js', () => { // Footer received cloned buttons from the visible notification (without hidden class) const footer = document.getElementById( 'hcaptcha-notifications-footer' ); const cloned = footer.querySelector( '.hcaptcha-notification-buttons' ); - expect( cloned ).toBeTruthy( ); + expect( cloned ).toBeTruthy(); expect( cloned.classList.contains( 'hidden' ) ).toBe( false ); - expect( footer.querySelector( 'button.btn-two' ) ).toBeTruthy( ); + expect( footer.querySelector( 'button.btn-two' ) ).toBeTruthy(); // One $.post call happened with the correct URL and data (cannot read arguments from default spy, so override) - postSpy.mockRestore( ); + postSpy.mockRestore(); const calls = []; - jest.spyOn( $, 'post' ).mockImplementation( ( opts ) => { calls.push( opts ); return { success( ) { return this; } }; } ); + jest.spyOn( $, 'post' ).mockImplementation( ( opts ) => { + calls.push( opts ); + return { + done() { + return this; + }, + }; + } ); // Trigger dismisses of the second now - document.querySelector( '.hcaptcha-notification[data-id="n2"] .notice-dismiss' ).click( ); + document.querySelector( '.hcaptcha-notification[data-id="n2"] .notice-dismiss' ).click(); expect( calls.length ).toBe( 1 ); expect( calls[ 0 ].url ).toBe( defaultNotifications.ajaxUrl ); expect( calls[ 0 ].data.action ).toBe( defaultNotifications.dismissNotificationAction ); @@ -127,8 +136,8 @@ describe( 'notifications.js', () => { test( 'dismissing last notification removes notifications container', () => { bootNotifications( { withTwo: false } ); const dismissBtn = document.querySelector( '.hcaptcha-notification .notice-dismiss' ); - dismissBtn.click( ); - expect( document.getElementById( 'hcaptcha-notifications' ) ).toBeNull( ); + dismissBtn.click(); + expect( document.getElementById( 'hcaptcha-notifications' ) ).toBeNull(); } ); test( 'navigation next/prev toggles visibility and disabled classes; nav counters update', async () => { @@ -167,12 +176,13 @@ describe( 'notifications.js', () => { } ); test( 'reset button posts reset action and replaces notifications HTML; triggers helper flows', async () => { - bootNotifications( ); + bootNotifications(); - // Prepare post to call .success with a successful response containing new markup - postSpy.mockImplementation( ( opts ) => ( { - success( cb ) { - cb( { success: true, data: ` + // Prepare post to call .done with a successful response containing new markup + postSpy.mockImplementation( () => ( { + done( cb ) { + cb( { + success: true, data: `

    New notification

    @@ -180,20 +190,24 @@ describe( 'notifications.js', () => {
    - ` } ); + `, + } ); return this; }, } ) ); // Spy on jQuery(document).trigger for wp-updates-notice-added - const triggerSpy = jest.spyOn( $.fn, 'trigger' ).mockImplementation( function() { return this; } ); + const triggerSpy = jest.spyOn( $.fn, 'trigger' ).mockImplementation( function() { + return this; + } ); - document.getElementById( 'reset_notifications' ).click( ); + document.getElementById( 'reset_notifications' ).click(); + expect( document.querySelector( '.hcaptcha-general-reset-notifications' ).classList.contains( 'hidden' ) ).toBe( true ); // Allow any microtasks and macrotasks in success handlers to run await Promise.resolve(); await Promise.resolve(); - await new Promise( (r) => setTimeout( r, 0 ) ); - await new Promise( (r) => setTimeout( r, 0 ) ); + await new Promise( ( r ) => setTimeout( r, 0 ) ); + await new Promise( ( r ) => setTimeout( r, 0 ) ); // Old container removed and a new one inserted before the section header const keysHeader = document.querySelector( 'h3.hcaptcha-section-keys' ); @@ -205,26 +219,47 @@ describe( 'notifications.js', () => { expect( newContainer.querySelectorAll( '.hcaptcha-notification' ).length ).toBeGreaterThan( 0 ); // Ensure post payload contained reset action - expect( postSpy ).toHaveBeenCalled( ); + expect( postSpy ).toHaveBeenCalled(); const args = postSpy.mock.calls[ 0 ][ 0 ]; expect( args.url ).toBe( defaultNotifications.ajaxUrl ); expect( args.data.action ).toBe( defaultNotifications.resetNotificationAction ); expect( args.data.nonce ).toBe( defaultNotifications.resetNotificationNonce ); // Trigger called with wp-updates-notice-added at least once - expect( triggerSpy ).toHaveBeenCalled( ); - triggerSpy.mockRestore( ); + expect( triggerSpy ).toHaveBeenCalled(); + triggerSpy.mockRestore(); } ); test( 'reset button: success false does nothing (no replacement)', () => { - bootNotifications( ); + bootNotifications(); const original = document.getElementById( 'hcaptcha-notifications' ); - postSpy.mockImplementation( () => ( { success( cb ) { cb( { success: false, data: '' } ); return this; } } ) ); - document.getElementById( 'reset_notifications' ).click( ); + postSpy.mockImplementation( () => ( { + done( cb ) { + cb( { success: false, data: '' } ); + return this; + }, + } ) ); + document.getElementById( 'reset_notifications' ).click(); const current = document.getElementById( 'hcaptcha-notifications' ); expect( current ).toBe( original ); } ); + test( 'reset does not show notifications before live keys are saved', () => { + bootNotifications(); + $( '#hcaptcha-notifications' ).addClass( 'hcaptcha-setup-notice' ); + postSpy.mockImplementation( () => ( { + done( callback ) { + callback( { success: true, data: '
    Notifications
    ' } ); + return this; + }, + } ) ); + + document.getElementById( 'reset_notifications' ).click(); + + expect( document.getElementById( 'hcaptcha-notifications' ).classList.contains( 'hcaptcha-setup-notice' ) ).toBe( true ); + expect( document.querySelector( '.hcaptcha-general-reset-notifications' ).classList.contains( 'hidden' ) ).toBe( true ); + } ); + test( 'normalizeNotificationHeight updates maxHeight when outerHeight returns positive value', () => { bootNotifications(); @@ -234,7 +269,7 @@ describe( 'notifications.js', () => { // Re-run the initializer; normalizeNotificationHeight is called at the bottom. window.hCaptchaNotifications( $ ); - // The spy was invoked (once per notification inside the each loop). + // The spy was invoked (once per notification inside each loop). expect( outerHeightSpy ).toHaveBeenCalled(); outerHeightSpy.mockRestore(); } ); diff --git a/tests/js/assets-js-files/onboarding-wizard.test.js b/tests/js/assets-js-files/onboarding-wizard.test.js index 901d9bced..79e29ef82 100644 --- a/tests/js/assets-js-files/onboarding-wizard.test.js +++ b/tests/js/assets-js-files/onboarding-wizard.test.js @@ -14,6 +14,7 @@ const defaultOnboardingObject = { page: 'general', currentStep: 'step 3', generalUrl: 'https://test.test/wp-admin/admin.php?page=hcaptcha', + antispamUrl: 'https://test.test/wp-admin/admin.php?page=hcaptcha-antispampage', integrationsUrl: 'https://test.test/wp-admin/admin.php?page=hcaptcha-integrations', stepParam: 'onboarding_step', stepNonce: 'step_nonce', @@ -21,6 +22,7 @@ const defaultOnboardingObject = { iconAnimatedUrl: 'https://test.test/wp-content/plugins/hcaptcha/assets/images/icon.svg', videoUrl: 'https://youtu.be/khKYehgr8t0', ratingUrl: 'https://wordpress.org/support/plugin/hcaptcha-for-forms-and-more/reviews/#new-post', + signupUrl: 'https://www.hcaptcha.com/signup-interstitial/?r=wp&utm_source=wordpress&utm_medium=wpplugin&utm_campaign=sk', selectors: { general: { site_key: '#site_key', @@ -32,7 +34,10 @@ const defaultOnboardingObject = { set_min_submit_time: '#set_min_submit_time_1', antispam_check: '#antispam_1', antispam_provider: 'select[name="hcaptcha_settings[antispam_provider]"]', - antispam: '.hcaptcha-section-antispam+table', + save: '#hcaptcha-options #submit', + }, + antispam: { + bot_detection: '.hcaptcha-section-bot-detection+table', save: '#hcaptcha-options #submit', }, integrations: { @@ -45,16 +50,17 @@ const defaultOnboardingObject = { 2: 'Switch Mode to Live', 3: 'Enter keys, solve hCaptcha and Check Config', 4: 'Enable Force (recommended)', - 5: 'Enable Anti-spam options (recommended)', - 6: 'Save settings', - 7: 'Enable hCaptcha for installed plugins', - 8: 'Save settings', + 5: 'Save settings', + 6: 'Review bot detection options', + 7: 'Save settings', + 8: 'Enable hCaptcha for installed plugins', + 9: 'Save settings', }, i18n: { done: 'Done', choiceTitle: 'How would you like to continue?', choiceBody: 'Your keys are configured and verified. We can now apply the recommended setup automatically, or you can continue step by step.', - choiceAutoBody: 'Automatic setup will enable Force, apply the recommended anti-spam options, enable hCaptcha for installed plugins and themes, and save your settings.', + choiceAutoBody: 'Automatic setup will enable Force, Honeypot, and minimum submit time, apply available reCAPTCHA migrations, and save your settings.', choiceAutoCta: 'Apply recommended setup automatically', choiceManualCta: 'Continue step by step', close: 'Close', @@ -114,6 +120,16 @@ function getIntegrationsDom() { `; } +function getAntiSpamDom() { + return ` +
    +

    Bot Detection

    +
    + +
    + `; +} + function bootOnboarding( overrides = {}, dom = getGeneralDom() ) { jest.resetModules(); $( document ).off(); @@ -194,7 +210,7 @@ describe( 'onboarding.js', () => { expect( $( '.hcap-onb-panel [data-step="4"]' ).hasClass( 'current' ) ).toBe( true ); } ); - test( 'automatic setup on the general page enables recommended options and prepares integrations auto-save', () => { + test( 'automatic setup submits General settings through the auto-setup URL', () => { bootOnboarding(); const form = document.getElementById( 'hcaptcha-options' ); @@ -210,14 +226,14 @@ describe( 'onboarding.js', () => { ); } ); - test( 'automatic setup on the integrations page completes the wizard on step 8', () => { + test( 'automatic setup completion on General clears its session flag and shows congrats', () => { sessionStorage.setItem( 'hcapOnbAutoSetup', '1' ); bootOnboarding( { - page: 'integrations', - currentStep: 'step 8', + page: 'general', + currentStep: 'step 9', }, - getIntegrationsDom(), + getGeneralDom(), ); expect( postSpy ).toHaveBeenCalledWith( @@ -225,7 +241,7 @@ describe( 'onboarding.js', () => { expect.objectContaining( { value: 'completed' } ), ); expect( document.body.textContent ).toContain( 'Congrats — setup complete!' ); - expect( sessionStorage.getItem( 'hcapOnbAutoSetup' ) ).toBe( '1' ); + expect( sessionStorage.getItem( 'hcapOnbAutoSetup' ) ).toBeNull(); } ); // ─── welcome modal ──────────────────────────────────────────────────────── @@ -241,6 +257,16 @@ describe( 'onboarding.js', () => { expect( $( '.hcap-onb-panel' ).length ).toBe( 1 ); expect( $( '.hcap-onb-tip-text' ).first().text() ).toBe( 'Get your keys at hcaptcha.com' ); + + const $signupLinks = $( '.hcap-onb-signup-link' ); + + expect( $signupLinks ).toHaveLength( 2 ); + $signupLinks.each( function() { + expect( $( this ).text() ).toBe( 'Get your keys at hcaptcha.com' ); + expect( $( this ).attr( 'href' ) ).toBe( defaultOnboardingObject.signupUrl ); + expect( $( this ).attr( 'target' ) ).toBe( '_blank' ); + expect( $( this ).attr( 'rel' ) ).toBe( 'noopener noreferrer' ); + } ); } ); test( 'clicking the welcome overlay also dismisses and proceeds', () => { @@ -427,13 +453,30 @@ describe( 'onboarding.js', () => { test( 'clicking an integrations-page step in the panel navigates to the integrations URL', () => { bootOnboarding(); - $( '.hcap-onb-list li[data-step="7"]' ).trigger( 'click' ); + $( '.hcap-onb-list li[data-step="8"]' ).trigger( 'click' ); - expect( locationHref ).toContain( 'onboarding_step=7' ); + expect( locationHref ).toContain( 'onboarding_step=8' ); expect( locationHref ).toContain( 'hcaptcha_onboarding_nonce=step_nonce' ); expect( locationHref ).toContain( 'page=hcaptcha-integrations' ); } ); + test( 'clicking an Anti-Spam step in the panel navigates to the Anti-Spam URL', () => { + bootOnboarding(); + $( '.hcap-onb-list li[data-step="6"]' ).trigger( 'click' ); + + expect( locationHref ).toContain( 'onboarding_step=6' ); + expect( locationHref ).toContain( 'page=hcaptcha-antispampage' ); + } ); + + test( 'clicking the signup link does not navigate to a wizard step', () => { + bootOnboarding(); + const event = $.Event( 'click' ); + event.preventDefault(); + $( '.hcap-onb-panel .hcap-onb-signup-link' ).trigger( event ); + + expect( locationHref ).toBe( 'http://localhost/' ); + } ); + test( 'clicking a list item with data-step=0 does not navigate', () => { bootOnboarding(); // Manually inject an invalid step item @@ -453,6 +496,13 @@ describe( 'onboarding.js', () => { expect( locationHref ).toContain( 'hcaptcha_onboarding_nonce=step_nonce' ); } ); + test( 'keydown Enter on the signup link does not navigate to a wizard step', () => { + bootOnboarding(); + $( '.hcap-onb-panel .hcap-onb-signup-link' ).trigger( $.Event( 'keydown', { key: 'Enter' } ) ); + + expect( locationHref ).toBe( 'http://localhost/' ); + } ); + test( 'keydown Space on panel step item navigates', () => { bootOnboarding(); $( '.hcap-onb-list li[data-step="2"]' ).trigger( $.Event( 'keydown', { key: ' ' } ) ); @@ -507,7 +557,7 @@ describe( 'onboarding.js', () => { // ─── showStep: target on wrong page ─────────────────────────────────────── test( 'showStep returns early when target step belongs to another page', () => { - // step 7 belongs to integrations; booting general page at step 7 should show no tooltip + // Step 7 belongs to Anti-Spam; General has no tooltip for it. bootOnboarding( { page: 'general', currentStep: 'step 7' } ); jest.runAllTimers(); @@ -639,41 +689,64 @@ describe( 'onboarding.js', () => { } ).not.toThrow(); } ); - // ─── step 6 done → redirect to integrations ─────────────────────────────── + // ─── step 5 done → save General ──────────────────────────────────────────── - test( 'done button on step 6 (general) redirects to integrationsUrl', () => { - bootOnboarding( { currentStep: 'step 6' } ); + test( 'done button on step 5 saves General and prepares Anti-Spam', () => { + bootOnboarding( { currentStep: 'step 5' } ); + const form = document.getElementById( 'hcaptcha-options' ); + form.submit = jest.fn(); jest.runAllTimers(); $( '.hcap-onb-done' ).trigger( 'click' ); expect( postSpy ).toHaveBeenCalledWith( 'https://test.test/wp-admin/admin-ajax.php', - expect.objectContaining( { value: 'step 7' } ), + expect.objectContaining( { value: 'step 6' } ), ); - expect( locationHref ).toContain( 'page=hcaptcha-integrations' ); + expect( form.submit ).toHaveBeenCalledTimes( 1 ); + expect( sessionStorage.getItem( 'hcapOnbGoAntiSpam' ) ).toBe( '1' ); } ); - // ─── step 8 done → congrats modal ───────────────────────────────────────── + test( 'Anti-Spam steps highlight bot detection and save before Integrations', () => { + bootOnboarding( { page: 'antispam', currentStep: 'step 6' }, getAntiSpamDom() ); + const form = document.getElementById( 'hcaptcha-options' ); + form.submit = jest.fn(); - test( 'done button on step 8 (integrations) shows congrats modal and removes panel on dismiss', () => { - bootOnboarding( { page: 'integrations', currentStep: 'step 8' }, getIntegrationsDom() ); + expect( $( '.hcap-onb-tip-text' ).first().text() ).toBe( 'Review bot detection options' ); + $( '.hcap-onb-done' ).trigger( 'click' ); + expect( $( '.hcap-onb-tip-text' ).first().text() ).toBe( 'Save settings' ); + $( '.hcap-onb-done' ).trigger( 'click' ); + + expect( postSpy ).toHaveBeenCalledWith( + 'https://test.test/wp-admin/admin-ajax.php', + expect.objectContaining( { value: 'step 8' } ), + ); + expect( form.submit ).toHaveBeenCalledTimes( 1 ); + expect( sessionStorage.getItem( 'hcapOnbGoIntegrations' ) ).toBe( '1' ); + } ); + + // ─── step 9 done → congrats modal ───────────────────────────────────────── + + test( 'done button on step 9 (integrations) shows congrats modal', () => { + bootOnboarding( { page: 'integrations', currentStep: 'step 9' }, getIntegrationsDom() ); + document.getElementById( 'hcaptcha-options' ).submit = jest.fn(); jest.runAllTimers(); $( '.hcap-onb-done' ).trigger( 'click' ); expect( document.body.textContent ).toContain( 'Congrats — setup complete!' ); - // Dismiss via overlay → removes tooltip and panel. + // Dismiss via overlay and submit the Integration settings. $( '.hcap-onb-modal-overlay' ).trigger( 'click' ); jest.runAllTimers(); expect( $( '.hcap-onb-modal-overlay' ).length ).toBe( 0 ); - expect( $( '.hcap-onb-panel' ).length ).toBe( 0 ); + expect( document.getElementById( 'hcaptcha-options' ).submit ).toHaveBeenCalledTimes( 1 ); } ); test( 'congrats modal rate button click schedules a dismiss via setTimeout', () => { - bootOnboarding( { page: 'integrations', currentStep: 'step 8' }, getIntegrationsDom() ); + bootOnboarding( { page: 'integrations', currentStep: 'step 9' }, getIntegrationsDom() ); + document.getElementById( 'hcaptcha-options' ).submit = jest.fn(); jest.runAllTimers(); $( '.hcap-onb-done' ).trigger( 'click' ); @@ -690,7 +763,7 @@ describe( 'onboarding.js', () => { test( 'congrats overlay dismiss when no onDismiss callback (autoSetup path)', () => { sessionStorage.setItem( 'hcapOnbAutoSetup', '1' ); - bootOnboarding( { page: 'integrations', currentStep: 'step 8' }, getIntegrationsDom() ); + bootOnboarding( { page: 'integrations', currentStep: 'step 9' }, getIntegrationsDom() ); expect( document.body.textContent ).toContain( 'Congrats — setup complete!' ); @@ -699,10 +772,10 @@ describe( 'onboarding.js', () => { expect( $( '.hcap-onb-modal-overlay' ).length ).toBe( 0 ); } ); - // ─── form submit: step 6 general ───────────────────────────────────────── + // ─── form submit: step 5 general ───────────────────────────────────────── - test( 'form submit on step 6 (general) posts step 7 and sets sessionStorage flag', () => { - bootOnboarding( { currentStep: 'step 6' } ); + test( 'form submit on step 5 (general) posts step 6 and sets sessionStorage flag', () => { + bootOnboarding( { currentStep: 'step 5' } ); document.getElementById( 'hcaptcha-options' ).submit = jest.fn(); @@ -710,9 +783,9 @@ describe( 'onboarding.js', () => { expect( postSpy ).toHaveBeenCalledWith( 'https://test.test/wp-admin/admin-ajax.php', - expect.objectContaining( { value: 'step 7' } ), + expect.objectContaining( { value: 'step 6' } ), ); - expect( sessionStorage.getItem( 'hcapOnbGoIntegrations' ) ).toBe( '1' ); + expect( sessionStorage.getItem( 'hcapOnbGoAntiSpam' ) ).toBe( '1' ); } ); test( 'form submit on other steps is a no-op for post', () => { @@ -727,10 +800,10 @@ describe( 'onboarding.js', () => { expect( postSpy ).not.toHaveBeenCalled(); } ); - // ─── form submit: step 8 integrations ──────────────────────────────────── + // ─── form submit: step 9 integrations ──────────────────────────────────── - test( 'form submit on step 8 (integrations, first time) prevents default and shows congrats, then resubmits form', () => { - bootOnboarding( { page: 'integrations', currentStep: 'step 8' }, getIntegrationsDom() ); + test( 'form submit on step 9 (integrations, first time) prevents default and shows congrats, then resubmits form', () => { + bootOnboarding( { page: 'integrations', currentStep: 'step 9' }, getIntegrationsDom() ); const form = document.getElementById( 'hcaptcha-options' ); const submitSpy = jest.fn(); @@ -750,8 +823,8 @@ describe( 'onboarding.js', () => { expect( submitSpy ).toHaveBeenCalledTimes( 1 ); } ); - test( 'form submit on step 8 (integrations, second time) allows normal submit', () => { - bootOnboarding( { page: 'integrations', currentStep: 'step 8' }, getIntegrationsDom() ); + test( 'form submit on step 9 (integrations, second time) allows normal submit', () => { + bootOnboarding( { page: 'integrations', currentStep: 'step 9' }, getIntegrationsDom() ); const form = document.getElementById( 'hcaptcha-options' ); @@ -763,16 +836,34 @@ describe( 'onboarding.js', () => { jest.runAllTimers(); // Second submit: hcapOnbSubmitting is true → just return, no new congrats modal. + window.HCaptchaOnboardingObject.currentStep = 'step 9'; const beforeCalls = postSpy.mock.calls.length; - - $( '#hcaptcha-options' ).trigger( 'submit' ); + const event = $.Event( 'submit' ); + event.preventDefault = jest.fn(); + $( '#hcaptcha-options' ).trigger( event ); expect( postSpy.mock.calls.length ).toBe( beforeCalls ); + expect( event.preventDefault ).not.toHaveBeenCalled(); expect( document.body.textContent ).not.toContain( 'Congrats' ); } ); - test( 'form submit step 8: fallback trigger click when form.submit throws', () => { - bootOnboarding( { page: 'integrations', currentStep: 'step 8' }, getIntegrationsDom() ); + test( 'skips settings submission when the form disappears before the update completes', () => { + bootOnboarding( { currentStep: 'step 5' } ); + const deferred = $.Deferred(); + postSpy.mockImplementationOnce( () => deferred ); + const form = document.getElementById( 'hcaptcha-options' ); + form.submit = jest.fn(); + + $( form ).trigger( 'submit' ); + form.remove(); + deferred.resolve( { success: true } ); + + expect( form.submit ).not.toHaveBeenCalled(); + expect( sessionStorage.getItem( 'hcapOnbGoAntiSpam' ) ).toBe( '1' ); + } ); + + test( 'form submit step 9: fallback trigger click when form.submit throws', () => { + bootOnboarding( { page: 'integrations', currentStep: 'step 9' }, getIntegrationsDom() ); const form = document.getElementById( 'hcaptcha-options' ); @@ -797,16 +888,20 @@ describe( 'onboarding.js', () => { test( 'automatic setup falls back to window.location.href when form has no submit method', () => { bootOnboarding(); - // Ensure form.submit is not a function (jsdom normally provides one). + // Simulate a browser that cannot submit the form. const form = document.getElementById( 'hcaptcha-options' ); form.submit = 'not-a-function'; + const submitSpy = jest.spyOn( HTMLFormElement.prototype, 'submit' ).mockImplementation( () => { + throw new Error( 'submit blocked' ); + } ); $( '.hcap-onb-done' ).trigger( 'click' ); $( '.hcap-onb-auto-setup' ).trigger( 'click' ); expect( locationHref ).toContain( 'auto-setup=1' ); expect( locationHref ).toContain( 'hcaptcha_onboarding_nonce=auto_setup_nonce' ); + submitSpy.mockRestore(); } ); test( 'automatic setup falls back to window.location.href when form element is absent', () => { @@ -870,18 +965,26 @@ describe( 'onboarding.js', () => { Storage.prototype.setItem.mockRestore(); } ); - // ─── init: page=general num=7 with goIntegrations flag ─────────────────── + // ─── init: redirects after saving a settings page ───────────────────────── - test( 'init redirects to integrations when goIntegrations session flag is set at step 7', () => { + test( 'init redirects to Anti-Spam after saving General', () => { + sessionStorage.setItem( 'hcapOnbGoAntiSpam', '1' ); + bootOnboarding( { page: 'general', currentStep: 'step 6' } ); + + expect( locationHref ).toContain( 'page=hcaptcha-antispampage' ); + expect( sessionStorage.getItem( 'hcapOnbGoAntiSpam' ) ).toBeNull(); + } ); + + test( 'init redirects to integrations when goIntegrations session flag is set at step 8', () => { sessionStorage.setItem( 'hcapOnbGoIntegrations', '1' ); - bootOnboarding( { page: 'general', currentStep: 'step 7' } ); + bootOnboarding( { page: 'antispam', currentStep: 'step 8' } ); expect( locationHref ).toContain( 'page=hcaptcha-integrations' ); expect( sessionStorage.getItem( 'hcapOnbGoIntegrations' ) ).toBeNull(); } ); - test( 'init does not redirect when goIntegrations flag is absent at step 7', () => { - bootOnboarding( { page: 'general', currentStep: 'step 7' } ); + test( 'init does not redirect when goIntegrations flag is absent at step 8', () => { + bootOnboarding( { page: 'antispam', currentStep: 'step 8' } ); expect( locationHref ).toBe( 'http://localhost/' ); } ); @@ -1124,8 +1227,10 @@ describe( 'onboarding.js', () => { Object.defineProperty( window, 'sessionStorage', descriptor ); } ); - test( 'form submit step 6 continues when sessionStorage is unavailable', () => { - bootOnboarding( { currentStep: 'step 6' } ); + test( 'form submit step 5 continues when sessionStorage is unavailable', () => { + bootOnboarding( { currentStep: 'step 5' } ); + const form = document.getElementById( 'hcaptcha-options' ); + form.submit = jest.fn(); const descriptor = Object.getOwnPropertyDescriptor( window, 'sessionStorage' ); Object.defineProperty( window, 'sessionStorage', { configurable: true, @@ -1135,6 +1240,7 @@ describe( 'onboarding.js', () => { expect( () => { $( '#hcaptcha-options' ).trigger( 'submit' ); } ).not.toThrow(); + expect( form.submit ).toHaveBeenCalledTimes( 1 ); Object.defineProperty( window, 'sessionStorage', descriptor ); } ); diff --git a/tests/php/ci-shard-dependencies.php b/tests/php/ci-shard-dependencies.php index d225e749d..379544387 100644 --- a/tests/php/ci-shard-dependencies.php +++ b/tests/php/ci-shard-dependencies.php @@ -20,7 +20,7 @@ */ function hcaptcha_ci_shard_dependencies( array $units ): array { $public_plugins = array_fill_keys( - explode( ' ', 'acf-extended bbpress blocksy-companion buddypress coblocks contact-form-7 download-manager elementor essential-addons-for-elementor-lite essential-blocks events-manager fluentform formidable forminator give jetpack kadence-blocks learnpress mailchimp-for-wp mailin mailpoet maintenance metform ninja-forms otter-blocks password-protected theme-my-login tutor ultimate-addons-for-gutenberg ultimate-member woocommerce wordfence wpforms-lite wpforo' ), + explode( ' ', 'acf-extended bbpress blocksy-companion buddypress coblocks contact-form-7 download-manager easy-digital-downloads elementor essential-addons-for-elementor-lite essential-blocks events-manager fluentform formidable forminator give html-forms jetpack kadence-blocks learnpress mailchimp-for-wp mailin mailpoet maintenance metform ninja-forms otter-blocks password-protected simple-membership supportcandy theme-my-login tutor ultimate-addons-for-gutenberg ultimate-member woocommerce wordfence wpforms-lite wpforo' ), true ); $private_plugins = array_fill_keys( diff --git a/tests/php/integration.suite.yml b/tests/php/integration.suite.yml index 41ba2d38d..fb3da4160 100644 --- a/tests/php/integration.suite.yml +++ b/tests/php/integration.suite.yml @@ -1,4 +1,169 @@ bootstrap: ./_bootstrap.php +coverage: + include: + - ./src/php/Abilities/Abilities.php + - ./src/php/Abstracts/LoginBase.php + - ./src/php/ACFE/Form.php + - ./src/php/Admin/AdminNotices.php + - ./src/php/Admin/Events/Events.php + - ./src/php/Admin/MaxMindDb.php + - ./src/php/Admin/Notifications.php + - ./src/php/Admin/OnboardingWizard.php + - ./src/php/Admin/PluginStats.php + - ./src/php/Admin/Privacy.php + - ./src/php/Admin/SupportModal.php + - ./src/php/Admin/WhatsNew.php + - ./src/php/Affiliates/Login.php + - ./src/php/Affiliates/Register.php + - ./src/php/Asgaros/Base.php + - ./src/php/Asgaros/Form.php + - ./src/php/AutoVerify/AutoVerify.php + - ./src/php/Avada/Form.php + - ./src/php/BackInStockNotifier/Form.php + - ./src/php/BBPress/Login.php + - ./src/php/BBPress/LostPassword.php + - ./src/php/BBPress/NewTopic.php + - ./src/php/BBPress/Register.php + - ./src/php/BBPress/Reply.php + - ./src/php/BeaverBuilder/Base.php + - ./src/php/BeaverBuilder/Contact.php + - ./src/php/BeaverBuilder/Login.php + - ./src/php/Blocksy/NewsletterSubscribe.php + - ./src/php/Blocksy/ProductReview.php + - ./src/php/Blocksy/Waitlist.php + - ./src/php/Brizy/Form.php + - ./src/php/BuddyPress/CreateGroup.php + - ./src/php/BuddyPress/Register.php + - ./src/php/CF7/Admin.php + - ./src/php/CF7/CF7.php + - ./src/php/CF7/ReallySimpleCaptcha.php + - ./src/php/ClassifiedListing/Contact.php + - ./src/php/ClassifiedListing/Login.php + - ./src/php/ClassifiedListing/LostPassword.php + - ./src/php/ClassifiedListing/Register.php + - ./src/php/CLI/Commands.php + - ./src/php/CoBlocks/Form.php + - ./src/php/CustomerReviews/Review.php + - ./src/php/CustomerReviews/QuestionAnswer.php + - ./src/php/DelayedScript/DelayedScript.php + - ./src/php/Divi/Comment.php + - ./src/php/Divi/Contact.php + - ./src/php/Divi/EmailOptin.php + - ./src/php/Divi/Login.php + - ./src/php/DownloadManager/DownloadManager.php + - ./src/php/EasyDigitalDownloads/Checkout.php + - ./src/php/EasyDigitalDownloads/LostPassword.php + - ./src/php/EasyDigitalDownloads/Register.php + - ./src/php/ElementorPro/HCaptchaHandler.php + - ./src/php/ElementorPro/Login.php + - ./src/php/EssentialAddons/Base.php + - ./src/php/EssentialAddons/Login.php + - ./src/php/EssentialAddons/Register.php + - ./src/php/EssentialBlocks/Form.php + - ./src/php/EventsManager/Booking.php + - ./src/php/FluentForm/Form.php + - ./src/php/FormidableForms/Form.php + - ./src/php/Forminator/Form.php + - ./src/php/GiveWP/Base.php + - ./src/php/GiveWP/Form.php + - ./src/php/GiveWP/PayPalGrant.php + - ./src/php/GravityForms/Field.php + - ./src/php/GravityForms/Form.php + - ./src/php/Helpers/API.php + - ./src/php/Helpers/CloudflareDetector.php + - ./src/php/Helpers/DB.php + - ./src/php/Helpers/EntryData.php + - ./src/php/Helpers/FormSubmitTime.php + - ./src/php/Helpers/HCaptcha.php + - ./src/php/Helpers/Install.php + - ./src/php/Helpers/LoginAttempts.php + - ./src/php/Helpers/Minify/CSS.php + - ./src/php/Helpers/Minify/JS.php + - ./src/php/Helpers/Pages.php + - ./src/php/Helpers/Playground.php + - ./src/php/HTMLForms/Form.php + - ./src/php/IcegramExpress/Form.php + - ./src/php/Jetpack/Base.php + - ./src/php/Jetpack/Form.php + - ./src/php/Kadence/AdvancedForm.php + - ./src/php/Kadence/Base.php + - ./src/php/Kadence/BlockParser.php + - ./src/php/Kadence/Form.php + - ./src/php/LearnDash/LostPassword.php + - ./src/php/LearnDash/Register.php + - ./src/php/LearnPress/Checkout.php + - ./src/php/LearnPress/Register.php + - ./src/php/LoginSignupPopup/Register.php + - ./src/php/Mailchimp/Form.php + - ./src/php/MailPoet/Form.php + - ./src/php/Main.php + - ./src/php/Maintenance/Login.php + - ./src/php/MemberPress/Login.php + - ./src/php/MemberPress/Register.php + - ./src/php/MetForm/Form.php + - ./src/php/Migrations/Migrations.php + - ./src/php/MigrationWizard/DetectionResult.php + - ./src/php/MigrationWizard/Detectors/EssentialBlocksDetector.php + - ./src/php/NF/Field.php + - ./src/php/NF/NF.php + - ./src/php/Otter/Form.php + - ./src/php/Passster/Protect.php + - ./src/php/PasswordProtected/Protect.php + - ./src/php/ProfileBuilder/Login.php + - ./src/php/ProfileBuilder/LostPassword.php + - ./src/php/ProfileBuilder/Register.php + - ./src/php/ProtectContent/ProtectContent.php + - ./src/php/Quform/Quform.php + - ./src/php/Sendinblue/Sendinblue.php + - ./src/php/SimpleMembership/Login.php + - ./src/php/SimpleMembership/LostPassword.php + - ./src/php/SimpleMembership/Register.php + - ./src/php/Spectra/Form.php + - ./src/php/Subscriber/Form.php + - ./src/php/SupportCandy/Form.php + - ./src/php/ThemeMyLogin/Assets.php + - ./src/php/ThemeMyLogin/Login.php + - ./src/php/ThemeMyLogin/LostPassword.php + - ./src/php/ThemeMyLogin/Register.php + - ./src/php/ThemeMyLogin/Signup.php + - ./src/php/Tutor/Checkout.php + - ./src/php/Tutor/Login.php + - ./src/php/Tutor/LostPassword.php + - ./src/php/Tutor/Register.php + - ./src/php/UltimateAddons/Base.php + - ./src/php/UltimateAddons/Login.php + - ./src/php/UltimateAddons/Register.php + - ./src/php/UM/Base.php + - ./src/php/UM/Login.php + - ./src/php/UM/LostPassword.php + - ./src/php/UM/Register.php + - ./src/php/UsersWP/ForgotPassword.php + - ./src/php/UsersWP/Login.php + - ./src/php/UsersWP/Register.php + - ./src/php/WC/AddPaymentMethod.php + - ./src/php/WC/Checkout.php + - ./src/php/WC/Login.php + - ./src/php/WC/LostPassword.php + - ./src/php/WC/OrderTracking.php + - ./src/php/WC/OrderWithdrawal.php + - ./src/php/WC/Register.php + - ./src/php/WCGermanized/ReturnRequest.php + - ./src/php/WCWishlists/CreateList.php + - ./src/php/WooCommercePayPalPayments/Button.php + - ./src/php/Wordfence/General.php + - ./src/php/WP/Comment.php + - ./src/php/WP/Login.php + - ./src/php/WP/LoginOut.php + - ./src/php/WP/LostPassword.php + - ./src/php/WP/PasswordProtected.php + - ./src/php/WP/Register.php + - ./src/php/WP/Signup.php + - ./src/php/WPDiscuz/Comment.php + - ./src/php/WPDiscuz/Subscribe.php + - ./src/php/WPForms/Form.php + - ./src/php/WPForo/NewTopic.php + - ./src/php/WPForo/Reply.php + - ./src/php/WPJobOpenings/Form.php extensions: enabled: - HCaptcha\Tests\Codeception\FunctionMockerExtension diff --git a/tests/php/integration/AAAMainTest.php b/tests/php/integration/AAAMainTest.php index dc0e8b51d..1ac6c6219 100644 --- a/tests/php/integration/AAAMainTest.php +++ b/tests/php/integration/AAAMainTest.php @@ -225,19 +225,6 @@ public function test_init_on_xml_rpc(): void { self::assertSame( [], $this->get_protected_property( $subject, 'loaded_classes' ) ); } - /** - * Test declaring compatibility with WooCommerce features. - */ - public function test_declare_wc_compatibility(): void { - $features = Mockery::mock( 'alias:Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ); - $features->shouldReceive( 'declare_compatibility' ) - ->once() - ->with( 'custom_order_tables', HCAPTCHA_FILE ) - ->andReturn( true ); - - ( new Main() )->declare_wc_compatibility(); - } - /** * Test that Tutor LMS Pro is the preferred module source. * @@ -629,6 +616,153 @@ public function dp_test_csp_headers(): array { ]; } + /** + * Test CSP parsing retains the restrictions a browser actually enforces. + * + * @dataProvider dp_test_parse_csp + * + * @param string $policy Serialized policy. + * @param array $expected Effective directives. + */ + public function test_parse_csp( string $policy, array $expected ): void { + $subject = new Main(); + $parse = $this->set_method_accessibility( $subject, 'parse_csp' ); + + self::assertSame( $expected, $parse->invoke( $subject, $policy ) ); + } + + /** + * CSP parsing cases. + * + * @return array + */ + public function dp_test_parse_csp(): array { + return [ + 'valueless restrictions' => [ + 'sandbox; upgrade-insecure-requests; img-src; object-src; future-directive', + [ + 'sandbox' => [], + 'upgrade-insecure-requests' => [], + 'img-src' => [], + 'object-src' => [], + 'future-directive' => [], + ], + ], + 'first duplicate wins' => [ + "script-src 'none'; script-src *", + [ 'script-src' => [ "'none'" ] ], + ], + 'case insensitive duplicate' => [ + "ScRiPt-SrC 'self'; SCRIPT-SRC *", + [ 'script-src' => [ "'self'" ] ], + ], + 'empty first duplicate' => [ + 'img-src; IMG-SRC *', + [ 'img-src' => [] ], + ], + 'ASCII whitespace' => [ + " \tFRAME-SRC\t'self' https://good.example\f;\r\n sandbox\t ", + [ + 'frame-src' => [ "'self'", 'https://good.example' ], + 'sandbox' => [], + ], + ], + 'reporting and trusted types' => [ + "report-uri /csp; require-trusted-types-for 'script'; trusted-types app", + [ + 'report-uri' => [ '/csp' ], + 'require-trusted-types-for' => [ "'script'" ], + 'trusted-types' => [ 'app' ], + ], + ], + 'empty separators' => [ '; ;', [] ], + ]; + } + + /** + * Test CSP augmentation keeps separate policies and unrelated headers. + */ + public function test_csp_headers_preserve_policy_intersection(): void { + add_filter( 'hcap_add_csp_headers', '__return_true' ); + $subject = new Main(); + $headers = [ + 'X-Test' => 'unchanged', + 'content-security-policy' => "script-src 'self'; sandbox", + 'Content-Security-Policy' => "script-src 'none'; SCRIPT-SRC *; img-src", + ]; + $result = $subject->csp_headers( $headers ); + $parse = $this->set_method_accessibility( $subject, 'parse_csp' ); + $parts = explode( ', ', $result['Content-Security-Policy'] ); + + self::assertSame( 'unchanged', $result['X-Test'] ); + self::assertArrayNotHasKey( 'content-security-policy', $result ); + self::assertCount( 2, $parts ); + $first = $parse->invoke( $subject, $parts[0] ); + $second = $parse->invoke( $subject, $parts[1] ); + + self::assertSame( [], $first['sandbox'] ); + self::assertSame( [], $second['img-src'] ); + self::assertContains( "'self'", $first['script-src'] ); + self::assertNotContains( "'self'", $second['script-src'] ); + self::assertNotContains( '*', $second['script-src'] ); + self::assertContains( 'https://hcaptcha.com', $second['script-src'] ); + } + + /** + * Test CSP augmentation does not union a serialized policy list. + */ + public function test_csp_headers_preserve_serialized_policy_list(): void { + add_filter( 'hcap_add_csp_headers', '__return_true' ); + $subject = new Main(); + $result = $subject->csp_headers( [ 'Content-Security-Policy' => "script-src 'self', script-src 'none'" ] ); + $parts = explode( ', ', $result['Content-Security-Policy'] ); + + self::assertCount( 2, $parts ); + self::assertStringContainsString( "'self'", $parts[0] ); + self::assertStringNotContainsString( "'self'", $parts[1] ); + self::assertStringContainsString( "'none'", $parts[1] ); + } + + /** + * Empty policy members must not impose new restrictions on allowed sources. + */ + public function test_csp_headers_ignore_empty_policy_members(): void { + add_filter( 'hcap_add_csp_headers', '__return_true' ); + $subject = new Main(); + $policy = "script-src https://cdn.example, ,\t"; + $plain = $subject->csp_headers( [ 'Content-Security-Policy' => 'script-src https://cdn.example' ] ); + $result = $subject->csp_headers( [ 'Content-Security-Policy' => ', ,' . $policy ] ); + + self::assertSame( $plain, $result ); + self::assertSame( + [ 'Content-Security-Policy' => '' ], + $subject->csp_headers( [ 'Content-Security-Policy' => ", ,\t,\r\n" ] ) + ); + } + + /** + * The directive filter receives each independent policy as an array. + */ + public function test_csp_headers_filter_each_policy(): void { + add_filter( 'hcap_add_csp_headers', '__return_true' ); + $seen = []; + add_filter( + 'hcap_csp_headers', + static function ( array $directives ) use ( &$seen ): array { + $seen[] = $directives; + $directives[] = "object-src 'none'"; + + return $directives; + } + ); + $result = ( new Main() )->csp_headers( [ 'Content-Security-Policy' => "script-src 'self', script-src 'none'" ] ); + + self::assertCount( 2, $seen ); + self::assertStringContainsString( "'self'", $seen[0][0] ); + self::assertStringNotContainsString( "'self'", $seen[1][0] ); + self::assertSame( 2, substr_count( $result['Content-Security-Policy'], "object-src 'none'" ) ); + } + /** * Test print_inline_styles(). * @@ -1629,6 +1763,9 @@ public function test_denylist_ip( $denylisted_ips, $client_ip, bool $expected ): */ public function dp_test_denylist_ip(): array { return [ + 'IPv6 outside IPv4 range' => [ '38.0.0.0-38.255.255.255', '2600::1', false ], + 'numeric packed outsider' => [ '49.101.49.48-49.101.49.48', '49.48.69.57', false ], + 'numeric packed endpoint' => [ '49.101.49.48-49.101.49.48', '49.101.49.48', true ], 'no settings, local ip' => [ '', false, false ], 'some ips, local ip' => [ " 4444444.777.2 \r\n 220.45.45.1 \r\n", false, false ], 'some ips, not matching ip' => [ " 4444444.777.2 \r\n 220.45.45.1 \r\n", '220.45.45.2', false ], @@ -1665,6 +1802,9 @@ public function test_allowlist_ip( $allowlisted_ips, $client_ip, bool $expected */ public function dp_test_allowlist_ip(): array { return [ + 'IPv6 outside IPv4 range' => [ '38.0.0.0-38.255.255.255', '2600::1', false ], + 'numeric packed outsider' => [ '49.101.49.48-49.101.49.48', '49.48.69.57', false ], + 'numeric packed endpoint' => [ '49.101.49.48-49.101.49.48', '49.101.49.48', true ], 'no settings, local ip' => [ '', false, false ], 'some ips, local ip' => [ " 4444444.777.2 \r\n 220.45.45.1 \r\n", false, false ], 'some ips, not matching ip' => [ " 4444444.777.2 \r\n 220.45.45.1 \r\n", '220.45.45.2', false ], @@ -2236,17 +2376,21 @@ public function dp_test_load_modules(): array { 'Colorlib Customizer Login' => [ [ 'colorlib_customizer_status', 'login' ], 'colorlib-login-customizer/colorlib-login-customizer.php', - \HCaptcha\ColorlibCustomizer\Login::class, + [ + \HCaptcha\ColorlibCustomizer\Login::class, + Login::class, + LoginOut::class, + ], ], 'Colorlib Customizer Lost Password' => [ [ 'colorlib_customizer_status', 'lost_pass' ], 'colorlib-login-customizer/colorlib-login-customizer.php', - \HCaptcha\ColorlibCustomizer\LostPassword::class, + [ \HCaptcha\ColorlibCustomizer\LostPassword::class, LostPassword::class ], ], 'Colorlib Customizer Register' => [ [ 'colorlib_customizer_status', 'register' ], 'colorlib-login-customizer/colorlib-login-customizer.php', - \HCaptcha\ColorlibCustomizer\Register::class, + [ \HCaptcha\ColorlibCustomizer\Register::class, Register::class ], ], 'Contact Form 7' => [ [ 'cf7_status', 'form' ], diff --git a/tests/php/integration/ACFE/FormTest.php b/tests/php/integration/ACFE/FormTest.php index d73141ba7..7c498b5c5 100644 --- a/tests/php/integration/ACFE/FormTest.php +++ b/tests/php/integration/ACFE/FormTest.php @@ -14,6 +14,7 @@ use acfe_field_recaptcha; use HCaptcha\ACFE\Form; +use HCaptcha\Helpers\FormSubmitTime; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; use ReflectionClass; @@ -62,6 +63,18 @@ class FormTest extends HCaptchaPluginWPTestCase { 'acfe/form/render/before_fields', ]; + /** + * Setup test. + * + * @throws ReflectionException Reflection exception. + */ + public function setUp(): void { + parent::setUp(); + + // Rebuild the supported forms cache using this test's protection settings. + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + } + /** * Test a live ACF Extended form with its reCAPTCHA field replaced by hCaptcha. * @@ -144,6 +157,7 @@ public function test_init_hooks(): void { $subject = new Form(); self::assertSame( 10, has_action( 'acfe/form/render/before_fields', [ $subject, 'before_fields' ] ) ); + self::assertSame( 10, has_action( 'acfe/form/validate_form', [ $subject, 'validate_form' ] ) ); self::assertSame( 8, has_action( Form::RENDER_HOOK, [ $subject, 'remove_recaptcha_render' ] ) ); self::assertSame( 11, has_action( Form::RENDER_HOOK, [ $subject, 'add_hcaptcha' ] ) ); self::assertSame( 9, has_filter( Form::VALIDATION_HOOK, [ $subject, 'remove_recaptcha_verify' ] ) ); @@ -224,6 +238,24 @@ public function test_add_hcaptcha( array $field, string $expected ): void { hcaptcha()->init_hooks(); + if ( $expected ) { + // Render the expected form after setUp() has installed the test settings. + $expected = sprintf( + $expected, + $this->get_hcap_form( + [ + 'id' => [ + 'source' => [ + 'acf-extended-pro/acf-extended.php', + 'acf-extended/acf-extended.php', + ], + 'form_id' => 0, + ], + ] + ) + ); + } + ob_start(); $subject->add_hcaptcha( $field ); @@ -243,18 +275,8 @@ public function dp_test_add_hcaptcha(): array { 'key' => 'some-key', 'name' => 'some-name', ], - '
    ' . - $this->get_hcap_form( - [ - 'id' => [ - 'source' => [ - 'acf-extended-pro/acf-extended.php', - 'acf-extended/acf-extended.php', - ], - 'form_id' => 0, - ], - ] - ) . '
    ', + '
    %s
    ' . + '
    ', ], 'some field' => [ [ 'type' => 'some' ], @@ -296,6 +318,7 @@ public function test_remove_recaptcha_verify(): void { * @return void * @dataProvider dp_test_verify * @throws ReflectionException ReflectionException. + * @noinspection PhpConditionAlreadyCheckedInspection */ public function test_verify( bool $result, $expected ): void { $valid = ! $expected; @@ -313,6 +336,8 @@ public function test_verify( bool $result, $expected ): void { $this->prepare_verify_request( $value, $result ); $subject = new Form(); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Test request fixture. + $post_data = $_POST; add_filter( 'wp_doing_ajax', '__return_true' ); @@ -320,6 +345,8 @@ public function test_verify( bool $result, $expected ): void { self::assertSame( $form_id, $this->get_protected_property( $subject, 'form_id' ) ); remove_filter( 'wp_doing_ajax', '__return_true' ); + $_POST = $post_data; + hcaptcha()->has_result = false; self::assertSame( $expected, $subject->verify( $valid, $value, $field, $input ) ); self::assertSame( $form_id, $this->get_protected_property( $subject, 'form_id' ) ); @@ -337,6 +364,111 @@ public function dp_test_verify(): array { ]; } + /** + * Test frontend AJAX validation consumes FST once and hands its result to the final POST. + * + * @param bool $result Request result. + * @param bool|string $expected Expected result. + * + * @dataProvider dp_test_verify + * @throws ReflectionException Reflection exception. + * @noinspection PhpConditionAlreadyCheckedInspection + */ + public function test_verify_frontend_ajax_in_admin_context( bool $result, $expected ): void { + $form_id = 5; + $value = 'some hcaptcha response'; + $field = [ 'required' => true ]; + $payload = [ + 'post_id' => '123', + 'issued_at' => time() - 10, + 'ttl' => FormSubmitTime::DEFAULT_TOKEN_TTL, + 'token_id' => wp_generate_password( 32, false ), + ]; + $fst = new FormSubmitTime(); + $method = $this->set_method_accessibility( $fst, 'token_from_payload' ); + $token = $method->invoke( $fst, $payload ); + $nonce = 'hcap_fst_nonce_' . explode( '-', $token, 2 )[1]; + + $_POST['_acf_form'] = 'acf-form'; + $this->register_acf_form( $form_id ); + $this->prepare_widget_id( $form_id ); + $this->prepare_verify_request( $value, $result ); + $_POST['hcap_fst_token'] = $token; + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Test request fixture. + $post_data = $_POST; + $subject = new Form(); + + set_transient( $nonce, $payload, FormSubmitTime::DEFAULT_TOKEN_TTL ); + remove_filter( 'hcap_verify_fst_token', '__return_true' ); + set_current_screen( 'dashboard' ); + add_filter( 'wp_doing_ajax', '__return_true' ); + + try { + self::assertSame( $expected, $subject->verify( true, $value, $field, 'captcha' ) ); + self::assertFalse( get_transient( $nonce ) ); + } finally { + remove_filter( 'wp_doing_ajax', '__return_true' ); + set_current_screen( 'front' ); + } + + $_POST = $post_data; + hcaptcha()->has_result = false; + self::assertSame( $expected, $subject->verify( true, $value, $field, 'captcha' ) ); + + $_POST = $post_data; + hcaptcha()->has_result = false; + // Restore the FST setting that a new HTTP request would load again. + hcaptcha()->settings()->set( 'set_min_submit_time', [ 'on' ] ); + self::assertSame( 'Token replayed or expired.', $subject->verify( true, $value, $field, 'captcha' ) ); + } + + /** + * Test cached AJAX validation cannot be reused by a different submission. + * + * @noinspection PhpConditionAlreadyCheckedInspection + */ + public function test_verify_does_not_reuse_another_submission(): void { + $form_id = 5; + $field = [ 'required' => true ]; + $value = 'some hcaptcha response'; + + $_POST['_acf_form'] = 'acf-form'; + $this->register_acf_form( $form_id ); + $this->prepare_widget_id( $form_id ); + $this->prepare_verify_request( $value ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Test request fixture. + $post_data = $_POST; + $subject = new Form(); + + add_filter( 'wp_doing_ajax', '__return_true' ); + self::assertTrue( $subject->verify( true, $value, $field, 'captcha' ) ); + remove_filter( 'wp_doing_ajax', '__return_true' ); + + $_POST = $post_data; + $_POST['h-captcha-response'] = 'other response'; + hcaptcha()->has_result = false; + $this->prepare_verify_request( 'other response', false ); + + self::assertSame( 'The hCaptcha is invalid.', $subject->verify( true, 'other response', $field, 'captcha' ) ); + } + + /** + * Test admin AJAX field editing without a frontend form still skips hCaptcha. + */ + public function test_verify_admin_ajax_without_frontend_form(): void { + $subject = new Form(); + + set_current_screen( 'dashboard' ); + add_filter( 'wp_doing_ajax', '__return_true' ); + + try { + self::assertTrue( $subject->verify( false, '', [ 'required' => true ], 'captcha' ) ); + } finally { + remove_filter( 'wp_doing_ajax', '__return_true' ); + set_current_screen( 'front' ); + } + } + /** * Test verify when field NOT required. * @@ -353,6 +485,131 @@ public function test_verify_when_NOT_required(): void { self::assertFalse( $subject->verify( false, $value, $field, $input ) ); } + /** + * An optional submitted field must not stand in for the form's required CAPTCHA. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function test_validate_form_rejects_optional_field_substitution(): void { + $form = $this->register_sec052_form( true ); + + $_POST['acf'] = [ 'field_sec052_optional' => '' ]; + + $subject = new Form(); + acf_reset_validation_errors(); + + try { + self::assertTrue( $subject->verify( true, '', [ 'required' => false ], 'acf[field_sec052_optional]' ) ); + $subject->validate_form( $form ); + self::assertSame( 'Bad hCaptcha signature!', acf_get_validation_errors()[0]['message'] ); + } finally { + acf_reset_validation_errors(); + } + } + + /** + * A verified form shares one CAPTCHA result with its required field validator. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function test_validate_form_reuses_verified_result(): void { + $form = $this->register_sec052_form( true ); + + $_POST['acf'] = [ 'field_sec052_required' => 'valid response' ]; + $this->prepare_widget_id( 52 ); + $this->prepare_verify_request( 'valid response' ); + + $subject = new Form(); + acf_reset_validation_errors(); + $has_result = hcaptcha()->has_result; + + try { + $subject->validate_form( $form ); + self::assertFalse( acf_get_validation_errors() ); + + hcaptcha()->has_result = false; + self::assertTrue( $subject->verify( false, 'valid response', [ 'required' => true ], 'acf[field_sec052_required]' ) ); + } finally { + hcaptcha()->has_result = $has_result; + acf_reset_validation_errors(); + } + } + + /** + * Optional-only forms retain their existing no-CAPTCHA submission behavior. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function test_validate_form_ignores_optional_only_fields(): void { + $form = $this->register_sec052_form( false ); + + $_POST['acf'] = [ 'field_sec052_optional' => '' ]; + + $subject = new Form(); + acf_reset_validation_errors(); + + try { + $subject->validate_form( $form ); + self::assertFalse( acf_get_validation_errors() ); + } finally { + acf_reset_validation_errors(); + } + } + + /** + * Register a target form and its reCAPTCHA field metadata. + * + * @param bool $required Whether the target CAPTCHA is required. + * + * @return array + * @noinspection PhpUndefinedFunctionInspection + */ + private function register_sec052_form( bool $required ): array { + $group_key = $required ? 'group_hcaptcha_sec052_required' : 'group_hcaptcha_sec052_optional_only'; + $fields = [ + [ + 'key' => 'field_sec052_optional', + 'name' => 'optional_captcha', + 'label' => 'Optional CAPTCHA', + 'type' => 'acfe_recaptcha', + 'required' => 0, + ], + ]; + + if ( $required ) { + array_unshift( + $fields, + [ + 'key' => 'field_sec052_required', + 'name' => 'required_captcha', + 'label' => 'Required CAPTCHA', + 'type' => 'acfe_recaptcha', + 'required' => 1, + ] + ); + } + + $form = [ + 'ID' => 52, + 'name' => 'hcaptcha-sec052', + 'field_groups' => [ $group_key ], + ]; + + acf_add_local_field_group( + [ + 'key' => $group_key, + 'title' => 'SEC052 form fields', + 'fields' => $fields, + 'location' => [], + ] + ); + + $_POST['_acf_form'] = 'acf-form'; + $this->register_acf_form( $form ); + + return $form; + } + /** * Test verify direct POST without previous AJAX validation. * diff --git a/tests/php/integration/Abilities/AbilitiesTest.php b/tests/php/integration/Abilities/AbilitiesTest.php index 90bc6e0ca..2a4062641 100644 --- a/tests/php/integration/Abilities/AbilitiesTest.php +++ b/tests/php/integration/Abilities/AbilitiesTest.php @@ -7,7 +7,9 @@ // phpcs:disable Generic.Commenting.DocComment.MissingShort /** @noinspection PhpLanguageLevelInspection */ +/** @noinspection PhpUndefinedNamespaceInspection */ /** @noinspection PhpUndefinedClassInspection */ +/** @noinspection PhpUndefinedFunctionInspection */ // phpcs:enable Generic.Commenting.DocComment.MissingShort namespace HCaptcha\Tests\Integration\Abilities; @@ -22,7 +24,11 @@ use HCaptcha\Tests\Integration\HCaptchaWPTestCase; use Mockery; use ReflectionException; +use tad\FunctionMocker\FunctionMocker; use WP_Error; +use function Patchwork\relay; + +require_once __DIR__ . '/UnreadableImportStream.php'; /** * Test Abilities API integration. @@ -30,6 +36,83 @@ * @group abilities */ class AbilitiesTest extends HCaptchaWPTestCase { + /** + * Older WordPress versions leave Abilities API registration unavailable. + */ + public function test_registration_without_wordpress_abilities_api(): void { + FunctionMocker::replace( + 'function_exists', + static function ( string $name ): bool { + if ( in_array( $name, [ 'wp_register_ability_category', 'wp_register_ability' ], true ) ) { + return false; + } + + return relay(); + } + ); + $subject = new Abilities(); + + $subject->register_categories(); + $subject->register_abilities(); + self::assertFalse( function_exists( 'hcaptcha_nonexistent_ability' ) ); + } + + /** + * Threat queries also work against the Events schema before Trash Folder columns. + */ + public function test_legacy_events_schema_queries(): void { + global $wpdb; + + remove_all_filters( 'query', 10 ); + Events::create_table(); + $subject = new Abilities(); + $table = $wpdb->prefix . Events::TABLE_NAME; + $from = '2000-01-01 00:00:00'; + $to = '2000-01-01 00:01:00'; + $total = $this->set_method_accessibility( $subject, 'get_threats_total' ); + $failed = $this->set_method_accessibility( $subject, 'get_threats_failed_rows' ); + + self::assertSame( '0', (string) $total->invoke( $subject, $table, $from, $to, false ) ); + self::assertSame( [], $failed->invoke( $subject, $table, $from, $to, false ) ); + } + + /** + * Persist the current offender map through the same option used by lookups. + */ + public function test_set_offender_blocks(): void { + $subject = new Abilities(); + $blocks = [ + 'hashed-offender' => [ + 'expires_at' => time() + 60, + 'reason' => 'test', + 'created_at' => time(), + ], + ]; + $this->set_method_accessibility( $subject, 'set_offender_blocks' )->invoke( $subject, $blocks ); + + self::assertSame( $blocks, get_option( 'hcaptcha_offender_blocks_v1' ) ); + } + + /** + * A file that becomes unreadable after stat is rejected before decoding. + */ + public function test_import_file_read_failure(): void { + $scheme = 'hcapunreadable'; + self::assertTrue( stream_wrapper_register( $scheme, UnreadableImportStream::class ) ); + + try { + $subject = new Abilities(); + $method = $this->set_method_accessibility( $subject, 'read_import_file' ); + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- The stream intentionally fails when opened. + $result = @$method->invoke( $subject, $scheme . '://payload' ); + + self::assertInstanceOf( WP_Error::class, $result ); + self::assertSame( 'Input file is too large or cannot be read.', $result->get_error_message() ); + } finally { + stream_wrapper_unregister( $scheme ); + } + } + /** * Test init() and init_hooks(). @@ -365,6 +448,83 @@ public function test_import_settings_missing_input_file(): void { self::assertSame( 'Input file not found or unreadable.', $result->get_error_message() ); } + /** + * Test import_settings() rejects a directory before attempting to read it. + */ + public function test_import_settings_rejects_directory(): void { + $result = ( new Abilities() )->import_settings( + [ 'input_file' => sys_get_temp_dir() ] + ); + + self::assertInstanceOf( WP_Error::class, $result ); + self::assertSame( 'hcaptcha_invalid_payload', $result->get_error_code() ); + self::assertSame( 'Input file not found or unreadable.', $result->get_error_message() ); + } + + /** + * Test import_settings() rejects an oversized regular file before JSON decoding. + */ + public function test_import_settings_rejects_oversized_file(): void { + $file = tempnam( HCAPTCHA_PATH, 'hcap' ); + self::assertNotFalse( $file ); + + try { + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents + file_put_contents( $file, str_repeat( ' ', 1024 * 1024 + 1 ) ); + + $result = ( new Abilities() )->import_settings( + [ + 'input_file' => $file, + 'dry_run' => true, + ] + ); + + self::assertInstanceOf( WP_Error::class, $result ); + self::assertSame( 'hcaptcha_invalid_payload', $result->get_error_code() ); + self::assertSame( 'Input file is too large.', $result->get_error_message() ); + } finally { + if ( is_string( $file ) && file_exists( $file ) ) { + // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink + unlink( $file ); + } + } + } + + /** + * Test import_settings() still accepts valid JSON at the exact file limit. + */ + public function test_import_settings_accepts_file_at_size_limit(): void { + $file = tempnam( HCAPTCHA_PATH, 'hcap' ); + self::assertNotFalse( $file ); + + try { + $payload = ( new SettingsTransfer() )->build_export_payload(); + $json = wp_json_encode( $payload ); + self::assertIsString( $json ); + self::assertLessThanOrEqual( 1024 * 1024, strlen( $json ) ); + + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents + file_put_contents( $file, str_pad( $json, 1024 * 1024 ) ); + + $result = ( new Abilities() )->import_settings( + [ + 'input_file' => $file, + 'dry_run' => true, + ] + ); + + self::assertIsArray( $result ); + self::assertTrue( $result['success'] ); + self::assertTrue( $result['dry_run'] ); + self::assertFalse( $result['applied']['settings'] ); + } finally { + if ( is_string( $file ) && file_exists( $file ) ) { + // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink + unlink( $file ); + } + } + } + /** * Test import_settings() returns an error for invalid JSON in input_file. */ @@ -520,7 +680,7 @@ public function test_block_offender(): void { 'reason' => 'test', 'created_at' => $now, ], - // Expired block to ensure it gets pruned by prune_offender_blocks(). + // Expired entries must be ignored without persisting a public lookup. $expired_hash => [ 'expires_at' => $expired_expires, 'reason' => 'expired', @@ -538,17 +698,62 @@ public function test_block_offender(): void { self::assertFalse( $subject->block_offender( false, '8.8.8.8' ) ); self::assertTrue( $subject->block_offender( true, '8.8.8.8' ) ); - // Ensure expired blocks are pruned and persisted back to the option. + self::assertFalse( $subject->block_offender( false, $expired_ip ) ); + + // Public reads preserve the stored map, including expired entries. $blocks = get_option( 'hcaptcha_offender_blocks_v1', [] ); self::assertIsArray( $blocks ); self::assertArrayHasKey( $hash, $blocks ); - self::assertArrayNotHasKey( $expired_hash, $blocks ); + self::assertArrayHasKey( $expired_hash, $blocks ); // Edge case: false client IP should not break and should preserve denylisted value. self::assertFalse( $subject->block_offender( false, false ) ); self::assertTrue( $subject->block_offender( true, false ) ); } + /** + * A suspended public lookup cannot overwrite a newly persisted administrator ban. + */ + public function test_public_lookup_preserves_intervening_offender_ban(): void { + $subject = new Abilities(); + $option = 'hcaptcha_offender_blocks_v1'; + $expired_hash = wp_hash( '192.0.2.1' ); + $visitor = '192.0.2.2'; + $new_hash = wp_hash( $visitor ); + $stale = [ + $expired_hash => [ + 'expires_at' => time() - 1, + 'reason' => 'expired', + 'created_at' => time() - 300, + ], + ]; + update_option( $option, $stale, false ); + $interleave = null; + $interleave = static function () use ( $subject, $option, $new_hash, $stale, &$interleave ) { + remove_filter( 'option_' . $option, $interleave ); + $subject->block_offenders( + [ + 'offender_ids' => [ $new_hash ], + 'ttl_seconds' => 300, + ] + ); + + return $stale; + }; + add_filter( 'option_' . $option, $interleave ); + + try { + self::assertFalse( $subject->block_offender( false, $visitor ) ); + } finally { + remove_filter( 'option_' . $option, $interleave ); + } + + $blocks = get_option( $option, [] ); + self::assertArrayHasKey( $new_hash, $blocks ); + self::assertArrayNotHasKey( $expired_hash, $blocks ); + self::assertTrue( $subject->block_offender( false, $visitor ) ); + } + /** * Test can_get_threat_snapshot(). */ diff --git a/tests/php/integration/Abilities/UnreadableImportStream.php b/tests/php/integration/Abilities/UnreadableImportStream.php new file mode 100644 index 000000000..1a2830ab9 --- /dev/null +++ b/tests/php/integration/Abilities/UnreadableImportStream.php @@ -0,0 +1,51 @@ + $mode, + 2 => $mode, + 'size' => 1, + 7 => 1, + ]; + } + + /** + * Simulate a read failure after file checks have passed. + * + * @param string $path Stream path. + * @param string $mode Open mode. + * @param int $options Stream options. + * @param string|null $opened_path Opened path. + * + * @return bool + * @noinspection PhpUnused + * @noinspection PhpUnusedParameterInspection + * @noinspection PhpMissingParamTypeInspection + */ + public function stream_open( string $path, string $mode, int $options, &$opened_path ): bool { + return false; + } +} diff --git a/tests/php/integration/Abstracts/LoginBaseTest.php b/tests/php/integration/Abstracts/LoginBaseTest.php index 2432ef4d4..8801e6743 100644 --- a/tests/php/integration/Abstracts/LoginBaseTest.php +++ b/tests/php/integration/Abstracts/LoginBaseTest.php @@ -26,6 +26,24 @@ * Test LoginBase class. */ class LoginBaseTest extends HCaptchaWPTestCase { + /** + * An interval beyond the bounded store lifetime disables the adaptive limit. + */ + public function test_excessive_login_interval_disables_limit(): void { + update_option( + 'hcaptcha_settings', + [ + 'login_limit' => 2, + 'login_interval' => intdiv( LoginAttempts::MAX_TTL, MINUTE_IN_SECONDS ) + 1, + ] + ); + hcaptcha()->init_hooks(); + + $method = new ReflectionMethod( LoginBase::class, 'get_login_limit' ); + $method->setAccessible( true ); + + self::assertSame( 0, $method->invoke( new WPLogin() ) ); + } /** * Clear the shared login state after each case. diff --git a/tests/php/integration/Admin/Events/EventsTest.php b/tests/php/integration/Admin/Events/EventsTest.php index 6da4b6e7a..115028847 100644 --- a/tests/php/integration/Admin/Events/EventsTest.php +++ b/tests/php/integration/Admin/Events/EventsTest.php @@ -20,7 +20,11 @@ use HCaptcha\Settings\General; use HCaptcha\Settings\PluginSettingsBase; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; +use ReflectionException; +use RuntimeException; use tad\FunctionMocker\FunctionMocker; +use WP_Error; +use wpdb; /** * Test EventsTest class. @@ -640,6 +644,208 @@ public function test_save_event_returns_when_already_saved(): void { self::assertSame( 'success', $subject->save_event( 'success', [], (object) [] ) ); } + /** + * User agents fit the column without losing verification events. + * + * @dataProvider dp_test_save_event_bounds_user_agent + * + * @param string $user_agent Raw user agent. + * @param string $expected Stored user agent. + * @param bool $anonymous Whether to hash before normalization. + * @param bool $collect Whether to collect user agents. + */ + public function test_save_event_bounds_user_agent( string $user_agent, string $expected, bool $anonymous, bool $collect ): void { + global $wpdb; + + update_option( + 'hcaptcha_settings', + [ + 'statistics' => [ 'on' ], + 'collect_ua' => $collect ? [ 'on' ] : [], + 'anonymous' => $anonymous ? [ 'on' ] : [], + ] + ); + hcaptcha()->init_hooks(); + $this->drop_table(); + Events::create_table(); + $_SERVER['HTTP_USER_AGENT'] = $user_agent; + $subject = new Events(); + self::assertNull( $subject->save_event( null, [], (object) [] ) ); + self::assertSame( 'second-result', $subject->save_event( 'second-result', [], (object) [] ) ); + $table_name = $wpdb->prefix . Events::TABLE_NAME; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $events = $wpdb->get_results( "SELECT user_agent FROM $table_name" ); + + self::assertCount( 1, $events ); + self::assertSame( $anonymous ? wp_hash( $user_agent ) : $expected, $events[0]->user_agent ); + } + + /** + * Character and encoding boundaries of the real user_agent column. + * + * @return array + */ + public function dp_test_save_event_bounds_user_agent(): array { + $cases = []; + + foreach ( [ 255, 256, 257, 4096 ] as $length ) { + $cases[ 'ASCII ' . $length ] = [ str_repeat( 'A', $length ), str_repeat( 'A', min( 256, $length ) ), false, true ]; + } + + foreach ( [ 'é', '界', '🙂' ] as $character ) { + foreach ( [ 256, 257 ] as $length ) { + $cases[ $character . ' ' . $length ] = [ str_repeat( $character, $length ), str_repeat( $character, 256 ), false, true ]; + } + } + + $cases['invalid UTF-8'] = [ "A\xFFB", 'AB', false, true ]; + $cases['anonymous full'] = [ str_repeat( 'A', 4096 ), '', true, true ]; + $cases['collection off'] = [ str_repeat( 'A', 4096 ), '', false, false ]; + $cases['empty metadata'] = [ '', '', false, true ]; + + return $cases; + } + + /** + * A failed insert preserves verification, releases its lock, and is not retried. + * + * @throws ReflectionException Reflection exception. + */ + public function test_save_event_preserves_result_when_insert_fails(): void { + global $wpdb; + + $this->drop_table(); + Events::create_table(); + $table_name = $wpdb->prefix . Events::TABLE_NAME; + $attempts = 0; + $fail_query = static function ( string $query ) use ( $table_name, &$attempts ): string { + if ( 0 === strpos( $query, 'INSERT INTO `' . $table_name . '`' ) ) { + ++$attempts; + + return 'INVALID SEC064 INSERT'; + } + + return $query; + }; + $subject = new Events(); + $suppressed = $wpdb->suppress_errors(); + add_filter( 'query', $fail_query ); + + try { + self::assertNull( $subject->save_event( null, [], (object) [] ) ); + self::assertSame( 'failure', $subject->save_event( 'failure', [], (object) [] ) ); + self::assertSame( 1, $attempts ); + } finally { + remove_filter( 'query', $fail_query ); + $wpdb->suppress_errors( $suppressed ); + } + + $method = $this->set_method_accessibility( $subject, 'get_write_lock_name' ); + $lock_name = $method->invoke( $subject ); + $method->setAccessible( false ); + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + self::assertSame( 0, (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" ) ); + self::assertSame( '1', (string) $wpdb->get_var( $wpdb->prepare( 'SELECT IS_FREE_LOCK(%s)', $lock_name ) ) ); + // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + } + + /** + * Optional metadata conversion errors preserve the verification result and attempt guard. + * + * @dataProvider dp_test_save_event_handles_user_agent_conversion_failure + * + * @param bool $throws_error Whether column discovery throws instead of returning WP_Error. + */ + public function test_save_event_handles_user_agent_conversion_failure( bool $throws_error ): void { + global $wpdb; + + update_option( + 'hcaptcha_settings', + [ + 'statistics' => [ 'on' ], + 'collect_ua' => [ 'on' ], + ] + ); + hcaptcha()->init_hooks(); + $this->drop_table(); + Events::create_table(); + $_SERVER['HTTP_USER_AGENT'] = 'fixture-agent'; + $table_name = $wpdb->prefix . Events::TABLE_NAME; + $failure = null; + $failure = static function ( $pre, $table, $column ) use ( $throws_error, $table_name, &$failure ) { + if ( $table_name !== $table || 'user_agent' !== $column ) { + return $pre; + } + + remove_filter( 'pre_get_col_charset', $failure ); + + if ( $throws_error ) { + throw new RuntimeException( 'Simulated column discovery failure.' ); + } + + return new WP_Error( 'fixture-conversion', 'Simulated metadata conversion error.' ); + }; + add_filter( 'pre_get_col_charset', $failure, 10, 3 ); + $subject = new Events(); + + try { + self::assertSame( 'empty', $subject->save_event( 'empty', [], (object) [ 'codes' => [ 'empty' ] ] ) ); + self::assertSame( 'second-result', $subject->save_event( 'second-result', [], (object) [] ) ); + } finally { + remove_filter( 'pre_get_col_charset', $failure ); + } + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $rows = $wpdb->get_results( "SELECT user_agent FROM $table_name", ARRAY_A ); + + self::assertSame( $throws_error ? [] : [ [ 'user_agent' => '' ] ], $rows ); + } + + /** + * Metadata normalization can return a WordPress error or throw during discovery. + * + * @return array + */ + public function dp_test_save_event_handles_user_agent_conversion_failure(): array { + return [ + 'WP_Error fallback' => [ false ], + 'exception' => [ true ], + ]; + } + + /** + * Sampling compares the bounded representation that is actually stored. + */ + public function test_save_event_samples_normalized_user_agent(): void { + global $wpdb; + + wp_set_current_user( 0 ); + update_option( + 'hcaptcha_settings', + [ + 'statistics' => [ 'on' ], + 'collect_ua' => [ 'on' ], + 'anonymous' => [], + ] + ); + hcaptcha()->init_hooks(); + $this->drop_table(); + Events::create_table(); + + foreach ( [ 257, 258 ] as $length ) { + $_SERVER['HTTP_USER_AGENT'] = str_repeat( 'A', $length ); + self::assertSame( 'empty', ( new Events() )->save_event( 'empty', [], (object) [ 'codes' => [ 'empty' ] ] ) ); + } + + $table_name = $wpdb->prefix . Events::TABLE_NAME; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared + self::assertSame( 1, (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" ) ); + } + /** * Test save_event() anonymizes collected IP and user agent. * @@ -712,6 +918,8 @@ public function test_verify_request_bounds_anonymous_failure_burst(): void { ], ]; + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( $entry['expected_id'] ); + self::assertSame( hcap_get_error_messages()['empty'], API::verify_request( '', $entry ) ); self::assertSame( $expected_count, Events::get_events()['total'] ); } @@ -737,6 +945,7 @@ public function test_verify_request_bounds_anonymous_failure_burst(): void { * Test identical anonymous failures are sampled without changing verification. * * @return void + * @noinspection SqlWithoutWhere */ public function test_save_event_samples_identical_anonymous_failures(): void { global $wpdb; @@ -861,7 +1070,7 @@ public function test_save_event_preserves_result_when_cleanup_fails(): void { $query_filter = static function ( string $query ): string { if ( false !== strpos( $query, 'FORCE INDEX (status_date_gmt)' ) ) { - throw new \RuntimeException( 'Simulated event cleanup failure.' ); + throw new RuntimeException( 'Simulated event cleanup failure.' ); } return $query; @@ -891,7 +1100,7 @@ public function test_save_event_preserves_result_when_cleanup_fails(): void { * Test a busy allocation lock skips logging without changing verification. * * @return void - * @throws \ReflectionException Reflection exception. + * @throws ReflectionException Reflection exception. */ public function test_save_event_skips_allocation_when_write_lock_is_busy(): void { global $wpdb; @@ -902,7 +1111,7 @@ public function test_save_event_skips_allocation_when_write_lock_is_busy(): void $subject = new Events(); $method = $this->set_method_accessibility( $subject, 'get_write_lock_name' ); $lock_name = $method->invoke( $subject ); - $lock_db = new \wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST ); + $lock_db = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST ); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $acquired = $lock_db->get_var( $lock_db->prepare( 'SELECT GET_LOCK(%s, 0)', $lock_name ) ); @@ -1089,6 +1298,7 @@ public function test_cleanup_trash_returns_when_table_is_missing(): void { hcaptcha()->init_hooks(); $this->set_trash_schema_ready( true ); $this->drop_table(); + self::assertFalse( Events::is_retention_schema_ready() ); $wpdb->last_query = ''; diff --git a/tests/php/integration/Admin/NotificationsTest.php b/tests/php/integration/Admin/NotificationsTest.php index baa2ddcaf..3845ff969 100644 --- a/tests/php/integration/Admin/NotificationsTest.php +++ b/tests/php/integration/Admin/NotificationsTest.php @@ -13,6 +13,8 @@ namespace HCaptcha\Tests\Integration\Admin; use HCaptcha\Admin\Notifications; +use HCaptcha\Admin\OnboardingWizard; +use HCaptcha\Settings\General; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; use Mockery; use tad\FunctionMocker\FunctionMocker; @@ -88,13 +90,16 @@ public function test_get_notifications( string $setting ): void { $expected = [ 'register' => [ - 'title' => 'Get your hCaptcha site keys', - 'message' => 'To use hCaptcha, please register here to get your site and secret keys.', - 'button' => + 'title' => 'Set up hCaptcha', + 'message' => 'To use the plugin, create an hCaptcha account and get your keys. Then select Live mode below and enter your keys.', + 'button' => [ - 'url' => 'https://www.hcaptcha.com/signup-interstitial/?r=wp&utm_source=wordpress&utm_medium=wpplugin&utm_campaign=sk', - 'text' => 'Get site keys', + 'url' => '', + 'text' => 'Show Setup Wizard', + 'target' => '_self', ], + 'notice_type' => 'warning', + 'dismissible' => false, ], 'pro-free-trial' => [ @@ -140,17 +145,17 @@ public function test_get_notifications( string $setting ): void { ], 'statistics' => [ 'title' => 'Events statistics and Forms admin page', - 'message' => 'Turn on events statistics and see how your forms are used.', + 'message' => 'Turn on events statistics and see how your forms are used.', 'button' => [ - 'url' => 'http://test.test/wp-admin/options-general.php?page=hcaptcha&tab=general#statistics_1', + 'url' => 'http://test.test/wp-admin/options-general.php?page=hcaptcha&tab=advanced#statistics_1', 'text' => 'Turn on stats', ], ], 'events_page' => [ 'title' => 'Events admin page', - 'message' => 'Turn on events statistics and upgrade to Pro to see retained statistics on form events.', + 'message' => 'Turn on events statistics and upgrade to Pro to see retained statistics on form events.', 'button' => [ - 'url' => 'http://test.test/wp-admin/options-general.php?page=hcaptcha&tab=general#statistics_1', + 'url' => 'http://test.test/wp-admin/options-general.php?page=hcaptcha&tab=advanced#statistics_1', 'text' => 'Turn on stats', ], ], @@ -181,7 +186,7 @@ public function test_get_notifications( string $setting ): void { ], 'protect-content' => [ 'title' => 'Protect Site Content', - 'message' => 'Protect selected site URLs from bots with hCaptcha. Works best with Pro 99.9% passive mode.', + 'message' => 'Protect selected site URLs from bots with hCaptcha. Works best with Pro 99.9% passive mode.', 'button' => [ 'url' => 'http://test.test/wp-content/plugins/hcaptcha-wordpress-plugin/assets/images/demo/protect-content.gif', 'text' => 'See an example', @@ -220,12 +225,27 @@ public function test_get_notifications( string $setting ): void { 'text' => 'Review headers', ], ], + 'rest-api-protection' => [ + 'title' => 'Unique REST API Protection', + 'message' => 'hCaptcha now protects selected content in WordPress REST responses and search, verifies native REST comments, and blocks REST post-password attempts when the corresponding protections are enabled. No other plugin in our October 2026 review of the 10 most-installed WordPress.org plugins tagged captcha offered all three.', + 'button' => [ + 'url' => 'http://test.test/wp-admin/options-general.php?page=hcaptcha&tab=advanced#protect_content_1', + 'text' => 'Configure Content Protection', + ], + ], ]; switch ( $setting ) { case 'not_empty_keys': $site_key = 'some_key'; $secret_key = 'secret_key'; + update_option( + 'hcaptcha_settings', + [ + 'site_key' => $site_key, + 'secret_key' => $secret_key, + ] + ); unset( $expected['register'] ); break; @@ -306,6 +326,16 @@ static function () use ( $secret_key ) { set_current_screen( 'hcaptcha' ); do_action( 'admin_menu' ); + if ( isset( $expected['register'] ) ) { + $expected['register']['button']['url'] = add_query_arg( + [ + OnboardingWizard::STEP_PARAM => 1, + OnboardingWizard::NONCE_PARAM => wp_create_nonce( OnboardingWizard::STEP_ACTION ), + ], + hcaptcha()->settings()->tab_url( General::class ) + ); + } + $subject = Mockery::mock( Notifications::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); @@ -430,25 +460,15 @@ static function () use ( $secret_key ) { ); $expected = ' -
    +
    Notifications
    -
    -
    - Get your hCaptcha site keys -
    -

    To use hCaptcha, please register here to get your site and secret keys.

    +
    +
    Set up hCaptcha
    +

    To use the plugin, create an hCaptcha account and get your keys. Then select Live mode below and enter your keys.

    $subject->show(); $actual = $this->trim_tags( ob_get_clean() ); - $header = '
    Notifications
    '; + $header = '
    Notifications
    '; $body = '
    '; $footer = '
    '; $pattern = "#($header) ($body) ($footer)#"; @@ -530,6 +550,7 @@ class="button button-primary " target="_blank"> $expected_notifications = $expected_notifications[0]; $actual_notifications = $actual_notifications[0]; + $actual_notifications = preg_replace( '/hcaptcha_onboarding_nonce=[^"&]+/', 'hcaptcha_onboarding_nonce=NONCE', $actual_notifications ); if ( version_compare( $GLOBALS['wp_version'], '7.0-RC1', '>=' ) ) { $expected_notifications = str_replace( '&', '&', $expected_notifications ); @@ -609,6 +630,7 @@ class="button button-primary " target="_blank"> $expected_notifications = $expected_notifications[0]; $actual_notifications = $actual_notifications[0]; + $actual_notifications = preg_replace( '/hcaptcha_onboarding_nonce=[^"&]+/', 'hcaptcha_onboarding_nonce=NONCE', $actual_notifications ); if ( version_compare( $GLOBALS['wp_version'], '7.0-RC1', '>=' ) ) { $expected_notifications = str_replace( '&', '&', $expected_notifications ); @@ -632,6 +654,61 @@ class="button button-primary " target="_blank"> self::assertSame( $expected_notifications, $sorted_actual_notifications ); } + /** + * The reset control should ignore dismissed notifications that cannot currently appear. + */ + public function test_has_dismissed_notifications(): void { + $user_id = 1; + + wp_set_current_user( $user_id ); + + $subject = Mockery::mock( Notifications::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'get_notifications' )->andReturn( + [ + 'register' => [ 'dismissible' => false ], + 'active' => [], + ] + ); + + delete_user_meta( $user_id, Notifications::HCAPTCHA_DISMISSED_META_KEY ); + self::assertFalse( $subject->has_dismissed_notifications() ); + + update_user_meta( $user_id, Notifications::HCAPTCHA_DISMISSED_META_KEY, [ 'register', 'removed' ] ); + self::assertFalse( $subject->has_dismissed_notifications() ); + + update_user_meta( $user_id, Notifications::HCAPTCHA_DISMISSED_META_KEY, [ 'active' ] ); + self::assertTrue( $subject->has_dismissed_notifications() ); + } + + /** + * Test that setup shows a single warning even if the old registration notice was dismissed. + */ + public function test_show_setup_only(): void { + $user_id = 1; + + wp_set_current_user( $user_id ); + delete_option( 'hcaptcha_settings' ); + hcaptcha()->init_hooks(); + add_filter( 'hcap_site_key', '__return_empty_string' ); + add_filter( 'hcap_secret_key', '__return_empty_string' ); + update_user_meta( $user_id, Notifications::HCAPTCHA_DISMISSED_META_KEY, [ 'register' ] ); + + $subject = new Notifications(); + + ob_start(); + $subject->show( true ); + $output = ob_get_clean(); + + self::assertSame( 1, substr_count( $output, 'class="hcaptcha-notification notice' ) ); + self::assertStringContainsString( 'class="hcaptcha-setup-notice"', $output ); + self::assertStringContainsString( 'notice-warning', $output ); + self::assertStringContainsString( 'Then select Live mode below and enter your keys.', $output ); + self::assertStringContainsString( 'Show Setup Wizard', $output ); + self::assertStringContainsString( 'target="_self"', $output ); + self::assertStringNotContainsString( 'is-dismissible', $output ); + } + /** * Test show() without notifications. * diff --git a/tests/php/integration/Admin/OnboardingWizardTest.php b/tests/php/integration/Admin/OnboardingWizardTest.php index 18a3a1c05..ec301d079 100644 --- a/tests/php/integration/Admin/OnboardingWizardTest.php +++ b/tests/php/integration/Admin/OnboardingWizardTest.php @@ -9,12 +9,14 @@ use Exception; use HCaptcha\Admin\OnboardingWizard; +use HCaptcha\Settings\AntiSpamPage; use HCaptcha\Settings\General; use HCaptcha\Settings\Integrations; use HCaptcha\Settings\PluginSettingsBase; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; use ReflectionClass; use ReflectionException; +use tad\FunctionMocker\FunctionMocker; /** * Class OnboardingWizardTest @@ -98,6 +100,7 @@ public function test_init_completes_wizard_when_keys_exist(): void { self::assertSame( 'completed', $option[ OnboardingWizard::OPTION_NAME ] ); self::assertInstanceOf( General::class, $this->get_wizard_property( $subject, 'general_tab' ) ); + self::assertInstanceOf( AntiSpamPage::class, $this->get_wizard_property( $subject, 'antispam_tab' ) ); self::assertInstanceOf( Integrations::class, $this->get_wizard_property( $subject, 'integrations_tab' ) ); } @@ -172,9 +175,8 @@ public function test_maybe_handle_direct_step( string $step_param, string $expec $_GET[ OnboardingWizard::NONCE_PARAM ] = wp_create_nonce( OnboardingWizard::STEP_ACTION ); $general = $this->get_general_tab(); - $integrations = $this->get_integrations_tab(); $subject = $this->make_initialized_wizard( $general ); - $target = General::class === $target_tab ? $general : $integrations; + $target = hcaptcha()->settings()->get_tab( $target_tab ); $expected_url = $general->tab_url( $target ); $subject->maybe_handle_direct_step(); @@ -193,7 +195,9 @@ public function test_maybe_handle_direct_step( string $step_param, string $expec public function dp_test_maybe_handle_direct_step(): array { return [ 'general step' => [ '3', 'step 3', General::class ], - 'integrations step' => [ '7', 'step 7', Integrations::class ], + 'anti-spam step' => [ '6', 'step 6', AntiSpamPage::class ], + 'integrations step' => [ '8', 'step 8', Integrations::class ], + 'final step' => [ '9', 'step 9', Integrations::class ], 'out of range step' => [ '99', 'step 1', General::class ], ]; } @@ -248,6 +252,19 @@ public function test_admin_enqueue_scripts_when_completed(): void { self::assertFalse( wp_script_is( OnboardingWizard::HANDLE, 'registered' ) ); } + /** + * A fresh installation shows settings until the wizard is explicitly started. + */ + public function test_admin_enqueue_scripts_without_explicit_start(): void { + $this->refresh_settings(); + set_current_screen( 'settings_page_hcaptcha' ); + + $subject = $this->make_initialized_wizard( $this->get_general_tab() ); + $subject->admin_enqueue_scripts(); + + self::assertFalse( wp_script_is( OnboardingWizard::HANDLE, 'registered' ) ); + } + /** * Test admin_enqueue_scripts(). */ @@ -270,6 +287,8 @@ public function test_admin_enqueue_scripts(): void { self::assertStringContainsString( 'var HCaptchaOnboardingObject = ', $script->extra['data'] ); self::assertStringContainsString( '"page":"general"', $script->extra['data'] ); self::assertStringContainsString( '"currentStep":"step 5"', $script->extra['data'] ); + self::assertStringContainsString( '"signupUrl":"https:', $script->extra['data'] ); + self::assertStringContainsString( 'utm_campaign=sk', $script->extra['data'] ); self::assertTrue( wp_style_is( OnboardingWizard::HANDLE, 'registered' ) ); @@ -280,6 +299,59 @@ public function test_admin_enqueue_scripts(): void { self::assertSame( HCAPTCHA_VERSION, $style->ver ); } + /** + * The localized wizard identifies each non-general settings tab. + */ + public function test_admin_enqueue_scripts_on_other_tabs(): void { + $this->refresh_settings( [ OnboardingWizard::OPTION_NAME => 'step 8' ] ); + foreach ( [ + Integrations::class => 'integrations', + AntiSpamPage::class => 'antispam', + ] as $class => $page ) { + $tab = hcaptcha()->settings()->get_tab( $class ); + self::assertInstanceOf( $class, $tab ); + $option_page = $this->set_method_accessibility( $tab, 'option_page' )->invoke( $tab ); + set_current_screen( 'settings_page_' . $option_page ); + $subject = $this->make_initialized_wizard( $tab ); + $subject->admin_enqueue_scripts(); + + self::assertTrue( wp_script_is( OnboardingWizard::HANDLE, 'registered' ) ); + self::assertStringContainsString( + '"page":"' . $page . '"', + wp_scripts()->registered[ OnboardingWizard::HANDLE ]->extra['data'] + ); + wp_dequeue_script( OnboardingWizard::HANDLE ); + wp_deregister_script( OnboardingWizard::HANDLE ); + } + } + + /** + * Debug mode serves the unminified wizard script with its file version. + */ + public function test_admin_enqueue_scripts_in_debug_mode(): void { + FunctionMocker::replace( + 'defined', + static function ( $name ) { + return 'SCRIPT_DEBUG' === $name ? true : FunctionMocker::callOriginal(); + } + ); + FunctionMocker::replace( + 'constant', + static function ( $name ) { + return 'SCRIPT_DEBUG' === $name ? true : FunctionMocker::callOriginal(); + } + ); + + $this->refresh_settings( [ OnboardingWizard::OPTION_NAME => 'step 1' ] ); + set_current_screen( 'settings_page_hcaptcha' ); + $subject = $this->make_initialized_wizard( $this->get_general_tab() ); + $subject->admin_enqueue_scripts(); + + $script = wp_scripts()->registered[ OnboardingWizard::HANDLE ]; + self::assertSame( HCAPTCHA_URL . '/assets/js/onboarding-wizard.js', $script->src ); + self::assertStringStartsWith( HCAPTCHA_VERSION . '-', $script->ver ); + } + /** * Test ajax_update() with a bad nonce. */ @@ -488,17 +560,4 @@ private function get_general_tab(): General { return $tab; } - - /** - * Get Integrations tab. - * - * @return Integrations - */ - private function get_integrations_tab(): Integrations { - $tab = hcaptcha()->settings()->get_tab( Integrations::class ); - - self::assertInstanceOf( Integrations::class, $tab ); - - return $tab; - } } diff --git a/tests/php/integration/Admin/PluginStatsTest.php b/tests/php/integration/Admin/PluginStatsTest.php index 82ce67527..001fdc6cb 100644 --- a/tests/php/integration/Admin/PluginStatsTest.php +++ b/tests/php/integration/Admin/PluginStatsTest.php @@ -10,6 +10,7 @@ use HCaptcha\Admin\PluginStats; use HCaptcha\Admin\Privacy; use HCaptcha\Helpers\Playground; +use HCaptcha\Settings\Advanced; use HCaptcha\Settings\General; use HCaptcha\Settings\SystemInfo; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; @@ -375,7 +376,7 @@ static function () use ( &$requests ) { * @throws ReflectionException ReflectionException. */ public function test_telemetry_disclosures(): void { - $fields = $this->get_protected_property( new General(), 'form_fields' ); + $fields = $this->get_protected_property( new Advanced(), 'form_fields' ); $helper = $fields['statistics']['helper']; $claims = [ 'visitor IP of the current request (X-Forwarded-For)', diff --git a/tests/php/integration/Admin/WhatsNewTest.php b/tests/php/integration/Admin/WhatsNewTest.php index b32ce88f2..8bf812015 100644 --- a/tests/php/integration/Admin/WhatsNewTest.php +++ b/tests/php/integration/Admin/WhatsNewTest.php @@ -21,6 +21,19 @@ * @group whats-new */ class WhatsNewTest extends HCaptchaWPTestCase { + /** + * Normalize supported release versions and reject malformed versions. + * + * @throws ReflectionException Reflection exception. + */ + public function test_normalize_version(): void { + $subject = new WhatsNew(); + $method = $this->set_method_accessibility( $subject, 'normalize_version' ); + + self::assertSame( '5.4.0-RC1', $method->invoke( $subject, ' 5.4.0-rc1 ' ) ); + self::assertSame( '', $method->invoke( $subject, 'invalid' ) ); + } + /** * Test init() and init_hooks(). * @@ -172,8 +185,18 @@ static function ( $method ) use ( $prefix ) { usort( $versions, 'version_compare' ); $versions = array_reverse( $versions ); - $version = $versions[0]; - $method = $prefix . str_replace( '.', '_', $version ); + $current = explode( '-', HCAPTCHA_VERSION )[0]; + $version = ''; + + foreach ( $versions as $candidate ) { + if ( version_compare( $candidate, $current, '<=' ) ) { + $version = $candidate; + + break; + } + } + + $method = $prefix . str_replace( '.', '_', $version ); $subject->shouldAllowMockingProtectedMethods(); $subject->shouldReceive( 'render_popup' )->once()->with( $method, true ); @@ -422,6 +445,7 @@ public function test_render_popup(): void { self::assertStringContainsString( '' . $version . '', $html ); self::assertStringContainsString( 'class="hcaptcha-whats-new-version-toggle"', $html ); self::assertStringContainsString( 'id="hcaptcha-whats-new-versions"', $html ); + self::assertStringContainsString( 'data-version="5.5.0"', $html ); self::assertStringContainsString( 'data-version="5.4.0"', $html ); self::assertStringContainsString( 'data-version="5.3.0"', $html ); self::assertStringContainsString( 'data-version="5.2.0"', $html ); @@ -451,7 +475,7 @@ public function test_whats_new_4_13_0(): void {
    Protect Content @@ -1034,6 +1058,46 @@ static function ( $args ) { self::assertSame( 1, substr_count( $html, 'class="hcaptcha-lightbox"' ) ); } + /** + * Test whats_new_5_5_0(). + * + * @return void + */ + public function test_whats_new_5_5_0(): void { + add_filter( + 'hcap_settings_init_args', + static function ( $args ) { + $args['mode'] = 'tabs'; + + return $args; + } + ); + + wp_set_current_user( 1 ); + hcaptcha()->init_hooks(); + set_current_screen( 'hcaptcha' ); + do_action( 'admin_menu' ); + + $subject = Mockery::mock( WhatsNew::class )->makePartial(); + + $subject->shouldAllowMockingProtectedMethods(); + + ob_start(); + + $subject->whats_new_5_5_0(); + + $html = ob_get_clean(); + + self::assertSame( 1, substr_count( $html, 'class="hcaptcha-whats-new-block ' ) ); + self::assertStringContainsString( 'Unique REST API Protection', $html ); + self::assertStringContainsString( 'REST post-password attempts are blocked', $html ); + self::assertStringContainsString( 'none offered all three protections', $html ); + self::assertStringContainsString( 'Configure Content Protection', $html ); + self::assertStringContainsString( '#protect_content_1', $html ); + self::assertStringContainsString( 'assets/images/rest-api-protection.png', $html ); + self::assertSame( 1, substr_count( $html, 'class="hcaptcha-lightbox"' ) ); + } + /** * Test update_whats_new(). * diff --git a/tests/php/integration/Affiliates/LoginTest.php b/tests/php/integration/Affiliates/LoginTest.php index c3b23a5e8..242b5ac0f 100644 --- a/tests/php/integration/Affiliates/LoginTest.php +++ b/tests/php/integration/Affiliates/LoginTest.php @@ -17,6 +17,19 @@ * @group affiliates-login */ class LoginTest extends HCaptchaWPTestCase { + /** + * Skip other login forms and render the dashboard spacing rule. + */ + public function test_other_form_and_inline_styles(): void { + $subject = new Login(); + + self::assertSame( 'other form', $subject->add_affiliates_captcha( 'other form', [] ) ); + + ob_start(); + $subject->print_inline_styles(); + + self::assertStringContainsString( '.affiliates-dashboard .h-captcha', ob_get_clean() ); + } /** * Test that the rendered login form contains honeypot fields. diff --git a/tests/php/integration/Affiliates/RegisterTest.php b/tests/php/integration/Affiliates/RegisterTest.php index f0bc3dbe7..087d93510 100644 --- a/tests/php/integration/Affiliates/RegisterTest.php +++ b/tests/php/integration/Affiliates/RegisterTest.php @@ -18,6 +18,19 @@ * @group affiliates-register */ class RegisterTest extends HCaptchaWPTestCase { + /** + * Ignore unrelated dashboard sections and requests without a registration submit. + */ + public function test_ignores_other_sections_and_requests(): void { + $subject = new Register(); + $level = ob_get_level(); + + $subject->before_section( 'other' ); + $subject->after_section( 'other' ); + + self::assertSame( $level, ob_get_level() ); + self::assertTrue( $subject->verify( true ) ); + } /** * Set up the test. @@ -84,4 +97,63 @@ public function test_filled_honeypot_is_rejected(): void { self::assertStringContainsString( 'Anti-spam check failed.', $output ); } + + /** + * The native registration email is used for email policy checks. + */ + public function test_native_registration_email_is_checked(): void { + $settings = (array) get_option( 'hcaptcha_settings', [] ); + $settings['disposable_email'] = [ 'on' ]; + update_option( 'hcaptcha_settings', $settings ); + + $this->prepare_verify_post( 'hcaptcha_registration_nonce', 'hcaptcha_registration' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'affiliates/affiliates.php' ], + 'form_id' => 'register', + ] + ); + $_POST['affiliates-registration-submit'] = 'Register'; + $_POST['user_email'] = 'person@example.com'; + add_filter( 'hcap_is_disposable_email', '__return_true' ); + + self::assertTrue( ( new Register() )->verify( false ) ); + } + + /** + * A logged-in affiliate is checked using the account address. + */ + public function test_logged_in_affiliate_uses_account_email(): void { + $user_id = $this->factory()->user->create( [ 'user_email' => 'account@example.com' ] ); + wp_set_current_user( $user_id ); + + $settings = (array) get_option( 'hcaptcha_settings', [] ); + $settings['disposable_email'] = [ 'on' ]; + update_option( 'hcaptcha_settings', $settings ); + + $this->prepare_verify_post( 'hcaptcha_registration_nonce', 'hcaptcha_registration' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'affiliates/affiliates.php' ], + 'form_id' => 'register', + ] + ); + $_POST['affiliates-registration-submit'] = 'Register'; + $_POST['user_email'] = 'forged@example.com'; + + $checked = []; + add_filter( + 'hcap_is_disposable_email', + static function ( bool $disposable, string $email ) use ( &$checked ): bool { + $checked[] = $email; + + return true; + }, + 10, + 2 + ); + + self::assertTrue( ( new Register() )->verify( false ) ); + self::assertSame( [ 'account@example.com' ], $checked ); + } } diff --git a/tests/php/integration/Asgaros/FormTest.php b/tests/php/integration/Asgaros/FormTest.php index 2ee94ff2b..e0a04ac94 100644 --- a/tests/php/integration/Asgaros/FormTest.php +++ b/tests/php/integration/Asgaros/FormTest.php @@ -18,6 +18,39 @@ * @group asgaros */ class FormTest extends HCaptchaWPTestCase { + /** + * Ignore other shortcodes and print the forum editor spacing rules. + */ + public function test_other_shortcode_and_inline_styles(): void { + $subject = new Form(); + + self::assertSame( 'other', $subject->add_captcha( 'other', 'other', [], [] ) ); + + ob_start(); + $subject->print_inline_styles(); + + self::assertStringContainsString( '#af-wrapper div.editor-row.editor-row-hcaptcha', ob_get_clean() ); + } + + /** + * Allow a forum post after successful verification. + */ + public function test_valid_forum_proof_is_accepted(): void { + global $asgarosforum; + + $this->prepare_verify_post( 'hcaptcha_asgaros_new_topic_nonce', 'hcaptcha_asgaros_new_topic' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'asgaros-forum/asgaros-forum.php' ], + 'form_id' => 7, + ] + ); + $asgarosforum = Mockery::mock(); + $asgarosforum->current_forum = 7; + $asgarosforum->shouldNotReceive( 'add_notice' ); + + self::assertTrue( ( new Form() )->verify( true ) ); + } /** * Set up the test. @@ -50,12 +83,26 @@ public function tearDown(): void { * @return void */ public function test_form_contains_honeypot(): void { + global $asgarosforum; + + $asgarosforum = Mockery::mock(); + $asgarosforum->current_forum = 7; + $html = '
    '; $output = ( new Form() )->add_captcha( $html, 'forum', [ 'id' => 7 ], [] ); self::assertStringContainsString( 'name="hcap_hp_test"', $output ); self::assertStringContainsString( 'name="hcap_hp_sig"', $output ); self::assertStringContainsString( 'name="hcaptcha-widget-id"', $output ); + self::assertStringContainsString( + HCaptcha::widget_id_value( + [ + 'source' => [ 'asgaros-forum/asgaros-forum.php' ], + 'form_id' => 7, + ] + ), + $output + ); } /** @@ -76,9 +123,31 @@ public function test_filled_honeypot_is_rejected(): void { ); $_POST['hcap_hp_test'] = 'bot'; - $asgarosforum = Mockery::mock(); + $asgarosforum = Mockery::mock(); + $asgarosforum->current_forum = 7; $asgarosforum->shouldReceive( 'add_notice' )->once()->with( 'Anti-spam check failed.' ); self::assertFalse( ( new Form() )->verify( true ) ); } + + /** + * A widget rendered for another forum is rejected. + */ + public function test_foreign_forum_widget_is_rejected(): void { + global $asgarosforum; + + $this->prepare_verify_post( 'hcaptcha_asgaros_new_topic_nonce', 'hcaptcha_asgaros_new_topic' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'asgaros-forum/asgaros-forum.php' ], + 'form_id' => 8, + ] + ); + + $asgarosforum = Mockery::mock(); + $asgarosforum->current_forum = 7; + $asgarosforum->shouldReceive( 'add_notice' )->once()->with( hcap_get_error_messages()['bad-signature'] ); + + self::assertFalse( ( new Form() )->verify( true ) ); + } } diff --git a/tests/php/integration/AutoVerify/AutoVerifyTest.php b/tests/php/integration/AutoVerify/AutoVerifyTest.php index a461cff33..61faabed2 100644 --- a/tests/php/integration/AutoVerify/AutoVerifyTest.php +++ b/tests/php/integration/AutoVerify/AutoVerifyTest.php @@ -13,10 +13,12 @@ namespace HCaptcha\Tests\Integration\AutoVerify; use HCaptcha\AutoVerify\AutoVerify; +use HCaptcha\Helpers\API; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; use Mockery; use ReflectionException; +use WP_Query; /** * Test AutoVerify class. @@ -35,9 +37,15 @@ public function tearDown(): void { $_GET['p'], $_GET['page_id'], $_GET['rest_route'], + $_GET['name'], + $_GET['post_type'], + $_GET['attachment_id'], + $_GET['subpost_id'], $GLOBALS['current_screen'] ); delete_transient( AutoVerify::TRANSIENT ); + wp_dequeue_script( AutoVerify::HANDLE ); + wp_deregister_script( AutoVerify::HANDLE ); parent::tearDown(); } @@ -59,6 +67,70 @@ public function test_init_and_init_hooks(): void { self::assertSame( 10, has_action( 'hcap_auto_verify_register', [ $subject, 'content_filter' ] ) ); } + /** + * Uninstall cleanup deletes persisted registrations and the legacy transient. + */ + public function test_delete_all_removes_stored_forms(): void { + $name = 'hcaptcha_auto_verify_form_cleanup_test'; + add_option( $name, [ 'form' => true ], '', 'no' ); + set_transient( AutoVerify::TRANSIENT, [ 'legacy' => true ] ); + + AutoVerify::delete_all(); + + self::assertFalse( get_option( $name ) ); + self::assertFalse( get_transient( AutoVerify::TRANSIENT ) ); + } + + /** + * Auto forms receive a normalized widget ID while ordinary forms retain their arguments. + */ + public function test_auto_form_arguments_and_registration(): void { + $subject = new AutoVerify(); + self::assertSame( [ 'auto' => false ], $subject->add_default_id( [ 'auto' => false ] ) ); + $subject->register_hcaptcha( 'invalid' ); + + $args = $subject->add_default_id( + [ + 'auto' => true, + 'ajax' => true, + 'honeypot' => 'yes', + ] + ); + self::assertTrue( $args['id']['honeypot'] ); + self::assertSame( [ AutoVerify::class ], $args['id']['source'] ); + $subject->register_hcaptcha( $args ); + $subject->enqueue_scripts(); + + self::assertTrue( wp_script_is( AutoVerify::HANDLE ) ); + self::assertStringContainsString( 'hcaptcha-auto-verify', wp_scripts()->registered[ AutoVerify::HANDLE ]->src ); + self::assertStringContainsString( 'HCaptchaAutoVerifyObject', wp_scripts()->registered[ AutoVerify::HANDLE ]->extra['data'] ); + } + + /** + * Empty auto registry does not enqueue a script. + */ + public function test_enqueue_scripts_without_ajax_form(): void { + $subject = new AutoVerify(); + $subject->enqueue_scripts(); + + self::assertFalse( wp_script_is( AutoVerify::HANDLE ) ); + } + + /** + * Numeric references and sibling registrations retain their expected values. + */ + public function test_numeric_reference_and_sibling_registration(): void { + $subject = new AutoVerify(); + $decode = $this->set_method_accessibility( $subject, 'decode_numeric_reference' ); + self::assertSame( '©', $decode->invoke( $subject, '©' ) ); + + $forms = [ 'action' => [ [ 'id' => 1 ], [ 'id' => 2 ] ] ]; + $remove = $this->set_method_accessibility( $subject, 'remove_registered_form' ); + $args = [ &$forms, 'action', $forms['action'], 0 ]; + $remove->invokeArgs( $subject, $args ); + self::assertSame( [ [ 'id' => 2 ] ], $forms['action'] ); + } + /** * Test content_filter(). */ @@ -81,6 +153,187 @@ public function test_content_filter(): void { self::assertFalse( get_transient( $subject::TRANSIENT ) ); } + /** + * Browser-equivalent form actions must protect the actual submission endpoint. + * + * @dataProvider dp_test_html_form_actions_verify_actual_target + * + * @param string $opening Form opening tag. + * @param string $target Browser submission path. + * @param bool $valid_submission Whether hCaptcha data is valid. + */ + public function test_html_form_actions_verify_actual_target( string $opening, string $target, bool $valid_submission = false ): void { + $_SERVER['REQUEST_URI'] = '/render/contact/'; + $subject = new AutoVerify(); + $subject->init(); + $content = str_replace( + [ '
    ', '
    ' ], + [ $opening, '' ], + $this->get_test_content() + ); + $subject->content_filter( do_shortcode( $content ) ); + $forms = $this->get_registered_action_forms( $target ); + + self::assertCount( 1, $forms ); + self::assertSame( [], $this->get_registered_action_forms( '/wrong' ) ); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['REQUEST_URI'] = $target; + $_POST = [ 'test_input' => 'value' ]; + + if ( $valid_submission ) { + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = $forms[0]['widget_id']; + $args = $forms[0]['args']; + $_POST[ $args['name'] ] = wp_create_nonce( $args['action'] ); + $this->prepare_verify_request( 'some response' ); + } + + $submitted = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing + $die_arr = []; + add_filter( + 'wp_die_handler', + static function () use ( &$die_arr ) { + return static function ( $message, $title, $args ) use ( &$die_arr ) { + $die_arr = [ $message, $title, $args ]; + }; + } + ); + $subject->verify(); + + if ( $valid_submission ) { + self::assertSame( [], $die_arr ); + self::assertTrue( hcaptcha()->has_result ); + self::assertSame( $submitted, $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } else { + self::assertSame( 'Bad hCaptcha signature!', $die_arr[0] ?? null ); + self::assertSame( 403, $die_arr[2]['response'] ?? null ); + self::assertSame( [], $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } + } + + /** + * Form action syntax and ordinary submission controls. + * + * @return array + * @noinspection HtmlUnknownTarget + * @noinspection HtmlUnknownAnchorTarget + */ + public function dp_test_html_form_actions_verify_actual_target(): array { + return [ + 'single quotes' => [ "
    ", '/submit' ], + 'unquoted' => [ '', '/submit' ], + 'uppercase attribute' => [ '', '/submit' ], + 'ASCII whitespace' => [ "", '/submit' ], + 'quoted tag end' => [ '', '/submit' ], + 'data action decoy' => [ '', '/submit' ], + 'quoted action decoy' => [ '', '/submit' ], + 'first duplicate' => [ '', '/submit' ], + 'first empty duplicate' => [ '', '/render/contact' ], + 'bare action' => [ '', '/render/contact' ], + 'no action' => [ '', '/render/contact' ], + 'data action only' => [ '', '/render/contact' ], + 'descendant action' => [ '', '/render/contact' ], + 'entities' => [ '', '/submit' ], + 'no semicolon numeric' => [ '', '/submit' ], + 'no semicolon hex' => [ '', '/submit' ], + 'relative path' => [ '', '/render/contact/submit' ], + 'dot relative path' => [ '', '/render/contact/submit' ], + 'parent relative path' => [ '', '/render/submit' ], + 'root dot segments' => [ '', '/submit' ], + 'absolute dot segments' => [ '', '/submit' ], + 'empty before parent' => [ '', '/a/submit' ], + 'encoded slash parent' => [ '', '/submit' ], + 'encoded dot parent' => [ '', '/submit' ], + 'zero action' => [ '', '/render/contact/0' ], + 'schemeless URL' => [ '', '/submit' ], + 'origin only' => [ '', '/' ], + 'schemeless origin' => [ '', '/' ], + 'fragment action' => [ '', '/render/contact' ], + 'valid single quotes' => [ "", '/submit', true ], + 'valid uppercase' => [ '', '/submit', true ], + ]; + } + + /** + * Raw text and unrelated forms must not change the protected form's target. + */ + public function test_html_form_extraction_ignores_raw_text(): void { + $subject = new AutoVerify(); + $subject->init(); + $_SERVER['REQUEST_URI'] = '/render/contact/'; + $content = do_shortcode( $this->get_test_content() ); + $content = str_replace( + '', + '', + $content + ); + $content = '' . $content; + $subject->content_filter( $content ); + + self::assertCount( 1, $this->get_registered_action_forms( '/submit' ) ); + self::assertSame( [], $this->get_registered_action_forms( '/wrong' ) ); + } + + /** + * Attribute entities retain browser decoding and never decode a reference twice. + * + * @dataProvider dp_test_decode_action_attribute + * + * @param string $value Attribute source. + * @param string $expected Browser attribute value. + */ + public function test_decode_action_attribute( string $value, string $expected ): void { + $subject = new AutoVerify(); + $method = $this->set_method_accessibility( $subject, 'decode_action_attribute' ); + + self::assertSame( $expected, $method->invoke( $subject, $value ) ); + } + + /** + * Browser attribute character reference boundaries. + * + * @return array + */ + public function dp_test_decode_action_attribute(): array { + return [ + [ '/submit', '/submit' ], + [ '/submit', '/submit' ], + [ '/submit', '/submit' ], + [ '&#47;', '/' ], + [ '&amp;', '&' ], + [ '&/', '&/' ], + [ '&=1', '&=1' ], + [ '&next', '&next' ], + [ 'é/', 'é/' ], + [ '©/', '©/' ], + [ '&sol/', '&sol/' ], + [ '/', '/' ], + [ '�', "\xef\xbf\xbd" ], + [ '�', "\xef\xbf\xbd" ], + [ '�', "\xef\xbf\xbd" ], + [ '€', '€' ], + [ '😀', '😀' ], + ]; + } + + /** + * Entity decoding and actionless fallback preserve query selectors after ampersands. + * + * @noinspection HtmlUnknownAnchorTarget + */ + public function test_html_form_actions_preserve_query_selectors(): void { + $page_id = $this->factory()->post->create( [ 'post_type' => 'page' ] ); + $subject = new AutoVerify(); + $subject->init(); + $_SERVER['REQUEST_URI'] = '/?tracking=1&page_id=' . $page_id; + $method = $this->set_method_accessibility( $subject, 'get_form_action' ); + $expected = 'post:' . $page_id . ':/'; + + self::assertSame( $expected, $method->invoke( $subject, '
    ' ) ); + self::assertSame( $expected, $method->invoke( $subject, '' ) ); + self::assertSame( $expected, $method->invoke( $subject, '' ) ); + self::assertSame( '/', $method->invoke( $subject, '' ) ); + } + /** * An actionless form on a query route must not claim unrelated home requests. * @@ -134,6 +387,155 @@ static function () use ( &$die_arr ) { self::assertSame( 403, $die_arr[2]['response'] ?? null ); } + /** + * Equivalent plain permalink routes must verify the page's registered form. + * + * @param string $registration_path Registration path. + * @param string $request_path Submission path. + * @param string $query Page selector query. + * @param bool $explicit_action Whether the form has an explicit action. + * @param bool $valid_submission Whether the submission has valid hCaptcha data. + * @param string $home_path Home URL subdirectory. + * @param bool $post_selector Whether the page selector is submitted in POST. + * @param string $post_type Protected post type. + * + * @dataProvider dp_test_plain_permalink_aliases_verify_registered_form + */ + public function test_plain_permalink_aliases_verify_registered_form( + string $registration_path, + string $request_path, + string $query, + bool $explicit_action = false, + bool $valid_submission = false, + string $home_path = '', + bool $post_selector = false, + string $post_type = 'page' + ): void { + $old_structure = (string) get_option( 'permalink_structure' ); + $old_home = get_option( 'home' ); + $old_script_name = array_intersect_key( $_SERVER, [ 'SCRIPT_NAME' => true ] ); + + try { + $_SERVER['SCRIPT_NAME'] = '/index.php'; + $this->set_permalink_structure(); + update_option( 'home', untrailingslashit( $old_home ) . $home_path ); + $page_id = $this->factory()->post->create( + [ + 'post_type' => $post_type, + 'post_status' => 'publish', + 'post_name' => 'protected-auto-form', + ] + ); + $other_id = $this->factory()->post->create( [ 'post_type' => 'page' ] ); + $subject = new AutoVerify(); + $subject->init(); + + $selector = 'post' === $post_type ? 'p' : 'page_id'; + $registration_uri = $home_path . $registration_path . '?' . $selector . '=' . $page_id; + $_SERVER['REQUEST_URI'] = $home_path . '/?' . $selector . '=' . $page_id; + $_GET = [ $selector => (string) $page_id ]; + $content = $this->get_test_content(); + + if ( $explicit_action || '/index.php' === $registration_path ) { + $content = str_replace( '', '', $content ); + } + + apply_filters( 'the_content', $content ); + $target_key = 'post:' . $page_id . ':' . ( untrailingslashit( $home_path . $registration_path ) ?: '/' ); + $forms = $this->get_registered_action_forms( $target_key ); + self::assertCount( 1, $forms ); + + $query = str_replace( [ '{id}', '{other_id}' ], [ (string) $page_id, (string) $other_id ], $query ); + parse_str( $query, $query_vars ); + $_GET = $post_selector ? [] : $query_vars; + $_POST = [ 'test_input' => 'value' ]; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['REQUEST_URI'] = $home_path . $request_path . ( $post_selector ? '' : '?' . $query ); + + if ( $post_selector ) { + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $_POST = array_merge( $_POST, $query_vars ); + } + + $page_query = new WP_Query( $query_vars ); + self::assertSame( $page_id, $page_query->get_queried_object_id() ); + + if ( $valid_submission ) { + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = $forms[0]['widget_id']; + $args = $forms[0]['args']; + $_POST[ $args['name'] ] = wp_create_nonce( $args['action'] ); + $this->prepare_verify_request( 'some response' ); + } + + $submitted_post = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing + $die_arr = []; + add_filter( + 'wp_die_handler', + static function () use ( &$die_arr ) { + return static function ( $message, $title, $args ) use ( &$die_arr ) { + $die_arr = [ $message, $title, $args ]; + }; + } + ); + + $subject->verify(); + + if ( $valid_submission ) { + self::assertSame( [], $die_arr ); + self::assertTrue( hcaptcha()->has_result ); + self::assertSame( $submitted_post, $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } else { + self::assertSame( 403, $die_arr[2]['response'] ?? null ); + self::assertSame( [], $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } + } finally { + update_option( 'home', $old_home ); + $this->set_permalink_structure( $old_structure ); + unset( $_SERVER['SCRIPT_NAME'] ); + $_SERVER += $old_script_name; + } + } + + /** + * Data provider for plain permalink registration and submission aliases. + * + * @return array + */ + public function dp_test_plain_permalink_aliases_verify_registered_form(): array { + return [ + 'root to index' => [ '/', '/index.php', 'page_id={id}' ], + 'root to fresh path' => [ '/', '/fresh-path', 'page_id={id}' ], + 'login-shaped alias' => [ '/', '/wp-login.php', 'page_id={id}' ], + 'index to root' => [ '/index.php', '/', 'page_id={id}' ], + 'index to fresh path' => [ '/index.php', '/fresh-path', 'page_id={id}' ], + 'explicit root action' => [ '/', '/index.php', 'page_id={id}', true ], + 'explicit index action' => [ '/index.php', '/fresh-path', 'page_id={id}', true ], + 'post selector' => [ '/', '/fresh-path', 'p={id}', false, false, '', false, 'post' ], + 'page slug selector' => [ '/', '/fresh-path', 'pagename=protected-auto-form' ], + 'encoded selector' => [ '/', '/fresh-path', '%70age_id={id}' ], + 'encoded post selector' => [ '/', '/fresh-path', '%70={id}', false, false, '', false, 'post' ], + 'preceding parameter' => [ '/', '/fresh-path', 'tracking=1&page_id={id}' ], + 'zero page selector' => [ '/', '/fresh-path', 'page_id=0&p={id}', false, false, '', false, 'post' ], + 'negative page selector' => [ '/', '/fresh-path', 'page_id=-{id}' ], + 'numeric prefix' => [ '/', '/fresh-path', 'page_id={id}suffix' ], + 'HTML numeric suffix' => [ '/', '/fresh-path', 'page_id={id}%3Cbr%3E1' ], + 'percent numeric suffix' => [ '/', '/fresh-path', 'page_id={id}%25201' ], + 'encoded slug value' => [ '/', '/fresh-path', 'pagename=%2570rotected-auto-form' ], + 'name selector' => [ '/', '/fresh-path', 'post_type=page&name=protected-auto-form' ], + 'post name selector' => [ '/', '/fresh-path', 'name=protected-auto-form', false, false, '', false, 'post' ], + 'attachment ID alias' => [ '/', '/fresh-path', 'attachment_id={id}&post_type=page' ], + 'subpost ID alias' => [ '/', '/fresh-path', 'subpost_id={id}&post_type=page' ], + 'name overrides path' => [ '/', '/fresh-path', 'post_type=page&name=protected-auto-form&pagename=missing-page' ], + 'page takes precedence' => [ '/', '/fresh-path', 'post_type=page&p={other_id}&page_id={id}' ], + 'POST page selector' => [ '/', '/fresh-path', 'page_id={id}', false, false, '', true ], + 'POST slug selector' => [ '/', '/fresh-path', 'pagename=protected-auto-form', false, false, '', true ], + 'subdirectory root' => [ '/', '/index.php', 'page_id={id}', false, false, '/blog' ], + 'subdirectory index' => [ '/index.php', '/fresh-path', 'page_id={id}', false, false, '/blog' ], + 'valid root form' => [ '/', '/index.php', 'page_id={id}', false, true ], + 'valid index form' => [ '/index.php', '/fresh-path', 'page_id={id}', false, true ], + ]; + } + /** * An explicit root action on a query page still targets the home route. */ @@ -605,6 +1007,173 @@ public function test_verify_form_succeeds_without_transient_entry(): void { self::assertTrue( hcaptcha()->has_result ); } + /** + * Array-named inputs must reach CAPTCHA verification after form registration. + * + * @param array $inputs Registered input names. + * @param string $query Encoded submission. + * @param string $response CAPTCHA response. + * @param string $error Expected verification error. + * + * @dataProvider dp_test_verify_form_with_array_inputs + */ + public function test_verify_form_with_array_inputs( array $inputs, string $query, string $response, string $error ): void { + $_SERVER['REQUEST_URI'] = '/array-form'; + $subject = new AutoVerify(); + $subject->init(); + $content = ''; + + foreach ( $inputs as $input ) { + $content .= ''; + } + + apply_filters( 'the_content', $content . '[hcaptcha auto="true"]
    ' ); + $form = $this->get_registered_action_forms( '/array-form' )[0]; + + self::assertSame( $inputs, $form['inputs'] ); + parse_str( $query, $post ); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = $post + [ + HCaptcha::HCAPTCHA_WIDGET_ID => $form['widget_id'], + 'hcaptcha_nonce' => wp_create_nonce( 'hcaptcha_action' ), + 'hcap_hp_test' => '', + 'hcap_hp_sig' => wp_create_nonce( 'hcap_hp_test' ), + ]; + $this->prepare_verify_request( $response ); + $submitted = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing + $die_message = ''; + add_filter( + 'wp_die_handler', + static function () use ( &$die_message ) { + return static function ( $message ) use ( &$die_message ) { + $die_message = $message; + }; + } + ); + $subject->verify(); + + self::assertSame( $error, $die_message ); + + if ( '' === $error ) { + self::assertTrue( API::get_siteverify_response()['success'] ); + self::assertSame( $submitted, $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } else { + self::assertSame( [], $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } + } + + /** + * Successful and rejected submissions with PHP array field names. + * + * @return array + */ + public function dp_test_verify_form_with_array_inputs(): array { + return [ + 'contact form' => [ + [ 'contact[name]', 'contact[email]' ], + 'contact[name]=User&contact[email]=user@example.com', + 'some response', + '', + ], + 'nested lists' => [ + [ 'contact[emails][]', 'contacts[][name]' ], + 'contact[emails][]=user@example.com&contacts[2][name]=User', + 'some response', + '', + ], + 'missing sibling' => [ + [ 'contact[name]', 'contact[email]' ], + 'contact[name]=User', + 'some response', + 'Bad hCaptcha signature!', + ], + 'wrong widget' => [ + [ 'contact[email]' ], + 'contact[email]=user@example.com&hcaptcha-widget-id=other-widget-id', + 'some response', + 'Bad hCaptcha signature!', + ], + 'missing CAPTCHA response' => [ + [ 'contact[email]' ], + 'contact[email]=user@example.com', + '', + 'Please complete the hCaptcha.', + ], + ]; + } + + /** + * Default auto-verified forms do not require unsupported timing protection. + * + * @param bool $ajax Whether the form uses AJAX submission. + * @param bool $logged_in Whether the submitter is logged in. + * + * @dataProvider dp_test_default_shortcode_with_global_fst + */ + public function test_default_shortcode_with_global_fst( bool $ajax, bool $logged_in ): void { + $settings = (array) get_option( 'hcaptcha_settings', [] ); + $settings['set_min_submit_time'] = [ 'on' ]; + $settings['min_submit_time'] = '0'; + update_option( 'hcaptcha_settings', $settings ); + $this->prepare_verify_request( 'some response' ); + + wp_set_current_user( $logged_in ? $this->factory()->user->create() : 0 ); + $_POST = []; + $_SERVER['REQUEST_METHOD'] = 'GET'; + $_SERVER['REQUEST_URI'] = '/default-auto-form'; + $subject = new AutoVerify(); + $subject->init(); + $shortcode = '[hcaptcha auto="true"' . ( $ajax ? ' ajax="true"' : '' ) . ']'; + $content = '
    ' . $shortcode . '
    '; + + apply_filters( 'the_content', $content ); + $form = $this->get_registered_action_forms( '/default-auto-form' )[0]; + + self::assertSame( [ AutoVerify::class ], $form['args']['id']['source'] ); + self::assertFalse( hcaptcha()->settings()->is_on( 'set_min_submit_time' ) ); + self::assertSame( [ 'on' ], get_option( 'hcaptcha_settings' )['set_min_submit_time'] ); + + // Reload persisted settings as a new submission request would. + $this->prepare_verify_request( 'some response' ); + remove_filter( 'hcap_verify_fst_token', '__return_true' ); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ + 'test_input' => 'some input', + 'hcaptcha-widget-id' => $form['widget_id'], + 'hcaptcha_nonce' => wp_create_nonce( 'hcaptcha_action' ), + 'h-captcha-response' => 'some response', + ]; + $expected_post = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing + $die_message = null; + $die_handler = static function () use ( &$die_message ) { + return static function ( $message ) use ( &$die_message ) { + $die_message = $message; + }; + }; + add_filter( 'wp_die_handler', $die_handler ); + add_filter( 'wp_die_ajax_handler', $die_handler ); + + self::assertTrue( hcaptcha()->settings()->is_on( 'set_min_submit_time' ) ); + $subject->verify(); + + self::assertNull( $die_message ); + self::assertTrue( API::get_siteverify_response()['success'] ); + self::assertSame( $expected_post, $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } + + /** + * Data provider for default shortcode submissions with globally enabled FST. + * + * @return array + */ + public function dp_test_default_shortcode_with_global_fst(): array { + return [ + 'guest POST' => [ false, false ], + 'guest AJAX' => [ true, false ], + 'logged-in POST' => [ false, true ], + ]; + } + /** * Test verify_form() when the widget id is missing. */ @@ -1014,6 +1583,7 @@ private function get_test_registered_forms(): array { 'form_id' => 0, ], 'protect' => true, + 'mandatory' => false, ]; return [ diff --git a/tests/php/integration/Avada/FormTest.php b/tests/php/integration/Avada/FormTest.php index a567368ea..e6e0b3a75 100644 --- a/tests/php/integration/Avada/FormTest.php +++ b/tests/php/integration/Avada/FormTest.php @@ -62,7 +62,7 @@ class FormTest extends HCaptchaPluginWPTestCase { * @return void */ public function tearDown(): void { - unset( $_POST['field_types'], $_POST['formData'], $_POST['hcaptcha-widget-id'] ); + unset( $_POST['field_types'], $_POST['formData'], $_POST['form_id'], $_POST['hcaptcha-widget-id'] ); wp_dequeue_script( 'hcaptcha-avada' ); wp_deregister_script( 'hcaptcha-avada' ); @@ -202,12 +202,35 @@ public function test_verify(): void { // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode $_POST['field_types'] = json_encode( $field_types ); $_POST['formData'] = $form_data; + $_POST['form_id'] = (string) $form_id; $subject = new Form(); self::assertSame( $demo_mode, $subject->verify( $demo_mode ) ); } + /** + * A request without the native form ID cannot select a CAPTCHA identity. + */ + public function test_verify_without_form_id(): void { + $messages = []; + add_filter( + 'wp_die_handler', + static function () use ( &$messages ) { + return static function ( $message ) use ( &$messages ) { + $messages[] = $message; + }; + } + ); + + ( new Form() )->verify( true ); + + self::assertSame( + [ '{"status":"error","info":{"hcaptcha":"Bad hCaptcha signature!"}}' ], + $messages + ); + } + /** * Test verify() when widget id is bad. * @@ -233,6 +256,7 @@ public function test_verify_bad_widget_id(): void { $this->prepare_verify_request( $hcaptcha_response ); $_POST['formData'] = $this->get_form_data( $form_id, $hcaptcha_response, $bad_widget_id ); + $_POST['form_id'] = (string) $form_id; $subject = new Form(); @@ -257,7 +281,8 @@ static function ( $name ) use ( &$die_arr ) { * @noinspection PhpUnusedParameterInspection */ public function test_verify_not_verified(): void { - $hcaptcha_response = 'some_response'; + $form_id = 123; + $hcaptcha_response = ''; $die_arr = []; $expected = [ '{"status":"error","info":{"hcaptcha":"Please complete the hCaptcha."}}', @@ -267,7 +292,9 @@ public function test_verify_not_verified(): void { $this->prepare_verify_request( $hcaptcha_response, false ); - $subject = new Form(); + $_POST['form_id'] = (string) $form_id; + $_POST['formData'] = $this->get_form_data( $form_id, $hcaptcha_response ); + $subject = new Form(); add_filter( 'wp_die_handler', @@ -283,6 +310,58 @@ static function ( $name ) use ( &$die_arr ) { self::assertSame( $expected, $die_arr ); } + /** + * A nonce key inside formData cannot select another CAPTCHA identity. + * + * @return void + */ + public function test_verify_binds_to_native_form_id(): void { + $target_id = 123; + $die_arr = []; + + $_POST['form_id'] = (string) $target_id; + + add_filter( + 'wp_die_handler', + static function () use ( &$die_arr ) { + return static function ( $message ) use ( &$die_arr ) { + $die_arr[] = $message; + }; + } + ); + + $foreign_ids = [ + 0 => [ + 'source' => [ 'WordPress' ], + 'form_id' => 'register', + ], + 456 => [ + 'source' => [ 'Avada' ], + 'form_id' => 456, + ], + ]; + + foreach ( $foreign_ids as $foreign_id => $widget_identity ) { + $_POST['formData'] = http_build_query( + [ + "fusion-form-nonce-$foreign_id" => 'untrusted-first', + "fusion-form-nonce-$target_id" => 'valid-target', + 'hcaptcha-widget-id' => HCaptcha::widget_id_value( $widget_identity ), + ] + ); + + ( new Form() )->verify( false ); + } + + self::assertSame( + [ + '{"status":"error","info":{"hcaptcha":"Bad hCaptcha signature!"}}', + '{"status":"error","info":{"hcaptcha":"Bad hCaptcha signature!"}}', + ], + $die_arr + ); + } + /** * Test enqueue_scripts(). * diff --git a/tests/php/integration/BBPress/LostPasswordTest.php b/tests/php/integration/BBPress/LostPasswordTest.php index 30a85bb0e..0241478db 100644 --- a/tests/php/integration/BBPress/LostPasswordTest.php +++ b/tests/php/integration/BBPress/LostPasswordTest.php @@ -9,7 +9,7 @@ use HCaptcha\BBPress\LostPassword; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; -use WP_Error; +use ReflectionMethod; /** * Test LostPassword class. @@ -71,6 +71,25 @@ public function test_init_hooks(): void { self::assertSame( 10, has_filter( 'do_shortcode_tag', [ $subject, 'add_captcha' ] ) ); } + /** + * The lost-password request is owned only for the matching login action. + */ + public function test_is_owner_action(): void { + $subject = new LostPassword(); + $method = new ReflectionMethod( $subject, 'is_owner_action' ); + $method->setAccessible( true ); + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $_GET['action'] = 'lostpassword'; + self::assertTrue( $method->invoke( $subject ) ); + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $_GET['action'] = 'register'; + self::assertFalse( $method->invoke( $subject ) ); + + unset( $_GET['action'] ); + } + /** * Test add_captcha(). * diff --git a/tests/php/integration/BBPress/RegisterTest.php b/tests/php/integration/BBPress/RegisterTest.php index e60d9720d..67b3ff134 100644 --- a/tests/php/integration/BBPress/RegisterTest.php +++ b/tests/php/integration/BBPress/RegisterTest.php @@ -220,6 +220,20 @@ public function test_verify_when_not_verified(): void { self::assertEquals( $expected, $subject->verify( $errors, $sanitized_user_login, $user_email ) ); } + /** + * Reject a registration with an invalid widget signature. + */ + public function test_verify_rejects_invalid_widget_signature(): void { + $errors = new WP_Error(); + + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = 'invalid'; + + $result = ( new Register() )->verify( $errors, '', '' ); + + self::assertSame( $errors, $result ); + self::assertSame( [ 'bad-signature' ], $result->get_error_codes() ); + } + /** * Test verify() skips a request owned by the native WordPress verifier. * @@ -231,6 +245,7 @@ public function test_verify_skips_wordpress_owner(): void { new WPRegister(); + $_POST['action'] = 'register'; $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( [ 'source' => [ 'WordPress' ], @@ -239,6 +254,7 @@ public function test_verify_skips_wordpress_owner(): void { ); self::assertSame( $errors, $subject->verify( $errors, '', '' ) ); + self::assertSame( [ 'some code' ], $errors->get_error_codes() ); } /** diff --git a/tests/php/integration/BackInStockNotifier/FormTest.php b/tests/php/integration/BackInStockNotifier/FormTest.php index 4845cea49..11b219a75 100644 --- a/tests/php/integration/BackInStockNotifier/FormTest.php +++ b/tests/php/integration/BackInStockNotifier/FormTest.php @@ -78,9 +78,10 @@ static function ( array $form_args ) use ( &$args ): string { ); self::assertSame( [ - 'action' => 'hcaptcha_back_in_stock_notifier', - 'name' => 'hcaptcha_back_in_stock_notifier_nonce', - 'id' => [ + 'mandatory' => false, + 'action' => 'hcaptcha_back_in_stock_notifier', + 'name' => 'hcaptcha_back_in_stock_notifier_nonce', + 'id' => [ 'source' => [ 'source' ], 'form_id' => $product_id, ], @@ -93,17 +94,25 @@ static function ( array $form_args ) use ( &$args ): string { * Test that submitted fields are passed to verification. */ public function test_verify(): void { + $id = [ + 'source' => [ 'back-in-stock-notifier-for-woocommerce/cwginstocknotifier.php' ], + 'form_id' => 123, + ]; $post_data = [ + 'product_id' => 123, + 'user_email' => 'person@example.com', + 'product_note' => 'Please notify me', + 'payment_card' => 'private-payment-data', 'h-captcha-response' => 'response-token', - 'hcaptcha-widget-id' => 'widget-id', + 'hcaptcha-widget-id' => HCaptcha::widget_id_value( $id ), 'hcaptcha_back_in_stock_notifier_nonce' => 'nonce', ]; $actual = []; FunctionMocker::replace( '\\HCaptcha\\Helpers\\API::verify_post_data', - static function ( string $name, string $action, array $data ) use ( &$actual ): ?string { - $actual = [ $name, $action, $data ]; + static function ( string $name, string $action, array $data, array $expected_id, array $entry ) use ( &$actual ): ?string { + $actual = [ $name, $action, $data, $expected_id, $entry ]; return null; } @@ -112,11 +121,50 @@ static function ( string $name, string $action, array $data ) use ( &$actual ): ( new Form() )->verify( $post_data, false ); self::assertSame( - [ 'hcaptcha_back_in_stock_notifier_nonce', 'hcaptcha_back_in_stock_notifier', $post_data ], + [ + 'hcaptcha_back_in_stock_notifier_nonce', + 'hcaptcha_back_in_stock_notifier', + $post_data, + $id, + [ + 'data' => [ + 'product_id' => '123', + 'user_email' => 'person@example.com', + 'product_note' => 'Please notify me', + 'email' => 'person@example.com', + ], + 'email_addresses' => [ 'person@example.com' ], + ], + ], $actual ); } + /** + * Missing product IDs still carry a nonempty expected widget identity. + */ + public function test_verify_without_product_id_checks_widget_identity(): void { + $expected_id = []; + FunctionMocker::replace( + '\HCaptcha\Helpers\API::verify_post_data', + static function ( string $name, string $action, array $data, array $id ) use ( &$expected_id ): ?string { + $expected_id = $id; + + return null; + } + ); + + ( new Form() )->verify( [], false ); + + self::assertSame( + [ + 'source' => [ 'back-in-stock-notifier-for-woocommerce/cwginstocknotifier.php' ], + 'form_id' => 0, + ], + $expected_id + ); + } + /** * Test that an AJAX verification error is returned as JSON. * @@ -262,6 +310,7 @@ public function test_filled_honeypot_is_rejected(): void { ] ); $_POST['hcap_hp_test'] = 'bot'; + $_POST['product_id'] = 123; $subject = Mockery::mock( Form::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); diff --git a/tests/php/integration/BeaverBuilder/LoginTest.php b/tests/php/integration/BeaverBuilder/LoginTest.php index 166365f76..2d880842a 100644 --- a/tests/php/integration/BeaverBuilder/LoginTest.php +++ b/tests/php/integration/BeaverBuilder/LoginTest.php @@ -99,6 +99,26 @@ public function test_init_hooks(): void { has_filter( 'fl_builder_render_module_content', [ $subject, 'add_beaver_builder_captcha' ] ) ); self::assertSame( 10, has_filter( 'wp_authenticate_user', [ $subject, 'verify' ] ) ); + self::assertSame( 10, has_action( 'wp_login', [ $subject, 'login' ] ) ); + self::assertSame( 10, has_action( 'wp_login_failed', [ $subject, 'login_failed' ] ) ); + } + + /** + * Beaver login failures activate its adaptive challenge. + * + * @return void + */ + public function test_failed_login_activates_adaptive_challenge(): void { + hcaptcha()->settings()->set( 'login_limit', 1 ); + hcaptcha()->settings()->set( 'login_interval', 15 ); + + $subject = new Login(); + $this->set_protected_property( $subject, 'ip', '198.51.100.223' ); + $exceeded = $this->set_method_accessibility( $subject, 'is_login_limit_exceeded' ); + + self::assertFalse( $exceeded->invoke( $subject ) ); + $subject->login_failed( 'sec022-invalid-user' ); + self::assertTrue( $exceeded->invoke( $subject ) ); } /** diff --git a/tests/php/integration/Blocksy/ProductReviewTest.php b/tests/php/integration/Blocksy/ProductReviewTest.php index dbc89d42e..8c4803286 100644 --- a/tests/php/integration/Blocksy/ProductReviewTest.php +++ b/tests/php/integration/Blocksy/ProductReviewTest.php @@ -13,7 +13,7 @@ namespace HCaptcha\Tests\Integration\Blocksy; use HCaptcha\Blocksy\ProductReview; -use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; +use HCaptcha\Tests\Integration\WC\WooCommerceTestCase; use ReflectionClass; /** @@ -21,14 +21,7 @@ * * @group blocksy */ -class ProductReviewTest extends HCaptchaPluginWPTestCase { - - /** - * WooCommerce plugin entry file. - * - * @var string - */ - protected static $plugin = 'woocommerce/woocommerce.php'; +class ProductReviewTest extends WooCommerceTestCase { /** * Blocksy theme stylesheet. @@ -38,19 +31,17 @@ class ProductReviewTest extends HCaptchaPluginWPTestCase { protected static string $theme = 'blocksy'; /** - * Hooks to replay after loading WooCommerce. + * Optional incorrect usage notice raised by the live theme. * * @var string[] */ - protected static array $plugin_load_hooks = [ - 'plugins_loaded', - 'init', - ]; + protected static array $plugin_optional_incorrect_usage = [ "add_theme_support( 'title-tag' )" ]; /** * Test that the live Blocksy screen manager and WooCommerce are loaded. * * @return void + * @noinspection PhpUndefinedFunctionInspection */ public function test_live_blocksy_and_woocommerce_are_loaded(): void { $theme_file = wp_normalize_path( ( new ReflectionClass( 'Blocksy_Screen_Manager' ) )->getFileName() ); @@ -89,6 +80,7 @@ public function test_constructor_and_init_hooks(): void { * Test add_hcaptcha() when not a product page. * * @return void + * @noinspection PhpUndefinedFunctionInspection */ public function test_add_hcaptcha_not_product(): void { $page_id = wp_insert_post( @@ -116,6 +108,7 @@ public function test_add_hcaptcha_not_product(): void { * Test add_hcaptcha() when on a product page. * * @return void + * @noinspection PhpUndefinedFunctionInspection */ public function test_add_hcaptcha_product(): void { $product_id = wp_insert_post( diff --git a/tests/php/integration/Brizy/FormTest.php b/tests/php/integration/Brizy/FormTest.php index 36cacd5a9..d74111f46 100644 --- a/tests/php/integration/Brizy/FormTest.php +++ b/tests/php/integration/Brizy/FormTest.php @@ -105,16 +105,20 @@ static function ( array $form_args ) use ( &$args ): string { * Test that submitted fields are passed to verification. */ public function test_verify(): void { - $post_data = [ + $expected_id = [ + 'source' => [ 'brizy/brizy.php' ], + 'form_id' => 'form', + ]; + $post_data = [ 'email' => 'person@example.com', 'h-captcha-response' => 'response-token', - 'hcaptcha-widget-id' => 'widget-id', + 'hcaptcha-widget-id' => HCaptcha::widget_id_value( $expected_id ), 'hcaptcha_brizy_nonce' => 'nonce', 'hcap_hp_dynamic' => '', 'hcap_hp_sig' => 'honeypot-signature', 'hcap_fst_token' => 'fst-token', ]; - $data = []; + $data = []; foreach ( $post_data as $name => $value ) { $data[] = [ @@ -134,21 +138,27 @@ public function test_verify(): void { FunctionMocker::replace( '\\HCaptcha\\Helpers\\API::verify_post_data', - static function ( string $name, string $action, array $submitted_data ) use ( &$actual ): ?string { - $actual = [ $name, $action, $submitted_data ]; + static function ( string $name, string $action, array $submitted_data, array $bound_id ) use ( &$actual ): ?string { + $actual = [ $name, $action, $submitted_data, $bound_id ]; return null; } ); self::assertSame( 'form', ( new Form() )->verify( 'form' ) ); - self::assertSame( [ 'hcaptcha_brizy_nonce', 'hcaptcha_brizy_form', $post_data ], $actual ); + self::assertSame( [ 'hcaptcha_brizy_nonce', 'hcaptcha_brizy_form', $post_data, $expected_id ], $actual ); } /** * Test that the legacy response field is normalized. */ public function test_verify_with_legacy_response_name(): void { + $expected_id = [ + 'source' => [ 'brizy/brizy.php' ], + 'form_id' => 'form', + ]; + $widget_id = HCaptcha::widget_id_value( $expected_id ); + $_POST['data'] = wp_json_encode( [ [ @@ -159,14 +169,18 @@ public function test_verify_with_legacy_response_name(): void { 'name' => 'hcaptcha_brizy_nonce', 'value' => 'nonce', ], + [ + 'name' => HCaptcha::HCAPTCHA_WIDGET_ID, + 'value' => $widget_id, + ], ] ); $actual = []; FunctionMocker::replace( '\\HCaptcha\\Helpers\\API::verify_post_data', - static function ( string $name, string $action, array $submitted_data ) use ( &$actual ): ?string { - $actual = [ $name, $action, $submitted_data ]; + static function ( string $name, string $action, array $submitted_data, array $bound_id ) use ( &$actual ): ?string { + $actual = [ $name, $action, $submitted_data, $bound_id ]; return null; } @@ -181,7 +195,9 @@ static function ( string $name, string $action, array $submitted_data ) use ( &$ [ 'h-captcha-response' => 'response-token', 'hcaptcha_brizy_nonce' => 'nonce', + 'hcaptcha-widget-id' => $widget_id, ], + $expected_id, ], $actual ); diff --git a/tests/php/integration/BuddyPress/RegisterTest.php b/tests/php/integration/BuddyPress/RegisterTest.php index 0637fd4a2..e13112aa0 100644 --- a/tests/php/integration/BuddyPress/RegisterTest.php +++ b/tests/php/integration/BuddyPress/RegisterTest.php @@ -119,6 +119,7 @@ public function test_add_captcha(): void { * Test hCaptcha in the live BuddyPress registration template. * * @return void + * @noinspection PhpUndefinedFunctionInspection */ public function test_live_registration_template(): void { $bp = buddypress(); @@ -249,4 +250,51 @@ private function prepare_widget_id(): void { ] ); } + + /** + * Check the native signup email instead of a generic submitted alias. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native email. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + global $bp; + + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $bp->signup = (object) [ + 'errors' => [], + 'email' => $email, + ]; + $_POST['signup_email'] = $email; + $_POST['email'] = 'safe@example.com'; + $this->prepare_widget_id(); + $this->prepare_verify_post( 'hcaptcha_bp_register_nonce', 'hcaptcha_bp_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'bp_status', [ 'registration' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + + self::assertSame( ! $blocked, ( new Register() )->verify() ); + self::assertSame( $blocked ? hcap_get_error_messages()['disposable-email'] : '', $bp->signup->errors['hcaptcha_response_verify'] ?? '' ); + } + + /** + * Native email policy controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable email' => [ 'user@disposable.example', true ], + 'permanent email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } } diff --git a/tests/php/integration/CF7/AdminTest.php b/tests/php/integration/CF7/AdminTest.php index a7c16802a..dd1f9d152 100644 --- a/tests/php/integration/CF7/AdminTest.php +++ b/tests/php/integration/CF7/AdminTest.php @@ -373,6 +373,68 @@ static function () use ( $stripe_form ) { self::assertSame( $expected, ob_get_clean() ); } + /** + * The editor renders a live preview for an unsaved CF7 form. + */ + public function test_insert_live_form_without_shortcode(): void { + FunctionMocker::replace( '\HCaptcha\CF7\current_user_can', true ); + $subject = new Admin(); + $method = $this->set_method_accessibility( $subject, 'insert_live_form' ); + $editor = '
    ' + . '' + . '

    '; + + $output = $method->invoke( $subject, $editor ); + + self::assertStringContainsString( 'id="form-live"', $output ); + self::assertStringContainsString( 'your-name', $output ); + } + + /** + * Users without CF7 editing permission receive the original editor markup. + */ + public function test_insert_live_form_without_permission(): void { + FunctionMocker::replace( '\HCaptcha\CF7\current_user_can', false ); + $subject = new Admin(); + $method = $this->set_method_accessibility( $subject, 'insert_live_form' ); + + self::assertSame( 'editor markup', $method->invoke( $subject, 'editor markup' ) ); + } + + /** + * AJAX preview renders an unsaved form without a CF7 shortcode. + * + * @noinspection JsonEncodingApiUsageInspection + */ + public function test_update_form_without_shortcode(): void { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $original_request = $_REQUEST; + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Snapshot before the simulated request. + $original_post = $_POST; + FunctionMocker::replace( '\HCaptcha\CF7\current_user_can', true ); + $_REQUEST['nonce'] = wp_create_nonce( Admin::UPDATE_FORM_ACTION ); + $_POST['shortcode'] = ''; + $_POST['form'] = '[text* your-name]'; + $die_handler = static function () { + return static function () {}; + }; + add_filter( 'wp_doing_ajax', '__return_true' ); + add_filter( 'wp_die_ajax_handler', $die_handler ); + + try { + ob_start(); + ( new Admin() )->update_form(); + $response = json_decode( ob_get_clean(), true ); + self::assertTrue( $response['success'] ); + self::assertStringContainsString( 'your-name', $response['data'] ); + } finally { + remove_filter( 'wp_doing_ajax', '__return_true' ); + remove_filter( 'wp_die_ajax_handler', $die_handler ); + $_REQUEST = $original_request; + $_POST = $original_post; + } + } + /** * Test add_tag_generator_hcaptcha(). * @@ -475,6 +537,7 @@ public function test_tag_generator_hcaptcha(): void { * * @noinspection PhpConditionAlreadyCheckedInspection * @noinspection PhpUndefinedConstantInspection + * @noinspection JsonEncodingApiUsageInspection */ public function test_enqueue_admin_scripts(): void { global $wp_scripts; @@ -541,7 +604,7 @@ public function test_action_admin_print_footer_scripts(): void { * * @return void * @noinspection HtmlUnknownAnchorTarget - * @noinspection PhpVariableIsUsedOnlyInClosureInspection + * @noinspection JsonEncodingApiUsageInspection */ public function test_update_form(): void { $user_id = 1; diff --git a/tests/php/integration/CF7/CF7Test.php b/tests/php/integration/CF7/CF7Test.php index 816b1b6fd..d61532d99 100644 --- a/tests/php/integration/CF7/CF7Test.php +++ b/tests/php/integration/CF7/CF7Test.php @@ -14,11 +14,14 @@ use HCaptcha\CF7\Base; use HCaptcha\CF7\CF7; +use HCaptcha\Helpers\API; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Settings\General; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; use Mockery; +use ReflectionProperty; use tad\FunctionMocker\FunctionMocker; +use WPCF7_ContactForm; use WPCF7_FormTag; use WPCF7_Submission; use WPCF7_Validation; @@ -448,6 +451,67 @@ static function ( $prefix, $more_entropy ) use ( $uniqid ) { self::assertSame( $expected, $subject->wpcf7_shortcode( $output, $tag, $attr, $m ) ); } + /** + * CF7 form IDs are read from either hidden-input order or the data attribute. + */ + public function test_get_form_id_from_alternate_native_markup(): void { + $subject = new CF7(); + $method = $this->set_method_accessibility( $subject, 'get_form_id' ); + + self::assertSame( 41, $method->invoke( $subject, '', [] ) ); + self::assertSame( 42, $method->invoke( $subject, '
    ', [] ) ); + } + + /** + * A saved RSC tag is found when CF7 has no current matching form. + */ + public function test_form_has_rsc_tag_uses_saved_form(): void { + $contact_form = WPCF7_ContactForm::get_template( + [ + 'locale' => 'en_US', + 'title' => 'Saved RSC form', + ] + ); + $properties = $contact_form->get_properties(); + $properties['form'] = '[captchar captcha-1]'; + $contact_form->set_properties( $properties ); + $form_id = $contact_form->save(); + + $subject = new CF7(); + $method = $this->set_method_accessibility( $subject, 'form_has_rsc_tag' ); + self::assertFalse( $method->invoke( $subject, 0, 'captchar' ) ); + $current = WPCF7_ContactForm::get_current(); + $current_property = new ReflectionProperty( WPCF7_ContactForm::class, 'current' ); + $current_property->setAccessible( true ); + $current_property->setValue( null, null ); + + try { + self::assertTrue( $method->invoke( $subject, $form_id, 'captchar' ) ); + } finally { + $current_property->setValue( null, $current ); + } + } + + /** + * CF7's optional Unicode whitespace helper is used when available. + * + * @runInSeparateProcess + * @preserveGlobalState disabled + * @group process-isolation-php74 + */ + public function test_has_rsc_tag_with_unicode_whitespace_helper(): void { + if ( ! function_exists( 'wpcf7_get_unicode_whitespaces' ) ) { + require_once dirname( __DIR__ ) . '/Stubs/CF7/wpcf7_get_unicode_whitespaces.php'; + } + + $contact_form = Mockery::mock( WPCF7_ContactForm::class ); + $contact_form->shouldReceive( 'prop' )->with( 'form' )->andReturn( '[captchar captcha-1]' ); + $subject = new CF7(); + $method = $this->set_method_accessibility( $subject, 'has_rsc_tag' ); + + self::assertTrue( $method->invoke( $subject, $contact_form, 'captchar' ) ); + } + /** * Test check_rest_nonce(). * @@ -1078,4 +1142,77 @@ private function prepare_widget_id( int $form_id, array $id = [] ): void { $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( $id ); } + /** + * Apply email policy to all native email tags despite custom names and collisions. + * + * @param bool $blocked Whether the trusted email is disposable. + * @dataProvider dp_sec063_email_policy + */ + public function test_sec063_typed_email_policy( bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + $this->prepare_widget_id( 23 ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $form = Mockery::mock( WPCF7_ContactForm::class ); + $form->shouldReceive( 'id' )->andReturn( 23 ); + $form->shouldReceive( 'scan_form_tags' )->andReturn( + [ + new WPCF7_FormTag( + [ + 'type' => 'email', + 'basetype' => 'email', + 'name' => 'billing_email', + ] + ), + new WPCF7_FormTag( + [ + 'type' => 'email', + 'basetype' => 'email', + 'name' => 'contact_address', + ] + ), + new WPCF7_FormTag( + [ + 'type' => 'text', + 'basetype' => 'text', + 'name' => 'email', + ] + ), + new WPCF7_FormTag( + [ + 'type' => 'text', + 'basetype' => 'text', + 'name' => 'password', + ] + ), + ] + ); + $submission = Mockery::mock( WPCF7_Submission::class ); + $submission->shouldReceive( 'get_contact_form' )->andReturn( $form ); + $submission->shouldReceive( 'get_posted_data' )->andReturn( + [ + 'billing_email' => [ 'primary@example.com', [ $blocked ? 'person@sec063-disposable.test' : 'person@example.com' ] ], + 'contact_address' => 'reader@example.com', + 'email' => 'spoof@sec063-disposable.test', + 'password' => 'private-password', + ] + ); + $subject = new CF7(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $submission ); + + self::assertArrayNotHasKey( 'password', $entry['data'] ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + /** + * Exercise both policy rejection and permanent address acceptance. + * + * @return array + */ + public function dp_sec063_email_policy(): array { + return [ + 'disposable' => [ true ], + 'permanent' => [ false ], + ]; + } } diff --git a/tests/php/integration/CF7/ReallySimpleCaptchaTest.php b/tests/php/integration/CF7/ReallySimpleCaptchaTest.php index d526b765e..610451f80 100644 --- a/tests/php/integration/CF7/ReallySimpleCaptchaTest.php +++ b/tests/php/integration/CF7/ReallySimpleCaptchaTest.php @@ -15,12 +15,13 @@ use HCaptcha\CF7\CF7; use HCaptcha\CF7\ReallySimpleCaptcha; +use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; use Mockery; use ReflectionClass; +use ReflectionProperty; use WPCF7_ContactForm; use WPCF7_Submission; -use function PHPUnit\Framework\assertSame; /** * Test ReallySimpleCaptcha class. @@ -56,7 +57,7 @@ class ReallySimpleCaptchaTest extends HCaptchaPluginWPTestCase { * @return void */ protected function before_load_test_plugins(): void { - update_option( 'hcaptcha_settings', [ 'cf7_status' => [ 'replace_rsc', 'embed' ] ] ); + update_option( 'hcaptcha_settings', [ 'cf7_status' => [ 'replace_rsc' ] ] ); hcaptcha()->init_hooks(); new ReallySimpleCaptcha(); new CF7(); @@ -65,9 +66,13 @@ protected function before_load_test_plugins(): void { /** * Test a live Contact Form 7 form containing Really Simple CAPTCHA tags. * + * @param string $form_template RSC form template. + * @param string $shortcode CF7 shortcode alias. + * @dataProvider dp_live_rsc_forms + * * @return void */ - public function test_live_really_simple_captcha_form(): void { + public function test_live_really_simple_captcha_form( string $form_template, string $shortcode ): void { $contact_form = WPCF7_ContactForm::get_template( [ 'locale' => 'en_US', @@ -75,7 +80,7 @@ public function test_live_really_simple_captcha_form(): void { ] ); $properties = $contact_form->get_properties(); - $properties['form'] = '[text* your-name] [captchac captcha-1] [captchar* captcha-1] [submit "Send"]'; + $properties['form'] = $form_template; $properties['mail'] = []; $properties['mail_2'] = []; @@ -84,7 +89,12 @@ public function test_live_really_simple_captcha_form(): void { add_shortcode( 'contact-form-7', 'wpcf7_contact_form_tag_func' ); - $output = do_shortcode( '[contact-form-7 id="' . $form_id . '"]' ); + if ( 'contact-form' === $shortcode ) { + add_shortcode( 'contact-form', 'wpcf7_contact_form_tag_func' ); + add_post_meta( $form_id, '_old_cf7_unit_id', $form_id ); + } + + $output = do_shortcode( 'contact-form' === $shortcode ? '[contact-form ' . $form_id . ']' : '[contact-form-7 id="' . $form_id . '"]' ); $plugin_file = wp_normalize_path( ( new ReflectionClass( \ReallySimpleCaptcha::class ) )->getFileName() ); self::assertTrue( is_plugin_active( 'contact-form-7/wp-contact-form-7.php' ) ); @@ -97,6 +107,117 @@ public function test_live_really_simple_captcha_form(): void { self::assertStringNotContainsString( '[captchar', $output ); } + /** + * RSC forms can use both native CF7 aliases and Unicode tag separators. + * + * @return array + */ + public function dp_live_rsc_forms(): array { + $normal_form = '[text* your-name] [captchac captcha-1] [captchar captcha-1] [submit "Send"]'; + $nbsp = "\u{00A0}"; + $nbsp_form = '[text* your-name] [captchac' . $nbsp . 'captcha-1] [captchar' . $nbsp . 'captcha-1] [submit "Send"]'; + + return [ + 'default' => [ $normal_form, 'contact-form-7' ], + 'nbsp' => [ $nbsp_form, 'contact-form-7' ], + 'legacy-alias' => [ $normal_form, 'contact-form' ], + 'alias-nbsp' => [ $nbsp_form, 'contact-form' ], + 'one-sided-close' => [ '[text* your-name] [captchac captcha-1] [captchar captcha-1]] [submit "Send"]', 'contact-form-7' ], + 'one-sided-open' => [ '[text* your-name] [[captchac captcha-1] [captchar captcha-1] [submit "Send"]', 'contact-form-7' ], + ]; + } + + /** + * Replacement alone must validate RSC forms without affecting other forms. + * + * @param string $form_template Form template. + * @param bool $should_reject Whether the missing proof must be rejected. + * @param bool $valid_proof Whether to use a valid hCaptcha proof. + * @dataProvider dp_replace_only_submission + * + * @return void + */ + public function test_replace_only_submission( string $form_template, bool $should_reject, bool $valid_proof ): void { + $contact_form = WPCF7_ContactForm::get_template( + [ + 'locale' => 'en_US', + 'title' => 'SEC041 form', + ] + ); + $properties = $contact_form->get_properties(); + $properties['form'] = $form_template; + $properties['mail'] = []; + $properties['mail_2'] = []; + $contact_form->set_properties( $properties ); + $form_id = $contact_form->save(); + self::assertGreaterThan( 0, $form_id ); + + $before_mail = false; + add_filter( 'wpcf7_skip_spam_check', '__return_true' ); + add_action( + 'wpcf7_before_send_mail', + static function ( $form, &$abort ) use ( &$before_mail ): void { + $before_mail = true; + $abort = true; + }, + 10, + 2 + ); + + $_POST = [ + '_wpcf7' => (string) $form_id, + '_wpcf7_unit_tag' => 'wpcf7-f' . $form_id . '-o1', + '_wpcf7_locale' => 'en_US', + '_wpcf7_container_post' => '0', + 'your-name' => 'SEC041 sender', + ]; + if ( $valid_proof ) { + $this->prepare_verify_request( 'sec041-local-proof' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'contact-form-7/wp-contact-form-7.php' ], + 'form_id' => $form_id, + ] + ); + } + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Synthetic native CF7 request. + $_REQUEST = $_POST; + $_SERVER['REQUEST_METHOD'] = 'POST'; + + try { + $result = $contact_form->submit( [ 'skip_mail' => true ] ); + self::assertSame( $should_reject ? 'validation_failed' : 'aborted', $result['status'] ); + self::assertSame( ! $should_reject, $before_mail ); + } finally { + $submission_instance = new ReflectionProperty( WPCF7_Submission::class, 'instance' ); + $submission_instance->setAccessible( true ); + $submission_instance->setValue( null, null ); + unset( $_POST, $_REQUEST, $_SERVER['REQUEST_METHOD'] ); + } + } + + /** + * Cases for replacement-only CF7 submissions. + * + * @return array + */ + public function dp_replace_only_submission(): array { + $nbsp = "\u{00A0}"; + + return [ + 'rsc-pair-missing' => [ '[text* your-name] [captchac captcha-1] [captchar captcha-1] [submit "Send"]', true, false ], + 'rsc-pair-valid' => [ '[text* your-name] [captchac captcha-1] [captchar captcha-1] [submit "Send"]', false, true ], + 'rsc-nbsp-missing' => [ '[text* your-name] [captchac' . $nbsp . 'captcha-1] [captchar' . $nbsp . 'captcha-1] [submit "Send"]', true, false ], + 'rsc-nbsp-valid' => [ '[text* your-name] [captchac' . $nbsp . 'captcha-1] [captchar' . $nbsp . 'captcha-1] [submit "Send"]', false, true ], + 'one-sided-close' => [ '[text* your-name] [captchac captcha-1] [captchar captcha-1]] [submit "Send"]', true, false ], + 'one-sided-open' => [ '[text* your-name] [[captchac captcha-1] [captchar captcha-1] [submit "Send"]', true, false ], + 'rsc-response' => [ '[text* your-name] [captchar* captcha-1] [submit "Send"]', true, false ], + 'ordinary' => [ '[text* your-name] [submit "Send"]', false, false ], + 'explicit-embed' => [ '[text* your-name] [cf7-hcaptcha] [submit "Send"]', false, false ], + 'escaped-rsc' => [ '[text* your-name] [[captchac captcha-1]] [[captchar captcha-1]] [submit "Send"]', false, false ], + ]; + } + /** * Test init_hooks(). * @@ -149,6 +270,7 @@ public function test_wpcf7_shortcode(): void { // CF7 tag. self::assertSame( $expected, $subject->wpcf7_shortcode( $output, $tag, [], [] ) ); + self::assertSame( $expected, $subject->wpcf7_shortcode( $output, 'contact-form', [], [] ) ); } /** diff --git a/tests/php/integration/ClassifiedListing/EmailPolicyTest.php b/tests/php/integration/ClassifiedListing/EmailPolicyTest.php new file mode 100644 index 000000000..cf15d08db --- /dev/null +++ b/tests/php/integration/ClassifiedListing/EmailPolicyTest.php @@ -0,0 +1,114 @@ +settings()->set( 'classified_listing_status', [ 'contact', 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + } + + /** + * A submitted alias cannot replace the native callback address. + */ + public function test_registration_checks_native_callback_email(): void { + $this->prepare_form( 'register' ); + $_POST['rtcl-register'] = 'Register'; + $_POST['email'] = 'safe@example.com'; + + // The production API verifies the test nonce. + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $result = ( new Register() )->verify( new WP_Error(), 'user@disposable.example', 'guest', '', $_POST ); + + self::assertSame( hcap_get_error_messages()['disposable-email'], $result->get_error_message( 'disposable-email' ) ); + } + + /** + * Contact validation checks the native validated data. + */ + public function test_contact_checks_native_data_email(): void { + $this->prepare_form( 'contact' ); + $_POST['email'] = 'safe@example.com'; + $error = new WP_Error(); + + ( new Contact() )->verify( $error, [ 'email' => 'user@disposable.example' ] ); + + self::assertSame( hcap_get_error_messages()['disposable-email'], $error->get_error_message( 'disposable-email' ) ); + } + + /** + * Legitimate native email and an email-free submission remain accepted. + * + * @dataProvider dp_test_allowed_contact + * + * @param array $data Native data. + */ + public function test_allowed_contact( array $data ): void { + $this->prepare_form( 'contact' ); + $_POST['email'] = 'forged@disposable.example'; + $error = new WP_Error(); + + ( new Contact() )->verify( $error, $data ); + + self::assertFalse( $error->has_errors() ); + } + + /** + * Native contact email controls. + * + * @return array + */ + public function dp_test_allowed_contact(): array { + return [ + 'permanent email' => [ [ 'email' => 'safe@example.com' ] ], + 'email-free data' => [ [] ], + ]; + } + + /** + * Prepare a signed form and successful remote proof. + * + * @param string $form_id Native form ID. + */ + private function prepare_form( string $form_id ): void { + $this->prepare_verify_post( 'hcaptcha_classified_listing_' . $form_id . '_nonce', 'hcaptcha_classified_listing_' . $form_id ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'classified_listing_status', [ 'contact', 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'classified-listing/classified-listing.php' ], + 'form_id' => $form_id, + ] + ); + } +} diff --git a/tests/php/integration/ClassifiedListing/FormsTest.php b/tests/php/integration/ClassifiedListing/FormsTest.php index 3bd718b4f..973c8b827 100644 --- a/tests/php/integration/ClassifiedListing/FormsTest.php +++ b/tests/php/integration/ClassifiedListing/FormsTest.php @@ -21,6 +21,34 @@ * @group classified-listing */ class FormsTest extends HCaptchaWPTestCase { + /** + * Leave unrelated template parts outside the contact form buffer. + */ + public function test_contact_ignores_other_template_parts(): void { + $subject = new Contact(); + $level = ob_get_level(); + + $subject->before_template_part( 'other', '', [] ); + $subject->after_template_part( 'other', '', [] ); + + self::assertSame( $level, ob_get_level() ); + } + + /** + * A valid native registration proof preserves the existing error object. + */ + public function test_registration_accepts_valid_proof(): void { + $this->prepare_verify_post( 'hcaptcha_classified_listing_register_nonce', 'hcaptcha_classified_listing_register' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'classified-listing/classified-listing.php' ], + 'form_id' => 'register', + ] + ); + $errors = new WP_Error(); + + self::assertSame( $errors, ( new Register() )->verify( $errors, 'safe@example.com', 'guest', '', [ 'rtcl-register' => 'Register' ] ) ); + } /** * Set up the test. @@ -91,12 +119,81 @@ public function test_filled_honeypot_blocks_registration(): void { $_POST['hcap_hp_test'] = 'bot'; $_POST['rtcl-register'] = 'Register'; - $result = ( new Register() )->verify( new WP_Error(), '', '', '', [] ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $result = ( new Register() )->verify( new WP_Error(), '', '', '', $_POST ); self::assertInstanceOf( WP_Error::class, $result ); self::assertSame( 'Anti-spam check failed.', $result->get_error_message( 'spam' ) ); } + /** + * Both native login handlers call this filter before wp_signon. + */ + public function test_native_login_filter_rejects_missing_hcaptcha_without_form_marker(): void { + add_filter( 'hcap_login_limit_exceeded', '__return_true' ); + $subject = new Login(); + + self::assertSame( 10, has_filter( 'rtcl_process_login_errors', [ $subject, 'verify' ] ) ); + self::assertFalse( has_filter( 'wp_authenticate_user', [ $subject, 'verify' ] ) ); + + $result = apply_filters( 'rtcl_process_login_errors', new WP_Error(), 'synthetic-user', 'synthetic-password' ); + + self::assertSame( 'bad-signature', $result->get_error_code() ); + } + + /** + * Adaptive login protection still permits native attempts below its threshold. + */ + public function test_native_login_filter_preserves_below_threshold_result(): void { + add_filter( 'hcap_login_limit_exceeded', '__return_false' ); + new Login(); + $errors = new WP_Error(); + + $result = apply_filters( 'rtcl_process_login_errors', $errors, 'synthetic-user', 'synthetic-password' ); + + self::assertSame( $errors, $result ); + } + + /** + * The localized non-AJAX submit label cannot disable account registration protection. + */ + public function test_registration_accepts_any_native_nonempty_submit_marker(): void { + $post = [ 'rtcl-register' => 'S’inscrire' ]; + + $result = ( new Register() )->verify( new WP_Error(), 'safe@example.com', 'synthetic-user', '', $post ); + + self::assertSame( 'bad-signature', $result->get_error_code() ); + } + + /** + * Native account registration AJAX does not require a submit-button marker. + */ + public function test_native_ajax_registration_rejects_missing_hcaptcha_without_marker(): void { + // Simulate the server-owned action around the native validation callback. + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited + $GLOBALS['wp_current_filter'][] = 'wp_ajax_nopriv_rtcl_registration_request'; + + try { + $result = ( new Register() )->verify( new WP_Error(), 'safe@example.com', 'synthetic-user', '', [] ); + self::assertSame( 'bad-signature', $result->get_error_code() ); + } finally { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited + array_pop( $GLOBALS['wp_current_filter'] ); + } + } + + /** + * Guest listing registration shares the filter but has no account form widget. + */ + public function test_guest_listing_registration_is_not_forced_through_account_widget(): void { + $_POST['rtcl-register'] = 'Register'; + $errors = new WP_Error(); + + $result = ( new Register() )->verify( $errors, 'safe@example.com', 'synthetic-user', '', [] ); + + self::assertSame( $errors, $result ); + } + /** * Test that a filled honeypot blocks the contact form. * diff --git a/tests/php/integration/CoBlocks/FormTest.php b/tests/php/integration/CoBlocks/FormTest.php index 114d00705..f01f509dd 100644 --- a/tests/php/integration/CoBlocks/FormTest.php +++ b/tests/php/integration/CoBlocks/FormTest.php @@ -19,6 +19,7 @@ use Mockery; use ReflectionClass; use WP_Block; +use WP_Block_Type_Registry; /** * Test Form class. @@ -59,7 +60,7 @@ public function test_live_coblocks_form(): void { self::assertTrue( is_plugin_active( static::$plugin ) ); self::assertStringStartsWith( wp_normalize_path( WP_PLUGIN_DIR . '/coblocks/' ), $plugin_file ); - self::assertTrue( \WP_Block_Type_Registry::get_instance()->is_registered( 'coblocks/form' ) ); + self::assertTrue( WP_Block_Type_Registry::get_instance()->is_registered( 'coblocks/form' ) ); self::assertStringContainsString( 'class="coblocks-form"', $output ); self::assertStringContainsString( '>Subscribe', $output ); self::assertStringContainsString( ' 'other', ]; - // Unknown field type — covers second continue. - $_POST['field-phone'] = [ - 'label' => 'Phone', - 'value' => '123456', + // Hidden fields are not submitted content. + $_POST['field-hidden'] = [ + 'label' => 'Hidden', + 'value' => 'internal value', ]; $subject = new Form(); @@ -305,6 +306,186 @@ public function test_verify(): void { self::assertFalse( has_filter( 'pre_http_request', [ $subject, 'verify' ] ) ); } + /** + * The disposable-email policy checks the field CoBlocks selected for Reply-To. + * + * @dataProvider dp_test_sender_email_policy + * + * @param string|null $email_field_id Submitted native sender selector. + * @param array $fields Submitted form fields. + * @param string $sender_email Expected native sender address. + * @param bool $blocked Whether the policy should reject the form. + */ + public function test_sender_email_policy( ?string $email_field_id, array $fields, string $sender_email, bool $blocked ): void { + $form_id = '5509c11f003ddee1ee47fbb0a2ffb7b47b57434c'; + $this->prepare_verify_post( 'hcaptcha_coblocks_nonce', 'hcaptcha_coblocks' ); + $this->prepare_widget_id( $form_id ); + $_POST['form-hash'] = $form_id; + + if ( null !== $email_field_id ) { + $_POST['email-field-id'] = $email_field_id; + } + + foreach ( $fields as $key => $field ) { + // The native form nonce is checked when the handler processes this test submission. + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $_POST[ $key ] = $field; + } + + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + + $seen = []; + add_filter( + 'hcap_is_disposable_email', + static function ( bool $disposable, string $email ) use ( &$seen ): bool { + $seen[] = $email; + + return $disposable; + }, + 10, + 2 + ); + + $subject = new Form(); + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $subject->before_form_submit( $_POST, [] ); + + // Native CoBlocks removes this selector before its reCAPTCHA request. + unset( $_POST['email-field-id'] ); + + $response = $subject->verify( + false, + [ 'body' => [ 'response' => 'hcaptcha_token' ] ], + CoBlocks_Form::GCAPTCHA_VERIFY_URL + ); + + self::assertSame( [ $sender_email ], $seen ); + self::assertSame( wp_json_encode( [ 'success' => ! $blocked ] ), $response['body'] ); + } + + /** + * Sender IDs, labels, and extra fields must not change the selected address. + * + * @return array + */ + public function dp_test_sender_email_policy(): array { + return [ + 'forged sensitive label' => [ + 'field-email', + [ + 'field-email' => [ + 'label' => 'password', + 'value' => 'user@disposable.example', + ], + ], + 'user@disposable.example', + true, + ], + 'custom email label' => [ + 'field-email-address', + [ + 'field-email-address' => [ + 'label' => 'Email Address', + 'value' => 'user@disposable.example', + ], + ], + 'user@disposable.example', + true, + ], + 'forged later alias' => [ + 'field-email', + [ + 'field-email' => [ + 'label' => 'Email', + 'value' => 'user@disposable.example', + ], + 'fake-field-email' => [ + 'label' => 'Other', + 'value' => 'safe@example.com', + ], + ], + 'user@disposable.example', + true, + ], + 'non-email suffix' => [ + 'field-contact-address', + [ + 'field-contact-address' => [ + 'label' => 'Contact', + 'value' => 'user@disposable.example', + ], + ], + 'user@disposable.example', + true, + ], + 'native default selector' => [ + null, + [ + 'field-email' => [ + 'label' => 'Email', + 'value' => 'user@disposable.example', + ], + ], + 'user@disposable.example', + true, + ], + 'html suffix in sender' => [ + null, + [ + 'field-email' => [ + 'label' => 'Email', + 'value' => 'user@disposable.example
    ', + ], + ], + 'user@disposable.example', + true, + ], + 'encoded newline sender' => [ + null, + [ + 'field-email' => [ + 'label' => 'Email', + 'value' => 'user@disposable.example%0A', + ], + ], + 'user@disposable.example', + true, + ], + 'allowed html suffix' => [ + null, + [ + 'field-email' => [ + 'label' => 'Email', + 'value' => 'safe@example.com
    ', + ], + ], + 'safe@example.com', + false, + ], + 'allowed native sender' => [ + 'field-contact-address', + [ + 'field-contact-address' => [ + 'label' => 'Contact', + 'value' => 'safe@example.com', + ], + 'field-email' => [ + 'label' => 'Email', + 'value' => 'user@disposable.example', + ], + ], + 'safe@example.com', + false, + ], + ]; + } + /** * Test verify() when not verified. * diff --git a/tests/php/integration/CustomerReviews/EmailPolicyTest.php b/tests/php/integration/CustomerReviews/EmailPolicyTest.php new file mode 100644 index 000000000..f01c9321b --- /dev/null +++ b/tests/php/integration/CustomerReviews/EmailPolicyTest.php @@ -0,0 +1,89 @@ + true ]; + } + ); + $_POST['email'] = $email; + $_POST['user_email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_customer_reviews_nonce', 'hcaptcha_customer_reviews' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'customer_reviews_status', [ 'review', 'q&a' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'customer-reviews-woocommerce/ivole.php' ], + 'form_id' => $form_id, + ] + ); + add_filter( 'wp_doing_ajax', '__return_true' ); + add_filter( + 'wp_die_ajax_handler', + static function () { + return static function (): void {}; + } + ); + + ob_start(); + ( new $integration_class() )->verify(); + $output = (string) ob_get_clean(); + + self::assertSame( + $blocked ? wp_json_encode( + [ + 'code' => 1, + 'description' => hcap_get_error_messages()['disposable-email'], + 'button' => 'Try again', + ] + ) : '', + $output + ); + } + + /** + * Native review and question address controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'blocked review' => [ Review::class, 'review', 'user@disposable.example', true ], + 'allowed review' => [ Review::class, 'review', 'safe@example.com', false ], + 'no review email' => [ Review::class, 'review', '', false ], + 'blocked Q&A' => [ QuestionAnswer::class, 'q&a', 'user@disposable.example', true ], + 'allowed Q&A' => [ QuestionAnswer::class, 'q&a', 'safe@example.com', false ], + 'no Q&A email' => [ QuestionAnswer::class, 'q&a', '', false ], + ]; + } +} diff --git a/tests/php/integration/CustomerReviews/QuestionAnswerTest.php b/tests/php/integration/CustomerReviews/QuestionAnswerTest.php new file mode 100644 index 000000000..fba9e1eea --- /dev/null +++ b/tests/php/integration/CustomerReviews/QuestionAnswerTest.php @@ -0,0 +1,92 @@ +settings()->set( 'customer_reviews_status', [ 'q&a' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + } + + /** + * Keep unrelated product tabs and templates untouched. + */ + public function test_other_tabs_and_templates_are_ignored(): void { + $subject = new QuestionAnswer(); + + self::assertSame( [], $subject->product_tabs( null ) ); + self::assertSame( [ 'description' => [] ], $subject->product_tabs( [ 'description' => [] ] ) ); + ob_start(); + $subject->add_captcha( 'other-template.php', '', '', [] ); + self::assertSame( '', ob_get_clean() ); + } + + /** + * Wrap the native Q&A callback and place one challenge before its submit button. + */ + public function test_native_question_tab_receives_one_challenge(): void { + $subject = new QuestionAnswer(); + $template = '
    '; + $tabs = $subject->product_tabs( + [ + 'cr_qna' => [ + 'callback' => static function ( $attributes ) use ( $template ): void { + self::assertSame( [ 'product_id' => 42 ], $attributes ); + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Test fixture. + echo $template; + }, + ], + ] + ); + + self::assertSame( [ $subject, 'display_qna_tab' ], $tabs['cr_qna']['callback'] ); + $buffer_level = ob_get_level(); + ob_start(); + try { + call_user_func( $tabs['cr_qna']['callback'], [ 'product_id' => 42 ] ); + $output = (string) ob_get_clean(); + } finally { + while ( ob_get_level() > $buffer_level ) { + ob_end_clean(); + } + } + + self::assertStringContainsString( + HCaptcha::widget_id_value( + [ + 'source' => [ 'customer-reviews-woocommerce/ivole.php' ], + 'form_id' => 'q&a', + ] + ), + $output + ); + self::assertStringContainsString( 'name="hcaptcha_customer_reviews_nonce"', $output ); + self::assertLessThan( strpos( $output, 'cr-review-form-submit' ), strpos( $output, 'hcaptcha-widget-id' ) ); + + ob_start(); + ob_start(); + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Test fixture. + echo $template; + $subject->add_captcha( 'single-product/tabs/tabs.php', '', '', [] ); + self::assertSame( $template, ob_get_clean() ); + } +} diff --git a/tests/php/integration/CustomerReviews/ReviewTest.php b/tests/php/integration/CustomerReviews/ReviewTest.php index 56e5d27b4..fb0770aa9 100644 --- a/tests/php/integration/CustomerReviews/ReviewTest.php +++ b/tests/php/integration/CustomerReviews/ReviewTest.php @@ -61,6 +61,16 @@ public function test_add_captcha(): void { self::assertStringContainsString( 'name="hcap_hp_sig"', $output ); } + /** + * Ignore templates other than the Customer Reviews form. + */ + public function test_add_captcha_ignores_other_templates(): void { + ob_start(); + ( new Review() )->add_captcha( 'other-template.php', '', '', [] ); + + self::assertSame( '', ob_get_clean() ); + } + /** * Test filled honeypot blocks review processing. * diff --git a/tests/php/integration/Divi/Contact5EmailPolicyTest.php b/tests/php/integration/Divi/Contact5EmailPolicyTest.php new file mode 100644 index 000000000..478c3c825 --- /dev/null +++ b/tests/php/integration/Divi/Contact5EmailPolicyTest.php @@ -0,0 +1,484 @@ +get_native_theme(); + if ( ! $theme ) { + self::markTestSkipped( 'The installed Divi 5 native parser is required.' ); + } + + require_once $theme . '/includes/builder-5/server/vendor/autoload.php'; + if ( ! class_exists( 'ET_Builder_Module_Order' ) ) { + require_once $theme . '/includes/builder/class-et-builder-module-order.php'; + } + + if ( ! function_exists( 'et_core_is_fb_enabled' ) ) { + $core = get_theme_root() . '/Divi/core/functions.php'; + // The native D5 Conditions proxy uses the shared legacy core function. + require_once is_file( $core ) ? $core : $theme . '/core/functions.php'; + } + add_filter( 'divi_module_library_should_register_all_d5_modules', '__return_true' ); + BlockParserStore::reset(); + BlockParserStore::reset_order_index(); + $_SERVER['REQUEST_METHOD'] = 'POST'; + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + } + + /** + * Restore the native store and request method. + * + * @return void + * @noinspection PhpUndefinedMethodInspection + */ + public function tearDown(): void { + if ( class_exists( BlockParserStore::class, false ) ) { + BlockParserStore::reset(); + BlockParserStore::reset_order_index(); + } + $_SERVER['REQUEST_METHOD'] = 'GET'; + + parent::tearDown(); + } + + /** + * Locate the native Divi 5 installation used only for integration context. + * + * @return string + */ + private function get_native_theme(): string { + foreach ( [ 'Divi', '.Divi_5', 'Divi_5' ] as $slug ) { + $theme = get_theme_root() . '/' . $slug; + if ( is_file( $theme . '/includes/builder-5/server/Packages/ModuleLibrary/ContactForm/ContactFormHandler.php' ) ) { + return $theme; + } + } + + return ''; + } + + /** + * A forged submit counter and honeypot cannot skip a Divi 5 nonce-backed submission. + * + * @return void + */ + public function test_sec050_native_order_index_and_nonce(): void { + $module = $this->parse_native_form( [] ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $order_index = $module->orderIndex; + unset( $_POST[ 'et_pb_contactform_submit_' . $order_index ] ); + $_POST['et_pb_contactform_submit_999'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_999'] = 'bot'; + $_POST[ 'et_pb_contact_et_number_' . $order_index ] = 'bot'; + + // Divi 5 reaches the native submission hook using its nonce, even without the submit marker. + self::assertSame( [], $this->get_native_fields( $module ) ); + + $subject = new Contact(); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $store_instance = $module->storeInstance; + $subject->verify_5( + [], + [ + 'name' => 'divi/contact-form', + 'id' => $module->id, + 'storeInstance' => $store_instance, + ] + ); + + self::assertSame( $order_index, $this->get_protected_property( $subject, 'render_count' ) ); + self::assertSame( 'on', $this->get_protected_property( $subject, 'captcha' ) ); + self::assertSame( 'on', $module->attrs['module']['advanced']['spamProtection']['desktop']['value']['enabled'] ); + + $error = null; + $capture = static function ( array $values, bool $native_error ) use ( &$error ): void { + $error = $native_error; + throw new RuntimeException( 'sec050-native-handler-stopped' ); + }; + add_action( 'et_pb_contact_form_submit', $capture, PHP_INT_MAX, 2 ); + try { + new ContactFormHandler( $module->id, $store_instance ); + self::fail( 'Native validated-field hook was not reached.' ); + } catch ( RuntimeException $exception ) { + self::assertSame( 'sec050-native-handler-stopped', $exception->getMessage() ); + } finally { + remove_action( 'et_pb_contact_form_submit', $capture, PHP_INT_MAX ); + } + + self::assertTrue( $error ); + } + + /** + * A genuine hCaptcha result still permits the nonce-backed Divi 5 submission. + * + * @return void + */ + public function test_sec050_native_nonce_with_valid_hcaptcha(): void { + $this->prepare_verify_post( 'hcaptcha_divi_cf_nonce', 'hcaptcha_divi_cf' ); + $module = $this->parse_native_form( [] ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $order_index = $module->orderIndex; + unset( $_POST[ 'et_pb_contactform_submit_' . $order_index ] ); + $_POST['et_pb_contactform_submit_999'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_999'] = 'bot'; + + $subject = new Contact(); + $id = $this->set_method_accessibility( $subject, 'get_expected_id' )->invoke( $subject ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( $id ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $store_instance = $module->storeInstance; + $subject->verify_5( + [], + [ + 'name' => 'divi/contact-form', + 'id' => $module->id, + 'storeInstance' => $store_instance, + ] + ); + + self::assertSame( 'off', $this->get_protected_property( $subject, 'captcha' ) ); + self::assertSame( 'off', $module->attrs['module']['advanced']['spamProtection']['desktop']['value']['enabled'] ); + self::assertSame( [], $this->get_native_fields( $module ) ); + } + + /** + * Enforce policy through verify_5 and compare every email to native accepted fields. + * + * @param array $definitions Stored native field definitions. + * @param bool $blocked Whether effective native email is disposable. + * + * @dataProvider dp_sec063_native_projection + * @return void + * @noinspection PhpConditionAlreadyCheckedInspection + * @noinspection UnnecessaryAssertionInspection + */ + public function test_sec063_native_projection( array $definitions, bool $blocked ): void { + $this->prepare_verify_post( 'hcaptcha_divi_cf_nonce', 'hcaptcha_divi_cf' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $module = $this->parse_native_form( $definitions ); + self::assertInstanceOf( BlockParserBlock::class, $module ); + self::assertStringEndsWith( 'ContactFormHandler.php', ( new ReflectionClass( ContactFormHandler::class ) )->getFileName() ); + $native = $this->get_native_fields( $module ); + $emails = []; + foreach ( $native as $field ) { + if ( 'email' === $field['type'] && '' !== $field['value'] ) { + $emails[] = $field['value']; + } + } + + $subject = new Contact(); + $id = $this->set_method_accessibility( $subject, 'get_expected_id' )->invoke( $subject ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( $id ); + $api_result = 'verification did not run'; + $capture = static function ( $result ) use ( &$api_result ) { + $api_result = $result; + + return $result; + }; + add_filter( 'hcap_verify_request', $capture, PHP_INT_MAX ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $store_instance = $module->storeInstance; + $subject->verify_5( + [], + [ + 'name' => 'divi/contact-form', + 'id' => $module->id, + 'storeInstance' => $store_instance, + ] + ); + remove_filter( 'hcap_verify_request', $capture, PHP_INT_MAX ); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, [] ); + + self::assertSame( $blocked ? hcap_get_error_messages()['disposable-email'] : null, $api_result ); + self::assertSame( $emails, EntryData::get_emails( $entry ) ); + self::assertSame( $blocked ? 'on' : 'off', $this->get_protected_property( $subject, 'captcha' ) ); + self::assertSame( $blocked ? 'on' : 'off', $module->attrs['module']['advanced']['spamProtection']['desktop']['value']['enabled'] ); + } + + /** + * Parse saved native block attributes and populate their native unique POST names. + * + * @param array $definitions Stored native field definitions. + * + * @return BlockParserBlock + * @noinspection PhpUndefinedMethodInspection + */ + private function parse_native_form( array $definitions ): BlockParserBlock { + $attrs = [ + 'module' => [ + 'advanced' => [ + 'spamProtection' => [ + 'desktop' => [ + 'value' => [ + 'enabled' => 'off', + 'useBasicCaptcha' => 'off', + ], + ], + ], + ], + ], + ]; + $content = ''; + foreach ( $definitions as $field ) { + $content .= ''; + } + $content .= ''; + $parser = new BlockParser(); + $blocks = $parser->parse( $content ); + $module = BlockParserStore::get( $blocks[0]['id'], $parser->get_store_instance() ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $store_instance = $module->storeInstance; + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $order_index = $module->orderIndex; + foreach ( BlockParserStore::get_children( $module->id, $store_instance ) as $index => $field ) { + $name = ContactFieldModule::get_field_unique_id( $field->id, $store_instance ); + $_POST[ $name ] = wp_slash( $definitions[ $index ]['value'] ); + } + $_POST[ 'et_pb_contactform_submit_' . $order_index ] = 'et_contact_proccess'; + $_POST[ '_wpnonce-et-pb-contact-form-submitted-' . $order_index ] = wp_create_nonce( 'et-pb-contact-form-submit-' . $order_index ); + + return $module; + } + + /** + * Construct native stored field attributes. + * + * @param array $field Fixture field. + * + * @return array + */ + private function get_field_attrs( array $field ): array { + $attrs = [ + 'fieldItem' => [ + 'advanced' => [ + 'id' => [ 'desktop' => [ 'value' => $field['id'] ] ], + 'type' => [ 'desktop' => [ 'value' => $field['type'] ] ], + 'required' => [ 'desktop' => [ 'value' => 'off' ] ], + 'checkboxOptions' => [ 'desktop' => [ 'value' => [ [ 'value' => 'visible option' ], [ 'value' => 'other' ] ] ] ], + ], + 'innerContent' => [ 'desktop' => [ 'value' => $field['label'] ?? 'Payment contact' ] ], + ], + ]; + if ( isset( $field['rules'] ) ) { + $attrs['conditionalLogic'] = [ + 'advanced' => [ + 'enable' => [ 'desktop' => [ 'value' => 'on' ] ], + 'relation' => [ 'desktop' => [ 'value' => $field['all'] ?? 'off' ] ], + ], + 'innerContent' => [ 'desktop' => [ 'value' => $field['rules'] ] ], + ]; + } + + return $attrs; + } + + /** + * Capture the actual validated hook map before native mail side effects. + * + * @param BlockParserBlock $module Native parsed module. + * + * @return array + */ + private function get_native_fields( BlockParserBlock $module ): array { + $fields = null; + $capture = static function ( array $values, bool $error ) use ( &$fields ): void { + self::assertFalse( $error, 'Fixture must be accepted by native validation before email policy.' ); + $fields = $values; + throw new RuntimeException( 'sec063-native-fields-captured' ); + }; + add_action( 'et_pb_contact_form_submit', $capture, PHP_INT_MAX, 2 ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- Native parser property. + $store_instance = $module->storeInstance; + try { + new ContactFormHandler( $module->id, $store_instance ); + self::fail( 'Native validated-field hook was not reached.' ); + } catch ( RuntimeException $exception ) { + self::assertSame( 'sec063-native-fields-captured', $exception->getMessage() ); + } finally { + remove_action( 'et_pb_contact_form_submit', $capture, PHP_INT_MAX ); + } + + return $fields; + } + + /** + * Native block and conditional visibility policy cases. + * + * @return array + */ + public function dp_sec063_native_projection(): array { + $permanent = [ + 'id' => 'billing_address', + 'type' => 'email', + 'value' => 'reader@example.com', + 'label' => 'Payment contact', + ]; + $disposable = [ + 'id' => 'CONTACT_ADDRESS', + 'type' => 'email', + 'value' => 'person@sec063-disposable.test', + 'label' => 'Другой адрес', + ]; + $spoof = [ + 'id' => 'email', + 'type' => 'input', + 'value' => 'spoof@sec063-disposable.test', + ]; + $cases = [ + 'custom labels multiple blocked' => [ [ $permanent, $disposable, $spoof ], true ], + 'text email spoof allowed' => [ [ $permanent, $spoof ], false ], + 'duplicate input wins' => [ + [ + $disposable, + [ + 'id' => 'contact_address', + 'type' => 'input', + 'value' => 'person@sec063-disposable.test', + ], + ], + false, + ], + 'duplicate email wins' => [ + [ + $spoof, + [ + 'id' => 'EMAIL', + 'type' => 'email', + 'value' => 'person@sec063-disposable.test', + ], + ], + true, + ], + 'duplicate permanent wins' => [ + [ + $disposable, + [ + 'id' => 'contact_address', + 'type' => 'email', + 'value' => 'reader@example.com', + ], + ], + false, + ], + ]; + $conditions = [ + 'is visible' => [ 'yes', 'is', 'yes', true ], + 'is hidden' => [ 'no', 'is', 'yes', false ], + 'native strict numeric rule hidden' => [ '12', 'is', 12, false ], + 'is not visible' => [ 'no', 'is not', 'yes', true ], + 'is not hidden' => [ 'yes', 'is not', 'yes', false ], + 'greater visible' => [ '12', 'is greater', '10', true ], + 'less hidden' => [ '12', 'is less', '10', false ], + 'less visible' => [ '2', 'is less', '10', true ], + 'contains escaped literal' => [ 'a.b[1]', 'contains', '.b[1]', true ], + 'does not contain visible' => [ 'no', 'does not contain', 'yes', true ], + 'empty visible' => [ '', 'is empty', '', true ], + 'not empty visible' => [ 'yes', 'is not empty', '', true ], + 'unknown selector native default' => [ '', 'unknown selector', '', true ], + ]; + foreach ( $conditions as $name => $case ) { + $field = $disposable; + $field['rules'] = [ + [ + 'field' => 'DISPLAY', + 'condition' => $case[1], + 'value' => $case[2], + ], + ]; + $cases[ $name ] = [ + [ + [ + 'id' => 'display', + 'type' => 'input', + 'value' => $case[0], + ], + $field, + $permanent, + $spoof, + ], + $case[3], + ]; + } + foreach ( [ + 'all hidden' => [ 'on', false ], + 'any visible' => [ 'off', true ], + ] as $name => $case ) { + $field = $disposable; + $field['all'] = $case[0]; + $field['rules'] = [ + [ + 'field' => 'choice', + 'condition' => 'contains', + 'value' => 'visible option', + ], + [ + 'field' => 'missing', + 'condition' => 'is not empty', + 'value' => '', + ], + ]; + $cases[ $name ] = [ + [ + [ + 'id' => 'choice', + 'type' => 'checkbox', + 'value' => 'visible+option,other', + ], + $field, + $permanent, + ], + $case[1], + ]; + } + foreach ( [ + 'empty all visible' => [ 'on', true ], + 'empty any hidden' => [ 'off', false ], + ] as $name => $case ) { + $field = $disposable; + $field['rules'] = []; + $field['all'] = $case[0]; + $cases[ $name ] = [ [ $field, $permanent ], $case[1] ]; + } + + return $cases; + } +} diff --git a/tests/php/integration/Divi/ContactTest.php b/tests/php/integration/Divi/ContactTest.php index bf141157c..1e035787d 100644 --- a/tests/php/integration/Divi/ContactTest.php +++ b/tests/php/integration/Divi/ContactTest.php @@ -5,13 +5,19 @@ * @package HCaptcha\Tests */ +// phpcs:ignore Generic.Commenting.DocComment.MissingShort +/** @noinspection PhpUndefinedClassInspection */ + namespace HCaptcha\Tests\Integration\Divi; +use ET\Builder\FrontEnd\BlockParser\BlockParserStore; +use ET_Builder_Module_Contact_Form; use HCaptcha\Divi\Contact; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; use Mockery; use ReflectionException; +use tad\FunctionMocker\FunctionMocker; use WP_Block; /** @@ -266,6 +272,137 @@ public function test_filter_fields_data_rejects_nested_values(): void { self::assertSame( [ $valid ], $method->invoke( $subject, array_merge( [ $valid ], $malformed ) ) ); } + /** + * Divi 5 skips requests outside its contact form submission route. + */ + public function test_verify_5_ignores_other_requests(): void { + $subject = new Contact(); + $attrs = [ 'unchanged' => true ]; + $_SERVER['REQUEST_METHOD'] = 'GET'; + self::assertSame( $attrs, $subject->verify_5( $attrs, [ 'name' => 'divi/contact-form' ] ) ); + + $_SERVER['REQUEST_METHOD'] = 'POST'; + self::assertSame( $attrs, $subject->verify_5( $attrs, [ 'name' => 'divi/other' ] ) ); + } + + /** + * A missing Divi 5 block leaves module attributes unchanged. + */ + public function test_verify_5_ignores_missing_block(): void { + if ( ! class_exists( BlockParserStore::class ) ) { + require_once dirname( __DIR__ ) . '/Stubs/ET/Builder/FrontEnd/BlockParser/BlockParserStore.php'; + } + $_SERVER['REQUEST_METHOD'] = 'POST'; + $attrs = [ 'unchanged' => true ]; + $subject = new Contact(); + + self::assertSame( + $attrs, + $subject->verify_5( + $attrs, + [ + 'name' => 'divi/contact-form', + 'id' => 'missing', + 'storeInstance' => null, + ] + ) + ); + } + + /** + * Divi form fields contribute only ordinary name and email data to the entry. + */ + public function test_entry_collects_native_contact_fields(): void { + $subject = new Contact(); + $method = $this->set_method_accessibility( $subject, 'get_entry' ); + $_POST['et_pb_contact_name_0'] = 'Jane Doe'; + $_POST['et_pb_contact_email_0'] = 'person@example.com'; + $_POST['et_pb_contact_password_0'] = 'secret'; + $fields = [ + [ + 'field_type' => 'input', + 'field_id' => 'et_pb_contact_name_0', + 'original_id' => 'name', + 'field_label' => 'Name', + ], + [ + 'field_type' => 'email', + 'field_id' => 'et_pb_contact_email_0', + 'original_id' => 'email', + 'field_label' => 'Email', + ], + [ + 'field_type' => 'input', + 'field_id' => 'et_pb_contact_password_0', + 'original_id' => 'password', + 'field_label' => 'Password', + ], + ]; + + $entry = $method->invoke( $subject, $fields ); + self::assertSame( 'Jane Doe', $entry['name'] ); + self::assertSame( 'person@example.com', $entry['email'] ); + self::assertArrayNotHasKey( 'Password', $entry['data'] ); + } + + /** + * Divi 5 field values follow its own text and checkbox normalization. + */ + public function test_block_field_value_normalization(): void { + $subject = new Contact(); + $method = $this->set_method_accessibility( $subject, 'get_block_field_value' ); + $_POST['message'] = "First line\nSecond line"; + $_POST['choices'] = ''; + self::assertSame( "First line\nSecond line", $method->invoke( $subject, 'message', 'text' ) ); + self::assertSame( [], $method->invoke( $subject, 'choices', 'checkbox' ) ); + } + + /** + * Divi 4 removes hCaptcha metadata before comparing submitted form fields. + * + * @noinspection JsonEncodingApiUsageInspection + */ + public function test_verify_4_filters_submitted_field_metadata(): void { + $this->prepare_verify_post( 'hcaptcha_divi_cf_nonce', 'hcaptcha_divi_cf' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'Divi' ], + 'form_id' => 'contact', + ] + ); + $_POST['et_pb_contactform_submit_0'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_0'] = ''; + $_POST['et_pb_contact_name_0'] = 'Jane'; + $fields = [ + [ + 'field_type' => 'input', + 'field_id' => 'et_pb_contact_name_0', + 'original_id' => 'name', + 'field_label' => 'Name', + ], + [ + 'field_type' => 'text', + 'field_id' => 'h-captcha-response', + 'original_id' => 'captcha', + 'field_label' => '', + ], + ]; + $encoded = wp_json_encode( $fields ); + FunctionMocker::replace( + 'filter_input', + static function ( $type, $name ) use ( $encoded ) { + return 'et_pb_contact_email_fields_0' === $name ? $encoded : FunctionMocker::callOriginal(); + } + ); + + $subject = new Contact(); + $subject->verify_4( false, 'et_pb_contact_form', [], [] ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Assert the raw POST value written by the filter under test. + $filtered = json_decode( wp_unslash( $_POST['et_pb_contact_email_fields_0'] ), true ); + self::assertCount( 1, $filtered ); + self::assertSame( 'et_pb_contact_name_0', $filtered[0]['field_id'] ); + } + /** * Test verify_4() with the wrong shortcode tag. * @@ -277,6 +414,65 @@ public function test_verify_4_with_wrong_tag(): void { self::assertSame( 'some html', $subject->verify_4( 'some html', 'wrong-tag', [], [] ) ); } + /** + * A forged earlier counter cannot select a filled honeypot instead of the active form. + * + * @return void + */ + public function test_sec050_forged_earlier_submit_counter(): void { + $_POST['et_pb_contactform_submit_999'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_999'] = 'bot'; + $_POST['et_pb_contactform_submit_0'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_0'] = ''; + + $subject = new Contact(); + $subject->verify_4( false, 'et_pb_contact_form', [], [] ); + + self::assertSame( 'on', $this->get_protected_property( $subject, 'captcha' ) ); + self::assertSame( + [ + 'captcha' => 'on', + 'use_spam_service' => 'on', + ], + $subject->shortcode_attributes( [], [], 'et_pb_contact_form', '', '' ) + ); + } + + /** + * The rendered form counter remains authoritative after an earlier form. + * + * @return void + */ + public function test_sec050_later_rendered_form_counter(): void { + $_POST['et_pb_contactform_submit_0'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_0'] = 'bot'; + $_POST['et_pb_contactform_submit_1'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_1'] = ''; + + $subject = new Contact(); + $this->set_protected_property( $subject, 'render_count', 1 ); + $subject->verify_4( false, 'et_pb_contact_form', [], [] ); + + self::assertSame( 'on', $this->get_protected_property( $subject, 'captcha' ) ); + } + + /** + * A real filled Divi 4 honeypot remains native-rejected without hCaptcha verification. + * + * @return void + */ + public function test_sec050_actual_honeypot_control(): void { + $_POST['et_pb_contactform_submit_999'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_999'] = ''; + $_POST['et_pb_contactform_submit_0'] = 'et_contact_proccess'; + $_POST['et_pb_contact_et_number_0'] = 'bot'; + + $subject = new Contact(); + $subject->verify_4( false, 'et_pb_contact_form', [], [] ); + + self::assertSame( 'off', $this->get_protected_property( $subject, 'captcha' ) ); + } + /** * Test shortcode_attributes(). * @@ -390,4 +586,90 @@ public function test_enqueue_scripts_when_hcaptcha_was_not_shown(): void { self::assertTrue( wp_script_is( 'et-core-api-spam-recaptcha' ) ); self::assertFalse( wp_script_is( 'hcaptcha-divi' ) ); } + /** + * Apply email policy using the server shortcode fields rather than client type claims. + * + * @param bool $blocked Whether the trusted email is disposable. + * @dataProvider dp_sec063_email_policy + */ + public function test_sec063_typed_email_policy( bool $blocked ): void { + $this->prepare_verify_post( 'hcaptcha_divi_cf_nonce', 'hcaptcha_divi_cf' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'Divi' ], + 'form_id' => 'contact', + ] + ); + $_POST['et_pb_contactform_submit_0'] = 'et_contact_proccess'; + $_POST['et_pb_contact_billing_address_0'] = $blocked ? 'person@sec063-disposable.test' : 'person@example.com'; + $_POST['et_pb_contact_contact_address_0'] = 'reader@example.com'; + $_POST['et_pb_contact_email_0'] = 'spoof@example.com'; + $subject = new Contact(); + $subject->verify_4( + false, + 'et_pb_contact_form', + [], + [ 5 => '[et_pb_contact_field field_type="email" field_id="billing_address" field_title="Payment contact" /][et_pb_contact_field field_type="email" field_id="contact_address" field_title="Другой адрес" /][et_pb_contact_field field_type="input" field_id="email" /]' ] + ); + + self::assertSame( $blocked ? 'on' : 'off', $this->get_protected_property( $subject, 'captcha' ) ); + } + /** + * Exercise both policy rejection and permanent address acceptance. + * + * @return array + */ + public function dp_sec063_email_policy(): array { + return [ + 'disposable' => [ true ], + 'permanent' => [ false ], + ]; + } + + /** + * Exclude stale conditional emails only when native stored fields permit hiding. + * + * @param string $conditional Native conditional field status. + * @param bool $blocked Whether the address remains effective. + * + * @dataProvider dp_sec063_hidden_email_policy + * @return void + */ + public function test_sec063_hidden_email_policy( string $conditional, bool $blocked ): void { + $this->prepare_verify_post( 'hcaptcha_divi_cf_nonce', 'hcaptcha_divi_cf' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'Divi' ], + 'form_id' => 'contact', + ] + ); + $_POST['et_pb_contactform_submit_0'] = 'et_contact_proccess'; + $_POST['et_pb_contact_billing_address_0'] = 'person@sec063-disposable.test'; + $_POST['et_pb_contact_contact_address_0'] = 'reader@example.com'; + $_POST['et_pb_contact_email_hidden_fields_0'] = wp_slash( wp_json_encode( [ 'billing_address', 'contact_address' ] ) ); + $content = '[et_pb_contact_field field_type="email" field_id="billing_address" conditional_logic="' . $conditional . '" /][et_pb_contact_field field_type="email" field_id="contact_address" conditional_logic="off" /]'; + $native = new ET_Builder_Module_Contact_Form(); + $map = $native->get_form_map( $content, 0, [ 'billing_address', 'contact_address' ] ); + self::assertCount( $blocked ? 2 : 1, $map['fields'] ); + $subject = new Contact(); + $subject->verify_4( false, 'et_pb_contact_form', [], [ 5 => $content ] ); + + self::assertSame( $blocked ? 'on' : 'off', $this->get_protected_property( $subject, 'captcha' ) ); + } + + /** + * Native conditional and nonconditional hidden-address controls. + * + * @return array + */ + public function dp_sec063_hidden_email_policy(): array { + return [ + 'conditional stale address allowed' => [ 'on', false ], + 'nonconditional address blocked' => [ 'off', true ], + ]; + } } diff --git a/tests/php/integration/DownloadManager/DownloadManagerTest.php b/tests/php/integration/DownloadManager/DownloadManagerTest.php index 33094664b..19d6a401c 100644 --- a/tests/php/integration/DownloadManager/DownloadManagerTest.php +++ b/tests/php/integration/DownloadManager/DownloadManagerTest.php @@ -16,6 +16,7 @@ use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; use ReflectionClass; +use ReflectionException; use WPDM\Package\PackageController; /** @@ -177,17 +178,51 @@ public function test_add_hcaptcha(): void {
    HTML; - $vars = []; + $vars = [ 'ID' => $form_id ]; $subject = new DownloadManager(); self::assertSame( $expected, $subject->add_hcaptcha( $template, $vars ) ); } + /** + * The signed widget follows native template data rather than a link in the HTML. + * + * @return void + */ + public function test_add_hcaptcha_uses_native_package_id(): void { + $subject = new DownloadManager(); + $template = '
      Download'; + $html = $subject->add_hcaptcha( $template, [ 'ID' => '0012' ] ); + $widget = HCaptcha::widget_id_value( + [ + 'source' => [ 'download-manager/download-manager.php' ], + 'form_id' => 12, + ] + ); + + self::assertStringContainsString( 'name="hcaptcha-widget-id"', $html ); + self::assertStringContainsString( 'value="' . $widget . '"', $html ); + } + + /** + * Reject package data without an ID. + * + * @throws ReflectionException Reflection exception. + */ + public function test_get_package_id_without_package_data(): void { + $subject = new DownloadManager(); + $method = $this->set_method_accessibility( $subject, 'get_package_id' ); + + self::assertSame( 0, $method->invoke( $subject, null ) ); + self::assertSame( 0, $method->invoke( $subject, [] ) ); + } + /** * Test hCaptcha in a package rendered by the live Download Manager template. * * @return void + * @noinspection PhpUndefinedFunctionInspection */ public function test_live_package_template(): void { $package_id = PackageController::create( @@ -230,7 +265,7 @@ public function test_verify(): void { $subject = new DownloadManager(); - $subject->verify( null ); + $subject->verify( [ 'ID' => $form_id ] ); } /** @@ -266,7 +301,7 @@ static function ( $name ) use ( &$die_arr ) { } ); - $subject->verify( null ); + $subject->verify( [ 'ID' => $form_id ] ); self::assertSame( $expected, $die_arr ); } @@ -302,11 +337,123 @@ static function ( $name ) use ( &$die_arr ) { } ); - $subject->verify( null ); + $subject->verify( [ 'ID' => 3220 ] ); self::assertSame( $expected, $die_arr ); } + /** + * A different package's signed exemption cannot authorize a native download. + * + * @return void + * @noinspection PhpArrayIsAlwaysEmptyInspection + * @noinspection PhpUnusedLocalVariableInspection + */ + public function test_verify_rejects_other_package_exemption_for_malformed_query(): void { + $source = HCaptcha::get_class_source( DownloadManager::class ); + $exempt = static function ( $protect, $form_source, $form_id ) use ( $source ) { + return $source === $form_source && 121 === $form_id ? false : $protect; + }; + $die_arr = []; + + $this->prepare_verify_post( 'hcaptcha_download_manager_nonce', 'hcaptcha_download_manager', null ); + $this->prepare_widget_id( 121 ); + + add_filter( 'hcap_protect_form', $exempt, 10, 3 ); + add_filter( + 'wp_die_handler', + static function () use ( &$die_arr ) { + return static function ( $message, $title, $args ) use ( &$die_arr ) { + $die_arr = [ $message, $title, $args ]; + }; + } + ); + + try { + $subject = new DownloadManager(); + + foreach ( [ '12
      1', '12%201' ] as $query_id ) { + $_GET['wpdmdl'] = $query_id; + $die_arr = []; + + $subject->verify( [ 'ID' => 12 ] ); + + self::assertSame( 'Bad hCaptcha signature!', $die_arr[0] ?? null, $query_id ); + } + } finally { + remove_filter( 'hcap_protect_form', $exempt ); + } + } + + /** + * The native package's own exemption remains valid without remote proof. + * + * @return void + */ + public function test_verify_accepts_native_package_exemption(): void { + $source = HCaptcha::get_class_source( DownloadManager::class ); + $exempt = static function ( $protect, $form_source, $form_id ) use ( $source ) { + return $source === $form_source && 121 === $form_id ? false : $protect; + }; + $die_arr = []; + + $this->prepare_verify_post( 'hcaptcha_download_manager_nonce', 'hcaptcha_download_manager', null ); + $this->prepare_widget_id( 121 ); + + $_GET['wpdmdl'] = '12
      1'; + + add_filter( 'hcap_protect_form', $exempt, 10, 3 ); + add_filter( + 'wp_die_handler', + static function () use ( &$die_arr ) { + return static function ( $message, $title, $args ) use ( &$die_arr ) { + $die_arr = [ $message, $title, $args ]; + }; + } + ); + + try { + $subject = new DownloadManager(); + $subject->verify( [ 'ID' => '00121' ] ); + + self::assertSame( [], $die_arr ); + } finally { + remove_filter( 'hcap_protect_form', $exempt ); + } + } + + /** + * Invalid native package data must fail closed even with a valid exemption. + * + * @return void + */ + public function test_verify_rejects_invalid_native_package_id(): void { + $die_arr = []; + + $this->prepare_verify_post( 'hcaptcha_download_manager_nonce', 'hcaptcha_download_manager', null ); + $this->prepare_widget_id( 121 ); + $_GET['wpdmdl'] = '12
      1'; + + add_filter( 'hcap_protect_form', '__return_false' ); + add_filter( + 'wp_die_handler', + static function () use ( &$die_arr ) { + return static function ( $message, $title, $args ) use ( &$die_arr ) { + $die_arr = [ $message, $title, $args ]; + }; + } + ); + + try { + $subject = new DownloadManager(); + $subject->verify( [ 'ID' => '12
      1' ] ); + + self::assertSame( 'Bad hCaptcha signature!', $die_arr[0] ?? null ); + } finally { + remove_filter( 'hcap_protect_form', '__return_false' ); + } + } + /** * Prepare hCaptcha widget id. * diff --git a/tests/php/integration/EasyDigitalDownloads/BlockRenderingTest.php b/tests/php/integration/EasyDigitalDownloads/BlockRenderingTest.php new file mode 100644 index 000000000..3de0982ef --- /dev/null +++ b/tests/php/integration/EasyDigitalDownloads/BlockRenderingTest.php @@ -0,0 +1,58 @@ + 'edd/login' ]; + $object = new WP_Block( $block ); + $html = '
      '; + + self::assertSame( $html, $subject->add_captcha( $html, $block, $object ) ); + do_action( 'edd_lost_password_fields_after' ); + self::assertSame( $html, $subject->add_captcha( $html, [ 'blockName' => 'core/group' ], $object ) ); + + $output = $subject->add_captcha( $html, $block, $object ); + + self::assertStringContainsString( 'name="hcaptcha_easy_digital_downloads_lostpassword_nonce"', $output ); + self::assertLessThan( strpos( $output, 'edd_lost_password_submit' ), strpos( $output, 'hcaptcha-widget-id' ) ); + } + + /** + * A registration challenge appears before the EDD submit control. + */ + public function test_registration_block(): void { + $subject = new Register(); + $block = [ 'blockName' => 'edd/register' ]; + $object = new WP_Block( $block ); + $html = '
      '; + + self::assertSame( $html, $subject->add_captcha( $html, $block, $object ) ); + do_action( 'edd_register_form_fields_after' ); + self::assertSame( $html, $subject->add_captcha( $html, [ 'blockName' => 'core/group' ], $object ) ); + + $output = $subject->add_captcha( $html, $block, $object ); + + self::assertStringContainsString( 'name="hcaptcha_easy_digital_downloads_register_nonce"', $output ); + self::assertLessThan( strpos( $output, 'reset-pass-submit' ), strpos( $output, 'hcaptcha-widget-id' ) ); + } +} diff --git a/tests/php/integration/EasyDigitalDownloads/CheckoutNoticeTest.php b/tests/php/integration/EasyDigitalDownloads/CheckoutNoticeTest.php new file mode 100644 index 000000000..6596d552e --- /dev/null +++ b/tests/php/integration/EasyDigitalDownloads/CheckoutNoticeTest.php @@ -0,0 +1,111 @@ +request = [ $_GET, $_POST, $_REQUEST ]; + $_GET = []; + $_POST = []; + $_REQUEST = []; + Messages::clear(); + } + + /** + * Restore native messages and request fields. + */ + public function tearDown(): void { + Messages::clear(); + [ $_GET, $_POST, $_REQUEST ] = $this->request; + + parent::tearDown(); + } + + /** + * A CAPTCHA-only rejection must be visible in EDD's checkout form. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function test_captcha_rejection_is_visible(): void { + $_POST['action'] = 'edd_process_checkout'; + $_POST['edd_email'] = 'buyer@example.com'; + + $errors = ( new Checkout() )->verify( [] ); + + self::assertSame( [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], $errors ); + self::assertSame( $errors, Messages::get_by_type( 'error' ) ); + + ob_start(); + edd_print_errors(); + $html = (string) ob_get_clean(); + + self::assertStringContainsString( 'edd-alert-error', $html ); + self::assertStringContainsString( 'edd_error_bad-signature', $html ); + self::assertSame( [], Messages::get_by_type( 'error' ) ); + } + + /** + * Other EDD requests must not create a checkout CAPTCHA notice. + */ + public function test_unrelated_request_has_no_checkout_notice(): void { + $_POST['action'] = 'edd_apply_discount'; + + self::assertSame( [], ( new Checkout() )->verify( [] ) ); + self::assertSame( [], Messages::get_by_type( 'error' ) ); + } +} diff --git a/tests/php/integration/EasyDigitalDownloads/CheckoutTest.php b/tests/php/integration/EasyDigitalDownloads/CheckoutTest.php index f8943bdd4..a309f4f8a 100644 --- a/tests/php/integration/EasyDigitalDownloads/CheckoutTest.php +++ b/tests/php/integration/EasyDigitalDownloads/CheckoutTest.php @@ -29,7 +29,7 @@ public function setUp(): void { hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); - hcaptcha()->settings()->set( 'easy_digital_downloads_status', 'checkout' ); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'checkout' ] ); $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } @@ -79,4 +79,212 @@ public function test_filled_honeypot_is_rejected(): void { ( new Checkout() )->verify( [] ) ); } + + /** + * Native non-AJAX checkout has edd_action=purchase and no AJAX action field. + * + * @return void + */ + public function test_native_purchase_requires_captcha(): void { + $_POST['edd_action'] = 'purchase'; + $_POST['edd_email'] = 'buyer@example.com'; + + $subject = new Checkout(); + self::assertSame( [], $subject->verify( [] ) ); + + $result = null; + add_action( + 'edd_purchase', + static function () use ( $subject, &$result ): void { + $result = $subject->verify( [] ); + } + ); + do_action( 'edd_purchase' ); + + self::assertSame( [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], $result ); + } + + /** + * A signed native purchase still passes its checkout verification. + * + * @return void + */ + public function test_native_purchase_with_valid_captcha(): void { + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_register_nonce', 'hcaptcha_easy_digital_downloads_register' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'checkout', + ] + ); + $_POST['edd_action'] = 'purchase'; + $_POST['edd_email'] = 'buyer@example.com'; + + $subject = new Checkout(); + $result = null; + add_action( + 'edd_purchase', + static function () use ( $subject, &$result ): void { + $result = $subject->verify( [] ); + } + ); + do_action( 'edd_purchase' ); + + self::assertSame( [], $result ); + } + + /** + * WordPress can select EDD's AJAX handler from a query action without a POST action. + * + * @return void + */ + public function test_ajax_query_action_requires_captcha(): void { + $_GET['action'] = 'edd_process_checkout'; + $_POST['edd_email'] = 'buyer@example.com'; + + $subject = new Checkout(); + self::assertSame( [], $subject->verify( [] ) ); + + $result = null; + add_action( + 'wp_ajax_nopriv_edd_process_checkout', + static function () use ( $subject, &$result ): void { + $result = $subject->verify( [] ); + } + ); + do_action( 'wp_ajax_nopriv_edd_process_checkout' ); + + self::assertSame( [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], $result ); + } + + /** + * A signed checkout request also passes the native query-action AJAX route. + * + * @return void + */ + public function test_ajax_query_action_with_valid_captcha(): void { + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_register_nonce', 'hcaptcha_easy_digital_downloads_register' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'checkout', + ] + ); + $_GET['action'] = 'edd_process_checkout'; + $_POST['edd_email'] = 'buyer@example.com'; + + $subject = new Checkout(); + $result = null; + add_action( + 'wp_ajax_edd_process_checkout', + static function () use ( $subject, &$result ): void { + $result = $subject->verify( [] ); + } + ); + do_action( 'wp_ajax_edd_process_checkout' ); + + self::assertSame( [], $result ); + } + + /** + * Check the authoritative native email through the production API. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native address. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $_POST['action'] = 'edd_process_checkout'; + $_POST['edd_email'] = $email; + $_POST['email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_register_nonce', 'hcaptcha_easy_digital_downloads_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'checkout' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'checkout', + ] + ); + + $result = ( new Checkout() )->verify( [] ); + + self::assertSame( $blocked ? [ 'disposable-email' => hcap_get_error_messages()['disposable-email'] ] : [], $result ); + } + + /** + * Native email policy controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable email' => [ 'user@disposable.example', true ], + 'permanent email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } + + /** + * An omitted checkout email keeps the native current-user fallback. + * + * @dataProvider dp_test_current_checkout_email + * + * @param string $stored Current customer's address. + * @param string|null $posted Native override or omitted field. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_current_checkout_email( string $stored, ?string $posted, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + wp_set_current_user( $this->factory()->user->create( [ 'user_email' => $stored ] ) ); + $_POST['action'] = 'edd_process_checkout'; + $_POST['email'] = 'safe@example.com'; + if ( null !== $posted ) { + $_POST['edd_email'] = $posted; + } + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_register_nonce', 'hcaptcha_easy_digital_downloads_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'checkout' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'checkout', + ] + ); + + $result = ( new Checkout() )->verify( [] ); + + self::assertSame( $blocked ? [ 'disposable-email' => hcap_get_error_messages()['disposable-email'] ] : [], $result ); + wp_set_current_user( 0 ); + } + + /** + * Current customer address controls. + * + * @return array + */ + public function dp_test_current_checkout_email(): array { + return [ + 'blocked fallback' => [ 'user@disposable.example', null, true ], + 'allowed fallback' => [ 'safe@example.com', null, false ], + 'allowed override' => [ 'user@disposable.example', 'safe@example.com', false ], + 'blocked override' => [ 'safe@example.com', 'user@disposable.example', true ], + ]; + } } diff --git a/tests/php/integration/EasyDigitalDownloads/LostPasswordEntryTest.php b/tests/php/integration/EasyDigitalDownloads/LostPasswordEntryTest.php new file mode 100644 index 000000000..90f7e7572 --- /dev/null +++ b/tests/php/integration/EasyDigitalDownloads/LostPasswordEntryTest.php @@ -0,0 +1,67 @@ + 'unrelated' ]; + $actual = []; + + FunctionMocker::replace( + '\\HCaptcha\\Helpers\\API::verify_post', + static function ( string $name, string $action, array $expected_id, array $entry ) use ( &$actual ): ?string { + $actual = $entry; + + return null; + } + ); + + try { + ( new LostPassword() )->verify( + [ + 'edd_lost-password_nonce' => wp_create_nonce( 'edd-lost-password-nonce' ), + 'user_login' => 'alice@example.com', + 'profile_note' => 'Please help', + 'payment_card' => 'private-payment-data', + ] + ); + } finally { + if ( null === $method ) { + unset( $_SERVER['REQUEST_METHOD'] ); + } else { + $_SERVER['REQUEST_METHOD'] = $method; + } + } + + self::assertSame( + [ + 'data' => [ + 'user_login' => 'alice@example.com', + 'profile_note' => 'Please help', + ], + 'email_addresses' => [], + ], + $actual + ); + } +} diff --git a/tests/php/integration/EasyDigitalDownloads/LostPasswordTest.php b/tests/php/integration/EasyDigitalDownloads/LostPasswordTest.php new file mode 100644 index 000000000..06dc9be5a --- /dev/null +++ b/tests/php/integration/EasyDigitalDownloads/LostPasswordTest.php @@ -0,0 +1,345 @@ +request = [ $_GET, $_POST, $_REQUEST ]; + // phpcs:enable WordPress.Security.NonceVerification + $this->server = $_SERVER; + $_GET = []; + $_POST = []; + $_REQUEST = []; + $_SERVER['REQUEST_METHOD'] = 'POST'; + wp_set_current_user( 0 ); + Messages::clear(); + if ( class_exists( Router::class ) ) { + Router::reset(); + } + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'lost_pass' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + $this->subject = hcaptcha()->get( LostPassword::class ) ?: new LostPassword(); + + self::assertSame( 9, has_action( 'edd_user_lost_password', [ $this->subject, 'verify' ] ) ); + self::assertSame( 10, has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + } + + /** + * Restore request state and the native EDD handler after each case. + */ + public function tearDown(): void { + if ( $this->request ) { + Messages::clear(); + add_action( 'edd_user_lost_password', 'edd_handle_lost_password_request', 10, 1 ); + [ $_GET, $_POST, $_REQUEST ] = $this->request; + $_SERVER = $this->server; + } + + parent::tearDown(); + } + + /** + * Native POST and GET transports, including router normalization, require CAPTCHA. + * + * @dataProvider dp_missing_proof_routes + * + * @param string $transport Native router transport. + * @param string $action Raw router action. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function test_missing_proof_stops_native_recovery( string $transport, string $action ): void { + $native = $this->native_payload( $action ); + $this->set_route( $transport, $native ); + + self::assertSame( 0, $this->dispatch_before_reset_key( $native, $transport ) ); + self::assertFalse( has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + self::assertSame( + [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], + Messages::get_by_type( 'error' ) + ); + self::assertSame( Messages::get_by_type( 'error' ), edd_get_errors() ); + } + + /** + * Every native action spelling and request carrier must be covered. + * + * @return array + */ + public function dp_missing_proof_routes(): array { + return [ + 'POST action' => [ 'POST', 'user_lost_password' ], + 'GET action on POST' => [ 'GET', 'user_lost_password' ], + 'normalized POST action' => [ 'POST', 'USER_LOST_PASSWORD' ], + ]; + } + + /** + * Both native router passes stay blocked when one POST carries both actions. + */ + public function test_dual_carrier_missing_proof_blocks_both_dispatches(): void { + $native = $this->native_payload( 'user_lost_password' ); + // phpcs:disable WordPress.Security.NonceVerification -- Set both synthetic native request carriers. + $_GET = $native; + $_POST = $native; + $_REQUEST = array_merge( $_GET, $_POST ); + // phpcs:enable WordPress.Security.NonceVerification + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Dispatch the synthetic native GET carrier. + self::assertSame( 0, $this->dispatch_before_reset_key( $_GET, 'GET' ) ); + self::assertFalse( has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Dispatch the synthetic native POST carrier. + self::assertSame( 0, $this->dispatch_before_reset_key( $_POST ) ); + self::assertFalse( has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + self::assertSame( + [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], + Messages::get_by_type( 'error' ) + ); + } + + /** + * Signed proof allows the installed native recovery callback to begin. + * + * @dataProvider dp_valid_proof_routes + * + * @param string $transport Native router transport. + */ + public function test_valid_proof_reaches_native_recovery( string $transport ): void { + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_lostpassword_nonce', 'hcaptcha_easy_digital_downloads_lostpassword' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'lost_password', + ] + ); + $native = $this->native_payload( 'user_lost_password' ); + $this->set_route( $transport, $native ); + + self::assertSame( 1, $this->dispatch_before_reset_key( $native, $transport ) ); + self::assertSame( 10, has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + self::assertSame( [], Messages::get_by_type( 'error' ) ); + } + + /** + * A valid proof can accompany either native action carrier. + * + * @return array + */ + public function dp_valid_proof_routes(): array { + return [ + 'POST action' => [ 'POST' ], + 'GET action on POST' => [ 'GET' ], + ]; + } + + /** + * A signed proof from another EDD form must not unlock recovery. + */ + public function test_foreign_widget_identity_stops_recovery(): void { + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_lostpassword_nonce', 'hcaptcha_easy_digital_downloads_lostpassword' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'login', + ] + ); + $native = $this->native_payload( 'user_lost_password' ); + $this->set_route( 'POST', $native ); + + self::assertSame( 0, $this->dispatch_before_reset_key( $native ) ); + self::assertSame( [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], Messages::get_by_type( 'error' ) ); + } + + /** + * An invalid native EDD nonce retains EDD's original error path. + */ + public function test_invalid_native_nonce_preserves_edd_error(): void { + $native = $this->native_payload( 'user_lost_password' ); + $native['edd_lost-password_nonce'] = 'invalid'; + $this->set_route( 'POST', $native ); + + self::assertSame( 0, $this->dispatch_before_reset_key( $native ) ); + self::assertArrayHasKey( 'edd_lost_password', Messages::get_by_type( 'error' ) ); + self::assertArrayNotHasKey( 'bad-signature', Messages::get_by_type( 'error' ) ); + self::assertSame( 10, has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + } + + /** + * A different EDD action does not trigger the recovery CAPTCHA. + */ + public function test_unrelated_native_action_is_unaffected(): void { + $native = $this->native_payload( 'unrelated_action' ); + $this->set_route( 'POST', $native ); + + self::assertSame( 0, $this->dispatch_before_reset_key( $native ) ); + self::assertSame( [], Messages::get_by_type( 'error' ) ); + self::assertSame( 10, has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + } + + /** + * The hCaptcha callback preserves the native non-POST method gate. + */ + public function test_non_post_method_does_not_validate_captcha(): void { + $_SERVER['REQUEST_METHOD'] = 'GET'; + $this->subject->verify( $this->native_payload( 'user_lost_password' ) ); + + self::assertSame( [], Messages::get_by_type( 'error' ) ); + self::assertSame( 10, has_action( 'edd_user_lost_password', 'edd_handle_lost_password_request' ) ); + } + + /** + * Construct a native EDD request without any real account name. + * + * @param string $action Raw native router action. + * + * @return array + */ + private function native_payload( string $action ): array { + return [ + 'edd_action' => $action, + 'edd_lost-password_nonce' => wp_create_nonce( 'edd-lost-password-nonce' ), + 'user_login' => '', + ]; + } + + /** + * Set the native carrier while retaining the prepared POST proof, if any. + * + * @param string $transport Native router transport. + * @param array $native Native request fields. + * + * @return void + */ + private function set_route( string $transport, array $native ): void { + // phpcs:disable WordPress.Security.NonceVerification -- Set synthetic test request carriers. + if ( 'GET' === $transport ) { + $_GET = $native; + $_POST['user_login'] = ''; + } else { + $_POST = array_merge( $_POST, $native ); + } + $_REQUEST = array_merge( $_GET, $_POST ); + // phpcs:enable WordPress.Security.NonceVerification + } + + /** + * Dispatch through EDD and stop at WordPress's pre-key recovery hook. + * + * @param array $native Native dispatcher request. + * @param string $transport Native request transport. + * + * @return int Number of attempts to enter WordPress recovery. + * @throws RuntimeException When an unrelated native callback fails. + * @noinspection PhpUndefinedFunctionInspection + */ + private function dispatch_before_reset_key( array $native, string $transport = 'POST' ): int { + $attempts = 0; + $stop = static function () use ( &$attempts ): void { + self::assertTrue( doing_action( 'edd_user_lost_password' ) ); + ++$attempts; + throw new RuntimeException( esc_html( self::BOUNDARY ) ); + }; + add_action( 'lostpassword_post', $stop, PHP_INT_MIN ); + + try { + if ( class_exists( Router::class ) ) { + Router::frontend( $native ); + } elseif ( 'GET' === $transport ) { + edd_get_actions(); + } else { + edd_post_actions(); + } + } catch ( RuntimeException $error ) { + if ( self::BOUNDARY !== $error->getMessage() ) { + throw $error; + } + } finally { + remove_action( 'lostpassword_post', $stop, PHP_INT_MIN ); + } + + return $attempts; + } +} diff --git a/tests/php/integration/EasyDigitalDownloads/RegisterDispatchTest.php b/tests/php/integration/EasyDigitalDownloads/RegisterDispatchTest.php new file mode 100644 index 000000000..02a18ff39 --- /dev/null +++ b/tests/php/integration/EasyDigitalDownloads/RegisterDispatchTest.php @@ -0,0 +1,529 @@ +request = [ $_GET, $_REQUEST ]; + $this->server = $_SERVER; + $_GET = []; + $_POST = []; + $_REQUEST = []; + wp_set_current_user( 0 ); + Messages::clear(); + Router::reset(); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + } + + /** + * Restore native messages, rate state, and request values. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function tearDown(): void { + if ( class_exists( Router::class ) && class_exists( RegistrationGuard::class ) && class_exists( Messages::class ) ) { + RegistrationGuard::limiter()->reset( edd_get_ip() ); + Messages::clear(); + [ $_GET, $_REQUEST ] = $this->request; + $_SERVER = $this->server; + } + + parent::tearDown(); + } + + /** + * Every native spelling and transport must enforce the same registration proof. + * + * @dataProvider dp_test_native_registration_routes + * + * @param string $transport Native request transport. + * @param string $action Raw action before native sanitize_key normalization. + * @param bool $proof Valid CAPTCHA proof present. + */ + public function test_native_registration_routes( string $transport, string $action, bool $proof ): void { + $payload = $this->prepare_payload( $action, $proof ); + new Register(); + + if ( 'GET' === $transport ) { + $_GET = $payload; + $_POST = []; + } else { + $_POST = $payload; + } + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Snapshot request state around the native dispatch. + $before = $_POST; + $result = $this->dispatch( $payload ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verify the adapter restores the untouched outer request. + self::assertSame( $before, $_POST ); + self::assertSame( $proof ? 1 : 0, $result['sink_attempts'] ); + self::assertSame( $proof ? [] : [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], $result['filtered_errors'] ); + self::assertFalse( username_exists( 'sec002-registration' ) ); + } + + /** + * Native Router accepts both request arrays and normalized action spellings. + * + * @return array + */ + public function dp_test_native_registration_routes(): array { + return [ + 'canonical POST missing proof' => [ 'POST', 'user_register', false ], + 'uppercase POST missing proof' => [ 'POST', 'USER_REGISTER', false ], + 'punctuation POST missing proof' => [ 'POST', 'user!_register', false ], + 'GET missing proof' => [ 'GET', 'user_register', false ], + 'canonical POST valid proof' => [ 'POST', 'user_register', true ], + 'GET valid proof' => [ 'GET', 'user_register', true ], + ]; + } + + /** + * Proof and email must come from the current native payload, without merging transports. + * + * @dataProvider dp_test_conflicting_payloads + * + * @param string $transport Native request transport. + * @param string $variant Conflicting proof or address scenario. + * @param string $expected_error Expected hCaptcha error code, or empty on success. + */ + public function test_conflicting_payloads( string $transport, string $variant, string $expected_error ): void { + $payload = $this->prepare_payload( 'POST' === $transport ? 'USER_REGISTER' : 'user_register', 'missing proof' !== $variant ); + $decoy = $this->prepare_payload( 'user_register' ); + $this->enable_email_policy(); + + if ( 'foreign widget' === $variant ) { + $payload[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'checkout', + ] + ); + } elseif ( 'native disposable' === $variant ) { + $payload['edd_user_email'] = 'native@disposable.example'; + } elseif ( 'decoy disposable' === $variant ) { + $decoy['edd_user_email'] = 'decoy@disposable.example'; + $decoy[ HCaptcha::HCAPTCHA_WIDGET_ID ] .= 'tampered'; + } + + $_POST = 'GET' === $transport ? $decoy : $payload; + $_GET = 'GET' === $transport ? $payload : $decoy; + new Register(); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Preserve the complete outer transport snapshot. + $before = $_POST; + $result = $this->dispatch( $payload ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verify full restoration, including decoy proof and fields. + self::assertSame( $before, $_POST ); + self::assertSame( '' === $expected_error ? 1 : 0, $result['sink_attempts'] ); + self::assertSame( '' === $expected_error ? [] : [ $expected_error => hcap_get_error_messages()[ $expected_error ] ], $result['filtered_errors'] ); + } + + /** + * Conflicting transport controls. + * + * @return array + */ + public function dp_test_conflicting_payloads(): array { + return [ + 'GET cannot borrow POST proof' => [ 'GET', 'missing proof', 'bad-signature' ], + 'GET rejects own foreign widget' => [ 'GET', 'foreign widget', 'bad-signature' ], + 'GET checks own disposable email' => [ 'GET', 'native disposable', 'disposable-email' ], + 'GET ignores bad POST decoys' => [ 'GET', 'decoy disposable', '' ], + 'POST cannot borrow GET proof' => [ 'POST', 'missing proof', 'bad-signature' ], + 'POST checks own disposable email' => [ 'POST', 'native disposable', 'disposable-email' ], + ]; + } + + /** + * The integration must retain native origin and inexpensive form checks. + * + * @dataProvider dp_test_native_guards + * + * @param string $field Native field modified. + * @param string $value Invalid native value. + * @param string $expected_error Expected native code, or empty for a non-submission. + */ + public function test_native_guards( string $field, string $value, string $expected_error ): void { + $payload = $this->prepare_payload( 'user_register' ); + $payload[ $field ] = $value; + $_POST = $payload; + new Register(); + $result = $this->dispatch( $payload ); + + self::assertSame( 0, $result['sink_attempts'] ); + + if ( '' === $expected_error ) { + self::assertSame( [], $result['stored_errors'] ); + } else { + self::assertArrayHasKey( $expected_error, $result['stored_errors'] ); + } + + if ( in_array( $field, [ 'edd_register_submit', 'edd_register_token' ], true ) ) { + self::assertSame( 0, $result['remote_calls'] ); + } + } + + /** + * Native checks stay authoritative before account insertion. + * + * @return array + */ + public function dp_test_native_guards(): array { + return [ + 'not a submission' => [ 'edd_register_submit', '', '' ], + 'invalid HMAC token' => [ 'edd_register_token', 'invalid-token', 'registration_token' ], + 'filled honeypot' => [ 'edd_honeypot', 'bot', 'invalid_form_data' ], + 'password mismatch' => [ 'edd_user_pass2', 'different-password', 'password_mismatch' ], + 'invalid email' => [ 'edd_user_email', 'invalid-email', 'email_invalid' ], + ]; + } + + /** + * Valid CAPTCHA must not bypass native registration volume limits. + */ + public function test_native_rate_limit_remains_authoritative(): void { + $payload = $this->prepare_payload( 'user_register' ); + + for ( $i = 0; $i < RegistrationGuard::MAX_ATTEMPTS; ++$i ) { + self::assertTrue( RegistrationGuard::check_rate_limit() ); + } + + $_POST = $payload; + new Register(); + $result = $this->dispatch( $payload ); + + self::assertSame( 0, $result['sink_attempts'] ); + self::assertArrayHasKey( 'rate_limit_exceeded', $result['stored_errors'] ); + self::assertSame( 1, $result['remote_calls'] ); + } + + /** + * Only the current native registration hook owns the error collection. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function test_unrelated_and_completed_actions_do_not_claim_errors(): void { + $payload = $this->prepare_payload( 'user_register', false ); + $_POST = $payload; + new Register(); + $native = [ 'native_error' => 'Native error remains unchanged.' ]; + edd_set_error( 'native_error', $native['native_error'] ); + $observed = null; + add_action( + 'edd_sec002_unrelated', + static function () use ( &$observed ): void { + $observed = edd_get_errors(); + } + ); + Router::frontend( [ 'edd_action' => 'sec002_unrelated' ] ); + + self::assertSame( $native, $observed ); + // No submit means the native registration handler returns without error collection. + unset( $payload['edd_register_submit'] ); + Router::frontend( $payload ); + self::assertSame( $native, edd_get_errors() ); + } + + /** + * A nested native dispatch must restore its outer payload and single-use proof. + * + * @noinspection PhpUndefinedFunctionInspection + */ + public function test_nested_different_proofs_restore_outer_registration(): void { + $outer = $this->prepare_payload( 'user_register' ); + $inner = $this->prepare_payload( 'user_register' ); + $inner['edd_user_login'] = 'sec002-inner-registration'; + $inner['edd_user_email'] = 'sec002-inner@example.com'; + $outer['h-captcha-response'] = 'outer-response'; + $inner['h-captcha-response'] = 'inner-response'; + $this->prepare_verify_request( 'outer-response' ); + add_filter( + 'pre_http_request', + static function ( $preempt, array $args, string $url ) { + if ( 'https://api.hcaptcha.com/siteverify' !== $url ) { + return $preempt; + } + + self::assertContains( $args['body']['response'], [ 'outer-response', 'inner-response' ] ); + + return [ 'body' => wp_json_encode( [ 'success' => true ] ) ]; + }, + 11, + 3 + ); + $settings = (array) get_option( 'hcaptcha_settings', [] ); + $settings['set_min_submit_time'] = 'on'; + $settings['min_submit_time'] = '0'; + $settings['easy_digital_downloads_status'] = [ 'register' ]; + update_option( 'hcaptcha_settings', $settings ); + hcaptcha()->init_hooks(); + self::assertSame( 0, (int) hcaptcha()->settings()->get( 'min_submit_time' ) ); + // The standard API helper replaces issued tokens; this case needs their real signatures. + remove_all_filters( 'hcap_fst_token' ); + $_SERVER['REMOTE_ADDR'] = '203.0.113.22'; + FormSubmitTimeStore::delete_all(); + + try { + $outer['hcap_fst_token'] = $this->issue_timing_token(); + $inner['hcap_fst_token'] = $this->issue_timing_token(); + remove_filter( 'hcap_verify_fst_token', '__return_true' ); + $_POST = $outer; + new Register(); + $nested = false; + add_action( + 'edd_process_register_form', + static function () use ( $inner, &$nested ): void { + if ( $nested ) { + return; + } + + $nested = true; + // Extensions can collect errors before triggering another native registration. + self::assertSame( [], (array) edd_get_errors() ); + Router::frontend( $inner ); + } + ); + $result = $this->dispatch( $outer ); + + self::assertSame( [], $result['filtered_errors'] ); + self::assertSame( [], $result['stored_errors'] ); + self::assertSame( 2, $result['sink_attempts'] ); + self::assertSame( 2, $result['remote_calls'] ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verify both scoped verifications restore the outer request. + self::assertSame( $outer, $_POST ); + } finally { + FormSubmitTimeStore::delete_all(); + } + } + + /** + * Enable deterministic native disposable-email controls. + */ + private function enable_email_policy(): void { + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + } + + /** + * Call the real timing-token issuance endpoint without terminating the runner. + * + * @return string + * @noinspection JsonEncodingApiUsageInspection + */ + private function issue_timing_token(): string { + $fst = hcaptcha()->get( FormSubmitTime::class ); + self::assertInstanceOf( FormSubmitTime::class, $fst ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $post = $_POST; + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $request = $_REQUEST; + $_POST = [ + 'nonce' => wp_create_nonce( 'hcaptcha-fst-issue-token' ), + 'postId' => '0', + 'context' => $this->set_method_accessibility( $fst, 'context_from_post_id' )->invoke( $fst, '0' ), + ]; + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Native check_ajax_referer reads REQUEST. + $_REQUEST = $_POST; + $die_handler = static function (): callable { + return static function (): void {}; + }; + add_filter( 'wp_doing_ajax', '__return_true' ); + add_filter( 'wp_die_ajax_handler', $die_handler ); + + try { + ob_start(); + $fst->issue_token(); + $response = json_decode( (string) ob_get_clean(), true ); + } finally { + remove_filter( 'wp_doing_ajax', '__return_true' ); + remove_filter( 'wp_die_ajax_handler', $die_handler ); + $_POST = $post; + $_REQUEST = $request; + } + + self::assertTrue( $response['success'] ); + + return $response['data']['token']; + } + + /** + * Issue the native HMAC token and a complete form payload. + * + * @param string $action Raw EDD action. + * @param bool $proof Whether to include valid CAPTCHA proof. + * + * @return array + * @noinspection PhpUndefinedFunctionInspection + */ + private function prepare_payload( string $action, bool $proof = true ): array { + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_register_nonce', 'hcaptcha_easy_digital_downloads_register' ); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'register', + ] + ); + RegistrationGuard::limiter()->reset( edd_get_ip() ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Transfer prepared test proof into the native payload. + $captcha = $proof ? $_POST : []; + + ob_start(); + RegistrationGuard::token_fields(); + $markup = (string) ob_get_clean(); + preg_match_all( '/name="([^"]+)" value="([^"]+)"/', $markup, $fields, PREG_SET_ORDER ); + $tokens = []; + + foreach ( $fields as $field ) { + $tokens[ $field[1] ] = html_entity_decode( $field[2], ENT_QUOTES ); + } + + $payload = array_merge( + $captcha, + $tokens, + [ + 'edd_action' => $action, + 'edd_register_submit' => 'Register', + 'edd_user_login' => 'sec002-registration', + 'edd_user_email' => 'sec002@example.com', + 'edd_user_pass' => 'sec002-test-password', + 'edd_user_pass2' => 'sec002-test-password', + 'edd_honeypot' => '', + ] + ); + self::assertTrue( RegistrationGuard::has_valid_token( $payload ) ); + + return $payload; + } + + /** + * Run native routing and prevent only the final insertion side effect. + * + * @param array $payload The unmerged request passed by the native router. + * + * @return array + */ + private function dispatch( array $payload ): array { + $filtered_errors = []; + $sink_attempts = 0; + $remote_calls = 0; + add_filter( + 'pre_http_request', + static function ( $preempt, array $args, string $url ) use ( &$remote_calls ) { + if ( 'https://api.hcaptcha.com/siteverify' === $url ) { + ++$remote_calls; + } + + return $preempt; + }, + 5, + 3 + ); + add_filter( + 'edd_errors', + static function ( $errors ) use ( &$filtered_errors ) { + $filtered_errors = (array) $errors; + + return $errors; + }, + PHP_INT_MAX + ); + add_filter( + 'edd_insert_user_args', + static function ( array $args ) use ( &$sink_attempts ): array { + ++$sink_attempts; + // An empty native login fails wp_insert_user before it creates an account. + $args['user_login'] = ''; + + return $args; + } + ); + Router::frontend( $payload ); + + return [ + 'filtered_errors' => $filtered_errors, + 'stored_errors' => Messages::get_by_type( 'error' ), + 'sink_attempts' => $sink_attempts, + 'remote_calls' => $remote_calls, + ]; + } +} diff --git a/tests/php/integration/EasyDigitalDownloads/RegisterEmailPolicyTest.php b/tests/php/integration/EasyDigitalDownloads/RegisterEmailPolicyTest.php new file mode 100644 index 000000000..27d595e4e --- /dev/null +++ b/tests/php/integration/EasyDigitalDownloads/RegisterEmailPolicyTest.php @@ -0,0 +1,123 @@ +settings()->set( 'easy_digital_downloads_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + } + + /** + * Clear native error messages between projections. + */ + public function tearDown(): void { + Messages::clear(); + + parent::tearDown(); + } + + /** + * Reject only the authoritative native address when disposable. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native address. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + $_POST['edd_action'] = 'user_register'; + $_POST['edd_user_email'] = $email; + $_POST['email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_register_nonce', 'hcaptcha_easy_digital_downloads_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'register', + ] + ); + + $subject = new Register(); + $result = []; + add_action( + 'edd_user_register', + static function () use ( $subject, &$result ): void { + $result = $subject->verify( [] ); + } + ); + // The projection test omits submit, so the native handler returns before registration side effects. + // phpcs:ignore WordPress.Security.NonceVerification.Missing + do_action( 'edd_user_register', $_POST ); + + self::assertSame( $blocked ? [ 'disposable-email' => hcap_get_error_messages()['disposable-email'] ] : [], $result ); + } + + /** + * Native address controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable email' => [ 'user@disposable.example', true ], + 'permanent email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } +} diff --git a/tests/php/integration/EasyDigitalDownloads/RegisterLegacyDispatchTest.php b/tests/php/integration/EasyDigitalDownloads/RegisterLegacyDispatchTest.php new file mode 100644 index 000000000..6cbd9e9ee --- /dev/null +++ b/tests/php/integration/EasyDigitalDownloads/RegisterLegacyDispatchTest.php @@ -0,0 +1,243 @@ +request = [ $_GET, $_POST, $_REQUEST ]; + $_GET = []; + $_POST = []; + $_REQUEST = []; + // phpcs:enable WordPress.Security.NonceVerification + wp_set_current_user( 0 ); + Messages::clear(); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + } + + /** + * Restore request values and native messages. + */ + public function tearDown(): void { + if ( $this->request ) { + Messages::clear(); + // phpcs:ignore WordPress.Security.NonceVerification -- Restore synthetic request globals. + [ $_GET, $_POST, $_REQUEST ] = $this->request; + } + + parent::tearDown(); + } + + /** + * The legacy GET and POST entry points enforce CAPTCHA before account insertion. + * + * @dataProvider dp_native_legacy_routes + * + * @param string $transport Native request carrier. + * @param string $action Raw action normalized by EDD. + * @param bool $proof Whether to include valid CAPTCHA proof. + */ + public function test_native_legacy_registration_routes( string $transport, string $action, bool $proof ): void { + $payload = $this->prepare_payload( $action, $proof ); + new Register(); + + // phpcs:disable WordPress.Security.NonceVerification -- Populate one native request carrier. + if ( 'GET' === $transport ) { + $_GET = $payload; + $_POST = []; + } else { + $_POST = $payload; + } + $_REQUEST = array_merge( $_GET, $_POST ); + $before = $_POST; + // phpcs:enable WordPress.Security.NonceVerification + + $sink_attempts = $this->dispatch( $transport ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Assert the adapter restores the outer request. + self::assertSame( $before, $_POST ); + self::assertSame( $proof ? 1 : 0, $sink_attempts ); + self::assertSame( + $proof ? [] : [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], + Messages::get_by_type( 'error' ) + ); + self::assertFalse( username_exists( 'sec002-legacy-registration' ) ); + } + + /** + * Cover both legacy request carriers and sanitize_key action normalization. + * + * @return array + */ + public function dp_native_legacy_routes(): array { + return [ + 'POST without proof' => [ 'POST', 'user_register', false ], + 'GET without proof' => [ 'GET', 'user_register', false ], + 'normalized POST without proof' => [ 'POST', 'USER_REGISTER', false ], + 'POST with proof' => [ 'POST', 'user_register', true ], + 'GET with proof' => [ 'GET', 'user_register', true ], + ]; + } + + /** + * A valid POST proof cannot authorize the native GET registration request. + */ + public function test_get_registration_cannot_borrow_post_proof(): void { + $payload = $this->prepare_payload( 'user_register', false ); + $decoy = $this->prepare_payload( 'user_register', true ); + // phpcs:disable WordPress.Security.NonceVerification -- Populate conflicting native request carriers. + $_GET = $payload; + $_POST = $decoy; + $_REQUEST = array_merge( $_GET, $_POST ); + $before = $_POST; + // phpcs:enable WordPress.Security.NonceVerification + new Register(); + + self::assertSame( 0, $this->dispatch( 'GET' ) ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verify the decoy transport remains untouched. + self::assertSame( $before, $_POST ); + self::assertSame( [ 'bad-signature' => hcap_get_error_messages()['bad-signature'] ], Messages::get_by_type( 'error' ) ); + } + + /** + * A native validation error still blocks insertion when CAPTCHA is valid. + */ + public function test_native_email_guard_remains_authoritative(): void { + $payload = $this->prepare_payload( 'user_register', true ); + $payload['edd_user_email'] = 'invalid-email'; + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Populate the native POST carrier. + $_POST = $payload; + new Register(); + + self::assertSame( 0, $this->dispatch( 'POST' ) ); + self::assertArrayHasKey( 'email_invalid', Messages::get_by_type( 'error' ) ); + self::assertArrayNotHasKey( 'bad-signature', Messages::get_by_type( 'error' ) ); + } + + /** + * Dispatch the installed legacy EDD function and stop before account creation. + * + * @param string $transport Native request carrier. + * + * @return int Number of attempted user insertions. + * @noinspection PhpUndefinedFunctionInspection + */ + private function dispatch( string $transport ): int { + $sink_attempts = 0; + $stop = static function ( array $args ) use ( &$sink_attempts ): array { + ++$sink_attempts; + // Force wp_insert_user to stop before creating an account. + $args['user_login'] = ''; + + return $args; + }; + add_filter( 'edd_insert_user_args', $stop ); + + try { + if ( 'GET' === $transport ) { + edd_get_actions(); + } else { + edd_post_actions(); + } + } finally { + remove_filter( 'edd_insert_user_args', $stop ); + } + + return $sink_attempts; + } + + /** + * Build a full legacy registration payload with optional signed proof. + * + * @param string $action Raw EDD action. + * @param bool $proof Whether to include valid CAPTCHA proof. + * + * @return array + */ + private function prepare_payload( string $action, bool $proof ): array { + $this->prepare_verify_post( 'hcaptcha_easy_digital_downloads_register_nonce', 'hcaptcha_easy_digital_downloads_register' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-digital-downloads/easy-digital-downloads.php' ], + 'form_id' => 'register', + ] + ); + hcaptcha()->settings()->set( 'easy_digital_downloads_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Copy prepared synthetic proof into the native payload. + $captcha = $proof ? $_POST : []; + + return array_merge( + $captcha, + [ + 'edd_action' => $action, + 'edd_register_submit' => 'Register', + 'edd_user_login' => 'sec002-legacy-registration', + 'edd_user_email' => 'sec002-legacy@example.com', + 'edd_user_pass' => 'sec002-test-password', + 'edd_user_pass2' => 'sec002-test-password', + ] + ); + } +} diff --git a/tests/php/integration/ElementorPro/HCaptchaHandlerTest.php b/tests/php/integration/ElementorPro/HCaptchaHandlerTest.php index 239a24c66..9fef3a2a4 100644 --- a/tests/php/integration/ElementorPro/HCaptchaHandlerTest.php +++ b/tests/php/integration/ElementorPro/HCaptchaHandlerTest.php @@ -22,6 +22,7 @@ use ElementorPro\Modules\Forms\Module as FormsModule; use ElementorPro\Plugin as ElementorProPlugin; use HCaptcha\ElementorPro\HCaptchaHandler; +use HCaptcha\Helpers\API; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Settings\General; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; @@ -86,8 +87,8 @@ public function test_get_entry_excludes_sensitive_fields(): void { self::assertSame( [ - 'email' => 'reader@example.com', 'opinion' => 'Very useful', + 'email' => 'reader@example.com', ], $entry['data'] ); @@ -173,7 +174,7 @@ public function test_constructor(): void { * @return void */ public function test_block_native_integration(): void { - $is_native_loaded = class_exists( HCaptcha_Handler::class, false ); + $is_native_loaded = class_exists( HCaptcha_Handler::class ); $actions = [ 'elementor_pro/forms/field_types', 'elementor/element/form/section_form_fields/after_section_end', @@ -222,6 +223,32 @@ public function test_block_native_integration(): void { wp_deregister_script( 'hcaptcha' ); } + /** + * The native Elementor hCaptcha callbacks and scripts are removed when its handler is present. + * + * @runInSeparateProcess + * @preserveGlobalState disabled + * @group process-isolation-php74 + */ + public function test_block_native_integration_with_loaded_handler(): void { + if ( ! class_exists( HCaptcha_Handler::class, false ) ) { + class_alias( get_class( new class() {} ), HCaptcha_Handler::class ); + } + + $action = 'elementor_pro/forms/field_types'; + $callback = [ HCaptcha_Handler::class, 'test_callback' ]; + add_action( $action, $callback ); + wp_register_script( 'elementor-hcaptcha-api', '', [], HCAPTCHA_VERSION, true ); + wp_register_script( 'hcaptcha', '', [], HCAPTCHA_VERSION, true ); + + $subject = new HCaptchaHandler(); + $subject->block_native_integration(); + + self::assertFalse( has_action( $action, $callback ) ); + self::assertFalse( wp_script_is( 'elementor-hcaptcha-api', 'registered' ) ); + self::assertFalse( wp_script_is( 'hcaptcha', 'registered' ) ); + } + /** * Test init(). * @@ -1586,4 +1613,60 @@ private function prepare_widget_id( $form_id, array $id = [] ): void { $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( $id ); } + /** + * Apply email policy to native sanitized custom email fields. + * + * @param bool $blocked Whether the trusted email is disposable. + * @dataProvider dp_sec063_email_policy + */ + public function test_sec063_typed_email_policy( bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + $this->prepare_widget_id( 'form-1' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $record = Mockery::mock( Form_Record::class ); + $record->shouldReceive( 'get' )->with( 'form_settings' )->andReturn( [ 'id' => 'form-1' ] ); + $record->shouldReceive( 'get' )->with( 'sent_data' )->andReturn( + [ + 'billing_address' => $blocked ? 'person@sec063-disposable.test' : 'person@example.com', + 'second_address' => 'reader@example.com', + 'email' => 'spoof@sec063-disposable.test', + ] + ); + $record->shouldReceive( 'get' )->with( 'fields' )->andReturn( + [ + [ + 'id' => 'billing_address', + 'type' => 'email', + 'field_label' => 'Payment contact', + 'value' => $blocked ? 'person@sec063-disposable.test' : 'person@example.com', + ], + [ + 'id' => 'second_address', + 'type' => 'email', + 'value' => 'reader@example.com', + ], + [ + 'id' => 'email', + 'type' => 'text', + 'value' => 'spoof@sec063-disposable.test', + ], + ] + ); + $subject = new HCaptchaHandler(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $record ); + + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + /** + * Exercise both policy rejection and permanent address acceptance. + * + * @return array + */ + public function dp_sec063_email_policy(): array { + return [ + 'disposable' => [ true ], + 'permanent' => [ false ], + ]; + } } diff --git a/tests/php/integration/EssentialAddons/LoginTest.php b/tests/php/integration/EssentialAddons/LoginTest.php index f676f9f1a..27f07577b 100644 --- a/tests/php/integration/EssentialAddons/LoginTest.php +++ b/tests/php/integration/EssentialAddons/LoginTest.php @@ -17,7 +17,7 @@ use Essential_Addons_Elementor\Elements\Login_Register as EssentialAddonsLoginRegister; use HCaptcha\EssentialAddons\Login; use HCaptcha\Helpers\HCaptcha; -use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; +use HCaptcha\Tests\Integration\WC\WooCommerceTestCase; use Mockery; use ReflectionClass; use tad\FunctionMocker\FunctionMocker; @@ -28,27 +28,18 @@ * @group essential-addons * @group essential-addons-login */ -class LoginTest extends HCaptchaPluginWPTestCase { +class LoginTest extends WooCommerceTestCase { /** * Plugin relative paths. * * @var string[] */ protected static $plugin = [ + 'woocommerce/woocommerce.php', 'elementor/elementor.php', 'essential-addons-for-elementor-lite/essential_adons_elementor.php', ]; - /** - * Hooks to replay after loading the plugin. - * - * @var string[] - */ - protected static array $plugin_load_hooks = [ - 'plugins_loaded', - 'init', - ]; - /** * Test that live Elementor and Essential Addons plugins are loaded. * @@ -74,7 +65,7 @@ public function test_live_plugins_are_loaded(): void { * @return void */ public function tearDown(): void { - unset( $_POST['widget_id'], $_SERVER['HTTP_REFERER'] ); + unset( $_POST['page_id'], $_POST['widget_id'], $_SERVER['HTTP_REFERER'] ); parent::tearDown(); } @@ -274,7 +265,7 @@ static function ( $name, $value ) use ( &$setcookie ) { $subject = Mockery::mock( Login::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); - $subject->shouldReceive( 'exit' )->with()->times( (int) $has_referer ); + $subject->shouldReceive( 'exit' )->with()->once(); ob_start(); $subject->verify( $post, $settings, $bootstrap ); @@ -284,7 +275,7 @@ static function ( $name, $value ) use ( &$setcookie ) { self::assertSame( '{"success":false,"data":"' . $error_message . '"}', $json ); self::assertSame( 'eael_login_error_' . $widget_id, $setcookie[0] ); self::assertSame( $error_message, $setcookie[1] ); - self::assertSame( $redirect, $has_referer ); + self::assertTrue( $redirect ); } /** @@ -299,6 +290,84 @@ public function dp_test_verify_not_verified(): array { ]; } + /** + * Test that a non-AJAX CAPTCHA rejection stops native login processing. + * + * @param bool $has_referer Whether the request has a Referer header. + * @param bool $has_page Whether the native form page is supplied. + * + * @return void + * @dataProvider dp_test_verify_not_verified_without_ajax + */ + public function test_verify_not_verified_without_ajax( bool $has_referer, bool $has_page ): void { + $page_id = $this->factory()->post->create( [ 'post_type' => 'page' ] ); + $page_url = get_permalink( $page_id ); + $post = []; + $widget_id = 'some_id'; + $error_message = 'The hCaptcha is invalid.'; + $setcookie = []; + $redirect_url = ''; + + $_POST['widget_id'] = $widget_id; + + if ( $has_page ) { + $post['page_id'] = $page_id; + $_POST['page_id'] = $page_id; + } + + if ( $has_referer ) { + $_SERVER['HTTP_REFERER'] = $page_url; + } + + $this->prepare_verify_post( 'hcaptcha_login_nonce', 'hcaptcha_login', false ); + $this->prepare_widget_id( + [ + 'source' => [], + 'form_id' => 'login', + ] + ); + + add_filter( 'hcap_login_limit_exceeded', '__return_true' ); + add_filter( 'wp_doing_ajax', '__return_false' ); + add_filter( + 'wp_redirect', + static function ( $location ) use ( &$redirect_url ) { + $redirect_url = $location; + + return false; + } + ); + + FunctionMocker::replace( + 'setcookie', + static function ( $name, $value ) use ( &$setcookie ) { + $setcookie = [ $name, $value ]; + } + ); + + $subject = Mockery::mock( Login::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'exit' )->with()->once(); + + $subject->verify( $post, [], Bootstrap::instance() ); + + self::assertSame( [ 'eael_login_error_' . $widget_id, $error_message ], $setcookie ); + self::assertSame( $has_referer || $has_page ? $page_url : home_url( '/' ), $redirect_url ); + } + + /** + * Data provider for non-AJAX CAPTCHA rejections. + * + * @return array + */ + public function dp_test_verify_not_verified_without_ajax(): array { + return [ + 'headerless form page' => [ false, true ], + 'headerless home fallback' => [ false, false ], + 'referer' => [ true, true ], + ]; + } + /** * Test verify() when widget id is bad. * @@ -345,7 +414,9 @@ static function ( $name, $value ) use ( &$setcookie ) { } ); - $subject = new Login(); + $subject = Mockery::mock( Login::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'exit' )->with()->once(); ob_start(); $subject->verify( $post, $settings, $bootstrap ); diff --git a/tests/php/integration/EssentialAddons/RegisterTest.php b/tests/php/integration/EssentialAddons/RegisterTest.php index 0a489a8e7..7993f50fa 100644 --- a/tests/php/integration/EssentialAddons/RegisterTest.php +++ b/tests/php/integration/EssentialAddons/RegisterTest.php @@ -54,7 +54,7 @@ class RegisterTest extends HCaptchaPluginWPTestCase { * @return void */ public function tearDown(): void { - unset( $_POST['widget_id'], $_SERVER['HTTP_REFERER'] ); + unset( $_POST['page_id'], $_POST['widget_id'], $_SERVER['HTTP_REFERER'] ); parent::tearDown(); } @@ -72,6 +72,7 @@ public function test_init_hooks(): void { has_action( 'eael/login-register/after-password-field', [ $subject, 'add_register_hcaptcha' ] ) ); self::assertSame( 10, has_action( 'eael/login-register/before-register', [ $subject, 'verify' ] ) ); + self::assertSame( 10, has_filter( 'eael/login-register/register-form-allowed-html', [ $subject, 'allow_hcaptcha_html' ] ) ); self::assertSame( 10, has_action( 'wp_head', [ $subject, 'print_inline_styles' ] ) ); @@ -138,6 +139,29 @@ public function test_add_register_hcaptcha_with_form_interaction(): void { self::assertStringContainsString( 'class="h-captcha hcaptcha-api-delayed"', $actual ); } + /** + * Test that Essential Addons preserves the widget and strips unapproved attributes. + * + * @return void + */ + public function test_allow_hcaptcha_html(): void { + $subject = new Register(); + $allowed_html = [ + 'div' => [ 'class' => true ], + 'h-captcha' => [ 'title' => true ], + ]; + $actual = $subject->allow_hcaptcha_html( $allowed_html ); + $markup = ''; + $filtered = wp_kses( $markup, $actual ); + + self::assertSame( $allowed_html['div'], $actual['div'] ); + self::assertTrue( $actual['h-captcha']['title'] ); + self::assertStringContainsString( 'with()->times( (int) $has_referer ); + $subject->shouldReceive( 'exit' )->with()->once(); ob_start(); $subject->verify(); @@ -231,7 +255,7 @@ static function ( $name, $value ) use ( &$setcookie ) { self::assertSame( '{"success":false,"data":"' . $error_message . '"}', $json ); self::assertSame( 'eael_login_error_' . $widget_id, $setcookie[0] ); self::assertSame( $error_message, $setcookie[1] ); - self::assertSame( $redirect, $has_referer ); + self::assertTrue( $redirect ); } /** @@ -246,6 +270,85 @@ public function dp_test_verify_not_verified(): array { ]; } + /** + * Test that a non-AJAX CAPTCHA rejection stops native registration processing. + * + * @param bool $has_referer Whether the request has a Referer header. + * @param bool $has_page Whether the native form page is supplied. + * + * @return void + * @dataProvider dp_test_verify_not_verified_without_ajax + */ + public function test_verify_not_verified_without_ajax( bool $has_referer, bool $has_page ): void { + $page_id = $this->factory()->post->create( [ 'post_type' => 'page' ] ); + $page_url = get_permalink( $page_id ); + $widget_id = 'some_id'; + $error_message = 'The hCaptcha is invalid.'; + $setcookie = []; + $redirect_url = ''; + + $_POST['widget_id'] = $widget_id; + + if ( $has_page ) { + $_POST['page_id'] = $page_id; + } + + if ( $has_referer ) { + $_SERVER['HTTP_REFERER'] = $page_url; + } + + $this->prepare_verify_post( + 'hcaptcha_essential_addons_register_nonce', + 'hcaptcha_essential_addons_register', + false + ); + $this->prepare_widget_id( + [ + 'source' => [], + 'form_id' => 'register', + ] + ); + + add_filter( 'wp_doing_ajax', '__return_false' ); + add_filter( + 'wp_redirect', + static function ( $location ) use ( &$redirect_url ) { + $redirect_url = $location; + + return false; + } + ); + + FunctionMocker::replace( + 'setcookie', + static function ( $name, $value ) use ( &$setcookie ) { + $setcookie = [ $name, $value ]; + } + ); + + $subject = Mockery::mock( Register::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'exit' )->with()->once(); + + $subject->verify(); + + self::assertSame( [ 'eael_login_error_' . $widget_id, $error_message ], $setcookie ); + self::assertSame( $has_referer || $has_page ? $page_url : home_url( '/' ), $redirect_url ); + } + + /** + * Data provider for non-AJAX CAPTCHA rejections. + * + * @return array + */ + public function dp_test_verify_not_verified_without_ajax(): array { + return [ + 'headerless form page' => [ false, true ], + 'headerless home fallback' => [ false, false ], + 'referer' => [ true, true ], + ]; + } + /** * Test verify() when widget id is bad. * @@ -292,7 +395,9 @@ static function ( $name, $value ) use ( &$setcookie ) { } ); - $subject = new Register(); + $subject = Mockery::mock( Register::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'exit' )->with()->once(); ob_start(); $subject->verify(); diff --git a/tests/php/integration/EssentialBlocks/FormTest.php b/tests/php/integration/EssentialBlocks/FormTest.php index 525741639..e5a5b1aa4 100644 --- a/tests/php/integration/EssentialBlocks/FormTest.php +++ b/tests/php/integration/EssentialBlocks/FormTest.php @@ -5,9 +5,15 @@ * @package HCaptcha\Tests */ +// phpcs:disable Generic.Commenting.DocComment.MissingShort +/** @noinspection PhpUndefinedNamespaceInspection */ +/** @noinspection PhpUndefinedClassInspection */ +// phpcs:enable Generic.Commenting.DocComment.MissingShort + namespace HCaptcha\Tests\Integration\EssentialBlocks; use HCaptcha\EssentialBlocks\Form; +use HCaptcha\Helpers\API; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; use Mockery; @@ -23,6 +29,16 @@ * @group essential-blocks-form */ class FormTest extends HCaptchaPluginWPTestCase { + /** + * Fall back to the form element ID when the submit button has no native ID. + */ + public function test_get_form_id_without_native_submit_button(): void { + $subject = new Form(); + $method = $this->set_method_accessibility( $subject, 'get_form_id_from_block_content' ); + + self::assertSame( 'fallback', $method->invoke( $subject, '
      ' ) ); + self::assertSame( '0', $method->invoke( $subject, '
      no form
      ' ) ); + } /** * Plugin relative path. @@ -278,13 +294,13 @@ public function test_get_entry(): void { 'first-name' => 'Melany', 'last-name' => 'Doe', 'subject' => 'Subject', - 'email' => 'your.email+fakedata80629@gmail.com', 'message' => 'Message', ], 'expected_id' => [ 'source' => [ 'essential-blocks/essential-blocks.php' ], 'form_id' => 'eb-form-xmouf', ], + 'email_addresses' => [], ], $actual ); @@ -355,4 +371,71 @@ private function get_widget_id( string $form_id ): string { ] ); } + /** + * Apply email policy to trusted stored Essential Blocks fields. + * + * @param bool $blocked Whether the trusted email is disposable. + * + * @dataProvider dp_sec063_email_policy + * @noinspection PhpUndefinedConstantInspection + */ + public function test_sec063_typed_email_policy( bool $blocked ): void { + global $wpdb; + $this->prepare_verify_request( 'sec063-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + // The fixture uses the native plugin settings table. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery + $wpdb->insert( + ESSENTIAL_BLOCKS_FORM_SETTINGS_TABLE, + [ + 'block_id' => 'sec063', + 'title' => 'Email policy', + 'fields' => maybe_serialize( + [ + 'billing_address' => (object) [ + 'type' => 'email', + 'label' => 'Payment contact', + ], + 'contact_address' => (object) [ + 'type' => 'email', + 'label' => 'Другой адрес', + ], + 'email' => (object) [ + 'type' => 'text', + 'label' => 'Other', + ], + ] + ), + 'form_options' => '', + 'settings' => '', + 'created_by' => 0, + 'updated_at' => current_time( 'mysql' ), + ] + ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = $this->get_widget_id( 'sec063' ); + $subject = new Form(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( + $subject, + [ + 'billing_address' => $blocked ? 'person@sec063-disposable.test' : 'person@example.com', + 'contact_address' => 'reader@example.com', + 'email' => 'spoof@sec063-disposable.test', + ], + 'sec063' + ); + + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + /** + * Exercise both policy rejection and permanent address acceptance. + * + * @return array + */ + public function dp_sec063_email_policy(): array { + return [ + 'disposable' => [ true ], + 'permanent' => [ false ], + ]; + } } diff --git a/tests/php/integration/EventsManager/BookingTest.php b/tests/php/integration/EventsManager/BookingTest.php index 5553a4015..ca0c2fd9d 100644 --- a/tests/php/integration/EventsManager/BookingTest.php +++ b/tests/php/integration/EventsManager/BookingTest.php @@ -11,7 +11,9 @@ namespace HCaptcha\Tests\Integration\EventsManager; use EM_Booking; +use EM_Bookings; use EM_Event; +use EM_Person; use HCaptcha\EventsManager\Booking; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; @@ -24,6 +26,15 @@ * @group events-manager-booking */ class BookingTest extends HCaptchaPluginWPTestCase { + /** + * Print the booking form spacing rule. + */ + public function test_print_inline_styles(): void { + ob_start(); + ( new Booking() )->print_inline_styles(); + + self::assertStringContainsString( '.em-booking-section .h-captcha', ob_get_clean() ); + } /** * Plugin relative path. @@ -42,7 +53,7 @@ public function setUp(): void { hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); - hcaptcha()->settings()->set( 'events_manager_status', 'booking' ); + hcaptcha()->settings()->set( 'events_manager_status', [ 'booking' ] ); $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } @@ -88,8 +99,153 @@ public function test_filled_honeypot_is_rejected(): void { $_POST['hcap_hp_test'] = 'bot'; $booking = Mockery::mock( EM_Booking::class ); + $event = Mockery::mock( EM_Event::class ); + $event->shouldReceive( 'get_event_uid' )->andReturn( 123 ); + $booking->shouldReceive( 'get_event' )->once()->andReturn( $event ); + $booking->shouldReceive( 'get_person' )->once()->andReturn( (object) [ 'user_email' => '' ] ); $booking->shouldReceive( 'add_error' )->once()->with( 'Anti-spam check failed.' ); - self::assertTrue( ( new Booking() )->verify( true, $booking ) ); + self::assertFalse( ( new Booking() )->verify( true, $booking ) ); + } + + /** + * A booking without an event ID still checks the signed widget identity. + */ + public function test_missing_event_id_rejects_foreign_widget(): void { + $this->prepare_verify_post( 'hcaptcha_events_manager_nonce', 'hcaptcha_events_manager' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'events-manager/events-manager.php' ], + 'form_id' => 123, + ] + ); + + $event = new EM_Event(); + $event->event_id = 0; + $booking = Mockery::mock( EM_Booking::class ); + $booking->shouldReceive( 'get_event' )->once()->andReturn( $event ); + $booking->shouldReceive( 'get_person' )->once()->andReturn( (object) [ 'user_email' => '' ] ); + $booking->shouldReceive( 'add_error' )->once()->with( hcap_get_error_messages()['bad-signature'] ); + + self::assertFalse( ( new Booking() )->verify( true, $booking ) ); + } + + /** + * Validate the resolved booking recipient rather than posted aliases. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native recipient email. + * @param bool $blocked Whether disposal policy rejects it. + * + * @noinspection PhpUndefinedMethodInspection + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $_POST['user_email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_events_manager_nonce', 'hcaptcha_events_manager' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'events_manager_status', [ 'booking' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'events-manager/events-manager.php' ], + 'form_id' => 123, + ] + ); + + $booking = Mockery::mock( EM_Booking::class )->makePartial(); + $event = new EM_Event(); + $event->event_id = 123; + $booking->shouldReceive( 'get_event' )->once()->andReturn( $event ); + $booking->person = new EM_Person( 0 ); + $booking->person_id = 0; + $booking->booking_meta = [ 'registration' => [ 'user_email' => $email ] ]; + + $result = ( new Booking() )->verify( true, $booking ); + + self::assertSame( ! $blocked, $result ); + self::assertSame( $blocked ? [ hcap_get_error_messages()['disposable-email'] ] : [], $booking->get_errors() ); + } + + /** + * Resolved recipient controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable recipient' => [ 'user@disposable.example', true ], + 'permanent recipient' => [ 'safe@example.com', false ], + 'email-free booking' => [ '', false ], + ]; + } + + /** + * A logged-in booking keeps its resolved person email even if the request carries another address. + * + * @param string $person_email Resolved booking person's address. + * @param string $request_email Unrelated native request address. + * @param bool $blocked Whether the resolved address is disposable. + * @dataProvider dp_logged_in_booking_email + */ + public function test_logged_in_booking_uses_person_email( string $person_email, string $request_email, bool $blocked ): void { + self::assertFalse( EM_Bookings::is_registration_forced() ); + $user_id = $this->factory()->user->create( [ 'user_email' => $person_email ] ); + wp_set_current_user( $user_id ); + self::assertSame( $person_email, get_userdata( $user_id )->user_email ); + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $this->prepare_verify_post( 'hcaptcha_events_manager_nonce', 'hcaptcha_events_manager' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a decoy field in a native booking test. + $_REQUEST['user_email'] = $request_email; + $_POST['user_email'] = $request_email; + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'events-manager/events-manager.php' ], + 'form_id' => 123, + ] + ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + self::assertTrue( + HCaptcha::is_protection_enabled( + [ + 'source' => [ 'events-manager/events-manager.php' ], + 'form_id' => 123, + ] + ) + ); + + $event = new EM_Event(); + $event->event_id = 123; + $booking = Mockery::mock( EM_Booking::class ); + $booking->shouldReceive( 'get_event' )->once()->andReturn( $event ); + $booking->shouldReceive( 'get_person' )->once()->andReturn( get_userdata( $user_id ) ); + $booking->shouldReceive( 'add_error' )->times( $blocked ? 1 : 0 ); + + self::assertSame( ! $blocked, ( new Booking() )->verify( true, $booking ) ); + } + + /** + * Logged-in recipient and decoy request controls. + * + * @return array + */ + public function dp_logged_in_booking_email(): array { + return [ + 'permanent person and disposable decoy' => [ 'reader@example.com', 'user@disposable.example', false ], + 'disposable person and permanent decoy' => [ 'user@disposable.example', 'reader@example.com', true ], + ]; } } diff --git a/tests/php/integration/EventsManager/NativeBookingDispatchTest.php b/tests/php/integration/EventsManager/NativeBookingDispatchTest.php new file mode 100644 index 000000000..c9fd2f04b --- /dev/null +++ b/tests/php/integration/EventsManager/NativeBookingDispatchTest.php @@ -0,0 +1,464 @@ +request = $_REQUEST; + + foreach ( [ 'EM_Event', 'EM_Booking', 'EM_Person', 'EM_Ticket', 'EM_Notices', 'EM_Mailer', 'EM_SAVING_EVENT', 'em_temp_user_data', 'em_capabilities_array' ] as $name ) { + $this->native_globals[ $name ] = [ + 'exists' => array_key_exists( $name, $GLOBALS ), + 'value' => $GLOBALS[ $name ] ?? null, + ]; + unset( $GLOBALS[ $name ] ); + } + + $_REQUEST = []; + + if ( ! self::$native_capabilities ) { + wp_set_current_user( 0 ); + em_init(); + self::$native_capabilities = $GLOBALS['em_capabilities_array']; + } + + $GLOBALS['em_capabilities_array'] = self::$native_capabilities; + $this->prepare_native_tables(); + + update_option( 'dbem_rsvp_enabled', true ); + update_option( 'dbem_bookings_anonymous', true ); + update_option( 'dbem_bookings_registration_disable', false ); + update_option( 'dbem_bookings_tickets_orderby', 'ticket_price DESC, ticket_name ASC' ); + update_option( 'dbem_require_location', false ); + + hcaptcha()->settings()->set( 'honeypot', 'on' ); + hcaptcha()->settings()->set( 'events_manager_status', [ 'booking' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + } + + /** + * Restore native request state and remove the event fixture. + * + * @return void + */ + public function tearDown(): void { + global $wpdb; + + if ( $this->event && $this->event->event_id ) { + wp_set_current_user( $this->event->event_owner ); + $this->event->delete( true ); + } + + foreach ( array_reverse( $this->native_fixture_tables ) as $table ) { + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Remove only tables this fixture created. + $wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS `' . esc_sql( $table ) . '`' ); + } + + foreach ( $this->native_globals as $name => $state ) { + if ( $state['exists'] ) { + $GLOBALS[ $name ] = $state['value']; + } else { + unset( $GLOBALS[ $name ] ); + } + } + + $_REQUEST = $this->request; + + parent::tearDown(); + } + + /** + * Verification failures stop guest registration before user insertion. + * + * @dataProvider dp_test_rejected_booking + * + * @param string $failure Verification failure. + * @param string $error_code Expected verification error code. + * + * @return void + */ + public function test_rejected_booking_does_not_reach_user_insertion( string $failure, string $error_code ): void { + $this->prepare_booking_request(); + $checked_emails = []; + + switch ( $failure ) { + case 'missing-response': + unset( $_POST['h-captcha-response'] ); + break; + case 'honeypot': + $_POST['hcap_hp_test'] = 'bot'; + break; + case 'email': + $this->guest_email = 'guest-' . wp_generate_uuid4() . '@sec007-disposable.test'; + $_REQUEST['user_email'] = $this->guest_email; + $_POST['user_email'] = $this->guest_email; + + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'sec007-disposable.test' => true ]; + } + ); + add_filter( + 'hcap_is_disposable_email', + static function ( $is_disposable, $email ) use ( &$checked_emails ) { + $checked_emails[] = $email; + + return $is_disposable; + }, + PHP_INT_MAX, + 2 + ); + break; + case 'signature': + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = 'invalid-widget-signature'; + break; + } + + $result = $this->dispatch_booking(); + $error = hcap_get_error_messages()[ $error_code ]; + + self::assertTrue( $result['native_validated'], 'The event and ticket must pass native validation before hCaptcha.' ); + self::assertSame( [], $result['native_errors'] ); + self::assertSame( [ $error ], $result['booking']->get_errors() ); + self::assertSame( 0, $result['user_insert_calls'], 'Rejected verification must stop the controller before wp_insert_user().' ); + self::assertFalse( $result['validated'] ); + self::assertSame( 0, $result['booking_save_calls'] ); + self::assertStringContainsString( $error, $GLOBALS['EM_Notices']->get_errors() ); + + if ( 'email' === $failure ) { + self::assertContains( $this->guest_email, $checked_emails ); + self::assertNotContains( ( new EM_Person( 0 ) )->user_email, $checked_emails ); + } + + $this->assert_no_guest_records(); + } + + /** + * Booking verification failures. + * + * @return array + */ + public function dp_test_rejected_booking(): array { + return [ + 'missing CAPTCHA response' => [ 'missing-response', 'empty' ], + 'filled honeypot' => [ 'honeypot', 'spam' ], + 'rejected native email' => [ 'email', 'disposable-email' ], + 'invalid widget signature' => [ 'signature', 'bad-signature' ], + ]; + } + + /** + * A valid request reaches the native user insertion boundary. + * + * @return void + */ + public function test_valid_booking_reaches_native_user_insertion(): void { + $this->prepare_booking_request(); + + $result = $this->dispatch_booking(); + + self::assertTrue( $result['native_validated'] ); + self::assertTrue( $result['validated'] ); + self::assertSame( [], $result['booking']->get_errors() ); + self::assertSame( 1, $result['user_insert_calls'] ); + self::assertSame( 0, $result['booking_save_calls'], 'The empty-login sentinel must stop registration without saving a booking.' ); + $this->assert_no_guest_records(); + } + + /** + * Successful CAPTCHA verification preserves native rejection. + * + * @return void + */ + public function test_successful_verification_preserves_native_false(): void { + $this->prepare_booking_request(); + $_REQUEST['em_tickets'] = []; + + $result = $this->dispatch_booking(); + + self::assertFalse( $result['native_validated'] ); + self::assertFalse( $result['validated'] ); + self::assertNotEmpty( $result['native_errors'] ); + self::assertSame( $result['native_errors'], $result['booking']->get_errors() ); + self::assertSame( 0, $result['user_insert_calls'] ); + self::assertSame( 0, $result['booking_save_calls'] ); + $this->assert_no_guest_records(); + } + + /** + * Create missing native tables used by the fixture and its cleanup. + * + * @return void + * @noinspection PhpUndefinedConstantInspection + */ + private function prepare_native_tables(): void { + global $wpdb; + + require_once EM_DIR . '/em-install.php'; + $test_prefix = $wpdb->prefix; + $native_prefix = substr( EM_EVENTS_TABLE, 0, -strlen( 'em_events' ) ); + + $tables = [ + EM_EVENTS_TABLE => 'em_create_events_table', + EM_TIMERANGES_TABLE => 'em_create_timeslots_table', + EM_EVENT_TIMESLOTS_TABLE => 'em_create_event_timeslots_table', + EM_META_TABLE => 'em_create_events_meta_table', + EM_LOCATIONS_TABLE => 'em_create_locations_table', + EM_BOOKINGS_TABLE => 'em_create_bookings_table', + EM_BOOKINGS_META_TABLE => 'em_create_bookings_meta_table', + EM_TICKETS_TABLE => 'em_create_tickets_table', + EM_TICKETS_BOOKINGS_TABLE => 'em_create_tickets_bookings_table', + EM_TICKETS_BOOKINGS_META_TABLE => 'em_create_tickets_bookings_meta_table', + ]; + + try { + // Events Manager's constants were defined before the test runner changed the WordPress table prefix. + $wpdb->set_prefix( $native_prefix ); + + foreach ( $tables as $table => $create_table ) { + // The WordPress test harness creates temporary tables, which SHOW TABLES omits. + $lookup = 'SHOW COLUMNS FROM `' . esc_sql( $table ) . '`'; + $errors_hidden = $wpdb->suppress_errors(); + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The identifier comes from native plugin table constants above. + $exists = null !== $wpdb->get_var( $lookup ); + $wpdb->suppress_errors( $errors_hidden ); + + if ( ! $exists ) { + $create_table(); + $this->native_fixture_tables[] = $table; + } + + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The identifier comes from native plugin table constants above. + self::assertNotNull( $wpdb->get_var( $lookup ), 'The native fixture table must exist: ' . $table . '. ' . $wpdb->last_error ); + } + } finally { + $wpdb->set_prefix( $test_prefix ); + } + } + + /** + * Save a native event and ticket and prepare a protected guest request. + * + * @return void + */ + private function prepare_booking_request(): void { + wp_set_current_user( $this->factory()->user->create( [ 'role' => 'administrator' ] ) ); + + foreach ( [ 'edit_events', 'edit_others_events', 'publish_events', 'manage_bookings', 'manage_others_bookings', 'delete_events', 'delete_others_events' ] as $capability ) { + wp_get_current_user()->add_cap( $capability ); + } + + $date = gmdate( 'Y-m-d', time() + WEEK_IN_SECONDS ); + + $this->event = new EM_Event(); + $this->event->event_name = 'hCaptcha guest booking regression'; + $this->event->event_start_date = $date; + $this->event->event_end_date = $date; + $this->event->event_start_time = '12:00:00'; + $this->event->event_end_time = '13:00:00'; + $this->event->event_rsvp = 1; + $this->event->event_spaces = 10; + $this->event->location_id = 0; + $this->event->force_status = 'publish'; + + $ticket = new EM_Ticket(); + $ticket->event = $this->event; + $ticket->ticket_status = 1; + $ticket->ticket_spaces = 10; + $this->event->get_tickets()->tickets = [ $ticket ]; + + self::assertTrue( $this->event->save(), implode( ' ', $this->event->get_errors() ) ); + self::assertNotEmpty( $ticket->ticket_id ); + + $event_id = $this->event->event_id; + wp_cache_delete( $event_id, 'em_events' ); + $this->event = new EM_Event( $event_id ); + + wp_set_current_user( 0 ); + unset( $GLOBALS['EM_Event'], $GLOBALS['EM_Booking'], $GLOBALS['EM_Person'], $GLOBALS['EM_Ticket'] ); + $GLOBALS['EM_Notices'] = new EM_Notices(); + $this->guest_email = 'guest-' . wp_generate_uuid4() . '@example.com'; + + $_REQUEST = [ + 'action' => 'booking_add', + '_wpnonce' => wp_create_nonce( 'booking_add' ), + 'event_id' => $event_id, + 'em_tickets' => [ $ticket->ticket_id => [ 'spaces' => 1 ] ], + 'user_email' => $this->guest_email, + 'user_name' => 'Guest Booker', + ]; + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Native controller validates the test nonce during dispatch. + $_POST = $_REQUEST; + + $this->prepare_verify_post( 'hcaptcha_events_manager_nonce', 'hcaptcha_events_manager' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'events-manager/events-manager.php' ], + 'form_id' => $event_id, + ] + ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + } + + /** + * Run the actual native controller with an account-creation sentinel. + * + * @return array + * @noinspection PhpUndefinedFunctionInspection + */ + private function dispatch_booking(): array { + $native_validated = null; + $native_errors = null; + $validated = null; + $booking = null; + $user_insert_calls = 0; + $booking_save_calls = 0; + + $before_verification = static function ( $value, EM_Booking $subject ) use ( &$native_validated, &$native_errors ) { + $native_validated = $value; + $native_errors = $subject->get_errors(); + + return $value; + }; + $booking_action = static function ( EM_Event $event, EM_Booking $subject, $value ) use ( &$booking, &$validated ): void { + $booking = $subject; + $validated = $value; + }; + $user_insert = static function () use ( &$user_insert_calls ): string { + ++$user_insert_calls; + + // Core rejects the empty login before insertion, so no account or notification is created. + return ''; + }; + $booking_save = static function () use ( &$booking_save_calls ): void { + ++$booking_save_calls; + }; + + add_filter( 'em_booking_validate', $before_verification, 1, 2 ); + add_action( 'em_booking_add', $booking_action, 10, 3 ); + add_filter( 'pre_user_login', $user_insert ); + add_action( 'em_booking_save_pre', $booking_save ); + new Booking(); + + $buffer_level = ob_get_level(); + ob_start(); + + try { + em_init_actions_start(); + } finally { + while ( ob_get_level() > $buffer_level ) { + ob_end_clean(); + } + + remove_filter( 'em_booking_validate', $before_verification, 1 ); + remove_action( 'em_booking_add', $booking_action ); + remove_filter( 'pre_user_login', $user_insert ); + remove_action( 'em_booking_save_pre', $booking_save ); + } + + self::assertInstanceOf( EM_Booking::class, $booking ); + + return compact( 'native_validated', 'native_errors', 'validated', 'booking', 'user_insert_calls', 'booking_save_calls' ); + } + + /** + * Assert the guest request persisted neither an account nor a booking. + * + * @return void + * @noinspection PhpUndefinedConstantInspection + */ + private function assert_no_guest_records(): void { + global $wpdb; + + self::assertFalse( email_exists( $this->guest_email ) ); + self::assertSame( + '0', + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- EM_BOOKINGS_TABLE is defined by the installed native plugin. + $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . EM_BOOKINGS_TABLE . ' WHERE event_id = %d', $this->event->event_id ) ) + ); + } +} diff --git a/tests/php/integration/FluentForm/AdaptiveSubmissionTest.php b/tests/php/integration/FluentForm/AdaptiveSubmissionTest.php new file mode 100644 index 000000000..b66174d34 --- /dev/null +++ b/tests/php/integration/FluentForm/AdaptiveSubmissionTest.php @@ -0,0 +1,787 @@ + [ + 'honeypotStatus' => 'yes', + 'tokenBasedProtectionStatus' => 'yes', + ], + ] + ); + } + + /** + * Capture native request state before dispatch controls. + */ + public function setUp(): void { + parent::setUp(); + $this->native_request = App::getInstance()['request']; + LoginAttempts::delete_all(); + wp_set_current_user( 0 ); + add_filter( 'wp_doing_ajax', '__return_true' ); + add_filter( 'fluentform/nonce_verify', '__return_true' ); + add_filter( 'pre_wp_mail', '__return_true' ); + add_filter( + 'wp_die_ajax_handler', + static function () { + return static function () { + throw new RuntimeException( 'SEC008 native JSON completed.' ); + }; + } + ); + } + + /** + * Restore native request state and bounded login records. + */ + public function tearDown(): void { + App::getInstance()['request'] = $this->native_request; + FormFieldsParser::resetData(); + LoginAttempts::delete_all(); + parent::tearDown(); + } + + /** + * Valid credentials must not remove the challenge needed by this submission. + * + * @param bool $valid_password Whether the real password is correct. + * @param int $seed_count Failed attempts preceding this request. + * @param bool $blocked Whether native insertion must be prevented. + * @param int $final_count Expected count after the native request. + * @dataProvider dp_credentials_without_proof + */ + public function test_credentials_without_proof( bool $valid_password, int $seed_count, bool $blocked, int $final_count ): void { + $this->prepare_submission( $seed_count ); + + if ( ! $valid_password ) { + $this->data['password'] = 'incorrect-synthetic-password'; + } + + unset( $this->data['h-captcha-response'] ); + $result = $this->dispatch( $this->data ); + + if ( $blocked ) { + self::assertArrayHasKey( 'h-captcha-response', $result['errors'] ?? [], wp_json_encode( $result ) ); + self::assertSame( 0, $this->submission_count() ); + self::assertSame( [], $this->observed_counts ); + } else { + self::assertTrue( $result['success'] ?? false, wp_json_encode( $result ) ); + self::assertGreaterThan( 0, $result['data']['insert_id'] ); + self::assertSame( 1, $this->submission_count() ); + self::assertSame( + [ + 'before_insert' => $seed_count, + 'inserted' => 0, + ], + $this->observed_counts + ); + } + + self::assertSame( $final_count, $this->read_count() ); + } + + /** + * Credential and threshold boundary controls. + * + * @return array + */ + public function dp_credentials_without_proof(): array { + return [ + 'valid credentials above threshold' => [ true, 2, true, 2 ], + 'wrong credentials above threshold' => [ false, 2, true, 3 ], + 'valid credentials below threshold' => [ true, 1, false, 0 ], + 'wrong credentials reach threshold' => [ false, 1, true, 2 ], + ]; + } + + /** + * An accepted challenge resets the snapshot only after actual insertion. + */ + public function test_valid_proof_resets_after_native_insertion(): void { + $this->prepare_submission( 2 ); + $result = $this->dispatch( $this->data ); + + self::assertTrue( $result['success'] ?? false, wp_json_encode( $result ) ); + self::assertGreaterThan( 0, $result['data']['insert_id'] ); + self::assertSame( 1, $this->submission_count() ); + self::assertSame( + [ + 'before_insert' => 2, + 'inserted' => 0, + ], + $this->observed_counts + ); + self::assertSame( 0, $this->read_count() ); + } + + /** + * A global before-insert observer does not turn an ordinary form into a login. + * + * @param bool $valid_proof Whether the submitted challenge is valid. + * + * @dataProvider dp_ordinary_email_password_form + * @noinspection PhpUndefinedFieldInspection + */ + public function test_ordinary_email_password_form_requires_captcha( bool $valid_proof ): void { + $this->prepare_submission( 0, false ); + $this->set_protected_property( $this->adapter, 'form_id', (int) $this->form->id ); + $render = $this->set_method_accessibility( $this->adapter, 'get_hcaptcha' ); + + self::assertNotFalse( has_action( 'fluentform/before_insert_submission' ) ); + self::assertStringContainsString( 'invoke( $this->adapter ) ); + + if ( ! $valid_proof ) { + unset( $this->data['h-captcha-response'] ); + } + + $result = $this->dispatch( $this->data ); + + if ( $valid_proof ) { + self::assertTrue( $result['success'] ?? false, wp_json_encode( $result ) ); + self::assertSame( 1, $this->submission_count() ); + } else { + self::assertArrayHasKey( 'h-captcha-response', $result['errors'] ?? [], wp_json_encode( $result ) ); + self::assertSame( 0, $this->submission_count() ); + } + + self::assertSame( 0, $this->read_count() ); + } + + /** + * Ordinary form proof controls. + * + * @return array + */ + public function dp_ordinary_email_password_form(): array { + return [ + 'missing proof' => [ false ], + 'valid proof' => [ true ], + ]; + } + + /** + * Opting in one login form cannot exempt another saved form. + * + * @noinspection PhpUndefinedFieldInspection + */ + public function test_login_opt_in_is_scoped_to_form_id(): void { + $this->prepare_submission( 0 ); + $login_id = (int) $this->form->id; + $other_id = (int) $this->create_form()->id; + $render = $this->set_method_accessibility( $this->adapter, 'get_hcaptcha' ); + + $this->set_protected_property( $this->adapter, 'form_id', $login_id ); + self::assertSame( '', $render->invoke( $this->adapter ) ); + + $this->set_protected_property( $this->adapter, 'form_id', $other_id ); + self::assertStringContainsString( 'invoke( $this->adapter ) ); + } + + /** + * Native validation and late anti-spam failures preserve the captured record. + * + * @param string $failure The production guard that rejects the request. + * @param string $error Expected native error key or message fragment. + * + * @dataProvider dp_native_failure + * @noinspection PhpUndefinedFieldInspection + */ + public function test_failed_native_submission_retains_count( string $failure, string $error ): void { + $this->prepare_submission( 2 ); + + if ( 'challenge' === $failure ) { + add_filter( + 'pre_http_request', + static function ( $preempt, $args, $url ) { + return 'https://api.hcaptcha.com/siteverify' === $url + ? [ + 'body' => wp_json_encode( + [ + 'success' => false, + 'error-codes' => [ 'invalid-input-response' ], + ] + ), + ] + : $preempt; + }, + 11, + 3 + ); + } elseif ( 'widget' === $failure ) { + $this->data['hcaptcha-widget-id'] = HCaptcha::widget_id_value( + [ + 'source' => [ 'fluentformpro/fluentformpro.php', 'fluentform/fluentform.php' ], + 'form_id' => (int) $this->form->id + 1, + ] + ); + } elseif ( 'captcha_nonce' === $failure ) { + // The hCaptcha nonce contract applies to authenticated submissions only. + $user = get_user_by( 'email', $this->data['email'] ); + wp_set_current_user( $user->ID ); + $this->data[ '_fluentform_' . $this->form->id . '_fluentformnonce' ] = wp_create_nonce( 'fluentform-submit-form' ); + $this->data['hcaptcha_fluentform_nonce'] = 'invalid-captcha-nonce'; + } elseif ( 'required_name' === $failure ) { + unset( $this->data['name'] ); + } elseif ( 'native_nonce' === $failure ) { + $this->data[ '_fluentform_' . $this->form->id . '_fluentformnonce' ] = 'invalid-native-nonce'; + } elseif ( 'native_honeypot' === $failure ) { + $this->data[ 'item_' . $this->form->id . '__fluent_sf' ] = 'filled-honeypot'; + } elseif ( 'native_token' === $failure ) { + $this->data[ '__fluent_protection_token_' . $this->form->id ] = 'invalid-native-token'; + } else { + add_action( + 'fluentform/before_insert_submission', + static function () { + throw new ValidationException( '', 423, null, [ 'errors' => [ 'late_check' => [ 'Native late check rejected.' ] ] ] ); + }, + 20, + 0 + ); + } + + $result = $this->dispatch( $this->data ); + + self::assertStringContainsString( $error, wp_json_encode( $result['errors'] ?? [] ), wp_json_encode( $result ) ); + self::assertSame( 0, $this->submission_count() ); + self::assertArrayNotHasKey( 'inserted', $this->observed_counts ); + self::assertSame( 2, $this->read_count() ); + } + + /** + * Early validation, hCaptcha, and late native protection controls. + * + * @return array + */ + public function dp_native_failure(): array { + return [ + 'invalid challenge' => [ 'challenge', 'h-captcha-response' ], + 'foreign widget identity' => [ 'widget', 'h-captcha-response' ], + 'authenticated hCaptcha nonce' => [ 'captcha_nonce', 'h-captcha-response' ], + 'native required field' => [ 'required_name', 'name' ], + 'native nonce' => [ 'native_nonce', '_fluentformnonce' ], + 'native honeypot' => [ 'native_honeypot', 'can not submit' ], + 'native anti-spam token' => [ 'native_token', 'Suspicious activity' ], + 'late before-insert check' => [ 'late_check', 'late_check' ], + ]; + } + + /** + * Completing one valid request must retain a concurrently updated attempt record. + */ + public function test_concurrent_failure_survives_successful_insertion(): void { + $this->prepare_submission( 2 ); + add_action( + 'fluentform/before_insert_submission', + function () { + ( new LoginAttempts() )->increment( $this->address, time(), 15 * MINUTE_IN_SECONDS ); + }, + 10, + 0 + ); + $result = $this->dispatch( $this->data ); + + self::assertTrue( $result['success'] ?? false, wp_json_encode( $result ) ); + self::assertSame( 1, $this->submission_count() ); + self::assertSame( + [ + 'before_insert' => 3, + 'inserted' => 3, + ], + $this->observed_counts + ); + self::assertSame( 3, $this->read_count() ); + } + + /** + * A callback for a non-positive ID or another form cannot reset pending credentials. + * + * @param bool $foreign_form Whether a positive callback belongs to another form. + * @dataProvider dp_unrelated_completion + */ + public function test_unrelated_completion_does_not_reset_count( bool $foreign_form ): void { + $this->prepare_submission( 2 ); + $other_form = $foreign_form ? $this->create_form() : $this->form; + add_filter( + 'fluentform/validation_errors', + function ( $errors, $data ) use ( $foreign_form, $other_form ) { + // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- Exercise the installed native callback contract. + do_action( 'fluentform/submission_inserted', $foreign_form ? 12345 : 0, $data, $other_form ); + self::assertSame( 2, $this->read_count() ); + unset( $this->observed_counts['inserted'] ); + + return $errors; + }, + 11, + 3 + ); + $result = $this->dispatch( $this->data ); + + self::assertTrue( $result['success'] ?? false, wp_json_encode( $result ) ); + self::assertSame( + [ + 'before_insert' => 2, + 'inserted' => 0, + ], + $this->observed_counts + ); + self::assertSame( 0, $this->read_count() ); + } + + /** + * Native final-hook ownership controls. + * + * @return array + */ + public function dp_unrelated_completion(): array { + return [ + 'no insertion' => [ false ], + 'another form' => [ true ], + ]; + } + + /** + * The embedded native field must still reach the production challenge verifier. + * + * @param bool $valid_proof Whether the serialized native form contains a challenge. + * + * @dataProvider dp_embedded_hcaptcha + * @noinspection PhpDynamicFieldDeclarationInspection + * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpUndefinedFieldInspection + * @noinspection PhpUndefinedMethodInspection + */ + public function test_embedded_native_hcaptcha( bool $valid_proof ): void { + $this->prepare_submission( 2 ); + $schema = json_decode( $this->form->form_fields, true ); + $schema['fields'][] = [ + 'element' => 'hcaptcha', + 'settings' => [ 'label' => 'Native challenge' ], + ]; + $this->form->form_fields = wp_json_encode( $schema ); + $this->form->save(); + FormFieldsParser::resetData(); + $native_calls = 0; + $production_calls = 0; + add_filter( + 'pre_http_request', + static function ( $preempt, $args, $url ) use ( &$native_calls, &$production_calls ) { + if ( 'https://hcaptcha.com/siteverify' === $url ) { + ++$native_calls; + } elseif ( 'https://api.hcaptcha.com/siteverify' === $url ) { + ++$production_calls; + } + + return $preempt; + }, + 12, + 3 + ); + + if ( ! $valid_proof ) { + unset( $this->data['h-captcha-response'] ); + } + + $result = $this->dispatch( $this->data ); + + self::assertSame( 1, $native_calls ); + self::assertSame( $valid_proof ? 1 : 0, $production_calls ); + + if ( $valid_proof ) { + self::assertTrue( $result['success'] ?? false, wp_json_encode( $result ) ); + self::assertSame( 1, $this->submission_count() ); + self::assertSame( + [ + 'before_insert' => 2, + 'inserted' => 0, + ], + $this->observed_counts + ); + self::assertSame( 0, $this->read_count() ); + } else { + self::assertArrayHasKey( 'h-captcha-response', $result['errors'] ?? [], wp_json_encode( $result ) ); + self::assertSame( 0, $this->submission_count() ); + self::assertSame( 2, $this->read_count() ); + } + } + + /** + * Embedded native hCaptcha acceptance and missing-proof controls. + * + * @return array + */ + public function dp_embedded_hcaptcha(): array { + return [ + 'missing proof' => [ false ], + 'accepted proof' => [ true ], + ]; + } + + /** + * Build real schema, credentials, anti-spam inputs, and a pre-authentication snapshot. + * + * @param int $seed_count Failed login records preceding this request. + * @param bool $login_form Whether this synthetic form is an opted-in login. + * + * @noinspection DynamicInvocationViaScopeResolutionInspection + * @noinspection PhpUndefinedFieldInspection + */ + private function prepare_submission( int $seed_count, bool $login_form = true ): void { + update_option( + 'hcaptcha_settings', + [ + 'fluent_status' => [ 'form' ], + 'login_limit' => 2, + 'login_interval' => 15, + ] + ); + $this->prepare_verify_request( 'sec008-challenge' ); + $this->remove_integration_callbacks(); + $this->address = hcap_get_user_ip(); + $attempts = new LoginAttempts(); + + for ( $i = 0; $i < $seed_count; ++$i ) { + $attempts->increment( $this->address, time(), 15 * MINUTE_IN_SECONDS ); + } + + $this->adapter = new Form(); + $user_id = self::factory()->user->create( + [ + 'user_login' => 'sec008-native-reader', + 'user_email' => 'sec008-native-reader@example.com', + 'user_pass' => 'sec008-synthetic-password', + ] + ); + $this->form = $this->create_form(); + + if ( $login_form ) { + add_filter( + 'hcap_fluentform_is_login_form', + function ( $is_login_form, int $form_id ): bool { + return (int) $this->form->id === $form_id; + }, + 10, + 2 + ); + } + + $this->data = [ + 'email' => get_userdata( $user_id )->user_email, + 'password' => 'sec008-synthetic-password', + 'name' => 'Native reader', + '_wp_http_referer' => home_url( '/sec008-native-form/' ), + 'h-captcha-response' => 'sec008-challenge', + 'hcaptcha-widget-id' => HCaptcha::widget_id_value( + [ + 'source' => [ 'fluentformpro/fluentformpro.php', 'fluentform/fluentform.php' ], + 'form_id' => (int) $this->form->id, + ] + ), + 'hcaptcha_fluentform_nonce' => wp_create_nonce( 'hcaptcha_fluentform' ), + 'hcap_hp_test' => '', + 'hcap_hp_sig' => wp_create_nonce( 'hcap_hp_test' ), + 'hcap_fst_token' => 'test_token', + ]; + $this->data[ '_fluentform_' . $this->form->id . '_fluentformnonce' ] = wp_create_nonce( 'fluentform-submit-form' ); + $this->data[ 'item_' . $this->form->id . '__fluent_sf' ] = ''; + $this->data += $this->issue_native_token(); + add_action( + 'fluentform/before_insert_submission', + function () { + $this->observed_counts['before_insert'] = $this->read_count(); + }, + 11, + 0 + ); + add_action( + 'fluentform/submission_inserted', + function () { + $this->observed_counts['inserted'] = $this->read_count(); + }, + PHP_INT_MAX, + 0 + ); + self::assertSame( $seed_count, $this->read_count() ); + self::assertNotFalse( has_action( 'wp_ajax_nopriv_fluentform_submit' ) ); + } + + /** + * Remove prior production instances so the seeded snapshot owns this request. + */ + private function remove_integration_callbacks(): void { + global $wp_filter; + + foreach ( $wp_filter as $hook => $registered ) { + foreach ( $registered->callbacks as $priority => $callbacks ) { + foreach ( $callbacks as $callback ) { + $function = $callback['function']; + + if ( is_array( $function ) && $function[0] instanceof Form ) { + remove_filter( $hook, $function, $priority ); + } + } + } + } + } + + /** + * Issue the enabled native anti-spam token through its nonce-guarded endpoint. + * + * @return array + * @noinspection PhpUndefinedFieldInspection + * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + private function issue_native_token(): array { + $_POST = [ + 'nonce' => wp_create_nonce( 'fluentform_generate_token_nonce' ), + 'form_id' => $this->form->id, + ]; + ob_start(); + + try { + ( new TokenBasedSpamProtection( App::getInstance() ) )->ajaxGenerateToken(); + } catch ( RuntimeException $exception ) { + self::assertSame( 'SEC008 native JSON completed.', $exception->getMessage() ); + } + + $response = json_decode( ob_get_clean(), true ); + self::assertTrue( $response['success'] ?? false, wp_json_encode( $response ) ); + + return [ '__fluent_protection_token_' . $this->form->id => $response['data']['token'] ]; + } + + /** + * Run the actual public native AJAX action, including parser and insert lifecycle. + * + * @param array $data Submitted native form fields. + * + * @return array + * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpConditionAlreadyCheckedInspection + * @noinspection PhpUndefinedFieldInspection + */ + private function dispatch( array $data ): array { + global $wp_current_filter; + + $_POST = [ + 'action' => 'fluentform_submit', + 'form_id' => (int) $this->form->id, + 'data' => http_build_query( $data ), + ]; + $app = App::getInstance(); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Native dispatch validates the real submitted nonce. + $app['request'] = new Request( $app, [], $_POST ); + $current_filters = $wp_current_filter; + FormFieldsParser::resetData(); + ob_start(); + + try { + do_action( is_user_logged_in() ? 'wp_ajax_fluentform_submit' : 'wp_ajax_nopriv_fluentform_submit' ); + } catch ( RuntimeException $exception ) { + self::assertSame( 'SEC008 native JSON completed.', $exception->getMessage() ); + } finally { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Native JSON stops its action before WordPress pops the stack. + $wp_current_filter = $current_filters; + } + + return (array) json_decode( ob_get_clean(), true ); + } + + /** + * Create a native saved login-shaped schema with real required-field validation. + * + * @return FluentForm + * @noinspection PhpIncompatibleReturnTypeInspection + * @noinspection PhpUndefinedMethodInspection + */ + private function create_form(): FluentForm { + $fields = []; + + foreach ( [ + 'email' => 'email', + 'password' => 'password', + 'name' => 'text', + ] as $name => $type ) { + $fields[] = [ + 'element' => 'input_' . $type, + 'attributes' => [ + 'type' => $type, + 'name' => $name, + 'value' => '', + 'id' => '', + 'class' => '', + 'placeholder' => $name, + ], + 'settings' => [ + 'container_class' => '', + 'label' => $name, + 'label_placement' => '', + 'help_message' => '', + 'validation_rules' => [ + 'required' => [ + 'value' => true, + 'message' => 'This field is required', + ], + ], + 'conditional_logics' => [], + ], + 'editor_options' => [ + 'title' => $name, + 'template' => 'inputText', + ], + ]; + } + + $form = FluentForm::create( + FluentForm::prepare( + [ + 'title' => 'SEC008 native credential form', + 'status' => 'published', + 'form_fields' => wp_json_encode( + [ + 'fields' => $fields, + 'submitButton' => [ + 'element' => 'button', + 'attributes' => [ + 'type' => 'submit', + 'class' => '', + ], + 'settings' => [ + 'button_ui' => [ + 'type' => 'default', + 'text' => 'Submit', + ], + ], + ], + ] + ), + 'type' => 'form', + ] + ) + ); + FormMeta::persist( $form->id, 'formSettings', FluentForm::getFormsDefaultSettings() ); + + return FluentForm::find( $form->id ); + } + + /** + * Count actual native rows for this saved form. + * + * @return int + * @noinspection PhpUndefinedFieldInspection + */ + private function submission_count(): int { + return Submission::where( 'form_id', $this->form->id )->count(); + } + + /** + * Read the production store without mocking its threshold or reset behavior. + * + * @return int + */ + private function read_count(): int { + return ( new LoginAttempts() )->read( $this->address, time() ); + } +} diff --git a/tests/php/integration/FluentForm/FormTest.php b/tests/php/integration/FluentForm/FormTest.php index 267bff73a..4e29b7c75 100644 --- a/tests/php/integration/FluentForm/FormTest.php +++ b/tests/php/integration/FluentForm/FormTest.php @@ -22,7 +22,6 @@ use ReflectionClass; use ReflectionException; use stdClass; -use WP_User; /** * Test FluentForm. @@ -50,6 +49,8 @@ class FormTest extends HCaptchaPluginWPTestCase { /** * Test rendering through the live Fluent Forms model and shortcode. + * + * @noinspection PhpUndefinedFieldInspection */ public function test_live_form_render(): void { update_option( 'hcaptcha_settings', [ 'fluent_status' => [ 'form' ] ] ); @@ -93,6 +94,10 @@ public function test_constructor_and_init_hooks(): void { 10, has_action( 'fluentform/validation_errors', [ $subject, 'verify' ] ) ); + self::assertSame( + 10, + has_action( 'fluentform/submission_inserted', [ $subject, 'submission_inserted' ] ) + ); self::assertSame( 10, has_filter( 'fluentform/rendering_form', [ $subject, 'fluentform_rendering_form_filter' ] ) @@ -163,6 +168,7 @@ public function test_pre_option(): void { * * @return void * @throws ReflectionException ReflectionException. + * @noinspection PhpUndefinedFieldInspection */ public function test_render_field_hcaptcha(): void { $live_form = $this->create_fluent_form(); @@ -200,6 +206,8 @@ class='ff-el-hcaptcha h-captcha'> /** * Test add_hcaptcha(). + * + * @noinspection PhpUndefinedFieldInspection */ public function test_add_hcaptcha(): void { hcaptcha()->init_hooks(); @@ -247,6 +255,9 @@ public function test_add_captcha_with_own_captcha(): void { * * @return void * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpArrayIndexImmediatelyRewrittenInspection + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection PhpUndefinedFieldInspection */ public function test_verify(): void { $errors = [ @@ -363,6 +374,10 @@ public function test_verify(): void { * * @return void * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpArrayIndexImmediatelyRewrittenInspection + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection PhpUnusedLocalVariableInspection + * @noinspection PhpUndefinedFieldInspection */ public function test_verify_not_verified(): void { $errors = [ @@ -421,6 +436,9 @@ public function test_verify_not_verified(): void { * * @return void * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection PhpUnusedLocalVariableInspection + * @noinspection PhpUndefinedFieldInspection */ public function test_verify_missing_widget_id(): void { $errors = [ @@ -474,6 +492,10 @@ public function test_verify_missing_widget_id(): void { * @return void * @noinspection PhpUnusedParameterInspection * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpArrayIndexImmediatelyRewrittenInspection + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection PhpUnusedLocalVariableInspection + * @noinspection PhpUndefinedFieldInspection */ public function test_verify_multi_step_not_verified(): void { $errors = [ @@ -566,6 +588,9 @@ static function ( $name ) use ( &$die_arr ) { * @dataProvider dp_test_verify_login_form * @noinspection PhpUnusedParameterInspection * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpUnusedLocalVariableInspection + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection PhpUndefinedFieldInspection */ public function test_verify_login_form( bool $password_ok, bool $is_login_limit_exceeded ): void { $errors = [ @@ -621,7 +646,8 @@ static function ( $name ) use ( &$die_arr ) { $mock->shouldReceive( 'is_login_limit_exceeded' )->with()->andReturn( $is_login_limit_exceeded ); if ( $password_ok ) { - $mock->shouldReceive( 'login' )->with( $email, Mockery::type( WP_User::class ) )->once(); + // Successful credentials cannot reset failures while native validation still has errors. + $mock->shouldReceive( 'login' )->never(); } else { $mock->shouldReceive( 'login_failed' )->with( $email )->once(); } @@ -717,6 +743,9 @@ public function test_print_hcaptcha_scripts(): void { * @throws ReflectionException ReflectionException. * @noinspection ES6ConvertVarToLetConst * @noinspection JsonEncodingApiUsageInspection + * @noinspection PhpUnusedLocalVariableInspection + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection PhpUndefinedFieldInspection */ public function test_print_footer_scripts(): void { global $wp_scripts; @@ -806,6 +835,27 @@ public function test_print_footer_scripts(): void { self::assertFalse( wp_script_is( $fluent_forms_conversational_script, 'registered' ) ); } + /** + * Print footer scripts only for a shown form, without conversational extras. + */ + public function test_print_footer_scripts_without_conversational_form(): void { + $handle = 'hcaptcha-fluentform'; + $subject = new Form(); + + wp_dequeue_script( $handle ); + wp_deregister_script( $handle ); + + $subject->print_footer_scripts(); + self::assertFalse( wp_script_is( $handle, 'registered' ) ); + + $this->set_protected_property( $subject, 'form_shown', true ); + + ob_start(); + $subject->print_footer_scripts(); + self::assertSame( '', ob_get_clean() ); + self::assertTrue( wp_script_is( $handle, 'registered' ) ); + } + /** * Test admin_enqueue_scripts(). * @@ -1031,6 +1081,7 @@ public function dp_has_own_hcaptcha(): array { * * @return void * @throws ReflectionException ReflectionException. + * @noinspection PhpUndefinedFieldInspection */ public function test_get_hcaptcha(): void { $form = $this->create_fluent_form(); @@ -1077,6 +1128,8 @@ public function test_get_hcaptcha_for_login_form(): void { * @param bool $multi_step Whether to make the form multi-step. * * @return FluentForm + * @noinspection PhpUndefinedMethodInspection + * @noinspection PhpIncompatibleReturnTypeInspection */ private function create_fluent_form( array $fields = [], bool $multi_step = false ): FluentForm { $fields = $fields ?: [ @@ -1186,6 +1239,7 @@ private function get_get_hcaptcha_wrapped( int $form_id ): string { * @param array $id Widget id. * * @return string + * @noinspection PhpSameParameterValueInspection */ private function get_widget_id( int $form_id, array $id = [] ): string { $id = $id ?: [ @@ -1214,4 +1268,163 @@ private function get_hcaptcha( int $form_id ): string { return HCaptcha::form( $args ); } + /** + * Apply email policy to trusted custom email inputs before native submission. + * + * @param bool $blocked Whether the trusted email is disposable. + * + * @dataProvider dp_sec063_email_policy + * @noinspection PhpUndefinedFieldInspection + */ + public function test_sec063_typed_email_policy( bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $form = $this->create_fluent_form( + [ + [ + 'element' => 'input_email', + 'attributes' => [ + 'name' => 'billing_address', + 'type' => 'email', + ], + ], + [ + 'element' => 'input_email', + 'attributes' => [ + 'name' => 'contact_address', + 'type' => 'email', + ], + ], + [ + 'element' => 'input_text', + 'attributes' => [ + 'name' => 'email', + 'type' => 'text', + ], + ], + ] + ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = $this->get_widget_id( (int) $form->id ); + $data = [ + 'billing_address' => $blocked ? 'person@sec063-disposable.test' : 'person@example.com', + 'contact_address' => 'reader@example.com', + 'email' => 'spoof@sec063-disposable.test', + ]; + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $_POST['data'] = http_build_query( array_merge( $_POST, $data ) ); + $subject = new Form(); + + self::assertSame( + $blocked ? [ 'h-captcha-response' => [ 'Please use a permanent email address.' ] ] : [], + $subject->verify( [], $data, $form, [] ) + ); + } + /** + * Exercise both policy rejection and permanent address acceptance. + * + * @return array + */ + public function dp_sec063_email_policy(): array { + return [ + 'disposable' => [ true ], + 'permanent' => [ false ], + ]; + } + + /** + * Apply email policy through native container and composite field accessors. + * + * @param string $shape Native schema shape. + * @param bool $blocked Whether the accepted address is disposable. + * + * @dataProvider dp_sec063_native_shapes + * @noinspection PhpUndefinedFieldInspection + */ + public function test_sec063_native_email_shapes( string $shape, bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $email_field = [ + 'element' => 'input_email', + 'attributes' => [ + 'name' => 'contact_address', + 'type' => 'email', + ], + ]; + $address = $blocked ? 'person@sec063-disposable.test' : 'reader@example.com'; + $data = [ + 'contact_address' => $address, + 'email' => 'spoof@sec063-disposable.test', + ]; + + if ( 'container' === $shape ) { + $fields = [ + [ + 'element' => 'container', + 'columns' => [ [ 'fields' => [ $email_field ] ] ], + ], + ]; + } elseif ( 'composite' === $shape ) { + $email_field['attributes']['name'] = 'address'; + $email_field['settings']['visible'] = true; + $fields = [ + [ + 'element' => 'input_name', + 'attributes' => [ 'name' => 'contact' ], + 'fields' => [ $email_field ], + ], + ]; + $data = [ + 'contact' => [ 'address' => $address ], + 'email' => 'spoof@sec063-disposable.test', + ]; + } else { + $fields = [ + [ + 'element' => 'input_repeat', + 'attributes' => [ 'name' => 'recipients' ], + 'fields' => [ $email_field ], + ], + ]; + $data = [ + 'recipients' => [ [ 'primary@example.com', $address ] ], + 'email' => 'spoof@sec063-disposable.test', + ]; + } + + $fields[] = [ + 'element' => 'input_text', + 'attributes' => [ + 'name' => 'email', + 'type' => 'text', + ], + ]; + $form = $this->create_fluent_form( $fields ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = $this->get_widget_id( (int) $form->id ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $_POST['data'] = http_build_query( array_merge( $_POST, $data ) ); + $subject = new Form(); + + self::assertSame( + $blocked ? [ 'h-captcha-response' => [ 'Please use a permanent email address.' ] ] : [], + $subject->verify( [], $data, $form, [] ) + ); + } + + /** + * Native field shapes and block/allow controls. + * + * @return array + */ + public function dp_sec063_native_shapes(): array { + return [ + 'container blocked' => [ 'container', true ], + 'container allowed' => [ 'container', false ], + 'composite blocked' => [ 'composite', true ], + 'composite allowed' => [ 'composite', false ], + 'repeat blocked' => [ 'repeat', true ], + 'repeat allowed' => [ 'repeat', false ], + ]; + } } diff --git a/tests/php/integration/Formidable/FormTest.php b/tests/php/integration/Formidable/FormTest.php index 24d3bd402..57f79c626 100644 --- a/tests/php/integration/Formidable/FormTest.php +++ b/tests/php/integration/Formidable/FormTest.php @@ -12,7 +12,13 @@ namespace HCaptcha\Tests\Integration\Formidable; +use FrmAppController; +use FrmAppHelper; +use FrmField; +use FrmFieldsHelper; +use FrmForm; use FrmSettings; +use HCaptcha\AntiSpam\DisposableEmail; use HCaptcha\FormidableForms\Form; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; @@ -59,7 +65,7 @@ class FormTest extends HCaptchaPluginWPTestCase { public function test_live_form_render(): void { global $frm_settings, $wpdb; - $settings = \FrmAppHelper::get_settings(); + $settings = FrmAppHelper::get_settings(); $settings->active_captcha = 'hcaptcha'; $settings->store(); @@ -68,17 +74,17 @@ public function test_live_form_render(): void { $form_id = $this->create_formidable_form(); - $name_field = \FrmFieldsHelper::setup_new_vars( 'text', $form_id ); + $name_field = FrmFieldsHelper::setup_new_vars( 'text', $form_id ); $name_field['name'] = 'Name'; - self::assertIsInt( \FrmField::create( $name_field ), $wpdb->last_error ); + self::assertIsInt( FrmField::create( $name_field ), $wpdb->last_error ); - $captcha_field = \FrmFieldsHelper::setup_new_vars( 'captcha', $form_id ); + $captcha_field = FrmFieldsHelper::setup_new_vars( 'captcha', $form_id ); $captcha_field['name'] = 'Captcha'; - self::assertIsInt( \FrmField::create( $captcha_field ), $wpdb->last_error ); + self::assertIsInt( FrmField::create( $captcha_field ), $wpdb->last_error ); - $model_file = wp_normalize_path( ( new ReflectionClass( \FrmForm::class ) )->getFileName() ); + $model_file = wp_normalize_path( ( new ReflectionClass( FrmForm::class ) )->getFileName() ); $html = do_shortcode( '[formidable id="' . $form_id . '"]' ); self::assertTrue( is_plugin_active( static::$plugin ) ); @@ -192,7 +198,7 @@ public function test_add_hcaptcha(): void { $html = str_replace( $hcaptcha_div, '', $html_with_hcaptcha ); $field = [ 'type' => 'some' ]; $atts = [ 'form' => (object) [ 'id' => $form_id ] ]; - $frm_settings = \FrmAppHelper::get_settings(); + $frm_settings = FrmAppHelper::get_settings(); $frm_settings->active_captcha = 'recaptcha'; $expected = str_replace( $hcaptcha_div, $hcap_form, $html_with_hcaptcha ); @@ -213,6 +219,13 @@ public function test_add_hcaptcha(): void { // Success path. self::assertSame( $expected, $subject->add_hcaptcha( $html_with_hcaptcha, $field, $atts ) ); + + // A label set to "None" leaves the field container and widget on the same line. + $container_start = '
      '; + $inline_html = $container_start . $hcaptcha_div . '
      '; + $inline_expected = $container_start . $hcap_form . '
      '; + + self::assertSame( $inline_expected, $subject->add_hcaptcha( $inline_html, $field, $atts ) ); } /** @@ -228,7 +241,7 @@ public function test_prevent_native_validation(): void { 'type' => 'some', ]; $post = [ 'some past data' ]; - $frm_settings = \FrmAppHelper::get_settings(); + $frm_settings = FrmAppHelper::get_settings(); $frm_settings->active_captcha = 'recaptcha'; $subject = Mockery::mock( Form::class )->makePartial(); @@ -251,6 +264,7 @@ public function test_prevent_native_validation(): void { * Test verify() with a bad response. * * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection */ public function test_verify_no_success(): void { $form_id = $this->create_formidable_form(); @@ -329,6 +343,11 @@ public function test_verify(): void { $empty_field->type = 'text'; $empty_field->name = 'Phone'; + $sensitive_field = new stdClass(); + $sensitive_field->id = 14; + $sensitive_field->type = 'password'; + $sensitive_field->name = 'Password'; + $values = [ 'h-captcha-response' => 'some-token', 'form_id' => $form_id, @@ -337,11 +356,12 @@ public function test_verify(): void { 11 => 'john@doe.com', 12 => 'Hello World', 13 => '', + 14 => 'secret', ], ]; $validate_args = [ - 'posted_fields' => [ $name_field, $email_field, $text_field, $empty_field ], + 'posted_fields' => [ $name_field, $email_field, $text_field, $empty_field, $sensitive_field ], ]; $this->prepare_verify( @@ -354,6 +374,55 @@ public function test_verify(): void { self::assertSame( $errors, $subject->verify( $errors, $values, $validate_args ) ); } + /** + * The canonical email matches the value accepted by native field validation. + * + * @dataProvider dp_test_email_normalization_policy + * + * @param mixed $submitted Submitted email value. + * @param string $expected Native normalized address. + * @param bool $blocked Whether the domain is disposable. + */ + public function test_email_normalization_policy( $submitted, string $expected, bool $blocked ): void { + $field = (object) [ + 'id' => 11, + 'type' => 'email', + 'name' => 'Email', + ]; + $subject = new Form(); + $data = $this->set_method_accessibility( $subject, 'get_data' )->invoke( + $subject, + [ $field ], + [ 'item_meta' => [ 11 => $submitted ] ] + ); + + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + add_filter( 'pre_transient_hcaptcha_disposable_email_blocklist', '__return_empty_array' ); + + self::assertSame( $expected, $data['email'] ); + self::assertSame( $expected, $data['Email'] ); + self::assertSame( $blocked, ( new DisposableEmail() )->is_disposable_email( $data['email'] ) ); + } + + /** + * Email inputs accepted by the native Formidable field validator. + * + * @return array + */ + public function dp_test_email_normalization_policy(): array { + return [ + 'plain blocked' => [ 'user@disposable.example', 'user@disposable.example', true ], + 'outer spaces' => [ ' user@disposable.example ', 'user@disposable.example', true ], + 'singleton array with spaces' => [ [ ' user@disposable.example ' ], 'user@disposable.example', true ], + 'allowed address' => [ ' safe@example.com ', 'safe@example.com', false ], + ]; + } + /** * Test verify() when widget id is missing. * @@ -497,11 +566,12 @@ public function test_is_formidable_forms_admin_page(): void { * Create a form through the live Formidable Forms model. * * @return int + * @noinspection PhpRedundantOptionalArgumentInspection */ private function create_formidable_form(): int { - \FrmAppController::install(); + FrmAppController::install(); - $form_id = \FrmForm::create( + $form_id = FrmForm::create( [ 'form_key' => uniqid( 'hcaptcha-form-', false ), 'name' => 'hCaptcha integration form', diff --git a/tests/php/integration/Forminator/FormTest.php b/tests/php/integration/Forminator/FormTest.php index cc497d4a1..ecbb800f0 100644 --- a/tests/php/integration/Forminator/FormTest.php +++ b/tests/php/integration/Forminator/FormTest.php @@ -47,7 +47,8 @@ class FormTest extends HCaptchaPluginWPTestCase { /** * Test rendering through the live Forminator API and frontend renderer. - */ + * + * @noinspection PhpUndefinedFunctionInspection*/ public function test_live_form_render(): void { $api_file = wp_normalize_path( ( new ReflectionClass( Forminator_API::class ) )->getFileName() ); @@ -160,18 +161,17 @@ public function test_add_hcaptcha(): void { ] ); $html = '
      Some content
      '; - $button = 'Some button'; $expected = str_replace( ''; + $output = $subject->do_shortcode_tag( $html, 'passster', [], [] ); + break; + case 'paypal-button': + $output = $this->capture_output( [ $subject, 'add_captcha' ] ); + break; + case 'paypal-cart-block': + $output = $subject->add_block_captcha( '
      Cart express payment
      ' ); + break; + case 'back-in-stock': + $output = $this->capture_output( + static function () use ( $subject ): void { + $subject->after_email_field( 0, 0 ); + echo '
      '; + $subject->after_submit_button( 0, 0 ); + } + ); + break; + default: + $output = $subject->add_checkout_block_captcha( '
      Checkout express payment
      ' ); + } + + $this->assert_challenge( $output, $nonce_name, $action ); + self::assertContains( + [ + 'source' => HCaptcha::get_class_source( $class_name ), + 'form_id' => $form_id, + ], + $this->protection_checks + ); + } + + /** + * Unbound handlers and the native markup each consumes. + * + * @return array + */ + public function dp_test_native_unbound_renderer(): array { + return [ + 'Asgaros forum' => [ 'asgaros', AsgarosForm::class, 7, 'hcaptcha_asgaros_new_topic_nonce', 'hcaptcha_asgaros_new_topic' ], + 'Passster unlock' => [ 'passster', Protect::class, '3866', 'hcaptcha_passster_nonce', 'hcaptcha_passster' ], + 'PayPal classic button' => [ 'paypal-button', Button::class, 'paypal_button', 'hcaptcha_woocommerce_paypal_payments_nonce', 'hcaptcha_woocommerce_paypal_payments' ], + 'PayPal cart block' => [ 'paypal-cart-block', Button::class, 'express_payment_block', 'hcaptcha_woocommerce_paypal_payments_nonce', 'hcaptcha_woocommerce_paypal_payments' ], + 'PayPal checkout own block' => [ 'paypal-checkout-block', Button::class, 'express_payment_block', 'hcaptcha_woocommerce_paypal_payments_nonce', 'hcaptcha_woocommerce_paypal_payments' ], + 'Back In Stock without product id' => [ 'back-in-stock', BackInStockForm::class, 0, 'hcaptcha_back_in_stock_notifier_nonce', 'hcaptcha_back_in_stock_notifier' ], + ]; + } + + /** + * An Icegram widget can honor exemptions only when it has a native form id. + * + * @param int $form_id Native form ID, or zero when absent from widget markup. + * + * @dataProvider dp_test_icegram_widget + * + * @throws ReflectionException Reflection exception. + */ + public function test_icegram_widget( int $form_id ): void { + $subject = ( new ReflectionClass( IcegramForm::class ) )->newInstanceWithoutConstructor(); + $this->set_protected_property( $subject, 'in_widget', true ); + $html = ''; + + $output = $this->capture_output( + static function () use ( $subject, $html ): void { + ob_start(); + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Native widget markup supplied to the renderer. + echo $html; + $subject->dynamic_sidebar_after( 1, true ); + } + ); + + if ( 0 === $form_id ) { + $this->assert_challenge( $output, 'hcaptcha_icegram_express_nonce', 'hcaptcha_icegram_express' ); + } else { + self::assertStringNotContainsString( ' HCaptcha::get_class_source( IcegramForm::class ), + 'form_id' => $form_id, + ], + $this->protection_checks + ); + } + + /** + * Bound and unbound Icegram widget markup. + * + * @return array + */ + public function dp_test_icegram_widget(): array { + return [ + 'missing form id' => [ 0 ], + 'known form id' => [ 17 ], + ]; + } + + /** + * The shared Checkout widget remains available only for an enabled PayPal handler. + * + * @param bool $paypal_enabled PayPal button protection is enabled. + * @param bool $block Render the Checkout block instead of the classic form. + * + * @dataProvider dp_test_shared_checkout_challenge + * + * @throws ReflectionException Reflection exception. + */ + public function test_shared_checkout_challenge( bool $paypal_enabled, bool $block ): void { + hcaptcha()->settings()->set( 'woocommerce_status', [ 'checkout' ] ); + hcaptcha()->settings()->set( 'paypal_payments_status', $paypal_enabled ? [ 'button' ] : [] ); + $button = $paypal_enabled ? new Button() : null; + $subject = ( new ReflectionClass( Checkout::class ) )->newInstanceWithoutConstructor(); + + if ( $block ) { + $parsed = [ + 'blockName' => 'woocommerce/checkout', + 'attrs' => [], + ]; + $output = $subject->add_block_captcha( + '
      ', + $parsed, + new WP_Block( $parsed ) + ); + } else { + $output = $this->capture_output( [ $subject, 'add_captcha' ] ); + } + + if ( $paypal_enabled ) { + $this->assert_challenge( $output, Checkout::NONCE, Checkout::ACTION ); + } else { + self::assertStringNotContainsString( ' 'unrelated_rendering', + 'name' => 'unrelated_rendering_nonce', + 'id' => [ + 'source' => HCaptcha::get_class_source( Checkout::class ), + 'form_id' => 'register', + ], + ] + ); + self::assertStringNotContainsString( ' [ true, false ], + 'Checkout block with PayPal' => [ true, true ], + 'classic Checkout without PayPal' => [ false, false ], + 'Checkout block without PayPal' => [ false, true ], + ]; + } + + /** + * Assert the rendered challenge includes a valid native nonce and signed identity. + * + * @param string $output Rendered native form. + * @param string $nonce_name Nonce field name. + * @param string $action Nonce action. + */ + private function assert_challenge( string $output, string $nonce_name, string $action ): void { + self::assertStringContainsString( ' $level ) { + ob_end_clean(); + } + } + } +} diff --git a/tests/php/integration/IcegramExpress/FormTest.php b/tests/php/integration/IcegramExpress/FormTest.php index 46bef32e5..c9333b6ca 100644 --- a/tests/php/integration/IcegramExpress/FormTest.php +++ b/tests/php/integration/IcegramExpress/FormTest.php @@ -5,11 +5,18 @@ * @package HCaptcha\Tests */ +// phpcs:ignore Generic.Commenting.DocComment.MissingShort +/** @noinspection PhpUndefinedClassInspection */ + namespace HCaptcha\Tests\Integration\IcegramExpress; +use ES_Form_Widget; use HCaptcha\Helpers\HCaptcha; use HCaptcha\IcegramExpress\Form; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; +use Mockery; +use stdClass; +use tad\FunctionMocker\FunctionMocker; /** * Test the Icegram Express form integration. @@ -17,6 +24,13 @@ * @group icegram-express */ class FormTest extends HCaptchaWPTestCase { + /** + * Plugin basenames used to detect Icegram Express editions. + */ + private const PLUGIN_BASENAMES = [ + 'email-subscribers-premium/email-subscribers-premium.php', + 'email-subscribers/email-subscribers.php', + ]; /** * Set up the test. @@ -28,10 +42,149 @@ public function setUp(): void { hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); - hcaptcha()->settings()->set( 'icegram_express_status', 'form' ); + hcaptcha()->settings()->set( 'icegram_express_status', [ 'form' ] ); $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } + /** + * Remove frontend script state between form rendering tests. + */ + public function tearDown(): void { + wp_dequeue_script( 'hcaptcha-icegram-express' ); + wp_deregister_script( 'hcaptcha-icegram-express' ); + + parent::tearDown(); + } + + /** + * Other shortcodes and failed native validation are left unchanged. + */ + public function test_unrelated_shortcode_and_native_error(): void { + $subject = new Form(); + self::assertSame( 'original', $subject->add_hcaptcha( 'original', 'other', [], [] ) ); + self::assertSame( [ 'status' => 'ERROR' ], $subject->verify( [ 'status' => 'ERROR' ], [] ) ); + } + + /** + * The native sidebar widget receives hCaptcha inside its ordinary form. + * + * @noinspection PhpUndefinedClassInspection + */ + public function test_native_sidebar_widget_rendering(): void { + $subject = new Form(); + $widget = Mockery::mock( ES_Form_Widget::class ); + $subject->dynamic_sidebar( [ 'callback' => [ new stdClass(), 'display_callback' ] ] ); + $subject->dynamic_sidebar_after( 'sidebar-1', true ); + $level = ob_get_level(); + + ob_start(); + $subject->dynamic_sidebar( [ 'callback' => [ $widget, 'display_callback' ] ] ); + self::assertSame( $level + 2, ob_get_level() ); + echo '
      '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Test fixture. + $subject->dynamic_sidebar_after( 'sidebar-1', true ); + $output = ob_get_clean(); + + self::assertSame( $level, ob_get_level() ); + self::assertStringContainsString( 'h-captcha', $output ); + } + + /** + * Default arguments and inline styling support generic subscription forms. + */ + public function test_generic_form_arguments_and_styles(): void { + $subject = new Form(); + $method = $this->set_method_accessibility( $subject, 'get_args' ); + $args = $method->invoke( $subject, 0 ); + self::assertTrue( $args['mandatory'] ); + self::assertSame( 0, $args['id']['form_id'] ); + + ob_start(); + $subject->print_inline_styles(); + self::assertStringContainsString( '.emaillist .h-captcha', ob_get_clean() ); + } + + /** + * A shortcode without a stored Icegram form uses the ordinary inline widget. + */ + public function test_shortcode_without_stored_form(): void { + $forms_db = Mockery::mock(); + $forms_db->shouldReceive( 'get_form_by_id' )->with( 3 )->andReturn( null ); + $service = (object) [ 'forms_db' => $forms_db ]; + FunctionMocker::replace( + '\HCaptcha\IcegramExpress\ES', + static function () use ( $service ) { + return $service; + } + ); + + $markup = '
      '; + $output = ( new Form() )->add_hcaptcha( $markup, 'email-subscribers-form', [ 'id' => 3 ], [] ); + + self::assertStringContainsString( 'h-captcha', $output ); + } + + /** + * Popup forms defer their hCaptcha markup to the frontend script. + */ + public function test_popup_shortcode_defers_hcaptcha(): void { + $forms_db = Mockery::mock(); + $forms_db->shouldReceive( 'get_form_by_id' )->with( 3 )->andReturn( (object) [ 'id' => 3 ] ); + $service = (object) [ 'forms_db' => $forms_db ]; + FunctionMocker::replace( + '\HCaptcha\IcegramExpress\ES', + static function () use ( $service ) { + return $service; + } + ); + Mockery::mock( 'alias:ES_Forms_Table' ) + ->shouldReceive( 'get_form_data_from_body' ) + ->andReturn( [ 'show_in_popup' => 'yes' ] ); + + $subject = new Form(); + $markup = '
      '; + self::assertSame( $markup, $subject->add_hcaptcha( $markup, 'email-subscribers-form', [ 'id' => 3 ], [] ) ); + ob_start(); + $subject->print_footer_scripts(); + $output = ob_get_clean(); + self::assertStringContainsString( 'hCaptchaWidgets', $output ); + } + + /** + * Test that both editions are recognized. + * + * @param string $plugin Plugin basename. + * + * @dataProvider dp_test_detects_icegram_variants + */ + public function test_detects_icegram_variants( string $plugin ): void { + self::assertSame( self::PLUGIN_BASENAMES, hcaptcha()->modules['Icegram Express'][1] ); + self::assertSame( self::PLUGIN_BASENAMES, HCaptcha::get_class_source( Form::class ) ); + + $filter = static function () use ( $plugin ): array { + return [ $plugin ]; + }; + + add_filter( 'pre_option_active_plugins', $filter ); + + try { + self::assertTrue( hcaptcha()->plugin_or_theme_active( self::PLUGIN_BASENAMES ) ); + } finally { + remove_filter( 'pre_option_active_plugins', $filter ); + } + } + + /** + * Icegram Express plugin basenames. + * + * @return array + */ + public function dp_test_detects_icegram_variants(): array { + return [ + 'Max' => [ self::PLUGIN_BASENAMES[0] ], + 'Free' => [ self::PLUGIN_BASENAMES[1] ], + ]; + } + /** * Test a filled honeypot blocks subscription validation. * @@ -42,13 +195,13 @@ public function test_filled_honeypot_is_rejected(): void { $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( [ - 'source' => [ 'email-subscribers/email-subscribers.php' ], + 'source' => self::PLUGIN_BASENAMES, 'form_id' => 1, ] ); $_POST['hcap_hp_test'] = 'bot'; - $result = ( new Form() )->verify( [ 'status' => 'SUCCESS' ], [] ); + $result = ( new Form() )->verify( [ 'status' => 'SUCCESS' ], [ 'esfpx_form_id' => '1' ] ); self::assertSame( [ @@ -63,6 +216,106 @@ public function test_filled_honeypot_is_rejected(): void { ); } + /** + * Generic subscription forms retain widget identity checks with form ID zero. + */ + public function test_generic_form_rejects_foreign_widget(): void { + $this->prepare_verify_post( 'hcaptcha_icegram_express_nonce', 'hcaptcha_icegram_express' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => self::PLUGIN_BASENAMES, + 'form_id' => 1, + ] + ); + + $result = ( new Form() )->verify( [ 'status' => 'SUCCESS' ], [ 'esfpx_form_id' => '0' ] ); + + self::assertSame( + [ + 'status' => 'ERROR', + 'message' => 'hcaptcha_error', + ], + $result + ); + self::assertSame( + hcap_get_error_messages()['bad-signature'], + apply_filters( 'ig_es_subscription_messages', [] )['hcaptcha_error'] + ); + } + + /** + * Bind subscription exemptions to the native submitted form. + * + * @param int $native_form_id Native form ID. + * @param int $widget_form_id Signed widget form ID. + * @param string|null $error_code Expected verification error code. + * + * @dataProvider dp_test_exemption_uses_native_form + */ + public function test_exemption_uses_native_form( int $native_form_id, int $widget_form_id, ?string $error_code ): void { + $this->prepare_verify_request( '' ); + + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => self::PLUGIN_BASENAMES, + 'form_id' => $widget_form_id, + ] + ); + + $remote_requests = 0; + + add_filter( + 'hcap_protect_form', + static function ( $protect, $source, $form_id ) { + return self::PLUGIN_BASENAMES === $source && 1 === $form_id ? false : $protect; + }, + PHP_INT_MAX, + 3 + ); + add_filter( + 'pre_http_request', + static function () use ( &$remote_requests ): array { + ++$remote_requests; + + return [ 'body' => wp_json_encode( [ 'success' => false ] ) ]; + }, + PHP_INT_MAX + ); + + $result = ( new Form() )->verify( [ 'status' => 'SUCCESS' ], [ 'esfpx_form_id' => (string) $native_form_id ] ); + + if ( null === $error_code ) { + self::assertSame( [ 'status' => 'SUCCESS' ], $result ); + } else { + self::assertSame( + [ + 'status' => 'ERROR', + 'message' => 'hcaptcha_error', + ], + $result + ); + self::assertSame( + hcap_get_error_messages()[ $error_code ], + apply_filters( 'ig_es_subscription_messages', [] )['hcaptcha_error'] + ); + } + + self::assertSame( 0, $remote_requests ); + } + + /** + * Native form targets and widget identities for exemption controls. + * + * @return array + */ + public function dp_test_exemption_uses_native_form(): array { + return [ + 'matching exempt form' => [ 1, 1, null ], + 'foreign exempt form' => [ 2, 1, 'bad-signature' ], + 'protected form' => [ 2, 2, 'empty' ], + ]; + } + /** * Test that the integration script is only registered after a form is shown. * @@ -83,4 +336,66 @@ public function test_print_footer_scripts(): void { self::assertTrue( wp_script_is( 'hcaptcha-icegram-express', 'registered' ) ); self::assertStringContainsString( 'HCaptchaIcegramExpressObject', $output ); } + + /** + * Check the native subscription email from the validated form data. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native email. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $this->prepare_verify_post( 'hcaptcha_icegram_express_nonce', 'hcaptcha_icegram_express' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'icegram_express_status', [ 'form' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => self::PLUGIN_BASENAMES, + 'form_id' => 1, + ] + ); + $_POST['email'] = 'safe@example.com'; + + $result = ( new Form() )->verify( + [ 'status' => 'SUCCESS' ], + [ + 'esfpx_form_id' => '1', + 'esfpx_email' => $email, + ] + ); + + self::assertSame( + $blocked ? [ + 'status' => 'ERROR', + 'message' => 'hcaptcha_error', + ] : [ 'status' => 'SUCCESS' ], + $result + ); + + if ( $blocked ) { + self::assertSame( hcap_get_error_messages()['disposable-email'], apply_filters( 'ig_es_subscription_messages', [] )['hcaptcha_error'] ); + } + } + + /** + * Native email policy controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable email' => [ 'USER@DISPOSABLE.EXAMPLE', true ], + 'permanent email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } } diff --git a/tests/php/integration/Jetpack/BaseTest.php b/tests/php/integration/Jetpack/BaseTest.php index a6416c08d..8f2600f22 100644 --- a/tests/php/integration/Jetpack/BaseTest.php +++ b/tests/php/integration/Jetpack/BaseTest.php @@ -5,12 +5,21 @@ * @package HCaptcha\Tests */ +// phpcs:disable Generic.Commenting.DocComment.MissingShort +/** @noinspection PhpUndefinedNamespaceInspection */ +/** @noinspection PhpUndefinedClassInspection */ +// phpcs:enable Generic.Commenting.DocComment.MissingShort + namespace HCaptcha\Tests\Integration\Jetpack; use Automattic\Jetpack\Forms\ContactForm\Contact_Form as JetpackForm; use Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin as JetpackFormPlugin; +use Automattic\Jetpack\Forms\ContactForm\Feedback; +use HCaptcha\AntiSpam\DisposableEmail; +use HCaptcha\Helpers\EntryData; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Jetpack\Form; +use Jetpack; use ReflectionClass; use ReflectionException; use tad\FunctionMocker\FunctionMocker; @@ -36,7 +45,7 @@ public function test_live_plugin_is_loaded(): void { self::assertNotFalse( $plugin_dir ); self::assertStringStartsWith( trailingslashit( wp_normalize_path( $plugin_dir ) ), $form_file ); self::assertTrue( version_compare( constant( 'JETPACK__VERSION' ), '16.0.1', '>=' ) ); - self::assertTrue( \Jetpack::is_module_active( 'contact-form' ) ); + self::assertTrue( Jetpack::is_module_active( 'contact-form' ) ); $shortcode_callback = $GLOBALS['shortcode_tags']['contact-form']; self::assertSame( JetpackForm::class, ltrim( $shortcode_callback[0], '\\' ) ); @@ -59,6 +68,9 @@ public function tearDown(): void { unset( $_POST['contact-form-hash'], $_POST['contact-form-id'], + $_POST['jetpack_contact_form_jwt'], + $_POST['hcaptcha_jetpack_nonce'], + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ], $_POST['g13-name'], $_POST['g13-email'], $_POST['g13'], @@ -96,6 +108,7 @@ public function test_init_hooks( bool $is_editing_jetpack_form_post ): void { self::assertSame( 10, has_filter( 'widget_text', 'do_shortcode' ) ); self::assertSame( 100, has_filter( 'jetpack_contact_form_is_spam', [ $subject, 'verify' ] ) ); + self::assertSame( PHP_INT_MAX, has_filter( 'jetpack_forms_extra_webhooks', [ $subject, 'capture_form_hash' ] ) ); self::assertSame( 10, has_action( 'wp_head', [ $subject, 'print_inline_styles' ] ) ); @@ -168,6 +181,275 @@ public function test_live_jetpack_spam_pipeline(): void { self::assertFalse( apply_filters( 'jetpack_contact_form_is_spam', false, $form ) ); } + // These tests pass synthetic POST data into native Jetpack readers without saving a submission. + // phpcs:disable WordPress.Security.NonceVerification.Missing + /** + * Disposable-email checks must use Jetpack's email field, not a later POST alias. + * + * @param bool $jwt Whether Jetpack selected the form from a JWT. + * @param string $label Native email field label. + * + * @dataProvider dp_test_native_email_policy + */ + public function test_native_email_policy_ignores_post_alias( bool $jwt, string $label ): void { + $original_post = $_POST; + $subject = new Form(); + do_shortcode( '[contact-form id="13"][contact-field label="' . $label . '" type="email" required="1"/][/contact-form]' ); + $rendered = JetpackForm::$last; + $form = $jwt ? JetpackForm::get_instance_from_jwt( $rendered->get_jwt(), true ) : $rendered; + $email_id = $form->get_field_ids()['email']; + + try { + $_POST = [ + 'contact-form-id' => '13', + 'contact-form-hash' => $form->hash, + $email_id => 'blocked@sec065-disposable.test', + 'g13g13-email' => 'allowed@example.org', + ]; + + if ( $jwt ) { + $_POST['jetpack_contact_form_jwt'] = $rendered->get_jwt(); + $subject->capture_form_hash( [], $form ); + } + + $form->validate(); + self::assertFalse( $form->has_errors() ); + + $spam_data = Feedback::from_submission( $_POST, $form )->get_akismet_vars(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $spam_data ); + + self::assertSame( 'blocked@sec065-disposable.test', $spam_data['comment_author_email'] ); + self::assertSame( 'blocked@sec065-disposable.test', $entry['email'] ); + self::assertSame( 'blocked@sec065-disposable.test', $entry['data']['email'] ); + self::assertSame( [ 'blocked@sec065-disposable.test' ], EntryData::get_emails( $entry ) ); + + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec065-disposable.test' => true ] ); + self::assertFalse( (bool) ( new DisposableEmail() )->verify( $entry ) ); + + $_POST[ $email_id ] = 'allowed@example.org'; + $_POST['g13g13-email'] = 'blocked@sec065-disposable.test'; + $spam_data = Feedback::from_submission( $_POST, $form )->get_akismet_vars(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $spam_data ); + + self::assertSame( [ 'allowed@example.org' ], EntryData::get_emails( $entry ) ); + self::assertTrue( (bool) ( new DisposableEmail() )->verify( $entry ) ); + } finally { + delete_transient( 'hcaptcha_disposable_email_blocklist' ); + $_POST = $original_post; + } + } + + /** + * Email policy routes and labels. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'jwt_default' => [ true, 'Email' ], + 'jwt_custom' => [ true, 'Contact Address' ], + 'legacy_default' => [ false, 'Email' ], + 'legacy_custom' => [ false, 'Contact Address' ], + ]; + } + + /** + * Every visible native email field is checked, even when the first is permitted. + */ + public function test_native_email_policy_checks_additional_email_fields(): void { + $original_post = $_POST; + $subject = new Form(); + do_shortcode( '[contact-form id="13"][contact-field label="Primary" type="email" required="1"/][contact-field label="Secondary" type="email" required="1"/][/contact-form]' ); + $form = JetpackForm::$last; + $ids = $form->get_field_ids()['all']; + + try { + $_POST = [ + 'contact-form-id' => '13', + 'contact-form-hash' => $form->hash, + $ids[0] => 'allowed@example.org', + $ids[1] => 'foo&bar@sec065-disposable.test', + ]; + + $form->validate(); + self::assertFalse( $form->has_errors() ); + + $spam_data = Feedback::from_submission( $_POST, $form )->get_akismet_vars(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $spam_data ); + + self::assertSame( 'allowed@example.org', $spam_data['comment_author_email'] ); + self::assertSame( [ 'allowed@example.org', 'foo&bar@sec065-disposable.test' ], EntryData::get_emails( $entry ) ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec065-disposable.test' => true ] ); + self::assertFalse( (bool) ( new DisposableEmail() )->verify( $entry ) ); + } finally { + delete_transient( 'hcaptcha_disposable_email_blocklist' ); + $_POST = $original_post; + } + } + + /** + * Legacy Jetpack can select a rebuilt form whose hash differs from the submitted hash. + */ + public function test_native_email_policy_checks_rebuilt_legacy_form(): void { + $original_post = $_POST; + $subject = new Form(); + do_shortcode( '[contact-form id="13"][contact-field label="Primary" type="email" required="1"/][contact-field label="Secondary" type="email" required="1"/][/contact-form]' ); + $form = JetpackForm::$last; + $ids = $form->get_field_ids()['all']; + $old_hash = $form->hash; + $fake_hash = str_repeat( 'a', 40 ); + + try { + self::assertNotSame( $old_hash, $fake_hash ); + self::assertArrayNotHasKey( $fake_hash, JetpackForm::$forms ); + $_POST = [ + 'contact-form-id' => '13', + 'contact-form-hash' => $fake_hash, + $ids[0] => 'allowed@example.org', + $ids[1] => 'blocked@sec065-disposable.test', + ]; + + $spam_data = Feedback::from_submission( $_POST, $form )->get_akismet_vars(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $spam_data ); + + self::assertSame( 'allowed@example.org', $spam_data['comment_author_email'] ); + self::assertSame( [ 'allowed@example.org', 'blocked@sec065-disposable.test' ], EntryData::get_emails( $entry ) ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec065-disposable.test' => true ] ); + self::assertFalse( (bool) ( new DisposableEmail() )->verify( $entry ) ); + } finally { + delete_transient( 'hcaptcha_disposable_email_blocklist' ); + $_POST = $original_post; + } + } + + /** + * A filter may change the author email while Jetpack retains the submitted field. + */ + public function test_native_email_policy_checks_stored_email_after_author_filter(): void { + $original_post = $_POST; + $subject = new Form(); + do_shortcode( '[contact-form id="13"][contact-field label="Email" type="email" required="1"/][/contact-form]' ); + $form = JetpackForm::$last; + $email_id = $form->get_field_ids()['email']; + $filter = static function (): string { + return 'allowed@example.org'; + }; + + try { + $_POST = [ + 'contact-form-id' => '13', + 'contact-form-hash' => $form->hash, + $email_id => 'blocked@sec065-disposable.test', + ]; + + $form->validate(); + self::assertFalse( $form->has_errors() ); + add_filter( 'pre_comment_author_email', $filter ); + + $feedback = Feedback::from_submission( $_POST, $form ); + $spam_data = $feedback->get_akismet_vars(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $spam_data ); + + self::assertSame( 'allowed@example.org', $spam_data['comment_author_email'] ); + self::assertSame( [ 'allowed@example.org', 'blocked@sec065-disposable.test' ], EntryData::get_emails( $entry ) ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec065-disposable.test' => true ] ); + self::assertFalse( (bool) ( new DisposableEmail() )->verify( $entry ) ); + } finally { + remove_filter( 'pre_comment_author_email', $filter ); + delete_transient( 'hcaptcha_disposable_email_blocklist' ); + $_POST = $original_post; + } + } + + /** + * A text field named email does not become a native email field. + */ + public function test_native_email_policy_preserves_email_free_form(): void { + $original_post = $_POST; + $subject = new Form(); + do_shortcode( '[contact-form id="13"][contact-field label="Email" type="text"/][/contact-form]' ); + $form = JetpackForm::$last; + $id = $form->get_field_ids()['all'][0]; + + try { + $_POST = [ + 'contact-form-id' => '13', + 'contact-form-hash' => $form->hash, + $id => 'blocked@sec065-disposable.test', + 'g13g13-email' => 'blocked@sec065-disposable.test', + ]; + + $spam_data = Feedback::from_submission( $_POST, $form )->get_akismet_vars(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $spam_data ); + + self::assertSame( '', $spam_data['comment_author_email'] ); + self::assertSame( [], EntryData::get_emails( $entry ) ); + self::assertArrayNotHasKey( 'email', $entry ); + self::assertArrayNotHasKey( 'email', $entry['data'] ); + } finally { + $_POST = $original_post; + } + } + // phpcs:enable WordPress.Security.NonceVerification.Missing + + /** + * A JWT-selected protected form cannot inherit another form's CAPTCHA exemption. + */ + public function test_jwt_form_hash_owns_captcha_policy(): void { + $subject = new Form(); + $html_a = do_shortcode( '[contact-form id="13"][contact-field label="Name A" type="name" required="1"/][/contact-form]' ); + $form_a = JetpackForm::$last; + $jwt_a = $form_a->get_jwt(); + $hash_a = $form_a->hash; + $html_b = do_shortcode( '[contact-form id="13"][contact-field label="Name B" type="name" required="1"/][/contact-form]' ); + $form_b = JetpackForm::$last; + $jwt_b = $form_b->get_jwt(); + $hash_b = $form_b->hash; + $source = HCaptcha::get_class_source( Form::class ); + + self::assertStringContainsString( "name='jetpack_contact_form_jwt'", $html_a ); + self::assertStringContainsString( "name='jetpack_contact_form_jwt'", $html_b ); + self::assertNotSame( $hash_a, $hash_b ); + + $native_a = JetpackForm::get_instance_from_jwt( $jwt_a, true ); + $native_b = JetpackForm::get_instance_from_jwt( $jwt_b, true ); + $exempt_b = static function ( $protect, $form_source, $form_id ) use ( $source, $hash_b ) { + return $source === $form_source && 'contact_' . $hash_b === $form_id ? false : $protect; + }; + + add_filter( 'hcap_protect_form', $exempt_b, 10, 3 ); + + try { + $_POST['contact-form-id'] = '13'; + $_POST['hcaptcha_jetpack_nonce'] = wp_create_nonce( 'hcaptcha_jetpack' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => $source, + 'form_id' => 'contact_' . $hash_b, + ] + ); + $_POST['jetpack_contact_form_jwt'] = $jwt_a; + $_POST['contact-form-hash'] = $hash_b; + + self::assertSame( [], $subject->capture_form_hash( [], $native_a ) ); + self::assertSame( 'invalid_hcaptcha', $subject->verify()->get_error_code() ); + self::assertSame( $hash_a, $this->get_protected_property( $subject, 'error_form_hash' ) ); + + $_POST['contact-form-hash'] = $hash_a; + self::assertSame( 'invalid_hcaptcha', $subject->verify()->get_error_code() ); + + $_POST['jetpack_contact_form_jwt'] = $jwt_b; + $_POST['contact-form-hash'] = $hash_b; + self::assertSame( [], $subject->capture_form_hash( [], $native_b ) ); + self::assertFalse( $subject->verify() ); + + unset( $_POST['jetpack_contact_form_jwt'] ); + self::assertFalse( $subject->verify() ); + } finally { + remove_filter( 'hcap_protect_form', $exempt_b ); + } + } + /** * Test verify() not verified. * @@ -328,6 +610,7 @@ public function test_add_type_module(): void { * Test editor_enqueue_scripts(). * * @return void + * @noinspection JsonEncodingApiUsageInspection */ public function test_editor_enqueue_scripts(): void { $admin_handle = 'admin-jetpack'; diff --git a/tests/php/integration/Kadence/AdvancedFormTest.php b/tests/php/integration/Kadence/AdvancedFormTest.php index 407ec81e5..6e3f4db7d 100644 --- a/tests/php/integration/Kadence/AdvancedFormTest.php +++ b/tests/php/integration/Kadence/AdvancedFormTest.php @@ -10,13 +10,16 @@ namespace HCaptcha\Tests\Integration\Kadence; +use HCaptcha\Helpers\API; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Kadence\BlockParser; use HCaptcha\Kadence\AdvancedForm; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; +use KB_Ajax_Advanced_Form; use Mockery; use ReflectionException; use ReflectionMethod; +use ReflectionProperty; /** * Test Kadence AdvancedForm. @@ -203,7 +206,7 @@ public function test_render_block_data(): void { public function test_render_nested_forms_with_different_ids(): void { $form_ids = []; - foreach ( [ 'first', 'second' ] as $index => $slug ) { + foreach ( [ 'first', 'second' ] as $slug ) { $form_ids[] = wp_insert_post( [ 'post_type' => 'kadence_form', @@ -254,13 +257,12 @@ public function test_process_ajax(): void { [ 'post_content' => 'temp', 'post_status' => 'publish', + 'post_type' => 'kadence_form', ] ); // phpcs:disable Generic.WhiteSpace.ScopeIndent.IncorrectExact, Generic.Strings.UnnecessaryHeredoc.Found $post_content = << -

      Some intro text

      @@ -288,8 +290,6 @@ public function test_process_ajax(): void {
      Message
      -
      - HTML; // phpcs:enable Generic.WhiteSpace.ScopeIndent.IncorrectExact @@ -328,6 +328,24 @@ public function test_process_ajax(): void { self::assertSame( 'Hello there', $entry['data']['Message'] ); } + /** + * Ignore unrelated blocks and non-content advanced form fields. + */ + public function test_add_form_field_ignores_non_content_blocks(): void { + $subject = new AdvancedForm(); + $method = new ReflectionMethod( $subject, 'add_form_field' ); + $data = []; + $emails = []; + $form_data = []; + $method->setAccessible( true ); + + $method->invokeArgs( $subject, [ &$data, [ 'blockName' => 'core/paragraph' ], &$emails, $form_data ] ); + $method->invokeArgs( $subject, [ &$data, [ 'blockName' => 'kadence/advanced-form-hidden' ], &$emails, $form_data ] ); + + self::assertSame( [], $data ); + self::assertSame( [], $emails ); + } + /** * Test process_ajax() when not success. * @@ -335,6 +353,7 @@ public function test_process_ajax(): void { * * @return void * @dataProvider dp_test_process_ajax_when_not_success + * @noinspection JsonEncodingApiUsageInspection */ public function test_process_ajax_when_not_success( ?bool $result ): void { $hcaptcha_response = 'some response'; @@ -379,6 +398,7 @@ static function () use ( &$die_arr ) { * Test process_ajax() when widget id is missing. * * @return void + * @noinspection JsonEncodingApiUsageInspection */ public function test_process_ajax_missing_widget_id(): void { $hcaptcha_response = 'some response'; @@ -547,4 +567,190 @@ static function () use ( $secret_key ) { self::assertSame( $site_key, apply_filters( 'pre_option_kadence_blocks_hcaptcha_site_key', 'some' ) ); self::assertSame( $secret_key, apply_filters( 'pre_option_kadence_blocks_hcaptcha_secret_key', 'some' ) ); } + /** + * Apply email policy to every trusted advanced email field. + * + * @param bool $blocked Whether the trusted email is disposable. + * @dataProvider dp_sec063_email_policy + */ + public function test_sec063_typed_email_policy( bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $post_id = $this->factory()->post->create(); + wp_update_post( + [ + 'ID' => $post_id, + 'post_content' => '', + ] + ); + $_POST['_kb_adv_form_post_id'] = $post_id; + $_POST['billing_email'] = $blocked ? ' person@sec063-disposable.test ' : ' person@example.com '; + $_POST['fieldone'] = 'spoof@sec063-disposable.test'; + $_POST['fieldtwo'] = 'reader@example.com'; + $_POST['fieldthree'] = 'spoof@sec063-disposable.test'; + $this->prepare_widget_id( $post_id ); + $subject = new AdvancedForm(); + // phpcs:ignore WordPress.Security.NonceVerification.Missing + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $_POST ); + + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + /** + * Exercise both policy rejection and permanent address acceptance. + * + * @return array + */ + public function dp_sec063_email_policy(): array { + return [ + 'disposable' => [ true ], + 'permanent' => [ false ], + ]; + } + + /** + * Match the native accepted email before enforcing disposable-address policy. + * + * @param string $raw_email Posted native email input. + * @param string $email Native normalized address. + * @param bool $blocked Whether native address is disposable. + * @dataProvider dp_sec063_native_email_normalization + * @return void + */ + public function test_sec063_native_email_normalization( string $raw_email, string $email, bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $post_id = $this->factory()->post->create( + [ + 'post_type' => 'kadence_form', + 'post_status' => 'publish', + ] + ); + wp_update_post( + [ + 'ID' => $post_id, + 'post_content' => '', + ] + ); + $_POST['_kb_adv_form_post_id'] = $post_id; + $_POST['billing_email'] = wp_slash( $raw_email ); + $_POST['email'] = 'spoof@example.com'; + $this->prepare_widget_id( $post_id ); + + $native = KB_Ajax_Advanced_Form::get_instance(); + $fields = new ReflectionProperty( KB_Ajax_Advanced_Form::class, 'fields' ); + $fields->setAccessible( true ); + $stored_fields = $fields->getValue(); + $fields->setValue( null, [] ); + try { + $form = $this->set_method_accessibility( $native, 'get_form' )->invoke( $native, $post_id ); + $processed = $native->process_fields( $form['fields'] ); + } finally { + $fields->setValue( null, $stored_fields ); + } + self::assertSame( $email, $processed[0]['value'] ); + self::assertSame( 'email', $processed[0]['type'] ); + self::assertSame( 'billing_email', $processed[0]['name'] ); + + $subject = new AdvancedForm(); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Native pipeline owns its nonce check. + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $_POST ); + self::assertSame( [ $processed[0]['value'] ], $entry['email_addresses'] ); + self::assertSame( $processed[0]['value'], $entry['data']['email'] ); + self::assertArrayNotHasKey( 'Payment contact', $entry['data'] ); + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + + /** + * Native HTML insertion normalization and ordinary address controls. + * + * @return array + */ + public function dp_sec063_native_email_normalization(): array { + return [ + 'disposable with HTML insertion' => [ ' person@sec063-disposabe.test ', 'person@sec063-disposable.test', true ], + 'permanent with HTML insertion' => [ ' reader@exampe.com ', 'reader@example.com', false ], + 'ordinary disposable' => [ ' person@sec063-disposable.test ', 'person@sec063-disposable.test', true ], + 'ordinary permanent' => [ ' reader@example.com ', 'reader@example.com', false ], + ]; + } + + /** + * Project email fields from the same post selected by native Kadence. + * + * @param string $id_format Posted ID representation. + * @param string $email Submitted email address. + * @param bool $blocked Whether the disposable policy must reject it. + * @param bool $imported_id Whether the block uses an imported unique ID. + * @param bool $nested Whether the email leaf is inside another Kadence block. + * @dataProvider dp_sec061_form_id_spelling + * @return void + */ + public function test_sec061_form_id_spelling( string $id_format, string $email, bool $blocked, bool $imported_id, bool $nested ): void { + $this->prepare_verify_request( 'sec061-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec061-disposable.test' => true ] ); + $post_id = $this->factory()->post->create( + [ + 'post_type' => 'kadence_form', + 'post_status' => 'publish', + ] + ); + $unique_id = $imported_id ? 'imported_sec061' : $post_id . '_sec061'; + $email_block = ''; + + if ( $nested ) { + $email_block = '' . $email_block . ''; + } + + wp_update_post( + [ + 'ID' => $post_id, + 'post_content' => '' . $email_block . '', + ] + ); + $posted_id = sprintf( $id_format, $post_id ); + $_POST['_kb_adv_form_post_id'] = $posted_id; + $_POST['contact_email'] = $email; + $this->prepare_widget_id( $post_id ); + + $native = KB_Ajax_Advanced_Form::get_instance(); + $fields = new ReflectionProperty( KB_Ajax_Advanced_Form::class, 'fields' ); + $fields->setAccessible( true ); + $stored_fields = $fields->getValue(); + $fields->setValue( null, [] ); + try { + $form = $this->set_method_accessibility( $native, 'get_form' )->invoke( $native, $posted_id ); + $processed = $native->process_fields( $form['fields'] ); + } finally { + $fields->setValue( null, $stored_fields ); + } + self::assertSame( $email, $processed[0]['value'] ); + self::assertSame( 'contact_email', $processed[0]['name'] ); + + $subject = new AdvancedForm(); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Native pipeline owns its nonce check. + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $_POST ); + self::assertSame( $post_id, $entry['expected_id']['form_id'] ); + self::assertSame( [ $processed[0]['value'] ], $entry['email_addresses'] ); + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + + /** + * ID spellings and disposable-email controls for SEC-061. + * + * @return array + */ + public function dp_sec061_form_id_spelling(): array { + return [ + 'canonical blocked' => [ '%s', 'person@sec061-disposable.test', true, false, false ], + 'leading zero blocked' => [ '00%s', 'person@sec061-disposable.test', true, false, false ], + 'decimal suffix blocked' => [ '%s.0', 'person@sec061-disposable.test', true, false, false ], + 'leading zero allowed' => [ '00%s', 'reader@example.com', false, false, false ], + 'imported block ID' => [ '%s', 'person@sec061-disposable.test', true, true, false ], + 'nested email field' => [ '%s', 'person@sec061-disposable.test', true, false, true ], + ]; + } } diff --git a/tests/php/integration/Kadence/BaseTest.php b/tests/php/integration/Kadence/BaseTest.php index 19a7c78e5..cdaa32646 100644 --- a/tests/php/integration/Kadence/BaseTest.php +++ b/tests/php/integration/Kadence/BaseTest.php @@ -97,6 +97,7 @@ public function test_dequeue_kadence_captcha_api_not_replaced(): void { * @throws ReflectionException ReflectionException. */ public function test_dequeue_kadence_captcha_api_replaced(): void { + hcaptcha()->settings()->set( 'kadence_status', [ 'form', 'advanced_form' ] ); $subject = new Base(); $this->set_protected_property( $subject, 'has_captcha', true ); diff --git a/tests/php/integration/Kadence/BlockParserTest.php b/tests/php/integration/Kadence/BlockParserTest.php index b889f0150..cbb81741c 100644 --- a/tests/php/integration/Kadence/BlockParserTest.php +++ b/tests/php/integration/Kadence/BlockParserTest.php @@ -9,6 +9,7 @@ use HCaptcha\Kadence\BlockParser; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; +use ReflectionException; /** * Test Kadence BlockParser. @@ -43,6 +44,7 @@ class BlockParserTest extends HCaptchaPluginWPTestCase { public function setUp(): void { parent::setUp(); + hcaptcha()->settings()->set( 'kadence_status', [ 'form', 'advanced_form' ] ); BlockParser::$form_id = 0; } @@ -90,4 +92,28 @@ public function test_parse(): void { self::assertEquals( 789, BlockParser::$form_id ); self::assertEmpty( $advanced_form['innerBlocks'] ); } + + /** + * Ignore malformed nested block data after parsing a block. + * + * @throws ReflectionException Reflection exception. + */ + public function test_process_block_without_inner_blocks(): void { + $subject = new BlockParser(); + $block = [ + 'blockName' => 'some/some', + 'innerBlocks' => null, + ]; + $method = $this->set_method_accessibility( $subject, 'process_block' ); + + $method->invokeArgs( $subject, [ &$block ] ); + + self::assertSame( + [ + 'blockName' => 'some/some', + 'innerBlocks' => null, + ], + $block + ); + } } diff --git a/tests/php/integration/Kadence/CaptchaIsolationTest.php b/tests/php/integration/Kadence/CaptchaIsolationTest.php new file mode 100644 index 000000000..8cbd3ca93 --- /dev/null +++ b/tests/php/integration/Kadence/CaptchaIsolationTest.php @@ -0,0 +1,778 @@ +request = $_REQUEST; + // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Restore the original transport unchanged. + $this->request_method = $_SERVER['REQUEST_METHOD'] ?? null; + } + + /** + * Restore request globals changed by the AJAX fixtures. + * + * @return void + */ + public function tearDown(): void { + $_REQUEST = $this->request; + if ( null === $this->request_method ) { + unset( $_SERVER['REQUEST_METHOD'] ); + } else { + $_SERVER['REQUEST_METHOD'] = $this->request_method; + } + BlockParser::$form_id = 0; + unset( $GLOBALS['current_screen'] ); + parent::tearDown(); + } + + /** + * Preserve the native classic CAPTCHA check under advanced-only integration. + * + * @param array $modules Enabled Kadence integration modules. + * @param bool|null $captcha Stored native CAPTCHA setting, or absence. + * @param bool $success Whether the native form should submit. + * + * @dataProvider dp_native_classic_submission + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_native_classic_submission( array $modules, ?bool $captcha, bool $success ): void { + $this->load_kadence_modules( $modules ); + $post_id = $this->create_classic_form( $captcha ); + $native = KB_Ajax_Form::get_instance(); + $args = $this->set_method_accessibility( $native, 'get_form_args' )->invoke( $native, (string) $post_id, 'sec003-classic' ); + + self::assertNotEmpty( $args ); + self::assertFalse( $this->has_classic_verifier() ); + + $_POST = [ + 'action' => 'kb_process_ajax_submit', + '_kb_form_post_id' => (string) $post_id, + '_kb_form_id' => 'sec003-classic', + '_kb_verify_email' => '', + 'kb_field_0' => 'Reader Name', + ]; + $result = $this->submit_classic_form(); + + self::assertSame( $success, $result['json']['success'] ); + self::assertCount( $success ? 1 : 0, $result['mail'] ); + if ( $success ) { + self::assertSame( 'sec003-recipient@example.com', $result['mail'][0]['to'] ); + self::assertStringContainsString( 'Reader Name', $result['mail'][0]['message'] ); + } else { + self::assertSame( 'reCAPTCHA Failed', $result['json']['data']['console'] ); + } + if ( null === $captcha ) { + self::assertArrayNotHasKey( 'recaptcha', $args ); + } else { + self::assertSame( $captcha, $args['recaptcha'] ); + } + } + + /** + * Native CAPTCHA rejection and CAPTCHA-free submission controls. + * + * @return array + */ + public function dp_native_classic_submission(): array { + return [ + 'neither module, native CAPTCHA' => [ [], true, false ], + 'advanced only, native CAPTCHA' => [ [ 'advanced_form' ], true, false ], + 'advanced only, CAPTCHA off' => [ [ 'advanced_form' ], false, true ], + 'advanced only, CAPTCHA absent' => [ [ 'advanced_form' ], null, true ], + ]; + } + + /** + * A classic integration must replace native CAPTCHA with real hCaptcha proof. + * + * @param array $modules Enabled Kadence integration modules. + * @param bool $proof Whether a valid hCaptcha proof is submitted. + * + * @dataProvider dp_integrated_classic_submission + * @return void + */ + public function test_integrated_classic_submission( array $modules, bool $proof ): void { + $this->prepare_verify_request( 'sec003-hcaptcha-proof' ); + $this->load_kadence_modules( $modules ); + $post_id = $this->create_classic_form( true ); + self::assertTrue( $this->has_classic_verifier() ); + + $_POST['_kb_form_post_id'] = (string) $post_id; + $_POST['_kb_form_id'] = 'sec003-classic'; + $_POST['_kb_verify_email'] = ''; + $_POST['kb_field_0'] = 'Reader Name'; + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ static::$plugin ], + 'form_id' => $post_id, + ] + ); + if ( ! $proof ) { + unset( $_POST['h-captcha-response'] ); + } + $result = $this->submit_classic_form(); + + self::assertSame( $proof, $result['json']['success'] ); + self::assertCount( $proof ? 1 : 0, $result['mail'] ); + if ( ! $proof ) { + self::assertSame( 'hCaptcha Failed', $result['json']['data']['console'] ); + } + } + + /** + * Classic-only and both-module hCaptcha proof controls. + * + * @return array + */ + public function dp_integrated_classic_submission(): array { + return [ + 'classic only, valid proof' => [ [ 'form' ], true ], + 'classic only, missing proof' => [ [ 'form' ], false ], + 'both modules, valid proof' => [ [ 'form', 'advanced_form' ], true ], + 'both modules, missing proof' => [ [ 'form', 'advanced_form' ], false ], + ]; + } + + /** + * Keep native form configuration scoped to its selected integration module. + * + * @param array $modules Enabled Kadence integration modules. + * @param bool|null $captcha Classic native CAPTCHA setting, or absence. + * + * @dataProvider dp_module_configuration + * @return void + */ + public function test_module_configuration( array $modules, ?bool $captcha ): void { + // Store the native forms before installing the submission request's parser. + $post_id = $this->create_classic_form( $captcha ); + $advanced_id = $this->factory()->post->create( + [ + 'post_type' => 'kadence_form', + 'post_status' => 'publish', + 'post_content' => '', + ] + ); + $this->load_kadence_modules( $modules ); + $args = $this->set_method_accessibility( KB_Ajax_Form::get_instance(), 'get_form_args' )->invoke( KB_Ajax_Form::get_instance(), (string) $post_id, 'sec003-classic' ); + $classic = in_array( 'form', $modules, true ); + + self::assertSame( $classic, $this->has_classic_verifier() ); + if ( $classic || null !== $captcha ) { + self::assertSame( $classic ? false : $captcha, $args['recaptcha'] ); + } else { + self::assertArrayNotHasKey( 'recaptcha', $args ); + } + self::assertTrue( $args['honeyPot'] ); + self::assertTrue( $args['fields'][0]['required'] ); + + $native = KB_Ajax_Advanced_Form::get_instance(); + $fields = new ReflectionProperty( KB_Ajax_Advanced_Form::class, 'fields' ); + $captcha = new ReflectionProperty( KB_Ajax_Advanced_Form::class, 'captcha_attrs' ); + $fields->setAccessible( true ); + $captcha->setAccessible( true ); + $old_fields = $fields->getValue(); + $old_captcha = $captcha->getValue(); + $fields->setValue( null, [] ); + $captcha->setValue( null, false ); + try { + $advanced = $this->set_method_accessibility( $native, 'get_form' )->invoke( $native, $advanced_id ); + self::assertCount( in_array( 'advanced_form', $modules, true ) ? 1 : 2, $advanced['fields'] ); + self::assertTrue( $advanced['fields'][0]['required'] ); + if ( in_array( 'advanced_form', $modules, true ) ) { + self::assertFalse( $captcha->getValue() ); + } else { + self::assertSame( 'hcaptcha', $captcha->getValue()['type'] ); + } + } finally { + $fields->setValue( null, $old_fields ); + $captcha->setValue( null, $old_captcha ); + } + } + + /** + * All independent module settings and stored classic CAPTCHA states. + * + * @return array + */ + public function dp_module_configuration(): array { + $cases = []; + foreach ( [ + 'neither' => [], + 'classic' => [ 'form' ], + 'advanced' => [ 'advanced_form' ], + 'both' => [ 'form', 'advanced_form' ], + ] as $name => $modules ) { + foreach ( [ + 'on' => true, + 'off' => false, + 'absent' => null, + ] as $state => $captcha ) { + $cases[ $name . ' CAPTCHA ' . $state ] = [ $modules, $captcha ]; + } + } + return $cases; + } + + /** + * Exercise the native locator for nested, reusable, and widget forms. + * + * @param string $location Native form location. + * + * @dataProvider dp_native_locations + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_native_locations( string $location ): void { + $this->load_kadence_modules( [ 'advanced_form' ] ); + $post_id = $this->create_classic_form( true ); + $native_id = $this->relocate_classic_form( $post_id, $location ); + $native = KB_Ajax_Form::get_instance(); + $args = $this->set_method_accessibility( $native, 'get_form_args' )->invoke( $native, $native_id, 'sec003-classic' ); + self::assertTrue( $args['recaptcha'] ); + + $_POST = [ + '_kb_form_post_id' => $native_id, + '_kb_form_id' => 'sec003-classic', + '_kb_verify_email' => '', + 'kb_field_0' => 'Reader Name', + ]; + $result = $this->submit_classic_form(); + self::assertFalse( $result['json']['success'] ); + self::assertSame( 'reCAPTCHA Failed', $result['json']['data']['console'] ); + self::assertCount( 0, $result['mail'] ); + } + + /** + * Supported native form locators. + * + * @return array + */ + public function dp_native_locations(): array { + return [ + 'post' => [ 'post' ], + 'nested' => [ 'nested' ], + 'reusable' => [ 'reusable' ], + 'widget' => [ 'widget' ], + 'unknown widget' => [ 'unknown-widget' ], + ]; + } + + /** + * Keep the native required field, honeypot, and optional nonce checks. + * + * @param array $overrides Submitted values overriding valid defaults. + * @param bool $nonce Whether native nonce checking is enabled. + * @param string $error Expected native rejection, or empty on success. + * + * @dataProvider dp_native_input_guards + * @return void + */ + public function test_native_input_guards( array $overrides, bool $nonce, string $error ): void { + $this->load_kadence_modules( [ 'advanced_form' ] ); + $post_id = $this->create_classic_form( false ); + if ( $nonce ) { + add_filter( 'kadence_blocks_form_verify_nonce', '__return_true' ); + } + $_POST = array_merge( + [ + '_kb_form_post_id' => (string) $post_id, + '_kb_form_id' => 'sec003-classic', + '_kb_verify_email' => '', + '_kb_form_verify' => wp_create_nonce( 'kb_form_nonce' ), + 'kb_field_0' => 'Reader Name', + ], + $overrides + ); + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Native check_ajax_referer reads the submitted transport. + $_REQUEST = $_POST; + $result = $this->submit_classic_form(); + self::assertSame( '' === $error, $result['json']['success'] ); + self::assertCount( '' === $error ? 1 : 0, $result['mail'] ); + if ( '' !== $error ) { + self::assertSame( $error, $result['json']['data']['console'] ); + } else { + self::assertStringContainsString( 'Reader Name', $result['mail'][0]['message'] ); + } + } + + /** + * Native validation controls unrelated to CAPTCHA replacement. + * + * @return array + */ + public function dp_native_input_guards(): array { + return [ + 'required field' => [ [ 'kb_field_0' => '' ], false, 'Required Field Empty' ], + 'honeypot' => [ [ '_kb_verify_email' => 'robot' ], false, 'Spam Detected' ], + 'invalid nonce' => [ [ '_kb_form_verify' => 'invalid' ], true, 'Token invalid' ], + 'valid nonce' => [ [], true, '' ], + ]; + } + + /** + * Replacing an advanced CAPTCHA must preserve native classic API scripts. + * + * @param string $version Native classic reCAPTCHA version. + * + * @dataProvider dp_native_recaptcha_versions + * @return void + */ + public function test_mixed_frontend_preserves_native_classic_scripts( string $version ): void { + $this->load_kadence_modules( [ 'advanced_form' ], true ); + update_option( 'kadence_blocks_recaptcha_site_key', 'sec003-native-site-key' ); + update_option( 'kadence_blocks_recaptcha_secret_key', 'sec003-native-secret-key' ); + $handle = 'kadence-blocks-google-recaptcha-' . $version; + foreach ( [ $handle, 'kadence-blocks-recaptcha' ] as $native_handle ) { + wp_dequeue_script( $native_handle ); + wp_deregister_script( $native_handle ); + } + $form_id = $this->factory()->post->create( + [ + 'post_type' => 'kadence_form', + 'post_status' => 'publish', + 'post_content' => '', + ] + ); + $captcha = 'v2' === $version + ? '
      ' + : ''; + $classic = '
      ' . $captcha . '
      '; + $output = do_blocks( $classic . '' ); + + self::assertStringContainsString( $captcha, $output ); + self::assertStringContainsString( 'callbacks[8] ?? []; + foreach ( $callbacks as $callback ) { + if ( is_array( $callback['function'] ) && $callback['function'][0] instanceof Base ) { + call_user_func( $callback['function'] ); + } + } + self::assertTrue( wp_script_is( $handle ) ); + self::assertTrue( wp_script_is( $handle, 'registered' ) ); + self::assertFalse( wp_script_is( 'kadence-blocks-recaptcha' ) ); + self::assertFalse( wp_script_is( 'kadence-blocks-recaptcha', 'registered' ) ); + } + + /** + * Classic native APIs share neither handle with the advanced API. + * + * @return array + */ + public function dp_native_recaptcha_versions(): array { + return [ + 'v2' => [ 'v2' ], + 'v3' => [ 'v3' ], + ]; + } + + /** + * Saving content must preserve native CAPTCHA after hCaptcha is disabled. + * + * @param array $modules Enabled Kadence integration modules. + * @param string $method Native WordPress save operation. + * @param bool $ajax Whether the save happens during native form AJAX. + * + * @dataProvider dp_classic_content_save + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_classic_content_save_preserves_native_captcha( array $modules, string $method, bool $ajax ): void { + $post_id = 'update' === $method ? $this->factory()->post->create( [ 'post_content' => 'Original content' ] ) : 0; + $user_id = $this->factory()->user->create( [ 'role' => 'author' ] ); + wp_set_current_user( $user_id ); + self::assertFalse( current_user_can( 'unfiltered_html' ) ); + kses_init(); + self::assertSame( 10, has_filter( 'content_save_pre', 'wp_filter_post_kses' ) ); + set_current_screen( 'post' ); + $this->load_kadence_modules( $modules, false, $ajax ? 'kb_process_ajax_submit' : '' ); + + $content = ''; + $data = [ + 'post_author' => $user_id, + 'post_status' => 'publish', + 'post_content' => $content, + ]; + if ( 'update' === $method ) { + $data['ID'] = $post_id; + $post_id = wp_update_post( $data, true ); + } else { + $post_id = wp_insert_post( $data, true ); + } + $this->assertNotWPError( $post_id ); + self::assertGreaterThan( 0, $post_id ); + + unset( $GLOBALS['current_screen'] ); + $this->disable_kadence_modules(); + self::assertFalse( $this->has_classic_verifier(), 'Disabling the integration must remove its request verifier.' ); + $native = KB_Ajax_Form::get_instance(); + $args = $this->set_method_accessibility( $native, 'get_form_args' )->invoke( $native, (string) $post_id, 'sec003-classic' ); + $_POST = [ + 'action' => 'kb_process_ajax_submit', + '_kb_form_post_id' => (string) $post_id, + '_kb_form_id' => 'sec003-classic', + '_kb_verify_email' => '', + 'kb_field_0' => 'Reader Name', + ]; + $result = $this->submit_classic_form(); + self::assertFalse( $result['json']['success'], 'The saved native CAPTCHA must reject after hCaptcha is disabled.' ); + self::assertCount( 0, $result['mail'] ); + self::assertSame( 'reCAPTCHA Failed', $result['json']['data']['console'] ); + self::assertTrue( $args['recaptcha'] ); + } + + /** + * Insert and update through KSES during editor and native AJAX requests. + * + * @return array + */ + public function dp_classic_content_save(): array { + $cases = []; + foreach ( [ + 'classic' => [ 'form' ], + 'both' => [ 'form', 'advanced_form' ], + ] as $module => $enabled ) { + foreach ( [ 'insert', 'update' ] as $method ) { + foreach ( [ + 'editor' => false, + 'native AJAX' => true, + ] as $context => $ajax ) { + $cases[ $module . ' ' . $method . ' ' . $context ] = [ $enabled, $method, $ajax ]; + } + } + } + return $cases; + } + + /** + * Save-time KSES must retain and serialize native advanced CAPTCHA blocks. + * + * @param string $method Native WordPress save operation. + * + * @dataProvider dp_advanced_content_save + * @return void + */ + public function test_advanced_content_save_preserves_native_captcha( string $method ): void { + $post_id = 'update' === $method ? $this->factory()->post->create( [ 'post_content' => 'Original content' ] ) : 0; + $user_id = $this->factory()->user->create( [ 'role' => 'author' ] ); + wp_set_current_user( $user_id ); + self::assertFalse( current_user_can( 'unfiltered_html' ) ); + kses_init(); + self::assertSame( 10, has_filter( 'content_save_pre', 'wp_filter_post_kses' ) ); + set_current_screen( 'post' ); + $this->load_kadence_modules( [ 'form', 'advanced_form' ], false, 'kb_process_advanced_form_submit' ); + + $content = ''; + $data = [ + 'post_author' => $user_id, + 'post_type' => 'kadence_form', + 'post_status' => 'publish', + 'post_content' => $content, + ]; + if ( 'update' === $method ) { + $data['ID'] = $post_id; + $post_id = wp_update_post( $data, true ); + } else { + $post_id = wp_insert_post( $data, true ); + } + $this->assertNotWPError( $post_id ); + self::assertGreaterThan( 0, $post_id ); + + $this->disable_kadence_modules(); + $stored = get_post( $post_id )->post_content; + $blocks = parse_blocks( $stored ); + self::assertCount( 2, $blocks[0]['innerBlocks'] ); + self::assertSame( 'kadence/advanced-form-captcha', $blocks[0]['innerBlocks'][1]['blockName'] ); + self::assertSame( 'hcaptcha', $blocks[0]['innerBlocks'][1]['attrs']['type'] ); + self::assertSame( $stored, serialize_blocks( $blocks ) ); + } + + /** + * Native insert and update APIs run identical KSES serialization. + * + * @return array + */ + public function dp_advanced_content_save(): array { + return [ + 'insert' => [ 'insert' ], + 'update' => [ 'update' ], + ]; + } + + /** + * Start the next native request with the integrations disabled in all tabs. + * + * @return void + */ + private function disable_kadence_modules(): void { + $settings = (array) get_option( 'hcaptcha_settings', [] ); + $settings['kadence_status'] = []; + update_option( 'hcaptcha_settings', $settings ); + hcaptcha()->init_hooks(); + $this->load_kadence_modules( [] ); + } + + /** + * Store a classic form in a location accepted by the native handler. + * + * @param int $post_id Original form post. + * @param string $location Native form location. + * + * @return string + */ + private function relocate_classic_form( int $post_id, string $location ): string { + $content = get_post( $post_id )->post_content; + if ( 'nested' === $location ) { + wp_update_post( + [ + 'ID' => $post_id, + 'post_content' => '' . $content . '', + ] + ); + } elseif ( 'reusable' === $location ) { + $reference = $this->factory()->post->create( + [ + 'post_type' => 'wp_block', + 'post_content' => $content, + ] + ); + wp_update_post( + [ + 'ID' => $post_id, + 'post_content' => '', + ] + ); + } elseif ( in_array( $location, [ 'widget', 'unknown-widget' ], true ) ) { + update_option( 'widget_block', [ 5 => [ 'content' => $content ] ] ); + return 'widget' === $location ? 'block-5' : 'block-unknown'; + } + return (string) $post_id; + } + + /** + * Replay enabled module constructors using the real module settings map. + * + * Main avoids constructing classes already loaded by earlier integration tests. + * WPTestCase resets their hooks, so each case must replay the enabled modules. + * + * @param array $enabled Enabled module setting values. + * @param bool $frontend Whether to simulate a frontend request. + * @param string $ajax_action Native AJAX action, or empty for an editor save. + * + * @return void + */ + private function load_kadence_modules( array $enabled, bool $frontend = false, string $ajax_action = 'kb_process_ajax_submit' ): void { + $this->set_kadence_request( $frontend, $ajax_action ); + hcaptcha()->settings()->set( 'kadence_status', $enabled ); + hcaptcha()->load_modules(); + + foreach ( $GLOBALS['wp_filter'] as $hook_name => $hook ) { + foreach ( $hook->callbacks as $priority => $callbacks ) { + foreach ( $callbacks as $callback ) { + $function = $callback['function']; + if ( is_array( $function ) && $function[0] instanceof Base ) { + remove_filter( $hook_name, $function, $priority ); + } + } + } + } + remove_all_filters( 'block_parser_class' ); + + foreach ( [ 'Kadence Form', 'Kadence Advanced Form' ] as $name ) { + $module = hcaptcha()->modules[ $name ]; + if ( hcaptcha()->settings()->is( $module[0][0], $module[0][1] ) ) { + $class = $module[2]; + new $class(); + } + } + } + + /** + * Model the native WordPress request before module hooks are registered. + * + * @param bool $frontend Whether to simulate a frontend request. + * @param string $ajax_action Native AJAX action, or empty for an editor save. + * + * @return void + */ + private function set_kadence_request( bool $frontend, string $ajax_action ): void { + $_SERVER['REQUEST_METHOD'] = $frontend ? 'GET' : 'POST'; + if ( $frontend || '' === $ajax_action ) { + remove_filter( 'wp_doing_ajax', '__return_true' ); + } else { + add_filter( 'wp_doing_ajax', '__return_true' ); + } + if ( ! $frontend ) { + $_POST['action'] = $ajax_action ?: 'editpost'; + $_REQUEST['action'] = $ajax_action ?: 'editpost'; + } + } + + /** + * Create a native classic form with a safe email action. + * + * @param bool|null $captcha Native CAPTCHA setting, or absence. + * + * @return int + */ + private function create_classic_form( ?bool $captcha ): int { + $attributes = [ + 'uniqueID' => 'sec003-classic', + 'recaptchaVersion' => 'v2', + 'honeyPot' => true, + 'fields' => [ + [ + 'type' => 'text', + 'label' => 'Name', + 'required' => true, + 'multiSelect' => false, + ], + ], + 'actions' => [ 'email' ], + 'email' => [ + [ + 'emailTo' => 'sec003-recipient@example.com', + 'subject' => 'SEC003 native form', + 'html' => false, + ], + ], + ]; + if ( null !== $captcha ) { + $attributes['recaptcha'] = $captcha; + } + + return $this->factory()->post->create( + [ + 'post_status' => 'publish', + 'post_content' => '', + ] + ); + } + + /** + * Check whether classic hCaptcha verification is hooked before Kadence. + * + * @return bool + */ + private function has_classic_verifier(): bool { + $callbacks = $GLOBALS['wp_filter']['wp_ajax_nopriv_kb_process_ajax_submit']->callbacks[9] ?? []; + foreach ( $callbacks as $callback ) { + if ( is_array( $callback['function'] ) && $callback['function'][0] instanceof Form ) { + return true; + } + } + return false; + } + + /** + * Run the native AJAX action, capture email, and stop at the JSON exit. + * + * @return array + * @noinspection JsonEncodingApiUsageInspection + */ + private function submit_classic_form(): array { + $mail = []; + $mail_capture = static function ( $pre, array $args ) use ( &$mail ) { + $mail[] = $args; + return true; + }; + $die_handler = static function () { + return static function () { + throw new RuntimeException( 'sec003-json-exit' ); + }; + }; + add_filter( 'pre_wp_mail', $mail_capture, PHP_INT_MAX, 2 ); + add_filter( 'wp_die_ajax_handler', $die_handler ); + $level = ob_get_level(); + ob_start(); + try { + do_action( 'wp_ajax_nopriv_kb_process_ajax_submit' ); + self::fail( 'The native AJAX action must terminate with JSON.' ); + } catch ( RuntimeException $error ) { + self::assertSame( 'sec003-json-exit', $error->getMessage() ); + $json = ob_get_contents(); + } finally { + while ( ob_get_level() > $level ) { + ob_end_clean(); + } + remove_filter( 'pre_wp_mail', $mail_capture, PHP_INT_MAX ); + remove_filter( 'wp_die_ajax_handler', $die_handler ); + } + return [ + 'json' => json_decode( $json, true ), + 'mail' => $mail, + ]; + } +} diff --git a/tests/php/integration/Kadence/FormTest.php b/tests/php/integration/Kadence/FormTest.php index c390f3aaf..99fdb759b 100644 --- a/tests/php/integration/Kadence/FormTest.php +++ b/tests/php/integration/Kadence/FormTest.php @@ -12,6 +12,7 @@ namespace HCaptcha\Tests\Integration\Kadence; +use HCaptcha\Helpers\API; use HCaptcha\Helpers\HCaptcha; use HCaptcha\Kadence\Form; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; @@ -27,6 +28,50 @@ * @group kadence-form */ class FormTest extends HCaptchaPluginWPTestCase { + /** + * Resolve native widget and nested block locations safely. + */ + public function test_form_block_lookup_fallbacks(): void { + $subject = new Form(); + $get_blocks = $this->set_method_accessibility( $subject, 'get_form_blocks' ); + $get_form = $this->set_method_accessibility( $subject, 'get_form' ); + $get_reference = $this->set_method_accessibility( $subject, 'get_referenced_form' ); + $nested_form = [ + 'blockName' => 'kadence/form', + 'attrs' => [ 'uniqueID' => 'target' ], + ]; + + $_POST['_kb_form_id'] = []; + self::assertSame( [], $get_blocks->invoke( $subject, 'block-unknown' ) ); + + $_POST['_kb_form_id'] = 'missing'; + self::assertSame( [], $get_blocks->invoke( $subject, 'block-unknown' ) ); + self::assertSame( + $nested_form, + $get_form->invoke( + $subject, + [ + [ + 'blockName' => 'core/group', + 'innerBlocks' => [ $nested_form ], + ], + ], + 'target' + ) + ); + self::assertSame( + [], + $get_reference->invoke( + $subject, + [ + 'blockName' => 'core/block', + 'attrs' => [ 'ref' => 9999999 ], + ], + 'target', + [] + ) + ); + } /** * Kadence Blocks plugin entry file. @@ -343,4 +388,267 @@ public function test_enqueue_scripts(): void { self::assertTrue( wp_script_is( $handle ) ); } + /** + * A malformed post selector cannot borrow another post's exemption. + * + * @param string $separator Text removed by Kadence's native sanitizer. + * + * @return void + * @dataProvider dp_sec020_post_id_aliases + */ + public function test_sec020_malformed_post_id_uses_native_identity( string $separator ): void { + [ $exempt_id, $protected_id, $suffix ] = $this->create_sec020_forms(); + $alias = $exempt_id . $separator . $suffix; + self::assertSame( (string) $protected_id, sanitize_text_field( wp_unslash( $alias ) ) ); + + $exempt = $this->exempt_sec020_form( $exempt_id ); + + try { + $_POST['_kb_form_id'] = 'sec020-form'; + $this->prepare_widget_id( $exempt_id ); + $subject = new Form(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( + $subject, + [ + '_kb_form_post_id' => $alias, + 'kb_field_0' => 'reader@example.com', + ] + ); + + self::assertSame( $protected_id, $entry['expected_id']['form_id'] ); + self::assertSame( get_post( $protected_id )->post_modified_gmt, $entry['form_date_gmt'] ); + self::assertSame( 'reader@example.com', $entry['data']['Protected contact'] ?? null ); + self::assertArrayNotHasKey( 'Exempt contact', $entry['data'] ); + self::assertSame( 'Bad hCaptcha signature!', API::verify_request( null, $entry ) ); + } finally { + remove_filter( 'hcap_protect_form', $exempt ); + } + } + + /** + * Encoded separators that Kadence removes before post lookup. + * + * @return array + */ + public function dp_sec020_post_id_aliases(): array { + return [ + 'HTML tag' => [ '
      ' ], + 'percent escape' => [ '%20' ], + ]; + } + + /** + * A canonical signed exemption remains valid for its own post. + * + * @return void + */ + public function test_sec020_own_exemption_remains_valid(): void { + [ $exempt_id ] = $this->create_sec020_forms(); + $exempt = $this->exempt_sec020_form( $exempt_id ); + + try { + $_POST['_kb_form_id'] = 'sec020-form'; + $this->prepare_widget_id( $exempt_id ); + $subject = new Form(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( + $subject, + [ '_kb_form_post_id' => (string) $exempt_id ] + ); + + self::assertSame( $exempt_id, $entry['expected_id']['form_id'] ); + self::assertNull( API::verify_request( null, $entry ) ); + } finally { + remove_filter( 'hcap_protect_form', $exempt ); + } + } + + /** + * A protected canonical post still accepts a verified challenge. + * + * @return void + */ + public function test_sec020_protected_post_accepts_valid_challenge(): void { + [ , $protected_id ] = $this->create_sec020_forms(); + $response = 'sec020-valid-response'; + $this->prepare_verify_request( $response ); + $_POST['_kb_form_id'] = 'sec020-form'; + $this->prepare_widget_id( $protected_id ); + $subject = new Form(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( + $subject, + [ + '_kb_form_post_id' => (string) $protected_id, + 'h-captcha-response' => $response, + ] + ); + + self::assertSame( $protected_id, $entry['expected_id']['form_id'] ); + self::assertNull( API::verify_request( $response, $entry ) ); + } + + /** + * Create two real Kadence form posts whose ids share a numeric prefix. + * + * @return array{int, int, string} + */ + private function create_sec020_forms(): array { + $form_id = 'sec020-form'; + $exempt_id = 0; + $protected_id = 0; + $suffix = ''; + + // Use vacant low IDs so repeated tests do not grow AUTO_INCREMENT. + for ( $candidate = 100; $candidate < 1000 && ! $exempt_id; ++$candidate ) { + if ( get_post( $candidate ) ) { + continue; + } + + for ( $digit = 1; $digit <= 9; ++$digit ) { + $target = (int) ( $candidate . $digit ); + + if ( ! get_post( $target ) ) { + $exempt_id = $candidate; + $protected_id = $target; + $suffix = (string) $digit; + break; + } + } + } + + self::assertNotSame( 0, $exempt_id ); + $created_id = $this->factory()->post->create( + [ + 'import_id' => $exempt_id, + 'post_content' => '', + ] + ); + self::assertSame( $exempt_id, $created_id ); + $created_id = $this->factory()->post->create( + [ + 'import_id' => $protected_id, + 'post_content' => '', + ] + ); + self::assertSame( $protected_id, $created_id ); + + return [ $exempt_id, $protected_id, $suffix ]; + } + + /** + * Exempt only the specified Kadence form post. + * + * @param int $form_id Form post id. + * + * @return callable + */ + private function exempt_sec020_form( int $form_id ): callable { + $exempt = static function ( $protect, $source, $candidate ) use ( $form_id ) { + return [ 'kadence-blocks/kadence-blocks.php' ] === $source && $form_id === $candidate ? false : $protect; + }; + add_filter( 'hcap_protect_form', $exempt, 10, 3 ); + + return $exempt; + } + + /** + * Apply email policy independently of labels and the last email field. + * + * @param bool $blocked Whether the trusted email is disposable. + * @dataProvider dp_sec063_email_policy + */ + public function test_sec063_typed_email_policy( bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $post_id = $this->factory()->post->create( + [ 'post_content' => '' ] + ); + $_POST['_kb_form_id'] = 'sec063'; + $this->prepare_widget_id( $post_id ); + $data = [ + '_kb_form_post_id' => $post_id, + 'kb_field_0' => $blocked ? ' person@sec063-disposable.test ' : ' person@example.com ', + 'kb_field_1' => 'reader@example.com', + 'kb_field_2' => 'spoof@sec063-disposable.test', + ]; + $subject = new Form(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $data ); + + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + /** + * Exercise both policy rejection and permanent address acceptance. + * + * @return array + */ + public function dp_sec063_email_policy(): array { + return [ + 'disposable' => [ true ], + 'permanent' => [ false ], + ]; + } + /** + * Apply native email policy in reusable blocks and supported block widgets. + * + * @param string $location Native form location. + * @param bool $blocked Whether the submitted address is disposable. + * @dataProvider dp_sec063_native_locations + */ + public function test_sec063_native_location_policy( string $location, bool $blocked ): void { + $this->prepare_verify_request( 'sec063-challenge' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec063-disposable.test' => true ] ); + $content = ''; + $post_id = 0; + if ( in_array( $location, [ 'reusable', 'reusable-cycle' ], true ) ) { + $reference = $this->factory()->post->create( + [ + 'post_type' => 'wp_block', + 'post_content' => $content, + ] + ); + + if ( 'reusable-cycle' === $location ) { + wp_update_post( + [ + 'ID' => $reference, + 'post_content' => '' . $content, + ] + ); + } + $post_id = $this->factory()->post->create( [ 'post_content' => '' ] ); + $native_post_id = $post_id; + } else { + update_option( 'widget_block', [ 5 => [ 'content' => $content ] ] ); + $native_post_id = 'unknown-widget' === $location ? 'block-unknown' : 'block-5'; + } + $_POST['_kb_form_id'] = 'sec063-location'; + $this->prepare_widget_id( $post_id ); + $data = [ + '_kb_form_post_id' => $native_post_id, + 'kb_field_0' => $blocked ? 'person@sec063-disposable.test' : 'reader@example.com', + 'kb_field_1' => 'spoof@sec063-disposable.test', + ]; + $subject = new Form(); + $entry = $this->set_method_accessibility( $subject, 'get_entry' )->invoke( $subject, $data ); + self::assertSame( $blocked ? 'Please use a permanent email address.' : null, API::verify_request( null, $entry ) ); + } + + /** + * Supported native form locations and block/allow controls. + * + * @return array + */ + public function dp_sec063_native_locations(): array { + return [ + 'reusable blocked' => [ 'reusable', true ], + 'reusable allowed' => [ 'reusable', false ], + 'reusable cycle blocked' => [ 'reusable-cycle', true ], + 'reusable cycle allowed' => [ 'reusable-cycle', false ], + 'widget blocked' => [ 'widget', true ], + 'widget allowed' => [ 'widget', false ], + 'unknown widget blocked' => [ 'unknown-widget', true ], + 'unknown widget allowed' => [ 'unknown-widget', false ], + ]; + } } diff --git a/tests/php/integration/LearnDash/LostPasswordTest.php b/tests/php/integration/LearnDash/LostPasswordTest.php index 33843c709..3b9fef297 100644 --- a/tests/php/integration/LearnDash/LostPasswordTest.php +++ b/tests/php/integration/LearnDash/LostPasswordTest.php @@ -56,4 +56,13 @@ public function test_add_captcha(): void { self::assertStringContainsString( 'name="hcap_hp_test"', $output ); self::assertStringContainsString( 'name="hcap_hp_sig"', $output ); } + + /** + * Leave other shortcodes unchanged. + */ + public function test_add_captcha_ignores_other_shortcodes(): void { + $output = '
      '; + + self::assertSame( $output, ( new LostPassword() )->add_captcha( $output, 'other', [], [] ) ); + } } diff --git a/tests/php/integration/LearnDash/RegisterTest.php b/tests/php/integration/LearnDash/RegisterTest.php index 2de49c8d1..e4c0b56c8 100644 --- a/tests/php/integration/LearnDash/RegisterTest.php +++ b/tests/php/integration/LearnDash/RegisterTest.php @@ -20,6 +20,45 @@ * @group learn-dash-register */ class RegisterTest extends HCaptchaWPTestCase { + /** + * Reject an unknown owner and defer a widget owned by another verifier. + */ + public function test_verify_request_ownership(): void { + $subject = new Register(); + $errors = new WP_Error(); + + $_POST['learndash-registration-form'] = '1'; + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = 'invalid'; + + self::assertSame( 'Bad hCaptcha signature!', $subject->verify( $errors, '', '' )->get_error_message( 'bad-signature' ) ); + + $this->prepare_widget_id(); + $errors = new WP_Error(); + $other_owner = static function (): string { + return WPRegister::class; + }; + add_filter( 'hcap_registration_request_owner', $other_owner ); + + try { + self::assertSame( $errors, $subject->verify( $errors, '', '' ) ); + } finally { + remove_filter( 'hcap_registration_request_owner', $other_owner ); + } + } + + /** + * Publish native registration errors and the form spacing rule. + */ + public function test_registration_errors_and_inline_styles(): void { + $subject = new Register(); + + self::assertArrayHasKey( 'bad-signature', $subject->add_registration_errors( [] ) ); + + ob_start(); + $subject->print_inline_styles(); + + self::assertStringContainsString( '#learndash_registerform .h-captcha', ob_get_clean() ); + } /** * Set up the test. @@ -31,7 +70,7 @@ public function setUp(): void { hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); - hcaptcha()->settings()->set( 'learn_dash_status', 'register' ); + hcaptcha()->settings()->set( 'learn_dash_status', [ 'register' ] ); $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } @@ -98,10 +137,98 @@ public function test_wordpress_register_defers_to_learndash_owner(): void { $wp_register = new WPRegister(); $errors = new WP_Error( 'some-code', 'some-message' ); - $_POST['action'] = 'register'; + $_POST['action'] = 'register'; + $_POST['learndash-registration-form'] = '1'; $this->prepare_widget_id(); self::assertSame( $errors, $wp_register->verify( $errors, '', '' ) ); + self::assertSame( [ 'some-code' ], $errors->get_error_codes() ); + } + + /** + * Test a foreign signature cannot suppress native registration without its marker. + * + * @dataProvider dp_test_callback_orders + * + * @param bool $native_first Whether the native verifier is registered first. + */ + public function test_foreign_owner_without_marker( bool $native_first ): void { + if ( $native_first ) { + new WPRegister(); + new Register(); + } else { + new Register(); + new WPRegister(); + } + + $_POST['action'] = 'register'; + $this->prepare_widget_id(); + + $errors = apply_filters( 'registration_errors', new WP_Error(), 'guest', 'guest@example.com' ); + + self::assertSame( 'Bad hCaptcha signature!', $errors->get_error_message( 'bad-signature' ) ); + } + + /** + * Test a registered LearnDash owner still rejects a missing challenge. + * + * @dataProvider dp_test_callback_orders + * + * @param bool $native_first Whether the native verifier is registered first. + */ + public function test_owner_with_marker_requires_challenge( bool $native_first ): void { + if ( $native_first ) { + new WPRegister(); + new Register(); + } else { + new Register(); + new WPRegister(); + } + + $_POST['action'] = 'register'; + $_POST['learndash-registration-form'] = '1'; + $this->prepare_widget_id(); + $this->prepare_verify_post( 'hcaptcha_learn_dash_register_nonce', 'hcaptcha_learn_dash_register' ); + $_POST['h-captcha-response'] = ''; + + $errors = apply_filters( 'registration_errors', new WP_Error(), 'guest', 'guest@example.com' ); + + self::assertSame( 'Please complete the hCaptcha.', $errors->get_error_message( 'empty' ) ); + self::assertSame( '', $errors->get_error_message( 'bad-signature' ) ); + } + + /** + * Test unmatched AutoVerify cannot defer to LearnDash without its marker. + */ + public function test_auto_verify_requires_owner_marker(): void { + $_POST['action'] = 'register'; + $widget_id = HCaptcha::widget_id_value( + [ + 'source' => [ 'sfwd-lms/sfwd_lms.php' ], + 'form_id' => 'register', + ] + ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = $widget_id; + $subject = new Register(); + $form = [ 'widget_id' => 'different' ]; + $path = untrailingslashit( (string) wp_parse_url( wp_login_url(), PHP_URL_PATH ) ); + + self::assertSame( + $form, + $subject->defer_auto_verification( $form, $path, $widget_id ) + ); + } + + /** + * Callback order variants. + * + * @return array + */ + public function dp_test_callback_orders(): array { + return [ + 'native first' => [ true ], + 'owner first' => [ false ], + ]; } /** @@ -153,4 +280,46 @@ private function prepare_widget_id(): void { ] ); } + + /** + * Check the native callback email instead of arbitrary submitted aliases. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native email. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $_POST['learndash-registration-form'] = '1'; + $_POST['email'] = 'safe@example.com'; + $this->prepare_widget_id(); + $this->prepare_verify_post( 'hcaptcha_learn_dash_register_nonce', 'hcaptcha_learn_dash_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'learn_dash_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + + $result = ( new Register() )->verify( new WP_Error(), 'guest', $email ); + + self::assertSame( $blocked ? hcap_get_error_messages()['disposable-email'] : '', $result->get_error_message( 'disposable-email' ) ); + } + + /** + * Native email policy controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable email' => [ 'user@disposable.example', true ], + 'permanent email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } } diff --git a/tests/php/integration/LearnPress/CheckoutTest.php b/tests/php/integration/LearnPress/CheckoutTest.php index 5917c46be..02b8f6146 100644 --- a/tests/php/integration/LearnPress/CheckoutTest.php +++ b/tests/php/integration/LearnPress/CheckoutTest.php @@ -59,7 +59,7 @@ public function setUp(): void { hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); - hcaptcha()->settings()->set( 'learn_press_status', 'checkout' ); + hcaptcha()->settings()->set( 'learn_press_status', [ 'checkout' ] ); $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } @@ -70,6 +70,7 @@ public function setUp(): void { */ public function tearDown(): void { wp_set_current_user( 0 ); + unset( $_REQUEST['reg_email'], $_REQUEST['guest_email'], $_REQUEST['username'] ); parent::tearDown(); } @@ -345,4 +346,76 @@ private function prepare_widget_id(): void { ] ); } + + /** + * Check native checkout mode precedence before account or order creation. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $mode Native checkout mode. + * @param string $email Native accepted address. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $mode, string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + wp_set_current_user( 0 ); + $this->set_protected_property( LearnPress::instance()->checkout(), '_checkout_email', '' ); + if ( 'login' === $mode || 'current' === $mode ) { + $user_id = $this->factory()->user->create( [ 'user_email' => $email ] ); + $user = get_userdata( $user_id ); + if ( 'current' === $mode ) { + wp_set_current_user( $user_id ); + } else { + $_POST['username'] = $user->user_login; + $_REQUEST['username'] = $user->user_login; + } + } else { + $field = 'register' === $mode ? 'reg_email' : 'guest_email'; + $_POST[ $field ] = $email; + $_REQUEST[ $field ] = $email; + } + if ( 'register' === $mode || 'login' === $mode ) { + $_POST['guest_email'] = 'safe@example.com'; + $_REQUEST['guest_email'] = 'safe@example.com'; + } + $_POST['email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_learn_press_checkout_nonce', 'hcaptcha_learn_press_checkout' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'learn_press_status', [ 'checkout' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $this->prepare_widget_id(); + $message = ''; + + try { + ( new Checkout() )->verify(); + } catch ( Exception $exception ) { + $message = $exception->getMessage(); + } + + self::assertSame( $blocked ? hcap_get_error_messages()['disposable-email'] : '', $message ); + } + + /** + * Native checkout address controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable register before guest' => [ 'register', 'user@disposable.example', true ], + 'permanent register before guest' => [ 'register', 'safe@example.com', false ], + 'disposable guest' => [ 'guest', 'user@disposable.example', true ], + 'permanent guest' => [ 'guest', 'safe@example.com', false ], + 'disposable login recipient' => [ 'login', 'user@disposable.example', true ], + 'permanent login recipient' => [ 'login', 'safe@example.com', false ], + 'disposable current user' => [ 'current', 'user@disposable.example', true ], + 'permanent current user' => [ 'current', 'safe@example.com', false ], + ]; + } } diff --git a/tests/php/integration/LearnPress/RegisterEmailPolicyTest.php b/tests/php/integration/LearnPress/RegisterEmailPolicyTest.php new file mode 100644 index 000000000..c1f474d95 --- /dev/null +++ b/tests/php/integration/LearnPress/RegisterEmailPolicyTest.php @@ -0,0 +1,228 @@ +add_hcaptcha(); + + self::assertSame( '', ob_get_clean() ); + } + + /** + * Native plugin dependency. + * + * @var string + */ + protected static $plugin = 'learnpress/learnpress.php'; + + /** + * Native lifecycle hooks. + * + * @var string[] + */ + protected static array $plugin_load_hooks = [ 'init' ]; + + /** + * Restore the native lifecycle after the WordPress test case resets hooks. + * + * @var bool + */ + protected static bool $force_plugin_load_hooks = true; + + /** + * Restore request globals after each native registration route. + * + * @return void + */ + public function tearDown(): void { + unset( + $_GET['learn-press-register-nonce'], + $_REQUEST['learn-press-register-nonce'] + ); + + parent::tearDown(); + } + + /** + * A nonce accepted by native registration must also run hCaptcha verification. + * + * @dataProvider dp_test_native_nonce_location + * + * @param string $location Native nonce location. + */ + public function test_native_nonce_without_hcaptcha_blocks_registration( string $location ): void { + wp_set_current_user( 0 ); + $nonce = wp_create_nonce( 'learn-press-register' ); + $password = 'A-strong-test-password-123!'; + + if ( 'post' === $location ) { + $_POST['learn-press-register-nonce'] = $nonce; + } else { + $_GET['learn-press-register-nonce'] = $nonce; + } + + $_REQUEST['learn-press-register-nonce'] = $nonce; + $_POST['reg_username'] = 'sec037-registration'; + $_POST['reg_email'] = 'sec037-registration@example.com'; + $_POST['reg_password'] = $password; + $_POST['reg_password2'] = $password; + + $this->prepare_verify_post( 'hcaptcha_learn_press_register_nonce', 'hcaptcha_learn_press_register', null ); + + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'learnpress/learnpress.php' ], + 'form_id' => 'register', + ] + ); + unset( $_POST['h-captcha-response'] ); + delete_option( 'lp-customer-message' ); + $customer_id = LP_Session_Handler::instance()->get_customer_id(); + + self::assertNotFalse( LP_Request::verify_nonce( 'learn-press-register' ) ); + self::assertNotFalse( has_action( 'wp_loaded', [ 'LP_Forms_Handler', 'init' ] ) ); + + ( new Register() )->verify(); + + self::assertFalse( has_action( 'wp_loaded', [ 'LP_Forms_Handler', 'init' ] ) ); + self::assertSame( + [ + $customer_id => [ + 'status' => 'error', + 'content' => hcap_get_error_messages()['empty'], + ], + ], + get_option( 'lp-customer-message', [] ) + ); + self::assertFalse( email_exists( 'sec037-registration@example.com' ) ); + } + + /** + * Native nonce locations. + * + * @return array + */ + public function dp_test_native_nonce_location(): array { + return [ + 'POST nonce' => [ 'post' ], + 'query nonce' => [ 'query' ], + ]; + } + + /** + * Invalid or malformed native nonces must leave unrelated requests alone. + * + * @dataProvider dp_test_invalid_native_nonce + * + * @param mixed $nonce Native nonce value. + */ + public function test_invalid_native_nonce_is_ignored( $nonce ): void { + if ( null !== $nonce ) { + $_REQUEST['learn-press-register-nonce'] = $nonce; + } + + $_POST['reg_email'] = 'sec037-registration@example.com'; + delete_option( 'lp-customer-message' ); + self::assertNotFalse( has_action( 'wp_loaded', [ 'LP_Forms_Handler', 'init' ] ) ); + + ( new Register() )->verify(); + + self::assertNotFalse( has_action( 'wp_loaded', [ 'LP_Forms_Handler', 'init' ] ) ); + self::assertSame( [], get_option( 'lp-customer-message', [] ) ); + } + + /** + * Invalid native nonce values. + * + * @return array + */ + public function dp_test_invalid_native_nonce(): array { + return [ + 'absent nonce' => [ null ], + 'invalid nonce' => [ 'not-a-valid-nonce' ], + 'array nonce' => [ [ 'not-a-valid-nonce' ] ], + ]; + } + + /** + * Validate the native address instead of a generic alias. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native email. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $nonce = wp_create_nonce( 'learn-press-register' ); + $_POST['learn-press-register-nonce'] = $nonce; + $_REQUEST['learn-press-register-nonce'] = $nonce; + $_POST['reg_email'] = $email; + $_POST['email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_learn_press_register_nonce', 'hcaptcha_learn_press_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'learn_press_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'learnpress/learnpress.php' ], + 'form_id' => 'register', + ] + ); + delete_option( 'lp-customer-message' ); + $customer_id = LP_Session_Handler::instance()->get_customer_id(); + + ( new Register() )->verify(); + + self::assertSame( + $blocked ? [ + $customer_id => [ + 'status' => 'error', + 'content' => hcap_get_error_messages()['disposable-email'], + ], + ] : [], + get_option( 'lp-customer-message', [] ) + ); + } + + /** + * Native email controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable native email' => [ 'user@disposable.example', true ], + 'permanent native email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } +} diff --git a/tests/php/integration/LoginSignupPopup/RegisterTest.php b/tests/php/integration/LoginSignupPopup/RegisterTest.php index 7a89926bd..1e53c34e9 100644 --- a/tests/php/integration/LoginSignupPopup/RegisterTest.php +++ b/tests/php/integration/LoginSignupPopup/RegisterTest.php @@ -30,7 +30,7 @@ public function setUp(): void { hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); - hcaptcha()->settings()->set( 'login_signup_popup_status', 'register' ); + hcaptcha()->settings()->set( 'login_signup_popup_status', [ 'register' ] ); $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } @@ -61,6 +61,54 @@ public function test_add_captcha(): void { self::assertStringContainsString( 'name="hcap_hp_sig"', $output ); } + /** + * Login forms do not start a registration buffer or render registration hCaptcha. + */ + public function test_other_form_is_ignored(): void { + $subject = new Register(); + $level = ob_get_level(); + $subject->form_start( 'login', [] ); + $subject->add_login_signup_popup_hcaptcha( 'login', [] ); + + self::assertSame( $level, ob_get_level() ); + } + + /** + * Registration verification wraps a missing native error container. + */ + public function test_verify_without_native_error(): void { + $this->prepare_verify_post( 'hcaptcha_login_signup_popup_register_nonce', 'hcaptcha_login_signup_popup_register' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-login-woocommerce/xoo-el-main.php' ], + 'form_id' => 'register', + ] + ); + + $result = ( new Register() )->verify( null, 'user', 'password', 'person@example.com' ); + self::assertFalse( $result->has_errors() ); + } + + /** + * Registration frontend assets are available to the native popup form. + */ + public function test_frontend_assets(): void { + $subject = new Register(); + ob_start(); + $subject->print_inline_styles(); + self::assertStringContainsString( 'div[data-section="register"] .h-captcha', ob_get_clean() ); + + try { + $subject->enqueue_scripts(); + $script = wp_scripts()->registered['hcaptcha-login-signup-popup']; + self::assertStringContainsString( 'hcaptcha-login-signup-popup', $script->src ); + self::assertSame( HCAPTCHA_VERSION, $script->ver ); + } finally { + wp_dequeue_script( 'hcaptcha-login-signup-popup' ); + wp_deregister_script( 'hcaptcha-login-signup-popup' ); + } + } + /** * Test a filled honeypot blocks registration. * @@ -84,4 +132,50 @@ public function test_filled_honeypot_is_rejected(): void { self::assertSame( 'Anti-spam check failed.', $result->get_error_message( 'spam' ) ); } + + /** + * Check the authoritative native email through the production API. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native address. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + $_POST['email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_login_signup_popup_register_nonce', 'hcaptcha_login_signup_popup_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'login_signup_popup_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'easy-login-woocommerce/xoo-el-main.php' ], + 'form_id' => 'register', + ] + ); + + $result = ( new Register() )->verify( new WP_Error(), 'guest', '', $email ); + + self::assertSame( $blocked ? hcap_get_error_messages()['disposable-email'] : '', $result->get_error_message() ); + } + + /** + * Native email policy controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable email' => [ 'user@disposable.example', true ], + 'permanent email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } } diff --git a/tests/php/integration/MailPoet/FormTest.php b/tests/php/integration/MailPoet/FormTest.php index 3496ae002..487c2c4ed 100644 --- a/tests/php/integration/MailPoet/FormTest.php +++ b/tests/php/integration/MailPoet/FormTest.php @@ -12,6 +12,7 @@ namespace HCaptcha\Tests\Integration\MailPoet; +use HCaptcha\Helpers\API as HCaptchaAPI; use HCaptcha\Helpers\HCaptcha; use HCaptcha\MailPoet\Form; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; @@ -21,8 +22,10 @@ use MailPoet\DI\ContainerWrapper; use MailPoet\Entities\FormEntity; use MailPoet\Form\FormsRepository; +use MailPoet\Form\Util\FieldNameObfuscator; use Mockery; use ReflectionClass; +use ReflectionMethod; /** * Test Form class. @@ -30,6 +33,19 @@ * @group mailpoet */ class FormTest extends HCaptchaPluginWPTestCase { + /** + * Request method before an admin-post test changes it. + * + * @var string|null + */ + private ?string $original_request_method = null; + + /** + * Whether an admin-post test changed the request method. + * + * @var bool + */ + private bool $request_method_changed = false; /** * MailPoet plugin entry file. @@ -61,7 +77,15 @@ class FormTest extends HCaptchaPluginWPTestCase { * Tear down the test. */ public function tearDown(): void { - unset( $_POST['action'], $_POST['endpoint'], $_POST['method'], $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] ); + unset( $_GET['action'], $_GET['data'], $_REQUEST['action'], $_REQUEST['data'], $_REQUEST['api_version'], $_REQUEST['endpoint'], $_REQUEST['method'], $_REQUEST['mailpoet_method'], $_REQUEST['token'], $_POST['action'], $_POST['data'], $_POST['api_version'], $_POST['endpoint'], $_POST['method'], $_POST['mailpoet_method'], $_POST['token'], $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] ); + + if ( $this->request_method_changed ) { + if ( null === $this->original_request_method ) { + unset( $_SERVER['REQUEST_METHOD'] ); + } else { + $_SERVER['REQUEST_METHOD'] = $this->original_request_method; + } + } parent::tearDown(); } @@ -134,6 +158,8 @@ public function test_init_hooks(): void { self::assertSame( 20, has_filter( 'the_content', [ $subject, 'the_content_filter' ] ) ); self::assertSame( 10, has_action( 'mailpoet_api_setup', [ $subject, 'verify' ] ) ); + self::assertSame( 0, has_action( 'admin_post_mailpoet_subscription_form', [ $subject, 'verify_admin_post' ] ) ); + self::assertSame( 0, has_action( 'admin_post_nopriv_mailpoet_subscription_form', [ $subject, 'verify_admin_post' ] ) ); self::assertSame( 9, has_action( 'wp_print_footer_scripts', [ $subject, 'enqueue_scripts' ] ) ); } @@ -198,10 +224,11 @@ public function test_verify(): void { $subject->verify( $api ); // Verify with $_POST['data'] having only form_id to cover an empty $fields path. - $_POST['action'] = 'mailpoet'; - $_POST['endpoint'] = 'subscribers'; - $_POST['method'] = 'subscribe'; - $_POST['data'] = [ + $_POST['action'] = 'mailpoet'; + $_REQUEST['action'] = 'mailpoet'; + $_POST['endpoint'] = 'subscribers'; + $_POST['method'] = 'subscribe'; + $_POST['data'] = [ 'form_id' => '1', ]; @@ -227,9 +254,10 @@ public function test_verify_with_data(): void { $subject = new Form(); - $_POST['action'] = 'mailpoet'; - $_POST['endpoint'] = 'subscribers'; - $_POST['method'] = 'subscribe'; + $_POST['action'] = 'mailpoet'; + $_REQUEST['action'] = 'mailpoet'; + $_POST['endpoint'] = 'subscribers'; + $_POST['method'] = 'subscribe'; // Verify with $_POST['data'] set. $_POST['data'] = [ @@ -244,6 +272,97 @@ public function test_verify_with_data(): void { $subject->verify( $api ); } + /** + * The disposable-email policy must inspect the address MailPoet decodes as its email field. + * + * @dataProvider dp_native_email_field_projection + * + * @param array $fields Native field names and submitted values, in POST order. + * @param string $expected_email Address retained by MailPoet's native decoder. + * @param bool $blocked Whether the disposable-email policy must reject it. + */ + public function test_native_email_field_projection( array $fields, string $expected_email, bool $blocked ): void { + $obfuscator = ContainerWrapper::getInstance()->get( FieldNameObfuscator::class ); + $data = [ + 'form_id' => '1', + 'email' => '', + ]; + + foreach ( $fields as [ $name, $value ] ) { + $data[ $obfuscator->obfuscate( $name ) ] = $value; + } + + $_POST['data'] = $data; + $this->prepare_verify_post( 'hcaptcha_mailpoet_nonce', 'hcaptcha_mailpoet' ); + $this->prepare_widget_id( 1 ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'disposable.example' => true ] ); + + $method = new ReflectionMethod( Form::class, 'get_entry' ); + $method->setAccessible( true ); + $entry = $method->invoke( new Form() ); + $native = $obfuscator->deobfuscateFormPayload( $data ); + + self::assertSame( $expected_email, $native['email'] ); + self::assertSame( $expected_email, $entry['data']['email'] ); + self::assertSame( [ 'email' => $expected_email ], array_intersect_key( $native, [ 'email' => true ] ) ); + + $checked = []; + $capture = static function ( bool $disposable, string $email ) use ( &$checked ): bool { + $checked[] = $email; + + return $disposable; + }; + add_filter( 'hcap_is_disposable_email', $capture, 10, 2 ); + + try { + $result = HCaptchaAPI::verify( $entry ); + } finally { + remove_filter( 'hcap_is_disposable_email', $capture ); + delete_transient( 'hcaptcha_disposable_email_blocklist' ); + } + + self::assertSame( [ $expected_email ], $checked ); + self::assertSame( $blocked ? hcap_get_error_messages()['disposable-email'] : null, $result ); + } + + /** + * Both sides of the native field-name boundary and an underscored content field. + * + * @return array + */ + public function dp_native_email_field_projection(): array { + return [ + 'canonical disposable' => [ [ [ 'email', 'person@disposable.example' ] ], 'person@disposable.example', true ], + 'ignored field after' => [ [ [ 'email', 'person@disposable.example' ], [ 'spare_email', 'reader@example.com' ] ], 'person@disposable.example', true ], + 'ignored field before' => [ [ [ 'spare_email', 'reader@example.com' ], [ 'email', 'person@disposable.example' ] ], 'person@disposable.example', true ], + 'ignored disposable extra' => [ [ [ 'email', 'reader@example.com' ], [ 'spare_email', 'person@disposable.example' ] ], 'reader@example.com', false ], + 'underscored content' => [ [ [ 'email', 'reader@example.com' ], [ 'first_name', 'Ava' ] ], 'reader@example.com', false ], + 'ignored sensitive field' => [ [ [ 'email', 'reader@example.com' ], [ 'password', 'secret' ] ], 'reader@example.com', false ], + ]; + } + + /** + * Accept only the native admin-post subscription request shape. + */ + public function test_is_native_admin_post_subscription(): void { + $subject = new Form(); + $method = new ReflectionMethod( $subject, 'is_native_admin_post_subscription' ); + $method->setAccessible( true ); + + self::assertFalse( $method->invoke( $subject, [] ) ); + + $_REQUEST['endpoint'] = 'subscribers'; + $_REQUEST['method'] = 'subscribe'; + $_REQUEST['api_version'] = 'v1'; + $_REQUEST['token'] = ''; + + self::assertFalse( $method->invoke( $subject, [ 'form_id' => '1' ] ) ); + + $_REQUEST['token'] = 'native-token'; + self::assertTrue( $method->invoke( $subject, [ 'form_id' => '1' ] ) ); + } + /** * Test verify() when not verified. */ @@ -263,10 +382,11 @@ public function test_verify_not_verified(): void { $subject->verify( $api ); - $_POST['action'] = 'mailpoet'; - $_POST['endpoint'] = 'subscribers'; - $_POST['method'] = 'subscribe'; - $_POST['data'] = [ + $_POST['action'] = 'mailpoet'; + $_REQUEST['action'] = 'mailpoet'; + $_POST['endpoint'] = 'subscribers'; + $_POST['method'] = 'subscribe'; + $_POST['data'] = [ 'form_id' => '1', 'email' => '', 'form_field_YjVlNWFkMmRiYTlhX2VtYWls' => 'foo@bar.com', @@ -295,10 +415,11 @@ public function test_verify_missing_widget_id(): void { $subject = new Form(); - $_POST['action'] = 'mailpoet'; - $_POST['endpoint'] = 'subscribers'; - $_POST['method'] = 'subscribe'; - $_POST['data'] = [ + $_POST['action'] = 'mailpoet'; + $_REQUEST['action'] = 'mailpoet'; + $_POST['endpoint'] = 'subscribers'; + $_POST['method'] = 'subscribe'; + $_POST['data'] = [ 'form_id' => '1', 'email' => '', 'form_field_YjVlNWFkMmRiYTlhX2VtYWls' => 'foo@bar.com', @@ -309,6 +430,310 @@ public function test_verify_missing_widget_id(): void { $subject->verify( $api ); } + /** + * MailPoet's method alias reaches the public subscribe action without a method field. + * + * @return void + */ + public function test_verify_mailpoet_method_alias(): void { + $error_response = Mockery::mock( ErrorResponse::class ); + $error_response->shouldReceive( 'send' )->once(); + $api = Mockery::mock( API::class ); + $api->shouldReceive( 'createErrorResponse' ) + ->with( 'fail', 'The hCaptcha is invalid.', Response::STATUS_UNAUTHORIZED ) + ->once() + ->andReturn( $error_response ); + + $_REQUEST['action'] = 'mailpoet'; + $_POST['action'] = 'mailpoet'; + $_POST['api_version'] = 'v1'; + $_POST['endpoint'] = 'subscribers'; + $_POST['mailpoet_method'] = 'subscribe'; + $_POST['data'] = [ 'form_id' => '1' ]; + $this->prepare_verify_post( 'hcaptcha_mailpoet_nonce', 'hcaptcha_mailpoet', false ); + $this->prepare_widget_id( 1 ); + + ( new Form() )->verify( $api ); + } + + /** + * Native endpoint normalization can resolve alternate names to Subscribers. + * + * @param string $endpoint Native endpoint selector. + * @return void + * @dataProvider dp_subscribers_endpoint_aliases + */ + public function test_verify_subscribers_endpoint_alias( string $endpoint ): void { + $error_response = Mockery::mock( ErrorResponse::class ); + $error_response->shouldReceive( 'send' )->once(); + $api = Mockery::mock( API::class ); + $api->shouldReceive( 'createErrorResponse' ) + ->with( 'fail', 'The hCaptcha is invalid.', Response::STATUS_UNAUTHORIZED ) + ->once() + ->andReturn( $error_response ); + + $_REQUEST['action'] = 'mailpoet'; + $_POST['api_version'] = 'v1'; + $_POST['endpoint'] = $endpoint; + $_POST['mailpoet_method'] = 'subscribe'; + $_POST['data'] = [ 'form_id' => '1' ]; + $this->prepare_verify_post( 'hcaptcha_mailpoet_nonce', 'hcaptcha_mailpoet', false ); + $this->prepare_widget_id( 1 ); + + ( new Form() )->verify( $api ); + } + + /** + * Alternate native names that resolve to Subscribers. + * + * @return array + */ + public function dp_subscribers_endpoint_aliases(): array { + return [ + 'leading underscore' => [ '_subscribers' ], + 'capitalized' => [ 'Subscribers' ], + ]; + } + + /** + * WordPress may select the AJAX action from the query while MailPoet selects the alias from POST. + * + * @return void + */ + public function test_verify_query_action_and_conflicting_method(): void { + $error_response = Mockery::mock( ErrorResponse::class ); + $error_response->shouldReceive( 'send' )->once(); + $api = Mockery::mock( API::class ); + $api->shouldReceive( 'createErrorResponse' ) + ->with( 'fail', 'The hCaptcha is invalid.', Response::STATUS_UNAUTHORIZED ) + ->once() + ->andReturn( $error_response ); + + $_GET['action'] = 'mailpoet'; + $_REQUEST['action'] = 'mailpoet'; + $_POST['api_version'] = 'v1'; + $_POST['endpoint'] = 'subscribers'; + $_POST['method'] = 'other'; + $_POST['mailpoet_method'] = 'subscribe'; + $_POST['data'] = [ 'form_id' => '1' ]; + $this->prepare_verify_post( 'hcaptcha_mailpoet_nonce', 'hcaptcha_mailpoet', false ); + $this->prepare_widget_id( 1 ); + + ( new Form() )->verify( $api ); + } + + /** + * A present alias suppresses the legacy method even when the alias is invalid. + * + * @return void + */ + public function test_verify_does_not_fall_back_from_invalid_alias(): void { + $api = Mockery::mock( API::class ); + $api->shouldNotReceive( 'createErrorResponse' ); + + $_REQUEST['action'] = 'mailpoet'; + $_POST['action'] = 'mailpoet'; + $_POST['endpoint'] = 'subscribers'; + $_POST['method'] = 'subscribe'; + + $subject = new Form(); + foreach ( [ 'other', '', [] ] as $alias ) { + $_POST['mailpoet_method'] = $alias; + $subject->verify( $api ); + } + } + + /** + * The WordPress-selected action controls this gate when GET and POST disagree. + * + * @return void + */ + public function test_verify_ignores_other_ajax_action(): void { + $api = Mockery::mock( API::class ); + $api->shouldNotReceive( 'createErrorResponse' ); + + $_REQUEST['action'] = 'other'; + $_POST['action'] = 'mailpoet'; + $_POST['endpoint'] = 'subscribers'; + $_POST['mailpoet_method'] = 'subscribe'; + + ( new Form() )->verify( $api ); + } + + /** + * A bad proof on MailPoet's native POST route is rejected before submission. + * + * @return void + */ + public function test_verify_admin_post_rejects_bad_proof(): void { + $this->prepare_admin_post_request(); + $this->prepare_verify_post( 'hcaptcha_mailpoet_nonce', 'hcaptcha_mailpoet', false ); + $this->prepare_widget_id( 1 ); + + $die = []; + $die_handler = $this->capture_admin_post_die( $die ); + + try { + ( new Form() )->verify_admin_post(); + } finally { + remove_filter( 'wp_die_handler', $die_handler ); + } + + self::assertSame( 'The hCaptcha is invalid.', $die[0] ?? null ); + self::assertSame( 'hCaptcha error', $die[1] ?? null ); + self::assertSame( Response::STATUS_FORBIDDEN, $die[2]['response'] ?? null ); + } + + /** + * A valid proof lets the native submission handler continue. + * + * @return void + */ + public function test_verify_admin_post_allows_valid_proof(): void { + $this->prepare_admin_post_request(); + $this->prepare_verify_post( 'hcaptcha_mailpoet_nonce', 'hcaptcha_mailpoet' ); + $this->prepare_widget_id( 1 ); + + $die = []; + $die_handler = $this->capture_admin_post_die( $die ); + + try { + ( new Form() )->verify_admin_post(); + } finally { + remove_filter( 'wp_die_handler', $die_handler ); + } + + self::assertSame( [], $die ); + } + + /** + * A crawler's bare GET may redirect, while a GET carrying form data is rejected. + * + * @return void + */ + public function test_verify_admin_post_rejects_get_payload(): void { + $this->set_request_method( 'GET' ); + $_GET['action'] = 'mailpoet_subscription_form'; + $_REQUEST['action'] = 'mailpoet_subscription_form'; + $subject = new Form(); + + $die = []; + $die_handler = $this->capture_admin_post_die( $die ); + + try { + $subject->verify_admin_post(); + self::assertSame( [], $die ); + + $_GET['data'] = [ 'form_id' => '1' ]; + $_REQUEST['data'] = [ 'form_id' => '1' ]; + $subject->verify_admin_post(); + } finally { + remove_filter( 'wp_die_handler', $die_handler ); + } + + self::assertSame( 405, $die[2]['response'] ?? null ); + } + + /** + * A POST cannot subscribe with GET-only data that get_entry() would not verify. + * + * @return void + */ + public function test_verify_admin_post_rejects_get_only_data_on_post(): void { + $this->prepare_admin_post_request(); + $_GET['data'] = [ 'form_id' => '1' ]; + unset( $_POST['data'] ); + + $die = []; + $die_handler = $this->capture_admin_post_die( $die ); + + try { + ( new Form() )->verify_admin_post(); + } finally { + remove_filter( 'wp_die_handler', $die_handler ); + } + + self::assertSame( Response::STATUS_FORBIDDEN, $die[2]['response'] ?? null ); + } + + /** + * Native requests for a different MailPoet endpoint retain their own handling. + * + * @return void + */ + public function test_verify_admin_post_ignores_other_endpoint(): void { + $this->prepare_admin_post_request(); + $_REQUEST['endpoint'] = 'other'; + + $die = []; + $die_handler = $this->capture_admin_post_die( $die ); + + try { + ( new Form() )->verify_admin_post(); + } finally { + remove_filter( 'wp_die_handler', $die_handler ); + } + + self::assertSame( [], $die ); + } + + /** + * Prepare the fields consumed by MailPoet's native admin-post submission handler. + * + * @return void + */ + private function prepare_admin_post_request(): void { + $this->set_request_method( 'POST' ); + $_GET['action'] = 'mailpoet_subscription_form'; + $_REQUEST['action'] = 'mailpoet_subscription_form'; + + $payload = [ + 'api_version' => 'v1', + 'endpoint' => 'subscribers', + 'mailpoet_method' => 'subscribe', + 'token' => 'mailpoet-token', + 'data' => [ 'form_id' => '1' ], + ]; + + foreach ( $payload as $name => $value ) { + $_POST[ $name ] = $value; + $_REQUEST[ $name ] = $value; + } + } + + /** + * Capture the WordPress termination response without ending the test process. + * + * @param array $die_response Captured wp_die() arguments. + * @return callable + */ + private function capture_admin_post_die( array &$die_response ): callable { + $die_handler = static function () use ( &$die_response ): callable { + return static function ( $message, $title, $args ) use ( &$die_response ): void { + $die_response = [ $message, $title, $args ]; + }; + }; + add_filter( 'wp_die_handler', $die_handler ); + + return $die_handler; + } + + /** + * Set the request method and retain its original value for tear down. + * + * @param string $method Request method. + * @return void + */ + private function set_request_method( string $method ): void { + if ( ! $this->request_method_changed ) { + // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Restore the exact original test environment. + $this->original_request_method = $_SERVER['REQUEST_METHOD'] ?? null; + $this->request_method_changed = true; + } + + $_SERVER['REQUEST_METHOD'] = $method; + } + /** * Prepare hCaptcha widget id. * diff --git a/tests/php/integration/MemberPress/LoginTest.php b/tests/php/integration/MemberPress/LoginTest.php index 7681f8533..d0ae75baf 100644 --- a/tests/php/integration/MemberPress/LoginTest.php +++ b/tests/php/integration/MemberPress/LoginTest.php @@ -79,4 +79,25 @@ public function test_filled_honeypot_is_rejected(): void { $result->get_error_message() ); } + + /** + * Skip verification outside MemberPress and before the login limit. + */ + public function test_verify_skips_other_logins_and_unlimited_attempts(): void { + $user = new WP_User( 1 ); + $subject = new Login(); + + self::assertSame( $user, $subject->verify( $user, 'password' ) ); + + hcaptcha()->settings()->set( 'login_limit', 1 ); + add_filter( 'hcap_login_limit_exceeded', '__return_false' ); + // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores + apply_filters( 'mepr-validate-login', [] ); + + try { + self::assertSame( $user, $subject->verify( $user, 'password' ) ); + } finally { + remove_filter( 'hcap_login_limit_exceeded', '__return_false' ); + } + } } diff --git a/tests/php/integration/MemberPress/RegisterTest.php b/tests/php/integration/MemberPress/RegisterTest.php index b52670f7d..d491a2542 100644 --- a/tests/php/integration/MemberPress/RegisterTest.php +++ b/tests/php/integration/MemberPress/RegisterTest.php @@ -89,6 +89,13 @@ public function test_verify(): void { 'hcaptcha_memberpress_register' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'memberpress/memberpress.php' ], + 'form_id' => 'register', + ] + ); + self::assertSame( $errors, $subject->verify( $errors ) ); } @@ -109,6 +116,13 @@ public function test_verify_no_success(): void { false ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'memberpress/memberpress.php' ], + 'form_id' => 'register', + ] + ); + self::assertSame( $error_message, $subject->verify( $errors ) ); } @@ -136,4 +150,100 @@ public function test_verify_filled_honeypot(): void { ( new Register() )->verify( [] ) ); } + + /** + * Check the authoritative native email through the production API. + * + * @dataProvider dp_test_native_email_policy + * + * @param string $email Native address. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( string $email, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + wp_set_current_user( 0 ); + $_POST['user_email'] = $email; + $_POST['email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_memberpress_register_nonce', 'hcaptcha_memberpress_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'memberpress_status', [ 'login', 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'memberpress/memberpress.php' ], + 'form_id' => 'register', + ] + ); + + $result = ( new Register() )->verify( [] ); + + self::assertSame( $blocked ? [ hcap_get_error_messages()['disposable-email'] ] : [], $result ); + } + + /** + * Native email policy controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + return [ + 'disposable email' => [ 'user@disposable.example', true ], + 'permanent email' => [ 'safe@example.com', false ], + 'email-free data' => [ '', false ], + ]; + } + + /** + * A current member's stored email wins over an unused posted address. + * + * @dataProvider dp_test_member_email_policy + * + * @param string $stored Current member address. + * @param string $posted Unused native new-member address. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_member_email_policy( string $stored, string $posted, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + wp_set_current_user( $this->factory()->user->create( [ 'user_email' => $stored ] ) ); + $_POST['user_email'] = $posted; + $this->prepare_verify_post( 'hcaptcha_memberpress_register_nonce', 'hcaptcha_memberpress_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'memberpress_status', [ 'login', 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'memberpress/memberpress.php' ], + 'form_id' => 'register', + ] + ); + + $result = ( new Register() )->verify( [] ); + + self::assertSame( $blocked ? [ hcap_get_error_messages()['disposable-email'] ] : [], $result ); + wp_set_current_user( 0 ); + } + + /** + * Stored member and misleading posted email controls. + * + * @return array + */ + public function dp_test_member_email_policy(): array { + return [ + 'blocked stored member' => [ 'user@disposable.example', 'safe@example.com', true ], + 'allowed stored member' => [ 'safe@example.com', 'user@disposable.example', false ], + ]; + } } diff --git a/tests/php/integration/MetForm/FormTest.php b/tests/php/integration/MetForm/FormTest.php index 7dfd7da8e..076ebb631 100644 --- a/tests/php/integration/MetForm/FormTest.php +++ b/tests/php/integration/MetForm/FormTest.php @@ -26,7 +26,9 @@ use Mockery; use ReflectionClass; use ReflectionException; +use WP_Error; use WP_REST_Request; +use WP_REST_Response; /** * Test Form class. @@ -256,11 +258,228 @@ public function test_capture_form_id(): void { self::assertSame( 0, $this->get_protected_property( $subject, 'form_id' ) ); $request = new WP_REST_Request( 'POST', '/metform/v1/entries/insert/456' ); + $request->set_url_params( + [ + 'action' => 'insert', + 'id' => '456', + ] + ); self::assertSame( $response, $subject->capture_form_id( $response, [], $request ) ); self::assertSame( 456, $this->get_protected_property( $subject, 'form_id' ) ); } + /** + * Ignore other actions and reject a non-scalar native form ID. + */ + public function test_capture_form_id_with_invalid_action_and_id_type(): void { + $subject = new Form(); + $request = new WP_REST_Request( 'POST', '/metform/v1/entries/insert/456' ); + $request->set_url_params( + [ + 'action' => 'other', + 'id' => '456', + ] + ); + + self::assertSame( 'response', $subject->capture_form_id( 'response', [], $request ) ); + + $request->set_url_params( + [ + 'action' => 'insert', + 'id' => [], + ] + ); + self::assertSame( + 'hcaptcha_metform_invalid_form_id', + $subject->capture_form_id( 'response', [], $request )->get_error_code() + ); + } + + /** + * Omit values that are absent from the native submission. + */ + public function test_get_field_value_without_submission_key(): void { + $subject = new Form(); + $method = $this->set_method_accessibility( $subject, 'get_field_value' ); + + self::assertNull( $method->invoke( $subject, [], 'missing', [] ) ); + } + + /** + * A document is unavailable before Elementor initializes its document manager. + */ + public function test_get_form_id_without_document_manager(): void { + $elementor = ElementorPlugin::instance(); + $documents = $elementor->documents; + $subject = new Form(); + $method = $this->set_method_accessibility( $subject, 'get_form_id' ); + + $elementor->documents = null; + + try { + self::assertSame( 0, $method->invoke( $subject ) ); + } finally { + $elementor->documents = $documents; + } + } + + /** + * Test matching body and query IDs used by MetForm. + * + * @throws ReflectionException Reflection exception. + */ + public function test_capture_form_id_with_matching_overrides(): void { + $subject = new Form(); + $request = new WP_REST_Request( 'POST', '/metform/v1/entries/insert/456' ); + $request->set_url_params( + [ + 'action' => 'insert', + 'id' => '456', + ] + ); + $request->set_query_params( [ 'id' => '456' ] ); + $request->set_body_params( [ 'id' => '456' ] ); + + self::assertNull( $subject->capture_form_id( null, [], $request ) ); + self::assertSame( 456, $this->get_protected_property( $subject, 'form_id' ) ); + + $request = new WP_REST_Request( 'POST', '/METFORM/v1/entries/INSERT/456' ); + $request->set_url_params( + [ + 'action' => 'INSERT', + 'id' => '456', + ] + ); + + self::assertNull( $subject->capture_form_id( null, [], $request ) ); + self::assertSame( 456, $this->get_protected_property( $subject, 'form_id' ) ); + } + + /** + * Test rejecting IDs and actions that would make MetForm submit another form. + * + * @throws ReflectionException Reflection exception. + */ + public function test_capture_form_id_rejects_overrides(): void { + $requests = [ + 'body ID' => [ + '/metform/v1/entries/insert/456', + [ + 'action' => 'insert', + 'id' => '456', + ], + [], + [ 'id' => '789' ], + ], + 'query ID' => [ + '/metform/v1/entries/insert/456', + [ + 'action' => 'insert', + 'id' => '456', + ], + [ 'id' => '789' ], + [], + ], + 'action alias' => [ + '/metform/v1/entries/other/456', + [ + 'action' => 'other', + 'id' => '456', + ], + [], + [ 'action' => 'insert' ], + ], + 'ID alias' => [ + '/metform/v1/entries/insert/other', + [ + 'action' => 'insert', + 'id' => 'other', + ], + [], + [ 'id' => '456' ], + ], + 'invalid ID' => [ + '/metform/v1/entries/insert/456', + [ + 'action' => 'insert', + 'id' => '456', + ], + [], + [ 'id' => '456suffix' ], + ], + 'cased alias' => [ + '/METFORM/v1/entries/other/456', + [ + 'action' => 'other', + 'id' => '456', + ], + [], + [ 'action' => 'INSERT' ], + ], + ]; + + foreach ( $requests as $case => [ $route, $url_params, $query_params, $body_params ] ) { + $subject = new Form(); + $request = new WP_REST_Request( 'POST', $route ); + $request->set_url_params( $url_params ); + $request->set_query_params( $query_params ); + $request->set_body_params( $body_params ); + + $response = $subject->capture_form_id( null, [], $request ); + + self::assertInstanceOf( WP_Error::class, $response, $case ); + self::assertSame( 'hcaptcha_metform_invalid_form_id', $response->get_error_code(), $case ); + self::assertSame( 400, $response->get_error_data()['status'], $case ); + self::assertSame( 0, $this->get_protected_property( $subject, 'form_id' ), $case ); + } + } + + /** + * Test form ID and action binding through the live MetForm REST route. + */ + public function test_rest_route_rejects_overridden_form_id(): void { + $subject = new Form(); + $dispatched = 0; + $intercept = static function () use ( &$dispatched ): WP_REST_Response { + ++$dispatched; + + return new WP_REST_Response( [ 'dispatched' => true ], 202 ); + }; + add_filter( 'rest_dispatch_request', $intercept ); + + try { + $requests = [ + 'body ID' => new WP_REST_Request( 'POST', '/metform/v1/entries/insert/456' ), + 'query ID' => new WP_REST_Request( 'POST', '/metform/v1/entries/insert/456' ), + 'JSON ID' => new WP_REST_Request( 'POST', '/metform/v1/entries/insert/456' ), + 'action alias' => new WP_REST_Request( 'POST', '/metform/v1/entries/other/456' ), + ]; + $requests['body ID']->set_body_params( [ 'id' => '789' ] ); + $requests['query ID']->set_query_params( [ 'id' => '789' ] ); + $requests['JSON ID']->set_header( 'Content-Type', 'application/json' ); + $requests['JSON ID']->set_body( wp_json_encode( [ 'id' => 789 ] ) ); + $requests['action alias']->set_body_params( [ 'action' => 'insert' ] ); + + foreach ( $requests as $case => $request ) { + $response = rest_do_request( $request ); + + self::assertSame( 400, $response->get_status(), $case ); + self::assertSame( 'hcaptcha_metform_invalid_form_id', $response->get_data()['code'], $case ); + self::assertSame( 0, $dispatched, $case ); + } + + $response = rest_do_request( new WP_REST_Request( 'POST', '/metform/v1/entries/insert/456' ) ); + + self::assertSame( 202, $response->get_status() ); + self::assertSame( [ 'dispatched' => true ], $response->get_data() ); + self::assertSame( 1, $dispatched ); + } finally { + remove_filter( 'rest_request_before_callbacks', [ $subject, 'capture_form_id' ] ); + remove_filter( 'rest_dispatch_request', $intercept ); + } + } + /** * Test successful verification. * @@ -292,6 +511,12 @@ public function test_verify(): void { 'file_data' => [], ]; $request = new WP_REST_Request( 'POST', '/metform/v1/entries/insert/' . $form_id ); + $request->set_url_params( + [ + 'action' => 'insert', + 'id' => (string) $form_id, + ] + ); $this->prepare_verify_request( $hcaptcha_response ); @@ -333,7 +558,13 @@ public function test_verify_failed(): void { 'form_data' => $form_data, ]; $request = new WP_REST_Request( 'POST', '/metform/v1/entries/insert/' . $form_id ); - $subject = Mockery::mock( Form::class )->makePartial(); + $request->set_url_params( + [ + 'action' => 'insert', + 'id' => (string) $form_id, + ] + ); + $subject = Mockery::mock( Form::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); $subject->shouldReceive( 'get_fields' )->once()->andReturn( [] ); @@ -375,32 +606,42 @@ public function test_get_entry_and_get_data(): void { ] ); $fields = [ - 'first-name' => (object) [ + 'first-name' => (object) [ 'mf_input_label' => 'First name', 'mf_input_name' => 'first-name', 'widgetType' => 'mf-listing-fname', ], - 'last-name' => (object) [ + 'last-name' => (object) [ 'mf_input_label' => 'Last name', 'mf_input_name' => 'last-name', 'widgetType' => 'mf-listing-lname', ], - 'email' => (object) [ + 'email' => (object) [ 'mf_input_label' => 'Email address', 'mf_input_name' => 'email', 'widgetType' => 'mf-email', ], - 'message' => (object) [ + 'other-email' => (object) [ + 'mf_input_label' => 'Secondary email', + 'mf_input_name' => 'other-email', + 'widgetType' => 'mf-email', + ], + 'safe-label-email' => (object) [ + 'mf_input_label' => 'Security email', + 'mf_input_name' => 'safe-label-email', + 'widgetType' => 'mf-email', + ], + 'message' => (object) [ 'mf_input_label' => 'Message', 'mf_input_name' => 'message', 'widgetType' => 'mf-textarea', ], - 'choice' => (object) [ + 'choice' => (object) [ 'mf_input_label' => '', 'mf_input_name' => 'choice', 'widgetType' => 'mf-checkbox', ], - 'empty' => (object) [ + 'empty' => (object) [ 'mf_input_label' => 'Empty', 'mf_input_name' => 'empty', 'widgetType' => 'mf-text', @@ -409,7 +650,9 @@ public function test_get_entry_and_get_data(): void { $form_data = [ 'first-name' => 'John', 'last-name' => 'Doe', - 'email' => 'john@example.com', + 'email' => 'john@sec060-disposable.test', + 'other-email' => 'john@example.com', + 'safe-label-email' => 'extra@sec060-disposable.test', 'message' => 'Hello world', 'choice' => [ 'One', 'Two' ], 'empty' => '', @@ -454,6 +697,12 @@ public function test_get_entry_and_get_data(): void { $subject = new Form(); $request = new WP_REST_Request( 'POST', '/metform/v1/entries/insert/' . $form_id ); + $request->set_url_params( + [ + 'action' => 'insert', + 'id' => (string) $form_id, + ] + ); $subject->capture_form_id( null, [], $request ); @@ -467,16 +716,19 @@ public function test_get_entry_and_get_data(): void { self::assertSame( $form_data, $entry['post_data'] ); self::assertSame( [ - 'First name' => 'John', - 'Last name' => 'Doe', - 'email' => 'john@example.com', - 'Email address' => 'john@example.com', - 'Message' => 'Hello world', - 'choice' => [ 'One', 'Two' ], - 'name' => 'John Doe', + 'First name' => 'John', + 'Last name' => 'Doe', + 'Email address' => 'john@sec060-disposable.test', + 'Secondary email' => 'john@example.com', + 'Message' => 'Hello world', + 'choice' => [ 'One', 'Two' ], + 'name' => 'John Doe', + 'email' => 'john@sec060-disposable.test', ], $entry['data'] ); + self::assertSame( [ 'john@sec060-disposable.test', 'john@example.com', 'extra@sec060-disposable.test' ], $entry['email_addresses'] ); + self::assertArrayNotHasKey( 'Security email', $entry['data'] ); self::assertSame( [ 'source' => [ 'metform/metform.php' ], diff --git a/tests/php/integration/MigrationWizard/DetectionResultTest.php b/tests/php/integration/MigrationWizard/DetectionResultTest.php new file mode 100644 index 000000000..683ee8aba --- /dev/null +++ b/tests/php/integration/MigrationWizard/DetectionResultTest.php @@ -0,0 +1,87 @@ + 'recaptcha', + 'source_plugin' => 'essential-blocks/essential-blocks.php', + 'source_name' => 'Essential Blocks', + 'surface' => 'essential_blocks_form', + 'surface_label' => 'Essential Blocks form', + 'confidence' => DetectionResult::CONFIDENCE_HIGH, + 'support_status' => DetectionResult::STATUS_SUPPORTED, + 'hcaptcha_option_key' => 'essential_blocks_status', + 'hcaptcha_option_value' => 'form', + 'notes' => 'Saved form detected.', + ]; + $result = DetectionResult::from_array( $data ); + + self::assertSame( $data['provider'], $result->get_provider() ); + self::assertSame( $data['source_plugin'], $result->get_source_plugin() ); + self::assertSame( $data['source_name'], $result->get_source_name() ); + self::assertSame( $data['surface'], $result->get_surface() ); + self::assertSame( $data['surface_label'], $result->get_surface_label() ); + self::assertSame( $data['confidence'], $result->get_confidence() ); + self::assertSame( $data['support_status'], $result->get_support_status() ); + self::assertSame( $data['hcaptcha_option_key'], $result->get_hcaptcha_option_key() ); + self::assertSame( $data['hcaptcha_option_value'], $result->get_hcaptcha_option_value() ); + self::assertSame( $data['notes'], $result->get_notes() ); + self::assertTrue( $result->is_migratable() ); + self::assertSame( $data + [ 'is_migratable' => true ], $result->to_array() ); + } + + /** + * Unsupported or incomplete settings cannot be migrated. + * + * @param array $data Surface overrides. + * + * @dataProvider dp_incomplete_surface + */ + public function test_incomplete_surface_is_not_migratable( array $data ): void { + $result = new DetectionResult( $data ); + + self::assertFalse( $result->is_migratable() ); + self::assertFalse( $result->to_array()['is_migratable'] ); + } + + /** + * Each missing prerequisite prevents migration. + * + * @return array + */ + public function dp_incomplete_surface(): array { + return [ + 'unknown by default' => [ [] ], + 'missing setting key' => [ + [ + 'support_status' => DetectionResult::STATUS_SUPPORTED, + 'hcaptcha_option_value' => 'form', + ], + ], + 'missing setting value' => [ + [ + 'support_status' => DetectionResult::STATUS_SUPPORTED, + 'hcaptcha_option_key' => 'essential_blocks_status', + ], + ], + ]; + } +} diff --git a/tests/php/integration/MigrationWizard/EssentialBlocksDetectorTest.php b/tests/php/integration/MigrationWizard/EssentialBlocksDetectorTest.php index eb18ac0bf..1328b0c94 100644 --- a/tests/php/integration/MigrationWizard/EssentialBlocksDetectorTest.php +++ b/tests/php/integration/MigrationWizard/EssentialBlocksDetectorTest.php @@ -17,6 +17,21 @@ * @group migration-wizard */ class EssentialBlocksDetectorTest extends HCaptchaWPTestCase { + /** + * Find reCAPTCHA blocks below another non-CAPTCHA inner block. + */ + public function test_contains_recaptcha_block_nested_under_group(): void { + $subject = new EssentialBlocksDetector(); + $method = $this->set_method_accessibility( $subject, 'contains_recaptcha_block' ); + $blocks = [ + [ + 'blockName' => 'core/group', + 'innerBlocks' => [ [ 'blockName' => 'essential-blocks/recaptcha' ] ], + ], + ]; + + self::assertTrue( $method->invoke( $subject, $blocks ) ); + } /** * Test source details and applicability. diff --git a/tests/php/integration/Migrations/MigrationsTest.php b/tests/php/integration/Migrations/MigrationsTest.php index 6342e7896..8aeb18d9b 100644 --- a/tests/php/integration/Migrations/MigrationsTest.php +++ b/tests/php/integration/Migrations/MigrationsTest.php @@ -902,6 +902,44 @@ public function test_add_events_retention_index(): void { ); } + /** + * Retention migration stops when creating the Events table fails. + */ + public function test_add_events_retention_index_without_table(): void { + $subject = new Migrations(); + $method = $this->set_method_accessibility( $subject, 'add_events_retention_index' ); + + FunctionMocker::replace( Events::class . '::is_retention_schema_ready', false ); + FunctionMocker::replace( Events::class . '::create_table' ); + FunctionMocker::replace( Events::class . '::table_exists', false ); + + $method->invoke( $subject ); + self::assertFalse( Events::table_exists() ); + } + + /** + * Retention migration stops when another request completes the schema first. + */ + public function test_add_events_retention_index_when_schema_becomes_ready(): void { + $subject = new Migrations(); + $method = $this->set_method_accessibility( $subject, 'add_events_retention_index' ); + $checks = 0; + + FunctionMocker::replace( + Events::class . '::is_retention_schema_ready', + static function () use ( &$checks ): bool { + ++$checks; + + return 1 < $checks; + } + ); + FunctionMocker::replace( Events::class . '::create_table' ); + FunctionMocker::replace( Events::class . '::table_exists', true ); + + $method->invoke( $subject ); + self::assertSame( 2, $checks ); + } + /** * Test repeated initialization skips DDL when the retention schema is ready. * diff --git a/tests/php/integration/NF/FieldTest.php b/tests/php/integration/NF/FieldTest.php index e462cc96e..2611659f4 100644 --- a/tests/php/integration/NF/FieldTest.php +++ b/tests/php/integration/NF/FieldTest.php @@ -5,8 +5,10 @@ * @package HCaptcha\Tests */ -// phpcs:ignore Generic.Commenting.DocComment.MissingShort +// phpcs:disable Generic.Commenting.DocComment.MissingShort /** @noinspection PhpUndefinedClassInspection */ +/** @noinspection PhpUndefinedFunctionInspection */ +// phpcs:enable Generic.Commenting.DocComment.MissingShort namespace HCaptcha\Tests\Integration\NF; @@ -15,8 +17,12 @@ use HCaptcha\NF\Field; use HCaptcha\NF\NF; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; +use NF_Database_Models_Form; +use NF_Display_Render; use Ninja_Forms; use ReflectionClass; +use ReflectionProperty; +use WPN_Helper; /** * Test Field class. @@ -62,6 +68,52 @@ public function test_live_form_render(): void { self::assertStringContainsString( '"type":"' . Base::NAME . '"', $html ); self::assertStringContainsString( 'class=\"h-captcha\"', $html ); self::assertStringContainsString( 'hcaptcha-widget-id', $html ); + ob_start(); + NF_Display_Render::output_templates(); + $templates = ob_get_clean(); + self::assertStringContainsString( 'id="tmpl-nf-field-' . Base::NAME . '"', $templates ); + self::assertStringContainsString( '{{{ data.hcaptcha }}}', $templates ); + } + + /** + * Test a page with native and bridge fields keeps the native script. + */ + public function test_mixed_form_render_keeps_native_script(): void { + $subject = new NF(); + Ninja_Forms::instance()->instantiateTranslatableObjects(); + + $form_id = $this->create_ninja_form( true, true ); + WPN_Helper::delete_nf_cache( $form_id ); + Ninja_Forms()->form( $form_id )->get_fields( [], true ); + // Native render counts outlive test transactions that reuse form IDs. + $render_count = new ReflectionProperty( NF_Display_Render::class, 'render_instance_count' ); + $render_count->setAccessible( true ); + $previous_counts = $render_count->getValue(); + $counts = $previous_counts; + unset( $counts[ $form_id ] ); + $render_count->setValue( null, $counts ); + + try { + $html = do_shortcode( '[ninja_form id="' . $form_id . '"]' ); + + self::assertStringContainsString( '"type":"' . Base::TYPE . '"', $html ); + self::assertStringContainsString( '"type":"' . Base::NAME . '"', $html ); + ob_start(); + NF_Display_Render::output_templates(); + $templates = ob_get_clean(); + self::assertStringContainsString( 'id="tmpl-nf-field-' . Base::TYPE . '"', $templates ); + self::assertStringContainsString( 'class="nf-h-captcha"', $templates ); + self::assertStringContainsString( 'id="tmpl-nf-field-' . Base::NAME . '"', $templates ); + self::assertStringContainsString( '{{{ data.hcaptcha }}}', $templates ); + self::assertTrue( wp_script_is( 'nf-hcaptcha' ) ); + + $subject->nf_captcha_script(); + + self::assertTrue( wp_script_is( 'nf-hcaptcha' ) ); + self::assertTrue( wp_script_is( 'hcaptcha-nf' ) ); + } finally { + $render_count->setValue( null, $previous_counts ); + } } /** @@ -69,6 +121,8 @@ public function test_live_form_render(): void { */ public function tearDown(): void { unset( $_POST['formData'], $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] ); + wp_dequeue_script( 'nf-hcaptcha' ); + wp_dequeue_script( 'hcaptcha-nf' ); parent::tearDown(); } @@ -88,14 +142,17 @@ public function test_constructor(): void { /** * Test validate(). * - * @noinspection PhpUndefinedFunctionInspection*/ + * @noinspection PhpUndefinedFunctionInspection + * @noinspection JsonEncodingApiUsageInspection + * @noinspection AmbiguousMethodsCallsInArrayMappingInspection + */ public function test_validate(): void { $form_id = $this->create_ninja_form(); $form = Ninja_Forms()->form( $form_id ); $fields = []; foreach ( $form->get_fields() as $field ) { - $fields[] = [ + $fields[ $field->get_id() ] = [ 'id' => $field->get_id(), 'value' => 'some value', ]; @@ -121,14 +178,17 @@ public function test_validate(): void { /** * Test validate() without a field. * - * @noinspection PhpUndefinedFunctionInspection*/ + * @noinspection PhpUndefinedFunctionInspection + * @noinspection AmbiguousMethodsCallsInArrayMappingInspection + * @noinspection JsonEncodingApiUsageInspection + */ public function test_validate_without_field(): void { $form_id = $this->create_ninja_form(); $form = Ninja_Forms()->form( $form_id ); $fields = []; foreach ( $form->get_fields() as $field ) { - $fields[] = [ + $fields[ $field->get_id() ] = [ 'id' => $field->get_id(), 'value' => 'some value', ]; @@ -154,14 +214,17 @@ public function test_validate_without_field(): void { /** * Test validate() when not validated. * - * @noinspection PhpUndefinedFunctionInspection*/ + * @noinspection PhpUndefinedFunctionInspection + * @noinspection AmbiguousMethodsCallsInArrayMappingInspection + * @noinspection JsonEncodingApiUsageInspection + */ public function test_validate_not_validated(): void { $form_id = $this->create_ninja_form(); $form = Ninja_Forms()->form( $form_id ); $fields = []; foreach ( $form->get_fields() as $field ) { - $fields[] = [ + $fields[ $field->get_id() ] = [ 'id' => $field->get_id(), 'value' => 'some value', ]; @@ -188,6 +251,8 @@ public function test_validate_not_validated(): void { * Test validate() when widget id is missing. * * @noinspection PhpUndefinedFunctionInspection + * @noinspection AmbiguousMethodsCallsInArrayMappingInspection + * @noinspection JsonEncodingApiUsageInspection */ public function test_validate_missing_widget_id(): void { $form_id = $this->create_ninja_form(); @@ -195,7 +260,7 @@ public function test_validate_missing_widget_id(): void { $fields = []; foreach ( $form->get_fields() as $field ) { - $fields[] = [ + $fields[ $field->get_id() ] = [ 'id' => $field->get_id(), 'value' => 'some value', ]; @@ -217,6 +282,192 @@ public function test_validate_missing_widget_id(): void { self::assertSame( 'Bad hCaptcha signature!', $subject->validate( $field, $data ) ); } + /** + * A foreign form's email field must not replace the target email checked by anti-spam. + */ + public function test_validate_ignores_foreign_email_field(): void { + $target_id = $this->create_ninja_form( true ); + $foreign_id = $this->create_ninja_form(); + self::assertNotSame( $target_id, $foreign_id ); + $foreign = Ninja_Forms()->form( $foreign_id ); + $foreign_email_id = 0; + + foreach ( $foreign->get_fields() as $model ) { + if ( 'email' === $model->get_setting( 'type' ) ) { + $foreign_email_id = $model->get_id(); + } + } + + self::assertGreaterThan( 0, $foreign_email_id ); + + [ $captcha, $fields ] = $this->prepare_email_submission( $target_id, 'reader@sec055-disposable.test' ); + $fields[ $foreign_email_id ] = [ + 'id' => $foreign_email_id, + 'value' => 'reader@example.com', + ]; + + self::assertSame( + 'Please use a permanent email address.', + ( new Field() )->validate( $captcha, [ 'fields' => $fields ] ) + ); + } + + /** + * Check every accepted target email regardless of client field order. + */ + public function test_validate_checks_all_target_email_fields(): void { + $form_id = $this->create_ninja_form( true ); + $second = Ninja_Forms()->form( $form_id )->field()->get(); + $second->update_setting( 'label', 'Second Email' ); + $second->update_setting( 'key', 'second_email' ); + $second->update_setting( 'type', 'email' ); + $second->update_setting( 'order', 5 ); + $second->save(); + + [ $captcha, $fields ] = $this->prepare_email_submission( $form_id, 'reader@sec055-disposable.test' ); + $fields[ $second->get_id() ] = [ + 'id' => $second->get_id(), + 'value' => 'reader@example.com', + ]; + + self::assertSame( + 'Please use a permanent email address.', + ( new Field() )->validate( $captcha, [ 'fields' => $fields ] ) + ); + } + + /** + * A target form with a permanent email and valid proof must still submit. + */ + public function test_validate_accepts_permanent_native_email(): void { + $form_id = $this->create_ninja_form( true ); + [ $captcha, $fields ] = $this->prepare_email_submission( $form_id, 'reader@example.com' ); + + self::assertNull( ( new Field() )->validate( $captcha, [ 'fields' => $fields ] ) ); + } + + /** + * Native filters may supply server field definitions as arrays. + */ + public function test_validate_checks_native_array_field_definitions(): void { + $form_id = $this->create_ninja_form( true ); + [ $captcha, $fields ] = $this->prepare_email_submission( $form_id, 'reader@sec055-disposable.test' ); + $as_arrays = static function ( array $form_fields, int $filtered_form_id ) use ( $form_id ): array { + if ( $form_id !== $filtered_form_id ) { + return $form_fields; + } + + foreach ( $form_fields as $id => $model ) { + $form_fields[ $id ] = [ + 'id' => $model->get_id(), + 'settings' => $model->get_settings(), + ]; + } + + return $form_fields; + }; + add_filter( 'ninja_forms_get_fields', $as_arrays, 10, 2 ); + + try { + self::assertSame( + 'Please use a permanent email address.', + ( new Field() )->validate( $captcha, [ 'fields' => $fields ] ) + ); + } finally { + remove_filter( 'ninja_forms_get_fields', $as_arrays ); + } + } + + /** + * Ignore malformed field definitions supplied by a native filter. + */ + public function test_validate_ignores_malformed_native_field_definitions(): void { + $form_id = $this->create_ninja_form( true ); + [ $captcha, $fields ] = $this->prepare_email_submission( $form_id, 'reader@example.com' ); + $with_invalid_field = static function ( array $form_fields, int $filtered_form_id ) use ( $form_id ): array { + if ( $form_id === $filtered_form_id ) { + $form_fields[] = null; + } + + return $form_fields; + }; + + add_filter( 'ninja_forms_get_fields', $with_invalid_field, 10, 2 ); + + try { + self::assertNull( ( new Field() )->validate( $captcha, [ 'fields' => $fields ] ) ); + } finally { + remove_filter( 'ninja_forms_get_fields', $with_invalid_field ); + } + } + + /** + * A sensitive field label cannot exempt a native email from disposable policy. + */ + public function test_validate_checks_native_email_with_sensitive_label(): void { + $form_id = $this->create_ninja_form( true ); + + foreach ( Ninja_Forms()->form( $form_id )->get_fields() as $model ) { + if ( 'email' === $model->get_setting( 'type' ) ) { + $model->update_setting( 'label', 'Payment Email' ); + $model->update_setting( 'key', 'payment_email' ); + $model->save(); + } + } + + [ $captcha, $fields ] = $this->prepare_email_submission( $form_id, 'reader@sec055-disposable.test' ); + self::assertSame( + 'Please use a permanent email address.', + ( new Field() )->validate( $captcha, [ 'fields' => $fields ] ) + ); + } + + /** + * Prepare the native field map, signed widget and disposable-email policy. + * + * @param int $form_id Form ID. + * @param string $email Submitted target email. + * + * @return array{0: array, 1: array} + * @noinspection JsonEncodingApiUsageInspection + */ + private function prepare_email_submission( int $form_id, string $email ): array { + $fields = []; + $captcha = []; + + foreach ( Ninja_Forms()->form( $form_id )->get_fields() as $model ) { + $id = $model->get_id(); + $type = $model->get_setting( 'type' ); + $value = 'email' === $type ? $email : 'some value'; + $fields[ $id ] = [ + 'id' => $id, + 'value' => $value, + ]; + + if ( Base::NAME === $type ) { + $captcha = $fields[ $id ]; + } + } + + self::assertNotEmpty( $captcha ); + // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode + $_POST['formData'] = json_encode( [ 'id' => (string) $form_id ] ); + $this->prepare_verify_request( $captcha['value'] ); + $this->prepare_widget_id( $form_id ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + set_transient( 'hcaptcha_disposable_email_blocklist', [ 'sec055-disposable.test' => true ] ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + self::assertTrue( + HCaptcha::is_protection_enabled( + [ + 'source' => [ 'ninja-forms/ninja-forms.php' ], + 'form_id' => $form_id, + ] + ) + ); + return [ $captcha, $fields ]; + } + /** * Test hide_field_type(). * @@ -224,11 +475,12 @@ public function test_validate_missing_widget_id(): void { */ public function test_hide_field_type(): void { $hidden_field_types = [ 'some type' ]; - $expected = [ 'some type', 'hcaptcha-for-ninja-forms' ]; + $expected = [ 'some type', 'hcaptcha', 'hcaptcha-for-ninja-forms' ]; $subject = new Field(); self::assertSame( $expected, $subject->hide_field_type( $hidden_field_types ) ); + self::assertSame( $expected, $subject->hide_field_type( $expected ) ); } /** @@ -238,6 +490,7 @@ public function test_hide_field_type(): void { * @param array $id Widget id. * * @return void + * @noinspection PhpSameParameterValueInspection */ private function prepare_widget_id( int $form_id, array $id = [] ): void { $id = array_merge( @@ -254,15 +507,18 @@ private function prepare_widget_id( int $form_id, array $id = [] ): void { /** * Create a Ninja form. * - * @param bool $with_hcaptcha Whether to add an hCaptcha field. + * @param bool $with_hcaptcha Whether to add a bridge hCaptcha field. + * @param bool $with_native_hcaptcha Whether to add a native hCaptcha field. * * @return int * @noinspection PhpUndefinedFunctionInspection * @noinspection PhpUndefinedClassInspection */ - protected function create_ninja_form( bool $with_hcaptcha = false ): int { + protected function create_ninja_form( bool $with_hcaptcha = false, bool $with_native_hcaptcha = false ): int { + global $wpdb; + // Create a Ninja form. - $form = Ninja_Forms()->form()->get(); + $form = new NF_Database_Models_Form( $wpdb, 0 ); $form->update_setting( 'title', 'Test Form' ); $form->update_setting( 'publish_state', 1 ); @@ -287,6 +543,16 @@ protected function create_ninja_form( bool $with_hcaptcha = false ): int { $hcaptcha_field->save(); } + if ( $with_native_hcaptcha ) { + $native_field = Ninja_Forms()->form( $form_id )->field()->get(); + $native_field->update_setting( 'label', 'Native hCaptcha' ); + $native_field->update_setting( 'key', 'native_hcaptcha' ); + $native_field->update_setting( 'type', Base::TYPE ); + $native_field->update_setting( 'label_visibility', 'visible' ); + $native_field->update_setting( 'order', 4 ); + $native_field->save(); + } + // Add an email field. $field = Ninja_Forms()->form( $form_id )->field()->get(); $field->update_setting( 'label', 'Email' ); diff --git a/tests/php/integration/NF/NFTest.php b/tests/php/integration/NF/NFTest.php index f09d01734..830c0bfa7 100644 --- a/tests/php/integration/NF/NFTest.php +++ b/tests/php/integration/NF/NFTest.php @@ -15,6 +15,7 @@ use HCaptcha\NF\NF; use HCaptcha\Settings\General; use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; +use NF_Fields_Hcaptcha; use Ninja_Forms; use ReflectionException; use tad\FunctionMocker\FunctionMocker; @@ -52,6 +53,7 @@ public function tearDown(): void { unset( $_GET['form_id'] ); wp_dequeue_script( 'hcaptcha-nf' ); + wp_dequeue_script( 'nf-hcaptcha' ); parent::tearDown(); } @@ -97,6 +99,14 @@ public function test_init_and_init_hooks(): void { 10, has_filter( 'ninja_forms_localize_field_hcaptcha-for-ninja-forms_preview', [ $subject, 'localize_field' ] ) ); + self::assertSame( + 10, + has_filter( 'ninja_forms_localize_field_hcaptcha', [ $subject, 'mark_native_field' ] ) + ); + self::assertSame( + 10, + has_filter( 'ninja_forms_localize_field_hcaptcha_preview', [ $subject, 'mark_native_field' ] ) + ); self::assertSame( 9, has_action( 'wp_print_footer_scripts', [ $subject, 'nf_captcha_script' ] ) ); } @@ -117,16 +127,12 @@ public function test_admin_template(): void { $templates_dir = $this->get_protected_property( $subject, 'templates_dir' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents - $template = file_get_contents( $templates_dir . 'fields-hcaptcha.html' ); - $expected = str_replace( - 'tmpl-nf-field-' . Base::TYPE, - 'tmpl-nf-field-' . Base::NAME, - $template - ); + $template = file_get_contents( $templates_dir . 'fields-' . Base::NAME . '.html' ); ob_start(); $subject->admin_template(); - self::assertSame( $expected, ob_get_clean() ); + self::assertSame( $template, ob_get_clean() ); + self::assertStringContainsString( 'id="tmpl-nf-field-' . Base::NAME . '"', $template ); } /** @@ -267,7 +273,10 @@ public function test_register_fields(): void { $fields = $nf_instance->fields; + self::assertInstanceOf( NF_Fields_Hcaptcha::class, $fields['hcaptcha'] ); self::assertInstanceOf( Field::class, $fields['hcaptcha-for-ninja-forms'] ); + self::assertContains( Base::TYPE, $fields['hcaptcha']->get_templates() ); + self::assertContains( Base::NAME, $fields['hcaptcha-for-ninja-forms']->get_templates() ); $hcap_index = array_search( Base::NAME, array_keys( $fields ), true ); $recap_index = array_search( 'recaptcha', array_keys( $fields ), true ); @@ -381,10 +390,31 @@ public function test_nf_captcha_script(): void { $subject = new NF(); $this->set_protected_property( $subject, 'form_shown', true ); + wp_enqueue_script( 'nf-hcaptcha', 'https://js.hcaptcha.com/1/api.js?render=explicit', [], '1.0', true ); + + $subject->nf_captcha_script(); + + self::assertTrue( wp_script_is( 'hcaptcha-nf' ) ); + self::assertFalse( wp_script_is( 'nf-hcaptcha' ) ); + } + + /** + * Test native and bridge fields keep both frontend scripts. + */ + public function test_nf_captcha_script_with_native_field(): void { + $subject = new NF(); + $this->set_protected_property( $subject, 'form_shown', true ); + $field = [ + 'id' => 12, + 'settings' => [ 'type' => 'hcaptcha' ], + ]; + self::assertSame( $field, $subject->mark_native_field( $field ) ); + wp_enqueue_script( 'nf-hcaptcha', 'https://js.hcaptcha.com/1/api.js?render=explicit', [], '1.0', true ); $subject->nf_captcha_script(); self::assertTrue( wp_script_is( 'hcaptcha-nf' ) ); + self::assertTrue( wp_script_is( 'nf-hcaptcha' ) ); } /** diff --git a/tests/php/integration/NF/NativeHcaptchaDispatchTest.php b/tests/php/integration/NF/NativeHcaptchaDispatchTest.php new file mode 100644 index 000000000..44678461d --- /dev/null +++ b/tests/php/integration/NF/NativeHcaptchaDispatchTest.php @@ -0,0 +1,180 @@ +instantiateTranslatableObjects(); + + self::assertInstanceOf( NF_Fields_Hcaptcha::class, Ninja_Forms()->fields['hcaptcha'] ); + + $field = $this->create_native_field(); + $old_secret = Ninja_Forms()->get_setting( 'hcaptcha_secret_key' ); + $calls = 0; + $success = false; + $siteverify = static function ( $response, $args, $url ) use ( &$calls, &$success ) { + if ( 'https://api.hcaptcha.com/siteverify' !== $url ) { + return $response; + } + + ++$calls; + + return [ + 'response' => [ + 'code' => 200, + 'message' => 'OK', + ], + 'headers' => [], + 'body' => wp_json_encode( [ 'success' => $success ] ), + 'cookies' => [], + ]; + }; + + Ninja_Forms()->update_setting( 'hcaptcha_secret_key', 'sec010-test-secret', true ); + add_filter( 'pre_http_request', $siteverify, 10, 3 ); + $native_error = esc_html( "Please verify you're human, then submit again." ); + + try { + $missing = $this->dispatch_native_field( $field ); + self::assertTrue( $missing['rejected'] ); + self::assertSame( $native_error, $missing['errors']['fields'][ $field['id'] ] ); + self::assertSame( 0, $calls ); + + $field['value'] = 'invalid-proof'; + $invalid = $this->dispatch_native_field( $field ); + self::assertTrue( $invalid['rejected'] ); + self::assertSame( $native_error, $invalid['errors']['fields'][ $field['id'] ] ); + self::assertSame( 1, $calls ); + + $success = true; + $valid = $this->dispatch_native_field( $field ); + self::assertFalse( $valid['rejected'] ); + self::assertSame( [], $valid['errors'] ); + self::assertSame( 2, $calls ); + } finally { + remove_filter( 'pre_http_request', $siteverify, 10 ); + Ninja_Forms()->update_setting( 'hcaptcha_secret_key', $old_secret, true ); + } + } + + /** + * Create and reload a native hCaptcha field stored on a published form. + * + * @return array + */ + private function create_native_field(): array { + $form = Ninja_Forms()->form()->get(); + $form->update_setting( 'title', 'SEC010 native hCaptcha form' ); + $form->update_setting( 'publish_state', 1 ); + $form->save(); + + $field = Ninja_Forms()->form( $form->get_id() )->field()->get(); + $field->update_setting( 'label', 'hCaptcha' ); + $field->update_setting( 'key', 'native_hcaptcha' ); + $field->update_setting( 'type', 'hcaptcha' ); + $field->save(); + + $stored = Ninja_Forms()->form( $form->get_id() )->get_field( $field->get_id() )->get_settings(); + self::assertSame( 'hcaptcha', $stored['type'] ); + + $stored['id'] = $field->get_id(); + $stored['value'] = ''; + + return $stored; + } + + /** + * Dispatch one field through Ninja Forms' installed submission controller. + * + * @param array $field Field settings and submitted value. + * + * @return array + */ + private function dispatch_native_field( array $field ): array { + $controller = new class() extends NF_AJAX_Controllers_Submission { + /** + * Run the native field dispatch. + * + * @param array $field Field. + */ + public function validate_test_field( array $field ): void { + $this->validate_field( $field ); + } + + /** + * Return field errors captured before a response. + * + * @return array + */ + public function get_test_errors(): array { + return $this->_errors; + } + + // phpcs:disable PSR2.Methods.MethodDeclaration.Underscore + /** + * Stop without exiting the test process. + * + * @param array $data Response data. + * + * @throws RuntimeException When validation rejects the field. + */ + protected function _respond( $data = [] ) { + throw new RuntimeException( 'native field rejected' ); + } + // phpcs:enable PSR2.Methods.MethodDeclaration.Underscore + }; + + $rejected = false; + + try { + $controller->validate_test_field( $field ); + } catch ( RuntimeException $error ) { + self::assertSame( 'native field rejected', $error->getMessage() ); + $rejected = true; + } + + return [ + 'rejected' => $rejected, + 'errors' => $controller->get_test_errors(), + ]; + } +} diff --git a/tests/php/integration/Otter/FormTest.php b/tests/php/integration/Otter/FormTest.php index f46510c2a..d65746352 100644 --- a/tests/php/integration/Otter/FormTest.php +++ b/tests/php/integration/Otter/FormTest.php @@ -59,10 +59,11 @@ class FormTest extends HCaptchaPluginWPTestCase { * Test a live Otter form block and request an object. */ public function test_live_form_block(): void { - $form_id = 'live-form'; - $content = << -
      + $form_id = 'live-form'; + $form_option = 'live-form-option'; + $content = << +
      HTML; @@ -77,13 +78,15 @@ public function test_live_form_block(): void { self::assertStringContainsString( 'otter-form__container', $html ); self::assertStringContainsString( 'class="h-captcha"', $html ); self::assertStringContainsString( 'hcaptcha_otter_nonce', $html ); + self::assertSame( 1, preg_match( '/name="hcaptcha_otter_form_nonce" value="([^"]+)"/', $html, $form_nonce ) ); self::assertStringNotContainsString( 'has-captcha', $html ); $this->prepare_verify_post( 'hcaptcha_otter_nonce', 'hcaptcha_otter' ); $request_data = [ - 'payload' => [ + 'payload' => [ 'formId' => 'wp-block-themeisle-blocks-form-' . $form_id, + 'formOption' => $form_option, 'antiSpamTime' => 5000, 'antiSpamHoneyPot' => '', 'postId' => wp_insert_post( @@ -101,8 +104,9 @@ public function test_live_form_block(): void { ], ], ], - 'h-captcha-response' => 'some response', - 'hcaptcha-widget-id' => HCaptcha::widget_id_value( + 'h-captcha-response' => 'some response', + 'hcaptcha_otter_form_nonce' => $form_nonce[1], + 'hcaptcha-widget-id' => HCaptcha::widget_id_value( [ 'source' => [ static::$plugin ], 'form_id' => $form_id, @@ -146,6 +150,27 @@ public function test_init_hooks(): void { self::assertSame( 9, has_action( 'wp_print_footer_scripts', [ $subject, 'enqueue_scripts' ] ) ); } + /** + * Do not replace the native site key in the admin area. + */ + public function test_init_hooks_in_admin(): void { + set_current_screen( 'dashboard' ); + + $subject = new Form(); + + self::assertFalse( has_filter( 'option_themeisle_google_captcha_api_site_key', [ $subject, 'replace_site_key' ] ) ); + } + + /** + * Reject a payload that cannot contain the native form nonce. + */ + public function test_has_valid_form_nonce_rejects_non_array_payload(): void { + $subject = new Form(); + $method = $this->set_method_accessibility( $subject, 'has_valid_form_nonce' ); + + self::assertFalse( $method->invoke( $subject, [ 'payload' => 'invalid' ] ) ); + } + /** * Test replace_site_key(). * @@ -164,8 +189,10 @@ public function test_replace_site_key(): void { * @return void */ public function test_add_hcaptcha(): void { - $form_id = 'fc0b7800'; - $hcap_form = $this->get_hcap_form( + $form_id = 'fc0b7800'; + $form_option = 'fc0b7800-option'; + $form_nonce = $this->create_form_nonce( $form_id, $form_option ); + $hcap_form = $this->get_hcap_form( [ 'action' => 'hcaptcha_otter', 'name' => 'hcaptcha_otter_nonce', @@ -194,12 +221,16 @@ public function test_add_hcaptcha(): void {
      HTML; - $block = [ 'blockName' => 'themeisle-blocks/form' ]; + $block = [ + 'blockName' => 'themeisle-blocks/form', + 'attrs' => [ 'optionName' => $form_option ], + ]; $expected = <<
      Some form inputs $hcap_form +
      @@ -211,6 +242,24 @@ public function test_add_hcaptcha(): void { self::assertSame( $expected, $subject->add_hcaptcha( $block_content, $block, $instance ) ); } + /** + * The signed option must match the rendered value Otter's script submits. + */ + public function test_add_hcaptcha_binds_rendered_option_name(): void { + $subject = new Form(); + $instance = Mockery::mock( WP_Block::class ); + $block = [ + 'blockName' => 'themeisle-blocks/form', + 'attrs' => [ 'optionName' => 'saved-option' ], + ]; + $content = '
      '; + $rendered = $subject->add_hcaptcha( $content, $block, $instance ); + + self::assertSame( 1, preg_match( '/name="hcaptcha_otter_form_nonce" value="([^"]+)"/', $rendered, $matches ) ); + self::assertNotFalse( wp_verify_nonce( $matches[1], 'hcaptcha_otter|' . wp_json_encode( [ 'rendered', 'rendered-option' ] ) ) ); + self::assertFalse( wp_verify_nonce( $matches[1], 'hcaptcha_otter|' . wp_json_encode( [ 'rendered', 'saved-option' ] ) ) ); + } + /** * Test verify(). * @@ -237,10 +286,11 @@ public function test_verify( bool $verified ): void { $form_data_request->shouldReceive( 'has_error' )->andReturn( false ); - $action = 'hcaptcha_otter'; - $nonce = 'hcaptcha_otter_nonce'; - $form_id = 'fc0b7800'; - $widget_id = HCaptcha::widget_id_value( + $action = 'hcaptcha_otter'; + $nonce = 'hcaptcha_otter_nonce'; + $form_id = 'fc0b7800'; + $form_option = 'fc0b7800-option'; + $widget_id = HCaptcha::widget_id_value( [ 'source' => [ 'otter-blocks/otter-blocks.php' ], 'form_id' => $form_id, @@ -251,15 +301,17 @@ public function test_verify( bool $verified ): void { $form_data_arr = [ 'form_data' => [ - 'payload' => [ - 'formId' => 'wp-block-themeisle-blocks-form-' . $form_id, + 'payload' => [ + 'formId' => 'wp-block-themeisle-blocks-form-' . $form_id, + 'formOption' => $form_option, ], - 'h-captcha-response' => 'some response', - 'hcaptcha-widget-id' => $widget_id, - $nonce => $_POST[ $nonce ], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash - 'hcap_fst_token' => $_POST['hcap_fst_token'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash - 'hcap_hp_test' => $_POST['hcap_hp_test'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash - 'hcap_hp_sig' => $_POST['hcap_hp_sig'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'h-captcha-response' => 'some response', + 'hcaptcha_otter_form_nonce' => $this->create_form_nonce( $form_id, $form_option ), + 'hcaptcha-widget-id' => $widget_id, + $nonce => $_POST[ $nonce ], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'hcap_fst_token' => $_POST['hcap_fst_token'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'hcap_hp_test' => $_POST['hcap_hp_test'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'hcap_hp_sig' => $_POST['hcap_hp_sig'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash ], ]; @@ -293,14 +345,16 @@ public function test_verify_missing_widget_id(): void { $form_data_request->shouldReceive( 'dump_data' )->with()->andReturn( [ 'form_data' => [ - 'payload' => [ - 'formId' => 'wp-block-themeisle-blocks-form-fc0b7800', + 'payload' => [ + 'formId' => 'wp-block-themeisle-blocks-form-fc0b7800', + 'formOption' => 'fc0b7800-option', ], - 'h-captcha-response' => 'some response', - $nonce => $_POST[ $nonce ], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash - 'hcap_fst_token' => $_POST['hcap_fst_token'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash - 'hcap_hp_test' => $_POST['hcap_hp_test'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash - 'hcap_hp_sig' => $_POST['hcap_hp_sig'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'h-captcha-response' => 'some response', + 'hcaptcha_otter_form_nonce' => $this->create_form_nonce( 'fc0b7800', 'fc0b7800-option' ), + $nonce => $_POST[ $nonce ], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'hcap_fst_token' => $_POST['hcap_fst_token'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'hcap_hp_test' => $_POST['hcap_hp_test'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash + 'hcap_hp_sig' => $_POST['hcap_hp_sig'], // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash ], ] ); @@ -310,6 +364,84 @@ public function test_verify_missing_widget_id(): void { self::assertInstanceOf( Form_Data_Request::class, $result ); } + + /** + * A signed widget for an exempt form cannot select another form's options. + */ + public function test_form_option_binding_rejects_exempt_widget_swap(): void { + $subject = new Form(); + $form_id = 'sec009-source'; + $source_name = 'sec009-source-option'; + $target_name = 'sec009-target-option'; + $block = [ + 'blockName' => 'themeisle-blocks/form', + 'attrs' => [ 'optionName' => $source_name ], + ]; + $content = '
      '; + $instance = Mockery::mock( WP_Block::class ); + $rendered = $subject->add_hcaptcha( $content, $block, $instance ); + + self::assertSame( 1, preg_match( '/name="hcaptcha_otter_form_nonce" value="([^"]+)"/', $rendered, $matches ) ); + $source_nonce = $matches[1]; + + $exempt_source = static function ( $protect, $source, $checked_form_id ) use ( $form_id ) { + return $form_id === $checked_form_id ? false : $protect; + }; + add_filter( 'hcap_protect_form', $exempt_source, 10, 3 ); + + try { + $widget_id = HCaptcha::widget_id_value( + [ + 'source' => [ static::$plugin ], + 'form_id' => $form_id, + ] + ); + + $make_request = static function ( $form_option, $form_nonce, $submitted_form_id = null ) use ( $form_id, $widget_id ) { + $request = new WP_REST_Request( 'POST', '/otter/v1/form/frontend' ); + $request->set_body( + wp_json_encode( + [ + 'payload' => [ + 'formId' => $submitted_form_id ?? 'wp-block-themeisle-blocks-form-' . $form_id, + 'formOption' => $form_option, + 'postId' => 0, + ], + 'hcaptcha-widget-id' => $widget_id, + 'hcaptcha_otter_form_nonce' => $form_nonce, + ] + ) + ); + + return new Form_Data_Request( $request ); + }; + + $swapped = $make_request( $target_name, $source_nonce ); + $subject->verify( $swapped ); + self::assertTrue( $swapped->has_error() ); + self::assertSame( 'bad-signature', $swapped->get_error_code() ); + + $missing = $make_request( $source_name, '' ); + $subject->verify( $missing ); + self::assertTrue( $missing->has_error() ); + self::assertSame( 'bad-signature', $missing->get_error_code() ); + + $synthetic = $make_request( $source_name, $source_nonce, 'wp-block-themeisle-blocks-form-wrong' ); + $subject->verify( $synthetic ); + self::assertTrue( $synthetic->has_error() ); + self::assertSame( 'bad-signature', $synthetic->get_error_code() ); + + $legitimate = $make_request( $source_name, $source_nonce ); + $subject->verify( $legitimate ); + self::assertFalse( $legitimate->has_error() ); + + $legacy_id = $make_request( $source_name, $source_nonce, $form_id ); + $subject->verify( $legacy_id ); + self::assertFalse( $legacy_id->has_error() ); + } finally { + remove_filter( 'hcap_protect_form', $exempt_source ); + } + } /** * Data provider for test_verify(). * @@ -345,6 +477,11 @@ public function test_get_entry_and_data(): void { ], [ 'label' => 'Email', + 'value' => 'jane@sec060-disposable.test', + 'type' => 'email', + ], + [ + 'label' => 'Secondary email', 'value' => 'jane@example.com', 'type' => 'email', ], @@ -362,6 +499,10 @@ public function test_get_entry_and_data(): void { 'label' => 'Empty', 'value' => '', ], + [ + 'label' => 'Empty array', + 'value' => [], + ], ]; $post_data = [ 'payload' => [ @@ -387,12 +528,28 @@ public function test_get_entry_and_data(): void { ], $entry['expected_id'] ); - self::assertSame( 'jane@example.com', $entry['data']['email'] ); + self::assertSame( 'jane@sec060-disposable.test', $entry['data']['email'] ); + self::assertSame( [ 'jane@sec060-disposable.test', 'jane@example.com' ], $entry['email_addresses'] ); + self::assertSame( 'jane@example.com', $entry['data']['Secondary email'] ); self::assertSame( 'Jane Doe', $entry['data']['name'] ); self::assertSame( 'Jane Doe', $entry['data']['Name'] ); self::assertSame( [ 'Hello', 'world' ], $entry['data']['Message'] ); self::assertSame( 'Field value', $entry['data']['field-id'] ); self::assertArrayNotHasKey( 'Empty', $entry['data'] ); + self::assertArrayNotHasKey( 'Empty array', $entry['data'] ); + + $post_data['payload']['formInputsData'] = [ + [ + 'label' => '', + 'id' => '', + 'type' => 'email', + 'value' => 'nameless@sec060-disposable.test', + ], + ]; + $entry = $method->invoke( $subject, $post_data ); + + self::assertSame( 'nameless@sec060-disposable.test', $entry['data']['email'] ); + self::assertSame( [ 'nameless@sec060-disposable.test' ], $entry['email_addresses'] ); } /** @@ -460,4 +617,16 @@ public function test_enqueue_scripts(): void { // Check if the script is enqueued. self::assertTrue( wp_script_is( 'hcaptcha-otter' ) ); } + + /** + * Create an Otter form binding nonce for existing direct-filter cases. + * + * @param string $form_id Form id without the Otter prefix. + * @param string $form_option Native Otter option name. + * + * @return string + */ + private function create_form_nonce( string $form_id, string $form_option ): string { + return wp_create_nonce( 'hcaptcha_otter|' . wp_json_encode( [ $form_id, $form_option ] ) ); + } } diff --git a/tests/php/integration/Passster/ProtectTest.php b/tests/php/integration/Passster/ProtectTest.php index 7e70ab65b..36f03a92e 100644 --- a/tests/php/integration/Passster/ProtectTest.php +++ b/tests/php/integration/Passster/ProtectTest.php @@ -11,8 +11,12 @@ use HCaptcha\Helpers\HCaptcha; use HCaptcha\Passster\Protect; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; +use ReflectionException; +use ReflectionMethod; +use tad\FunctionMocker\FunctionMocker; use WP_REST_Request; use WP_REST_Response; +use WP_REST_Server; /** * Test the Passster integration. @@ -35,6 +39,50 @@ public function setUp(): void { $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } + /** + * Unrelated shortcodes retain their original output. + */ + public function test_unrelated_shortcode_is_unchanged(): void { + $subject = new Protect(); + + self::assertSame( 'original', $subject->do_shortcode_tag( 'original', 'other', [], [] ) ); + } + + /** + * Script and style helpers act only after a Passster hCaptcha form is shown. + * + * @noinspection HtmlUnknownTarget + */ + public function test_frontend_script_and_style_helpers(): void { + $subject = new Protect(); + $form_shown = hcaptcha()->form_shown; + $handle = 'hcaptcha-passster'; + + try { + hcaptcha()->form_shown = false; + $subject->enqueue_scripts(); + self::assertFalse( wp_script_is( $handle ) ); + + hcaptcha()->form_shown = true; + $subject->enqueue_scripts(); + self::assertTrue( wp_script_is( $handle ) ); + self::assertStringContainsString( 'hcaptcha-passster', wp_scripts()->registered[ $handle ]->src ); + + // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Input fixture for a tag filter. + $tag = ''; + self::assertSame( $tag, $subject->add_type_module( $tag, 'other', '' ) ); + self::assertStringContainsString( 'type="module"', $subject->add_type_module( $tag, $handle, '' ) ); + + ob_start(); + $subject->print_inline_styles(); + self::assertStringContainsString( '.passster-form .h-captcha', ob_get_clean() ); + } finally { + hcaptcha()->form_shown = $form_shown; + wp_dequeue_script( $handle ); + wp_deregister_script( $handle ); + } + } + /** * Test that the rendered form contains honeypot fields. * @@ -49,6 +97,46 @@ public function test_form_contains_honeypot(): void { self::assertStringContainsString( 'name="hcap_hp_test"', $output ); self::assertStringContainsString( 'name="hcap_hp_sig"', $output ); self::assertStringContainsString( 'name="hcaptcha-widget-id"', $output ); + self::assertStringContainsString( + HCaptcha::widget_id_value( + [ + 'source' => [ 'content-protector/content-protector.php' ], + 'form_id' => '3866', + ] + ), + $output + ); + } + + /** + * Password and legacy input fields never become anti-spam entry data. + * + * @throws ReflectionException Reflection exception. + */ + public function test_entry_contains_only_unlock_context(): void { + $method = new ReflectionMethod( Protect::class, 'get_entry' ); + $method->setAccessible( true ); + + self::assertSame( + [ + 'data' => [ + 'form' => 'protect', + 'area' => '3866', + 'post_id' => '123', + 'type' => 'password', + ], + ], + $method->invoke( + new Protect(), + [ + 'password' => 'private-password', + 'input' => 'private-input', + 'area' => '3866', + 'post_id' => 123, + 'type' => 'password', + ] + ) + ); } /** @@ -88,6 +176,7 @@ public function test_filled_honeypot_is_rejected_in_rest_request(): void { ] ); $_POST['hcap_hp_test'] = 'bot'; + $_POST['area_id'] = 3866; $request = new WP_REST_Request( 'POST', '/passster/v1/unlock' ); $request->set_header( 'Content-Type', 'application/json' ); @@ -106,6 +195,239 @@ public function test_filled_honeypot_is_rejected_in_rest_request(): void { ); } + /** + * Native Passster unlock requests must reject missing or failed hCaptcha proof at every route casing. + * + * @dataProvider dp_invalid_rest_unlock_requests + * + * @param string $route Unlock route as sent by the client. + * @param bool $failed_response Whether to supply a failed hCaptcha response. + * + * @return void + */ + public function test_rest_unlock_case_variants_reject_invalid_hcaptcha( string $route, bool $failed_response ): void { + $_POST = []; + $data = [ + 'password' => 'local-test-password', + 'type' => 'password', + 'post_id' => 123, + ]; + + if ( $failed_response ) { + $this->prepare_verify_post( 'hcaptcha_passster_nonce', 'hcaptcha_passster', false ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'content-protector/content-protector.php' ], + 'form_id' => 0, + ] + ); + + $data = array_merge( $data, $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + } + + $request = new WP_REST_Request( 'POST', $route ); + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( wp_json_encode( $data ) ); + + $response = ( new Protect() )->verify_rest( null, null, $request ); + + self::assertInstanceOf( WP_REST_Response::class, $response ); + self::assertFalse( $response->get_data()['success'] ); + self::assertNotSame( '', $response->get_data()['error'] ); + self::assertSame( $failed_response, hcaptcha()->has_result ); + } + + /** + * Invalid native unlock requests with canonical and case-variant routes. + * + * @return array + */ + public function dp_invalid_rest_unlock_requests(): array { + return [ + 'canonical without proof' => [ '/passster/v1/unlock', false ], + 'uppercase without proof' => [ '/PASSSTER/v1/UNLOCK', false ], + 'mixed case without proof' => [ '/Passster/V1/UnLock', false ], + 'terminal LF without proof' => [ "/passster/v1/unlock\n", false ], + 'canonical failed proof' => [ '/passster/v1/unlock', true ], + 'uppercase failed proof' => [ '/PASSSTER/v1/UNLOCK', true ], + 'mixed case failed proof' => [ '/Passster/V1/UnLock', true ], + 'terminal LF failed proof' => [ "/Passster/V1/UnLock\n", true ], + ]; + } + + /** + * WordPress routes terminal-LF unlock requests to the native callback, so hCaptcha must run first. + * + * @return void + */ + public function test_rest_dispatch_guards_terminal_lf_unlock(): void { + $subject = new Protect(); + $server = new WP_REST_Server(); + $dispatched = 0; + + $server->register_route( + 'passster/v1', + '/passster/v1/unlock', + [ + [ + 'methods' => 'POST', + 'callback' => static function () use ( &$dispatched ): WP_REST_Response { + ++$dispatched; + + return new WP_REST_Response( [ 'dispatched' => true ], 202 ); + }, + 'permission_callback' => '__return_true', + ], + ] + ); + + $request = new WP_REST_Request( 'POST', "/Passster/V1/UnLock\n" ); + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( '{}' ); + + try { + $response = $server->dispatch( $request ); + + self::assertFalse( $response->get_data()['success'] ); + self::assertSame( 0, $dispatched ); + + remove_filter( 'rest_pre_dispatch', [ $subject, 'verify_rest' ], 9 ); + $response = $server->dispatch( $request ); + + self::assertSame( 202, $response->get_status() ); + self::assertSame( [ 'dispatched' => true ], $response->get_data() ); + self::assertSame( 1, $dispatched ); + } finally { + remove_filter( 'rest_pre_dispatch', [ $subject, 'verify_rest' ], 9 ); + } + } + + /** + * A valid hCaptcha response still lets a case-variant unlock reach Passster. + * + * @return void + */ + public function test_valid_case_variant_rest_unlock_is_unchanged(): void { + $this->prepare_verify_post( 'hcaptcha_passster_nonce', 'hcaptcha_passster' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'content-protector/content-protector.php' ], + 'form_id' => 0, + ] + ); + + $request = new WP_REST_Request( 'POST', '/PASSSTER/v1/UNLOCK' ); + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( + wp_json_encode( + array_merge( + [ + 'password' => 'local-test-password', + 'type' => 'password', + 'post_id' => 123, + ], + $_POST // phpcs:ignore WordPress.Security.NonceVerification.Missing + ) + ) + ); + + self::assertNull( ( new Protect() )->verify_rest( null, null, $request ) ); + self::assertTrue( hcaptcha()->has_result ); + } + + /** + * REST unlocks reject a widget for a different protected area. + */ + public function test_rest_unlock_rejects_foreign_area_widget(): void { + $this->prepare_verify_post( 'hcaptcha_passster_nonce', 'hcaptcha_passster' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'content-protector/content-protector.php' ], + 'form_id' => '3866', + ] + ); + + $request = new WP_REST_Request( 'POST', '/passster/v1/unlock' ); + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( wp_json_encode( array_merge( $_POST, [ 'area_id' => 3867 ] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + + $response = ( new Protect() )->verify_rest( null, null, $request ); + + self::assertInstanceOf( WP_REST_Response::class, $response ); + self::assertSame( hcap_get_error_messages()['bad-signature'], $response->get_data()['error'] ); + } + + /** + * Legacy AJAX verification uses the native area field as the expected identity. + */ + public function test_legacy_verification_uses_native_area(): void { + $_POST['area'] = '3866'; + $expected_id = []; + FunctionMocker::replace( + '\HCaptcha\Helpers\API::verify_post', + static function ( string $name, string $action, array $id ) use ( &$expected_id ): ?string { + $expected_id = $id; + + return null; + } + ); + + ( new Protect() )->verify( 'password' ); + + self::assertSame( + [ + 'source' => [ 'content-protector/content-protector.php' ], + 'form_id' => '3866', + ], + $expected_id + ); + } + + /** + * Only POST requests matched to the native unlock route with no earlier response are intercepted. + * + * @dataProvider dp_unrelated_rest_unlock_requests + * + * @param string $method REST method. + * @param string $route REST route. + * + * @return void + */ + public function test_unrelated_rest_unlock_requests_are_ignored( string $method, string $route ): void { + $request = new WP_REST_Request( $method, $route ); + + self::assertNull( ( new Protect() )->verify_rest( null, null, $request ) ); + self::assertFalse( hcaptcha()->has_result ); + } + + /** + * Similar routes and non-POST methods must not be guarded. + * + * @return array + */ + public function dp_unrelated_rest_unlock_requests(): array { + return [ + 'prefix' => [ 'POST', '/passster/v1/unlock-more' ], + 'suffix' => [ 'POST', '/other/passster/v1/unlock' ], + 'nearby' => [ 'POST', '/passster/v1/unlocked' ], + 'GET unlock' => [ 'GET', '/PASSSTER/v1/UNLOCK' ], + 'PUT unlock' => [ 'PUT', '/Passster/V1/UnLock' ], + ]; + } + + /** + * An earlier REST pre-dispatch result must pass through unchanged. + * + * @return void + */ + public function test_existing_rest_pre_dispatch_result_is_unchanged(): void { + $request = new WP_REST_Request( 'POST', '/PASSSTER/v1/UNLOCK' ); + $result = new WP_REST_Response( [ 'handled' => true ], 202 ); + + self::assertSame( $result, ( new Protect() )->verify_rest( $result, null, $request ) ); + self::assertFalse( hcaptcha()->has_result ); + } + /** * Test that unrelated REST requests are ignored. * diff --git a/tests/php/integration/ProfileBuilder/LoginTest.php b/tests/php/integration/ProfileBuilder/LoginTest.php index fddd27900..9a254da85 100644 --- a/tests/php/integration/ProfileBuilder/LoginTest.php +++ b/tests/php/integration/ProfileBuilder/LoginTest.php @@ -12,6 +12,7 @@ use HCaptcha\Tests\Integration\HCaptchaWPTestCase; use HCaptcha\WP\LoginOut; use Mockery; +use WP_User; /** * Test Login class. @@ -20,6 +21,35 @@ * @group profile-builder-login */ class LoginTest extends HCaptchaWPTestCase { + /** + * Skip unrelated form rendering and keep a low-risk login unchanged. + */ + public function test_other_form_and_login_below_limit(): void { + $subject = new Login(); + $user = new WP_User( 1 ); + + self::assertSame( 'other', $subject->add_wppb_captcha( 'other', [] ) ); + self::assertSame( $user, $subject->verify( $user, 'password' ) ); + + add_filter( 'hcap_login_limit_exceeded', '__return_false' ); + do_action( 'wppb_process_login_start' ); + + try { + self::assertSame( $user, $subject->verify( $user, 'password' ) ); + } finally { + remove_filter( 'hcap_login_limit_exceeded', '__return_false' ); + } + } + + /** + * Print the Profile Builder login spacing rule. + */ + public function test_print_inline_styles(): void { + ob_start(); + ( new Login() )->print_inline_styles(); + + self::assertStringContainsString( '#wppb-loginform .h-captcha', ob_get_clean() ); + } /** * Set up the test. diff --git a/tests/php/integration/ProfileBuilder/LostPasswordTest.php b/tests/php/integration/ProfileBuilder/LostPasswordTest.php index 914557c75..00e5a7707 100644 --- a/tests/php/integration/ProfileBuilder/LostPasswordTest.php +++ b/tests/php/integration/ProfileBuilder/LostPasswordTest.php @@ -10,6 +10,7 @@ use HCaptcha\Helpers\HCaptcha; use HCaptcha\ProfileBuilder\LostPassword; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; +use WP_Error; /** * Test the Profile Builder lost-password integration. @@ -18,6 +19,23 @@ * @group profile-builder-lost-password */ class LostPasswordTest extends HCaptchaWPTestCase { + /** + * Leave unrelated shortcodes and incomplete recovery requests unchanged. + */ + public function test_verify_ignores_unrelated_requests(): void { + $subject = new LostPassword(); + + self::assertSame( 'before', $subject->verify( 'before', 'other', [], [] ) ); + self::assertSame( 'before', $subject->verify( 'before', 'wppb-recover-password', [], [] ) ); + self::assertSame( 'message', $subject->recover_password_displayed_message1( 'message' ) ); + } + + /** + * Request method before the test. + * + * @var string|null + */ + private ?string $request_method = null; /** * Set up the test. @@ -26,6 +44,8 @@ class LostPasswordTest extends HCaptchaWPTestCase { */ public function setUp(): void { parent::setUp(); + // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized + $this->request_method = $_SERVER['REQUEST_METHOD'] ?? null; hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); @@ -33,6 +53,21 @@ public function setUp(): void { $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } + /** + * Restore the request method after each test. + * + * @return void + */ + public function tearDown(): void { + if ( null === $this->request_method ) { + unset( $_SERVER['REQUEST_METHOD'] ); + } else { + $_SERVER['REQUEST_METHOD'] = $this->request_method; + } + + parent::tearDown(); + } + /** * Test the lost-password form contains honeypot fields. * @@ -84,4 +119,159 @@ public function test_filled_honeypot_is_rejected(): void { // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput self::assertSame( 'person@example.com', $_POST['username_email'] ); } + + /** + * A valid recovery proof leaves the native shortcode output unchanged. + */ + public function test_verify_accepts_valid_recovery_proof(): void { + $this->prepare_verify_post( 'hcaptcha_profile_builder_lost_password_nonce', 'hcaptcha_profile_builder_lost_password' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'profile-builder/index.php' ], + 'form_id' => 'lost_password', + ] + ); + $_POST['action'] = 'recover_password'; + + self::assertSame( 'before', ( new LostPassword() )->verify( 'before', 'wppb-recover-password', [], [] ) ); + } + + /** + * A failed recovery without a login name still stops native processing. + */ + public function test_verify_rejects_failed_recovery_without_username(): void { + $_POST['action'] = 'recover_password'; + + $subject = new LostPassword(); + $subject->verify( false, 'wppb-recover-password', [], [] ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput + self::assertSame( '', $_POST['username_email'] ); + } + + /** + * The native final reset validation must reject a missing hCaptcha proof. + * + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_final_reset_rejects_missing_captcha(): void { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ 'action2' => 'recover_password2' ]; + $user = $this->factory()->user->create_and_get(); + new LostPassword(); + + $message = apply_filters( 'wppb_recover_password_extra_validation', '', $user ); + + self::assertSame( hcap_get_error_messages()['bad-signature'], $message ); + } + + /** + * A solved reset-stage widget still permits native password validation. + * + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_final_reset_accepts_valid_captcha(): void { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ 'action2' => 'recover_password2' ]; + $this->prepare_verify_post( 'hcaptcha_profile_builder_lost_password_nonce', 'hcaptcha_profile_builder_lost_password' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'profile-builder/index.php' ], + 'form_id' => 'lost_password', + ] + ); + + $user = $this->factory()->user->create_and_get(); + new LostPassword(); + + self::assertSame( '', apply_filters( 'wppb_recover_password_extra_validation', '', $user ) ); + } + + /** + * A signed widget with a failed siteverify result cannot reset a password. + * + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_final_reset_rejects_failed_captcha(): void { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ 'action2' => 'recover_password2' ]; + $this->prepare_verify_post( 'hcaptcha_profile_builder_lost_password_nonce', 'hcaptcha_profile_builder_lost_password', false ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'profile-builder/index.php' ], + 'form_id' => 'lost_password', + ] + ); + + $user = $this->factory()->user->create_and_get(); + new LostPassword(); + + self::assertSame( hcap_get_error_messages()['fail'], apply_filters( 'wppb_recover_password_extra_validation', '', $user ) ); + } + + /** + * A valid proof from another form cannot authorize password reset. + * + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_final_reset_rejects_foreign_widget(): void { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ 'action2' => 'recover_password2' ]; + $this->prepare_verify_post( 'hcaptcha_profile_builder_lost_password_nonce', 'hcaptcha_profile_builder_lost_password' ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'profile-builder/index.php' ], + 'form_id' => 'register', + ] + ); + + $user = $this->factory()->user->create_and_get(); + new LostPassword(); + + self::assertSame( hcap_get_error_messages()['bad-signature'], apply_filters( 'wppb_recover_password_extra_validation', '', $user ) ); + } + + /** + * Native key, user, password, and other validation errors take precedence. + * + * @return void + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_final_reset_preserves_native_error(): void { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = [ 'action2' => 'recover_password2' ]; + $user = $this->factory()->user->create_and_get(); + new LostPassword(); + + self::assertSame( 'Native validation error.', apply_filters( 'wppb_recover_password_extra_validation', 'Native validation error.', $user ) ); + self::assertSame( '', apply_filters( 'wppb_recover_password_extra_validation', '', new WP_Error( 'invalid_key', 'Invalid key.' ) ) ); + } + + /** + * Other methods and action markers are not reset-stage submissions. + * + * @return void + * @noinspection MultiAssignmentUsageInspection + */ + public function test_final_reset_ignores_other_requests(): void { + $user = $this->factory()->user->create_and_get(); + new LostPassword(); + + foreach ( + [ + [ 'GET', [ 'action2' => 'recover_password2' ] ], + [ 'POST', [ 'action' => 'recover_password' ] ], + [ 'POST', [ 'action2' => [ 'recover_password2' ] ] ], + [ 'POST', [] ], + ] as $request + ) { + $_SERVER['REQUEST_METHOD'] = $request[0]; + $_POST = $request[1]; + self::assertSame( '', apply_filters( 'wppb_recover_password_extra_validation', '', $user ) ); + } + } } diff --git a/tests/php/integration/ProfileBuilder/RegisterTest.php b/tests/php/integration/ProfileBuilder/RegisterTest.php index e62166af1..9db193410 100644 --- a/tests/php/integration/ProfileBuilder/RegisterTest.php +++ b/tests/php/integration/ProfileBuilder/RegisterTest.php @@ -18,6 +18,15 @@ * @group profile-builder-register */ class RegisterTest extends HCaptchaWPTestCase { + /** + * Leave other forms and empty error notices unchanged. + */ + public function test_ignores_other_forms_and_empty_error(): void { + $subject = new Register(); + + self::assertSame( [ 'existing' ], $subject->verify( [ 'existing' ], [], [], 'edit' ) ); + self::assertSame( 'existing', $subject->general_top_error_message( 'existing' ) ); + } /** * Set up the test. @@ -29,7 +38,7 @@ public function setUp(): void { hcaptcha()->settings()->set( 'honeypot', 'on' ); hcaptcha()->settings()->set( 'set_min_submit_time', 'on' ); - hcaptcha()->settings()->set( 'profile_builder_status', 'register' ); + hcaptcha()->settings()->set( 'profile_builder_status', [ 'register' ] ); $this->set_protected_property( hcaptcha(), 'supported_forms', null ); } @@ -67,8 +76,74 @@ public function test_filled_honeypot_is_rejected(): void { ); $_POST['hcap_hp_test'] = 'bot'; - $result = ( new Register() )->verify( [], [], [], 'register' ); + $subject = new Register(); + $result = $subject->verify( [], [], [], 'register' ); self::assertSame( [ 'Anti-spam check failed.' ], $result ); + self::assertSame( '

      Anti-spam check failed.

      ', $subject->general_top_error_message( '' ) ); + } + + /** + * Validate only the native default email field with its processing filter. + * + * @dataProvider dp_test_native_email_policy + * + * @param array $fields Native form schema. + * @param string $email Native input email. + * @param bool $rewrite Whether the native filter changes the address. + * @param bool $blocked Whether disposal policy rejects it. + */ + public function test_native_email_policy( array $fields, string $email, bool $rewrite, bool $blocked ): void { + add_filter( + 'hcap_disposable_email_domains', + static function (): array { + return [ 'disposable.example' => true ]; + } + ); + if ( $rewrite ) { + add_filter( + 'wppb_before_processing_email_from_forms', + static function (): string { + return 'user@disposable.example'; + } + ); + } + $_POST['email'] = 'safe@example.com'; + $this->prepare_verify_post( 'hcaptcha_profile_builder_register_nonce', 'hcaptcha_profile_builder_register' ); + hcaptcha()->settings()->set( 'disposable_email', [ 'on' ] ); + hcaptcha()->settings()->set( 'profile_builder_status', [ 'register' ] ); + $this->set_protected_property( hcaptcha(), 'supported_forms', null ); + self::assertTrue( hcaptcha()->settings()->is_on( 'disposable_email' ) ); + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = HCaptcha::widget_id_value( + [ + 'source' => [ 'profile-builder/index.php' ], + 'form_id' => 'register', + ] + ); + + $result = ( new Register() )->verify( [], $fields, [ 'email' => $email ], 'register' ); + + self::assertSame( $blocked ? [ hcap_get_error_messages()['disposable-email'] ] : [], $result ); + } + + /** + * Native email schema and normalization controls. + * + * @return array + */ + public function dp_test_native_email_policy(): array { + $native = [ + [ + 'field' => 'Default - E-mail', + 'field-title' => 'Secret contact', + ], + ]; + + return [ + 'disposable native field' => [ $native, 'user@disposable.example', false, true ], + 'permanent native field' => [ $native, 'safe@example.com', false, false ], + 'native processing filter' => [ $native, 'safe@example.com', true, true ], + 'no native email field' => [ [ [ 'field' => 'Input' ] ], 'user@disposable.example', false, false ], + ]; } } diff --git a/tests/php/integration/ProtectContent/ProtectContentTest.php b/tests/php/integration/ProtectContent/ProtectContentTest.php index d3d498ea1..b6597f92a 100644 --- a/tests/php/integration/ProtectContent/ProtectContentTest.php +++ b/tests/php/integration/ProtectContent/ProtectContentTest.php @@ -8,11 +8,16 @@ namespace HCaptcha\Tests\Integration\ProtectContent; use HCaptcha\PasswordProtected\Protect; +use HCaptcha\Helpers\HCaptcha; use HCaptcha\ProtectContent\ProtectContent; +use HCaptcha\Settings\Advanced; use HCaptcha\Tests\Integration\HCaptchaWPTestCase; use Mockery; use ReflectionException; use tad\FunctionMocker\FunctionMocker; +use WP_Query; +use WP_REST_Request; +use WP_REST_Response; use WP_Scripts; use WP_Styles; @@ -33,6 +38,291 @@ class ProtectContentTest extends HCaptchaWPTestCase { */ private const SESSION_COOKIE_NAME = 'hcaptcha_content_protection_session'; + /** + * REST post and page responses use the selected resource's clearance scope. + * + * @return void + */ + public function test_rest_posts_and_pages_require_resource_clearance(): void { + $post_id = $this->factory()->post->create( + [ + 'post_status' => 'publish', + 'post_content' => 'Protected REST post marker.', + ] + ); + $page_id = $this->factory()->post->create( + [ + 'post_type' => 'page', + 'post_status' => 'publish', + 'post_content' => 'Protected REST page marker.', + ] + ); + $public_id = $this->factory()->post->create( [ 'post_status' => 'publish' ] ); + $post_scope = get_permalink( $post_id ); + $page_scope = get_permalink( $page_id ); + + $this->configure_protected_urls( $post_scope . "\n" . $page_scope ); + $_SERVER['REQUEST_URI'] = '/wp-json/wp/v2/posts'; + $subject = new ProtectContent(); + $subject->init(); + + $previous_server = $GLOBALS['wp_rest_server'] ?? null; + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Isolate the native REST registry. + $GLOBALS['wp_rest_server'] = null; + + try { + $server = rest_get_server(); + $post_response = $server->dispatch( new WP_REST_Request( 'GET', '/wp/v2/posts/' . $post_id ) ); + $page_response = $server->dispatch( new WP_REST_Request( 'GET', '/wp/v2/pages/' . $page_id ) ); + $public_response = $server->dispatch( new WP_REST_Request( 'GET', '/wp/v2/posts/' . $public_id ) ); + + self::assertSame( 403, $post_response->get_status() ); + self::assertSame( 'hcaptcha_content_protected', $post_response->get_data()['code'] ); + self::assertSame( 403, $page_response->get_status() ); + self::assertSame( 'hcaptcha_content_protected', $page_response->get_data()['code'] ); + self::assertSame( 200, $public_response->get_status() ); + + wp_set_current_user( $this->factory()->user->create( [ 'role' => 'editor' ] ) ); + $edit_request = new WP_REST_Request( 'GET', '/wp/v2/posts/' . $post_id ); + $edit_request->set_query_params( [ 'context' => 'edit' ] ); + $edit_response = $server->dispatch( $edit_request ); + + self::assertSame( 200, $edit_response->get_status() ); + self::assertSame( 'Protected REST post marker.', $edit_response->get_data()['content']['raw'] ); + wp_set_current_user( 0 ); + + $collection = new WP_REST_Request( 'GET', '/wp/v2/posts' ); + $collection->set_query_params( [ '_fields' => 'content' ] ); + $collection_response = $server->dispatch( $collection ); + $page_collection_response = $server->dispatch( new WP_REST_Request( 'GET', '/wp/v2/pages' ) ); + + self::assertSame( 200, $collection_response->get_status() ); + self::assertStringNotContainsString( 'Protected REST post marker.', wp_json_encode( $collection_response->get_data() ) ); + self::assertSame( 200, $page_collection_response->get_status() ); + self::assertStringNotContainsString( 'Protected REST page marker.', wp_json_encode( $page_collection_response->get_data() ) ); + + $session_id = 'v1.' . str_repeat( 'a', 64 ); + $_COOKIE[ self::SESSION_COOKIE_NAME ] = $session_id; + $_COOKIE[ self::COOKIE_NAME ] = $this->create_clearance_cookie( str_repeat( 'b', 64 ), $session_id, $post_scope, time() + 300 ); + + $cleared_response = $server->dispatch( new WP_REST_Request( 'GET', '/wp/v2/posts/' . $post_id ) ); + $cleared_collection = $server->dispatch( new WP_REST_Request( 'GET', '/wp/v2/posts' ) ); + $other_scope_response = $server->dispatch( new WP_REST_Request( 'GET', '/wp/v2/pages/' . $page_id ) ); + + self::assertSame( 200, $cleared_response->get_status() ); + self::assertStringContainsString( 'Protected REST post marker.', $cleared_response->get_data()['content']['rendered'] ); + self::assertSame( 200, $cleared_collection->get_status() ); + self::assertStringContainsString( 'Protected REST post marker.', wp_json_encode( $cleared_collection->get_data() ) ); + self::assertSame( 403, $other_scope_response->get_status() ); + } finally { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restore the native REST registry. + $GLOBALS['wp_rest_server'] = $previous_server; + } + } + + /** + * REST search must not expose protected results or keyword match counts. + * + * @return void + */ + public function test_rest_search_excludes_uncleared_resources_before_pagination(): void { + $protected_post = $this->factory()->post->create( + [ + 'post_status' => 'publish', + 'post_title' => 'Restindexneedle hidden post', + 'post_content' => 'Restindexsecretword', + ] + ); + $protected_page = $this->factory()->post->create( + [ + 'post_type' => 'page', + 'post_status' => 'publish', + 'post_title' => 'Restindexneedle hidden page', + ] + ); + $public_post = $this->factory()->post->create( + [ + 'post_status' => 'publish', + 'post_title' => 'Restindexneedle public post', + ] + ); + $post_scope = get_permalink( $protected_post ); + $page_scope = get_permalink( $protected_page ); + + $this->configure_protected_urls( $post_scope . "\n" . $page_scope ); + $_SERVER['REQUEST_URI'] = '/wp-json/wp/v2/search'; + $subject = new ProtectContent(); + $subject->init(); + + $previous_server = $GLOBALS['wp_rest_server'] ?? null; + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Isolate the native REST registry. + $GLOBALS['wp_rest_server'] = null; + + try { + $server = rest_get_server(); + $search = new WP_REST_Request( 'GET', '/wp/v2/search' ); + $search->set_query_params( + [ + 'search' => 'Restindexneedle', + 'per_page' => 1, + '_fields' => 'title', + ] + ); + $response = $server->dispatch( $search ); + + self::assertSame( 200, $response->get_status() ); + self::assertCount( 1, $response->get_data() ); + self::assertSame( 'Restindexneedle public post', $response->get_data()[0]['title'] ); + self::assertSame( 1, $response->get_headers()['X-WP-Total'] ); + self::assertSame( 1, $response->get_headers()['X-WP-TotalPages'] ); + + $second_page = new WP_REST_Request( 'GET', '/wp/v2/search' ); + $second_page->set_query_params( + [ + 'search' => 'Restindexneedle', + 'per_page' => 1, + 'page' => 2, + ] + ); + $second_page_response = $server->dispatch( $second_page ); + + self::assertSame( 200, $second_page_response->get_status() ); + self::assertSame( [], $second_page_response->get_data() ); + self::assertSame( 0, $second_page_response->get_headers()['X-WP-Total'] ); + + $secret = new WP_REST_Request( 'GET', '/wp/v2/search' ); + $secret->set_query_params( [ 'search' => 'Restindexsecretword' ] ); + $secret_response = $server->dispatch( $secret ); + + self::assertSame( [], $secret_response->get_data() ); + self::assertSame( 0, $secret_response->get_headers()['X-WP-Total'] ); + + $post_collection = new WP_REST_Request( 'GET', '/wp/v2/posts' ); + $post_collection->set_query_params( + [ + 'search' => 'Restindexneedle', + '_fields' => 'id', + ] + ); + $post_collection_response = $server->dispatch( $post_collection ); + + self::assertSame( 200, $post_collection_response->get_status() ); + self::assertSame( [ [ 'id' => $public_post ] ], $post_collection_response->get_data() ); + self::assertSame( 1, $post_collection_response->get_headers()['X-WP-Total'] ); + + $post_collection->set_query_params( [ 'search' => 'Restindexsecretword' ] ); + $post_secret_response = $server->dispatch( $post_collection ); + + self::assertSame( [], $post_secret_response->get_data() ); + self::assertSame( 0, $post_secret_response->get_headers()['X-WP-Total'] ); + + $page_collection = new WP_REST_Request( 'GET', '/wp/v2/pages' ); + $page_collection->set_query_params( [ 'search' => 'Restindexneedle' ] ); + $page_collection_response = $server->dispatch( $page_collection ); + + self::assertSame( [], $page_collection_response->get_data() ); + self::assertSame( 0, $page_collection_response->get_headers()['X-WP-Total'] ); + + $slug_request = new WP_REST_Request( 'HEAD', '/wp/v2/posts' ); + $slug_request->set_query_params( [ 'slug' => get_post_field( 'post_name', $protected_post ) ] ); + $slug_response = $server->dispatch( $slug_request ); + + self::assertSame( 200, $slug_response->get_status() ); + self::assertSame( 0, $slug_response->get_headers()['X-WP-Total'] ); + + $include = new WP_REST_Request( 'GET', '/wp/v2/search' ); + $include->set_query_params( + [ + 'include' => [ $protected_post, $public_post ], + '_fields' => 'id', + ] + ); + $include_response = $server->dispatch( $include ); + + self::assertSame( [ [ 'id' => $public_post ] ], $include_response->get_data() ); + self::assertSame( 1, $include_response->get_headers()['X-WP-Total'] ); + + $include->set_query_params( [ 'include' => [ $protected_post ] ] ); + $hidden_include_response = $server->dispatch( $include ); + + self::assertSame( [], $hidden_include_response->get_data() ); + self::assertSame( 0, $hidden_include_response->get_headers()['X-WP-Total'] ); + + $page_search = new WP_REST_Request( 'HEAD', '/wp/v2/search' ); + $page_search->set_query_params( + [ + 'search' => 'Restindexneedle', + 'subtype' => 'page', + ] + ); + $page_response = $server->dispatch( $page_search ); + + self::assertSame( 0, $page_response->get_headers()['X-WP-Total'] ); + + $session_id = 'v1.' . str_repeat( 'a', 64 ); + $_COOKIE[ self::SESSION_COOKIE_NAME ] = $session_id; + $_COOKIE[ self::COOKIE_NAME ] = $this->create_clearance_cookie( str_repeat( 'b', 64 ), $session_id, $post_scope, time() + 300 ); + $cleared_response = $server->dispatch( $search ); + + self::assertSame( 2, $cleared_response->get_headers()['X-WP-Total'] ); + } finally { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restore the native REST registry. + $GLOBALS['wp_rest_server'] = $previous_server; + } + } + + /** + * Broad REST searches inspect every batch without rejecting the request. + * + * @return void + */ + public function test_rest_search_filters_candidates_beyond_first_batch(): void { + $protected_post = $this->factory()->post->create( [ 'post_status' => 'publish' ] ); + $public_post = $this->factory()->post->create( [ 'post_status' => 'publish' ] ); + $this->configure_protected_urls( get_permalink( $protected_post ) ); + $_SERVER['REQUEST_URI'] = '/wp-json/wp/v2/search'; + $subject = new ProtectContent(); + $subject->init(); + $request = new WP_REST_Request( 'GET', '/wp/v2/search' ); + $args = [ + 'post_type' => 'post', + 'post_status' => 'publish', + 'posts_per_page' => 10, + ]; + $offsets = []; + $pretend = static function ( $posts, WP_Query $query ) use ( &$offsets, $protected_post, $public_post ) { + if ( 'ids' === $query->get( 'fields' ) ) { + self::assertSame( 500, $query->get( 'posts_per_page' ) ); + $offset = (int) $query->get( 'offset' ); + $offsets[] = $offset; + + return 1000 === $offset ? [ $protected_post ] : array_fill( 0, 500, $public_post ); + } + + return $posts; + }; + + add_filter( 'posts_pre_query', $pretend, 10, 2 ); + + try { + $result = $subject->protect_rest_query( $args, $request ); + + self::assertSame( [ 0, 500, 1000 ], $offsets ); + self::assertSame( [ $protected_post ], $result['post__not_in'] ); + self::assertSame( 10, $result['posts_per_page'] ); + $response = new WP_REST_Response( [] ); + self::assertSame( $response, $subject->protect_rest_response( $response, [], $request ) ); + } finally { + remove_filter( 'posts_pre_query', $pretend ); + } + + $included = new WP_REST_Request( 'GET', '/wp/v2/search' ); + $included_ids = array_merge( array_fill( 0, 1000, $public_post ), [ $protected_post ] ); + $result = $subject->protect_rest_query( [ 'post__in' => $included_ids ], $included ); + + self::assertSame( array_fill( 0, 1000, $public_post ), array_values( $result['post__in'] ) ); + } + /** * Tear down. * @@ -71,7 +361,7 @@ public function test_init_and_init_hooks(): void { self::assertFalse( has_action( 'template_redirect', [ $subject, 'protect_content' ] ) ); - // The feature is activated, but the request uri is not in the list. + // The final WordPress route can be protected even when the raw URI is not. update_option( 'hcaptcha_settings', [ @@ -85,7 +375,7 @@ public function test_init_and_init_hooks(): void { $subject->init(); - self::assertFalse( has_action( 'template_redirect', [ $subject, 'protect_content' ] ) ); + self::assertSame( -PHP_INT_MAX, has_action( 'template_redirect', [ $subject, 'protect_content' ] ) ); // The request uri is in the list. update_option( @@ -148,6 +438,112 @@ public function test_init_and_init_hooks(): void { self::assertSame( -PHP_INT_MAX, has_action( 'template_redirect', [ $subject, 'protect_content' ] ) ); } + /** + * Configured expressions and literal URLs select the intended clearance scope. + * + * @dataProvider dp_test_init_matches_url_rules + * + * @param string $rules Rules separated by newlines. + * @param string $uri Request URI. + * @param string $scope Expected matching rule. + */ + public function test_init_matches_url_rules( string $rules, string $uri, string $scope ): void { + update_option( + 'hcaptcha_settings', + [ + 'protect_content' => [ 'on' ], + 'protected_urls' => $rules, + ] + ); + hcaptcha()->init_hooks(); + $_SERVER['REQUEST_URI'] = $uri; + $subject = new ProtectContent(); + $subject->init(); + + self::assertSame( $scope, $this->get_protected_property( $subject, 'resource_scope' ) ); + self::assertSame( -PHP_INT_MAX, has_action( 'template_redirect', [ $subject, 'protect_content' ] ) ); + } + + /** + * URL rules retain literal compatibility and regular expression semantics. + * + * @return array + */ + public function dp_test_init_matches_url_rules(): array { + $expression = '/private/(members|reports)/[0-9]+'; + $limited = '(*NO_AUTO_POSSESS)(*LIMIT_MATCH=10)https?://.*/(a+)+$'; + $preflight = '(*NO_START_OPT)(*LIMIT_MATCH=1)(?:/private/.*|(?:a?)*)'; + + return [ + 'wildcard' => [ '/private/.*', '/private/welcome', '/private/.*' ], + 'alternation' => [ $expression, '/private/reports/42', $expression ], + 'nonmatch' => [ $expression, '/public/welcome', '' ], + 'case variation' => [ '/private/.*', '/PRIVATE/welcome', '/private/.*' ], + 'encoded path' => [ '/private/.*', '/%70rivate/welcome', '/private/.*' ], + 'encoded literal' => [ '/private/%61ccount', '/private/%61ccount', '/private/%61ccount' ], + 'decoded literal' => [ '/private/%61ccount', '/private/account', '/private/%61ccount' ], + 'literal query' => [ '/private/file.php?download=1', '/private/file.php?download=1', '/private/file.php?download=1' ], + 'absolute URL' => [ home_url( '/private/.*' ), '/private/welcome', home_url( '/private/.*' ) ], + 'delimiter' => [ '/private/!.*', '/private/!welcome', '/private/!.*' ], + 'escaped delimiter' => [ '/private/\!.*', '/private/!welcome', '/private/\!.*' ], + 'delimiter choice' => [ '/private/[~#!%@;]+', '/private/~', '/private/[~#!%@;]+' ], + 'invalid literal' => [ '/private/[', '/private/[', '/private/[' ], + 'invalid nonmatch' => [ '/private/[', '/public/welcome', '' ], + 'longest scope' => [ "/private/.*\n/private/reports/[0-9]+", '/private/reports/42', '/private/reports/[0-9]+' ], + 'CRLF whitespace' => [ "\r\n /private/.* \r\n", '/private/welcome', '/private/.*' ], + 'empty list' => [ "\r\n \t", '/public/welcome', '/' ], + 'execution error' => [ $limited, '/' . str_repeat( 'a', 200 ) . 'X', $limited ], + 'preflight error' => [ $preflight, '/private/welcome', $preflight ], + ]; + } + + /** + * Named regex groups survive the actual settings sanitizer and textarea render. + * + * @throws ReflectionException ReflectionException. + */ + public function test_named_group_survives_settings_round_trip(): void { + $rule = '/private/(?[0-9]+)'; + $text = $rule . "\n"; + $settings = new Advanced(); + $value = $settings->sanitize_option_callback( + [ + 'protect_content' => [ 'on' ], + 'protected_urls' => $text, + ] + ); + + self::assertSame( $text, $value['protected_urls'] ); + update_option( 'hcaptcha_settings', $value ); + hcaptcha()->init_hooks(); + $settings = new Advanced(); + $method = $this->set_method_accessibility( $settings, 'print_textarea_field' ); + + ob_start(); + $method->invoke( + $settings, + [ + 'field_id' => 'protected_urls', + 'placeholder' => '', + 'disabled' => false, + 'preserve_text' => true, + ] + ); + $html = ob_get_clean(); + $method->setAccessible( false ); + + self::assertStringContainsString( esc_textarea( $text ), $html ); + self::assertStringNotContainsString( '', $html ); + self::assertStringNotContainsString( ''; + self::assertSame( $tag, $subject->add_type_module( $tag, 'other', 'paypal.js' ) ); + self::assertStringContainsString( 'type="module"', $subject->add_type_module( $tag, 'hcaptcha-woocommerce-paypal-payments', 'paypal.js' ) ); + ob_start(); + $subject->print_inline_styles(); + self::assertStringContainsString( '.hcaptcha-woocommerce-paypal-payments .h-captcha', ob_get_clean() ); + } + + /** + * Checkout requests use the shared verifier; disabled protection claims no request. + */ + public function test_verification_context_selection(): void { + $subject = new Button(); + hcaptcha()->settings()->set( 'paypal_payments_status', [] ); + hcaptcha()->settings()->set( 'woocommerce_status', [] ); + $method = $this->set_method_accessibility( $subject, 'get_verification_entry' ); + + self::assertSame( [], $method->invoke( $subject, [ 'context' => 'checkout' ] ) ); + ob_start(); + $subject->verify(); + self::assertSame( '', ob_get_clean() ); + + hcaptcha()->settings()->set( 'woocommerce_status', [ 'checkout' ] ); + self::assertSame( + [ + 'nonce' => Checkout::NONCE, + 'action' => Checkout::ACTION, + ], + $method->invoke( $subject, [ 'context' => 'checkout' ] ) + ); + } +} diff --git a/tests/php/integration/Wordfence/GeneralTest.php b/tests/php/integration/Wordfence/GeneralTest.php index a80e6ac4d..6c833a01c 100644 --- a/tests/php/integration/Wordfence/GeneralTest.php +++ b/tests/php/integration/Wordfence/GeneralTest.php @@ -9,6 +9,7 @@ /** @noinspection PhpLanguageLevelInspection */ /** @noinspection PhpUndefinedNamespaceInspection */ /** @noinspection PhpUndefinedClassInspection */ +/** @noinspection PhpUndefinedFunctionInspection */ // phpcs:enable Generic.Commenting.DocComment.MissingShort namespace HCaptcha\Tests\Integration\Wordfence; @@ -17,6 +18,7 @@ use HCaptcha\Tests\Integration\HCaptchaPluginWPTestCase; use HCaptcha\Wordfence\General; use HCaptcha\WP\Login; +use HCaptcha\WP\Register; use ReflectionClass; use ReflectionException; use tad\FunctionMocker\FunctionMocker; @@ -25,6 +27,8 @@ use WordfenceLS\Controller_WordfenceLS; use WordfenceLS\Model_View as WordfenceView; use WordfenceLS\ViewNotFoundException; +use WP_Error; +use function Patchwork\relay; /** * Test General class. @@ -32,6 +36,68 @@ * @group wordfence */ class GeneralTest extends HCaptchaPluginWPTestCase { + /** + * Register the admin notice when the installed Wordfence API exposes native hCaptcha settings. + */ + public function test_admin_script_with_native_hcaptcha_capability(): void { + FunctionMocker::replace( + 'defined', + static function ( string $name ): bool { + if ( 0 === strpos( $name, 'WordfenceLS\\Controller_' ) ) { + return true; + } + + return relay(); + } + ); + hcaptcha()->settings()->set( 'wordfence_status', [ 'login' ] ); + $subject = new General(); + + self::assertSame( 10, has_action( 'admin_enqueue_scripts', [ $subject, 'admin_enqueue_scripts' ] ) ); + $subject->admin_enqueue_scripts( 'other' ); + self::assertFalse( wp_script_is( 'admin-wordfence' ) ); + $subject->admin_enqueue_scripts( 'toplevel_page_WFLS' ); + self::assertTrue( wp_script_is( 'admin-wordfence' ) ); + self::assertStringContainsString( 'HCaptchaWordfenceObject', wp_scripts()->get_data( 'admin-wordfence', 'data' ) ); + } + + /** + * Wordfence enablement gates signed WordPress login protection. + */ + public function test_login_protection_filter_uses_wordfence_setting(): void { + $subject = new General(); + + self::assertFalse( $subject->filter_wp_login_protection_enabled( true ) ); + hcaptcha()->settings()->set( 'wordfence_status', [ 'login' ] ); + self::assertTrue( $subject->filter_wp_login_protection_enabled( true ) ); + self::assertFalse( $subject->filter_wp_login_protection_enabled( false ) ); + } + + /** + * An unsigned native registration still belongs to the active hCaptcha verifier. + */ + public function test_unsigned_native_registration_keeps_hcaptcha_owner(): void { + $subject = $this->enable_wordfence_integration( [ 'register' ] ); + $this->mark_native_registration_context(); + FunctionMocker::replace( + '\\HCaptcha\\Helpers\\HCaptcha::decode_id_info', + [ + 'valid' => false, + 'id' => [], + ] + ); + + self::assertTrue( $this->set_method_accessibility( $subject, 'is_native_registration_protected' )->invoke( $subject ) ); + } + + + /** + * HCaptcha modules loaded before each test. + * + * @var array + */ + private array $original_loaded_classes = []; + /** * Plugin relative path. * @@ -55,6 +121,7 @@ class GeneralTest extends HCaptchaPluginWPTestCase { */ public function setUp(): void { parent::setUp(); + $this->original_loaded_classes = $this->get_protected_property( hcaptcha(), 'loaded_classes' ); // Restore the live plugin hooks reset by WordPress test isolation. Controller_WordfenceLS::shared()->init(); @@ -76,8 +143,13 @@ public function tearDown(): void { wp_deregister_script( 'wordfence-ls-recaptcha' ); wp_dequeue_script( 'wordfence-ls-hcaptcha' ); wp_deregister_script( 'wordfence-ls-hcaptcha' ); + wp_dequeue_script( 'wordfence-ls-login' ); + wp_deregister_script( 'wordfence-ls-login' ); wp_dequeue_script( 'admin-wordfence' ); wp_deregister_script( 'admin-wordfence' ); + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + unset( $_GET['action'] ); + $this->set_protected_property( hcaptcha(), 'loaded_classes', $this->original_loaded_classes ); parent::tearDown(); } @@ -162,7 +234,8 @@ public function dp_test_init_hooks(): array { public function test_remove_wordfence_captcha_script( string $provider, string $script_handle ): void { $this->skip_unsupported_hcaptcha_provider( $provider ); $this->configure_wordfence_captcha( $provider ); - $this->enable_wordfence_integration(); + $this->enable_wordfence_integration( [ 'register' ] ); + $this->mark_native_registration_context(); $wordfence_enqueued_script = false; @@ -182,6 +255,45 @@ static function () use ( &$wordfence_enqueued_script, $script_handle ) { self::assertTrue( $wordfence_enqueued_script ); self::assertFalse( wp_script_is( $script_handle ) ); self::assertFalse( wp_script_is( $script_handle, 'registered' ) ); + self::assertFalse( wp_script_is( 'wordfence-ls-login' ) ); + self::assertFalse( wp_script_is( 'wordfence-ls-login', 'registered' ) ); + } + + /** + * Keep Wordfence CAPTCHA script when no hCaptcha verifier owns the page. + * + * @param string $action WordPress login action. + * @param string[] $wp_status Enabled native hCaptcha forms. + * @dataProvider dp_test_preserve_wordfence_captcha_script + */ + public function test_preserve_wordfence_captcha_script( string $action, array $wp_status ): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( $wp_status ); + + if ( 'register' === $action ) { + $this->mark_native_registration_context(); + } else { + $this->mark_native_login_context(); + } + + do_action( 'login_enqueue_scripts' ); + + self::assertTrue( wp_script_is( 'wordfence-ls-recaptcha' ) ); + self::assertTrue( wp_script_is( 'wordfence-ls-login' ) ); + self::assertStringContainsString( 'recaptchacompat=off', hcaptcha()->get_api_src() ); + } + + /** + * Data provider for native pages that remain owned by Wordfence. + * + * @return array + */ + public function dp_test_preserve_wordfence_captcha_script(): array { + return [ + 'login hCaptcha off' => [ 'login', [] ], + 'login hCaptcha on' => [ 'login', [ 'login' ] ], + 'registration hCaptcha off' => [ 'register', [ 'login' ] ], + ]; } /** @@ -210,10 +322,178 @@ public function test_block_wordfence_recaptcha( string $provider ): void { self::assertTrue( WordfenceCaptcha::shared()->is_captcha_required() ); - $subject = $this->enable_wordfence_integration(); + $subject = $this->enable_wordfence_integration( [ 'login' ] ); + $this->mark_native_login_context(); + + self::assertTrue( $subject->block_wordfence_recaptcha( true ) ); + self::assertFalse( $subject->block_wordfence_recaptcha( false ) ); + self::assertTrue( $this->wordfence_captcha_required_during_authentication() ); + } + + /** + * Wordfence must still verify login when its hCaptcha replacement is disabled. + */ + public function test_native_wordfence_login_without_hcaptcha_replacement(): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration(); + $this->mark_native_login_context(); + + self::assertTrue( $this->wordfence_captcha_required_during_authentication() ); + } + + /** + * Wordfence AJAX credential preflight must keep its CAPTCHA requirement. + */ + public function test_native_wordfence_login_preflight_with_hcaptcha_replacement(): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( [ 'login' ] ); + + self::assertTrue( $this->wordfence_captcha_required_during_authentication() ); + } + + /** + * Wordfence must still verify registration when its hCaptcha replacement is disabled. + * + * @param string[] $wp_status Enabled native hCaptcha forms. + * @param bool $native_context Whether this is the native WP registration action. + * @param bool $expected Whether Wordfence should require its own token. + * @dataProvider dp_test_native_wordfence_registration + */ + public function test_native_wordfence_registration( array $wp_status, bool $native_context, bool $expected ): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( $wp_status ); + + if ( $native_context ) { + $this->mark_native_registration_context(); + } else { + $_GET['action'] = 'register'; + } + + $errors = new WP_Error(); + + do_action( 'register_post', 'wordfence-user', 'wordfence@example.test', $errors ); + + self::assertSame( $expected, $errors->has_errors() ); + self::assertSame( $expected ? 'wfls_captcha_required' : '', $errors->get_error_code() ); + } + + /** + * Data provider for Wordfence registration coverage. + * + * @return array + */ + public function dp_test_native_wordfence_registration(): array { + return [ + 'no replacement' => [ [], true, true ], + 'login only' => [ [ 'login' ], true, true ], + 'registration enabled' => [ [ 'register' ], true, false ], + 'alternate route' => [ [ 'register' ], false, true ], + ]; + } + + /** + * An earlier registration error callback cannot skip the active hCaptcha verifier. + */ + public function test_registration_error_filter_keeps_hcaptcha_verifier(): void { + $this->enable_wordfence_integration( [ 'register' ] ); + $this->mark_native_registration_context(); + + add_filter( + 'registration_errors', + static function () { + return new WP_Error( 'earlier', 'Earlier registration error.' ); + }, + 1 + ); + + $errors = apply_filters( 'registration_errors', new WP_Error(), 'wordfence-user', 'wordfence@example.test' ); + + self::assertContains( 'earlier', $errors->get_error_codes() ); + self::assertContains( 'bad-signature', $errors->get_error_codes() ); + } + + /** + * Removing the replacement verifier restores the native Wordfence requirement. + */ + public function test_native_registration_without_active_hcaptcha_callback(): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( [ 'register' ] ); + $this->mark_native_registration_context(); + + $register = hcaptcha()->get( Register::class ); + remove_filter( 'registration_errors', [ $register, 'verify' ] ); + + $errors = new WP_Error(); + do_action( 'register_post', 'wordfence-user', 'wordfence@example.test', $errors ); + + self::assertSame( 'wfls_captcha_required', $errors->get_error_code() ); + } + + /** + * Keep Wordfence when another hCaptcha registration verifier owns the request. + */ + public function test_native_registration_with_foreign_hcaptcha_owner(): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( [ 'register' ] ); + $this->mark_native_registration_context(); + + FunctionMocker::replace( + '\\HCaptcha\\Helpers\\HCaptcha::decode_id_info', + [ + 'valid' => true, + 'id' => [ + 'source' => [ 'ForeignRegistration' ], + 'form_id' => 'register', + ], + ] + ); + add_filter( + 'hcap_registration_request_owner', + static function () { + return 'ForeignRegistration'; + }, + 1 + ); + + $errors = new WP_Error(); + do_action( 'register_post', 'wordfence-user', 'wordfence@example.test', $errors ); - self::assertFalse( $subject->block_wordfence_recaptcha() ); - self::assertFalse( WordfenceCaptcha::shared()->is_captcha_required() ); + self::assertSame( 'wfls_captcha_required', $errors->get_error_code() ); + + do_action( 'login_enqueue_scripts' ); + + self::assertTrue( wp_script_is( 'wordfence-ls-recaptcha' ) ); + self::assertTrue( wp_script_is( 'wordfence-ls-login' ) ); + } + + /** + * The native registration verifier owns its signed widget request. + */ + public function test_native_registration_with_own_hcaptcha_widget(): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( [ 'register' ] ); + $this->mark_native_registration_context(); + + FunctionMocker::replace( + '\\HCaptcha\\Helpers\\HCaptcha::decode_id_info', + [ + 'valid' => true, + 'id' => [ + 'source' => HCaptcha::get_class_source( Register::class ), + 'form_id' => 'register', + ], + ] + ); + + $errors = new WP_Error(); + do_action( 'register_post', 'wordfence-user', 'wordfence@example.test', $errors ); + + self::assertFalse( $errors->has_errors() ); + + $errors = apply_filters( 'registration_errors', $errors, 'wordfence-user', 'wordfence@example.test' ); + + self::assertTrue( $errors->has_errors() ); + self::assertNotContains( 'wfls_captcha_required', $errors->get_error_codes() ); } /** @@ -260,7 +540,6 @@ public function test_admin_enqueue_scripts( string $hook_suffix ): void { self::assertTrue( wp_script_is( 'admin-wordfence' ) ); $script = wp_scripts()->registered['admin-wordfence']; - $notice = HCaptcha::get_hcaptcha_plugin_notice(); $data = wp_scripts()->get_data( 'admin-wordfence', 'data' ); $prefix = 'var HCaptchaWordfenceObject = '; $json = substr( $data, strlen( $prefix ), -1 ); @@ -270,8 +549,8 @@ public function test_admin_enqueue_scripts( string $hook_suffix ): void { self::assertStringStartsWith( $prefix, $data ); self::assertSame( [ - 'noticeLabel' => $notice['label'], - 'noticeDescription' => html_entity_decode( $notice['description'], ENT_QUOTES, 'UTF-8' ), + 'noticeLabel' => 'hCaptcha integration is active', + 'noticeDescription' => 'Wordfence CAPTCHA settings still apply to forms without hCaptcha protection.', ], json_decode( $json, true ) ); @@ -290,17 +569,15 @@ public function dp_test_admin_enqueue_scripts(): array { } /** - * Test the real Wordfence authentication path with native CAPTCHA blocked. - * - * @param string $provider CAPTCHA provider. + * Test that Wordfence verifies a native login when hCaptcha login is enabled. * * @return void - * @dataProvider dp_test_captcha_provider */ - public function test_live_wordfence_authentication( string $provider ): void { - $this->skip_unsupported_hcaptcha_provider( $provider ); - $this->configure_wordfence_captcha( $provider ); - $this->enable_wordfence_integration(); + public function test_live_wordfence_authentication(): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( [ 'login' ] ); + $this->mark_native_login_context(); + $_POST['wfls-captcha-token'] = 'wordfence-test-token'; $user_id = $this->factory()->user->create( [ @@ -313,21 +590,43 @@ public function test_live_wordfence_authentication( string $provider ): void { add_filter( 'pre_http_request', - static function ( $response ) use ( &$requests ) { + static function () use ( &$requests ) { ++$requests; - return $response; + return [ + 'headers' => [], + 'body' => '{"success":true,"score":0.9,"action":"login"}', + 'response' => [ + 'code' => 200, + 'message' => 'OK', + ], + ]; } ); - $result = Controller_WordfenceLS::shared()->_authenticate( + $result = apply_filters( + 'authenticate', $user, 'wordfence-user', 'wordfence-password' ); self::assertSame( $user, $result ); - self::assertSame( 0, $requests ); + self::assertSame( 1, $requests ); + } + + /** + * A login attempt without Wordfence token must not proceed to authentication. + */ + public function test_live_wordfence_authentication_without_token(): void { + $this->configure_wordfence_captcha( 'recaptcha' ); + $this->enable_wordfence_integration( [ 'login' ] ); + $this->mark_native_login_context(); + + $result = apply_filters( 'authenticate', null, 'nonexistent-wordfence-user', 'invalid-password' ); + + self::assertInstanceOf( WP_Error::class, $result ); + self::assertSame( 'wfls_captcha_verify', $result->get_error_code() ); } /** @@ -437,21 +736,85 @@ private function configure_wordfence_captcha( string $provider ): void { /** * Enable the hCaptcha integration for Wordfence. * + * @param string[] $wp_status Enabled native hCaptcha forms. + * * @return General */ - private function enable_wordfence_integration(): General { + private function enable_wordfence_integration( array $wp_status = [] ): General { update_option( 'hcaptcha_settings', [ 'wordfence_status' => [ 'login' ], + 'wp_status' => $wp_status, ] ); hcaptcha()->init_hooks(); + $loaded_classes = $this->get_protected_property( hcaptcha(), 'loaded_classes' ); + + foreach ( + [ + 'login' => Login::class, + 'register' => Register::class, + ] as $setting => $class_name + ) { + if ( in_array( $setting, $wp_status, true ) ) { + $loaded_classes[ $class_name ] = new $class_name(); + } else { + unset( $loaded_classes[ $class_name ] ); + } + } + + $this->set_protected_property( hcaptcha(), 'loaded_classes', $loaded_classes ); return new General(); } + /** + * Mark the native WordPress login action as dispatched by wp-login.php. + */ + private function mark_native_login_context(): void { + // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited + $GLOBALS['wp_actions']['login_init'] = 1; + $GLOBALS['wp_actions']['login_form_login'] = 1; + $GLOBALS['wp_filters']['login_link_separator'] = 1; + // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited + } + + /** + * Mark the native WordPress registration action as dispatched by wp-login.php. + */ + private function mark_native_registration_context(): void { + $_SERVER['REQUEST_URI'] = '/wp-login.php?action=register'; + $_GET['action'] = 'register'; + + // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited + $GLOBALS['wp_actions']['login_init'] = 1; + $GLOBALS['wp_actions']['login_form_register'] = 1; + $GLOBALS['wp_filters']['login_link_separator'] = 1; + // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited + } + + /** + * Read the actual Wordfence requirement from its authentication filter chain. + * + * @return bool + */ + private function wordfence_captcha_required_during_authentication(): bool { + $required = false; + $check = static function ( $user ) use ( &$required ) { + $required = WordfenceCaptcha::shared()->is_captcha_required(); + + return $user; + }; + + add_filter( 'authenticate', $check, 0 ); + apply_filters( 'authenticate', null, '', '' ); + remove_filter( 'authenticate', $check, 0 ); + + return $required; + } + /** * Get Wordfence CAPTCHA setting keys used by the tests. * diff --git a/tests/php/multisite.suite.yml b/tests/php/multisite.suite.yml index 74399bcf1..651b177c0 100644 --- a/tests/php/multisite.suite.yml +++ b/tests/php/multisite.suite.yml @@ -1,4 +1,8 @@ bootstrap: ./_bootstrap.php +coverage: + include: + - ./src/php/* + - ./hcaptcha.php modules: enabled: - WPLoader diff --git a/tests/php/multisite/Settings/NetworkSettingsAuthorizationTest.php b/tests/php/multisite/Settings/NetworkSettingsAuthorizationTest.php index 3e5527ec2..6c82d5e9e 100644 --- a/tests/php/multisite/Settings/NetworkSettingsAuthorizationTest.php +++ b/tests/php/multisite/Settings/NetworkSettingsAuthorizationTest.php @@ -7,6 +7,7 @@ namespace HCaptcha\Tests\Integration\Settings; +use Exception; use HCaptcha\Abilities\Abilities; use HCaptcha\Admin\OnboardingWizard; use HCaptcha\Helpers\Request; @@ -17,7 +18,6 @@ use KAGG\Settings\Abstracts\SettingsBase; use lucatume\WPBrowser\TestCase\WPAjaxTestCase; use ReflectionClass; -use WPAjaxDieContinueException; /** * Test network settings authorization against real WordPress multisite capabilities. @@ -141,8 +141,8 @@ public function test_main_site_administrator_cannot_render_or_export_network_set * Test that a secondary-site administrator receives no broader network access. */ public function test_secondary_site_administrator_cannot_render_or_export_network_settings(): void { - $blog_id = self::factory()->blog->create(); - $user_id = self::factory()->user->create( [ 'role' => 'subscriber' ] ); + $blog_id = $this->factory()->blog->create(); + $user_id = $this->factory()->user->create( [ 'role' => 'subscriber' ] ); $added = add_user_to_blog( $blog_id, $user_id, 'administrator' ); self::assertTrue( $added ); @@ -246,6 +246,9 @@ public function test_blank_sensitive_field_preserves_network_secret(): void { /** * Test that onboarding cannot copy network credentials into site-local settings. + * + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection JsonEncodingApiUsageInspection */ public function test_onboarding_cannot_copy_network_settings_to_site_option(): void { $this->create_main_site_administrator(); @@ -272,7 +275,7 @@ public function test_onboarding_cannot_copy_network_settings_to_site_option(): v try { $this->_handleAjax( OnboardingWizard::UPDATE_ACTION ); - } catch ( WPAjaxDieContinueException $exception ) { + } catch ( Exception $exception ) { $did_die = true; } @@ -400,6 +403,56 @@ public function test_indirect_updates_preserve_network_ownership(): void { self::assertSame( [ 'on' ], get_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE ) ); } + /** + * Native option writes cannot downgrade ownership or copy credentials for an unauthorized caller. + * + * @dataProvider dp_test_native_updates_preserve_network_ownership + * + * @param bool $site_administrator Whether the caller is a blog administrator. + */ + public function test_native_updates_preserve_network_ownership( bool $site_administrator ): void { + if ( $site_administrator ) { + $this->create_main_site_administrator(); + } else { + wp_set_current_user( 0 ); + } + + $this->activate_network_settings(); + $network_settings = get_site_option( PluginSettingsBase::OPTION_NAME ); + $site_settings = get_option( PluginSettingsBase::OPTION_NAME ); + add_filter( 'pre_update_option_' . PluginSettingsBase::OPTION_NAME, [ $this->general, 'pre_update_option_filter' ], 10, 2 ); + add_filter( 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME, [ $this->general, 'pre_update_option_filter' ], 10, 2 ); + + foreach ( [ [], [ SettingsBase::NETWORK_WIDE => [] ], [ SettingsBase::NETWORK_WIDE => [ 'on' ] ] ] as $flags ) { + $value = array_merge( + [ + 'license' => 'free', + 'theme' => 'dark', + 'secret_key' => '', + ], + $flags + ); + update_option( PluginSettingsBase::OPTION_NAME, $value ); + update_site_option( PluginSettingsBase::OPTION_NAME, $value ); + + self::assertSame( [ 'on' ], get_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE ) ); + self::assertSame( $site_settings, get_option( PluginSettingsBase::OPTION_NAME ) ); + self::assertSame( $network_settings, get_site_option( PluginSettingsBase::OPTION_NAME ) ); + } + } + + /** + * Both unauthenticated requests and blog administrators lack network authority. + * + * @return array + */ + public function dp_test_native_updates_preserve_network_ownership(): array { + return [ + 'anonymous' => [ false ], + 'site administrator' => [ true ], + ]; + } + /** * Test that blank credentials keep their active value when settings ownership changes. * @@ -471,7 +524,7 @@ private function create_main_site_administrator(): int { self::assertSame( get_main_site_id(), get_current_blog_id() ); - $user_id = self::factory()->user->create( [ 'role' => 'administrator' ] ); + $user_id = $this->factory()->user->create( [ 'role' => 'administrator' ] ); wp_set_current_user( $user_id ); @@ -485,9 +538,10 @@ private function create_main_site_administrator(): int { * Create and select a network administrator. * * @return int + * @noinspection PhpReturnValueOfMethodIsNeverUsedInspection */ private function create_network_administrator(): int { - $user_id = self::factory()->user->create( [ 'role' => 'administrator' ] ); + $user_id = $this->factory()->user->create( [ 'role' => 'administrator' ] ); grant_super_admin( $user_id ); $this->super_admins[] = $user_id; @@ -538,7 +592,7 @@ private function assert_tab_access_denied( PluginSettingsBase $tab ): void { $not_ajax_filter = static function (): bool { return false; }; - $die_filter = static function ( $handler ) use ( &$die_message ): callable { + $die_filter = static function () use ( &$die_message ): callable { return static function ( $message ) use ( &$die_message ): void { $die_message = (string) $message; }; @@ -594,7 +648,7 @@ private function assert_import_access_denied(): void { $result = ( new SettingsTransfer() )->apply_import_payload( $payload, true ); - self::assertWPError( $result ); + $this->assertWPError( $result ); self::assertSame( 'hcaptcha_network_settings_forbidden', $result->get_error_code() ); self::assertSame( $network_settings, get_site_option( PluginSettingsBase::OPTION_NAME ) ); self::assertSame( [ 'on' ], get_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE ) ); @@ -640,6 +694,8 @@ private function export_settings( string $nonce, bool $include_keys ): array { * @param bool $include_keys Whether keys should be included. * * @return array{0: array, 1: string} + * @noinspection PhpArrayWriteIsNotUsedInspection + * @noinspection JsonEncodingApiUsageInspection */ private function export_settings_with_raw_response( string $nonce, bool $include_keys ): array { $_POST = [ @@ -652,7 +708,7 @@ private function export_settings_with_raw_response( string $nonce, bool $include try { $this->_handleAjax( Tools::EXPORT_ACTION ); - } catch ( WPAjaxDieContinueException $exception ) { + } catch ( Exception $exception ) { $did_die = true; } diff --git a/tests/php/multisite/Settings/SettingsStorageTest.php b/tests/php/multisite/Settings/SettingsStorageTest.php new file mode 100644 index 000000000..9e3987fcb --- /dev/null +++ b/tests/php/multisite/Settings/SettingsStorageTest.php @@ -0,0 +1,585 @@ + + */ + private array $option_hooks = []; + + /** + * Cached General settings present before the test. + * + * @var array + */ + private array $general_settings = []; + + /** + * Users temporarily granted network authority. + * + * @var int[] + */ + private array $super_admins = []; + + /** + * Setup test. + */ + public function setUp(): void { + global $wp_filter; + + parent::setUp(); + + self::assertTrue( is_multisite() ); + self::assertFalse( Request::is_cli(), 'Anonymous guard tests require a non-CLI process.' ); + + $settings = hcaptcha()->settings(); + + self::assertNotNull( $settings ); + + $this->general = $settings->get_tab( General::class ); + + self::assertInstanceOf( General::class, $this->general ); + + $property = new ReflectionProperty( SettingsBase::class, 'settings' ); + $property->setAccessible( true ); + $this->general_settings = $property->getValue( $this->general ); + + foreach ( $this->option_hook_names() as $hook ) { + $this->option_hooks[ $hook ] = isset( $wp_filter[ $hook ] ) ? clone $wp_filter[ $hook ] : null; + } + + wp_set_current_user( 0 ); + + self::assertSame( 0, get_current_user_id() ); + self::assertFalse( current_user_can( 'manage_network_options' ) ); + + $this->seed_settings( $this->local_settings(), $this->network_settings() ); + } + + /** + * Tear down test. + */ + public function tearDown(): void { + global $wp_filter; + + while ( ms_is_switched() ) { + restore_current_blog(); + } + + foreach ( $this->super_admins as $user_id ) { + revoke_super_admin( $user_id ); + } + + delete_option( PluginSettingsBase::OPTION_NAME ); + delete_site_option( PluginSettingsBase::OPTION_NAME ); + delete_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE ); + wp_set_current_user( 0 ); + + if ( $this->general ) { + $property = new ReflectionProperty( SettingsBase::class, 'settings' ); + $property->setAccessible( true ); + $property->setValue( $this->general, $this->general_settings ); + } + + foreach ( $this->option_hooks as $hook => $callbacks ) { + if ( null === $callbacks ) { + unset( $wp_filter[ $hook ] ); + } else { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restore the test hook fixture. + $wp_filter[ $hook ] = $callbacks; + } + } + + parent::tearDown(); + } + + /** + * Anonymous license checks change only the license in the active network scope. + * + * @param string $stored_license Previously stored network license. + * @param string $expected_license Expected network license. + * + * @dataProvider dp_test_anonymous_license_maintenance + */ + public function test_anonymous_license_maintenance( string $stored_license, string $expected_license ): void { + $local = $this->local_settings(); + $network = $this->network_settings(); + $network['license'] = $stored_license; + + $this->seed_settings( $local, $network ); + + $request_url = ''; + $request_count = 0; + $response = static function ( $preempt, array $arguments, string $url ) use ( &$request_url, &$request_count ): array { + $request_url = $url; + ++$request_count; + + return [ + 'body' => wp_json_encode( + [ + 'pass' => true, + 'features' => [ 'custom_theme' => true ], + ] + ), + 'response' => [ 'code' => 200 ], + ]; + }; + + add_filter( 'pre_http_request', $response, PHP_INT_MAX, 3 ); + + try { + HCaptcha::save_license_level(); + } finally { + remove_filter( 'pre_http_request', $response, PHP_INT_MAX ); + } + + $network['license'] = $expected_license; + $query = []; + + wp_parse_str( (string) wp_parse_url( $request_url, PHP_URL_QUERY ), $query ); + + self::assertSame( 1, $request_count ); + self::assertSame( $network['site_key'], $query['sitekey'] ?? null ); + self::assertSame( General::MODE_TEST_ENTERPRISE_SAFE_END_USER, hcaptcha()->settings()->get_mode() ); + $this->assert_storage( $local, $network ); + } + + /** + * An existing network Enterprise license survives a local Free license. + * + * @return array + */ + public function dp_test_anonymous_license_maintenance(): array { + return [ + 'network license promoted' => [ 'free', 'pro' ], + 'network Enterprise retained' => [ 'enterprise', 'enterprise' ], + ]; + } + + /** + * Explicit local maintenance cannot change network ownership or unrelated fields. + */ + public function test_explicit_local_maintenance_preserves_network_scope(): void { + $local = $this->local_settings(); + $network = $this->network_settings(); + + self::assertTrue( + SettingsStorage::update( + [ + 'license' => 'pro', + SettingsBase::NETWORK_WIDE => [ 'on' ], + ], + [ 'obsolete_marker', SettingsBase::NETWORK_WIDE ], + false + ) + ); + + $local['license'] = 'pro'; + unset( $local['obsolete_marker'] ); + + $this->assert_storage( $local, $network ); + } + + /** + * Posted form keys cannot acknowledge network review notices during maintenance or a rejected save. + */ + public function test_form_only_notice_acknowledgement_requires_authority(): void { + $local = $this->local_settings(); + $network = $this->network_settings(); + $network[ Migrations::REVIEW_TRUSTED_ADDRESS_HEADERS_OPTION ] = 'on'; + $network['trusted_address_headers'] = []; + $this->seed_settings( $local, $network ); + $anti_spam = hcaptcha()->settings()->get_tab( AntiSpamPage::class ); + $hook = 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME; + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Preserve deliberately unauthorized form data for this regression. + $post = $_POST; + + self::assertInstanceOf( AntiSpamPage::class, $anti_spam ); + add_filter( $hook, [ $anti_spam, 'clear_trusted_address_headers_review_notice' ], 30, 2 ); + $_POST[ PluginSettingsBase::OPTION_NAME ] = [ 'trusted_address_headers' => [] ]; + + try { + self::assertTrue( SettingsStorage::update( [ 'license' => 'pro' ] ) ); + $network['license'] = 'pro'; + $this->assert_storage( $local, $network ); + self::assertFalse( update_site_option( PluginSettingsBase::OPTION_NAME, [ 'license' => 'free' ] ) ); + $this->assert_storage( $local, $network ); + + $method = new ReflectionMethod( AntiSpamPage::class, 'save_cloudflare_detection_status' ); + $method->setAccessible( true ); + $status = [ + 'status' => 'detected', + 'confidence' => 'high', + 'checked_at' => 123, + ]; + $method->invoke( $anti_spam, $status ); + $network[ AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION ] = $status; + $this->assert_storage( $local, $network ); + + $user_id = $this->factory()->user->create( [ 'role' => 'administrator' ] ); + grant_super_admin( $user_id ); + $this->super_admins[] = $user_id; + wp_set_current_user( $user_id ); + self::assertTrue( update_site_option( PluginSettingsBase::OPTION_NAME, $network ) ); + $saved = get_site_option( PluginSettingsBase::OPTION_NAME ); + self::assertArrayNotHasKey( Migrations::REVIEW_TRUSTED_ADDRESS_HEADERS_OPTION, $saved ); + self::assertSame( $status, $saved[ AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION ] ); + self::assertSame( [ 'on' ], get_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE ) ); + } finally { + $_POST = $post; + remove_filter( $hook, [ $anti_spam, 'clear_trusted_address_headers_review_notice' ], 30 ); + } + } + + /** + * Events markers follow each blog rather than the active network settings. + */ + public function test_events_markers_belong_to_distinct_blogs(): void { + $local = $this->local_settings(); + $network = $this->network_settings(); + $blog_id = $this->factory()->blog->create(); + $mark = new ReflectionMethod( Events::class, 'mark_table_created' ); + $unmark = new ReflectionMethod( Events::class, 'unmark_table_created' ); + + $mark->setAccessible( true ); + $unmark->setAccessible( true ); + + self::assertFalse( Events::table_exists() ); + + $mark->invoke( null ); + $local[ Events::TABLE_CREATED_OPTION_NAME ] = 'on'; + + self::assertTrue( Events::table_exists() ); + $this->assert_storage( $local, $network ); + + $secondary = $this->local_settings(); + $secondary['site_key'] = 'secondary-site-key'; + $secondary['secret_key'] = 'secondary-secret-key'; + $secondary['local_only'] = 'secondary-only'; + + switch_to_blog( $blog_id ); + + try { + delete_option( PluginSettingsBase::OPTION_NAME ); + self::assertTrue( add_option( PluginSettingsBase::OPTION_NAME, $secondary ) ); + self::assertFalse( Events::table_exists() ); + + $mark->invoke( null ); + $secondary[ Events::TABLE_CREATED_OPTION_NAME ] = 'on'; + + self::assertTrue( Events::table_exists() ); + $this->assert_storage( $secondary, $network ); + } finally { + restore_current_blog(); + } + + $unmark->invoke( null ); + unset( $local[ Events::TABLE_CREATED_OPTION_NAME ] ); + + self::assertFalse( Events::table_exists() ); + $this->assert_storage( $local, $network ); + + switch_to_blog( $blog_id ); + + try { + self::assertTrue( Events::table_exists() ); + $this->assert_storage( $secondary, $network ); + + $unmark->invoke( null ); + unset( $secondary[ Events::TABLE_CREATED_OPTION_NAME ] ); + + self::assertFalse( Events::table_exists() ); + $this->assert_storage( $secondary, $network ); + } finally { + restore_current_blog(); + } + } + + /** + * A thrown native option hook cannot leave maintenance authorization behind. + * + * @noinspection PhpConditionAlreadyCheckedInspection + */ + public function test_maintenance_authorization_expires_after_a_thrown_hook(): void { + global $wp_filter, $wp_current_filter; + + $local = $this->local_settings(); + $network = $this->network_settings(); + $value = array_merge( $network, [ 'license' => 'pro' ] ); + $hook = 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME; + $guard = clone $wp_filter[ $hook ]; + $current_filter = $wp_current_filter; + $throw = static function (): void { + throw new RuntimeException( 'Interrupted maintenance write.' ); + }; + + add_filter( $hook, $throw, self::GUARD_PRIORITY + 1 ); + + try { + SettingsStorage::update( [ 'license' => 'pro' ] ); + self::fail( 'The native option hook must interrupt this write.' ); + } catch ( RuntimeException $exception ) { + self::assertSame( 'Interrupted maintenance write.', $exception->getMessage() ); + } finally { + // WordPress does not unwind its hook execution state when a callback throws. + // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited + $wp_filter[ $hook ] = $guard; + $wp_current_filter = $current_filter; + // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited + } + + self::assertFalse( update_site_option( PluginSettingsBase::OPTION_NAME, $value ) ); + self::assertFalse( update_option( PluginSettingsBase::OPTION_NAME, $value ) ); + $this->assert_storage( $local, $network ); + + self::assertTrue( SettingsStorage::update( [ 'license' => 'pro' ] ) ); + $network['license'] = 'pro'; + + $this->assert_storage( $local, $network ); + } + + /** + * A maintenance hook cannot lend its authorization to a different native write. + */ + public function test_reentrant_native_writes_require_the_exact_maintenance_value(): void { + $local = $this->local_settings(); + $network = $this->network_settings(); + $attack = array_merge( + $network, + [ + 'secret_key' => 'reentrant-secret', + SettingsBase::NETWORK_WIDE => [], + ] + ); + $entered = false; + $results = []; + $hook = 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME; + $reentrant = static function ( $value ) use ( &$entered, &$results, $attack ) { + if ( ! $entered ) { + $entered = true; + $results[] = update_site_option( PluginSettingsBase::OPTION_NAME, $attack ); + $results[] = update_option( PluginSettingsBase::OPTION_NAME, $attack ); + } + + return $value; + }; + + add_filter( $hook, $reentrant, self::GUARD_PRIORITY - 1 ); + + try { + self::assertTrue( SettingsStorage::update( [ 'license' => 'pro' ] ) ); + } finally { + remove_filter( $hook, $reentrant, self::GUARD_PRIORITY - 1 ); + } + + $network['license'] = 'pro'; + + self::assertSame( [ false, false ], $results ); + $this->assert_storage( $local, $network ); + } + + /** + * A normal authorized network save restores the guard for later anonymous writes. + */ + public function test_authorized_network_save_restores_the_native_guard(): void { + $local = $this->local_settings(); + $network = $this->network_settings(); + $user_id = $this->factory()->user->create( [ 'role' => 'administrator' ] ); + $hook = 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME; + + grant_super_admin( $user_id ); + $this->super_admins[] = $user_id; + wp_set_current_user( $user_id ); + + self::assertTrue( current_user_can( 'manage_network_options' ) ); + self::assertSame( self::GUARD_PRIORITY, has_filter( $hook, [ $this->general, 'pre_update_option_filter' ] ) ); + self::assertFalse( update_option( PluginSettingsBase::OPTION_NAME, array_merge( $network, [ 'theme' => 'dark' ] ) ) ); + + $saved = get_site_option( PluginSettingsBase::OPTION_NAME, [] ); + + self::assertSame( 'dark', $saved['theme'] ?? null ); + self::assertSame( $network['secret_key'], $saved['secret_key'] ?? null ); + self::assertSame( $network['custom_themes'], $saved['custom_themes'] ?? null ); + self::assertSame( self::GUARD_PRIORITY, has_filter( $hook, [ $this->general, 'pre_update_option_filter' ] ) ); + $this->assert_storage( $local, $saved ); + + wp_set_current_user( 0 ); + self::assertFalse( current_user_can( 'manage_network_options' ) ); + + $attack = array_merge( + $saved, + [ + 'secret_key' => 'guest-secret', + SettingsBase::NETWORK_WIDE => [], + ] + ); + + self::assertFalse( update_site_option( PluginSettingsBase::OPTION_NAME, $attack ) ); + self::assertFalse( update_option( PluginSettingsBase::OPTION_NAME, $attack ) ); + $this->assert_storage( $local, $saved ); + } + + /** + * Storage can maintain both scopes before Main initializes its Settings instance. + */ + public function test_storage_does_not_depend_on_main_settings(): void { + $local = $this->local_settings(); + $network = $this->network_settings(); + $main = hcaptcha(); + $property = new ReflectionProperty( Main::class, 'settings' ); + + $property->setAccessible( true ); + $settings = $property->getValue( $main ); + $property->setValue( $main, null ); + + try { + self::assertNull( $main->settings() ); + self::assertTrue( SettingsStorage::is_network_wide() ); + self::assertSame( $network, SettingsStorage::get() ); + self::assertSame( $local, SettingsStorage::get( false ) ); + self::assertTrue( SettingsStorage::update( [ 'license' => 'pro' ] ) ); + self::assertTrue( SettingsStorage::update( [ Events::TABLE_CREATED_OPTION_NAME => 'on' ], [], false ) ); + + $network['license'] = 'pro'; + $local[ Events::TABLE_CREATED_OPTION_NAME ] = 'on'; + + $this->assert_storage( $local, $network ); + } finally { + $property->setValue( $main, $settings ); + } + } + + /** + * The local fixture contains unrelated credentials, checkboxes, and maintenance data. + * + * @return array + */ + private function local_settings(): array { + return [ + 'site_key' => 'local-site-key', + 'secret_key' => 'local-secret-key', + 'license' => 'free', + 'mode' => General::MODE_LIVE, + 'theme' => 'light', + 'custom_themes' => [ 'on' ], + 'wp_status' => [ 'login', 'register' ], + 'local_only' => 'keep-local', + 'obsolete_marker' => 'remove-local', + SettingsBase::NETWORK_WIDE => [], + ]; + } + + /** + * The network fixture has different credentials and a misleading network Events marker. + * + * @return array + */ + private function network_settings(): array { + return [ + 'site_key' => 'network-site-key', + 'secret_key' => 'network-secret-key', + 'license' => 'free', + 'mode' => General::MODE_TEST_ENTERPRISE_SAFE_END_USER, + 'theme' => 'light', + 'custom_themes' => [ 'on' ], + 'wp_status' => [ 'login' ], + 'network_only' => 'keep-network', + Events::TABLE_CREATED_OPTION_NAME => 'on', + SettingsBase::NETWORK_WIDE => [ 'on' ], + ]; + } + + /** + * Seed exact options, then attach the real General guard to native WordPress hooks. + * + * @param array $local Local settings. + * @param array $network Network settings. + */ + private function seed_settings( array $local, array $network ): void { + foreach ( $this->option_hook_names() as $hook ) { + remove_all_filters( $hook ); + } + + delete_option( PluginSettingsBase::OPTION_NAME ); + delete_site_option( PluginSettingsBase::OPTION_NAME ); + delete_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE ); + + self::assertTrue( add_option( PluginSettingsBase::OPTION_NAME, $local ) ); + self::assertTrue( add_site_option( PluginSettingsBase::OPTION_NAME, $network ) ); + self::assertTrue( add_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE, [ 'on' ] ) ); + + $init = new ReflectionMethod( SettingsBase::class, 'init_settings' ); + $init->setAccessible( true ); + $init->invoke( $this->general ); + + foreach ( $this->option_hook_names() as $hook ) { + add_filter( $hook, [ $this->general, 'pre_update_option_filter' ], self::GUARD_PRIORITY, 2 ); + } + + $this->assert_storage( $local, $network ); + } + + /** + * Assert exact stored values and unchanged standalone network ownership. + * + * @param array $local Expected local settings. + * @param array $network Expected network settings. + */ + private function assert_storage( array $local, array $network ): void { + self::assertSame( $local, get_option( PluginSettingsBase::OPTION_NAME, [] ) ); + self::assertSame( $network, get_site_option( PluginSettingsBase::OPTION_NAME, [] ) ); + self::assertSame( [ 'on' ], get_site_option( PluginSettingsBase::OPTION_NAME . SettingsBase::NETWORK_WIDE, [] ) ); + } + + /** + * Native option hooks exercised by these tests. + * + * @return string[] + */ + private function option_hook_names(): array { + return [ + 'pre_update_option_' . PluginSettingsBase::OPTION_NAME, + 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME, + ]; + } +} diff --git a/tests/php/unit.suite.yml b/tests/php/unit.suite.yml index 71c37d796..4ba87dddf 100644 --- a/tests/php/unit.suite.yml +++ b/tests/php/unit.suite.yml @@ -1 +1,63 @@ bootstrap: ./_bootstrap.php +# Keep unit coverage limited to source files with dedicated unit tests. +coverage: + include: + - ./src/php/Admin/CommandPalette.php + - ./src/php/AntiSpam/AntiSpam.php + - ./src/php/AntiSpam/DisposableEmail.php + - ./src/php/AntiSpam/Honeypot.php + - ./src/php/AntiSpam/ProviderBase.php + - ./src/php/AutoVerify/AutoVerify.php + - ./src/php/Dependencies/PluginDependencyManager.php + - ./src/php/Helpers/Request.php + - ./src/php/Helpers/Utils.php + - ./src/php/includes/functions.php + - ./src/php/MigrationWizard/Detectors/AbstractDetector.php + - ./src/php/MigrationWizard/Detectors/ACFEDetector.php + - ./src/php/MigrationWizard/Detectors/AdvancedGoogleRecaptchaDetector.php + - ./src/php/MigrationWizard/Detectors/AdvancedNoCaptchaDetector.php + - ./src/php/MigrationWizard/Detectors/BeaverBuilderDetector.php + - ./src/php/MigrationWizard/Detectors/BrevoDetector.php + - ./src/php/MigrationWizard/Detectors/CF7RecaptchaDetector.php + - ./src/php/MigrationWizard/Detectors/CoBlocksDetector.php + - ./src/php/MigrationWizard/Detectors/ContactForm7CaptchaDetector.php + - ./src/php/MigrationWizard/Detectors/DownloadManagerDetector.php + - ./src/php/MigrationWizard/Detectors/ElementorProDetector.php + - ./src/php/MigrationWizard/Detectors/EssentialBlocksDetector.php + - ./src/php/MigrationWizard/Detectors/FluentFormsDetector.php + - ./src/php/MigrationWizard/Detectors/FormidableFormsDetector.php + - ./src/php/MigrationWizard/Detectors/ForminatorDetector.php + - ./src/php/MigrationWizard/Detectors/GiveWPDetector.php + - ./src/php/MigrationWizard/Detectors/GoogleCaptchaDetector.php + - ./src/php/MigrationWizard/Detectors/GravityFormsRecaptchaDetector.php + - ./src/php/MigrationWizard/Detectors/KadenceDetector.php + - ./src/php/MigrationWizard/Detectors/MailPoetDetector.php + - ./src/php/MigrationWizard/Detectors/MetFormDetector.php + - ./src/php/MigrationWizard/Detectors/NinjaFormsDetector.php + - ./src/php/MigrationWizard/Detectors/OtterDetector.php + - ./src/php/MigrationWizard/Detectors/SimpleTurnstileDetector.php + - ./src/php/MigrationWizard/Detectors/SpectraDetector.php + - ./src/php/MigrationWizard/Detectors/TutorLMSDetector.php + - ./src/php/MigrationWizard/Detectors/WordfenceDetector.php + - ./src/php/MigrationWizard/Detectors/WPFormsRecaptchaDetector.php + - ./src/php/MigrationWizard/DetectionResult.php + - ./src/php/MigrationWizard/MigrationWizard.php + - ./src/php/MigrationWizard/Scanner.php + - ./src/php/MigrationWizard/ScanResult.php + - ./src/php/MigrationWizard/SurfaceMapping.php + - ./src/php/Settings/Abstracts/SettingsBase.php + - ./src/php/Settings/Advanced.php + - ./src/php/Settings/AntiSpamPage.php + - ./src/php/Settings/EventsPage.php + - ./src/php/Settings/FormsPage.php + - ./src/php/Settings/General.php + - ./src/php/Settings/Integrations.php + - ./src/php/Settings/ListPageBase.php + - ./src/php/Settings/PluginSettingsBase.php + - ./src/php/Settings/Settings.php + - ./src/php/Settings/SettingsTransfer.php + - ./src/php/Settings/SystemInfo.php + - ./src/php/Settings/Tools.php + - ./src/php/SimpleDownloadMonitor/Form.php + - ./src/php/WooCommercePayPalPayments/Button.php + - ./src/php/ErrorHandler.php diff --git a/tests/php/unit/AntiSpam/DisposableEmailTest.php b/tests/php/unit/AntiSpam/DisposableEmailTest.php index a36401450..933b8c59f 100644 --- a/tests/php/unit/AntiSpam/DisposableEmailTest.php +++ b/tests/php/unit/AntiSpam/DisposableEmailTest.php @@ -393,6 +393,9 @@ public function dp_test_is_disposable_email(): array { 'no domain' => [ 'user@', $blocklist, false ], 'uppercase disposable' => [ 'TEST@MAILINATOR.COM', $blocklist, true ], 'mixed case' => [ 'Test@Mailinator.Com', $blocklist, true ], + 'quoted local at' => [ '"local@part"@mailinator.com', $blocklist, true ], + 'quoted subdomain' => [ '"local@part"@sub.mailinator.com', $blocklist, true ], + 'quoted permanent' => [ '"local@mailinator.com"@gmail.com', $blocklist, false ], ]; } diff --git a/tests/php/unit/AutoVerify/AutoVerifyTest.php b/tests/php/unit/AutoVerify/AutoVerifyTest.php index cdbe52488..e2dae55c6 100644 --- a/tests/php/unit/AutoVerify/AutoVerifyTest.php +++ b/tests/php/unit/AutoVerify/AutoVerifyTest.php @@ -33,7 +33,7 @@ class AutoVerifyTest extends HCaptchaTestCase { * Tear down the test. */ public function tearDown(): void { - unset( $GLOBALS['wpdb'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'] ); + unset( $GLOBALS['wpdb'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_GET['pagename'] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing foreach ( array_keys( $_POST ) as $key ) { @@ -443,6 +443,7 @@ static function ( $value ) { */ public function test_verify_when_form_is_not_registered(): void { $url = 'https://test.test/auto-verify?test=1'; + FunctionMocker::replace( '\HCaptcha\Helpers\Request::filter_input', '' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url $path = parse_url( $url, PHP_URL_PATH ); @@ -803,7 +804,7 @@ static function ( $value ) { } ); WP_Mock::userFunction( 'wp_parse_url' )->andReturnUsing( - static function ( $url, $component ) { + static function ( $url, $component = -1 ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url return parse_url( $url, $component ); } @@ -1048,6 +1049,87 @@ public function dp_test_get_registered_form(): array { ]; } + /** + * Match PHP array input names in both persistent and legacy registrations. + * + * @param array $inputs Registered input names. + * @param string $query Encoded submission. + * @param bool $matches Whether the submission matches. + * @param bool $persistent Whether to use persistent storage. + * + * @dataProvider dp_test_get_registered_form_with_array_inputs + * @throws ReflectionException Reflection exception. + */ + public function test_get_registered_form_with_array_inputs( array $inputs, string $query, bool $matches, bool $persistent ): void { + parse_str( $query, $post ); + $_POST = $post + [ HCaptcha::HCAPTCHA_WIDGET_ID => 'array-widget-id' ]; + $form = [ + 'inputs' => $inputs, + 'widget_id' => 'array-widget-id', + 'args' => [ 'auto' => true ], + ]; + + WP_Mock::userFunction( 'get_option' ) + ->with( 'hcaptcha_auto_verify_form_' . hash( 'sha256', '/array-form' ), false ) + ->once() + ->andReturn( $persistent ? [ $form ] : false ); + WP_Mock::userFunction( 'get_transient' ) + ->with( AutoVerify::TRANSIENT ) + ->times( $persistent ? 0 : 1 ) + ->andReturn( [ '/array-form' => [ $form ] ] ); + FunctionMocker::replace( + '\\HCaptcha\\Helpers\\Request::filter_input', + static function ( int $type, string $var_name ) use ( $post ) { + return $post[ $var_name ] ?? ( HCaptcha::HCAPTCHA_WIDGET_ID === $var_name ? 'array-widget-id' : '' ); + } + ); + + self::assertSame( + $matches ? $form : [], + $this->call_private( new AutoVerify(), 'get_registered_form', [ '/array-form' ] ) + ); + } + + /** + * Array field structures as parsed by PHP from an HTTP submission. + * + * @return array + */ + public function dp_test_get_registered_form_with_array_inputs(): array { + $cases = [ + 'contact fields' => [ [ 'contact[name]', 'contact[email]' ], 'contact[name]=User&contact[email]=user@example.com', true ], + 'empty values' => [ [ 'contact[name]', 'contact[email]' ], 'contact[name]=&contact[email]=', true ], + 'missing sibling' => [ [ 'contact[name]', 'contact[email]' ], 'contact[name]=User', false ], + 'missing parent' => [ [ 'contact[email]' ], 'other[email]=user@example.com', false ], + 'scalar parent' => [ [ 'contact[email]' ], 'contact=user@example.com', false ], + 'deep field' => [ [ 'contact[address][city]' ], 'contact[address][city]=Riga', true ], + 'missing deep field' => [ [ 'contact[address][city]' ], 'contact[address][country]=Latvia', false ], + 'indexed field' => [ [ 'contacts[2][email]' ], 'contacts[2][email]=user@example.com', true ], + 'wrong index' => [ [ 'contacts[2][email]' ], 'contacts[0][email]=user@example.com', false ], + 'list' => [ [ 'emails[]' ], 'emails[]=user@example.com', true ], + 'nonzero list index' => [ [ 'emails[]' ], 'emails[3]=user@example.com', true ], + 'scalar list' => [ [ 'emails[]' ], 'emails=user@example.com', false ], + 'nested list' => [ [ 'contact[emails][]' ], 'contact[emails][]=user@example.com', true ], + 'field inside list' => [ [ 'contacts[][email]' ], 'contacts[2][name]=User&contacts[3][email]=user@example.com', true ], + 'missing field in list' => [ [ 'contacts[][email]' ], 'contacts[2][name]=User', false ], + 'multidimensional list' => [ [ 'contacts[][emails][]' ], 'contacts[2][emails][3]=user@example.com', true ], + 'mixed field names' => [ [ 'subject', 'contact[email]' ], 'subject=Hello&contact[email]=user@example.com', true ], + 'normalized root' => [ [ 'contact.details[email]' ], 'contact.details[email]=user@example.com', true ], + 'literal plus and amp' => [ [ 'contact+details[email&name]' ], 'contact%2Bdetails[email%26name]=User', true ], + 'wrong widget identity' => [ [ 'contact[email]' ], 'contact[email]=user@example.com&hcaptcha-widget-id=other-widget-id', false ], + 'missing widget identity' => [ [ 'contact[email]' ], 'contact[email]=user@example.com&hcaptcha-widget-id=', false ], + ]; + $data = []; + + foreach ( [ false, true ] as $persistent ) { + foreach ( $cases as $name => $case ) { + $data[ $name . ( $persistent ? ' persistent' : ' legacy' ) ] = array_merge( $case, [ $persistent ] ); + } + } + + return $data; + } + /** * Get test request URI. * @@ -1188,18 +1270,20 @@ static function ( $path ) { */ public function test_registered_form_uses_canonical_path(): void { $_SERVER['REQUEST_URI'] = '/raw-path/'; + $_GET['pagename'] = 'page-slug'; $this->mock_url_helpers(); WP_Mock::passthruFunction( 'wp_unslash' ); FunctionMocker::replace( '\HCaptcha\Helpers\Request::current_url', 'https://test.test/raw-path/' ); FunctionMocker::replace( '\HCaptcha\Helpers\Request::filter_input', static function ( $type ) { - return INPUT_GET === $type ? 'page-slug' : 'widget-id'; + return INPUT_POST === $type ? 'widget-id' : ''; } ); - WP_Mock::userFunction( 'url_to_postid' )->with( 'https://test.test/raw-path/' )->once()->andReturn( 0 ); - WP_Mock::userFunction( 'get_page_by_path' )->with( 'page-slug' )->once()->andReturn( (object) [ 'ID' => 123 ] ); + $query = Mockery::mock( 'overload:WP_Query' ); + $query->shouldReceive( 'get_queried_object_id' )->once()->andReturn( 123 ); WP_Mock::userFunction( 'get_permalink' )->with( 123 )->once()->andReturn( 'https://test.test/canonical/' ); + WP_Mock::userFunction( 'home_url' )->with( '/' )->once()->andReturn( 'https://test.test/' ); $form = [ 'args' => [ 'auto' => true ], @@ -1227,11 +1311,13 @@ static function ( $type ) { * @throws ReflectionException Reflection exception. */ public function test_canonical_path_rejects_non_string_permalink(): void { + $this->mock_url_helpers(); + FunctionMocker::replace( '\HCaptcha\Helpers\Request::filter_input', '' ); FunctionMocker::replace( '\HCaptcha\Helpers\Request::current_url', 'https://test.test/page/' ); WP_Mock::userFunction( 'url_to_postid' )->with( 'https://test.test/page/' )->once()->andReturn( 123 ); WP_Mock::userFunction( 'get_permalink' )->with( 123 )->once()->andReturn( false ); - self::assertSame( '', $this->call_private( new AutoVerify(), 'get_canonical_request_path' ) ); + self::assertSame( [], $this->call_private( new AutoVerify(), 'get_canonical_request_keys' ) ); } /** @@ -1308,13 +1394,246 @@ public function test_remove_form_registration_updates_remaining_forms(): void { $registered_forms = [ '/form' => [ [ 'source' => 'post:1' ], [ 'source' => 'post:2' ] ] ]; $action_forms = $registered_forms['/form']; $option_name = 'hcaptcha_auto_verify_form_' . hash( 'sha256', '/form' ); + $updates = 0; WP_Mock::userFunction( 'update_option' ) ->with( $option_name, [ [ 'source' => 'post:2' ] ], false ) - ->once(); + ->once() + ->andReturnUsing( + static function () use ( &$updates ): void { + ++$updates; + } + ); $method = $this->set_method_accessibility( $subject, 'remove_form_registration' ); $method->invokeArgs( $subject, [ &$registered_forms, [ 'source' => 'post:1' ], '/form', $action_forms, 0 ] ); self::assertSame( [ '/form' => [ [ 'source' => 'post:2' ] ] ], $registered_forms ); + self::assertSame( 1, $updates ); + } + + /** + * Prefer the query-qualified registration over the plain path. + * + * @throws ReflectionException Reflection exception. + */ + public function test_registered_form_uses_query_key(): void { + $_SERVER['REQUEST_URI'] = '/?p=123'; + $this->mock_url_helpers(); + WP_Mock::passthruFunction( 'wp_unslash' ); + WP_Mock::userFunction( 'home_url' )->with( '/' )->andReturn( 'https://test.test/' ); + + $query = Mockery::mock( 'overload:WP_Query' ); + $query->shouldReceive( 'get_queried_object_id' )->once()->andReturn( 123 ); + + $form = [ + 'args' => [ 'auto' => true ], + 'inputs' => [], + 'widget_id' => 'query-widget', + ]; + $_POST[ HCaptcha::HCAPTCHA_WIDGET_ID ] = 'query-widget'; + FunctionMocker::replace( + '\HCaptcha\Helpers\Request::filter_input', + static function ( $type, $name ) { + return INPUT_POST === $type && HCaptcha::HCAPTCHA_WIDGET_ID === $name ? 'query-widget' : ''; + } + ); + WP_Mock::userFunction( 'get_option' ) + ->with( 'hcaptcha_auto_verify_form_' . hash( 'sha256', 'post:123:/' ), false ) + ->once() + ->andReturn( [ $form ] ); + + self::assertSame( $form, $this->call_private( new AutoVerify(), 'get_registered_form_for_request' ) ); + } + + /** + * Skip a canonical key that duplicates the request path. + * + * @throws ReflectionException Reflection exception. + */ + public function test_registered_form_skips_duplicate_canonical_key(): void { + $_SERVER['REQUEST_URI'] = '/'; + $_GET = []; + $this->mock_url_helpers(); + WP_Mock::passthruFunction( 'wp_unslash' ); + WP_Mock::userFunction( 'home_url' )->with( '/' )->andReturn( 'https://test.test/' ); + WP_Mock::userFunction( 'url_to_postid' )->with( 'https://test.test/' )->once()->andReturn( 1 ); + WP_Mock::userFunction( 'get_permalink' )->with( 1 )->once()->andReturn( 'https://test.test/' ); + FunctionMocker::replace( '\\HCaptcha\\Helpers\\Request::filter_input', '' ); + FunctionMocker::replace( '\\HCaptcha\\Helpers\\Request::current_url', 'https://test.test/' ); + + foreach ( [ '/', 'post:1:/', 'post:1:/index.php' ] as $path ) { + WP_Mock::userFunction( 'get_option' ) + ->with( 'hcaptcha_auto_verify_form_' . hash( 'sha256', $path ), false ) + ->once() + ->andReturn( false ); + } + WP_Mock::userFunction( 'get_transient' )->with( AutoVerify::TRANSIENT )->times( 3 )->andReturn( false ); + + self::assertNull( $this->call_private( new AutoVerify(), 'get_registered_form_for_request' ) ); + } + + /** + * Decode HTML action references using browser-compatible rules. + * + * @throws ReflectionException Reflection exception. + */ + public function test_decode_action_attribute_references(): void { + $subject = new AutoVerify(); + $cases = [ + 'A' => 'A', + '©' => '©', + '€' => '€', + '😀' => '😀', + '�' => "\xef\xbf\xbd", + '�' => "\xef\xbf\xbd", + '�' => "\xef\xbf\xbd", + '&' => '&', + '&bogus' => '&bogus', + ]; + + foreach ( $cases as $reference => $expected ) { + self::assertSame( $expected, $this->call_private( $subject, 'decode_action_attribute', [ $reference ] ) ); + } + } + + /** + * Resolve pathless, relative and absolute form actions. + * + * @throws ReflectionException Reflection exception. + */ + public function test_resolve_form_action_paths(): void { + $_SERVER['REQUEST_URI'] = '/directory/current?old=1'; + WP_Mock::passthruFunction( 'wp_unslash' ); + WP_Mock::userFunction( 'wp_parse_url' )->andReturnUsing( + static function ( $url, $component = -1 ) { + // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url + return parse_url( $url, $component ); + } + ); + + $subject = new AutoVerify(); + self::assertSame( '/directory/current', $this->call_private( $subject, 'resolve_form_action', [ '' ] ) ); + self::assertSame( '/directory/next', $this->call_private( $subject, 'resolve_form_action', [ 'next' ] ) ); + self::assertSame( '/', $this->call_private( $subject, 'resolve_form_action', [ 'https://other.test' ] ) ); + } + + /** + * Retire migrated actions while retaining unrelated legacy registrations. + * + * @throws ReflectionException Reflection exception. + */ + public function test_update_form_registrations_retires_legacy_transient(): void { + $action = '/form'; + $option_name = 'hcaptcha_auto_verify_form_' . hash( 'sha256', $action ); + $form_data = [ + 'action' => $action, + 'inputs' => [], + 'args' => [ 'auto' => true ], + ]; + $stored_form = [ + 'inputs' => [], + 'args' => [ 'auto' => true ], + ]; + + WP_Mock::userFunction( 'wp_parse_args' )->andReturnUsing( + static function ( $args, $defaults ) { + return array_merge( $defaults, $args ); + } + ); + WP_Mock::userFunction( 'get_transient' )->with( AutoVerify::TRANSIENT )->twice()->andReturn( + [ + $action => [], + '/other' => [], + ], + [ $action => [] ] + ); + WP_Mock::userFunction( 'get_option' )->with( $option_name, false )->twice()->andReturn( false ); + WP_Mock::userFunction( 'update_option' )->with( $option_name, [ $stored_form ], false )->twice(); + WP_Mock::userFunction( 'set_transient' ) + ->with( AutoVerify::TRANSIENT, [ '/other' => [] ], 86400 ) + ->once(); + WP_Mock::userFunction( 'delete_transient' )->with( AutoVerify::TRANSIENT )->once(); + FunctionMocker::replace( 'constant', 86400 ); + + $subject = new AutoVerify(); + $method = $this->set_method_accessibility( $subject, 'update_form_registrations' ); + $method->invoke( $subject, [ $form_data ] ); + $method->invoke( $subject, [ $form_data ] ); + } + + /** + * Replace an existing registration with the same source and widget ID. + * + * @throws ReflectionException Reflection exception. + */ + public function test_update_form_registrations_replaces_existing_form(): void { + $action = '/form'; + $option_name = 'hcaptcha_auto_verify_form_' . hash( 'sha256', $action ); + $stored_form = [ + 'inputs' => [ 'email' ], + 'widget_id' => 'widget-id', + 'source' => 'post:1', + 'args' => [ 'auto' => true ], + ]; + $new_form = $stored_form; + $new_form['args']['mandatory'] = true; + + WP_Mock::userFunction( 'wp_parse_args' )->andReturnUsing( + static function ( $args, $defaults ) { + return array_merge( $defaults, $args ); + } + ); + WP_Mock::userFunction( 'get_transient' )->with( AutoVerify::TRANSIENT )->once()->andReturn( false ); + WP_Mock::userFunction( 'get_option' )->with( $option_name, false )->once()->andReturn( [ $stored_form ] ); + WP_Mock::userFunction( 'update_option' )->with( $option_name, [ $new_form ], false )->once(); + + $subject = new AutoVerify(); + $method = $this->set_method_accessibility( $subject, 'update_form_registrations' ); + $method->invoke( $subject, [ [ 'action' => $action ] + $new_form ] ); + } + + /** + * Persist the remaining form when one source disables auto verification. + * + * @throws ReflectionException Reflection exception. + */ + public function test_update_form_registrations_removes_one_existing_form(): void { + $action = '/form'; + $option_name = 'hcaptcha_auto_verify_form_' . hash( 'sha256', $action ); + $stored_form = [ + 'inputs' => [ 'email' ], + 'widget_id' => 'widget-id', + 'source' => 'post:1', + 'args' => [ 'auto' => true ], + ]; + $other_form = [ + 'inputs' => [ 'name' ], + 'widget_id' => 'other-widget', + 'source' => 'post:2', + 'args' => [ 'auto' => true ], + ]; + + WP_Mock::userFunction( 'wp_parse_args' )->andReturnUsing( + static function ( $args, $defaults ) { + return array_merge( $defaults, $args ); + } + ); + WP_Mock::userFunction( 'get_transient' )->with( AutoVerify::TRANSIENT )->once()->andReturn( false ); + WP_Mock::userFunction( 'get_option' )->with( $option_name, false )->once()->andReturn( [ $stored_form, $other_form ] ); + WP_Mock::userFunction( 'update_option' )->with( $option_name, [ $other_form ], false )->once(); + + $subject = new AutoVerify(); + $method = $this->set_method_accessibility( $subject, 'update_form_registrations' ); + $method->invoke( + $subject, + [ + [ + 'action' => $action, + 'inputs' => [ 'email' ], + 'widget_id' => 'widget-id', + 'source' => 'post:1', + ], + ] + ); } } diff --git a/tests/php/unit/ChangelogTest.php b/tests/php/unit/ChangelogTest.php new file mode 100644 index 000000000..46d81f634 --- /dev/null +++ b/tests/php/unit/ChangelogTest.php @@ -0,0 +1,72 @@ +expectException( RuntimeException::class ); + $this->expectExceptionMessage( 'No release notes found in readme.txt.' ); + + hcaptcha_generate_changelog( "== Changelog ==\nNo version.\n", '' ); + } + + /** + * Version headings outside the changelog must never become release notes. + */ + public function test_missing_changelog_section(): void { + $this->expectException( RuntimeException::class ); + $this->expectExceptionMessage( 'No Changelog section found in readme.txt.' ); + + hcaptcha_generate_changelog( "= 5.5.0 =\nDescription.\n", '' ); + } +} diff --git a/tests/php/unit/HCaptchaTestCase.php b/tests/php/unit/HCaptchaTestCase.php index b52f2b5e4..4c7ea9e0c 100644 --- a/tests/php/unit/HCaptchaTestCase.php +++ b/tests/php/unit/HCaptchaTestCase.php @@ -12,7 +12,6 @@ namespace HCaptcha\Tests\Unit; -use HCaptcha\Settings\Integrations; use KAGG\Settings\Abstracts\SettingsBase; use HCaptcha\Settings\General; use Mockery; @@ -759,14 +758,6 @@ protected function get_test_general_form_fields(): array { */ protected function get_test_integrations_form_fields(): array { return [ - 'show_antispam_coverage' => [ - 'type' => 'checkbox', - 'section' => Integrations::SECTION_HEADER, - 'options' => [ - 'on' => 'Show Anti-Spam Indicators', - ], - 'helper' => 'Shows icons for built-in antispam methods (Honeypot, Time check) for supported integrations, including inactive ones.', - ], 'wp_status' => [ 'entity' => 'core', diff --git a/tests/php/unit/Helpers/RequestTest.php b/tests/php/unit/Helpers/RequestTest.php index 6682d5943..5cb2528a4 100644 --- a/tests/php/unit/Helpers/RequestTest.php +++ b/tests/php/unit/Helpers/RequestTest.php @@ -227,6 +227,79 @@ static function ( $url, $component ) { self::assertFalse( Request::is_rest() ); } + /** + * Test REST request detection across permalink formats and route values. + * + * @dataProvider dp_test_is_rest_routes + * + * @param string $request_uri Current request URI. + * @param string $rest_url REST API base URL. + * @param array|string|null $rest_route Route query parameter. + * @param bool $rest_request Whether REST_REQUEST is true. + * @param bool $expected Expected result. + * + * @return void + */ + public function test_is_rest_routes( string $request_uri, string $rest_url, $rest_route, bool $rest_request, bool $expected ): void { + $_SERVER['REQUEST_URI'] = $request_uri; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + + if ( null !== $rest_route ) { + $_GET['rest_route'] = $rest_route; + } + + FunctionMocker::replace( + 'defined', + static function ( $constant_name ) { + return 'REST_REQUEST' === $constant_name; + } + ); + FunctionMocker::replace( + 'constant', + static function ( $constant_name ) use ( $rest_request ) { + return 'REST_REQUEST' === $constant_name && $rest_request; + } + ); + + WP_Mock::passthruFunction( 'wp_unslash' ); + WP_Mock::passthruFunction( 'sanitize_text_field' ); + WP_Mock::passthruFunction( 'trailingslashit' ); + WP_Mock::userFunction( 'add_query_arg' )->with( [] )->andReturn( $request_uri ); + WP_Mock::userFunction( 'rest_url' )->with()->andReturn( $rest_url ); + WP_Mock::userFunction( 'wp_parse_url' )->andReturnUsing( + static function ( $url, $component = -1 ) { + // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url + return parse_url( $url, $component ); + } + ); + + Mockery::mock( 'WP_Rewrite' ); + + self::assertSame( $expected, Request::is_rest() ); + } + + /** + * Data provider for test_is_rest_routes(). + * + * @return array[] + */ + public function dp_test_is_rest_routes(): array { + return [ + 'plain index without route' => [ '/index.php', 'https://test.test/index.php?rest_route=/', null, false, false ], + 'plain index with other query' => [ '/index.php?foo=bar', 'https://test.test/index.php?rest_route=/', null, false, false ], + 'plain index prefix lookalike' => [ '/index.php-extra', 'https://test.test/index.php?rest_route=/', null, false, false ], + 'plain index with REST route' => [ '/index.php?rest_route=/wp/v2/posts', 'https://test.test/index.php?rest_route=/', '/wp/v2/posts', false, true ], + 'REST_REQUEST constant' => [ '/some-page/', 'https://test.test/wp-json/', null, true, true ], + 'pretty REST base' => [ '/wp-json/', 'https://test.test/wp-json/', null, false, true ], + 'pretty REST child' => [ '/wp-json/wp/v2/posts', 'https://test.test/wp-json/', null, false, true ], + 'pretty REST URL with query' => [ '/wp-json/wp/v2/posts', 'https://test.test/wp-json/?lang=en', null, false, true ], + 'index permalink REST child' => [ '/index.php/wp-json/wp/v2/posts', 'https://test.test/index.php/wp-json/', null, false, true ], + 'pretty prefix lookalike' => [ '/wp-jsonified/', 'https://test.test/wp-json/', null, false, false ], + 'index permalink prefix lookalike' => [ '/index.php/wp-json-extra/', 'https://test.test/index.php/wp-json/', null, false, false ], + 'array REST route' => [ '/index.php?rest_route[]=bad', 'https://test.test/index.php?rest_route=/', [ '/wp/v2/posts' ], false, false ], + ]; + } + /** * Test is_post(). * @@ -368,10 +441,37 @@ public function dp_test_is_ip_in_range(): array { // Range (IPv4). [ '192.168.1.10', '192.168.1.10-192.168.1.20', true ], [ '192.168.1.21', '192.168.1.10-192.168.1.20', false ], + [ '192.168.1.20', '192.168.1.10-192.168.1.20', true ], + [ ' 192.168.1.10 ', ' 192.168.1.10 - 192.168.1.20 ', true ], + [ '192.168.1.15', '192.168.1.20-192.168.1.10', false ], + [ '0.0.0.0', '0.0.0.0-0.0.0.0', true ], + + // Packed addresses must be compared as bytes, even when they look numeric. + [ '49.48.69.57', '49.101.49.48-49.101.49.48', false ], + [ '49.101.49.48', '49.101.49.48-49.101.49.48', true ], + [ '49.101.49.48', '49.48.69.57-49.101.49.48', true ], + [ '49.101.49.48', '49.101.49.48-49.48.69.57', false ], + [ '3130:4530:3030:3030:3030:3030:3030:3039', '3165:3030:3030:3030:3030:3030:3030:3130-3165:3030:3030:3030:3030:3030:3030:3130', false ], // Range (IPv6). [ '2001:db8::5', '2001:db8::1-2001:db8::f', true ], [ '2001:db8::10', '2001:db8::1-2001:db8::f', false ], + [ '2001:0db8:0000:0000:0000:0000:0000:0005', '2001:db8::1-2001:db8::f', true ], + [ '::', '::-::', true ], + [ '::ffff:192.0.2.5', '::ffff:192.0.2.1-::ffff:192.0.2.10', true ], + + // All range operands must be valid addresses in the same family. + [ '2600::1', '38.0.0.0-38.255.255.255', false ], + [ '38.1.1.1', '2600::-26ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', false ], + [ '38.1.1.1', '38.0.0.0-ffff::', false ], + [ '2600::1', '38.0.0.0-ffff::', false ], + [ 'not-an-ip', '192.168.1.10-192.168.1.20', false ], + [ '1.1.1.1', 'invalid-192.168.1.20', false ], + [ '192.168.1.15', '192.168.1.10-invalid', false ], + [ 'not-an-ip', 'invalid-invalid', false ], + [ '1.1.1.1', '-192.168.1.20', false ], + [ '192.168.1.15', '192.168.1.10-', false ], + [ '', '-', false ], // Mixed types. [ '192.168.1.1', '2001:db8::/64', false ], // IPv4 vs IPv6. diff --git a/tests/php/unit/ScoperTest.php b/tests/php/unit/ScoperTest.php new file mode 100644 index 000000000..1a0d5372e --- /dev/null +++ b/tests/php/unit/ScoperTest.php @@ -0,0 +1,57 @@ + [ "'\\\\MatthiasMullie\\\\Minify\\\\Minify'", $prefixed ], + 'unscoped literal' => [ "'\MatthiasMullie\Minify\Minify'", $prefixed ], + 'scoped escaped' => [ $escaped, $escaped ], + 'scoped literal' => [ $prefixed, $prefixed ], + 'other namespace' => [ $other, $other ], + ]; + } +} diff --git a/tests/php/unit/Settings/Abstracts/SettingsBaseTest.php b/tests/php/unit/Settings/Abstracts/SettingsBaseTest.php index 8b478d9e4..8532f7350 100644 --- a/tests/php/unit/Settings/Abstracts/SettingsBaseTest.php +++ b/tests/php/unit/Settings/Abstracts/SettingsBaseTest.php @@ -887,6 +887,7 @@ public function test_admin_enqueue_scripts(): void { public function test_base_admin_enqueue_scripts(): void { $plugin_url = 'http://test.test/wp-content/plugins/hcaptcha-for-forms-and-more'; $plugin_version = '1.0.0'; + $style_version = $plugin_version . '-' . filemtime( dirname( __DIR__, 5 ) . '/assets/css/settings-base.css' ); $page = Mockery::mock( SettingsBase::class ); $page->shouldReceive( 'admin_enqueue_scripts' )->with()->once(); @@ -920,7 +921,7 @@ public function test_base_admin_enqueue_scripts(): void { SettingsBase::PREFIX . '-' . SettingsBase::HANDLE, $plugin_url . '/assets/css/settings-base.css', [], - $plugin_version + $style_version ) ->once(); @@ -2936,10 +2937,7 @@ public function test_pre_update_option_filter( array $form_fields, $value, $old_ WP_Mock::userFunction( 'is_multisite' )->with()->andReturn( false ); WP_Mock::userFunction( 'current_user_can' )->with( 'manage_network_options' )->andReturn( true ); - $general_tab = isset( $value['site_key'] ); - $network_wide = $general_tab - ? $value['_network_wide'] - : []; + $network_wide = $value['_network_wide'] ?? []; $get_site_option = $network_wide ? $old_value : []; WP_Mock::userFunction( 'get_site_option' ) @@ -2949,6 +2947,23 @@ public function test_pre_update_option_filter( array $form_fields, $value, $old_ self::assertSame( $expected, $subject->pre_update_option_filter( $value, $old_value ) ); } + /** + * Reject a native network-wide write from an unauthorized request. + */ + public function test_pre_update_option_filter_rejects_unauthorized_network_write(): void { + $old_value = [ 'theme' => 'light' ]; + $new_value = [ 'theme' => 'dark' ]; + $subject = Mockery::mock( SettingsBase::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'option_name' )->andReturn( 'hcaptcha_settings' ); + $subject->shouldReceive( 'is_network_wide' )->once()->andReturn( true ); + $subject->shouldReceive( 'can_manage_settings' )->once()->andReturn( false ); + + FunctionMocker::replace( '\\HCaptcha\\Helpers\\Request::is_cli', false ); + + self::assertSame( $old_value, $subject->pre_update_option_filter( $new_value, $old_value ) ); + } + /** * Data provider for test_pre_update_option_filter(). * @@ -3153,7 +3168,7 @@ public function dp_test_pre_update_option_filter(): array { '_network_wide' => [], ], ], - 'table and network wide changed not on general tab' => [ + 'table and network wide changed with explicit value' => [ 'form_fields' => [], 'value' => [ 'bel' => [ 'Б' => 'B1' ], @@ -3166,7 +3181,7 @@ public function dp_test_pre_update_option_filter(): array { 'expected' => [ 'iso9' => [ 'Б' => 'B' ], 'bel' => [ 'Б' => 'B1' ], - '_network_wide' => [], + '_network_wide' => [ 'on' ], ], ], 'table and network wide changed on general tab' => [ @@ -3187,6 +3202,27 @@ public function dp_test_pre_update_option_filter(): array { 'site_key' => 'some_site_key', ], ], + 'network wide changed on advanced tab' => [ + 'form_fields' => [ + SettingsBase::NETWORK_WIDE => [ + 'type' => 'checkbox', + 'disabled' => false, + ], + ], + 'value' => [ + 'bel' => [ 'Б' => 'B1' ], + SettingsBase::NETWORK_WIDE => [ 'on' ], + ], + 'old_value' => [ + 'iso9' => [ 'Б' => 'B' ], + 'bel' => [ 'Б' => 'B' ], + ], + 'expected' => [ + 'iso9' => [ 'Б' => 'B' ], + 'bel' => [ 'Б' => 'B1' ], + SettingsBase::NETWORK_WIDE => [ 'on' ], + ], + ], ]; // phpcs:enable WordPress.Arrays.MultipleStatementAlignment.DoubleArrowNotAligned } @@ -3217,13 +3253,17 @@ public function test_pre_update_option_filter_on_multisite( array $form_fields, WP_Mock::userFunction( 'is_multisite' )->with()->andReturn( true ); WP_Mock::userFunction( 'current_user_can' )->with( 'manage_network_options' )->andReturn( true ); - $general_tab = isset( $value['site_key'] ); - $network_wide = $general_tab - ? $value[ $netwide_name ] ?? [] - : $get_network_wide; + $network_wide = $value[ $netwide_name ] ?? $get_network_wide; if ( $network_wide ) { $old_value = []; + WP_Mock::userFunction( 'get_site_option' )->with( $option_name, [] )->andReturn( $old_value ); + WP_Mock::expectFilterAdded( + 'pre_update_site_option_' . $option_name, + [ $subject, 'pre_update_option_filter' ], + 10, + 2 + ); } $merged_value = array_merge( $old_value, $value ); @@ -3232,7 +3272,9 @@ public function test_pre_update_option_filter_on_multisite( array $form_fields, WP_Mock::userFunction( 'update_site_option' ) ->with( $option_name . $netwide_name, $merged_value[ $netwide_name ] ); WP_Mock::userFunction( 'remove_filter' ) - ->with( 'pre_update_site_option_' . $option_name, [ $subject, 'pre_update_option_filter' ] ); + ->with( 'pre_update_site_option_' . $option_name, [ $subject, 'pre_update_option_filter' ], 10 ); + WP_Mock::userFunction( 'has_filter' ) + ->with( 'pre_update_site_option_' . $option_name, [ $subject, 'pre_update_option_filter' ] )->andReturn( 10 ); WP_Mock::userFunction( 'update_site_option' )->with( $option_name, $merged_value ); if ( $network_wide ) { @@ -3242,6 +3284,57 @@ public function test_pre_update_option_filter_on_multisite( array $form_fields, } } + /** + * Saving General must not turn off active network-wide settings moved to Advanced. + */ + public function test_general_save_preserves_network_wide_on_multisite(): void { + $option_name = 'hcaptcha_settings'; + $old_value = [ + 'site_key' => 'old-key', + '_network_wide' => [ 'on' ], + ]; + $value = [ 'site_key' => 'new-key' ]; + + $subject = Mockery::mock( SettingsBase::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'form_fields' )->andReturn( + [ + 'site_key' => [ + 'type' => 'text', + 'disabled' => false, + ], + ] + ); + $subject->shouldReceive( 'option_name' )->andReturn( $option_name ); + $subject->shouldReceive( 'get_network_wide' )->andReturn( [ 'on' ] ); + + WP_Mock::userFunction( 'is_multisite' )->andReturn( true ); + WP_Mock::userFunction( 'current_user_can' )->with( 'manage_network_options' )->andReturn( true ); + WP_Mock::userFunction( 'get_site_option' )->with( $option_name, [] )->andReturn( $old_value ); + WP_Mock::userFunction( 'update_site_option' ) + ->with( $option_name . '_network_wide', [ 'on' ] )->once(); + WP_Mock::userFunction( 'remove_filter' ) + ->with( 'pre_update_site_option_' . $option_name, [ $subject, 'pre_update_option_filter' ], 10 )->once(); + WP_Mock::userFunction( 'has_filter' ) + ->with( 'pre_update_site_option_' . $option_name, [ $subject, 'pre_update_option_filter' ] )->andReturn( 10 ); + WP_Mock::expectFilterAdded( + 'pre_update_site_option_' . $option_name, + [ $subject, 'pre_update_option_filter' ], + 10, + 2 + ); + WP_Mock::userFunction( 'update_site_option' ) + ->with( + $option_name, + [ + 'site_key' => 'new-key', + '_network_wide' => [ 'on' ], + ] + )->once(); + + self::assertSame( $old_value, $subject->pre_update_option_filter( $value, $old_value ) ); + } + /** * Test load_plugin_textdomain(). */ diff --git a/tests/php/unit/Settings/AdvancedTest.php b/tests/php/unit/Settings/AdvancedTest.php new file mode 100644 index 000000000..b12ff494c --- /dev/null +++ b/tests/php/unit/Settings/AdvancedTest.php @@ -0,0 +1,121 @@ +andReturn( true ); + + $subject = Mockery::mock( Advanced::class )->makePartial(); + $subject->init_form_fields(); + + $fields = $this->get_protected_property( $subject, 'form_fields' ); + + self::assertSame( General::SECTION_ENTERPRISE, $fields['api_host']['section'] ); + self::assertSame( General::SECTION_CONTENT, $fields['protect_content']['section'] ); + self::assertSame( General::SECTION_OTHER, $fields[ SettingsBase::NETWORK_WIDE ]['section'] ); + self::assertSame( General::SECTION_STATISTICS, $fields['statistics']['section'] ); + self::assertArrayNotHasKey( 'site_key', $fields ); + self::assertArrayNotHasKey( 'mode', $fields ); + self::assertSame( + [ + General::SECTION_CONTENT, + General::SECTION_OTHER, + General::SECTION_STATISTICS, + General::SECTION_ENTERPRISE, + ], + array_values( array_unique( array_column( $fields, 'section' ) ) ) + ); + } + + /** + * Enterprise fields remain disabled for a Free account. + */ + public function test_setup_fields_disables_enterprise_for_free(): void { + $settings = Mockery::mock( Settings::class )->makePartial(); + $settings->shouldReceive( 'get_license' )->andReturn( 'free' ); + + $main = Mockery::mock( Main::class )->makePartial(); + $main->shouldReceive( 'settings' )->andReturn( $settings ); + + $subject = Mockery::mock( Advanced::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'is_options_screen' )->andReturn( true ); + + $this->set_protected_property( + $subject, + 'form_fields', + [ + 'api_host' => [ + 'label' => 'API Host', + 'type' => 'text', + 'section' => General::SECTION_ENTERPRISE, + 'disabled' => false, + ], + ] + ); + + WP_Mock::passthruFunction( 'register_setting' ); + WP_Mock::passthruFunction( 'add_settings_field' ); + WP_Mock::userFunction( 'hcaptcha' )->with()->andReturn( $main ); + + $subject->setup_fields(); + + $fields = $this->get_protected_property( $subject, 'form_fields' ); + self::assertTrue( $fields['api_host']['disabled'] ); + } + + /** + * Test the unminified stylesheet receives a file-based version. + */ + public function test_admin_enqueue_scripts_without_min_suffix(): void { + $subject = Mockery::mock( Advanced::class )->makePartial(); + $this->set_protected_property( $subject, 'min_suffix', '' ); + + FunctionMocker::replace( + 'constant', + static function ( $name ) { + return [ + 'HCAPTCHA_VERSION' => '1.0.0', + 'HCAPTCHA_PATH' => HCAPTCHA_TEST_PATH, + 'HCAPTCHA_URL' => HCAPTCHA_TEST_URL, + ][ $name ]; + } + ); + + WP_Mock::userFunction( 'wp_enqueue_style' ) + ->with( + Advanced::HANDLE, + HCAPTCHA_TEST_URL . '/assets/css/advanced.css', + [ PluginSettingsBase::PREFIX . '-' . SettingsBase::HANDLE ], + '1.0.0-' . filemtime( HCAPTCHA_TEST_PATH . '/assets/css/advanced.css' ) + ) + ->once(); + + $subject->admin_enqueue_scripts(); + } +} diff --git a/tests/php/unit/Settings/AntiSpamPageBehaviorTest.php b/tests/php/unit/Settings/AntiSpamPageBehaviorTest.php index e5a5e3460..ad046ac7c 100644 --- a/tests/php/unit/Settings/AntiSpamPageBehaviorTest.php +++ b/tests/php/unit/Settings/AntiSpamPageBehaviorTest.php @@ -11,6 +11,7 @@ use HCaptcha\AntiSpam\AntiSpam; use HCaptcha\AntiSpam\DisposableEmail; use HCaptcha\Helpers\CloudflareDetector; +use HCaptcha\Helpers\Request; use HCaptcha\Migrations\Migrations; use HCaptcha\Settings\AntiSpamPage; use HCaptcha\Settings\PluginSettingsBase; @@ -45,6 +46,7 @@ public function test_init_hooks(): void { $subject->shouldAllowMockingProtectedMethods(); $subject->shouldReceive( 'is_main_menu_page' )->once()->andReturn( false ); $subject->shouldReceive( 'is_tab_active' )->with( $subject )->once()->andReturn( false ); + WP_Mock::userFunction( 'wp_doing_ajax' )->withNoArgs()->once()->andReturn( false ); WP_Mock::expectActionAdded( 'wp_ajax_' . AntiSpamPage::CHECK_IPS_ACTION, [ $subject, 'check_ips' ] ); WP_Mock::expectActionAdded( 'wp_ajax_' . AntiSpamPage::DETECT_CLOUDFLARE_ACTION, [ $subject, 'detect_cloudflare' ] ); @@ -187,30 +189,15 @@ public function test_maybe_toggle_disposable_email(): void { } /** - * Test settings storage paths for site and network contexts. + * Test only an authorized settings save clears stale review and detection data. * - * @throws ReflectionException Reflection exception. - */ - public function test_stored_settings(): void { - $subject = $this->create_subject(); - WP_Mock::userFunction( 'is_multisite' )->andReturn( true ); - WP_Mock::userFunction( 'get_site_option' ) - ->with( PluginSettingsBase::OPTION_NAME . '_network_wide', [] )->andReturn( [ 'on' ] ); - WP_Mock::userFunction( 'get_site_option' )->with( PluginSettingsBase::OPTION_NAME, [] )->andReturn( [ 'key' => 'value' ] ); - WP_Mock::userFunction( 'update_site_option' )->with( PluginSettingsBase::OPTION_NAME, [ 'key' => 'new' ] )->once(); - - $get = $this->set_method_accessibility( $subject, 'get_stored_settings' ); - $set = $this->set_method_accessibility( $subject, 'update_stored_settings' ); - self::assertSame( [ 'key' => 'value' ], $get->invoke( $subject ) ); - $set->invoke( $subject, [ 'key' => 'new' ] ); - } - - /** - * Test saving trusted headers clears stale review and detection data. + * @param bool $can_manage Whether the current user can manage settings. + * + * @dataProvider dp_test_clear_trusted_address_headers_review_notice * * @throws ReflectionException Reflection exception. */ - public function test_clear_trusted_address_headers_review_notice(): void { + public function test_clear_trusted_address_headers_review_notice( bool $can_manage ): void { $subject = $this->create_subject(); $this->set_protected_property( $subject, 'form_fields', [ 'trusted_address_headers' => [] ] ); $value = [ @@ -220,6 +207,9 @@ public function test_clear_trusted_address_headers_review_notice(): void { ]; WP_Mock::passthruFunction( 'wp_unslash' ); WP_Mock::passthruFunction( 'sanitize_key' ); + WP_Mock::userFunction( 'is_multisite' )->andReturn( false ); + WP_Mock::userFunction( 'current_user_can' )->with( 'manage_options' )->twice()->andReturn( $can_manage ); + FunctionMocker::replace( '\\' . Request::class . '::is_cli', false ); self::assertSame( 'invalid', $subject->clear_trusted_address_headers_review_notice( 'invalid', [] ) ); self::assertSame( $value, $subject->clear_trusted_address_headers_review_notice( $value, [] ) ); @@ -230,16 +220,33 @@ public function test_clear_trusted_address_headers_review_notice(): void { $value, [ 'trusted_address_headers' => [ 'HTTP_X_REAL_IP' ] ] ); - self::assertArrayNotHasKey( Migrations::REVIEW_TRUSTED_ADDRESS_HEADERS_OPTION, $unchanged ); - self::assertArrayHasKey( AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION, $unchanged ); - - $changed = $subject->clear_trusted_address_headers_review_notice( $value, [] ); - self::assertArrayNotHasKey( AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION, $changed ); + $changed = $subject->clear_trusted_address_headers_review_notice( $value, [] ); + + if ( $can_manage ) { + self::assertArrayNotHasKey( Migrations::REVIEW_TRUSTED_ADDRESS_HEADERS_OPTION, $unchanged ); + self::assertArrayHasKey( AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION, $unchanged ); + self::assertArrayNotHasKey( AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION, $changed ); + } else { + self::assertSame( $value, $unchanged ); + self::assertSame( $value, $changed ); + } } finally { unset( $_POST[ PluginSettingsBase::OPTION_NAME ] ); } } + /** + * Settings save authorization cases. + * + * @return array + */ + public function dp_test_clear_trusted_address_headers_review_notice(): array { + return [ + 'authorized settings save' => [ true ], + 'unauthorized settings save' => [ false ], + ]; + } + /** * Test valid and invalid IP Ajax requests. * @@ -283,9 +290,22 @@ public function dp_test_check_ips(): array { } /** - * Test Cloudflare detection persists a sanitized status. + * Test Cloudflare detection changes only its status in the active storage scope. + * + * @param bool $network Network-wide settings are active. + * + * @dataProvider dp_test_detect_cloudflare */ - public function test_detect_cloudflare(): void { + public function test_detect_cloudflare( bool $network ): void { + $stored_settings = [ + '_network_wide' => $network ? [ 'on' ] : [], + 'site_key' => 'existing-site-key', + 'secret_key' => 'existing-secret-key', + 'theme' => 'dark', + 'trusted_address_headers' => [ 'HTTP_X_REAL_IP' ], + Migrations::REVIEW_TRUSTED_ADDRESS_HEADERS_OPTION => 'on', + ]; + $subject = Mockery::mock( AntiSpamPage::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); $subject->shouldReceive( 'run_checks' )->with( AntiSpamPage::DETECT_CLOUDFLARE_ACTION )->once(); @@ -298,26 +318,49 @@ public function test_detect_cloudflare(): void { ); FunctionMocker::replace( '\\' . CloudflareDetector::class . '::get_recommendation', 'Use CF-Connecting-IP.' ); WP_Mock::passthruFunction( 'sanitize_key' ); - WP_Mock::userFunction( 'is_multisite' )->andReturn( false ); - WP_Mock::userFunction( 'get_option' )->with( PluginSettingsBase::OPTION_NAME, [] )->once()->andReturn( [] ); - WP_Mock::userFunction( 'update_option' ) + WP_Mock::userFunction( 'is_multisite' )->andReturn( $network ); + WP_Mock::userFunction( 'get_current_blog_id' )->withNoArgs()->once()->andReturn( 2 ); + WP_Mock::userFunction( 'get_current_network_id' )->withNoArgs()->once()->andReturn( 1 ); + if ( $network ) { + WP_Mock::userFunction( 'get_site_option' ) + ->with( PluginSettingsBase::OPTION_NAME . '_network_wide', [] )->once()->andReturn( [ 'on' ] ); + } + WP_Mock::userFunction( $network ? 'get_site_option' : 'get_option' ) + ->with( PluginSettingsBase::OPTION_NAME, [] )->once()->andReturn( $stored_settings ); + WP_Mock::userFunction( $network ? 'update_option' : 'update_site_option' )->never(); + WP_Mock::userFunction( $network ? 'update_site_option' : 'update_option' ) ->with( PluginSettingsBase::OPTION_NAME, Mockery::on( - static function ( $settings ) { + static function ( $settings ) use ( $stored_settings ) { $status = $settings[ AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION ] ?? []; - return CloudflareDetector::STATUS_VERIFIED_REQUEST === ( $status['status'] ?? '' ) && + unset( $settings[ AntiSpamPage::CLOUDFLARE_DETECTION_STATUS_OPTION ] ); + + return $stored_settings === $settings && + CloudflareDetector::STATUS_VERIFIED_REQUEST === ( $status['status'] ?? '' ) && 'high' === ( $status['confidence'] ?? '' ) && is_int( $status['checked_at'] ?? null ); } ) - )->once(); + )->once()->andReturn( true ); WP_Mock::userFunction( 'wp_send_json_success' ) ->with( [ 'message' => 'Use CF-Connecting-IP.' ] )->once(); $subject->detect_cloudflare(); } + /** + * Cloudflare maintenance storage scopes. + * + * @return array + */ + public function dp_test_detect_cloudflare(): array { + return [ + 'site settings' => [ false ], + 'network settings' => [ true ], + ]; + } + /** * Test trusted header guidance and invalid Cloudflare status fallback. * @@ -349,4 +392,25 @@ public function test_setup_fields_off_screen(): void { $subject->setup_fields(); } + + /** + * Read stored settings from the network on a network-wide page. + */ + public function test_get_stored_settings_network_wide(): void { + $stored = [ 'honeypot' => [ 'on' ] ]; + $subject = $this->create_subject(); + + WP_Mock::userFunction( 'is_multisite' )->twice()->andReturn( true ); + WP_Mock::userFunction( 'get_site_option' ) + ->with( PluginSettingsBase::OPTION_NAME . '_network_wide', [] ) + ->once() + ->andReturn( [ 'on' ] ); + WP_Mock::userFunction( 'get_site_option' ) + ->with( PluginSettingsBase::OPTION_NAME, [] ) + ->once() + ->andReturn( $stored ); + + $method = $this->set_method_accessibility( $subject, 'get_stored_settings' ); + self::assertSame( $stored, $method->invoke( $subject ) ); + } } diff --git a/tests/php/unit/Settings/EventsPageTest.php b/tests/php/unit/Settings/EventsPageTest.php index c1f861700..5de46c0d9 100644 --- a/tests/php/unit/Settings/EventsPageTest.php +++ b/tests/php/unit/Settings/EventsPageTest.php @@ -10,6 +10,7 @@ use HCaptcha\Admin\Events\EventsTable; use HCaptcha\Admin\Events\Events; use HCaptcha\Main; +use HCaptcha\Settings\Advanced; use HCaptcha\Settings\EventsPage; use HCaptcha\Settings\ListPageBase; use HCaptcha\Settings\PluginSettingsBase; @@ -391,12 +392,18 @@ public function test_section_callback_when_not_allowed(): void {

      It is an example of the Events page.

      -

      Want to see events statistics? Please turn on the Statistics switch on the General settings page and upgrade to Pro account.

      +

      Want to see events statistics? Please turn on the Statistics switch on the Advanced settings page and upgrade to Pro account.

      '; $subject = Mockery::mock( EventsPage::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); + $settings = Mockery::mock( Settings::class ); + $settings->shouldReceive( 'tab_url' )->with( Advanced::class ) + ->andReturn( 'options-general.php?page=hcaptcha&tab=advanced' ); + $main = Mockery::mock( Main::class ); + $main->shouldReceive( 'settings' )->andReturn( $settings ); + WP_Mock::userFunction( 'hcaptcha' )->with()->andReturn( $main ); WP_Mock::passthruFunction( 'admin_url' ); WP_Mock::passthruFunction( 'wp_kses_post' ); diff --git a/tests/php/unit/Settings/FormsPageTest.php b/tests/php/unit/Settings/FormsPageTest.php index 86d16d285..19f034cea 100644 --- a/tests/php/unit/Settings/FormsPageTest.php +++ b/tests/php/unit/Settings/FormsPageTest.php @@ -11,6 +11,7 @@ use HCaptcha\Admin\Events\Events; use HCaptcha\Admin\Events\FormsTable; use HCaptcha\Main; +use HCaptcha\Settings\Advanced; use HCaptcha\Settings\FormsPage; use HCaptcha\Settings\ListPageBase; use HCaptcha\Settings\PluginSettingsBase; @@ -386,12 +387,18 @@ public function test_section_callback_when_not_allowed(): void {

      It is an example of the Forms page.

      -

      Want to see form statistics? Please turn on the Statistics switch on the General settings page.

      +

      Want to see form statistics? Please turn on the Statistics switch on the Advanced settings page.

      '; $subject = Mockery::mock( FormsPage::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); + $settings = Mockery::mock( Settings::class ); + $settings->shouldReceive( 'tab_url' )->with( Advanced::class ) + ->andReturn( 'options-general.php?page=hcaptcha&tab=advanced' ); + $main = Mockery::mock( Main::class ); + $main->shouldReceive( 'settings' )->andReturn( $settings ); + WP_Mock::userFunction( 'hcaptcha' )->with()->andReturn( $main ); WP_Mock::passthruFunction( 'admin_url' ); WP_Mock::passthruFunction( 'wp_kses_post' ); diff --git a/tests/php/unit/Settings/GeneralTest.php b/tests/php/unit/Settings/GeneralTest.php index 94644c5fd..3a137445d 100644 --- a/tests/php/unit/Settings/GeneralTest.php +++ b/tests/php/unit/Settings/GeneralTest.php @@ -18,10 +18,11 @@ use HCaptcha\Main; use HCaptcha\MigrationWizard\DetectionResult; use HCaptcha\MigrationWizard\MigrationWizard; -use HCaptcha\Settings\PluginSettingsBase; -use KAGG\Settings\Abstracts\SettingsBase; +use HCaptcha\Settings\Advanced; use HCaptcha\Settings\General; +use HCaptcha\Settings\PluginSettingsBase; use HCaptcha\Settings\Settings; +use KAGG\Settings\Abstracts\SettingsBase; use HCaptcha\Tests\Unit\HCaptchaTestCase; use Mockery; use ReflectionException; @@ -222,7 +223,7 @@ static function ( $type, $name ) use ( $nonce ) { $subject->shouldReceive( 'update_option' )->once()->with( 'set_min_submit_time', [ 'on' ] ); $subject->shouldReceive( 'update_option' )->once()->with( 'antispam', [ 'on' ] ); $subject->shouldReceive( 'auto_migration' )->once(); - $subject->shouldReceive( 'update_option' )->once()->with( OnboardingWizard::OPTION_NAME, 'step 8' ); + $subject->shouldReceive( 'update_option' )->once()->with( OnboardingWizard::OPTION_NAME, 'step 9' ); $subject->shouldReceive( 'tab_url' )->once()->with( $subject )->andReturn( 'https://test.test/wp-admin/admin.php?page=hcaptcha' ); $subject->shouldReceive( 'redirect_after_onboarding_auto_setup' ) ->once() @@ -274,7 +275,7 @@ static function ( $type, $name ) use ( $nonce ) { $subject->shouldReceive( 'update_option' )->once()->with( 'set_min_submit_time', [ 'on' ] ); $subject->shouldReceive( 'update_option' )->never()->with( 'antispam', [ 'on' ] ); $subject->shouldReceive( 'auto_migration' )->once(); - $subject->shouldReceive( 'update_option' )->once()->with( OnboardingWizard::OPTION_NAME, 'step 8' ); + $subject->shouldReceive( 'update_option' )->once()->with( OnboardingWizard::OPTION_NAME, 'step 9' ); $subject->shouldReceive( 'tab_url' )->once()->with( $subject )->andReturn( 'https://test.test/wp-admin/admin.php?page=hcaptcha' ); $subject->shouldReceive( 'redirect_after_onboarding_auto_setup' ) ->once() @@ -520,10 +521,24 @@ public function test_init_form_fields(): void { WP_Mock::userFunction( 'is_multisite' )->andReturn( false ); WP_Mock::userFunction( 'number_format_i18n' )->with( 10000 )->andReturn( '10,000' ); - $expected = $this->get_test_general_form_fields(); - $subject->init_form_fields(); - self::assertSame( $expected, $this->get_protected_property( $subject, 'form_fields' ) ); + $fields = $this->get_protected_property( $subject, 'form_fields' ); + + self::assertSame( General::SECTION_KEYS, $fields['mode']['section'] ); + self::assertSame( General::SECTION_KEYS, $fields['site_key']['section'] ); + self::assertSame( General::SECTION_KEYS, $fields['reset_notifications']['section'] ); + self::assertSame( '', $fields['check_config']['label'] ?? '' ); + self::assertSame( 'Check Site Config', $fields['check_config']['text'] ); + self::assertSame( '', $fields['reset_notifications']['label'] ); + self::assertSame( 'Reset Notifications', $fields['reset_notifications']['text'] ); + self::assertSame( + [ 'site_key', 'secret_key', 'sample_hcaptcha', 'mode', 'check_config', 'reset_notifications' ], + array_slice( array_keys( $fields ), 0, 6 ) + ); + self::assertArrayHasKey( 'custom_themes', $fields ); + self::assertArrayNotHasKey( 'api_host', $fields ); + self::assertArrayNotHasKey( 'protect_content', $fields ); + self::assertArrayNotHasKey( 'statistics', $fields ); } /** @@ -538,6 +553,7 @@ public function test_init_form_fields(): void { public function test_setup_fields( string $mode ): void { $settings = Mockery::mock( Settings::class )->makePartial(); $settings->shouldReceive( 'get_mode' )->andReturn( $mode ); + $settings->shouldReceive( 'get_license' )->andReturn( 'free' ); $main = Mockery::mock( Main::class )->makePartial(); $main->shouldReceive( 'settings' )->andReturn( $settings ); @@ -545,10 +561,16 @@ public function test_setup_fields( string $mode ): void { $subject = Mockery::mock( General::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); $subject->shouldReceive( 'is_options_screen' )->andReturn( true ); + $subject->shouldReceive( 'get' )->with( 'site_key' )->andReturn( '' ); + $subject->shouldReceive( 'get' )->with( 'secret_key' )->andReturn( '' ); $this->set_protected_property( $subject, 'form_fields', $this->get_test_form_fields() ); + $notifications = Mockery::mock( Notifications::class )->makePartial(); + $notifications->shouldReceive( 'has_dismissed_notifications' )->never(); + $this->set_protected_property( $subject, 'notifications', $notifications ); WP_Mock::passthruFunction( 'register_setting' ); WP_Mock::passthruFunction( 'add_settings_field' ); + WP_Mock::userFunction( 'wp_get_current_user' )->andReturn( (object) [ 'ID' => 1 ] ); WP_Mock::userFunction( 'hcaptcha' )->with()->once()->andReturn( $main ); @@ -560,6 +582,11 @@ public function test_setup_fields( string $mode ): void { self::assertArrayHasKey( 'class', $form_field ); } + self::assertFalse( $form_fields['theme']['disabled'] ); + self::assertFalse( $form_fields['size']['disabled'] ); + self::assertFalse( $form_fields['language']['disabled'] ); + self::assertSame( 'hcaptcha-general-reset-notifications hidden', $form_fields['reset_notifications']['class'] ); + if ( General::MODE_LIVE === $mode ) { $form_fields['site_key']['disabled'] = true; $form_fields['secret_key']['disabled'] = true; @@ -585,16 +612,16 @@ public function dp_test_setup_fields(): array { * Test setup_fields() permissions by license. * * @param string $license License level. - * @param bool $enterprise_disabled Whether Enterprise fields are disabled. * @param bool $custom_disabled Whether Custom Themes is disabled. + * @param bool $has_dismissed Whether an active notification was dismissed. * * @dataProvider dp_test_setup_fields_by_license * @throws ReflectionException ReflectionException. */ public function test_setup_fields_by_license( string $license, - bool $enterprise_disabled, - bool $custom_disabled + bool $custom_disabled, + bool $has_dismissed ): void { $settings = Mockery::mock( Settings::class )->makePartial(); $settings->shouldReceive( 'get_mode' )->andReturn( General::MODE_LIVE ); @@ -606,23 +633,25 @@ public function test_setup_fields_by_license( $subject = Mockery::mock( General::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); $subject->shouldReceive( 'is_options_screen' )->andReturn( true ); + $subject->shouldReceive( 'get' )->with( 'site_key' )->andReturn( 'site-key' ); + $subject->shouldReceive( 'get' )->with( 'secret_key' )->andReturn( 'secret-key' ); $this->set_protected_property( $subject, 'form_fields', $this->get_test_form_fields() ); + $notifications = Mockery::mock( Notifications::class )->makePartial(); + $notifications->shouldReceive( 'has_dismissed_notifications' )->once()->andReturn( $has_dismissed ); + $this->set_protected_property( $subject, 'notifications', $notifications ); WP_Mock::passthruFunction( 'register_setting' ); WP_Mock::passthruFunction( 'add_settings_field' ); + WP_Mock::userFunction( 'wp_get_current_user' )->andReturn( (object) [ 'ID' => 1 ] ); WP_Mock::userFunction( 'hcaptcha' )->with()->once()->andReturn( $main ); $subject->setup_fields(); $form_fields = $this->get_protected_property( $subject, 'form_fields' ); - foreach ( $form_fields as $form_field ) { - if ( General::SECTION_ENTERPRISE === ( $form_field['section'] ?? '' ) ) { - self::assertSame( $enterprise_disabled, $form_field['disabled'] ); - } - } - self::assertSame( $custom_disabled, $form_fields['custom_themes']['disabled'] ); + self::assertFalse( $form_fields['theme']['disabled'] ); + self::assertSame( 'hcaptcha-general-reset-notifications' . ( $has_dismissed ? '' : ' hidden' ), $form_fields['reset_notifications']['class'] ); } /** @@ -632,9 +661,10 @@ public function test_setup_fields_by_license( */ public function dp_test_setup_fields_by_license(): array { return [ - 'Free' => [ 'free', true, true ], - 'Pro' => [ 'pro', true, false ], - 'Enterprise' => [ 'enterprise', false, false ], + 'Free' => [ 'free', true, true ], + 'Pro' => [ 'pro', false, true ], + 'Enterprise' => [ 'enterprise', false, true ], + 'No active dismissal' => [ 'free', true, false ], ]; } @@ -673,13 +703,30 @@ public function test_section_callback( string $section_id, string $expected ): v WP_Mock::userFunction( 'hcaptcha' )->with()->andReturn( $main ); $notifications = Mockery::mock( Notifications::class )->makePartial(); - $subject = Mockery::mock( General::class )->makePartial(); + $is_advanced = in_array( + $section_id, + [ General::SECTION_ENTERPRISE, General::SECTION_CONTENT, General::SECTION_OTHER, General::SECTION_STATISTICS ], + true + ); + $subject = Mockery::mock( $is_advanced ? Advanced::class : General::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); - $this->set_protected_property( $subject, 'notifications', $notifications ); + if ( ! $is_advanced ) { + $this->set_protected_property( $subject, 'notifications', $notifications ); + } if ( General::SECTION_KEYS === $section_id ) { - $notifications->shouldReceive( 'show' )->once(); + $notifications->shouldReceive( 'show' )->with( true )->once(); + } else { + $notifications->shouldReceive( 'show' )->never(); + } + + if ( General::SECTION_KEYS === $section_id ) { + $subject->shouldReceive( 'tab_url' )->andReturn( 'https://example.org/wp-admin/options-general.php?page=hcaptcha' ); + $subject->shouldReceive( 'get' )->andReturn( '' ); + WP_Mock::userFunction( 'wp_create_nonce' )->andReturn( 'nonce' ); + WP_Mock::userFunction( 'add_query_arg' )->andReturn( 'https://example.org/wp-admin/options-general.php?page=hcaptcha&onboarding=1' ); + WP_Mock::passthruFunction( 'esc_url' ); } WP_Mock::userFunction( 'wp_get_current_user' )->andReturn( $user ); @@ -688,7 +735,81 @@ public function test_section_callback( string $section_id, string $expected ): v ob_start(); $subject->section_callback( [ 'id' => $section_id ] ); - self::assertSame( $expected, ob_get_clean() ); + $output = ob_get_clean(); + + if ( General::SECTION_KEYS === $section_id ) { + self::assertStringContainsString( 'hcaptcha-section-keys', $output ); + return; + } + + if ( General::SECTION_APPEARANCE === $section_id ) { + self::assertStringContainsString( 'hcaptcha-section-appearance"', $output ); + self::assertStringNotContainsString( 'hcaptcha-keys-save', $output ); + return; + } + + if ( $is_advanced ) { + self::assertStringContainsString( 'hcaptcha-section-' . $section_id, $output ); + return; + } + + self::assertSame( $expected, $output ); + } + + /** + * Setup notification is shown until both live keys have been saved. + * + * @param string $site_key Saved site key. + * @param string $secret_key Saved secret key. + * @param bool $show_guidance Whether to show the setup notification. + * + * @dataProvider dp_test_keys_section_guidance + */ + public function test_keys_section_guidance( string $site_key, string $secret_key, bool $show_guidance ): void { + $settings = Mockery::mock( Settings::class )->makePartial(); + $settings->shouldReceive( 'get_license' )->andReturn( 'free' ); + + $main = Mockery::mock( Main::class )->makePartial(); + $main->shouldReceive( 'settings' )->andReturn( $settings ); + WP_Mock::userFunction( 'hcaptcha' )->andReturn( $main ); + + $notifications = Mockery::mock( Notifications::class )->makePartial(); + $notifications->shouldReceive( 'show' ) + ->withArgs( + static function ( bool $setup_only = false ) use ( $show_guidance ): bool { + return $setup_only === $show_guidance; + } + ) + ->once(); + + $subject = Mockery::mock( General::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'get' )->andReturnUsing( + static function ( string $key ) use ( $site_key, $secret_key ): string { + return 'site_key' === $key ? $site_key : $secret_key; + } + ); + $this->set_protected_property( $subject, 'notifications', $notifications ); + + ob_start(); + $subject->section_callback( [ 'id' => General::SECTION_KEYS ] ); + $output = ob_get_clean(); + + self::assertStringContainsString( 'hcaptcha-section-keys', $output ); + } + + /** + * Key combinations for setup guidance visibility. + * + * @return array + */ + public function dp_test_keys_section_guidance(): array { + return [ + 'no keys' => [ '', '', true ], + 'site only' => [ 'site-key', '', true ], + 'secret only' => [ '', 'secret-key', true ], + 'both keys' => [ 'site-key', 'secret-key', false ], + ]; } /** @@ -803,7 +924,7 @@ public function test_enterprise_section_callback_by_license( string $license, bo WP_Mock::userFunction( 'wp_get_current_user' )->andReturn( $user ); WP_Mock::userFunction( 'get_user_meta' )->andReturn( [] ); - $subject = Mockery::mock( General::class )->makePartial(); + $subject = Mockery::mock( Advanced::class )->makePartial(); $subject->shouldAllowMockingProtectedMethods(); ob_start(); @@ -1039,18 +1160,18 @@ public function test_settings_fields(): void { */ public function test_checkbox_helper_styles(): void { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents - $styles = file_get_contents( dirname( __DIR__, 4 ) . '/assets/css/general.css' ); + $styles = file_get_contents( dirname( __DIR__, 4 ) . '/assets/css/advanced.css' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $base_styles = file_get_contents( dirname( __DIR__, 4 ) . '/assets/css/settings-base.css' ); self::assertIsString( $styles ); self::assertIsString( $base_styles ); self::assertStringContainsString( - ".hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics td {\n\twidth: max-content;\n\tmin-width: 0;\n}", + ".hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics td {\n\twidth: max-content;\n\tmin-width: 0;\n}", $styles ); self::assertStringContainsString( - ".hcaptcha-section-statistics + table tbody tr.hcaptcha-general-statistics .helper-content {\n\tmax-width: calc(100vw - 40px);\n\twhite-space: normal;\n\toverflow-wrap: anywhere;", + ".hcaptcha-section-statistics + table tbody tr.hcaptcha-advanced-statistics .helper-content {\n\tmax-width: calc(100vw - 40px);\n\twhite-space: normal;\n\toverflow-wrap: anywhere;", $styles ); self::assertStringContainsString( diff --git a/tests/php/unit/Settings/IntegrationsDependencyTest.php b/tests/php/unit/Settings/IntegrationsDependencyTest.php index bc9fbc481..aa764b80d 100644 --- a/tests/php/unit/Settings/IntegrationsDependencyTest.php +++ b/tests/php/unit/Settings/IntegrationsDependencyTest.php @@ -23,23 +23,12 @@ */ class IntegrationsDependencyTest extends HCaptchaTestCase { /** - * Test command palette exposes only the anti-spam overview control. + * Test command palette excludes the retired anti-spam overview control. */ public function test_command_palette_form_fields(): void { $subject = Mockery::mock( Integrations::class )->makePartial(); - $subject->shouldAllowMockingProtectedMethods(); - $field = [ - 'type' => 'checkbox', - 'label' => 'Coverage', - ]; - $subject->shouldReceive( 'form_fields' )->once()->andReturn( - [ - 'show_antispam_coverage' => $field, - 'other' => [ 'type' => 'text' ], - ] - ); - self::assertSame( [ 'show_antispam_coverage' => $field ], $subject->command_palette_form_fields() ); + self::assertSame( [], $subject->command_palette_form_fields() ); } /** diff --git a/tests/php/unit/Settings/IntegrationsTest.php b/tests/php/unit/Settings/IntegrationsTest.php index 5dda79a54..3e6f1969b 100644 --- a/tests/php/unit/Settings/IntegrationsTest.php +++ b/tests/php/unit/Settings/IntegrationsTest.php @@ -409,10 +409,7 @@ static function ( $name ) use ( $plugin_url ) { $form_fields = $this->get_protected_property( $subject, 'form_fields' ); - reset( $form_fields ); - $first_key = key( $form_fields ); - - self::assertSame( 'show_antispam_coverage', $first_key ); + self::assertArrayNotHasKey( 'show_antispam_coverage', $form_fields ); foreach ( $form_fields as $form_field ) { if ( Integrations::SECTION_HEADER === ( $form_field['section'] ?? '' ) ) { @@ -440,6 +437,52 @@ public function test_setup_fields_not_on_options_screen(): void { $subject->shouldReceive( 'is_options_screen' )->andReturn( false ); $subject->setup_fields(); + $subject->setup_sections(); + } + + /** + * Test the header is registered before the integration sections without a header field. + * + * @throws ReflectionException ReflectionException. + */ + public function test_setup_sections(): void { + $page = 'hcaptcha-integrations'; + $sections = []; + $subject = Mockery::mock( Integrations::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'is_options_screen' )->andReturn( true ); + $subject->shouldReceive( 'get_active_tab' )->andReturn( $subject ); + $subject->shouldReceive( 'option_page' )->andReturn( $page ); + $this->set_protected_property( + $subject, + 'form_fields', + [ + 'wp_status' => [ + 'section' => Integrations::SECTION_ENABLED, + 'title' => '', + ], + 'acfe_status' => [ + 'section' => Integrations::SECTION_DISABLED, + 'title' => '', + ], + ] + ); + + WP_Mock::userFunction( 'add_settings_section' ) + ->with( Mockery::type( 'string' ), '', [ $subject, 'section_callback' ], $page ) + ->times( 3 ) + ->andReturnUsing( + static function ( string $id ) use ( &$sections ): void { + $sections[] = $id; + } + ); + + $subject->setup_sections(); + + self::assertSame( + [ Integrations::SECTION_HEADER, Integrations::SECTION_ENABLED, Integrations::SECTION_DISABLED ], + $sections + ); } /** @@ -493,9 +536,9 @@ public function test_search_box(): void { } /** - * Test settings_page() when no antispam method is enabled. + * Test settings_page() does not add an antispam indicator notice. */ - public function test_settings_page_adds_antispam_notice(): void { + public function test_settings_page_without_antispam_notice(): void { global $wp_settings_sections; $page = 'hcaptcha-integrations'; @@ -542,8 +585,8 @@ static function ( string $name ): string { ob_get_clean(); self::assertSame( - '

      Enable Honeypot or Time check in the Anti-Spam tab to use indicators.

      ', - $wp_settings_sections[ $page ][ Integrations::SECTION_HEADER ]['after_section'] + [], + $wp_settings_sections[ $page ][ Integrations::SECTION_HEADER ] ); } @@ -576,9 +619,9 @@ public function test_section_callback( string $id, string $expected ): void { } /** - * Test section_callback() when antispam coverage is visible. + * Test section_callback() ignores the saved antispam coverage setting. */ - public function test_section_callback_enabled_with_antispam_legend_visible(): void { + public function test_section_callback_enabled_without_antispam_legend(): void { WP_Mock::passthruFunction( 'esc_attr' ); WP_Mock::passthruFunction( 'wp_kses_post' ); @@ -597,7 +640,8 @@ public function test_section_callback_enabled_with_antispam_legend_visible(): vo $subject->section_callback( [ 'id' => Integrations::SECTION_ENABLED ] ); $output = ob_get_clean(); - self::assertStringContainsString( 'style="display: block;"', $output ); + self::assertStringNotContainsString( 'hcaptcha-antispam-legend', $output ); + self::assertStringNotContainsString( 'antispam-honeypot', $output ); } /** @@ -629,9 +673,7 @@ public function dp_test_section_callback(): array { ], 'enabled' => [ Integrations::SECTION_ENABLED, - ' -
      + '

      Active plugins and themes

      ', ], @@ -651,15 +693,15 @@ public function dp_test_section_callback(): array { /** * Test admin_enqueue_scripts(). * - * @param bool $activated Plugin activated status. + * @param bool $activated Plugin activated status. + * @param string $min_suffix Asset suffix. * * @throws ReflectionException ReflectionException. * @dataProvider dp_test_admin_enqueue_scripts */ - public function test_admin_enqueue_scripts( bool $activated ): void { + public function test_admin_enqueue_scripts( bool $activated, string $min_suffix ): void { $plugin_url = 'http://test.test/wp-content/plugins/hcaptcha-wordpress-plugin'; $plugin_version = '1.0.0'; - $min_suffix = '.min'; $ajax_url = 'https://test.test/wp-admin/admin-ajax.php'; $nonce = 'some_nonce'; $cf7_status = 'cf7_status'; @@ -716,6 +758,10 @@ static function ( $name ) use ( $plugin_url, $plugin_version ) { return $plugin_version; } + if ( 'HCAPTCHA_PATH' === $name ) { + return HCAPTCHA_TEST_PATH; + } + return ''; } ); @@ -811,12 +857,14 @@ static function ( $name ) use ( $plugin_url, $plugin_version ) { ) ->once(); + $style_version = $plugin_version . ( '' === $min_suffix ? '-' . filemtime( HCAPTCHA_TEST_PATH . '/assets/css/integrations.css' ) : '' ); + WP_Mock::userFunction( 'wp_enqueue_style' ) ->with( Integrations::HANDLE, $plugin_url . "/assets/css/integrations$min_suffix.css", [ PluginSettingsBase::PREFIX . '-' . SettingsBase::HANDLE, Integrations::DIALOG_HANDLE ], - $plugin_version + $style_version ) ->once(); @@ -830,23 +878,33 @@ static function ( $name ) use ( $plugin_url, $plugin_version ) { */ public function dp_test_admin_enqueue_scripts(): array { return [ - [ true ], - [ false ], + [ true, '.min' ], + [ false, '.min' ], + [ false, '' ], ]; } /** - * Test antispam helper styles keep the icon beside its label. + * Test saving integrations preserves the retired option value. */ - public function test_antispam_helper_styles(): void { - // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents - $styles = file_get_contents( dirname( __DIR__, 4 ) . '/assets/css/integrations.css' ); + public function test_save_preserves_antispam_coverage(): void { + $form_fields = $this->get_test_form_fields(); + self::assertArrayNotHasKey( 'show_antispam_coverage', $form_fields ); - self::assertIsString( $styles ); - self::assertStringContainsString( - "#hcaptcha-options .hcaptcha-integrations-show-antispam-coverage td {\n\twidth: max-content;\n}", - $styles - ); + $subject = Mockery::mock( Integrations::class )->makePartial(); + $subject->shouldAllowMockingProtectedMethods(); + $subject->shouldReceive( 'form_fields' )->andReturn( $form_fields ); + $subject->shouldReceive( 'get_network_wide' )->andReturn( [] ); + $subject->shouldReceive( 'is_network_wide' )->andReturn( false ); + + WP_Mock::userFunction( 'current_user_can' )->with( 'manage_network_options' )->andReturn( true ); + + $old_value = [ 'show_antispam_coverage' => [ 'on' ] ]; + $value = [ 'wp_status' => [ 'comment' ] ]; + $result = $subject->pre_update_option_filter( $value, $old_value ); + + self::assertSame( [ 'on' ], $result['show_antispam_coverage'] ); + self::assertSame( [ 'comment' ], $result['wp_status'] ); } /** @@ -3497,6 +3555,47 @@ public function test_get_checkbox_option_id(): void { ); } + /** + * Keep section headers ahead of their integration fields. + */ + public function test_sort_fields_places_section_header_first(): void { + $fields = [ + 'plugin' => [ + 'label' => 'Plugin', + 'section' => Integrations::SECTION_ENABLED, + ], + 'header' => [ + 'label' => 'Header', + 'section' => Integrations::SECTION_HEADER, + ], + ]; + + $subject = IntegrationsTestSubject::make(); + self::assertSame( [ 'header', 'plugin' ], array_keys( $subject->sort_fields( $fields ) ) ); + } + + /** + * Return the one-based option index for a registered checkbox. + */ + public function test_get_checkbox_option_id_for_existing_option(): void { + $subject = IntegrationsTestSubject::make(); + $this->set_protected_property( + $subject, + 'form_fields', + [ + 'woocommerce_status' => [ + 'options' => [ + 'login' => 'Login', + 'checkout' => 'Checkout', + ], + ], + ] + ); + + $method = $this->set_method_accessibility( $subject, 'get_checkbox_option_id' ); + self::assertSame( 'woocommerce_status_2', $method->invoke( $subject, 'woocommerce_status', 'checkout' ) ); + } + /** * Test prepare_antispam_data() with native and hcaptcha entries where hcaptcha is enabled. */ diff --git a/tests/php/unit/Settings/SettingsTransferTest.php b/tests/php/unit/Settings/SettingsTransferTest.php index ca8b4b785..0822abd46 100644 --- a/tests/php/unit/Settings/SettingsTransferTest.php +++ b/tests/php/unit/Settings/SettingsTransferTest.php @@ -310,10 +310,10 @@ public function test_wp_cli_preserves_network_wide_settings_without_user(): void $settings = Mockery::mock( Settings::class ); $main = Mockery::mock( Main::class ); - $general->shouldReceive( 'get_network_wide' )->withNoArgs()->times( 3 )->andReturn( [ 'on' ] ); - $general->shouldReceive( 'form_fields' )->withNoArgs()->once()->andReturn( [] ); + $general->shouldReceive( 'get_network_wide' )->withNoArgs()->andReturn( [ 'on' ] ); + $general->shouldReceive( 'form_fields' )->withNoArgs()->twice()->andReturn( [] ); $general->shouldReceive( 'option_name' ) - ->withNoArgs()->times( 5 )->andReturn( PluginSettingsBase::OPTION_NAME ); + ->withNoArgs()->andReturn( PluginSettingsBase::OPTION_NAME ); $settings->shouldReceive( 'get_plugin_name' )->withNoArgs()->once()->andReturn( 'hCaptcha for WP' ); $settings->shouldReceive( 'get_tab' )->with( General::class )->once()->andReturn( $general ); $settings->shouldReceive( 'get_raw_settings' )->withNoArgs()->once()->andReturn( $old_settings ); @@ -329,11 +329,23 @@ public function test_wp_cli_preserves_network_wide_settings_without_user(): void ->with( PluginSettingsBase::OPTION_NAME, [] )->twice()->andReturn( $old_settings ); WP_Mock::userFunction( 'update_site_option' ) ->with( PluginSettingsBase::OPTION_NAME . '_network_wide', [ 'on' ] )->once(); - WP_Mock::userFunction( 'remove_filter' ) + WP_Mock::userFunction( 'has_filter' ) ->with( 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME, [ $general, 'pre_update_option_filter' ] + )->once()->andReturn( 23 ); + WP_Mock::userFunction( 'remove_filter' ) + ->with( + 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME, + [ $general, 'pre_update_option_filter' ], + 23 )->once(); + WP_Mock::expectFilterAdded( + 'pre_update_site_option_' . PluginSettingsBase::OPTION_NAME, + [ $general, 'pre_update_option_filter' ], + 23, + 2 + ); WP_Mock::userFunction( 'update_site_option' ) ->with( PluginSettingsBase::OPTION_NAME, $new_settings )->once(); WP_Mock::userFunction( 'update_option' )->never(); diff --git a/tests/php/unit/Settings/SystemInfoTest.php b/tests/php/unit/Settings/SystemInfoTest.php index f6034040d..cab3d55da 100644 --- a/tests/php/unit/Settings/SystemInfoTest.php +++ b/tests/php/unit/Settings/SystemInfoTest.php @@ -329,10 +329,6 @@ public function test_get_system_info(): void { 4.0.0: Started 5.0.0: Failed ---- Integrations header info --- - - Show Anti-Spam Indicators: Off - --- Active plugins and themes --- Contact Form 7: @@ -633,9 +629,13 @@ public function test_get_system_info(): void { "; - $integration_fields = $this->get_test_integrations_form_fields(); - $integration_settings = $this->get_test_settings(); - $integrations_enabled = [ 'wp_status', 'cf7_status' ]; + $integration_fields = $this->get_test_integrations_form_fields(); + $integration_settings = $this->get_test_settings(); + $integration_fields['section_header'] = [ + 'label' => 'Section Header', + 'section' => Integrations::SECTION_HEADER, + ]; + $integrations_enabled = [ 'wp_status', 'cf7_status' ]; foreach ( $integration_fields as $key => & $field ) { if ( 'header' === ( $field['section'] ?? '' ) ) { diff --git a/tests/php/unit/SimpleDownloadMonitor/FormTest.php b/tests/php/unit/SimpleDownloadMonitor/FormTest.php index d28243138..7e05b37fb 100644 --- a/tests/php/unit/SimpleDownloadMonitor/FormTest.php +++ b/tests/php/unit/SimpleDownloadMonitor/FormTest.php @@ -29,8 +29,9 @@ public function test_constructor_and_init_hooks(): void { $instance = new AnyInstance( Form::class ); WP_Mock::expectFilterAdded( 'sdm_download_shortcode_output', [ $instance, 'add_captcha' ], 10, 2 ); - WP_Mock::expectActionAdded( 'init', [ $instance, 'verify' ], 0 ); + WP_Mock::expectActionAdded( 'sdm_download_via_direct_post', [ $instance, 'verify' ], 0 ); WP_Mock::expectActionAdded( 'wp_print_footer_scripts', [ $instance, 'enqueue_scripts' ], 9 ); + WP_Mock::expectFilterAdded( 'script_loader_tag', [ $instance, 'add_type_module' ], 10, 3 ); new Form(); } @@ -55,6 +56,7 @@ public function test_add_captcha(): void { $args = []; $subject = ( new ReflectionClass( Form::class ) )->newInstanceWithoutConstructor(); + WP_Mock::userFunction( 'absint' )->with( '00123' )->andReturn( 123 ); FunctionMocker::replace( '\HCaptcha\Helpers\HCaptcha::get_class_source', [ 'source' ] ); FunctionMocker::replace( '\HCaptcha\Helpers\HCaptcha::form', @@ -65,7 +67,7 @@ static function ( array $form_args ) use ( &$args ): string { } ); - self::assertSame( 'captcha' . $output, $subject->add_captcha( $output, [ 'id' => 123 ] ) ); + self::assertSame( 'captcha' . $output, $subject->add_captcha( $output, [ 'id' => '00123' ] ) ); self::assertSame( [ 'action' => 'hcaptcha_simple_download_monitor', @@ -79,20 +81,6 @@ static function ( array $form_args ) use ( &$args ): string { ); } - /** - * Test verify() without a download request. - * - * @throws ReflectionException Reflection exception. - */ - public function test_verify_without_download_request(): void { - $verify_post_data = FunctionMocker::replace( '\HCaptcha\Helpers\API::verify_post_data' ); - $subject = ( new ReflectionClass( Form::class ) )->newInstanceWithoutConstructor(); - - $subject->verify(); - - $verify_post_data->wasNotCalled(); - } - /** * Test verify(). * @@ -100,7 +88,8 @@ public function test_verify_without_download_request(): void { */ public function test_verify(): void { $get_data = [ - 'sdm_process_download' => '1', + 'sdm_process_download' => '1.0', + 'download_id' => '00123', 'h-captcha-response' => 'response-token', 'hcaptcha-widget-id' => 'widget-id', 'hcaptcha_simple_download_monitor_nonce' => 'nonce', @@ -114,10 +103,12 @@ public function test_verify(): void { WP_Mock::passthruFunction( 'sanitize_text_field' ); WP_Mock::passthruFunction( 'wp_unslash' ); + WP_Mock::userFunction( 'absint' )->with( '00123' )->andReturn( 123 ); + FunctionMocker::replace( '\HCaptcha\Helpers\HCaptcha::get_class_source', [ 'source' ] ); FunctionMocker::replace( '\HCaptcha\Helpers\API::verify_post_data', - static function ( string $name, string $action, array $data ) use ( &$actual ): ?string { - $actual = [ $name, $action, $data ]; + static function ( string $name, string $action, array $data, array $expected_id ) use ( &$actual ): ?string { + $actual = [ $name, $action, $data, $expected_id ]; return null; } @@ -131,6 +122,127 @@ static function ( string $name, string $action, array $data ) use ( &$actual ): 'hcaptcha_simple_download_monitor_nonce', 'hcaptcha_simple_download_monitor', $get_data, + [ + 'source' => [ 'source' ], + 'form_id' => 123, + ], + ], + $actual + ); + } + + /** + * Missing download IDs still carry a nonempty expected widget identity. + * + * @throws ReflectionException Reflection exception. + */ + public function test_verify_without_download_id_checks_widget_identity(): void { + $_GET = []; + $_REQUEST = []; + $actual = []; + + FunctionMocker::replace( '\HCaptcha\Helpers\HCaptcha::get_class_source', [ 'source' ] ); + FunctionMocker::replace( + '\HCaptcha\Helpers\API::verify_post_data', + static function ( string $name, string $action, array $data, array $expected_id ) use ( &$actual ): ?string { + $actual = $expected_id; + + return null; + } + ); + + $subject = ( new ReflectionClass( Form::class ) )->newInstanceWithoutConstructor(); + $subject->verify(); + + self::assertSame( + [ + 'source' => [ 'source' ], + 'form_id' => 0, + ], + $actual + ); + } + + /** + * Bind verification to the native request target when it differs from GET. + * + * @throws ReflectionException Reflection exception. + */ + public function test_verify_uses_native_request_target(): void { + $_GET = [ + 'sdm_process_download' => '1', + 'download_id' => '00123', + 'hcaptcha-widget-id' => 'widget-for-download-123', + ]; + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $_REQUEST = array_merge( $_GET, [ 'download_id' => '00456' ] ); + $actual = []; + + WP_Mock::passthruFunction( 'sanitize_text_field' ); + WP_Mock::passthruFunction( 'wp_unslash' ); + WP_Mock::userFunction( 'absint' )->with( '00456' )->andReturn( 456 ); + FunctionMocker::replace( '\HCaptcha\Helpers\HCaptcha::get_class_source', [ 'source' ] ); + FunctionMocker::replace( + '\HCaptcha\Helpers\API::verify_post_data', + static function ( string $name, string $action, array $data, array $expected_id ) use ( &$actual ): ?string { + $actual = [ $data, $expected_id ]; + + return null; + } + ); + + $subject = ( new ReflectionClass( Form::class ) )->newInstanceWithoutConstructor(); + $subject->verify(); + + self::assertSame( + [ + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $_GET, + [ + 'source' => [ 'source' ], + 'form_id' => 456, + ], + ], + $actual + ); + } + + /** + * Bind malformed array IDs to the same numeric ID as the native handler. + * + * @throws ReflectionException Reflection exception. + * @noinspection PhpArrayWriteIsNotUsedInspection + */ + public function test_verify_binds_array_target_to_native_id(): void { + $_GET = [ + 'sdm_process_download' => '1.0', + 'download_id' => '00456', + ]; + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $_REQUEST = [ + 'sdm_process_download' => '1.0', + 'download_id' => [ '00123' ], + ]; + $actual = []; + + WP_Mock::userFunction( 'absint' )->with( [ '00123' ] )->andReturn( 1 ); + FunctionMocker::replace( '\HCaptcha\Helpers\HCaptcha::get_class_source', [ 'source' ] ); + FunctionMocker::replace( + '\HCaptcha\Helpers\API::verify_post_data', + static function ( string $name, string $action, array $data, array $expected_id ) use ( &$actual ): ?string { + $actual = $expected_id; + + return null; + } + ); + + $subject = ( new ReflectionClass( Form::class ) )->newInstanceWithoutConstructor(); + $subject->verify(); + + self::assertSame( + [ + 'source' => [ 'source' ], + 'form_id' => 1, ], $actual ); @@ -146,11 +258,12 @@ public function test_verify_with_error(): void { $error = 'Verification failed.'; $get_data = [ 'h-captcha-response' => 'response-token' ]; $_GET = $get_data; - $_REQUEST = [ 'smd_process_download' => '1' ]; + $_REQUEST = [ 'smd_process_download' => '1.0' ]; $actual_data = []; WP_Mock::passthruFunction( 'sanitize_text_field' ); WP_Mock::passthruFunction( 'wp_unslash' ); + FunctionMocker::replace( '\HCaptcha\Helpers\HCaptcha::get_class_source', [ 'source' ] ); WP_Mock::userFunction( 'esc_html' )->with( $error )->once()->andReturn( $error ); WP_Mock::userFunction( 'wp_die' ) ->with( @@ -164,8 +277,8 @@ public function test_verify_with_error(): void { ->once(); FunctionMocker::replace( '\HCaptcha\Helpers\API::verify_post_data', - static function ( string $name, string $action, array $data ) use ( $error, &$actual_data ): string { - $actual_data = [ $name, $action, $data ]; + static function ( string $name, string $action, array $data, array $expected_id ) use ( $error, &$actual_data ): string { + $actual_data = [ $name, $action, $data, $expected_id ]; return $error; } @@ -179,6 +292,10 @@ static function ( string $name, string $action, array $data ) use ( $error, &$ac 'hcaptcha_simple_download_monitor_nonce', 'hcaptcha_simple_download_monitor', $get_data, + [ + 'source' => [ 'source' ], + 'form_id' => 0, + ], ], $actual_data ); @@ -232,4 +349,39 @@ public function dp_test_enqueue_scripts(): array { 'shown' => [ true, 1 ], ]; } + + /** + * The source script needs module loading, while the bundled script stays classic. + * + * @noinspection JSUnresolvedLibraryURL + */ + public function test_add_type_module(): void { + $subject = ( new ReflectionClass( Form::class ) )->newInstanceWithoutConstructor(); + // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- This is a script tag fixture. + $tag = ''; + + WP_Mock::userFunction( 'hcap_min_suffix' )->with()->andReturn( '' ); + + self::assertSame( + // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- This is the expected script tag. + '', + $subject->add_type_module( $tag, 'hcaptcha-simple-download-monitor', '' ) + ); + self::assertSame( $tag, $subject->add_type_module( $tag, 'other', '' ) ); + } + + /** + * The bundled script does not need module loading. + * + * @noinspection JSUnresolvedLibraryURL + */ + public function test_add_type_module_minified(): void { + $subject = ( new ReflectionClass( Form::class ) )->newInstanceWithoutConstructor(); + // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- This is a script tag fixture. + $tag = ''; + + WP_Mock::userFunction( 'hcap_min_suffix' )->with()->andReturn( '.min' ); + + self::assertSame( $tag, $subject->add_type_module( $tag, 'hcaptcha-simple-download-monitor', '' ) ); + } } diff --git a/tests/php/unit/WooCommercePayPalPayments/ButtonTest.php b/tests/php/unit/WooCommercePayPalPayments/ButtonTest.php index 3ee4a379a..f8c5c82d8 100644 --- a/tests/php/unit/WooCommercePayPalPayments/ButtonTest.php +++ b/tests/php/unit/WooCommercePayPalPayments/ButtonTest.php @@ -153,6 +153,131 @@ public function test_script_filters(): void { self::assertSame( '