REST API: Don’t remove unregistered properties from objects in schema.

In r41727 the ability to sanitise and validate objects from JSON schema was added, with a whitelist approach. It was decided we should pass through all non-registered properties to reflect the behaviour of the root object in register_rest_route. To prevent arbitrary extra data via setting objects, we force additionalProperties to false in the settings endpoint.

See #38583.

git-svn-id: https://develop.svn.wordpress.org/trunk@42000 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Joe Hoyle
2017-10-24 21:04:50 +00:00
parent 36f253d1d9
commit fb2e44456e
6 changed files with 118 additions and 13 deletions
@@ -545,7 +545,7 @@ abstract class WP_REST_Controller {
$endpoint_args[ $field_id ]['required'] = true;
}
foreach ( array( 'type', 'format', 'enum', 'items', 'properties' ) as $schema_prop ) {
foreach ( array( 'type', 'format', 'enum', 'items', 'properties', 'additionalProperties' ) as $schema_prop ) {
if ( isset( $params[ $schema_prop ] ) ) {
$endpoint_args[ $field_id ][ $schema_prop ] = $params[ $schema_prop ];
}
@@ -248,6 +248,8 @@ class WP_REST_Settings_Controller extends WP_REST_Controller {
continue;
}
$rest_args['schema'] = $this->set_additional_properties_to_false( $rest_args['schema'] );
$rest_options[ $rest_args['name'] ] = $rest_args;
}
@@ -301,4 +303,32 @@ class WP_REST_Settings_Controller extends WP_REST_Controller {
}
return rest_parse_request_arg( $value, $request, $param );
}
/**
* Recursively add additionalProperties = false to all objects in a schema.
*
* This is need to restrict properties of objects in settings values to only
* registered items, as the REST API will allow additional properties by
* default.
*
* @since 4.9.0
*
* @param array $schema The schema array.
* @return array
*/
protected function set_additional_properties_to_false( $schema ) {
switch ( $schema['type'] ) {
case 'object':
foreach ( $schema['properties'] as $key => $child_schema ) {
$schema['properties'][ $key ] = $this->set_additional_properties_to_false( $child_schema );
}
$schema['additionalProperties'] = false;
break;
case 'array':
$schema['items'] = $this->set_additional_properties_to_false( $schema['items'] );
break;
}
return $schema;
}
}