Skip to content

Closes #971: Enforce WordPress nonce verification sniffs - #1341

Merged
sandyfzu merged 6 commits into
developfrom
fix/971-nonce-verification
Nov 18, 2026
Merged

sandyfzu merged 6 commits into
developfrom
fix/971-nonce-verification

Conversation

@remyperona

@remyperona remyperona commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Note

This PR was created by an AI agent (Claude Code) and reviewed by a human before merge.

Description

Closes #971

Removes the WordPress.Security.NonceVerification.Missing and .Recommended excludes from phpcs.xml and resolves all 27 reported cases. Where a fix in code made sense, it is in code. A phpcs:ignore remains only where the read changes nothing, and each one has its reason written next to it.

User impact:

  • Settings page: the "Save & Go to Bulk Optimizer" button now redirects only when the request carries a valid settings form nonce. Saving from the real form behaves exactly as before.
  • AJAX requests: a parameter sent with the wrong HTTP method (GET instead of POST, or the reverse) now resolves to 'noop' instead of reading a key that doesn't exist. Before, that raised an undefined-index warning and returned ''. The request is still rejected either way.

Type of change

  • New feature (non-breaking change which adds functionality).
  • Bug fix (non-breaking change which fixes an issue).
  • Enhancement (non-breaking change which improves an existing functionality).
  • Breaking change (fix or feature that would cause existing functionality to not work as before).
  • Sub-task of #(issue number)
  • Chore
  • Release

Detailed scenario

What was tested

Automated:

  • composer phpcs with the two sniffs enabled: no errors on the whole codebase.
  • composer run-stan: no errors.
  • composer test-unit: 604 tests pass. The 2 "risky" results are a version_compare() deprecation in update_site_option_on_network that was already there before this change.
  • Integration suite in wp-env (PHP 8.2, --exclude-group AbilitiesCatalog): 285 tests pass, 37 skipped because they need multisite.
  • New integration tests: one test class per method, each with a single testShouldReturnExpected() and its cases in a Tests/Fixtures file (36 cases):
    • ImagifySettings/maybeSetRedirection: redirects with a valid nonce; no redirect when the nonce is missing, belongs to another action, or the bulk button wasn't clicked.
    • ImagifyAdminAjaxPost/getContext, getFolderType, getImagifyAction and Bulk/getContext: read from the right method, defaults (noop / optimize), method mismatch, array values, sanitization.
    • ImagifyViews/isSettingsPage, isBulkPage, isFilesPage: page detection with and without ?page=, on the right and wrong screens.

No manual browser testing was done.

How to test

  1. composer install, then composer phpcs. Expect no NonceVerification errors.
  2. Run the new tests: vendor/bin/phpunit --configuration Tests/Integration/phpunit.xml.dist --group Bulk,ImagifySettings,ImagifyAdminAjaxPost,ImagifyViews
  3. Manual check: on /wp-admin/options-general.php?page=imagify, click Save & Go to Bulk Optimizer. It should save and land on the Bulk Optimizer. Save Changes should stay on the settings page.
  4. Manual check: in the Media Library list view, filter by an Imagify status (Optimized / Unoptimized / Errors). The list should filter and the dropdown should keep the selected value.
  5. Manual check: on the Bulk Optimizer, run a bulk optimization and confirm the AJAX calls still succeed.

Affected Features & Quality Assurance Scope

  • Settings page: Save & Go to Bulk Optimizer redirect (single site and network).
  • Media Library: Imagify status filter dropdown and the query it filters.
  • Bulk Optimizer AJAX (get_context): bulk optimize, folder type data, bulk info seen.
  • Per-media AJAX actions (optimize, re-optimize, restore, missing sizes, next-gen generate/delete), and custom-folder actions that use get_folder_type / get_imagify_action.
  • Admin page detection (Imagify_Views::is_settings_page / is_bulk_page / is_files_page), which decides which assets and notices load.
  • NextGEN Gallery: bulk page types, asset enqueueing, auto-optimize skip on media library import. Only comments changed on these lines; the logic is unchanged.

Technical description

Documentation

  • Imagify_Settings::maybe_set_redirection() hooks into pre_update_option_imagify_settings, which can fire outside the settings form. It now checks the imagify-options nonce (the action settings_fields() uses) with wp_verify_nonce() before it sets $_REQUEST['_wp_http_referer'].
  • Imagify_Admin_Ajax_Post::get_request_param() (private) is now the only place that reads $_GET / $_POST for get_context(), get_folder_type() and get_imagify_action(). The nonce is checked by the calling AJAX callback, not inside the helper: several callbacks build the nonce action from the very values being read (media ID, context). Bulk::get_context() uses the same pattern inline.
  • Imagify_Views::get_requested_page() (private) is now the only read of $_GET['page'] for page detection.
  • The remaining phpcs:ignore comments are all on read-only code: screen detection, list filters, and NextGEN Gallery's own import request, whose nonce NextGEN checks itself. Legacy // WPCS: CSRF ok. comments, which PHPCS 3 no longer honors, were replaced.
  • AGENTS.md: the trap that said these sniffs are deliberately suppressed now says when an ignore is acceptable.

New dependencies

None.

Risks

  • The settings redirect now depends on the form nonce. Both the single-site form (options.php) and the network form (admin-post.php) post _wpnonce for imagify-options through settings_fields(), so real form submissions are unaffected.
  • On a GET/POST method mismatch, get_context() now returns 'noop' instead of ''. Both values make the callers refuse the request (Noop context or "Invalid request").

Mandatory Checklist

Code validation

  • I validated all the Acceptance Criteria. If possible, provide screenshots or videos.
  • I triggered all changed lines of code at least once without new errors/warnings/notices.
  • I implemented built-in tests to cover the new/changed code.

Code style

  • I wrote a self-explanatory code about what it does.
  • I protected entry points against unexpected inputs.
  • I did not introduce unnecessary complexity.
  • Output messages (errors, notices, logs) are explicit enough for users to understand the issue and are actionnable.

Unticked items justification

The settings, AJAX and page-detection changes are covered by the new integration tests. The NextGEN Gallery lines, the Media Library dropdown and the upload.php filter were not run in a browser. Their logic is unchanged apart from reading the value once, so QA should cover them with the manual steps above.

Additional Checks

  • In the case of complex code, I wrote comments to explain it.
  • When possible, I prepared ways to observe the implemented system (logs, data, etc.)
  • I added error handling logic when using functions that could throw errors (HTTP/API request, filesystem, etc.)

🤖 Generated with Claude Code

Remove the WordPress.Security.NonceVerification.Missing and .Recommended
excludes from phpcs.xml and resolve every reported case.

- Verify the settings form nonce before the "Save & Go to Bulk Optimizer"
  redirect is set.
- Read AJAX request parameters through a single helper; a value sent with
  the other HTTP method now yields 'noop' instead of an undefined index.
- Share one helper for the admin page slug in Imagify_Views.
- Keep a justified phpcs:ignore only for read-only screen detection, list
  filters, values read before the caller's own nonce check, and NextGEN
  Gallery's own import request; drop legacy "WPCS: CSRF ok" comments.
- Add integration tests and update the AGENTS.md trap.

Refs #971

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codacy-production

codacy-production Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity · 0 duplication

Metric Results
Complexity 0
Duplication 0

View in Codacy

🟢 Coverage 72.00% diff coverage

Metric Results
Coverage variation Report missing for af6a7711
Diff coverage ✅ 72.00% diff coverage (50.00%)

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (af6a771) Report Missing Report Missing Report Missing
Head commit (f973f60) 20590 2909 14.13%

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#1341) 25 18 72.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

1 Codacy didn't receive coverage data for the commit, or there was an error processing the received data. Check your integration for errors and validate that your coverage setup is correct.

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Move the request read into a private get_request_param() helper with an
early return, matching Imagify_Admin_Ajax_Post. Resolves the PHPMD
ElseExpression issue reported by Codacy on #1341.

Refs #971

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@remyperona remyperona self-assigned this Nov 12, 2026
@remyperona
remyperona marked this pull request as ready for review November 12, 2026 17:48
remyperona and others added 3 commits November 12, 2026 12:51
Restructure the tests added for #971 to the project standard: one test
class per tested method, a single testShouldReturnExpected() method, and
cases loaded from Tests/Fixtures through configTestData.

Add unit tests next to the integration tests so the changed lines count
toward Codacy diff coverage, which only measures the unit suite:
- Imagify_Admin_Ajax_Post get_context / get_folder_type / get_imagify_action
- Bulk::get_context
- Imagify_Views is_settings_page / is_bulk_page / is_files_page
- Imagify_Settings::maybe_set_redirection

Unit and integration tests for the same method share one fixture file.

Refs #971

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fication

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
develop now reports integration test coverage to Codacy (#1340), so the
unit tests added only to satisfy the diff coverage gate are redundant
with the integration tests sharing their fixtures. Remove them, and move
Bulk::get_context coverage to an integration test on the same fixture.

Refs #971

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@remyperona
remyperona requested a review from a team November 12, 2026 18:01
Comment thread classes/Bulk/Bulk.php Resolved
Bulk and Imagify_Admin_Ajax_Post had identical copies of the request
parameter helper. Move it into Imagify\Traits\RequestParamTrait, used by
both, and point the tests' @Covers at the trait.

Refs #971

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sandyfzu
sandyfzu self-requested a review November 18, 2026 15:56
@sandyfzu
sandyfzu added this pull request to the merge queue Nov 18, 2026
Merged via the queue into develop with commit 8984881 Nov 18, 2026
15 checks passed
@sandyfzu
sandyfzu deleted the fix/971-nonce-verification branch November 18, 2026 19:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Coding Standards: WordPress security nonce verification

3 participants