#66383 closed defect (bug) (fixed)
Abilities API: Share schema-based input coercion across execution paths
| Reported by: | gziolo | Owned by: | gziolo |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.2 |
| Component: | Abilities API | Version: | trunk |
| Severity: | normal | Keywords: | has-patch has-unit-tests needs-dev-note |
| Cc: | Focuses: |
Description (last modified by )
The Abilities API accepts some input values during schema validation without converting them to the types declared by the schema. For example, array properties can accept comma- or whitespace-separated strings, and object properties can accept PHP stdClass instances.
WP_Ability::validate_input() uses the REST schema validator, which normalizes a temporary copy when validating these values. Direct WP_Ability::execute() calls can therefore pass validation while still passing the original types to permission and execution callbacks.
The REST ability run controller already handles schema-based input coercion following #65594. Move this logic into a shared method on WP_Ability so direct callers and adapters receive consistent behavior without individual abilities repeating normalization.
Coercion should run after successful validation and before permission checks, ensuring permission and execution callbacks receive the same input. Coercing before validation could silently accept invalid input by removing unknown properties or casting invalid values.
Preserve the REST controller's handling of sanitization errors, respect validation filters, and review lifecycle hook ordering and compatibility with callbacks expecting original input types.
Follow-up to #66370, discussed in PR #14722.
Change History (26)
This ticket was mentioned in PR #14882 on WordPress/wordpress-develop by @gziolo.
2 weeks ago
#2
- Keywords has-patch has-unit-tests added
@gziolo commented on PR #14882:
2 weeks ago
#3
@jorgefilipecosta, since REST input coercion was introduced in 7.1, extending the same behavior to direct execute() calls in 7.2 seems like a reasonable follow-up.
One compatibility detail surfaced in testing: rest_sanitize_value_from_schema() casts number values to floats, including native integers. REST already does this, while direct calls currently preserve integers. A callback with strict integer assumptions can therefore work directly but fail through REST today. With shared coercion, both paths receive floats; callbacks must handle those values, or declare integer when that is the intended contract.
This can affect abilities previously exercised only through direct calls, but it gives both paths a consistent input contract. Does that tradeoff look reasonable to you for 7.2?
@gziolo commented on PR #14882:
2 weeks ago
#4
@jorgefilipecosta, addressed the remaining feedback in 468a370c7f. Coercion failures, including nested errors, now return WP_Error before permission checks or execution instead of falling back to raw input; REST uses its existing HTTP 400 handling. Updated regression coverage passes (847 tests, 2,933 assertions), along with PHPCS and PHPStan. Ready for another review. Thanks!
#7
@
2 weeks ago
Edit: new version posted in comment:26.
---
Dev note: Consistent input coercion in the Abilities API in WordPress 7.2
WordPress 7.2 moves input coercion into WP_Ability, giving direct PHP calls and REST requests consistent input handling. Validated input is converted to schema types before permission checks and execution.
How it works
Execution follows this order:
- Normalize input and apply defaults.
- Validate the input.
- Coerce values to the schema types.
- Check permissions.
- Run the ability.
Permission and execution callbacks receive the coerced input.
Coercion uses rest_sanitize_value_from_schema(). For example:
"10"becomes10for anintegerschema."false"becomesfalsefor abooleanschema."1,2"becomes[1, 2]for an array of integers.
It also applies format sanitization, such as stripping HTML tags for text-field.
Validation runs first so coercion cannot hide invalid input. Callers using the new WP_Ability::coerce_input() method directly must validate first. Calling execute() handles these steps automatically.
Number values become floats
A number schema now produces PHP floats in both direct and REST execution. For example, 10 becomes 10.0. This follows existing REST behavior.
Callbacks that require integers should use an integer schema. Callbacks using number should accept floats and avoid strict integer checks such as is_int() or === 10.
Coercion failures return errors
Some inputs pass validation but fail coercion. For example, ["1", "01"] contains distinct strings, but both become 1 when converted to integers. This fails a schema with uniqueItems: true.
Previously, the Abilities REST controller returned the original input when coercion failed. A failure in one field left all fields unchanged. This could pass "false" to a permission callback as a truthy string.
These failures now return WP_Error with the code ability_invalid_input. This also applies to nested errors. Permission and execution callbacks do not run. REST returns HTTP 400 through its existing error handling.
Normal inputs continue to work. Inputs previously accepted through the fallback may now fail. This gives both execution paths the same rule: coercion must succeed before callbacks run.
#10
@
8 days ago
- Resolution fixed
- Status closed → reopened
Hey @gziolo , I've looked over the PR and dev-note, but I'm not sure I'm following.
What exactly is the "bug" here, and is adding another public method (and another downstream execution step) really the best way to address it?
I would assume that if the issue is that ::validate_input() passes despite not adhering to the input schema, then the solution would be to fix the input validation. A coercion helper seems like a potentially nice feature addition for downstream implementations, but making it a required step after validation doesn't solve the fact that ::validate_input() is still broken.
(Reopening so this gets seen before RC1. Once a public method ships in 7.2 it'd be a breaking change to remove it)
#11
@
7 days ago
The bug is that the same input can behave differently depending on how an ability is called. Schema validation accepts certain values that can be converted to the declared type, but it doesn't perform that conversion.
For example, for a boolean field, validation accepts the string "false". REST converts it to boolean false, but direct execute() calls previously passed the string to callbacks, where PHP treats it as true.
The PR keeps the existing REST validation rules and applies the same conversion in both paths. Making validation reject these values is another option, but it would change which inputs are accepted.
Callers using execute() do not need an extra step. It handles coercion automatically.
As for the additional public method, this follows the original Abilities API design, where execute() handles the full lifecycle, while individual public methods operate independently. This was an intentional decision made before the API was merged into Core. For example, input validation was explicitly separated from check_permissions() in Abilities API v0.4.0, allowing integrations to compose the lifecycle steps themselves rather than having individual methods implicitly invoke one another.
The new coerce_input() method follows that existing pattern and allows integrations, including the REST controller, to reuse the same coercion logic. Developers choosing to bypass execute() are responsible for composing the steps they need.
So this fixes inconsistent execution behavior. It doesn't make validate_input() a strict PHP type check.
#12
@
7 days ago
Thanks for clarifying @gziolo 🙇
To confirm I'm following: the bug is that the same input reaches callbacks differently depending on the execution path. I'd frame the root cause as rest_validate_*() accepting inputs the schema doesn't actually describe, which only REST then compensates for. I agree that making validation strict isn't something for 7.2.
(IIRC that was the same root for the AI Client work that produced json-schema.php in 7.1, and I would expect decoupling from the REST baggage to continue in 7.3, with Abilities adopting the new helpers.)
That said, I'm still not sure I follow the fix here. [65044] makes ::execute() itself consistent, not by solving the inconsistency, but by moving it to every consumer that checks permissions manually (which, as you noted, is an explicit decision to support). Each of those consumers now needs to repeat normalize -> validate -> coerce -> check.
- That's the root of #66482. As @zaguiini reported, Ability checks fail over MCP with a
TypeError. (FWIW, that's the same typed-callback concern you raised in 66325#comment:11.) And like the same changes to REST here and MCP Adapter downstream, anybody that's calling the steps individually needs to refactor. - Even with the fix applied and the change to the REST endpoint to compensate, REST now coerces the input 3 separate times, and
wp_ability_{normalize|validate}_inputgets coerced input via REST but raw input via direct calls.
That seems like a lot of known and potential collateral for a change in beta, and it doesn't seem to get to the root of the issue or solve it consistently.
I also don't think ::coerce_input() fits the composability principle. It's not meant to "operate independently": as the docblock notes, it depends on validate_input(). So instead of giving devs something they can call, we're requiring them to call it, and only as part of that sequence.
Building off your point in #66482 (cc @jorbin), if we agree that a public API change this late in the release cycle is justified, a single public function prepare_input( $args ) that encapsulates normalize, validate, and coerce seems to respect that better than a public coercion step:
$input = $ability->prepare_input( $args ); // normalize, validate, convert
if ( is_wp_error( $input ) ) {
return $input;
}
$result = $ability->check_permissions( $input );
- Validation stays separate from authorization, which was the core of that feedback.
- Each step can still be overridden individually, since
prepare_input()calls the existing methods. - Consumers make one call instead of four ordered ones, and the conversion step itself doesn't need to be public.
::execute()and the REST controller use it too, so there's a single path and every filter sees the same input.
Even better, as an additive change, ::prepare_input() could validate strictly from the start. (e.g. but not the only way, ::execute() would call it, and if strict validation fails, fall back to today's lenient validation + coercion and log a deprecation notice. That keeps back-compat for anyone relying on REST's validation quirks, while giving us a path to strict validation.)
Taking inspiration from @jason_the_adams, I'd love to see if there's a way to iterate on this during beta, or failing that, at least demonstrate that this deserves some more discussion. The approach above isn't the only way to solve the problem holistically, and I'm not particularly married to it.
Some options to evaluate:
- Revert [65044] for 7.2 and land a more complete version in 7.3. This would let us drop the MCP and Woo workarounds (and most of #66482), and keep other downstream consumers from needing the same.
- Keep the conversion inside
::execute()for 7.2, and swap the publiccoerce_input()forprepare_input()(or similar). - Demote
coerce_input()toprotectedwith an@internalannotation for 7.2, and keep REST's coercion local to the REST controller. That way::execute()gets the fix now, and the downstream contract can be decided in 7.3 alongside the other options.
(If a standalone conversion method does survive, I'd at least recommend renaming it to ::sanitize_input() to match WordPress's existing validate/sanitize terminology.)
Longer term, I do believe a cleaner split would be strict validation in WP_Ability, with each transport responsible for handling its own idiosyncrasies. Callbacks would always get schema-typed input, and no step would change the input after validation. That would change which inputs are accepted, but so does [65044], so the question is which change has fewer knock-on effects while moving us toward the right design.
(More broadly, several recent tickets trace back to, or are limited by, how WP_Ability and WP_Abilities_Registry encapsulate the lifecycle. At some point we're going to need to address it instead of patching around it.)
To be clear, I agree direct calls should receive converted input. My concern is the public API we're committing to in order to get there, and that impact to downstream consumers and its knock-on effects don't seem justified.
@gziolo what do you think?
cc: @zaguiini @euvoor
#13
@
7 days ago
Thanks @justlevine. I have regression cases covering defaults, typed callbacks and invalid input across all three adapter entry points in https://github.com/WordPress/mcp-adapter/pull/444.
The patch follows the current Core sequence. Those cases can also help evaluate alternative approaches against downstream behavior. I'm happy to adapt the adapter once the Core direction is settled.
#14
@
7 days ago
Thanks @euvoor, that's much appreciated 🙇
(It's also a helpful illustration of the knock-on effects I'm concerned about here, alongside the diff on https://github.com/WordPress/wordpress-develop/pull/15514)
This ticket was mentioned in PR #15684 on WordPress/wordpress-develop by @gziolo.
6 days ago
#15
What
The REST run endpoint now prepares the ability input once, during REST request sanitization. Then the permission check uses it as is.
Before this change, a successful request with input did the work several times:
- REST sanitization validated and coerced the input.
check_ability_permissions()normalized, validated, and coerced it again.WP_Ability::execute()did the full preparation a third time.
Now:
sanitize_input_for_ability()normalizes, validates, and coerces the input. If any step fails, it returns the error, and the request is rejected before permissions are checked. This follows how the REST API handles invalid parameters.check_ability_permissions()only checks permissions. It prepares the input itself only when the input isnull. REST sanitization never runs for absent parameters, because anullargument default is not stored. This is how schema defaults still get applied.- Abilities hidden from REST and requests with the wrong HTTP method are skipped during sanitization. So they still get a 404 or 405 error, not an input error.
WP_Ability::execute()is unchanged.
Behavior change
Invalid input sent with the request is now reported as rest_invalid_param (400). The original error (for example ability_invalid_input, or a code from a filter) is in data.details.input. A custom status from a normalize or validate filter, like 422, is kept in those details. Existing tests were updated for this response shape.
Testing
npm run test:php -- --filter=Abilitpasses.- New tests check that the permission callback gets input prepared once, for both request input and the schema default. They also check that invalid input does not hide the 404 and 405 errors.
Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Implementation, test updates, and new tests, iterated on together with me. I reviewed the final code and tests.
---
This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.
🤖 Generated with Claude Code
This ticket was mentioned in PR #15685 on WordPress/wordpress-develop by @gziolo.
6 days ago
#16
[!NOTE]
This PR is stacked on #15684. It includes that PR's two commits. Only the last commit, "Abilities API: AddWP_Ability::prepare_input()", is new here. The diff will get smaller once #15684 lands.
What
Adds a public WP_Ability::prepare_input() method. It normalizes, validates, and sanitizes the input in one call, and returns the prepared input or the first WP_Error.
execute()usesprepare_input()instead of calling the three steps itself.- The REST run controller calls
prepare_input()in both places that prepare input:sanitize_input_for_ability()and thenullinput branch ofcheck_ability_permissions(). coerce_input()is renamed to the protectedsanitize_input(). Sanitizing input that was not validated can hide validation errors, soprepare_input()is now the public way to run it.coerce_input()was added in 7.2 and has not been released yet, so this is not a breaking change.
Why
Before this change, every caller had to run normalize_input(), validate_input(), and coerce_input() in the right order, and stop at the first error. This was repeated in execute() and twice in the REST controller. check_permissions() also documented the three steps for integrations that call it directly. Now there is one method that does it correctly.
Documentation
The docs now refer to prepare_input() instead of listing each step. This covers the Abilities API overview, check_permissions(), execute(), and the hook docs. Tests about the sanitization step now use "sanitization" in their names, to match the method name. Tests about type conversion keep "coerce".
Testing
npm run test:php -- --filter=Abilitpasses.- Linting and PHPStan pass.
Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Implementation, documentation updates, and test renames, iterated on together with me. I reviewed the final code and tests.
#17
@
6 days ago
Thanks for the feedback. I addressed it in two steps:
- https://github.com/WordPress/wordpress-develop/pull/15684 fixes the REST API handling. The run endpoint now prepares the input once, during request sanitization, and invalid input is rejected there like any other invalid REST parameter. The permission check uses the prepared input as is. It prepares the input itself only when the request has no input, because REST sanitization skips absent parameters.
- https://github.com/WordPress/wordpress-develop/pull/15685 (commit https://github.com/WordPress/wordpress-develop/pull/15685/commits/0fc0606523) adds a public
WP_Ability::prepare_input()method that normalizes, validates, and sanitizes the input in one call.coerce_input()is renamed to the protectedsanitize_input(), so it is no longer public.execute()and the REST controller both useprepare_input()now, so the steps are no longer repeated.
#18
@
6 days ago
Thanks so much @gziolo , it looks muchhhh more intuitive (IMO) and I really appreciate you finding the time to iterate on this so quickly 🙇
At a glance, the only thing I still want to explore is whether there's a way to make the new method strict-by-default so we won't need to deprecate again once REST and JSON validation are fully decoupled, while maintaining backcompat.
(Pseudocode broad-strokes long-term along the lines of:
-
::validate_input( $input, $strict = false ) {...}(or$schema_version = 'wp-rest'etc, with a newWP_Error( 'ability_input_fails_strict_validation', ...) - Inside the new
::prepare_input( $input, $strict = true )(or whatever) we'd call::validiate_input()and handle the error<?php // ::prepare_input() // ... if ( $validated_input instanceof WP_Error && 'ability_input_fails_...' = $prepared_input->get_error_code() ) { _doing_it_wrong( .... ); $validated_input = ::sanitize_input( $raw_input ) } /// ...
... or something. Hopefully with less flags )
I will make time over the weekend to dive in, so I'm not blocking this come the start of your work week on monday.
#19
@
6 days ago
Sounds good to me. I will see if I can get more eyes on these two PRs. I would prefer to commit them before the end of the day, as I will have limited availability next week.
@gziolo commented on PR #15684:
6 days ago
#20
@euvoor @jorgefilipecosta I’ve revised the approach in edbf3ca532.
Looking back at 7.1, coercion happened only in REST sanitization. Trunk now performs coercion in both the permission callback and execute(), making that earlier pass redundant. Moving normalization into sanitization caused the regression you identified: execute() received already-normalized input and normalized it again.
The endpoint now skips input sanitization. The permission callback and execute() independently normalize, validate, and coerce the original raw input. This removes the redundant pass without caching or modifying request parameters.
The public sanitizer shipped in 7.1, so it remains as a deprecated passthrough. Input preparation errors now come directly from the permission callback.
Added regression coverage for non-idempotent normalization, explicit null, absent input, duplicate parameter sources, and repeated dispatches.
@euvoor, could you rerun your targeted cases against this commit? @jorgefilipecosta, could you re-review the revised flow and deprecation handling? The PR description now reflects the implementation.
#21
@
4 days ago
... or something. Hopefully with less flags )
I've been playing around locally, and I think we can instead handle it per-ability registration time, via a meta.json_schema_version: string<SUPPORTED_JSON_SCHEMA_TYPES>.
We'd then consume it as an implementation detail inside ::validate_input() and ::sanitize_input(), instead of needing to pass an explicit prepare_input( $input, $schema_profile = 'rest-api' | 'draft-04' | ... | 'latest' ) at call time.
Downstream WP-flavored REST or other adapters that are laxer than the specific schema used would need to coerce themselves or alternatively add_filter( ... ) to downgrade the version to what the protocol expects. IMO either path would be fine when the times comes, but I would like confirmation so there aren't unnecessary frictions when the time comes to implement.
@gziolo how does that sound to you?
@gziolo commented on PR #15685:
3 days ago
#24
@jorgefilipecosta Good catch, thanks! Both documentation points are addressed in f822e2752c.
@zaguiini A WP_Error can hold multiple failures, but the underlying schema validators currently stop at the first one. I suggest handling aggregation separately in Trac #66436; prepare_input() can pass through the combined error.
#26
@
2 days ago
Dev note: Consistent input sanitization in the Abilities API in WordPress 7.2
WordPress 7.2 moves input sanitization into WP_Ability, so permission and execution callbacks receive input sanitized according to the ability's schema for both direct PHP calls and REST requests.
How it works
WP_Ability::execute() uses the new public WP_Ability::prepare_input() method for the first three steps.
- Normalize input and apply defaults.
- Validate the input.
- Sanitize the validated input.
- Check permissions.
- Run the ability.
Sanitization uses rest_sanitize_value_from_schema() to convert values to the types declared in the input schema.
"10"becomes10for anintegerschema."false"becomesfalsefor abooleanschema."1,2"becomes[1, 2]for an array of integers.
Sanitization also applies format-specific rules, such as stripping HTML tags for text-field. Validation runs first so these changes cannot hide invalid input.
If you call check_permissions() directly, call prepare_input() first. If it returns a WP_Error, stop. Otherwise, pass the prepared input to check_permissions().
The REST run endpoint skips the separate sanitization step for the input request argument. Its permission check and WP_Ability::execute() each prepare the original request input independently. The controller's sanitize_input_for_ability() method is deprecated and returns its input unchanged.
Number values become floats
A number schema now produces PHP floats in direct calls, matching existing REST behavior. For example, 10 becomes 10.0.
Callbacks that require integers should use an integer schema. Callbacks using number should accept floats and avoid strict integer checks such as is_int() or === 10.
Sanitization failures return errors
Some inputs pass validation but fail during sanitization. For example, ["1", "01"] contains distinct strings, but both become 1 when converted to integers. The resulting array violates uniqueItems: true.
Previously, if sanitization failed in one field, the Abilities REST controller returned the original input for all fields. A permission callback could then receive the string "false", which PHP treats as true.
In WordPress 7.2, a sanitization failure, even in a nested field, returns a WP_Error with the code ability_invalid_input before permission or execution callbacks run. REST returns HTTP 400.
Direct
WP_Ability::execute()calls can pass schema validation while callbacks still receive loosely typed input, such as"10"for an integer or"1,2"for an array. REST already coerces these values separately.Add public
WP_Ability::coerce_input()and invoke it after successful validation and before permission checks. Permission and execution callbacks receive the same coerced input. The REST controller delegates to the shared implementation while retaining its existing sanitization entry point, and also coerces normalized defaults before permission checks.Behavior and compatibility
coerce_input()must validate first; the method does not repeat validation or run its filters. Invalid input remains rejected before coercion in the execution lifecycle.uniqueItemscollisions, fall back to the original input.numbervalues to floats, including integer inputs. Direct callbacks with strict integer assumptions can therefore break. The affected registry test fixtures now accept floats, and an explicit regression case documents this behavior.This is a draft for reviewing the shared API and compatibility implications. It follows the core information ability fixes from #14722.
Validation
git diff --checkpassed.Tests cover typed callback input, validation filters, lifecycle hooks, defaults, object and list input, and sanitization-error fallback. Tests ran in single-site mode against the local test database; no end-to-end MCP test was performed.
Use of AI Tools
AI assistance: Yes
Tool: Codex
Used for: Implementation, regression tests, test execution, compatibility analysis, and drafting this PR description.