From 172e0b01c6a6b484091fff9ac588ad8fa7fc24b2 Mon Sep 17 00:00:00 2001 From: "K. Adam White" Date: Fri, 3 Jan 2020 18:42:09 +0000 Subject: [PATCH] REST API: Short-circuit comment controller permissions check if commented-upon post type does not exist. Props imani3011, dragosh635, subrataemfluence, timothyblynjacobs. Fixes #42238. git-svn-id: https://develop.svn.wordpress.org/trunk@47036 602fd350-edb4-49c9-b593-d223f7449a82 --- .../class-wp-rest-comments-controller.php | 8 +++++- .../rest-api/rest-comments-controller.php | 27 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index ca5336f5aa..e05f9802ea 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php @@ -1592,7 +1592,13 @@ class WP_REST_Comments_Controller extends WP_REST_Controller { * @return bool Whether post can be read. */ protected function check_read_post_permission( $post, $request ) { - $post_type = get_post_type_object( $post->post_type ); + $post_type = get_post_type_object( $post->post_type ); + + // Return false if custom post type doesn't exist + if ( ! $post_type ) { + return false; + } + $posts_controller = $post_type->get_rest_controller(); // Ensure the posts controller is specifically a WP_REST_Posts_Controller instance diff --git a/tests/phpunit/tests/rest-api/rest-comments-controller.php b/tests/phpunit/tests/rest-api/rest-comments-controller.php index da2d372a54..46738edc72 100644 --- a/tests/phpunit/tests/rest-api/rest-comments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-comments-controller.php @@ -3240,4 +3240,31 @@ class WP_Test_REST_Comments_Controller extends WP_Test_REST_Controller_Testcase $this->assertArrayNotHasKey( 'raw', $data['content'] ); } } + + /** + * @ticket 42238 + */ + public function test_check_read_post_permission_with_invalid_post_type() { + register_post_type( + 'bug-post', + array( + 'label' => 'Bug Posts', + 'supports' => array( 'title', 'editor', 'author', 'comments' ), + 'show_in_rest' => true, + 'public' => true, + ) + ); + create_initial_rest_routes(); + + $post_id = self::factory()->post->create( array( 'post_type' => 'bug-post' ) ); + $comment_id = self::factory()->comment->create( array( 'comment_post_ID' => $post_id ) ); + _unregister_post_type( 'bug-post' ); + + $this->setExpectedIncorrectUsage( 'map_meta_cap' ); + + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/wp/v2/comments/' . $comment_id ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 403, $response->get_status() ); + } }