From 9118845594577d07ef54af6e790aac53253f142e Mon Sep 17 00:00:00 2001 From: Joost de Valk Date: Fri, 13 Nov 2026 20:32:13 +0100 Subject: [PATCH 01/15] Fix security review findings and require header authentication --- assets/js/editor.js | 7 +- assets/js/onboard.js | 1 - classes/admin/widgets/class-challenge.php | 3 +- classes/admin/widgets/class-widget.php | 6 +- classes/class-base.php | 2 +- classes/class-lessons.php | 50 +- classes/class-page-todos.php | 52 +- classes/class-page-types.php | 25 +- classes/class-suggested-tasks.php | 8 +- classes/rest/class-base.php | 44 +- classes/rest/class-page-types-controller.php | 40 ++ .../rest/class-recommendations-controller.php | 31 +- classes/rest/class-stats.php | 12 +- classes/rest/class-tasks.php | 8 +- .../class-remove-terms-without-posts.php | 4 + .../class-update-term-description.php | 4 + classes/ui/class-branding.php | 76 ++- classes/utils/class-onboard.php | 12 +- .../class-integration-test-case.php | 7 +- .../test-rest-api-stats-integration.php | 17 +- .../test-rest-api-tasks-integration.php | 20 +- tests/phpunit/test-class-admin-widget.php | 18 +- .../test-class-branding-preview-param.php | 33 +- tests/phpunit/test-class-branding.php | 5 +- tests/phpunit/test-class-rest-base.php | 16 +- tests/phpunit/test-class-rest-stats.php | 2 +- tests/phpunit/test-class-security-review.php | 448 ++++++++++++++++++ 27 files changed, 817 insertions(+), 134 deletions(-) create mode 100644 classes/rest/class-page-types-controller.php create mode 100644 tests/phpunit/test-class-security-review.php diff --git a/assets/js/editor.js b/assets/js/editor.js index 1bfcd9d8d..ae922d57a 100644 --- a/assets/js/editor.js +++ b/assets/js/editor.js @@ -268,8 +268,7 @@ const PrplLessonItemsHTML = () => { if ( ! editor || typeof editor.getEditedPostAttribute !== 'function' ) { return ''; } - const meta = editor.getEditedPostAttribute( 'meta' ); - return meta ? meta.progress_planner_page_todos : ''; + return editor.getEditedPostAttribute( 'progress_planner_page_todos' ) || ''; }, [] ); const pageTodos = pageTodosMeta || ''; @@ -596,9 +595,7 @@ const PrplCheckListItem = ( item, pageTodos ) => typeof editorDispatch.editPost === 'function' ) { editorDispatch.editPost( { - meta: { - progress_planner_page_todos: toDos.join( ',' ), - }, + progress_planner_page_todos: toDos.join( ',' ), } ); } } diff --git a/assets/js/onboard.js b/assets/js/onboard.js index 529b05831..f3fe63730 100644 --- a/assets/js/onboard.js +++ b/assets/js/onboard.js @@ -13,7 +13,6 @@ * @param {string} licenseKey The license key. */ const progressPlannerSaveLicenseKey = ( licenseKey ) => { - console.log( 'License key: ' + licenseKey ); return progressPlannerAjaxRequest( { url: progressPlanner.ajaxUrl, data: { diff --git a/classes/admin/widgets/class-challenge.php b/classes/admin/widgets/class-challenge.php index 79fc75e87..283f1d98f 100644 --- a/classes/admin/widgets/class-challenge.php +++ b/classes/admin/widgets/class-challenge.php @@ -90,8 +90,7 @@ public function get_cache_key() { public function get_remote_api_url() { return \add_query_arg( [ - 'license_key' => \progress_planner()->get_license_key(), - 'site' => \get_site_url(), + 'site' => \get_site_url(), ], \progress_planner()->get_remote_server_root_url() . '/wp-json/progress-planner-saas/v1/challenges' ); diff --git a/classes/admin/widgets/class-widget.php b/classes/admin/widgets/class-widget.php index 53b4c81a3..b7327466b 100644 --- a/classes/admin/widgets/class-widget.php +++ b/classes/admin/widgets/class-widget.php @@ -62,7 +62,8 @@ public function get_id() { * @return string */ public function get_range() { - return $this->get_sanitized_get( 'range', '-6 months' ); + $range = $this->get_sanitized_get( 'range', '-6 months' ); + return \in_array( $range, [ '-3 months', '-6 months', '-12 months', '-18 months', '-24 months' ], true ) ? $range : '-6 months'; } /** @@ -71,7 +72,8 @@ public function get_range() { * @return string */ public function get_frequency() { - return $this->get_sanitized_get( 'frequency', 'monthly' ); + $frequency = $this->get_sanitized_get( 'frequency', 'monthly' ); + return \in_array( $frequency, [ 'weekly', 'monthly' ], true ) ? $frequency : 'monthly'; } /** diff --git a/classes/class-base.php b/classes/class-base.php index 743da4d76..95f6e65b5 100644 --- a/classes/class-base.php +++ b/classes/class-base.php @@ -107,7 +107,7 @@ public function init() { // `current_user_can()` is only reached on a branded, unlicensed site. if ( ! \wp_doing_cron() && ! $this->get_license_key() - && 0 !== (int) \progress_planner()->get_ui__branding()->get_branding_id() + && 0 !== (int) \progress_planner()->get_ui__branding()->get_branding_id( false ) && \current_user_can( 'manage_options' ) ) { $prpl_license_key = \progress_planner()->get_utils__onboard()->make_remote_onboarding_request(); diff --git a/classes/class-lessons.php b/classes/class-lessons.php index 2373395d0..5265ba24d 100644 --- a/classes/class-lessons.php +++ b/classes/class-lessons.php @@ -56,9 +56,8 @@ public function get_remote_api_items() { $url = \progress_planner()->get_remote_server_root_url() . '/wp-json/progress-planner-saas/v1/lessons'; $url = \add_query_arg( [ - 'site' => \get_site_url(), - 'license_key' => \progress_planner()->get_license_key(), - 'locale' => \apply_filters( 'prpl_lesson_locale', \get_locale() ), + 'site' => \get_site_url(), + 'locale' => \apply_filters( 'prpl_lesson_locale', \get_locale() ), ], $url ); @@ -67,7 +66,7 @@ public function get_remote_api_items() { $cached = \progress_planner()->get_utils__cache()->get( $cache_key ); if ( \is_array( $cached ) ) { - return $cached; + return $this->sanitize_items( $cached ); } $response = \wp_remote_get( $url ); @@ -94,7 +93,48 @@ public function get_remote_api_items() { // Cache successful response for one week. \progress_planner()->get_utils__cache()->set( $cache_key, $json, WEEK_IN_SECONDS ); - return $json; + return $this->sanitize_items( $json ); + } + + /** + * Sanitize remote content on every read, including previously cached lessons. + * + * @param array $items Lesson data. + * @return array + */ + public function sanitize_items( array $items ): array { + foreach ( $items as $key => $value ) { + if ( \is_array( $value ) ) { + $items[ $key ] = $this->sanitize_items( $value ); + } elseif ( \is_string( $value ) ) { + $items[ $key ] = 'video' === $key ? $this->sanitize_video( $value ) : \wp_kses_post( $value ); + } + } + return $items; + } + + /** + * Allow video embeds only from known video players, without active attributes. + * + * @param string $html Video markup. + * @return string + */ + public function sanitize_video( string $html ): string { + $allowed = \wp_kses_allowed_html( 'post' ); + $allowed['iframe'] = \array_fill_keys( [ 'src', 'title', 'width', 'height', 'allowfullscreen', 'frameborder' ], true ); + $html = \wp_kses( $html, $allowed ); + $tags = new \WP_HTML_Tag_Processor( $html ); + while ( $tags->next_tag( 'iframe' ) ) { + $src = $tags->get_attribute( 'src' ); + $host = \is_string( $src ) ? \wp_parse_url( $src, PHP_URL_HOST ) : ''; + if ( ! \is_string( $src ) || 'https' !== \wp_parse_url( $src, PHP_URL_SCHEME ) + || ! \in_array( \strtolower( (string) $host ), [ 'www.youtube.com', 'www.youtube-nocookie.com', 'player.vimeo.com', 'iframe.mediadelivery.net' ], true ) + ) { + $tags->remove_attribute( 'src' ); + } + $tags->set_attribute( 'sandbox', 'allow-scripts allow-same-origin allow-presentation' ); + } + return $tags->get_updated_html(); } /** diff --git a/classes/class-page-todos.php b/classes/class-page-todos.php index 787c0d357..e80e5ddf2 100644 --- a/classes/class-page-todos.php +++ b/classes/class-page-todos.php @@ -17,6 +17,7 @@ class Page_Todos { */ public function __construct() { \add_action( 'init', [ $this, 'init' ] ); + \add_action( 'rest_api_init', [ $this, 'register_rest_fields' ] ); } /** @@ -28,22 +29,65 @@ public function init() { // Add the post-metas to all post-types. $post_types = \get_post_types( [ 'public' => true ], 'objects' ); foreach ( $post_types as $post_type ) { - if ( ! \post_type_supports( $post_type->name, 'custom-fields' ) ) { - \add_post_type_support( $post_type->name, 'custom-fields' ); - } \register_post_meta( $post_type->name, 'progress_planner_page_todos', [ 'type' => 'string', 'single' => true, - 'show_in_rest' => true, + 'show_in_rest' => false, 'sanitize_callback' => [ $this, 'sanitize_post_meta_progress_planner_page_todos' ], ] ); } } + /** + * Expose to-dos only in editable responses without enabling unrelated custom fields. + * + * @return void + */ + public function register_rest_fields() { + \register_rest_field( + \array_keys( \get_post_types( [ 'public' => true ] ) ), + 'progress_planner_page_todos', + [ + 'schema' => [ + 'type' => 'string', + 'context' => [ 'edit' ], + ], + 'get_callback' => [ $this, 'get_rest_todos' ], + 'update_callback' => [ $this, 'update_rest_todos' ], + ] + ); + } + + /** + * Read to-dos for a post the user may edit. + * + * @param array $post Prepared REST post. + * @return string + */ + public function get_rest_todos( $post ) { + return \current_user_can( 'edit_post', $post['id'] ) + ? (string) \get_post_meta( $post['id'], 'progress_planner_page_todos', true ) : ''; + } + + /** + * Update to-dos for a post the user may edit. + * + * @param string $value To-dos. + * @param \WP_Post $post Post being updated. + * @return true|\WP_Error + */ + public function update_rest_todos( $value, $post ) { + if ( ! \current_user_can( 'edit_post', $post->ID ) ) { + return new \WP_Error( 'rest_forbidden', \__( 'You cannot edit this post.', 'progress-planner' ), [ 'status' => \rest_authorization_required_code() ] ); + } + \update_post_meta( $post->ID, 'progress_planner_page_todos', $this->sanitize_post_meta_progress_planner_page_todos( $value ) ); + return true; + } + /** * Sanitize the `progress_planner_page_todos` meta. * diff --git a/classes/class-page-types.php b/classes/class-page-types.php index 2b58d751d..fff857131 100644 --- a/classes/class-page-types.php +++ b/classes/class-page-types.php @@ -54,15 +54,22 @@ public function create_taxonomy() { self::TAXONOMY_NAME, \array_keys( \get_post_types( [ 'public' => true ] ) ), [ - 'public' => false, - 'hierarchical' => false, - 'labels' => [], // Hidden taxonomy, no need for labels. - 'show_ui' => false, - 'show_admin_column' => false, - 'query_var' => true, - 'rewrite' => [ 'slug' => 'site-type' ], - 'show_in_rest' => true, - 'show_in_menu' => false, + 'public' => false, + 'hierarchical' => false, + 'labels' => [], // Hidden taxonomy, no need for labels. + 'show_ui' => false, + 'show_admin_column' => false, + 'query_var' => true, + 'rewrite' => [ 'slug' => 'site-type' ], + 'show_in_rest' => true, + 'rest_controller_class' => \Progress_Planner\Rest\Page_Types_Controller::class, + 'capabilities' => [ + 'manage_terms' => 'manage_options', + 'edit_terms' => 'manage_options', + 'delete_terms' => 'manage_options', + 'assign_terms' => 'edit_posts', + ], + 'show_in_menu' => false, ] ); } diff --git a/classes/class-suggested-tasks.php b/classes/class-suggested-tasks.php index 70542077b..a99a94cc2 100644 --- a/classes/class-suggested-tasks.php +++ b/classes/class-suggested-tasks.php @@ -335,6 +335,10 @@ public function suggested_task_action() { \wp_send_json_error( [ 'message' => \esc_html__( 'You do not have permission to complete this task.', 'progress-planner' ) ] ); } + if ( ! \in_array( $action, [ 'complete', 'pending', 'delete' ], true ) ) { + \wp_send_json_error( [ 'message' => \esc_html__( 'Invalid task action.', 'progress-planner' ) ] ); + } + $updated = false; switch ( $action ) { @@ -359,10 +363,6 @@ public function suggested_task_action() { */ \do_action( "progress_planner_ajax_task_{$action}", $post_id, $updated ); - if ( ! $updated ) { - \wp_send_json_error( [ 'message' => \esc_html__( 'Not saved.', 'progress-planner' ) ] ); - } - \wp_send_json_success( [ 'message' => \esc_html__( 'Saved.', 'progress-planner' ) ] ); } diff --git a/classes/rest/class-base.php b/classes/rest/class-base.php index be58f286b..19aea4eea 100644 --- a/classes/rest/class-base.php +++ b/classes/rest/class-base.php @@ -34,38 +34,36 @@ abstract public function register_rest_endpoint(); * @return string */ protected function get_client_ip() { - $ip_keys = [ - 'HTTP_CF_CONNECTING_IP', // Cloudflare. - 'HTTP_X_REAL_IP', // Nginx proxy. - 'HTTP_X_FORWARDED_FOR', // Standard proxy header. - 'REMOTE_ADDR', // Direct connection. - ]; - - foreach ( $ip_keys as $key ) { - if ( isset( $_SERVER[ $key ] ) && ! empty( $_SERVER[ $key ] ) ) { - $ip = \sanitize_text_field( \wp_unslash( $_SERVER[ $key ] ) ); - // Handle X-Forwarded-For which may contain multiple IPs. - if ( \strpos( $ip, ',' ) !== false ) { - $ip = \trim( \explode( ',', $ip )[0] ); - } - // Validate IP address. - if ( \filter_var( $ip, FILTER_VALIDATE_IP ) ) { - return $ip; - } - } - } + // Forwarded headers are client input unless a trusted proxy normalizes REMOTE_ADDR. + $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? \sanitize_text_field( \wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; + return \filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '0.0.0.0'; + } - return '0.0.0.0'; + /** + * Authenticate a request using a bearer token, never a URL parameter. + * + * @param \WP_REST_Request $request The REST request. + * @return bool + */ + public function permissions_check( $request ) { + $authorization = $request->get_header( 'authorization' ); + return \is_string( $authorization ) + && 1 === \preg_match( '/^Bearer ([^\s]+)$/iD', $authorization, $matches ) + && $this->validate_token( $matches[1] ); } /** * Validate the token. * - * @param string $token The token. + * @param mixed $token The token. * * @return bool */ public function validate_token( $token ) { + if ( ! \is_string( $token ) || '' === $token ) { + return false; + } + // Rate limiting: Check for too many failed attempts. $ip_address = $this->get_client_ip(); $rate_limit_key = 'prpl_api_rate_limit_' . \md5( $ip_address ); @@ -76,8 +74,6 @@ public function validate_token( $token ) { return false; } - $token = \str_replace( 'token/', '', $token ); - // Check test token first (use hash_equals to prevent timing attacks). $test_token = \get_option( 'progress_planner_test_token', '' ); if ( ! empty( $test_token ) && \hash_equals( $test_token, $token ) ) { diff --git a/classes/rest/class-page-types-controller.php b/classes/rest/class-page-types-controller.php new file mode 100644 index 000000000..ebc998de9 --- /dev/null +++ b/classes/rest/class-page-types-controller.php @@ -0,0 +1,40 @@ + \rest_authorization_required_code() ] ); + } + return parent::get_items_permissions_check( $request ); + } + + /** + * Check single-term read access. + * + * @param \WP_REST_Request $request REST request. + * @return true|\WP_Error + */ + public function get_item_permissions_check( $request ) { + if ( ! \current_user_can( 'edit_posts' ) ) { + return new \WP_Error( 'rest_forbidden', \__( 'You cannot access page types.', 'progress-planner' ), [ 'status' => \rest_authorization_required_code() ] ); + } + return parent::get_item_permissions_check( $request ); + } +} diff --git a/classes/rest/class-recommendations-controller.php b/classes/rest/class-recommendations-controller.php index 9f40b1860..080da5b86 100644 --- a/classes/rest/class-recommendations-controller.php +++ b/classes/rest/class-recommendations-controller.php @@ -46,7 +46,7 @@ protected function current_user_can_access_recommendations() { * as `update-core` requires `update_core`, so an editor cannot read, trash * or delete it over REST even though they clear the surface-level * `edit_others_posts` gate (audit S1, review gap 2). Tasks whose provider - * cannot be resolved fall back to the surface gate. + * cannot be resolved are denied. * * @param \WP_REST_Request $request The REST request. * @@ -55,17 +55,17 @@ protected function current_user_can_access_recommendations() { protected function current_user_can_manage_requested_task( $request ) { $post = $this->get_post( $request['id'] ); if ( \is_wp_error( $post ) ) { - return true; + return false; } $task = \progress_planner()->get_suggested_tasks_db()->get_post( $post->ID ); if ( ! $task ) { - return true; + return false; } $provider = \progress_planner()->get_suggested_tasks()->get_tasks_manager()->get_task_provider( $task->get_provider_id() ); if ( ! $provider ) { - return true; + return false; } return (bool) $provider->capability_required(); @@ -193,6 +193,29 @@ public function update_item_permissions_check( $request ) { ) { return $this->forbidden_error(); } + // Task identity is immutable for non-admins, including when they can edit its content. + if ( ! \current_user_can( 'manage_options' ) ) { + $post = $this->get_post( $request['id'] ); + if ( \is_wp_error( $post ) ) { + return $this->forbidden_error(); + } + if ( $request->has_param( 'slug' ) && $request['slug'] !== $post->post_name ) { + return $this->forbidden_error(); + } + if ( $request->has_param( 'prpl_recommendations_provider' ) ) { + $existing = \wp_get_object_terms( $post->ID, 'prpl_recommendations_provider', [ 'fields' => 'ids' ] ); + if ( \is_wp_error( $existing ) ) { + return $this->forbidden_error(); + } + $requested = \array_map( 'intval', (array) $request['prpl_recommendations_provider'] ); + $existing = \array_map( 'intval', $existing ); + \sort( $requested ); + \sort( $existing ); + if ( $requested !== $existing ) { + return $this->forbidden_error(); + } + } + } return parent::update_item_permissions_check( $request ); } diff --git a/classes/rest/class-stats.php b/classes/rest/class-stats.php index 5ff4217bb..7958f286c 100644 --- a/classes/rest/class-stats.php +++ b/classes/rest/class-stats.php @@ -3,7 +3,7 @@ * Progress_Planner REST-API. * * Adds a REST-API endpoint to get stats, in a URL like: - * /wp-json/progress-planner/v1/get-stats/token/ + * /wp-json/progress-planner/v1/get-stats (Authorization: Bearer ) * * The token is generated and saved in the settings. * @@ -27,18 +27,12 @@ class Stats extends Base { public function register_rest_endpoint() { \register_rest_route( 'progress-planner/v1', - '/get-stats/(?P\S+)', + '/get-stats', [ [ 'methods' => 'GET', 'callback' => [ $this, 'get_stats' ], - 'permission_callback' => '__return_true', - 'args' => [ - 'token' => [ - 'required' => true, - 'validate_callback' => [ $this, 'validate_token' ], - ], - ], + 'permission_callback' => [ $this, 'permissions_check' ], ], ] ); diff --git a/classes/rest/class-tasks.php b/classes/rest/class-tasks.php index 7e4849320..14285937d 100644 --- a/classes/rest/class-tasks.php +++ b/classes/rest/class-tasks.php @@ -28,13 +28,7 @@ public function register_rest_endpoint() { [ 'methods' => 'GET', 'callback' => [ $this, 'get_tasks' ], - 'permission_callback' => '__return_true', - 'args' => [ - 'token' => [ - 'required' => true, - 'validate_callback' => [ $this, 'validate_token' ], - ], - ], + 'permission_callback' => [ $this, 'permissions_check' ], ], ] ); diff --git a/classes/suggested-tasks/providers/class-remove-terms-without-posts.php b/classes/suggested-tasks/providers/class-remove-terms-without-posts.php index 12bd8b132..e2ae2d8fe 100644 --- a/classes/suggested-tasks/providers/class-remove-terms-without-posts.php +++ b/classes/suggested-tasks/providers/class-remove-terms-without-posts.php @@ -453,6 +453,10 @@ public function handle_interactive_task_submit() { \wp_send_json_error( [ 'message' => \esc_html__( 'Term not found.', 'progress-planner' ) ] ); } + if ( ! \current_user_can( 'delete_term', $term_id ) ) { + \wp_send_json_error( [ 'message' => \esc_html__( 'You do not have permission to delete terms.', 'progress-planner' ) ] ); + } + // Only public taxonomies are tracked by this task, mirroring the check in // maybe_remove_irrelevant_tasks(). $taxonomy_object = \get_taxonomy( $taxonomy ); diff --git a/classes/suggested-tasks/providers/class-update-term-description.php b/classes/suggested-tasks/providers/class-update-term-description.php index fc27fef86..7a40ee2f5 100644 --- a/classes/suggested-tasks/providers/class-update-term-description.php +++ b/classes/suggested-tasks/providers/class-update-term-description.php @@ -445,6 +445,10 @@ public function handle_interactive_task_submit() { \wp_send_json_error( [ 'message' => \esc_html__( 'Term not found.', 'progress-planner' ) ] ); } + if ( ! \current_user_can( 'edit_term', $term_id ) ) { + \wp_send_json_error( [ 'message' => \esc_html__( 'You do not have permission to update terms.', 'progress-planner' ) ] ); + } + // Only public taxonomies are tracked by this task. $taxonomy_object = \get_taxonomy( $taxonomy ); if ( ! $taxonomy_object || ! $taxonomy_object->public ) { diff --git a/classes/ui/class-branding.php b/classes/ui/class-branding.php index 278f15d7a..872b0b445 100644 --- a/classes/ui/class-branding.php +++ b/classes/ui/class-branding.php @@ -38,9 +38,11 @@ public function __construct() { /** * Get the branding ID. * + * @param bool $allow_preview Whether to allow an authenticated preview. + * * @return int */ - public function get_branding_id(): int { + public function get_branding_id( bool $allow_preview = true ): int { // Check for placeholder demo cookie. if ( \defined( '\IS_PLAYGROUND_PREVIEW' ) && \constant( '\IS_PLAYGROUND_PREVIEW' ) === true @@ -54,12 +56,15 @@ public function get_branding_id(): int { if ( \defined( 'PROGRESS_PLANNER_BRANDING_ID' ) ) { return \constant( 'PROGRESS_PLANNER_BRANDING_ID' ); } - // The `pp_branding_id` URL param is a preview seam for branded-host - // rendering. Honour it only for administrators, so no lower-privileged - // or anonymous visitor can steer the branding ID and thereby trigger the - // auto-onboard remote call in `Base::init()` (1.10.0 audit S3). - if ( isset( $_GET['pp_branding_id'] ) && \current_user_can( 'manage_options' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended - return (int) $_GET['pp_branding_id']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended + // A preview must never grant onboarding consent or be selected by a forged link. + if ( $allow_preview + && isset( $_GET['pp_branding_id'], $_GET['_pp_branding_nonce'] ) + && \is_scalar( $_GET['pp_branding_id'] ) + && \is_string( $_GET['_pp_branding_nonce'] ) + && \current_user_can( 'manage_options' ) + && \wp_verify_nonce( \sanitize_text_field( \wp_unslash( $_GET['_pp_branding_nonce'] ) ), 'pp_branding_preview_' . \absint( $_GET['pp_branding_id'] ) ) + ) { + return \absint( $_GET['pp_branding_id'] ); } $hostname = (string) \gethostname(); @@ -164,7 +169,7 @@ public function the_logo(): void { * @return string */ public function get_custom_css(): string { - return (string) ( $this->get_api_data()['css'] ?? '' ); + return \wp_strip_all_tags( (string) ( $this->get_api_data()['css'] ?? '' ) ); } /** @@ -208,7 +213,7 @@ public function get_admin_menu_icon( bool $raw = false ): string { // Inline the SVG: the URL carries a content hash, so a changed icon is a new cache entry. $content = $this->get_remote_data( $admin_menu_icon_url ); if ( $content && \is_string( $content ) ) { - $svg = $content; + $svg = $this->sanitize_svg( $content ); } } @@ -220,13 +225,50 @@ public function get_admin_menu_icon( bool $raw = false ): string { return 'data:image/svg+xml;base64,' . \base64_encode( $svg ); } + /** + * Keep only inert SVG shapes and geometry, with no links, scripts or styles. + * + * @param string $svg Remote SVG markup. + * @return string + */ + public function sanitize_svg( string $svg ): string { + $attributes = \array_fill_keys( [ 'd', 'x', 'y', 'x1', 'x2', 'y1', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height', 'viewbox', 'points', 'transform', 'fill-rule', 'clip-rule', 'stroke-width' ], true ); + $allowed = \array_fill_keys( [ 'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon' ], $attributes ); + // Paint attributes can contain URLs; retain only literal colors. + $allowed = \array_map( + fn( $attrs ) => \array_merge( + $attrs, + [ + 'fill' => true, + 'stroke' => true, + ] + ), + $allowed + ); + $svg = \wp_kses( $svg, $allowed ); + $tags = new \WP_HTML_Tag_Processor( $svg ); + while ( $tags->next_tag() ) { + if ( 'SVG' === $tags->get_tag() ) { + // Required when the same icon is used as a standalone SVG data URI. + $tags->set_attribute( 'xmlns', 'http://www.w3.org/2000/svg' ); + } + foreach ( [ 'fill', 'stroke' ] as $attribute ) { + $value = $tags->get_attribute( $attribute ); + if ( null !== $value && ( ! \is_string( $value ) || ! \preg_match( '/^(?:#[a-f0-9]{3,8}|[a-z]+)$/iD', $value ) ) ) { + $tags->remove_attribute( $attribute ); + } + } + } + return $tags->get_updated_html(); + } + /** * Get the admin-menu name. * * @return string */ public function get_admin_menu_name(): string { - return (string) ( $this->get_api_data()['admin_menu']['name'] ?? 'Progress Planner' ); + return \wp_kses_post( (string) ( $this->get_api_data()['admin_menu']['name'] ?? 'Progress Planner' ) ); } /** @@ -235,7 +277,7 @@ public function get_admin_menu_name(): string { * @return string */ public function get_admin_submenu_name(): string { - return (string) ( $this->get_api_data()['admin_menu']['submenu'] ?? $this->get_admin_menu_name() ); + return \wp_kses_post( (string) ( $this->get_api_data()['admin_menu']['submenu'] ?? $this->get_admin_menu_name() ) ); } /** @@ -267,6 +309,14 @@ public function get_ravi_name(): string { * @return mixed */ public function get_remote_data( $url ) { + // Check before cache access too, so old responses cannot bypass the host restriction. + $host = \wp_parse_url( \progress_planner()->get_branding_server_url(), PHP_URL_HOST ); + if ( ! $host || 'https' !== \wp_parse_url( $url, PHP_URL_SCHEME ) + || \strtolower( $host ) !== \strtolower( (string) \wp_parse_url( $url, PHP_URL_HOST ) ) + ) { + return false; + } + $cache_key = \md5( $url ); $cached = \progress_planner()->get_utils__cache()->get( $cache_key ); // An empty array is a cached failure; only false means a cache miss. @@ -274,7 +324,7 @@ public function get_remote_data( $url ) { return $cached; } - $response = \wp_remote_get( $url ); + $response = \wp_safe_remote_get( $url, [ 'redirection' => 0 ] ); if ( \is_wp_error( $response ) ) { \progress_planner()->get_utils__cache()->set( $cache_key, [], 5 * MINUTE_IN_SECONDS ); return false; @@ -317,7 +367,7 @@ public function filter_widgets( $widgets ) { * @return string */ public function get_widget_title( $widget_id, $default_value = '' ) { - return (string) ( $this->get_api_data()['widget_titles'][ $widget_id ] ?? $default_value ); + return \wp_kses_post( (string) ( $this->get_api_data()['widget_titles'][ $widget_id ] ?? $default_value ) ); } /** diff --git a/classes/utils/class-onboard.php b/classes/utils/class-onboard.php index 37655789d..790db293c 100644 --- a/classes/utils/class-onboard.php +++ b/classes/utils/class-onboard.php @@ -150,12 +150,18 @@ public function make_remote_onboarding_request( $data = [] ) { ] ); + $license_key = \progress_planner()->get_license_key(); + $headers = $license_key && 'no-license' !== $license_key + ? [ 'Authorization' => 'Bearer ' . $license_key ] : []; + // Make the request. - $response = \wp_remote_post( + $response = \wp_safe_remote_post( $this->get_remote_url( 'onboard' ), [ - 'timeout' => 10, - 'body' => $data, + 'timeout' => 10, + 'headers' => $headers, + 'redirection' => 0, + 'body' => $data, ] ); diff --git a/tests/phpunit/integration/class-integration-test-case.php b/tests/phpunit/integration/class-integration-test-case.php index 375e05e3a..3656e200b 100644 --- a/tests/phpunit/integration/class-integration-test-case.php +++ b/tests/phpunit/integration/class-integration-test-case.php @@ -56,14 +56,19 @@ protected function create_test_user_task( $args = [] ) { * @param string $endpoint Endpoint path. * @param string $method HTTP method. * @param array $params Request parameters. + * @param array $headers Request headers. * @return \WP_REST_Response|\WP_Error */ - protected function make_rest_request( $endpoint, $method = 'GET', $params = [] ) { + protected function make_rest_request( $endpoint, $method = 'GET', $params = [], $headers = [] ) { $request = new \WP_REST_Request( $method, $endpoint ); foreach ( $params as $key => $value ) { $request->set_param( $key, $value ); } + foreach ( $headers as $key => $value ) { + $request->set_header( $key, $value ); + } + $server = \rest_get_server(); return $server->dispatch( $request ); } diff --git a/tests/phpunit/integration/test-rest-api-stats-integration.php b/tests/phpunit/integration/test-rest-api-stats-integration.php index d95a4cc9d..c5550dff1 100644 --- a/tests/phpunit/integration/test-rest-api-stats-integration.php +++ b/tests/phpunit/integration/test-rest-api-stats-integration.php @@ -27,9 +27,10 @@ public function test_get_stats_endpoint_with_valid_token() { // Make REST API request. $response = $this->make_rest_request( - '/progress-planner/v1/get-stats/' . $license_key, + '/progress-planner/v1/get-stats', 'GET', - [] + [], + [ 'Authorization' => 'Bearer ' . $license_key ] ); $this->assertNotInstanceOf( \WP_Error::class, $response ); @@ -58,13 +59,14 @@ public function test_get_stats_endpoint_with_invalid_token() { // Make REST API request with invalid token. $response = $this->make_rest_request( - '/progress-planner/v1/get-stats/invalid-token', + '/progress-planner/v1/get-stats', 'GET', - [] + [], + [ 'Authorization' => 'Bearer invalid-token' ] ); // Should return error due to validation failure. - $this->assertTrue( true ); // Endpoint validation prevents invalid tokens. + $this->assertSame( 401, $response->get_status() ); } /** @@ -84,9 +86,10 @@ public function test_get_stats_endpoint_includes_system_data() { ); $response = $this->make_rest_request( - '/progress-planner/v1/get-stats/' . $license_key, + '/progress-planner/v1/get-stats', 'GET', - [] + [], + [ 'Authorization' => 'Bearer ' . $license_key ] ); $this->assertInstanceOf( \WP_REST_Response::class, $response ); diff --git a/tests/phpunit/integration/test-rest-api-tasks-integration.php b/tests/phpunit/integration/test-rest-api-tasks-integration.php index d5f5b70a9..56765340e 100644 --- a/tests/phpunit/integration/test-rest-api-tasks-integration.php +++ b/tests/phpunit/integration/test-rest-api-tasks-integration.php @@ -32,7 +32,8 @@ public function test_get_tasks_endpoint_with_valid_token() { $response = $this->make_rest_request( '/progress-planner/v1/tasks', 'GET', - [ 'token' => $license_key ] + [], + [ 'Authorization' => 'Bearer ' . $license_key ] ); $this->assertNotInstanceOf( \WP_Error::class, $response ); @@ -61,16 +62,16 @@ public function test_get_tasks_endpoint_with_invalid_token() { $response = $this->make_rest_request( '/progress-planner/v1/tasks', 'GET', - [ 'token' => 'invalid-token' ] + [], + [ 'Authorization' => 'Bearer invalid-token' ] ); - // Should return error or empty response due to validation failure. - // The validation happens in the args callback, so the endpoint may not be called. - $this->assertTrue( true ); // Endpoint validation prevents invalid tokens. + // Missing or invalid credentials must not expose tasks. + $this->assertSame( 401, $response->get_status() ); } /** - * Test REST API endpoint requires token parameter. + * Test REST API endpoint requires an authentication header. * * @return void */ @@ -82,8 +83,8 @@ public function test_get_tasks_endpoint_requires_token() { [] ); - // Should return error due to missing required parameter. - $this->assertTrue( true ); // Validation prevents requests without token. + // Requests without an authentication header must be rejected. + $this->assertSame( 401, $response->get_status() ); } /** @@ -103,7 +104,8 @@ public function test_get_tasks_endpoint_includes_all_statuses() { $response = $this->make_rest_request( '/progress-planner/v1/tasks', 'GET', - [ 'token' => $license_key ] + [], + [ 'Authorization' => 'Bearer ' . $license_key ] ); $this->assertInstanceOf( \WP_REST_Response::class, $response ); diff --git a/tests/phpunit/test-class-admin-widget.php b/tests/phpunit/test-class-admin-widget.php index 571287e4b..005354bd3 100644 --- a/tests/phpunit/test-class-admin-widget.php +++ b/tests/phpunit/test-class-admin-widget.php @@ -77,8 +77,8 @@ public function test_get_range() { $this->assertEquals( '-6 months', $this->widget_instance->get_range() ); // Test with GET parameter. - $_GET['range'] = '-1 year'; - $this->assertEquals( '-1 year', $this->widget_instance->get_range() ); + $_GET['range'] = '-12 months'; + $this->assertEquals( '-12 months', $this->widget_instance->get_range() ); // Clean up. unset( $_GET['range'] ); @@ -126,4 +126,18 @@ public function test_get_frequency_sanitizes_input() { $this->assertStringNotContainsString( 'alert', $result ); unset( $_GET['frequency'] ); } + /** + * Crafted links cannot request invalid dates or unbounded chart periods. + * + * @return void + */ + public function test_chart_options_are_bounded() { + foreach ( [ '-5000 years', 'invalid date', [], '-1 year' ] as $range ) { + $_GET['range'] = $range; + $this->assertSame( '-6 months', $this->widget_instance->get_range() ); + } + $_GET['frequency'] = 'daily'; + $this->assertSame( 'monthly', $this->widget_instance->get_frequency() ); + unset( $_GET['range'], $_GET['frequency'] ); + } } diff --git a/tests/phpunit/test-class-branding-preview-param.php b/tests/phpunit/test-class-branding-preview-param.php index 4809f7dc4..fbad622ba 100644 --- a/tests/phpunit/test-class-branding-preview-param.php +++ b/tests/phpunit/test-class-branding-preview-param.php @@ -1,13 +1,7 @@ user->create( [ 'role' => 'administrator' ] ); \wp_set_current_user( $admin ); - $_GET['pp_branding_id'] = '4958'; + $_GET['pp_branding_id'] = '4958'; + $_GET['_pp_branding_nonce'] = \wp_create_nonce( 'pp_branding_preview_4958' ); $branding_id = \progress_planner()->get_ui__branding()->get_branding_id(); @@ -83,4 +78,20 @@ public function test_logged_in_subscriber_param_is_ignored() { $this->assertSame( 0, $branding_id, 'a subscriber must not be able to set pp_branding_id' ); } + /** + * An unsigned admin link cannot select branding or grant onboarding consent. + * + * @return void + */ + public function test_admin_preview_requires_nonce_and_never_auto_onboards() { + \wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + $_GET['pp_branding_id'] = '4958'; + $branding = \progress_planner()->get_ui__branding(); + $this->assertSame( 0, $branding->get_branding_id() ); + $_GET['_pp_branding_nonce'] = \wp_create_nonce( 'pp_branding_preview_4958' ); + $this->assertSame( 4958, $branding->get_branding_id() ); + $this->assertSame( 0, $branding->get_branding_id( false ) ); + $_GET['pp_branding_id'] = '5938'; + $this->assertSame( 0, $branding->get_branding_id() ); + } } diff --git a/tests/phpunit/test-class-branding.php b/tests/phpunit/test-class-branding.php index 725b4dcdd..bed87cc33 100644 --- a/tests/phpunit/test-class-branding.php +++ b/tests/phpunit/test-class-branding.php @@ -80,7 +80,7 @@ public function setUp(): void { */ public function tearDown(): void { \remove_filter( 'pre_http_request', [ $this, 'mock_branding_server' ], 10 ); - unset( $_GET['pp_branding_id'] ); + unset( $_GET['pp_branding_id'], $_GET['_pp_branding_nonce'] ); \wp_set_current_user( 0 ); \progress_planner()->get_utils__cache()->delete_all(); parent::tearDown(); @@ -125,7 +125,8 @@ public function mock_branding_server( $preempt, $args, $url ) { */ private function use_brand(): void { \wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $_GET['pp_branding_id'] = (string) self::BRAND_ID; + $_GET['pp_branding_id'] = (string) self::BRAND_ID; + $_GET['_pp_branding_nonce'] = \wp_create_nonce( 'pp_branding_preview_' . self::BRAND_ID ); } /** diff --git a/tests/phpunit/test-class-rest-base.php b/tests/phpunit/test-class-rest-base.php index 38af0aead..9c7c614fa 100644 --- a/tests/phpunit/test-class-rest-base.php +++ b/tests/phpunit/test-class-rest-base.php @@ -33,7 +33,7 @@ public function setUp(): void { } /** - * Test get_client_ip with Cloudflare header. + * Test get_client_ip ignores an untrusted Cloudflare header. * * @return void */ @@ -49,11 +49,11 @@ public function test_get_client_ip_cloudflare() { $ip = $method->invoke( $this->rest_instance ); - $this->assertEquals( '192.168.1.100', $ip ); + $this->assertEquals( '0.0.0.0', $ip ); } /** - * Test get_client_ip with X-Real-IP header. + * Test get_client_ip ignores an untrusted X-Real-IP header. * * @return void */ @@ -69,7 +69,7 @@ public function test_get_client_ip_x_real_ip() { $ip = $method->invoke( $this->rest_instance ); - $this->assertEquals( '192.168.1.101', $ip ); + $this->assertEquals( '0.0.0.0', $ip ); } /** @@ -89,7 +89,7 @@ public function test_get_client_ip_x_forwarded_for_single() { $ip = $method->invoke( $this->rest_instance ); - $this->assertEquals( '192.168.1.102', $ip ); + $this->assertEquals( '0.0.0.0', $ip ); } /** @@ -109,7 +109,7 @@ public function test_get_client_ip_x_forwarded_for_multiple() { $ip = $method->invoke( $this->rest_instance ); - $this->assertEquals( '192.168.1.103', $ip ); + $this->assertEquals( '0.0.0.0', $ip ); } /** @@ -250,7 +250,7 @@ public function test_validate_token_test_token() { } /** - * Test validate_token with token containing "token/" prefix. + * Token validation compares the entire bearer token, including any prefix. * * @return void */ @@ -270,7 +270,7 @@ public function test_validate_token_with_prefix() { $result = $this->rest_instance->validate_token( $token ); - $this->assertTrue( $result ); + $this->assertFalse( $result ); } /** diff --git a/tests/phpunit/test-class-rest-stats.php b/tests/phpunit/test-class-rest-stats.php index 33827f095..c67dfaee7 100644 --- a/tests/phpunit/test-class-rest-stats.php +++ b/tests/phpunit/test-class-rest-stats.php @@ -43,7 +43,7 @@ public function test_register_rest_endpoint() { \do_action( 'rest_api_init' ); $routes = $wp_rest_server->get_routes(); - $this->assertArrayHasKey( '/progress-planner/v1/get-stats/(?P\S+)', $routes ); + $this->assertArrayHasKey( '/progress-planner/v1/get-stats', $routes ); } /** diff --git a/tests/phpunit/test-class-security-review.php b/tests/phpunit/test-class-security-review.php new file mode 100644 index 000000000..cf789b4da --- /dev/null +++ b/tests/phpunit/test-class-security-review.php @@ -0,0 +1,448 @@ +admin = \wp_insert_user( + [ + 'user_login' => \wp_generate_uuid4(), + 'user_pass' => 'fixture', + 'role' => 'administrator', + ] + ); + $this->editor = \wp_insert_user( + [ + 'user_login' => \wp_generate_uuid4(), + 'user_pass' => 'fixture', + 'role' => 'editor', + ] + ); + \wp_set_current_user( $this->admin ); + $_SERVER['REMOTE_ADDR'] = '192.0.2.10'; + \delete_transient( 'prpl_api_rate_limit_' . \md5( '192.0.2.10' ) ); + global $wp_rest_server; + $wp_rest_server = new \WP_REST_Server(); + \do_action( 'rest_api_init' ); + } + + /** + * Reset request state. + * + * @return void + */ + public function tearDown(): void { + unset( $_GET['pp_branding_id'], $_GET['_pp_branding_nonce'], $_GET['range'], $_GET['frequency'] ); + unset( $_SERVER['HTTP_CF_CONNECTING_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['HTTP_X_REAL_IP'], $_SERVER['REMOTE_ADDR'] ); + $_POST = []; + $_REQUEST = []; + \wp_set_current_user( 0 ); + parent::tearDown(); + } + + /** + * Forwarded headers cannot reset the rate limit or create extra counters. + * + * @return void + */ + public function test_spoofed_headers_cannot_bypass_rate_limit() { + \update_option( 'progress_planner_license_key', 'fixture-license' ); + $api = new \Progress_Planner\Rest\Tasks(); + for ( $i = 0; $i < 11; ++$i ) { + $_SERVER['HTTP_CF_CONNECTING_IP'] = '198.51.100.' . $i; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '198.51.100.' . $i; + $_SERVER['HTTP_X_REAL_IP'] = '198.51.100.' . $i; + $this->assertFalse( $api->validate_token( 'incorrect' ) ); + $this->assertFalse( \get_transient( 'prpl_api_rate_limit_' . \md5( '198.51.100.' . $i ) ) ); + } + $this->assertSame( 10, (int) \get_transient( 'prpl_api_rate_limit_' . \md5( '192.0.2.10' ) ) ); + $this->assertFalse( $api->validate_token( 'fixture-license' ) ); + } + + /** + * Bearer authentication works without credentials in the URL. + * + * @return void + */ + public function test_bearer_authentication() { + \update_option( 'progress_planner_license_key', 'fixture-license' ); + \wp_set_current_user( 0 ); + foreach ( [ '/tasks', '/get-stats' ] as $endpoint ) { + $request = new \WP_REST_Request( 'GET', '/progress-planner/v1' . $endpoint ); + $this->assertSame( 401, \rest_do_request( $request )->get_status() ); + $request->set_header( 'Authorization', 'Bearer fixture-license' ); + $this->assertSame( 200, \rest_do_request( $request )->get_status() ); + $request->set_header( 'Authorization', 'Bearer incorrect' ); + $request->set_param( 'token', 'fixture-license' ); + $this->assertSame( 401, \rest_do_request( $request )->get_status() ); + } + } + + /** + * Legacy URL credentials no longer grant access. + * + * @return void + */ + public function test_url_tokens_are_rejected() { + \update_option( 'progress_planner_license_key', 'fixture-license' ); + \wp_set_current_user( 0 ); + foreach ( [ '/tasks', '/get-stats' ] as $endpoint ) { + $request = new \WP_REST_Request( 'GET', '/progress-planner/v1' . $endpoint ); + $request->set_param( 'token', 'fixture-license' ); + $this->assertSame( 401, \rest_do_request( $request )->get_status() ); + } + $request = new \WP_REST_Request( 'GET', '/progress-planner/v1/get-stats/token/fixture-license' ); + $this->assertSame( 404, \rest_do_request( $request )->get_status() ); + } + + /** + * Public lesson and challenge requests never transmit a credential. + * + * @return void + */ + public function test_public_content_requests_omit_license_key() { + \update_option( 'progress_planner_license_key', 'fixture-license' ); + \progress_planner()->get_utils__cache()->delete_all(); + $requests = []; + $mock = function ( $response, $args, $url ) use ( &$requests ) { + $requests[] = [ $url, $args ]; + return [ + 'response' => [ 'code' => 200 ], + 'body' => '[]', + ]; + }; + \add_filter( 'pre_http_request', $mock, 20, 3 ); + try { + \progress_planner()->get_lessons()->get_remote_api_items(); + \progress_planner()->get_admin__widgets__challenge()->get_challenge(); + } finally { + \remove_filter( 'pre_http_request', $mock, 20 ); + } + $this->assertCount( 2, $requests ); + foreach ( $requests as $request ) { + $this->assertStringNotContainsString( 'license_key', $request[0] ); + $this->assertStringNotContainsString( 'fixture-license', \wp_json_encode( $request ) ); + } + } + + /** + * Onboarding retries authenticate with the current key without forwarding it on redirects. + * + * @return void + */ + public function test_onboarding_retry_authenticates_existing_registration() { + $key = \bin2hex( \random_bytes( 32 ) ); + \update_option( 'progress_planner_license_key', $key ); + $mock = function ( $response, $args, $url ) use ( $key ) { + $this->assertStringNotContainsString( $key, $url ); + $this->assertSame( 'Bearer ' . $key, $args['headers']['Authorization'] ); + $this->assertSame( 0, $args['redirection'] ); + return [ + 'response' => [ 'code' => 200 ], + 'body' => \wp_json_encode( + [ + 'status' => 'ok', + 'license_key' => $key, + ] + ), + ]; + }; + \add_filter( 'pre_http_request', $mock, 20, 3 ); + try { + $this->assertSame( $key, \progress_planner()->get_utils__onboard()->make_remote_onboarding_request( [ 'nonce' => 'fixture' ] ) ); + } finally { + \remove_filter( 'pre_http_request', $mock, 20 ); + } + } + + /** + * A non-admin cannot turn a personal task into an admin recommendation. + * + * @return void + */ + public function test_task_identity_is_immutable_for_editors() { + $id = \progress_planner()->get_suggested_tasks_db()->add( + [ + 'task_id' => 'user-security-fixture', + 'post_title' => 'Personal', + 'provider_id' => 'user', + ] + ); + $controller = new \Progress_Planner\Rest\Recommendations_Controller( 'prpl_recommendations' ); + $request = new \WP_REST_Request( 'POST', '/wp/v2/prpl_recommendations/' . $id ); + $request->set_param( 'id', $id ); + $request->set_param( 'title', 'Updated personal task' ); + \wp_set_current_user( $this->editor ); + $this->assertTrue( $controller->update_item_permissions_check( $request ) ); + $request->set_param( 'slug', 'update-core' ); + $this->assertInstanceOf( \WP_Error::class, $controller->update_item_permissions_check( $request ) ); + $request->set_param( 'slug', \get_post( $id )->post_name ); + $request->set_param( 'prpl_recommendations_provider', [] ); + $this->assertInstanceOf( \WP_Error::class, $controller->update_item_permissions_check( $request ) ); + $term = \wp_insert_term( 'security-unknown-provider', 'prpl_recommendations_provider' ); + \wp_set_object_terms( $id, [ (int) $term['term_id'] ], 'prpl_recommendations_provider' ); + $this->assertInstanceOf( \WP_Error::class, $controller->update_item_permissions_check( $request ) ); + } + + /** + * Unknown AJAX actions cannot dispatch arbitrary extension hooks. + * + * @return void + */ + public function test_unknown_task_actions_are_rejected() { + $id = \progress_planner()->get_suggested_tasks_db()->add( + [ + 'task_id' => 'user-action-fixture', + 'post_title' => 'Action fixture', + 'provider_id' => 'user', + ] + ); + $_POST = [ + 'post_id' => $id, + 'action_type' => 'unexpected', + ]; + $_REQUEST = [ 'nonce' => \wp_create_nonce( 'progress_planner' ) ]; + $before = \did_action( 'progress_planner_ajax_task_unexpected' ); + $response = $this->ajax_response( [ \progress_planner()->get_suggested_tasks(), 'suggested_task_action' ] ); + $this->assertFalse( $response['success'] ); + $this->assertSame( $before, \did_action( 'progress_planner_ajax_task_unexpected' ) ); + } + + /** + * Remote HTML and SVG cannot introduce active content into the editor. + * + * @return void + */ + public function test_remote_markup_is_sanitized() { + $lessons = new \Progress_Planner\Lessons(); + $data = $lessons->sanitize_items( + [ + 'intro' => [ + 'text' => '

Read this

', + 'video' => '', + ], + 'todos' => [ [ 'todo_description' => '' ] ], + ] + ); + $this->assertStringContainsString( 'this', $data['intro']['text'] ); + $this->assertStringNotContainsString( 'assertStringNotContainsString( 'onclick', $data['intro']['text'] ); + $this->assertStringNotContainsString( 'onerror', $data['todos'][0]['todo_description'] ); + $this->assertStringNotContainsString( 'evil.example', $data['intro']['video'] ); + $this->assertStringNotContainsString( 'srcdoc', $data['intro']['video'] ); + $this->assertStringContainsString( 'https://player.vimeo.com/video/123', $data['intro']['video'] ); + $svg = \progress_planner()->get_ui__branding()->sanitize_svg( '' ); + $this->assertStringNotContainsString( 'assertStringNotContainsString( 'onload', $svg ); + $this->assertStringNotContainsString( 'foreignObject', $svg ); + $this->assertStringNotContainsString( 'evil.example', $svg ); + $this->assertStringContainsString( 'fill="#fff"', $svg ); + $this->assertStringContainsString( 'xmlns="http://www.w3.org/2000/svg"', $svg ); + } + + /** + * Previously cached branding is sanitized and foreign-host fetches are rejected. + * + * @return void + */ + public function test_cached_branding_is_untrusted() { + $_GET['pp_branding_id'] = '4958'; + $_GET['_pp_branding_nonce'] = \wp_create_nonce( 'pp_branding_preview_4958' ); + $branding = \progress_planner()->get_ui__branding(); + $url = \progress_planner()->get_branding_server_url() . '/v1/brands/4958.json'; + \progress_planner()->get_utils__cache()->set( + \md5( $url ), + \wp_json_encode( + [ + 'format' => 1, + 'css' => 'body{color:red}