diff --git a/assets/css/onboard.css b/assets/css/onboard.css index bac24ea7d..dc3afb0ee 100644 --- a/assets/css/onboard.css +++ b/assets/css/onboard.css @@ -21,3 +21,12 @@ display: flex; align-items: center; } + +.prpl-onboarding-error { + margin: 0 0 1rem; + padding: 0.75rem 1rem; + color: var(--prpl-color-alert-error-text); + background: var(--prpl-background-alert-error); + border: 1px solid var(--prpl-color-border-alert-error); + border-radius: var(--prpl-radius-paper); +} diff --git a/assets/js/editor.js b/assets/js/editor.js index 1bfcd9d8d..084402503 100644 --- a/assets/js/editor.js +++ b/assets/js/editor.js @@ -268,8 +268,9 @@ 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 +597,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..d0c5c8d0a 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: { @@ -24,6 +23,34 @@ const progressPlannerSaveLicenseKey = ( licenseKey ) => { } ); }; +/** + * Show an onboarding error and let the user submit the form again. + * + * @param {Object} response The server response, if any. + */ +const progressPlannerShowOnboardError = ( response ) => { + console.warn( response ); + + const errorElement = document.getElementById( 'prpl-onboarding-error' ); + if ( errorElement ) { + // textContent: the message comes from the remote server. + errorElement.textContent = + response && 'string' === typeof response.message && response.message + ? response.message + : progressPlanner.onboardError; + errorElement.hidden = false; + } + + document + .querySelectorAll( '#prpl-onboarding-form input[type="submit"]' ) + .forEach( ( input ) => { + input.disabled = false; + } ); + document + .querySelectorAll( '#prpl-onboarding-submit-wrapper .prpl-spinner' ) + .forEach( ( spinner ) => spinner.remove() ); +}; + /** * Make the AJAX request. * @@ -35,15 +62,17 @@ const progressPlannerAjaxAPIRequest = ( data ) => { data, } ) .then( ( response ) => { + if ( ! response || ! response.license_key ) { + progressPlannerShowOnboardError( response ); + return; + } // Make a local request to save the response data. progressPlannerSaveLicenseKey( response.license_key ).then( () => { // Refresh the page. window.location.reload(); } ); } ) - .catch( ( error ) => { - console.warn( error ); - } ); + .catch( progressPlannerShowOnboardError ); }; /** @@ -58,15 +87,19 @@ const progressPlannerOnboardCall = ( data ) => { progressPlannerAjaxRequest( { url: progressPlanner.onboardNonceURL, data, - } ).then( ( response ) => { - if ( 'ok' === response.status ) { + } ) + .then( ( response ) => { + if ( ! response || 'ok' !== response.status ) { + progressPlannerShowOnboardError( response ); + return; + } // Add the nonce to our data object. data.nonce = response.nonce; // Make the request to the API. progressPlannerAjaxAPIRequest( data ); - } - } ); + } ) + .catch( progressPlannerShowOnboardError ); }; if ( document.getElementById( 'prpl-onboarding-form' ) ) { @@ -133,6 +166,9 @@ if ( document.getElementById( 'prpl-onboarding-form' ) ) { return; } + // Hide an error from a previous attempt. + document.getElementById( 'prpl-onboarding-error' ).hidden = true; + // Disable all (both buttons) submit buttons. document .querySelectorAll( diff --git a/classes/admin/class-page.php b/classes/admin/class-page.php index e4eb12167..e356e49cb 100644 --- a/classes/admin/class-page.php +++ b/classes/admin/class-page.php @@ -178,6 +178,7 @@ public function enqueue_scripts() { 'onboardAPIUrl' => \progress_planner()->get_utils__onboard()->get_remote_url( 'onboard' ), 'ajaxUrl' => \admin_url( 'admin-ajax.php' ), 'nonce' => \wp_create_nonce( 'progress_planner' ), + 'onboardError' => \__( 'We could not connect your site. Please try again, or contact support if this keeps happening.', 'progress-planner' ), ], ]; 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..6fc9ec91b 100644 --- a/classes/class-lessons.php +++ b/classes/class-lessons.php @@ -14,6 +14,16 @@ */ class Lessons { + /** + * Lesson fields that contain HTML; every other string field is plain text. + */ + private const HTML_FIELDS = [ 'text', 'todo_description' ]; + + /** + * Version of the sanitized lessons cache. Bump it whenever `sanitize_items()` changes. + */ + private const CACHE_VERSION = 2; + /** * The ID for this API object. * @@ -53,18 +63,10 @@ public function get_items() { * - Additional fields as provided by remote API */ 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() ), - ], - $url - ); - - $cache_key = \md5( $url ); + $url = $this->get_remote_api_url(); + $cache_key = $this->get_cache_key(); + // Cached lessons were sanitized before they were stored (see CACHE_VERSION). $cached = \progress_planner()->get_utils__cache()->get( $cache_key ); if ( \is_array( $cached ) ) { return $cached; @@ -91,10 +93,91 @@ public function get_remote_api_items() { return []; } - // Cache successful response for one week. - \progress_planner()->get_utils__cache()->set( $cache_key, $json, WEEK_IN_SECONDS ); + // Sanitize once, then cache the successful response for one week. + $items = $this->sanitize_items( $json ); + \progress_planner()->get_utils__cache()->set( $cache_key, $items, WEEK_IN_SECONDS ); + + return $items; + } + + /** + * Get the URL of the remote lessons endpoint for this site and locale. + * + * @return string + */ + public function get_remote_api_url() { + return \add_query_arg( + [ + 'site' => \get_site_url(), + 'locale' => \apply_filters( 'prpl_lesson_locale', \get_locale() ), + ], + \progress_planner()->get_remote_server_root_url() . '/wp-json/progress-planner-saas/v1/lessons' + ); + } - return $json; + /** + * Get the cache key for the lessons. + * + * The key includes CACHE_VERSION, so entries cached before sanitizing (or before + * a sanitizer change) are never read and are fetched again once. + * + * @return string + */ + public function get_cache_key() { + return \md5( $this->get_remote_api_url() . '|v' . self::CACHE_VERSION ); + } + + /** + * Sanitize remote lesson content before it is cached. + * + * Only fields that carry markup keep (filtered) HTML. Everything else is plain + * text: running it through kses would HTML-encode `&` in names and IDs. + * + * @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 ) ) { + if ( 'video' === $key ) { + $items[ $key ] = $this->sanitize_video( $value ); + } elseif ( \in_array( $key, self::HTML_FIELDS, true ) ) { + $items[ $key ] = \wp_kses_post( $value ); + } else { + $items[ $key ] = \sanitize_text_field( $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' ); + // `style` is filtered by kses (safecss); `allow` and `loading` are needed by the Cloudflare Stream embed. + $allowed['iframe'] = \array_fill_keys( [ 'src', 'title', 'width', 'height', 'allowfullscreen', 'frameborder', 'style', 'allow', 'loading' ], 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 ) ? \strtolower( (string) \wp_parse_url( $src, PHP_URL_HOST ) ) : ''; + if ( ! \is_string( $src ) || 'https' !== \wp_parse_url( $src, PHP_URL_SCHEME ) + || ( ! \in_array( $host, [ 'www.youtube.com', 'www.youtube-nocookie.com', 'player.vimeo.com', 'iframe.mediadelivery.net' ], true ) + // Lesson videos are served from per-account Cloudflare Stream subdomains. + && ! \str_ends_with( $host, '.cloudflarestream.com' ) ) + ) { + $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..548da7f57 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' ) ] ); } @@ -610,7 +610,7 @@ public function rest_prepare_recommendation( $response, $post ) { if ( $provider ) { $response->data['prpl_provider'] = $provider_term[0]; // Link should be added during run time, since it is not added for users without required capability. - $response->data['meta']['prpl_url'] = $response->data['meta']['prpl_url'] && $provider->capability_required() + $response->data['meta']['prpl_url'] = ! empty( $response->data['meta']['prpl_url'] ) && $provider->capability_required() ? \esc_url( (string) $response->data['meta']['prpl_url'] ) : ''; diff --git a/classes/rest/class-base.php b/classes/rest/class-base.php index be58f286b..ff0c33b4c 100644 --- a/classes/rest/class-base.php +++ b/classes/rest/class-base.php @@ -12,11 +12,65 @@ */ abstract class Base { + /** + * HTTP header that carries the site token. + */ + const TOKEN_HEADER = 'X-Progress-Planner-Token'; + + /** + * REST namespace of the token-authenticated endpoints. + */ + const REST_NAMESPACE = '/progress-planner/v1'; + + /** + * Route of the endpoint, relative to the namespace. Empty means no route. + */ + const ROUTE = ''; + /** * Constructor. */ public function __construct() { \add_action( 'rest_api_init', [ $this, 'register_rest_endpoint' ] ); + \add_filter( 'rest_post_dispatch', [ $this, 'prevent_caching' ], 10, 3 ); + } + + /** + * Keep responses of this endpoint out of every cache. + * + * With header authentication every caller requests the same URL. A cache + * that stored an authenticated response would hand it to anyone requesting + * that URL, and the server would get stale data back. WordPress only sends + * no-cache headers to logged-in users, and the server is not logged in. + * Runs for successful and rejected requests alike. + * + * @param mixed $response The response. + * @param mixed $server The REST server. + * @param mixed $request The request. + * + * @return mixed + */ + public function prevent_caching( $response, $server, $request ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed + if ( '' === static::ROUTE + || ! $response instanceof \WP_HTTP_Response + || ! $request instanceof \WP_REST_Request + ) { + return $response; + } + + $route = self::REST_NAMESPACE . static::ROUTE; + if ( $route !== $request->get_route() && 0 !== \strpos( $request->get_route(), $route . '/' ) ) { + return $response; + } + + $response->header( 'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0, private' ); + $response->header( 'Expires', 'Wed, 11 Jan 1984 05:00:00 GMT' ); + + // LiteSpeed Cache caches REST responses for guests by default and sends + // its own cache header, so the headers above alone do not stop it. + \do_action( 'litespeed_control_set_nocache', 'Progress Planner token-authenticated endpoint' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- LiteSpeed Cache's public API. + + return $response; } /** @@ -34,38 +88,38 @@ 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 the site token header, never a URL parameter. + * + * A dedicated header, not `Authorization: Bearer`: bearer-auth plugins (JWT + * and OAuth) try to decode every bearer token and reject the request before + * this check runs, and some Apache setups strip `Authorization` entirely. + * + * @param \WP_REST_Request $request The REST request. + * @return bool + */ + public function permissions_check( $request ) { + $token = $request->get_header( self::TOKEN_HEADER ); + return \is_string( $token ) && $this->validate_token( \trim( $token ) ); } /** * 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 +130,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..5f972e6af 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(); @@ -144,6 +144,29 @@ public function create_item_permissions_check( $request ) { return parent::create_item_permissions_check( $request ); } + /** + * Give plain new to-dos a resolvable provider before WordPress saves them. + * + * @param \WP_REST_Request $request The REST request. + * @return \WP_REST_Response|\WP_Error + */ + public function create_item( $request ) { + if ( empty( $request['prpl_recommendations_provider'] ) ) { + $term = \get_term_by( 'slug', 'user', 'prpl_recommendations_provider' ); + if ( $term ) { + $term_id = (int) $term->term_id; + } else { + $created = \wp_insert_term( 'user', 'prpl_recommendations_provider' ); + if ( \is_wp_error( $created ) ) { + return $created; + } + $term_id = (int) $created['term_id']; + } + $request->set_param( 'prpl_recommendations_provider', [ $term_id ] ); + } + return parent::create_item( $request ); + } + /** * Whether a create request is limited to a personal (`user`) to-do: it may * carry only the `user` provider term (or none) and must not set a slug. @@ -193,6 +216,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..50c493137 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 (X-Progress-Planner-Token: ) * * The token is generated and saved in the settings. * @@ -19,6 +19,11 @@ */ class Stats extends Base { + /** + * Route of the endpoint, relative to the namespace. + */ + const ROUTE = '/get-stats'; + /** * Register the REST-API endpoint. * @@ -27,18 +32,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..c0883178d 100644 --- a/classes/rest/class-tasks.php +++ b/classes/rest/class-tasks.php @@ -15,6 +15,11 @@ */ class Tasks extends Base { + /** + * Route of the endpoint, relative to the namespace. + */ + const ROUTE = '/tasks'; + /** * Register the REST-API endpoint. * @@ -28,13 +33,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..b9a1eea0d 100644 --- a/classes/ui/class-branding.php +++ b/classes/ui/class-branding.php @@ -28,6 +28,36 @@ final class Branding { */ private static $inline_css_attached = []; + /** + * SVG elements a remote icon may use (lowercase local names). + * + * Anything that can run script, load a resource or carry CSS + * (`script`, `style`, `foreignObject`, `use`, `image`, `a`, ...) is left out. + */ + private const SVG_ELEMENTS = [ 'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon', 'defs', 'lineargradient', 'radialgradient', 'stop', 'clippath', 'title' ]; + + /** + * SVG attributes a remote icon may use (lowercase names). No `on*`, `style`, `href` or `xlink:href`. + */ + private const SVG_ATTRIBUTES = [ 'id', 'd', 'x', 'y', 'x1', 'x2', 'y1', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'fx', 'fy', 'width', 'height', 'viewbox', 'preserveaspectratio', 'points', 'transform', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'clip-rule', 'clip-path', 'clippathunits', 'opacity', 'offset', 'stop-color', 'stop-opacity', 'gradientunits', 'gradienttransform', 'role', 'aria-hidden', 'focusable', 'version' ]; + + /** + * Attributes that accept paint or references; their values are checked against `SVG_PAINT_PATTERN`. + */ + private const SVG_PAINT_ATTRIBUTES = [ 'fill', 'stroke', 'stop-color', 'clip-path' ]; + + /** + * Literal colors, or a reference to an element inside the same SVG (`url(#id)`), never an external URL. + */ + private const SVG_PAINT_PATTERN = '/^(?:#[0-9a-f]{3,8}|[a-z]+|rgba?\(\s*[0-9.%\s,\/]+\)|url\(\s*#[a-z_][\w.:-]*\s*\))$/iD'; + + /** + * Sanitized SVGs for this request, keyed by the hash of the remote markup. + * + * @var array + */ + private $sanitized_svgs = []; + /** * Constructor. */ @@ -38,9 +68,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 +86,16 @@ 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 + // Administrator-only preview seam for branded-host rendering. A preview only + // changes how the current page looks; `Base::init()` passes false, so it can + // never trigger the auto-onboard remote call (1.10.0 audit S3). No nonce: + // preview links are shared and bookmarked, and a nonce is user-bound and expires. + if ( $allow_preview + && isset( $_GET['pp_branding_id'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended + && \is_scalar( $_GET['pp_branding_id'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended + && \current_user_can( 'manage_options' ) + ) { + return \absint( $_GET['pp_branding_id'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended } $hostname = (string) \gethostname(); @@ -164,7 +200,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'] ?? '' ) ); } /** @@ -206,9 +242,10 @@ public function get_admin_menu_icon( bool $raw = false ): string { if ( $admin_menu_icon_url ) { // 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; + $content = $this->get_remote_data( $admin_menu_icon_url ); + $sanitized = $content && \is_string( $content ) ? $this->sanitize_svg( $content ) : ''; + if ( '' !== $sanitized ) { + $svg = $sanitized; } } @@ -220,13 +257,85 @@ public function get_admin_menu_icon( bool $raw = false ): string { return 'data:image/svg+xml;base64,' . \base64_encode( $svg ); } + // phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM properties are camelCase. + + /** + * Keep only inert SVG shapes, gradients and clip paths, with no scripts, styles or external references. + * + * The markup is parsed as XML, so case-sensitive names such as `viewBox` and + * `linearGradient` survive (the result is also used as an XML data URI). + * + * @param string $svg Remote SVG markup. + * @return string Sanitized markup, or an empty string when it is not a usable SVG. + */ + public function sanitize_svg( string $svg ): string { + $hash = \md5( $svg ); + if ( isset( $this->sanitized_svgs[ $hash ] ) ) { + return $this->sanitized_svgs[ $hash ]; + } + $this->sanitized_svgs[ $hash ] = ''; + + // DTDs can declare entities (billion laughs, external files); an icon never needs one. + if ( ! \class_exists( '\DOMDocument' ) || false !== \stripos( $svg, 'loadXML( $svg, LIBXML_NONET ); + \libxml_clear_errors(); + \libxml_use_internal_errors( $previous ); + + $root = $dom->documentElement; + if ( ! $loaded || ! $root || 'svg' !== \strtolower( (string) $root->localName ) ) { + return ''; + } + + $this->sanitize_svg_element( $root ); + // Required when the icon is used as a standalone SVG data URI. + if ( 'http://www.w3.org/2000/svg' !== $root->namespaceURI ) { + $root->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.w3.org/2000/svg' ); + } + + $this->sanitized_svgs[ $hash ] = (string) $dom->saveXML( $root ); + return $this->sanitized_svgs[ $hash ]; + } + + /** + * Remove disallowed attributes and children from an SVG element, recursively. + * + * @param \DOMElement $element The element to clean. + * @return void + */ + private function sanitize_svg_element( \DOMElement $element ): void { + foreach ( \iterator_to_array( $element->attributes ) as $attribute ) { + $name = \strtolower( $attribute->nodeName ); + if ( ! \in_array( $name, self::SVG_ATTRIBUTES, true ) + || ( \in_array( $name, self::SVG_PAINT_ATTRIBUTES, true ) && ! \preg_match( self::SVG_PAINT_PATTERN, \trim( $attribute->value ) ) ) + ) { + $element->removeAttributeNode( $attribute ); + } + } + + $is_title = 'title' === \strtolower( (string) $element->localName ); + foreach ( \iterator_to_array( $element->childNodes ) as $child ) { + if ( $child instanceof \DOMElement && \in_array( \strtolower( (string) $child->localName ), self::SVG_ELEMENTS, true ) ) { + $this->sanitize_svg_element( $child ); + } elseif ( ! ( $is_title && XML_TEXT_NODE === $child->nodeType ) ) { + // Drops disallowed elements with their content, comments, CDATA and processing instructions. + $element->removeChild( $child ); + } + } + } + // phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + /** * 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 +344,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 +376,19 @@ public function get_ravi_name(): string { * @return mixed */ public function get_remote_data( $url ) { + // Only fetch from the configured branding server (scheme and host), so a URL in + // the remote brand document cannot point anywhere else. Checked before cache + // access too, so old responses cannot bypass the restriction. + $server = \progress_planner()->get_branding_server_url(); + $host = \wp_parse_url( $server, PHP_URL_HOST ); + $scheme = \wp_parse_url( $server, PHP_URL_SCHEME ); + if ( ! $host || ! $scheme + || \strtolower( $scheme ) !== \strtolower( (string) \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 +396,9 @@ public function get_remote_data( $url ) { return $cached; } - $response = \wp_remote_get( $url ); + // Not wp_safe_remote_get(): the host is pinned above to the site owner's own + // configuration, which may be a local or private development server. + $response = \wp_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 +441,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..df2b79bff 100644 --- a/classes/utils/class-onboard.php +++ b/classes/utils/class-onboard.php @@ -150,12 +150,14 @@ public function make_remote_onboarding_request( $data = [] ) { ] ); - // Make the request. + // Make the request. Not wp_safe_remote_post(): the URL is hardcoded or set by the + // site owner in wp-config.php, and may be a local development server. $response = \wp_remote_post( $this->get_remote_url( 'onboard' ), [ - 'timeout' => 10, - 'body' => $data, + 'timeout' => 10, + 'redirection' => 0, + 'body' => $data, ] ); diff --git a/tests/e2e/api/tasks.api.ts b/tests/e2e/api/tasks.api.ts index a3e06d16c..08d06440e 100644 --- a/tests/e2e/api/tasks.api.ts +++ b/tests/e2e/api/tasks.api.ts @@ -40,19 +40,17 @@ export class TasksApi { // Suppress unused variable warning - cookies kept for future auth needs void this.getAuthCookies(); - const params: Record< string, string > = {}; // Use test token from environment or fallback to the value set in blueprint.json const testToken = process.env.PRPL_TEST_TOKEN || '0220a2de67fc29094281088395939f58'; - params.token = testToken; const response = await this.request.get( `${ this.baseUrl }/?rest_route=${ endpoint }`, { headers: { 'Content-Type': 'application/json', + 'X-Progress-Planner-Token': testToken, }, - params, } ); 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..c4431994d 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', - [] + [], + [ 'X-Progress-Planner-Token' => $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', - [] + [], + [ 'X-Progress-Planner-Token' => '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', - [] + [], + [ 'X-Progress-Planner-Token' => $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..8e98857b3 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 ] + [], + [ 'X-Progress-Planner-Token' => $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' ] + [], + [ 'X-Progress-Planner-Token' => '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 ] + [], + [ 'X-Progress-Planner-Token' => $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-api-get-stats.php b/tests/phpunit/test-class-api-get-stats.php index 38fdca6f2..22f83d8bc 100644 --- a/tests/phpunit/test-class-api-get-stats.php +++ b/tests/phpunit/test-class-api-get-stats.php @@ -66,18 +66,7 @@ public static function get_lessons() { * @return void */ public static function set_lessons_cache() { - // Mimic the URL building and caching of the lessons, see Progress_Planner\Lessons::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(), - ], - $url - ); - - $cache_key = \md5( $url ); + $cache_key = \progress_planner()->get_lessons()->get_cache_key(); \progress_planner()->get_utils__cache()->set( $cache_key, self::get_lessons(), WEEK_IN_SECONDS ); } @@ -119,7 +108,8 @@ public function tearDown(): void { * @return void. */ public function testEndpoint() { - $request = new WP_REST_Request( 'GET', '/progress-planner/v1/get-stats/' . $this->token ); + $request = new WP_REST_Request( 'GET', '/progress-planner/v1/get-stats' ); + $request->set_header( 'X-Progress-Planner-Token', $this->token ); $response = $this->server->dispatch( $request ); // Check if the response is successful. diff --git a/tests/phpunit/test-class-branding-preview-param.php b/tests/phpunit/test-class-branding-preview-param.php index 4809f7dc4..bb3e9808a 100644 --- a/tests/phpunit/test-class-branding-preview-param.php +++ b/tests/phpunit/test-class-branding-preview-param.php @@ -1,13 +1,7 @@ assertSame( 0, $branding_id, 'a subscriber must not be able to set pp_branding_id' ); } + /** + * A preview link changes the branding for the page but never grants onboarding consent. + * + * @return void + */ + public function test_admin_preview_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( 4958, $branding->get_branding_id() ); + $this->assertSame( 0, $branding->get_branding_id( false ) ); + } } diff --git a/tests/phpunit/test-class-branding.php b/tests/phpunit/test-class-branding.php index 725b4dcdd..64aaa83f1 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(); diff --git a/tests/phpunit/test-class-page-types.php b/tests/phpunit/test-class-page-types.php index becd2c962..e55eef843 100644 --- a/tests/phpunit/test-class-page-types.php +++ b/tests/phpunit/test-class-page-types.php @@ -67,19 +67,7 @@ public static function get_lessons() { * @return void */ public static function set_lessons_cache() { - // Mimic the URL building and caching of the lessons, see Progress_Planner\Lessons::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() ), - ], - $url - ); - - $cache_key = \md5( $url ); + $cache_key = \progress_planner()->get_lessons()->get_cache_key(); \progress_planner()->get_utils__cache()->set( $cache_key, self::get_lessons(), WEEK_IN_SECONDS ); } diff --git a/tests/phpunit/test-class-rest-base.php b/tests/phpunit/test-class-rest-base.php index 38af0aead..c037bf84d 100644 --- a/tests/phpunit/test-class-rest-base.php +++ b/tests/phpunit/test-class-rest-base.php @@ -33,7 +33,26 @@ public function setUp(): void { } /** - * Test get_client_ip with Cloudflare header. + * Only the dedicated token header authenticates; a bearer token is never read, + * so bearer-auth plugins and the site token cannot interfere with each other. + * + * @return void + */ + public function test_only_the_token_header_authenticates() { + \update_option( 'progress_planner_license_key', 'fixture-license' ); + \delete_transient( 'prpl_api_rate_limit_' . \md5( '0.0.0.0' ) ); + unset( $_SERVER['REMOTE_ADDR'] ); + $request = new \WP_REST_Request( 'GET', '/progress-planner/v1/tasks' ); + $request->set_header( 'Authorization', 'Bearer fixture-license' ); + $this->assertFalse( $this->rest_instance->permissions_check( $request ) ); + $request->set_header( 'x-progress-planner-token', 'fixture-license' ); + $this->assertTrue( $this->rest_instance->permissions_check( $request ) ); + $request->set_header( 'X-Progress-Planner-Token', 'wrong-key' ); + $this->assertFalse( $this->rest_instance->permissions_check( $request ) ); + } + + /** + * Test get_client_ip ignores an untrusted Cloudflare header. * * @return void */ @@ -49,11 +68,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 +88,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 +108,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 +128,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 +269,7 @@ public function test_validate_token_test_token() { } /** - * Test validate_token with token containing "token/" prefix. + * Token validation compares the entire token, including any prefix. * * @return void */ @@ -270,7 +289,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-recommendations-permissions.php b/tests/phpunit/test-class-rest-recommendations-permissions.php index bd6fd213f..63e6c26be 100644 --- a/tests/phpunit/test-class-rest-recommendations-permissions.php +++ b/tests/phpunit/test-class-rest-recommendations-permissions.php @@ -13,8 +13,9 @@ * leaking pending-update state, draft titles, the active SEO plugin, etc. * * The fix requires `edit_others_posts` (the plugin's own UI gate) for every - * read and write operation on the endpoint. Editors and admins keep full - * access; everyone below is rejected. + * read and write operation on the endpoint. Each task also requires its + * provider's capability; editors can manage user to-dos, while administrator + * tasks remain restricted to administrators. * * @package Progress_Planner\Tests */ @@ -45,11 +46,11 @@ public function setUp(): void { $wp_rest_server = new \WP_REST_Server(); \do_action( 'rest_api_init' ); - $this->task_id = self::factory()->post->create( + $this->task_id = \progress_planner()->get_suggested_tasks_db()->add( [ - 'post_type' => 'prpl_recommendations', - 'post_title' => 'Perform all updates', - 'post_name' => 'update-core-202638', + 'provider_id' => 'user', + 'post_title' => 'Review the site content', + 'task_id' => 'user-review-content', 'post_status' => 'publish', ] ); @@ -250,11 +251,27 @@ public function test_editor_can_create_and_delete_own_task() { ); $this->assertSame( 201, $create->get_status(), 'editor create should be allowed' ); $new_id = $create->get_data()['id']; + $this->assertTrue( \has_term( 'user', 'prpl_recommendations_provider', $new_id ) ); + $read = $this->request_as( $editor, 'GET', '/wp/v2/prpl_recommendations/' . $new_id ); + $this->assertSame( 200, $read->get_status(), 'new to-do should be readable' ); $delete = $this->request_as( $editor, 'DELETE', '/wp/v2/prpl_recommendations/' . $new_id, [ 'force' => true ] ); $this->assertSame( 200, $delete->get_status(), 'editor delete of own task should be allowed' ); } + /** + * A plain to-do without URL metadata still has a valid REST response. + * + * @return void + */ + public function test_task_response_without_url_metadata() { + \wp_set_current_user( self::factory()->user->create( [ 'role' => 'editor' ] ) ); + $post = \get_post( $this->task_id ); + $response = new \WP_REST_Response( [ 'slug' => $post->post_name ] ); + $response = \progress_planner()->get_suggested_tasks()->rest_prepare_recommendation( $response, $post ); + $this->assertSame( '', $response->get_data()['meta']['prpl_url'] ); + } + /** * Legitimate flow: an Editor CAN assign the provider taxonomy term, which * the tightened `assign_terms` capability must not block. 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..d24b60337 --- /dev/null +++ b/tests/phpunit/test-class-security-review.php @@ -0,0 +1,562 @@ +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' ) ); + } + + /** + * Header authentication works without credentials in the URL. + * + * @return void + */ + public function test_token_header_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( 'X-Progress-Planner-Token', 'fixture-license' ); + $this->assertSame( 200, \rest_do_request( $request )->get_status() ); + $request->set_header( 'X-Progress-Planner-Token', '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 ) ); + } + } + + /** + * Requests to the configured remote and branding servers allow local development hosts. + * + * @return void + */ + public function test_configured_servers_allow_local_hosts() { + $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_utils__onboard()->make_remote_onboarding_request( [ 'nonce' => 'fixture' ] ); + \progress_planner()->get_ui__branding()->get_remote_data( \progress_planner()->get_branding_server_url() . '/v1/brands/local-test.json' ); + } finally { + \remove_filter( 'pre_http_request', $mock, 20 ); + } + $this->assertCount( 2, $requests ); + foreach ( $requests as $args ) { + $this->assertEmpty( $args['reject_unsafe_urls'] ); + $this->assertSame( 0, $args['redirection'] ); + } + } + + /** + * 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 ); + } + + /** + * Lessons are sanitized once before caching, and pre-sanitizer cache entries are not read. + * + * @return void + */ + public function test_lessons_are_sanitized_before_caching() { + $lessons = \progress_planner()->get_lessons(); + $cache = \progress_planner()->get_utils__cache(); + // An entry stored under the old, unversioned key must be ignored. + $cache->set( \md5( $lessons->get_remote_api_url() ), [ [ 'name' => '' ] ], MINUTE_IN_SECONDS ); + $cache->delete( $lessons->get_cache_key() ); + + $requests = 0; + $mock = function () use ( &$requests ) { + ++$requests; + return [ + 'response' => [ 'code' => 200 ], + 'body' => \wp_json_encode( [ [ 'intro' => [ 'text' => '

Hi

' ] ] ] ), + ]; + }; + \add_filter( 'pre_http_request', $mock, 20, 3 ); + try { + $first = $lessons->get_remote_api_items(); + $second = $lessons->get_remote_api_items(); + } finally { + \remove_filter( 'pre_http_request', $mock, 20 ); + $cache->delete( $lessons->get_cache_key() ); + } + + $this->assertSame( 1, $requests ); + $this->assertSame( '

Hi

', $first[0]['intro']['text'] ); + $this->assertSame( $first, $second ); + } + + /** + * The Cloudflare Stream embed used by the real lessons keeps its source and layout. + * + * @return void + */ + public function test_cloudflare_stream_lesson_video_is_kept() { + $video = ( new \Progress_Planner\Lessons() )->sanitize_video( + '
' + . '' + ); + $this->assertStringContainsString( 'src="https://customer-abc123.cloudflarestream.com/0292a4e6/iframe?poster=x"', $video ); + $this->assertStringContainsString( 'position: absolute', $video ); + $this->assertStringContainsString( 'allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;"', $video ); + $this->assertStringContainsString( 'loading="lazy"', $video ); + $this->assertStringContainsString( 'sandbox=', $video ); + $this->assertStringNotContainsString( 'onload', $video ); + $this->assertStringNotContainsString( 'evil.example', $video ); + } + + /** + * Plain-text lesson fields keep their characters; only HTML fields keep markup. + * + * @return void + */ + public function test_lesson_text_fields_are_not_html_encoded() { + $data = ( new \Progress_Planner\Lessons() )->sanitize_items( + [ + [ + 'name' => 'Terms & Conditions', + 'settings' => [ + 'id' => 'terms-&-conditions', + 'title' => 'Terms & Conditions', + ], + 'intro' => [ + 'heading' => 'Q&A now', + 'text' => '

Read & learn

', + ], + ], + ] + ); + $this->assertSame( 'Terms & Conditions', $data[0]['name'] ); + $this->assertSame( 'terms-&-conditions', $data[0]['settings']['id'] ); + $this->assertSame( 'Terms & Conditions', $data[0]['settings']['title'] ); + $this->assertSame( 'Q&A now', $data[0]['intro']['heading'] ); + $this->assertSame( '

Read & learn

', $data[0]['intro']['text'] ); + } + + /** + * Inert icon structure survives sanitizing, including case-sensitive XML names. + * + * @return void + */ + public function test_svg_sanitizer_keeps_inert_icon_structure() { + $branding = \progress_planner()->get_ui__branding(); + $svg = $branding->sanitize_svg( + '' + ); + $this->assertStringContainsString( 'viewBox="0 0 10 10"', $svg ); + $this->assertStringContainsString( '', $svg ); + $this->assertStringContainsString( '', $svg ); + $this->assertStringContainsString( 'fill="url(#g)" clip-path="url(#c)"', $svg ); + $this->assertStringContainsString( 'fill="rgb(1, 2, 3)" opacity=".5"', $svg ); + $this->assertStringContainsString( 'role="img" aria-hidden="true" focusable="false"', $svg ); + $this->assertStringContainsString( 'Icon', $svg ); + $this->assertStringContainsString( 'stroke="url( #g )"', $svg ); + $this->assertStringNotContainsString( 'evil.example', $svg ); + $this->assertStringNotContainsString( 'style=', $svg ); + $this->assertStringNotContainsString( 'assertStringNotContainsString( 'assertSame( '', $branding->sanitize_svg( ']>&a;' ) ); + $this->assertSame( '', $branding->sanitize_svg( '' ) ); + $this->assertSame( '', $branding->sanitize_svg( 'not markup' ) ); + } + + /** + * 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'; + $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}