Skip to content

Commit d1406a3

Browse files
committed
Abilities API: Share input coercion across execution paths
Introduce WP_Ability::coerce_input() to apply schema-based type coercion and format sanitization after validation and before permission checks and execution. Reuse the shared implementation in the REST controller, including for normalized defaults and filter-provided input. Return ability_invalid_input on coercion failures, including nested errors, instead of falling back to raw input. Direct execution now follows REST type semantics, including converting number values to floats. Add regression coverage for coercion, lifecycle ordering, and REST error handling. Developed in #14882. Props gziolo, jorgefilipecosta. Fixes #66383. git-svn-id: https://develop.svn.wordpress.org/trunk@65044 602fd350-edb4-49c9-b593-d223f7449a82
1 parent f9e9686 commit d1406a3

7 files changed

Lines changed: 662 additions & 329 deletions

File tree

‎src/wp-includes/abilities-api/class-wp-ability.php‎

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,76 @@ public function normalize_input( $input = null ) {
562562
return apply_filters( 'wp_ability_normalize_input', $input, $this->name, $this );
563563
}
564564

565+
/**
566+
* Coerces validated input to the types declared in the input schema.
567+
*
568+
* Also applies schema format sanitization, such as stripping tags for
569+
* `text-field` and sanitizing URLs for `uri`, using rest_sanitize_value_from_schema().
570+
*
571+
* Call validate_input() before this method. Coercing unvalidated input can
572+
* remove unknown properties or cast invalid values, hiding validation errors.
573+
* This method does not apply defaults or run input validation filters.
574+
*
575+
* If sanitization produces an error, including in a nested value, an invalid
576+
* input error is returned to prevent execution with uncoerced values.
577+
*
578+
* @since 7.2.0
579+
*
580+
* @see validate_input()
581+
*
582+
* @param mixed $input Validated ability input.
583+
* @return mixed|WP_Error Coerced input, or WP_Error when it cannot be safely coerced.
584+
*/
585+
public function coerce_input( $input ) {
586+
$schema = $this->get_input_schema();
587+
if ( null === $input || empty( $schema ) ) {
588+
return $input;
589+
}
590+
591+
$sanitized = rest_sanitize_value_from_schema( $input, $schema, 'input' );
592+
593+
// Values unique before coercion can collide after casting, even in nested arrays.
594+
$error = self::get_input_error( $sanitized );
595+
if ( is_wp_error( $error ) ) {
596+
return new WP_Error(
597+
'ability_invalid_input',
598+
sprintf(
599+
/* translators: %1$s ability name, %2$s error message. */
600+
__( 'Ability "%1$s" has invalid input. Reason: %2$s' ),
601+
$this->name,
602+
$error->get_error_message()
603+
)
604+
);
605+
}
606+
607+
return $sanitized;
608+
}
609+
610+
/**
611+
* Retrieves the first WP_Error in a sanitized value.
612+
*
613+
* @since 7.2.0
614+
*
615+
* @param mixed $value The value to inspect.
616+
* @return WP_Error|null The first error found, or null if the value contains no errors.
617+
*/
618+
private static function get_input_error( $value ): ?WP_Error {
619+
if ( is_wp_error( $value ) ) {
620+
return $value;
621+
}
622+
623+
if ( is_array( $value ) ) {
624+
foreach ( $value as $item ) {
625+
$error = self::get_input_error( $item );
626+
if ( is_wp_error( $error ) ) {
627+
return $error;
628+
}
629+
}
630+
}
631+
632+
return null;
633+
}
634+
565635
/**
566636
* Validates input data against the input schema.
567637
*
@@ -860,12 +930,13 @@ protected function validate_output( $output ) {
860930
}
861931

862932
/**
863-
* Executes the ability after input validation and running a permission check.
933+
* Executes the ability after input validation, coercion, and a permission check.
864934
* Before returning the return value, it also validates the output.
865935
*
866936
* @since 6.9.0
867937
* @since 7.1.0 Added the `wp_ability_invoked` action.
868938
* @since 7.1.0 Added the `wp_pre_execute_ability` filter.
939+
* @since 7.2.0 Coerces validated input before permission checks and execution.
869940
*
870941
* @param mixed $input Optional. The input data for the ability. Default `null`.
871942
* @return mixed|WP_Error The result of the ability execution, or WP_Error on failure.
@@ -925,6 +996,11 @@ public function execute( $input = null ) {
925996
return $is_valid;
926997
}
927998

999+
$input = $this->coerce_input( $input );
1000+
if ( is_wp_error( $input ) ) {
1001+
return $input;
1002+
}
1003+
9281004
$has_permissions = $this->check_permissions( $input );
9291005
if ( true !== $has_permissions ) {
9301006
if ( is_wp_error( $has_permissions ) ) {
@@ -950,7 +1026,7 @@ public function execute( $input = null ) {
9501026
* @since 7.1.0 Added the `$ability` parameter.
9511027
*
9521028
* @param string $ability_name The name of the ability.
953-
* @param mixed $input The input data for the ability.
1029+
* @param mixed $input The validated and coerced input data for the ability.
9541030
* @param WP_Ability $ability The ability instance.
9551031
*/
9561032
do_action( 'wp_before_execute_ability', $this->name, $input, $this );
@@ -972,7 +1048,7 @@ public function execute( $input = null ) {
9721048
* @since 7.1.0 Added the `$ability` parameter.
9731049
*
9741050
* @param string $ability_name The name of the ability.
975-
* @param mixed $input The input data for the ability.
1051+
* @param mixed $input The validated and coerced input data for the ability.
9761052
* @param mixed $result The result of the ability execution.
9771053
* @param WP_Ability $ability The ability instance.
9781054
*/

‎src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-run-controller.php‎

Lines changed: 14 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,11 @@ public function check_ability_permissions( $request ) {
183183
return $this->ensure_error_status( $is_valid, 400 );
184184
}
185185

186+
$input = $ability->coerce_input( $input );
187+
if ( is_wp_error( $input ) ) {
188+
return $this->ensure_error_status( $input, 400 );
189+
}
190+
186191
$result = $ability->check_permissions( $input );
187192
if ( is_wp_error( $result ) ) {
188193
$result->add_data( array( 'status' => rest_authorization_required_code() ) );
@@ -240,107 +245,31 @@ private function get_input_from_request( $request ) {
240245
/**
241246
* Sanitizes the run input by coercing it to the ability's input schema.
242247
*
243-
* Registered as the `input` argument `sanitize_callback` so that both
244-
* `check_ability_permissions()` and `execute_ability()` receive natively typed input
245-
* regardless of transport.
248+
* Registered as the `input` argument `sanitize_callback` so request input is coerced
249+
* before any route callback runs, regardless of transport. `check_ability_permissions()`
250+
* and `WP_Ability::execute()` coerce the input again after normalization and validation,
251+
* so schema defaults and values from normalization filters are coerced too.
246252
*
247253
* @since 7.1.0
248254
*
249-
* @see WP_REST_Abilities_V1_Run_Controller::coerce_input_to_schema()
255+
* @see WP_Ability::coerce_input()
250256
*
251257
* @param mixed $input Raw input extracted from the request.
252258
* @param WP_REST_Request $request The request object.
253-
* @return mixed Coerced input, or the raw input when it cannot be safely coerced.
259+
* @return mixed|WP_Error Coerced input, raw input when validation fails, or WP_Error when coercion fails.
254260
*/
255261
public function sanitize_input_for_ability( $input, $request ) {
256262
$ability = wp_has_ability( $request['name'] ) ? wp_get_ability( $request['name'] ) : null;
257263
if ( ! $ability instanceof WP_Ability ) {
258264
return $input;
259265
}
260266

261-
return $this->coerce_input_to_schema( $input, $ability );
262-
}
263-
264-
/**
265-
* Coerces raw request input to the types declared in the ability input schema.
266-
*
267-
* GET and DELETE deliver every scalar as a string ("10", "true") and a list as a single
268-
* comma-separated string, so without coercion an ability receives raw strings where its
269-
* schema declares integers, booleans, or arrays.
270-
*
271-
* Coercion never changes what validation accepts. Input is coerced only when
272-
* {@see WP_Ability::validate_input()} already accepts it, and any error surfaced while
273-
* sanitizing falls back to the raw input, so `validate_input()` stays the single authority
274-
* on what is rejected.
275-
*
276-
* @since 7.1.0
277-
*
278-
* @param mixed $input Raw input extracted from the request.
279-
* @param WP_Ability $ability The ability being executed.
280-
* @return mixed Coerced input, or the raw input when it cannot be safely coerced.
281-
*/
282-
private function coerce_input_to_schema( $input, WP_Ability $ability ) {
283-
if ( null === $input ) {
284-
return $input;
285-
}
286-
287-
$schema = $ability->get_input_schema();
288-
if ( empty( $schema ) ) {
289-
return $input;
290-
}
291-
292-
/*
293-
* Only coerce input that already validates. Sanitizing invalid input can silently
294-
* change which values are accepted -- `additionalProperties: false` strips unknown
295-
* keys, and a non-numeric string casts to 0 -- so leaving invalid input untouched
296-
* lets validate_input() reject it exactly as it does without coercion.
297-
*
298-
* validate_input() is asked rather than rest_validate_value_from_schema() so that the
299-
* `wp_ability_validate_input` filter decides what counts as valid here as well. A filter
300-
* that overrides a schema failure accepts the input, so the input is coerced; a filter
301-
* that rejects otherwise valid input leaves it untouched for validate_input() to report.
302-
*/
303-
if ( is_wp_error( $ability->validate_input( $input ) ) ) {
304-
return $input;
305-
}
306-
307-
$sanitized = rest_sanitize_value_from_schema( $input, $schema, 'input' );
308-
309-
/*
310-
* Sanitizing can still surface an error the lenient validation above did not, such as
311-
* items that are unique as strings but collide once cast to integers (`uniqueItems`).
312-
* The error may be returned at the top level or nested inside the returned array, so
313-
* scan recursively and fall back to the raw input on any error.
314-
*/
315-
if ( $this->input_contains_error( $sanitized ) ) {
267+
// Validate before coercion so sanitization cannot rescue invalid input.
268+
if ( null === $input || empty( $ability->get_input_schema() ) || is_wp_error( $ability->validate_input( $input ) ) ) {
316269
return $input;
317270
}
318271

319-
return $sanitized;
320-
}
321-
322-
/**
323-
* Determines whether a sanitized value is, or contains, a WP_Error.
324-
*
325-
* @since 7.1.0
326-
*
327-
* @param mixed $value The value to inspect.
328-
* @return bool True if the value is, or contains, a WP_Error.
329-
*/
330-
private function input_contains_error( $value ): bool {
331-
if ( is_wp_error( $value ) ) {
332-
return true;
333-
}
334-
335-
if ( is_array( $value ) ) {
336-
foreach ( $value as $item ) {
337-
if ( $this->input_contains_error( $item ) ) {
338-
return true;
339-
}
340-
}
341-
}
342-
343-
return false;
272+
return $ability->coerce_input( $input );
344273
}
345274

346275
/**

‎tests/phpunit/tests/abilities-api/wpAbilitiesRegistry.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ public function set_up(): void {
6868
'description' => 'The result of adding the two numbers.',
6969
'required' => true,
7070
),
71-
'execute_callback' => static function ( array $input ): int {
71+
'execute_callback' => static function ( array $input ): float {
7272
return $input['a'] + $input['b'];
7373
},
7474
'permission_callback' => static function (): bool {
@@ -348,7 +348,7 @@ public function test_register_with_custom_ability_class_without_execute_callback
348348
'b' => 3,
349349
)
350350
);
351-
$this->assertSame( 15, $execute_result, 'Custom do_execute should multiply instead of add.' );
351+
$this->assertSame( 15.0, $execute_result, 'Custom do_execute should multiply instead of add.' );
352352
}
353353

354354
/**
@@ -679,7 +679,7 @@ static function ( $args ) use ( &$was_filter_callback_fired ) {
679679
);
680680

681681
$this->assertTrue( $was_filter_callback_fired, 'The execute callback defined in the filter was not fired.' );
682-
$this->assertSame( 3, $result, 'The original execute callback did not return the expected result.' );
682+
$this->assertSame( 3.0, $result, 'The original execute callback did not return the expected result.' );
683683
}
684684

685685
/**

0 commit comments

Comments
 (0)