diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml index 55202ba..a037063 100644 --- a/.github/workflows/phpunit.yml +++ b/.github/workflows/phpunit.yml @@ -41,7 +41,7 @@ jobs: composer-options: --prefer-dist --no-progress - name: Setup wp-env - run: wp-env start + run: wp-env start --config=.wp-env.tests.json env: WP_ENV_CORE: WordPress/WordPress#${{ matrix.wp }} WP_ENV_PHP_VERSION: ${{ matrix.php }} diff --git a/.gitignore b/.gitignore index ee951f3..e282cf8 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,7 @@ vendor/* !vendor/composer/ !vendor/masterminds/ !vendor/symfony/ + +# Local wp-env overrides +.wp-env.override.json +.wp-env.tests.override.json diff --git a/.wp-env.json b/.wp-env.json index dafab87..b535397 100644 --- a/.wp-env.json +++ b/.wp-env.json @@ -1,5 +1,6 @@ { "plugins": [ "." - ] + ], + "testsEnvironment": false } diff --git a/.wp-env.tests.json b/.wp-env.tests.json new file mode 100644 index 0000000..ae64b9c --- /dev/null +++ b/.wp-env.tests.json @@ -0,0 +1,7 @@ +{ + "plugins": [ + "." + ], + "port": 8889, + "testsEnvironment": false +} diff --git a/AGENTS.md b/AGENTS.md index 3bf970e..737bb2b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,7 +135,8 @@ These are the plugin's extension points: ```bash npm -g install @wordpress/env composer install -wp-env start +wp-env start # Development site from .wp-env.json +wp-env start --config=.wp-env.tests.json # Separate test environment ``` ### Running Tests @@ -146,7 +147,7 @@ composer test-multisite # Run tests in multisite mode composer test-watch # Watch mode (requires nodemon) ``` -Tests use PHPUnit 9.5 inside a WordPress environment via `@wordpress/env`. The base test class `RegistryTestCase` (in `tests/registry-test-case.php`) extends `WP_UnitTestCase` and auto-unregisters non-core blocks after each test. +Tests use PHPUnit 9.5 inside a WordPress environment via `@wordpress/env`. The test environment is a separate wp-env instance started from `.wp-env.tests.json` (port 8889), with its own containers and database. The WordPress test suite resets the database it runs against, which is why it is kept apart from the development site. `.wp-env.json` sets `testsEnvironment` to `false` because wp-env has deprecated its built-in dual development/tests setup in favor of separate config files. The base test class `RegistryTestCase` (in `tests/registry-test-case.php`) extends `WP_UnitTestCase` and auto-unregisters non-core blocks after each test. ### Linting diff --git a/README.md b/README.md index c68309b..747046d 100644 --- a/README.md +++ b/README.md @@ -293,6 +293,8 @@ The Block Data API integrates with **WPGraphQL** to provide a GraphQL API. It is Once WPGraphQL has been installed and setup, a new field called `blocksDataV2` will be available for post types that provide content, like posts, pages, etc. +The `blocksDataV2` field follows WPGraphQL's access rules for the queried post. When WPGraphQL restricts a post for the current user, the field resolves to `null`. Password-protected posts also require the current user to have permission to edit the post, because the field parses raw `post_content`. This matches the REST endpoint behavior. + For information on the legacy `blocksData` (v1) field, see [the README from plugin version `1.2.4`][repo-readme-1.2.4]. #### Usage @@ -1568,10 +1570,10 @@ composer install --no-dev ### Tests -Run tests locally with [`wp-env`][wp-env] and Docker: +Run tests locally with [`wp-env`][wp-env] and Docker. Tests run in a dedicated environment defined by `.wp-env.tests.json`, so they never touch the development site started from `.wp-env.json`: ``` -wp-env start +wp-env start --config=.wp-env.tests.json composer install composer run test ``` diff --git a/composer.json b/composer.json index dc70e34..8d55d48 100644 --- a/composer.json +++ b/composer.json @@ -6,8 +6,8 @@ "scripts": { "phpcs": "phpcs", "phpcs-fix": "phpcbf", - "test": "wp-env run tests-cli --env-cwd=wp-content/plugins/vip-block-data-api ./vendor/bin/phpunit", - "test-multisite": "wp-env run tests-cli --env-cwd=wp-content/plugins/vip-block-data-api /bin/bash -c 'WP_MULTISITE=1 ./vendor/bin/phpunit'", + "test": "wp-env run cli --config=.wp-env.tests.json --env-cwd=wp-content/plugins/vip-block-data-api ./vendor/bin/phpunit", + "test-multisite": "wp-env run cli --config=.wp-env.tests.json --env-cwd=wp-content/plugins/vip-block-data-api /bin/bash -c 'WP_MULTISITE=1 ./vendor/bin/phpunit'", "test-watch": [ "Composer\\Config::disableProcessTimeout", "nodemon -w ./ --ignore vendor/ -e php --exec 'composer run test'" diff --git a/src/graphql/graphql-api-v1.php b/src/graphql/graphql-api-v1.php index e09a8df..800efa3 100644 --- a/src/graphql/graphql-api-v1.php +++ b/src/graphql/graphql-api-v1.php @@ -8,6 +8,7 @@ namespace WPCOMVIP\BlockDataApi; use GraphQLRelay\Relay; +use WP_Post; defined( 'ABSPATH' ) || die(); @@ -29,11 +30,17 @@ public static function init() { * * @param \WPGraphQL\Model\Post $post_model Post model for post. * - * @return array + * @return array|\Exception|null Block data, an exception for parser errors, or null when the + * current user is not allowed to read the post's content. */ public static function get_blocks_data( $post_model ) { - $post_id = $post_model->ID; - $post = get_post( $post_id ); + $post = self::get_readable_post( $post_model ); + + if ( null === $post ) { + return null; + } + + $post_id = $post->ID; $content_parser = new ContentParser(); @@ -54,6 +61,42 @@ public static function get_blocks_data( $post_model ) { return $parser_results; } + /** + * Resolve the WP_Post behind a GraphQL post model when the current user is allowed to + * read its raw content. + * + * @param \WPGraphQL\Model\Post $post_model Post model for post. + * + * @return WP_Post|null The post, or null if its content must not be returned. + */ + private static function get_readable_post( $post_model ) { + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- WPGraphQL field name. + if ( isset( $post_model->isRestricted ) && true === $post_model->isRestricted ) { + return null; + } + + $post_id = $post_model->ID; + + if ( empty( $post_id ) ) { + return null; + } + + $post = get_post( intval( $post_id ) ); + + if ( ! $post instanceof WP_Post ) { + return null; + } + + // WPGraphQL withholds the content field for password-protected posts. Since this + // resolver parses raw post_content, require edit access before returning that content. + // This matches the REST endpoint's password-protected post handling. + if ( ! empty( $post->post_password ) && ! current_user_can( 'edit_post', $post->ID ) ) { + return null; + } + + return $post; + } + /** * Transform the block's format to the format expected by the graphQL API. * diff --git a/src/graphql/graphql-api-v2.php b/src/graphql/graphql-api-v2.php index ef5acda..5548fd4 100644 --- a/src/graphql/graphql-api-v2.php +++ b/src/graphql/graphql-api-v2.php @@ -8,6 +8,7 @@ namespace WPCOMVIP\BlockDataApi; use GraphQLRelay\Relay; +use WP_Post; defined( 'ABSPATH' ) || die(); @@ -29,11 +30,17 @@ public static function init() { * * @param \WPGraphQL\Model\Post $post_model Post model for post. * - * @return array + * @return array|\Exception|null Block data, an exception for parser errors, or null when the + * current user is not allowed to read the post's content. */ public static function get_blocks_data( $post_model ) { - $post_id = $post_model->ID; - $post = get_post( $post_id ); + $post = self::get_readable_post( $post_model ); + + if ( null === $post ) { + return null; + } + + $post_id = $post->ID; $content_parser = new ContentParser(); @@ -55,6 +62,42 @@ public static function get_blocks_data( $post_model ) { return $parser_results; } + /** + * Resolve the WP_Post behind a GraphQL post model when the current user is allowed to + * read its raw content. + * + * @param \WPGraphQL\Model\Post $post_model Post model for post. + * + * @return WP_Post|null The post, or null if its content must not be returned. + */ + private static function get_readable_post( $post_model ) { + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- WPGraphQL field name. + if ( isset( $post_model->isRestricted ) && true === $post_model->isRestricted ) { + return null; + } + + $post_id = $post_model->ID; + + if ( empty( $post_id ) ) { + return null; + } + + $post = get_post( intval( $post_id ) ); + + if ( ! $post instanceof WP_Post ) { + return null; + } + + // WPGraphQL withholds the content field for password-protected posts. Since this + // resolver parses raw post_content, require edit access before returning that content. + // This matches the REST endpoint's password-protected post handling. + if ( ! empty( $post->post_password ) && ! current_user_can( 'edit_post', $post->ID ) ) { + return null; + } + + return $post; + } + /** * Transform the block's format to the format expected by the graphQL API. * diff --git a/tests/graphql/test-graphql-api-v1.php b/tests/graphql/test-graphql-api-v1.php index 5380e96..a422b74 100644 --- a/tests/graphql/test-graphql-api-v1.php +++ b/tests/graphql/test-graphql-api-v1.php @@ -8,6 +8,9 @@ namespace WPCOMVIP\BlockDataApi; use GraphQLRelay\Relay; +use WP_Post; + +require_once dirname( __DIR__ ) . '/mocks/graphql-post-model-mock.php'; /** * Tests for the GraphQL API. @@ -482,4 +485,120 @@ public function test_flatten_inner_blocks() { $this->assertEquals( $expected_blocks, $flattened_blocks ); } + + // Access control tests + + private function create_post_with_marker( string $marker, string $post_password = '' ): WP_Post { + $this->register_block_with_attributes( 'test/custom-paragraph', [ + 'content' => [ + 'type' => 'rich-text', + 'source' => 'rich-text', + 'selector' => 'p', + '__experimentalRole' => 'content', + ], + ] ); + + return $this->factory()->post->create_and_get( [ + 'post_title' => 'Post with marker', + 'post_type' => 'post', + 'post_content' => sprintf( '
%s
', $marker ), + 'post_status' => 'publish', + 'post_password' => $post_password, + ] ); + } + + public function test_get_blocks_data__returns_blocks_for_unrestricted_post_model() { + $marker = 'public-post-model-marker'; + $post = $this->create_post_with_marker( $marker ); + + wp_set_current_user( 0 ); + + $blocks_data = GraphQLApiV1::get_blocks_data( new GraphQLPostModelMock( $post, false ) ); + + $this->assertIsArray( $blocks_data ); + $this->assertStringContainsString( $marker, wp_json_encode( $blocks_data ) ); + } + + public function test_get_blocks_data__returns_null_for_restricted_post_model() { + $marker = 'restricted-post-model-marker'; + $post = $this->create_post_with_marker( $marker, 'synthetic-password' ); + + wp_set_current_user( 0 ); + + // WPGraphQL sets the global post to the post being resolved before running field + // resolvers. A restricted model withholds its ID, and get_post( null ) would otherwise + // fall back to this global post. + $post_model = new GraphQLPostModelMock( $post, true ); + $this->assertNull( $post_model->ID ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- WPGraphQL field name. + $this->assertTrue( $post_model->isRestricted ); + + $blocks_data = $this->get_blocks_data_with_global_post( $post_model, $post ); + + $this->assertNull( $blocks_data ); + } + + public function test_get_blocks_data__returns_null_for_post_model_without_id() { + $marker = 'missing-id-post-model-marker'; + $post = $this->create_post_with_marker( $marker ); + + wp_set_current_user( 0 ); + + $post_model = new GraphQLPostModelMock( $post, false, [ 'ID' => null ] ); + $blocks_data = $this->get_blocks_data_with_global_post( $post_model, $post ); + + $this->assertNull( $blocks_data ); + } + + /** + * @dataProvider user_without_edit_access_provider + */ + public function test_get_blocks_data__returns_null_for_password_protected_post_without_edit_access( $role ) { + $marker = 'password-protected-content-marker'; + $post = $this->create_post_with_marker( $marker, 'synthetic-password' ); + + $user_id = '' === $role ? 0 : $this->factory()->user->create( [ 'role' => $role ] ); + wp_set_current_user( $user_id ); + + $blocks_data = GraphQLApiV1::get_blocks_data( $post ); + + wp_set_current_user( 0 ); + + $this->assertNull( $blocks_data ); + } + + public function user_without_edit_access_provider() { + return [ + 'anonymous' => [ '' ], + 'subscriber' => [ 'subscriber' ], + 'non-owner author' => [ 'author' ], + ]; + } + + public function test_get_blocks_data__returns_blocks_for_password_protected_post_when_user_can_edit() { + $marker = 'authorized-password-protected-content-marker'; + $post = $this->create_post_with_marker( $marker, 'synthetic-password' ); + + $user_id = $this->factory()->user->create( [ 'role' => 'editor' ] ); + wp_set_current_user( $user_id ); + + $blocks_data = GraphQLApiV1::get_blocks_data( new GraphQLPostModelMock( $post, false ) ); + + wp_set_current_user( 0 ); + + $this->assertIsArray( $blocks_data ); + $this->assertStringContainsString( $marker, wp_json_encode( $blocks_data ) ); + } + + private function get_blocks_data_with_global_post( $post_model, WP_Post $global_post ) { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited + $GLOBALS['post'] = $global_post; + + try { + return GraphQLApiV1::get_blocks_data( $post_model ); + } finally { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited + $GLOBALS['post'] = null; + } + } } diff --git a/tests/graphql/test-graphql-api-v2.php b/tests/graphql/test-graphql-api-v2.php index 53e5e2c..9d32464 100644 --- a/tests/graphql/test-graphql-api-v2.php +++ b/tests/graphql/test-graphql-api-v2.php @@ -8,6 +8,9 @@ namespace WPCOMVIP\BlockDataApi; use GraphQLRelay\Relay; +use WP_Post; + +require_once dirname( __DIR__ ) . '/mocks/graphql-post-model-mock.php'; /** * Tests for the GraphQL API. @@ -625,4 +628,120 @@ public function test_flatten_blocks() { $this->assertEquals( $expected_blocks, $flattened_blocks ); } + + // Access control tests + + private function create_post_with_marker( string $marker, string $post_password = '' ): WP_Post { + $this->register_block_with_attributes( 'test/custom-paragraph', [ + 'content' => [ + 'type' => 'rich-text', + 'source' => 'rich-text', + 'selector' => 'p', + '__experimentalRole' => 'content', + ], + ] ); + + return $this->factory()->post->create_and_get( [ + 'post_title' => 'Post with marker', + 'post_type' => 'post', + 'post_content' => sprintf( '%s
', $marker ), + 'post_status' => 'publish', + 'post_password' => $post_password, + ] ); + } + + public function test_get_blocks_data__returns_blocks_for_unrestricted_post_model() { + $marker = 'public-post-model-marker'; + $post = $this->create_post_with_marker( $marker ); + + wp_set_current_user( 0 ); + + $blocks_data = GraphQLApiV2::get_blocks_data( new GraphQLPostModelMock( $post, false ) ); + + $this->assertIsArray( $blocks_data ); + $this->assertStringContainsString( $marker, wp_json_encode( $blocks_data ) ); + } + + public function test_get_blocks_data__returns_null_for_restricted_post_model() { + $marker = 'restricted-post-model-marker'; + $post = $this->create_post_with_marker( $marker, 'synthetic-password' ); + + wp_set_current_user( 0 ); + + // WPGraphQL sets the global post to the post being resolved before running field + // resolvers. A restricted model withholds its ID, and get_post( null ) would otherwise + // fall back to this global post. + $post_model = new GraphQLPostModelMock( $post, true ); + $this->assertNull( $post_model->ID ); + // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- WPGraphQL field name. + $this->assertTrue( $post_model->isRestricted ); + + $blocks_data = $this->get_blocks_data_with_global_post( $post_model, $post ); + + $this->assertNull( $blocks_data ); + } + + public function test_get_blocks_data__returns_null_for_post_model_without_id() { + $marker = 'missing-id-post-model-marker'; + $post = $this->create_post_with_marker( $marker ); + + wp_set_current_user( 0 ); + + $post_model = new GraphQLPostModelMock( $post, false, [ 'ID' => null ] ); + $blocks_data = $this->get_blocks_data_with_global_post( $post_model, $post ); + + $this->assertNull( $blocks_data ); + } + + /** + * @dataProvider user_without_edit_access_provider + */ + public function test_get_blocks_data__returns_null_for_password_protected_post_without_edit_access( $role ) { + $marker = 'password-protected-content-marker'; + $post = $this->create_post_with_marker( $marker, 'synthetic-password' ); + + $user_id = '' === $role ? 0 : $this->factory()->user->create( [ 'role' => $role ] ); + wp_set_current_user( $user_id ); + + $blocks_data = GraphQLApiV2::get_blocks_data( $post ); + + wp_set_current_user( 0 ); + + $this->assertNull( $blocks_data ); + } + + public function user_without_edit_access_provider() { + return [ + 'anonymous' => [ '' ], + 'subscriber' => [ 'subscriber' ], + 'non-owner author' => [ 'author' ], + ]; + } + + public function test_get_blocks_data__returns_blocks_for_password_protected_post_when_user_can_edit() { + $marker = 'authorized-password-protected-content-marker'; + $post = $this->create_post_with_marker( $marker, 'synthetic-password' ); + + $user_id = $this->factory()->user->create( [ 'role' => 'editor' ] ); + wp_set_current_user( $user_id ); + + $blocks_data = GraphQLApiV2::get_blocks_data( new GraphQLPostModelMock( $post, false ) ); + + wp_set_current_user( 0 ); + + $this->assertIsArray( $blocks_data ); + $this->assertStringContainsString( $marker, wp_json_encode( $blocks_data ) ); + } + + private function get_blocks_data_with_global_post( $post_model, WP_Post $global_post ) { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited + $GLOBALS['post'] = $global_post; + + try { + return GraphQLApiV2::get_blocks_data( $post_model ); + } finally { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited + $GLOBALS['post'] = null; + } + } } diff --git a/tests/mocks/graphql-post-model-mock.php b/tests/mocks/graphql-post-model-mock.php new file mode 100644 index 0000000..d603220 --- /dev/null +++ b/tests/mocks/graphql-post-model-mock.php @@ -0,0 +1,79 @@ + + */ + private array $fields; + + /** + * Constructor. + * + * @param WP_Post $post The post being modeled. + * @param bool $is_restricted Whether WPGraphQL would restrict this model for the current user. + * @param array $field_overrides Optional. Field values to override before restriction is applied. + */ + public function __construct( WP_Post $post, bool $is_restricted, array $field_overrides = [] ) { + $this->fields = array_merge( [ + 'ID' => $post->ID, + 'databaseId' => $post->ID, + 'hasPassword' => ! empty( $post->post_password ), + 'isRestricted' => $is_restricted, + 'content' => $post->post_content, + ], $field_overrides ); + + if ( $is_restricted ) { + $this->fields = array_intersect_key( $this->fields, array_flip( self::ALLOWED_RESTRICTED_FIELDS ) ); + } + } + + /** + * Mirror WPGraphQL's magic isset. + * + * @param string $key Field name. + * @return bool + */ + public function __isset( $key ) { + return isset( $this->fields[ $key ] ); + } + + /** + * Mirror WPGraphQL's magic getter, which returns null for fields withheld from the model. + * + * @param string $key Field name. + * @return mixed|null + */ + public function __get( $key ) { + if ( ! array_key_exists( $key, $this->fields ) ) { + return null; + } + + return $this->fields[ $key ]; + } +}