Commit 3972c5c6119 for woocommerce
commit 3972c5c6119d12da037a9c8c37beb073bc5cf60a
Author: Lucio Giannotta <lucio.giannotta@a8c.com>
Date: Thu Nov 26 02:32:13 2026 +0100
Clean up custom webhook topics and keep the webhook author up to date (#71154)
---------
Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
diff --git a/plugins/woocommerce/changelog/fix-custom-webhook-topics b/plugins/woocommerce/changelog/fix-custom-webhook-topics
new file mode 100644
index 00000000000..56513227158
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-custom-webhook-topics
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Improve custom topic webhooks: stricter topic checks, cleaner payloads, and no self-triggered deliveries.
diff --git a/plugins/woocommerce/changelog/fix-webhook-author-on-delivery-url-change b/plugins/woocommerce/changelog/fix-webhook-author-on-delivery-url-change
new file mode 100644
index 00000000000..a723ed6b893
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-webhook-author-on-delivery-url-change
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Update the webhook author when a different user changes its delivery URL.
diff --git a/plugins/woocommerce/changelog/tweak-webhook-author-display b/plugins/woocommerce/changelog/tweak-webhook-author-display
new file mode 100644
index 00000000000..176ba444ecb
--- /dev/null
+++ b/plugins/woocommerce/changelog/tweak-webhook-author-display
@@ -0,0 +1,4 @@
+Significance: patch
+Type: tweak
+
+Show the webhook author on the webhook edit screen.
diff --git a/plugins/woocommerce/changelog/tweak-webhook-delete-user-warning b/plugins/woocommerce/changelog/tweak-webhook-delete-user-warning
new file mode 100644
index 00000000000..b5f47e16079
--- /dev/null
+++ b/plugins/woocommerce/changelog/tweak-webhook-delete-user-warning
@@ -0,0 +1,4 @@
+Significance: patch
+Type: tweak
+
+Explain on the delete user screen what happens to webhooks that are attributed to another user.
diff --git a/plugins/woocommerce/client/legacy/css/admin.scss b/plugins/woocommerce/client/legacy/css/admin.scss
index 01c00ec7d8b..2038302333e 100644
--- a/plugins/woocommerce/client/legacy/css/admin.scss
+++ b/plugins/woocommerce/client/legacy/css/admin.scss
@@ -8153,6 +8153,14 @@ table.bar_chart {
padding-top: 20px;
}
+ // Plain-text values: line up with the label text. Stacked mobile layouts already do.
+ @media screen and (min-width: 783px) {
+
+ .woocommerce table.form-table td.forminp-static {
+ padding-top: 25px;
+ }
+ }
+
.woocommerce table.form-table textarea {
padding: 6px 8px;
}
diff --git a/plugins/woocommerce/includes/admin/class-wc-admin-webhooks.php b/plugins/woocommerce/includes/admin/class-wc-admin-webhooks.php
index 8972f56a710..b87bbe23972 100644
--- a/plugins/woocommerce/includes/admin/class-wc-admin-webhooks.php
+++ b/plugins/woocommerce/includes/admin/class-wc-admin-webhooks.php
@@ -92,10 +92,16 @@ class WC_Admin_Webhooks {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$delivery_url = ! empty( $_POST['webhook_delivery_url'] ) ? esc_url_raw( wp_unslash( $_POST['webhook_delivery_url'] ) ) : '';
- if ( wc_is_valid_url( $delivery_url ) ) {
+ // An untouched form sends back the URL it displayed. That URL can differ from the stored one when a filter changes it, and it is not a change.
+ if ( wc_is_valid_url( $delivery_url ) && esc_url_raw( $webhook->get_delivery_url() ) !== $delivery_url ) {
$webhook->set_delivery_url( $delivery_url );
}
+ // Payloads are built as the author, so whoever changes where they go becomes the author.
+ if ( array_key_exists( 'delivery_url', $webhook->get_changes() ) ) {
+ $webhook->set_user_id( get_current_user_id() );
+ }
+
// Secret.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$secret = ! empty( $_POST['webhook_secret'] ) ? sanitize_text_field( wp_unslash( $_POST['webhook_secret'] ) ) : wp_generate_password( 50, true, true );
@@ -126,7 +132,7 @@ class WC_Admin_Webhooks {
if ( wc_is_webhook_valid_topic( $topic ) ) {
$webhook->set_topic( $topic );
} else {
- $errors[] = __( 'Webhook topic unknown. Please select a valid topic.', 'woocommerce' );
+ $errors[] = __( 'This webhook topic is not supported. Choose a different topic.', 'woocommerce' );
}
}
diff --git a/plugins/woocommerce/includes/admin/settings/views/html-webhooks-edit.php b/plugins/woocommerce/includes/admin/settings/views/html-webhooks-edit.php
index dcb76df879f..ef22c262d56 100644
--- a/plugins/woocommerce/includes/admin/settings/views/html-webhooks-edit.php
+++ b/plugins/woocommerce/includes/admin/settings/views/html-webhooks-edit.php
@@ -117,7 +117,8 @@ if ( ! defined( 'ABSPATH' ) ) {
</label>
</th>
<td class="forminp">
- <input name="webhook_delivery_url" id="webhook_delivery_url" type="text" class="input-text regular-input" value="<?php echo esc_attr( $webhook->get_delivery_url() ); ?>" />
+ <?php // esc_attr() keeps entities such as & as they are, so the browser would decode them and send back a different URL. esc_textarea() encodes them again. ?>
+ <input name="webhook_delivery_url" id="webhook_delivery_url" type="text" class="input-text regular-input" value="<?php echo esc_textarea( $webhook->get_delivery_url() ); ?>" />
</td>
</tr>
<tr valign="top">
@@ -163,6 +164,31 @@ if ( ! defined( 'ABSPATH' ) ) {
</select>
</td>
</tr>
+ <?php if ( $webhook->get_id() ) : ?>
+ <tr valign="top">
+ <th scope="row" class="titledesc">
+ <span class="wc-settings-radio-title">
+ <?php esc_html_e( 'Author', 'woocommerce' ); ?>
+ <?php echo wc_help_tip( __( 'Payloads are built as this user. Changing the delivery URL makes you the author.', 'woocommerce' ) ); ?>
+ </span>
+ </th>
+ <td class="forminp forminp-static">
+ <?php
+ $webhook_author = get_userdata( $webhook->get_user_id() );
+
+ if ( $webhook_author ) {
+ /* translators: 1: user display name, 2: username */
+ $webhook_author_label = sprintf( __( '%1$s (%2$s)', 'woocommerce' ), $webhook_author->display_name, $webhook_author->user_login );
+ $webhook_author_link = get_edit_user_link( $webhook_author->ID );
+
+ echo $webhook_author_link ? '<a href="' . esc_url( $webhook_author_link ) . '">' . esc_html( $webhook_author_label ) . '</a>' : esc_html( $webhook_author_label );
+ } else {
+ esc_html_e( 'None', 'woocommerce' );
+ }
+ ?>
+ </td>
+ </tr>
+ <?php endif; ?>
</tbody>
</table>
@@ -186,7 +212,7 @@ if ( ! defined( 'ABSPATH' ) ) {
<th scope="row" class="titledesc">
<?php esc_html_e( 'Created at', 'woocommerce' ); ?>
</th>
- <td class="forminp">
+ <td class="forminp forminp-static">
<?php echo esc_html( date_i18n( __( 'M j, Y @ G:i', 'woocommerce' ), strtotime( $webhook->get_date_created()->date( 'Y-m-d H:i:s' ) ) ) ); ?>
</td>
</tr>
@@ -195,7 +221,7 @@ if ( ! defined( 'ABSPATH' ) ) {
<th scope="row" class="titledesc">
<?php esc_html_e( 'Created at', 'woocommerce' ); ?>
</th>
- <td class="forminp">
+ <td class="forminp forminp-static">
<?php echo esc_html( date_i18n( __( 'M j, Y @ G:i', 'woocommerce' ), strtotime( $webhook->get_date_created()->date( 'Y-m-d H:i:s' ) ) ) ); ?>
</td>
</tr>
@@ -203,7 +229,7 @@ if ( ! defined( 'ABSPATH' ) ) {
<th scope="row" class="titledesc">
<?php esc_html_e( 'Updated at', 'woocommerce' ); ?>
</th>
- <td class="forminp">
+ <td class="forminp forminp-static">
<?php echo esc_html( date_i18n( __( 'M j, Y @ G:i', 'woocommerce' ), strtotime( $webhook->get_date_modified()->date( 'Y-m-d H:i:s' ) ) ) ); ?>
</td>
</tr>
diff --git a/plugins/woocommerce/includes/class-wc-webhook.php b/plugins/woocommerce/includes/class-wc-webhook.php
index cbb199606f1..f436f74ed10 100644
--- a/plugins/woocommerce/includes/class-wc-webhook.php
+++ b/plugins/woocommerce/includes/class-wc-webhook.php
@@ -14,6 +14,9 @@
use Automattic\Jetpack\Constants;
use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\Enums\ProductStatus;
+use Automattic\WooCommerce\Internal\Webhooks\WebhookCaptureRules;
+use Automattic\WooCommerce\Internal\Webhooks\WebhookObservers;
+use Automattic\WooCommerce\Internal\Webhooks\WebhookPayloadRedactor;
use Automattic\WooCommerce\Utilities\NumberUtil;
use Automattic\WooCommerce\Utilities\OrderUtil;
use Automattic\WooCommerce\Utilities\RestApiUtil;
@@ -116,7 +119,7 @@ class WC_Webhook extends WC_Legacy_Webhook {
$this->enqueued_blog_id = get_current_blog_id();
foreach ( $hooks as $hook ) {
- add_action( $hook, array( $this, 'process' ) );
+ WebhookCaptureRules::subscribe( $hook, array( $this, 'process' ), array( $this, 'process_with_context' ) );
}
}
}
@@ -130,13 +133,45 @@ class WC_Webhook extends WC_Legacy_Webhook {
* @return mixed $arg Returns the argument in case the webhook was hooked into a filter.
*/
public function process( $arg ) {
+ $hook = current_filter();
+ if ( $hook && ( WebhookObservers::is_suppressed( $hook ) || ! WebhookCaptureRules::allows_argument( $hook, $arg ) ) ) {
+ return $arg;
+ }
+
+ WebhookObservers::without_observers( fn() => $this->dispatch_delivery( $arg ) );
+
+ return $arg;
+ }
+
+ /**
+ * Check extra hook arguments before processing the webhook.
+ *
+ * @since 11.4.0
+ * @internal
+ *
+ * @param mixed $arg First hook argument.
+ * @param mixed ...$context Extra hook arguments.
+ * @return mixed The first hook argument.
+ */
+ public function process_with_context( $arg, ...$context ) {
+ $hook = current_filter();
+ if ( $hook && ! WebhookCaptureRules::allows_context( $hook, $context ) ) {
+ return $arg;
+ }
+
+ return $this->process( $arg );
+ }
- // Verify that webhook should be processed for delivery.
+ /**
+ * Check whether to deliver the webhook and dispatch it when allowed.
+ *
+ * @param mixed $arg First hook argument.
+ */
+ private function dispatch_delivery( $arg ): void {
if ( ! $this->should_deliver( $arg ) ) {
return;
}
- // Mark this $arg as processed to ensure it doesn't get processed again within the current request.
$this->processed[] = $arg;
/**
@@ -146,8 +181,6 @@ class WC_Webhook extends WC_Legacy_Webhook {
* @hooked wc_webhook_process_delivery - 10
*/
do_action( 'woocommerce_webhook_process_delivery', $this, $arg );
-
- return $arg;
}
/**
@@ -383,6 +416,16 @@ class WC_Webhook extends WC_Legacy_Webhook {
* @param mixed $arg First hook argument.
*/
public function deliver( $arg ) {
+ $topic = WebhookObservers::without_observers( fn() => $this->get_topic() );
+ WebhookObservers::during_delivery( $topic, fn() => $this->deliver_request( $arg ) );
+ }
+
+ /**
+ * Send a webhook and record the outcome.
+ *
+ * @param mixed $arg First hook argument.
+ */
+ private function deliver_request( $arg ): void {
$start_time = microtime( true );
$payload = $this->build_payload( $arg );
@@ -406,7 +449,7 @@ class WC_Webhook extends WC_Legacy_Webhook {
*
* @since 3.3.0
* @param array $http_args The HTTP arguments.
- * @param mixed $arg The first hook argument.
+ * @param mixed $arg The first hook argument, redacted for background delivery of custom action topics.
* @param int $webhook_id The webhook ID.
* @return array The filtered HTTP arguments.
*/
@@ -491,19 +534,21 @@ class WC_Webhook extends WC_Legacy_Webhook {
$resource = $this->get_resource();
$event = $this->get_event();
+ $payload_arg = WebhookPayloadRedactor::redact_for_payload( $this->get_topic(), $resource, $resource_id );
+
// If a resource has been deleted, just include the ID in the payload.
$payload = array(
- 'id' => $resource_id,
+ 'id' => $payload_arg,
);
if ( 'deleted' !== $event ) {
$api_version = $this->get_api_version();
if ( in_array( $api_version, wc_get_webhook_rest_api_versions(), true ) ) {
- $payload = $this->get_wp_api_payload( $resource, $resource_id, $event );
+ $payload = $this->get_wp_api_payload( $resource, $payload_arg, $event );
} elseif ( 'legacy_v3' === $api_version && WC()->legacy_rest_api_is_available() ) {
wc_deprecated_function( 'Webhook delivery via the Legacy REST API', '9.0.0', 'editing the webhook to use a current API version' );
- $payload = wc()->api->get_webhook_api_payload( $resource, $resource_id, $event );
+ $payload = wc()->api->get_webhook_api_payload( $resource, $payload_arg, $event );
} else {
throw new \Exception( esc_html__( 'Unsupported webhook API version. Please edit this webhook to use a current REST API version.', 'woocommerce' ) );
}
diff --git a/plugins/woocommerce/includes/class-woocommerce.php b/plugins/woocommerce/includes/class-woocommerce.php
index e03ea4cb3b7..341cb5041e0 100644
--- a/plugins/woocommerce/includes/class-woocommerce.php
+++ b/plugins/woocommerce/includes/class-woocommerce.php
@@ -485,6 +485,8 @@ final class WooCommerce {
$container->get( Automattic\WooCommerce\Internal\ProductFilters\MainQueryController::class )->register();
$container->get( Automattic\WooCommerce\Internal\ProductFilters\CacheController::class )->register();
+ $container->get( Automattic\WooCommerce\Internal\Webhooks\WebhookTopicNotices::class )->register();
+ $container->get( Automattic\WooCommerce\Internal\Webhooks\WebhookScheduledActionArgs::class )->register();
// Integration point between legacy reports and orders APIs (the reports caches invalidation focused).
\WC_Admin_Reports::register_orders_hook_handlers();
diff --git a/plugins/woocommerce/includes/data-stores/class-wc-webhook-data-store.php b/plugins/woocommerce/includes/data-stores/class-wc-webhook-data-store.php
index 27c5d9320b4..7fdc33b5d37 100644
--- a/plugins/woocommerce/includes/data-stores/class-wc-webhook-data-store.php
+++ b/plugins/woocommerce/includes/data-stores/class-wc-webhook-data-store.php
@@ -131,8 +131,6 @@ class WC_Webhook_Data_Store implements WC_Webhook_Data_Store_Interface {
$data = array(
'status' => $webhook->get_status( 'edit' ),
'name' => $webhook->get_name( 'edit' ),
- 'user_id' => $webhook->get_user_id( 'edit' ),
- 'delivery_url' => $webhook->get_delivery_url( 'edit' ),
'secret' => $webhook->get_secret( 'edit' ),
'topic' => $webhook->get_topic( 'edit' ),
'date_modified' => $date_modified,
@@ -142,6 +140,18 @@ class WC_Webhook_Data_Store implements WC_Webhook_Data_Store_Interface {
'pending_delivery' => $webhook->get_pending_delivery( 'edit' ),
);
+ // The getter can return a filtered URL even when the URL was not edited,
+ // that's why we don't want to update it if it hasn't changed, so the filter
+ // isn't applied twice.
+ if ( $trigger ) {
+ $data['delivery_url'] = $webhook->get_delivery_url( 'edit' );
+ }
+
+ // Save the author with the URL. An unrelated save may hold an older author.
+ if ( $trigger || isset( $changes['user_id'] ) ) {
+ $data['user_id'] = $webhook->get_user_id( 'edit' );
+ }
+
$wpdb->update(
$wpdb->prefix . 'wc_webhooks',
$data,
diff --git a/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-webhooks-v1-controller.php b/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-webhooks-v1-controller.php
index 80a908c33fe..b5b9c691a7d 100644
--- a/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-webhooks-v1-controller.php
+++ b/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-webhooks-v1-controller.php
@@ -424,11 +424,22 @@ class WC_REST_Webhooks_V1_Controller extends WC_REST_Controller {
// Update delivery URL.
if ( ! empty( $request['delivery_url'] ) ) {
- if ( wc_is_valid_url( $request['delivery_url'] ) ) {
- $webhook->set_delivery_url( $request['delivery_url'] );
- } else {
+ if ( ! wc_is_valid_url( $request['delivery_url'] ) ) {
return new WP_Error( "woocommerce_rest_{$this->post_type}_invalid_delivery_url", __( 'Webhook delivery URL must be a valid URL starting with http:// or https://.', 'woocommerce' ), array( 'status' => 400 ) );
}
+
+ // Clients can send back the filtered URL from the response without editing it.
+ $delivery_url = esc_url_raw( $request['delivery_url'], array( 'http', 'https' ) );
+ if ( esc_url_raw( $webhook->get_delivery_url(), array( 'http', 'https' ) ) !== $delivery_url ) {
+ $webhook->set_delivery_url( $request['delivery_url'] );
+ }
+ }
+
+ // Payloads are built as the author, so whoever changes where they go becomes the author.
+ // Code running without a logged-in user, such as scheduled tasks, keeps the existing author.
+ $editor_id = get_current_user_id();
+ if ( $editor_id && array_key_exists( 'delivery_url', $webhook->get_changes() ) ) {
+ $webhook->set_user_id( $editor_id );
}
// Update secret.
diff --git a/plugins/woocommerce/includes/wc-webhook-functions.php b/plugins/woocommerce/includes/wc-webhook-functions.php
index a52aee247cf..2b5926a2fe3 100644
--- a/plugins/woocommerce/includes/wc-webhook-functions.php
+++ b/plugins/woocommerce/includes/wc-webhook-functions.php
@@ -9,6 +9,9 @@
defined( 'ABSPATH' ) || exit;
use Automattic\WooCommerce\Internal\Utilities\ActionSchedulerUtil;
+use Automattic\WooCommerce\Internal\Webhooks\WebhookCaptureRules;
+use Automattic\WooCommerce\Internal\Webhooks\WebhookObservers;
+use Automattic\WooCommerce\Internal\Webhooks\WebhookPayloadRedactor;
/**
* Process the web hooks at the end of the request.
@@ -24,10 +27,19 @@ function wc_webhook_execute_queue() {
$now = time();
foreach ( $wc_queued_webhooks as $data ) {
- // Webhooks are processed in the background by default
- // so as to avoid delays or failures in delivery from affecting the
- // user who triggered it.
- if ( apply_filters( 'woocommerce_webhook_deliver_async', true, $data['webhook'], $data['arg'] ) ) {
+ $original_arg = $data['original_arg'] ?? $data['arg'];
+
+ /**
+ * Filters whether a webhook is delivered in the background.
+ *
+ * Background delivery is the default so a slow or failed delivery does not delay the request that triggered it.
+ *
+ * @since 3.5.0
+ * @param bool $deliver_async Whether to deliver in the background. Default true.
+ * @param WC_Webhook $webhook The webhook being delivered.
+ * @param mixed $arg The argument the webhook fired with, usually a resource ID.
+ */
+ if ( apply_filters( 'woocommerce_webhook_deliver_async', true, $data['webhook'], $original_arg ) ) {
$queue_args = array(
'webhook_id' => $data['webhook']->get_id(),
@@ -48,14 +60,14 @@ function wc_webhook_execute_queue() {
* @param WC_Webhook $webhook The webhook being delivered.
* @param mixed $arg The argument the webhook fired with, usually the resource ID.
*/
- $priority = apply_filters( 'woocommerce_webhook_delivery_priority', 10, $data['webhook'], $data['arg'] );
+ $priority = apply_filters( 'woocommerce_webhook_delivery_priority', 10, $data['webhook'], $original_arg );
$priority = is_numeric( $priority ) && is_finite( $priority ) ? (int) max( 0, min( $priority, 255 ) ) : 10;
ActionSchedulerUtil::schedule_single( $now, 'woocommerce_deliver_webhook_async', $queue_args, 'woocommerce-webhooks', false, $priority );
}
} else {
// Deliver immediately.
- $data['webhook']->deliver( $data['arg'] );
+ $data['webhook']->deliver( $original_arg );
}
}
}
@@ -66,7 +78,7 @@ add_action( 'shutdown', 'wc_webhook_execute_queue' );
*
* @since 3.3.0
* @param WC_Webhook $webhook Webhook instance.
- * @param array $arg Delivery arguments.
+ * @param mixed $arg Delivery argument.
*/
function wc_webhook_process_delivery( $webhook, $arg ) {
// We need to queue the webhook so that it can be ran after the request has finished processing.
@@ -75,8 +87,9 @@ function wc_webhook_process_delivery( $webhook, $arg ) {
$wc_queued_webhooks = array();
}
$wc_queued_webhooks[] = array(
- 'webhook' => $webhook,
- 'arg' => $arg,
+ 'webhook' => $webhook,
+ 'arg' => $webhook instanceof WC_Webhook ? WebhookPayloadRedactor::redact( $webhook->get_topic(), $arg ) : $arg,
+ 'original_arg' => $arg,
);
}
add_action( 'woocommerce_webhook_process_delivery', 'wc_webhook_process_delivery', 10, 2 );
@@ -91,21 +104,24 @@ add_action( 'woocommerce_webhook_process_delivery', 'wc_webhook_process_delivery
* @param mixed $arg Hook argument.
*/
function wc_deliver_webhook_async( $webhook_id, $arg ) {
- $webhook = new WC_Webhook( $webhook_id );
+ $webhook = WebhookObservers::without_observers(
+ static function () use ( $webhook_id ) {
+ $webhook = new WC_Webhook( $webhook_id );
- if ( 0 === $webhook->get_id() ) {
- return;
- }
+ return 0 === $webhook->get_id() || '' === $webhook->get_topic() ? null : $webhook;
+ }
+ );
- $webhook->deliver( $arg );
+ if ( $webhook ) {
+ $webhook->deliver( $arg );
+ }
}
add_action( 'woocommerce_deliver_webhook_async', 'wc_deliver_webhook_async', 10, 2 );
/**
* Check if the given topic is a valid webhook topic, a topic is valid if:
*
- * + starts with `action.woocommerce_` or `action.wc_` (unless explicitly blocked by
- * the `$invalid_topics` list below).
+ * + it is a custom action topic with a supported hook name that is not blocked below.
* + it has a valid resource & event AND (when both are part of the default sets) the
* `<resource>.<event>` pair has a registered hook. Default/default pairs with no
* registered hook (e.g. `order.published`, `customer.restored`) are rejected to
@@ -116,25 +132,20 @@ add_action( 'woocommerce_deliver_webhook_async', 'wc_deliver_webhook_async', 10,
* @return bool
*/
function wc_is_webhook_valid_topic( $topic ) {
- $invalid_topics = array(
- 'action.woocommerce_login_credentials',
- 'action.woocommerce_product_csv_importer_check_import_file_path',
- 'action.woocommerce_webhook_should_deliver',
- );
+ $data = explode( '.', $topic );
- if ( in_array( $topic, $invalid_topics, true ) ) {
+ if ( ! isset( $data[1] ) ) {
return false;
}
- // Custom topics are prefixed with woocommerce_ or wc_ are valid.
- if ( 0 === strpos( $topic, 'action.woocommerce_' ) || 0 === strpos( $topic, 'action.wc_' ) ) {
- return true;
- }
-
- $data = explode( '.', $topic );
+ if ( 'action' === $data[0] ) {
+ // WC_Webhook subscribes to the second segment, even when the topic has a suffix.
+ $hook = $data[1];
+ if ( 0 !== strpos( $hook, 'woocommerce_' ) && 0 !== strpos( $hook, 'wc_' ) ) {
+ return false;
+ }
- if ( ! isset( $data[0] ) || ! isset( $data[1] ) ) {
- return false;
+ return ! WebhookCaptureRules::is_blocked_hook( $hook );
}
$default_resources = array( 'coupon', 'customer', 'order', 'product' );
@@ -233,8 +244,12 @@ function wc_load_webhooks( $status = '', $limit = null ) {
break;
}
- $webhook = new WC_Webhook( $webhook_id );
- $webhook->enqueue();
+ WebhookObservers::without_observers(
+ static function () use ( $webhook_id ) {
+ $webhook = new WC_Webhook( $webhook_id );
+ $webhook->enqueue();
+ }
+ );
$loaded ++;
}
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index 229a205cdbc..a955273cc4d 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -15468,12 +15468,6 @@ parameters:
count: 1
path: includes/class-wc-webhook.php
- -
- message: '#^Action callback returns mixed but should not return anything\.$#'
- identifier: return.void
- count: 1
- path: includes/class-wc-webhook.php
-
-
message: '#^Call to an undefined method object\:\:get_api_version_number\(\)\.$#'
identifier: method.notFound
diff --git a/plugins/woocommerce/src/Internal/Utilities/WebhookUtil.php b/plugins/woocommerce/src/Internal/Utilities/WebhookUtil.php
index 3aeed925f54..67989aa772e 100644
--- a/plugins/woocommerce/src/Internal/Utilities/WebhookUtil.php
+++ b/plugins/woocommerce/src/Internal/Utilities/WebhookUtil.php
@@ -117,6 +117,16 @@ class WebhookUtil {
);
echo '<p>' . wp_kses_post( $text ) . '</p>';
+
+ if ( $users_have_content ) {
+ $text = sprintf(
+ /* translators: 1 = url of the WooCommerce webhooks settings page */
+ __( 'If the "Attribute all content to" option is selected, the affected WooCommerce webhooks will be attributed to the selected user. They will keep their delivery URLs, and their payloads will be built as that user. You can review them on the <a href="%1$s">WooCommerce webhooks settings page</a>.', 'woocommerce' ),
+ $webhooks_settings_url
+ );
+
+ echo '<p>' . wp_kses_post( $text ) . '</p>';
+ }
}
/**
diff --git a/plugins/woocommerce/src/Internal/Webhooks/WebhookCaptureRules.php b/plugins/woocommerce/src/Internal/Webhooks/WebhookCaptureRules.php
new file mode 100644
index 00000000000..e8547d1e896
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Webhooks/WebhookCaptureRules.php
@@ -0,0 +1,178 @@
+<?php
+/**
+ * Rules for capturing specific hook arguments in webhooks.
+ *
+ * @package WooCommerce\Internal\Webhooks
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\Webhooks;
+
+/**
+ * Checks hook arguments before they enter the webhook queue.
+ *
+ * @since 11.4.0
+ * @internal
+ */
+final class WebhookCaptureRules {
+
+ /**
+ * Hooks that pass request internals or interfere with core processing when observed by a webhook.
+ */
+ private const BLOCKED_HOOKS = array(
+ 'woocommerce_deliver_webhook_async',
+ 'woocommerce_form_field',
+ 'woocommerce_form_field_hidden',
+ 'woocommerce_form_field_password',
+ 'woocommerce_logger_days_to_retain_logs',
+ 'woocommerce_login_credentials',
+ 'woocommerce_mail_callback_params',
+ 'woocommerce_mail_content',
+ 'woocommerce_mail_style_inline_callback',
+ 'woocommerce_paypal_capture_request',
+ 'woocommerce_paypal_refund_request',
+ 'woocommerce_webhook_deliver_async',
+ 'woocommerce_webhook_delivery',
+ 'woocommerce_webhook_delivery_priority',
+ 'woocommerce_webhook_delivery_url',
+ 'woocommerce_webhook_http_args',
+ 'woocommerce_webhook_loaded',
+ 'woocommerce_webhook_payload',
+ 'woocommerce_webhook_process_delivery',
+ 'woocommerce_webhook_redact_additional_fields',
+ 'woocommerce_webhook_secret',
+ 'woocommerce_webhook_should_deliver',
+ );
+
+ /**
+ * Guards that need more than the first hook argument.
+ */
+ private const FILTER_GUARDS = array(
+ 'woocommerce_format_log_entry' => array( 'allows_formatted_log', 2 ),
+ 'woocommerce_logger_log_message' => array( 'allows_log_message', 3 ),
+ );
+
+ /**
+ * Guards for the first hook argument.
+ */
+ private const ARGUMENT_GUARDS = array(
+ 'woocommerce_mail_callback' => 'allows_mail_callback',
+ );
+
+ /**
+ * Check whether the hook can be used as a webhook topic.
+ *
+ * @since 11.4.0
+ * @param string $hook Hook name.
+ * @return bool Whether webhooks must skip the hook.
+ */
+ public static function is_blocked_hook( string $hook ): bool {
+ return in_array( $hook, self::BLOCKED_HOOKS, true );
+ }
+
+ /**
+ * Register a webhook callback with the arguments its guard needs.
+ *
+ * @since 11.4.0
+ *
+ * @param string $hook Hook to capture.
+ * @param callable $callback Callback for the first argument.
+ * @param callable $context_callback Callback for hooks with extra arguments.
+ */
+ public static function subscribe( string $hook, callable $callback, callable $context_callback ): void {
+ if ( ! isset( self::FILTER_GUARDS[ $hook ] ) ) {
+ add_action( $hook, $callback );
+ return;
+ }
+
+ add_filter( $hook, $context_callback, 10, self::FILTER_GUARDS[ $hook ][1] );
+ }
+
+ /**
+ * Check the extra arguments before the webhook queues the first one.
+ *
+ * @since 11.4.0
+ *
+ * @param string $hook Hook being captured.
+ * @param mixed[] $args Arguments after the first.
+ * @return bool
+ */
+ public static function allows_context( string $hook, array $args ): bool {
+ $guard = self::FILTER_GUARDS[ $hook ][0] ?? null;
+
+ return null === $guard || self::$guard( ...$args );
+ }
+
+ /**
+ * Check the first argument before the webhook queues it.
+ *
+ * @since 11.4.0
+ *
+ * @param string $hook Hook being captured.
+ * @param mixed $arg First hook argument.
+ * @return bool
+ */
+ public static function allows_argument( string $hook, $arg ): bool {
+ if ( self::is_blocked_hook( $hook ) ) {
+ return false;
+ }
+
+ $guard = self::ARGUMENT_GUARDS[ $hook ] ?? null;
+
+ return null === $guard || self::$guard( $arg );
+ }
+
+ /**
+ * Read the context from the details of a formatted log entry.
+ *
+ * @param mixed $details Details of the log entry.
+ * @return bool
+ */
+ private static function allows_formatted_log( $details = null ): bool {
+ return self::allows_log_context( is_array( $details ) ? ( $details['context'] ?? null ) : null );
+ }
+
+ /**
+ * Read the context that the logger passes after the log level.
+ *
+ * @param mixed $level Log level.
+ * @param mixed $context Log context.
+ * @return bool
+ */
+ private static function allows_log_message( $level = null, $context = null ): bool {
+ return self::allows_log_context( $context );
+ }
+
+ /**
+ * Keep logs about webhook deliveries from starting another delivery.
+ *
+ * @param mixed $context Log context.
+ * @return bool
+ */
+ private static function allows_log_context( $context ): bool {
+ return ! is_array( $context ) || 'webhooks-delivery' !== ( $context['source'] ?? null );
+ }
+
+ /**
+ * A webhook can capture a function name or a class and method name.
+ * A callback that contains an object is skipped, because the object would become part of the payload.
+ *
+ * @param mixed $callback Mail callback.
+ * @return bool
+ */
+ private static function allows_mail_callback( $callback ): bool {
+ if ( is_string( $callback ) ) {
+ return true;
+ }
+
+ if ( ! is_array( $callback ) || 2 !== count( $callback ) ) {
+ return false;
+ }
+
+ $class_name = $callback[0] ?? null;
+ $method_name = $callback[1] ?? null;
+
+ return is_string( $class_name ) && is_string( $method_name );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Webhooks/WebhookObservers.php b/plugins/woocommerce/src/Internal/Webhooks/WebhookObservers.php
new file mode 100644
index 00000000000..e4aa078c548
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Webhooks/WebhookObservers.php
@@ -0,0 +1,109 @@
+<?php
+/**
+ * Suppresses webhook observers while WooCommerce processes their deliveries.
+ *
+ * @package WooCommerce\Internal\Webhooks
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\Webhooks;
+
+/**
+ * Keeps webhook bookkeeping from recursively scheduling webhook observers.
+ *
+ * @internal
+ */
+final class WebhookObservers {
+
+ /**
+ * Hook names that can fire when WooCommerce reads, schedules or delivers a webhook.
+ */
+ private const HOOKS = array(
+ 'woocommerce_format_log_entry' => true,
+ 'woocommerce_logger_log_message' => true,
+ 'woocommerce_valid_webhook_events' => true,
+ 'woocommerce_valid_webhook_resources' => true,
+ 'woocommerce_webhook_disabled_due_delivery_failures' => true,
+ 'woocommerce_webhook_enable_delivery_log' => true,
+ 'woocommerce_webhook_event' => true,
+ 'woocommerce_webhook_hash_algorithm' => true,
+ 'woocommerce_webhook_hooks' => true,
+ 'woocommerce_webhook_name' => true,
+ 'woocommerce_webhook_resource' => true,
+ 'woocommerce_webhook_status' => true,
+ 'woocommerce_webhook_statuses' => true,
+ 'woocommerce_webhook_topic' => true,
+ 'woocommerce_webhook_topic_hooks' => true,
+ 'woocommerce_webhook_updated' => true,
+ );
+
+ /**
+ * Whether observer callbacks are currently suppressed in this request.
+ *
+ * @var bool
+ */
+ private static $suppressed = false;
+
+ /**
+ * Whether a webhook callback on this hook should skip capture.
+ *
+ * @since 11.4.0
+ *
+ * @param string $hook Currently firing hook.
+ * @return bool
+ */
+ public static function is_suppressed( string $hook ): bool {
+ return self::$suppressed && isset( self::HOOKS[ $hook ] );
+ }
+
+ /**
+ * Whether delivery of this topic should run with observers suppressed.
+ *
+ * @since 11.4.0
+ *
+ * @param string $topic Webhook topic.
+ * @return bool
+ */
+ public static function is_observer_topic( string $topic ): bool {
+ $parts = explode( '.', $topic, 3 );
+
+ return 'action' === $parts[0] && isset( self::HOOKS[ $parts[1] ?? '' ] );
+ }
+
+ /**
+ * Deliver a webhook. Suppress observers during delivery of an observer topic.
+ *
+ * @since 11.4.0
+ *
+ * @param string $topic Webhook topic.
+ * @param callable():void $deliver Delivery callback.
+ */
+ public static function during_delivery( string $topic, callable $deliver ): void {
+ if ( self::is_observer_topic( $topic ) ) {
+ self::without_observers( $deliver );
+ return;
+ }
+
+ $deliver();
+ }
+
+ /**
+ * Run webhook bookkeeping without admitting new observer deliveries.
+ *
+ * @since 11.4.0
+ *
+ * @template T
+ * @param callable(): T $callback Webhook bookkeeping or delivery.
+ * @return T
+ */
+ public static function without_observers( callable $callback ) {
+ $previous = self::$suppressed;
+ self::$suppressed = true;
+ try {
+ return $callback();
+ } finally {
+ self::$suppressed = $previous;
+ }
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Webhooks/WebhookPayloadRedactor.php b/plugins/woocommerce/src/Internal/Webhooks/WebhookPayloadRedactor.php
new file mode 100644
index 00000000000..d2650c30966
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Webhooks/WebhookPayloadRedactor.php
@@ -0,0 +1,306 @@
+<?php
+/**
+ * Redacts internal fields from custom webhook arguments.
+ *
+ * @package WooCommerce\Internal\Webhooks
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\Webhooks;
+
+use WC_Data;
+
+/**
+ * Prepares the stored and outgoing copies of custom webhook arguments.
+ *
+ * @internal
+ */
+final class WebhookPayloadRedactor {
+
+ public const REDACTED = '[redacted]';
+
+ /**
+ * Core resources whose payload starts with an ID or a data object.
+ */
+ private const ID_RESOURCES = array( 'coupon', 'customer', 'order', 'product' );
+
+ /**
+ * Core hooks that pass a bare checkout password.
+ */
+ private const PASSWORD_HOOKS = array(
+ 'woocommerce_process_checkout_field_account_password',
+ 'woocommerce_process_checkout_password_field',
+ );
+
+ /**
+ * Hook that passes checkout form data.
+ */
+ private const FORM_ARGUMENT_HOOK = 'woocommerce_checkout_update_order_review';
+
+ /**
+ * Hook that passes a Helper API request with a query string.
+ */
+ private const REQUEST_QUERY_HOOK = 'woocommerce_helper_api_request_args';
+
+ /**
+ * Fields to redact, matched case-insensitively in structured data.
+ */
+ private const REDACTED_FIELDS = array(
+ 'account_password' => true,
+ 'activation_key' => true,
+ 'access_token' => true,
+ 'access_token_secret' => true,
+ 'api_key' => true,
+ 'authorization' => true,
+ 'consumer_key' => true,
+ 'consumer_secret' => true,
+ 'nonce' => true,
+ 'password' => true,
+ 'payment_token' => true,
+ 'refresh_token' => true,
+ 'request_hash' => true,
+ 'reset_key' => true,
+ 'secret' => true,
+ 'set_password_url' => true,
+ 'token' => true,
+ 'user_activation_key' => true,
+ 'user_pass' => true,
+ 'user_password' => true,
+ 'verification_key' => true,
+ 'verify_email_key' => true,
+ 'verify_url' => true,
+ 'woocommerce-login-nonce' => true,
+ 'woocommerce-process-checkout-nonce' => true,
+ 'x-woo-signature' => true,
+ );
+
+ /**
+ * Prepare an argument for a payload. Core resource payloads must use an ID or a data object.
+ *
+ * @since 11.4.0
+ *
+ * @param string $topic Webhook topic.
+ * @param mixed $resource_name Resource name supplied by the webhook resource filter.
+ * @param mixed $arg First hook argument.
+ * @return mixed
+ */
+ public static function redact_for_payload( string $topic, $resource_name, $arg ) {
+ $arg = self::redact( $topic, $arg );
+ if ( ! in_array( $resource_name, self::ID_RESOURCES, true ) || is_numeric( $arg ) || $arg instanceof WC_Data ) {
+ return $arg;
+ }
+
+ return self::REDACTED;
+ }
+
+ /**
+ * Redact a custom topic's first argument without changing the original.
+ *
+ * @since 11.4.0
+ *
+ * @param string $topic Webhook topic.
+ * @param mixed $arg First hook argument.
+ * @return mixed
+ */
+ public static function redact( string $topic, $arg ) {
+ $parts = explode( '.', $topic, 3 );
+ if ( 'action' !== $parts[0] ) {
+ return $arg;
+ }
+
+ $hook = $parts[1] ?? '';
+ if ( is_string( $arg ) ) {
+ if ( in_array( $hook, self::PASSWORD_HOOKS, true ) ) {
+ return '' === $arg ? $arg : self::REDACTED;
+ }
+ if ( self::FORM_ARGUMENT_HOOK === $hook ) {
+ return self::redact_form_parameters( $arg, self::get_redacted_fields( $hook ) );
+ }
+ }
+
+ if ( is_array( $arg ) || is_object( $arg ) ) {
+ return self::redact_structure( $arg, self::get_redacted_fields( $hook ), self::REQUEST_QUERY_HOOK === $hook );
+ }
+
+ return $arg;
+ }
+
+ /**
+ * Redact a structured argument for the Scheduled Actions screen.
+ *
+ * Older rows may have been queued under a different topic, so check query parameters regardless of the current topic.
+ *
+ * @since 11.4.0
+ * @param string $topic Current webhook topic.
+ * @param array|object $arg Queued argument.
+ * @return mixed
+ */
+ public static function redact_queued_structure( string $topic, $arg ) {
+ $parts = explode( '.', $topic, 3 );
+ return self::redact_structure( $arg, self::get_redacted_fields( $parts[1] ?? '' ), true );
+ }
+
+ /**
+ * Combine Core and plugin field names into a case-insensitive lookup.
+ *
+ * @param string $hook Hook name.
+ * @return array<string, bool>
+ */
+ private static function get_redacted_fields( string $hook ): array {
+ /**
+ * Filters the additional field names to hide from a custom action webhook's argument.
+ *
+ * WooCommerce applies these names in addition to its built-in list. Matching is case-insensitive.
+ *
+ * @since 11.4.0
+ * @param string[] $additional_fields Field names to hide from structured data and recognized form or query parameters.
+ * @param string $hook Hook name from the webhook topic.
+ */
+ $additional_fields = apply_filters( 'woocommerce_webhook_redact_additional_fields', array(), $hook );
+ $fields = self::REDACTED_FIELDS;
+ if ( is_array( $additional_fields ) ) {
+ foreach ( $additional_fields as $field ) {
+ if ( is_string( $field ) && '' !== $field ) {
+ $fields[ strtolower( $field ) ] = true;
+ }
+ }
+ }
+
+ return $fields;
+ }
+
+ /**
+ * Check the data as JSON encodes it. Keep the original when no fields need to change.
+ *
+ * @param array|object $arg First hook argument.
+ * @param array<string, bool> $fields Field names to hide.
+ * @param bool $check_query_string Whether to check the top-level query string.
+ * @return mixed
+ */
+ private static function redact_structure( $arg, array $fields, bool $check_query_string ) {
+ $json = wp_json_encode( $arg );
+ if ( false === $json ) {
+ return null;
+ }
+
+ $changed = false;
+ $value = json_decode( $json );
+ if ( $check_query_string ) {
+ $value = self::redact_request_query( $value, $fields, $changed );
+ }
+ $clean = self::redact_fields( $value, $fields, $changed );
+
+ if ( ! $changed ) {
+ return $arg;
+ }
+
+ return is_array( $arg ) ? (array) $clean : $clean;
+ }
+
+ /**
+ * Redact the query string on a copy of the argument.
+ *
+ * @param mixed $value Data decoded from JSON.
+ * @param array<string, bool> $fields Field names to hide.
+ * @param bool $changed Whether any field was redacted.
+ * @return mixed The decoded data with its query string redacted.
+ */
+ private static function redact_request_query( $value, array $fields, bool &$changed ) {
+ if ( ! is_object( $value ) || ! is_string( $value->query_string ?? null ) ) {
+ return $value;
+ }
+
+ $query_string = self::redact_form_parameters( $value->query_string, $fields );
+ if ( $query_string !== $value->query_string ) {
+ $value->query_string = $query_string;
+ $changed = true;
+ }
+
+ return $value;
+ }
+
+ /**
+ * Redact the listed fields in JSON-shaped data.
+ *
+ * @param mixed $value Decoded data.
+ * @param array<string, bool> $fields Field names to hide.
+ * @param bool $changed Whether any field was redacted.
+ * @return mixed
+ */
+ private static function redact_fields( $value, array $fields, bool &$changed ) {
+ if ( ! is_array( $value ) && ! is_object( $value ) ) {
+ return $value;
+ }
+
+ $items = (array) $value;
+ foreach ( $items as $key => $item ) {
+ if ( isset( $fields[ strtolower( (string) $key ) ] ) && null !== $item && '' !== $item && self::REDACTED !== $item ) {
+ $items[ $key ] = self::REDACTED;
+ $changed = true;
+ } else {
+ $items[ $key ] = self::redact_fields( $item, $fields, $changed );
+ }
+ }
+
+ return is_array( $value ) ? $items : (object) $items;
+ }
+
+ /**
+ * Redact the listed fields in known form or query parameters.
+ *
+ * @param string $form Posted form data or query string.
+ * @param array<string, bool> $fields Field names to hide.
+ * @return string
+ */
+ private static function redact_form_parameters( string $form, array $fields ): string {
+ $prefix = '';
+ if ( 0 === strpos( $form, '?' ) ) {
+ $prefix = '?';
+ $form = substr( $form, 1 );
+ }
+
+ $pairs = explode( '&', $form );
+ foreach ( $pairs as $index => $pair ) {
+ $parts = explode( '=', $pair, 2 );
+ if ( '' === ( $parts[1] ?? '' ) ) {
+ continue;
+ }
+
+ $key = strtolower( urldecode( $parts[0] ) );
+ if ( self::is_redacted_form_field( $key, $fields ) ) {
+ $pairs[ $index ] = $parts[0] . '=' . self::REDACTED;
+ }
+ }
+
+ return $prefix . implode( '&', $pairs );
+ }
+
+ /**
+ * Match the full form field name or any part of a bracketed field name.
+ *
+ * @param string $key Decoded field name in lowercase.
+ * @param array<string, bool> $fields Field names to hide.
+ * @return bool
+ */
+ private static function is_redacted_form_field( string $key, array $fields ): bool {
+ if ( isset( $fields[ $key ] ) ) {
+ return true;
+ }
+
+ $parts = explode( '[', $key );
+ $root = array_shift( $parts );
+ if ( isset( $fields[ $root ] ) ) {
+ return true;
+ }
+
+ foreach ( $parts as $part ) {
+ $end = strpos( $part, ']' );
+ if ( false !== $end && isset( $fields[ substr( $part, 0, $end ) ] ) ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Webhooks/WebhookScheduledActionArgs.php b/plugins/woocommerce/src/Internal/Webhooks/WebhookScheduledActionArgs.php
new file mode 100644
index 00000000000..53e663f763e
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Webhooks/WebhookScheduledActionArgs.php
@@ -0,0 +1,86 @@
+<?php
+/**
+ * WebhookScheduledActionArgs class file.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\Webhooks;
+
+use Automattic\WooCommerce\Internal\RegisterHooksInterface;
+
+/**
+ * Shows the stored arguments of webhook deliveries redacted on Status > Scheduled Actions.
+ *
+ * Deliveries queued before redaction existed, or by a replacement queue, can still hold raw custom action arguments.
+ *
+ * @since 11.4.0
+ */
+class WebhookScheduledActionArgs implements RegisterHooksInterface {
+
+ /**
+ * Register hooks.
+ *
+ * @since 11.4.0
+ */
+ public function register() {
+ add_filter( 'action_scheduler_list_table_column_args', array( $this, 'handle_action_scheduler_list_table_column_args' ), 10, 2 );
+ }
+
+ /**
+ * Get the arguments column of a webhook delivery with its hook argument redacted.
+ *
+ * @internal
+ *
+ * @param mixed $html The column HTML.
+ * @param mixed $row The scheduled action row.
+ * @return mixed
+ */
+ public function handle_action_scheduler_list_table_column_args( $html, $row ) {
+ if ( ! is_array( $row ) || 'woocommerce_deliver_webhook_async' !== ( $row['hook'] ?? '' ) || ! is_array( $row['args'] ?? null ) || ! array_key_exists( 'arg', $row['args'] ) ) {
+ return $html;
+ }
+
+ $args = $row['args'];
+ $args['arg'] = $this->redact_queued_arg( (int) ( $args['webhook_id'] ?? 0 ), $args['arg'] );
+ if ( $row['args']['arg'] === $args['arg'] ) {
+ return $html;
+ }
+
+ $html = '<ul>';
+ foreach ( $args as $key => $value ) {
+ $html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( var_export( $key, true ) ), esc_html( var_export( $value, true ) ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export -- Same format as the Action Scheduler list table.
+ }
+
+ return $html . '</ul>';
+ }
+
+ /**
+ * Redact the hook argument of a queued webhook delivery for display.
+ *
+ * The webhook's topic may have changed since the delivery was queued, so the current topic can't say what a bare value means:
+ * IDs are kept unless the webhook is gone (for action topics only integers), other bare values are hidden, and arrays and objects are redacted by name.
+ *
+ * @param int $webhook_id The webhook ID.
+ * @param mixed $arg The queued hook argument.
+ * @return mixed
+ */
+ private function redact_queued_arg( int $webhook_id, $arg ) {
+ if ( null === $arg || '' === $arg || is_bool( $arg ) || WebhookPayloadRedactor::REDACTED === $arg ) {
+ return $arg;
+ }
+
+ $webhook = wc_get_webhook( $webhook_id );
+ $resource = $webhook ? $webhook->get_resource() : '';
+
+ if ( '' !== $resource && is_numeric( $arg ) && ( 'action' !== $resource || is_int( $arg ) ) ) {
+ return $arg;
+ }
+
+ if ( 'action' === $resource && ! is_scalar( $arg ) ) {
+ return WebhookPayloadRedactor::redact_queued_structure( $webhook->get_topic(), $arg );
+ }
+
+ return WebhookPayloadRedactor::REDACTED;
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Webhooks/WebhookTopicNotices.php b/plugins/woocommerce/src/Internal/Webhooks/WebhookTopicNotices.php
new file mode 100644
index 00000000000..c2b90bd7f83
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Webhooks/WebhookTopicNotices.php
@@ -0,0 +1,228 @@
+<?php
+/**
+ * WebhookTopicNotices class file.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\Webhooks;
+
+use Automattic\WooCommerce\Internal\RegisterHooksInterface;
+use WC_Admin_Notices;
+use WC_Cache_Helper;
+
+/**
+ * Disables stored custom action webhooks whose topic is no longer allowed, and tells store owners about them.
+ *
+ * @since 11.4.0
+ */
+class WebhookTopicNotices implements RegisterHooksInterface {
+
+ /**
+ * Version of the topic rules the stored webhooks were last checked against. Bump it when wc_is_webhook_valid_topic() refuses more topics.
+ */
+ public const TOPIC_CHECK_VERSION = 1;
+
+ /**
+ * Option holding the topic rules version the stored webhooks were last checked against.
+ */
+ public const TOPIC_CHECK_OPTION = 'woocommerce_webhook_topic_check_version';
+
+ /**
+ * Admin notice listing webhooks disabled because their topic is no longer allowed.
+ */
+ public const BLOCKED_TOPICS_NOTICE = 'webhook_topics_blocked';
+
+ /**
+ * Register hooks.
+ *
+ * @since 11.4.0
+ */
+ public function register() {
+ add_action( 'admin_init', array( $this, 'handle_admin_init' ) );
+ }
+
+ /**
+ * Handle the admin_init hook.
+ *
+ * @internal
+ */
+ public function handle_admin_init(): void {
+ if ( ! class_exists( WC_Admin_Notices::class ) ) {
+ return;
+ }
+
+ $this->maybe_disable_blocked_webhooks();
+ }
+
+ /**
+ * Disable webhooks with blocked topics and list them, including those already disabled.
+ */
+ private function maybe_disable_blocked_webhooks(): void {
+ if ( (int) get_option( self::TOPIC_CHECK_OPTION, 0 ) >= self::TOPIC_CHECK_VERSION ) {
+ return;
+ }
+
+ $webhooks = $this->get_stored_action_webhooks();
+ if ( null === $webhooks ) {
+ return;
+ }
+
+ $blocked = array();
+ $needs_retry = false;
+ foreach ( $webhooks as $webhook ) {
+ if ( ! $this->is_newly_blocked_topic( $webhook['topic'] ) ) {
+ continue;
+ }
+
+ if ( ! $this->disable_webhook( $webhook ) ) {
+ $needs_retry = true;
+ continue;
+ }
+
+ $blocked[] = $webhook;
+ }
+
+ if ( ! $needs_retry ) {
+ update_option( self::TOPIC_CHECK_OPTION, self::TOPIC_CHECK_VERSION );
+ }
+
+ if ( $blocked ) {
+ $this->clear_webhook_caches();
+ $this->show_blocked_webhooks_notice( $blocked );
+
+ foreach ( $blocked as $webhook ) {
+ if ( 'disabled' !== $webhook['status'] ) {
+ /**
+ * Fires after the topic check disables a webhook and clears the caches.
+ *
+ * @since 11.4.0
+ * @param int $webhook_id Webhook ID.
+ */
+ do_action( 'woocommerce_webhook_updated', (int) $webhook['webhook_id'] );
+ }
+ }
+ }
+ }
+
+ /**
+ * Read topics from the table. WC_Webhook clears invalid topics when it loads.
+ *
+ * @return array[]|null Stored rows, or null if the query failed.
+ */
+ private function get_stored_action_webhooks(): ?array {
+ global $wpdb;
+
+ $webhooks = $wpdb->get_results( "SELECT webhook_id, name, topic, status FROM {$wpdb->prefix}wc_webhooks WHERE topic LIKE 'action.%'", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time check of raw stored topics.
+ if ( '' !== $wpdb->last_error || ! is_array( $webhooks ) ) {
+ return null;
+ }
+
+ return $webhooks;
+ }
+
+ /**
+ * Check for blocked topics with a prefix that older versions accepted.
+ *
+ * @param string $topic Stored topic.
+ * @return bool
+ */
+ private function is_newly_blocked_topic( string $topic ): bool {
+ return ( 0 === strpos( $topic, 'action.woocommerce_' ) || 0 === strpos( $topic, 'action.wc_' ) ) && ! wc_is_webhook_valid_topic( $topic );
+ }
+
+ /**
+ * Disable a webhook and keep its stored topic.
+ *
+ * @param array<string,mixed> $webhook Stored row.
+ * @return bool Whether the row is disabled.
+ */
+ private function disable_webhook( array $webhook ): bool {
+ if ( 'disabled' === $webhook['status'] ) {
+ return true;
+ }
+
+ global $wpdb;
+ $webhook_id = (int) $webhook['webhook_id'];
+ $updated = $wpdb->update(
+ "{$wpdb->prefix}wc_webhooks",
+ array( 'status' => 'disabled' ),
+ array(
+ 'webhook_id' => $webhook_id,
+ 'topic' => $webhook['topic'],
+ 'status' => $webhook['status'],
+ )
+ ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Status-only update keeps the stored topic; caches are cleared below.
+
+ wp_cache_delete( $webhook_id, 'webhooks' );
+ if ( ! $updated ) {
+ // Retry on the next admin request if the write failed or the row changed.
+ return false;
+ }
+
+ wc_get_logger()->warning(
+ sprintf( 'Webhook ID %d was disabled because its topic "%s" is no longer allowed.', $webhook_id, $webhook['topic'] ),
+ array( 'source' => 'webhooks' )
+ );
+
+ return true;
+ }
+
+ /**
+ * Clear caches after the status changes.
+ */
+ private function clear_webhook_caches(): void {
+ delete_transient( 'woocommerce_webhook_ids' );
+ foreach ( array_keys( wc_get_webhook_statuses() ) as $status ) {
+ delete_transient( 'woocommerce_webhook_ids_status_' . $status );
+ }
+ WC_Cache_Helper::invalidate_cache_group( 'webhooks' );
+ }
+
+ /**
+ * Show store owners which webhooks use unsupported topics.
+ *
+ * @param array[] $blocked Stored rows to list.
+ */
+ private function show_blocked_webhooks_notice( array $blocked ): void {
+ $items = array_map(
+ fn( array $webhook ) => sprintf( '<li>%s (<code>%s</code>)</li>', esc_html( $this->get_webhook_label( (int) $webhook['webhook_id'], (string) $webhook['name'] ) ), esc_html( $webhook['topic'] ) ),
+ $blocked
+ );
+
+ WC_Admin_Notices::add_custom_notice(
+ self::BLOCKED_TOPICS_NOTICE,
+ '<p><strong>' . esc_html__( 'Some webhooks use topics that are no longer supported.', 'woocommerce' ) . '</strong></p>' .
+ '<p>' . esc_html__( 'These webhooks are disabled. To activate them again, switch to a supported topic and set its status to Active.', 'woocommerce' ) . '</p>' .
+ '<ul>' . implode( '', $items ) . '</ul>' .
+ '<p>' . $this->get_webhooks_settings_link() . '</p>'
+ );
+ // Save the notice now. The next admin request can skip the completed scan.
+ WC_Admin_Notices::store_notices();
+ }
+
+ /**
+ * Get a label for a webhook in a notice.
+ *
+ * @param int $webhook_id The webhook ID.
+ * @param string $name The webhook name.
+ * @return string
+ */
+ private function get_webhook_label( int $webhook_id, string $name ): string {
+ /* translators: 1: webhook name, 2: webhook ID. */
+ return sprintf( __( '%1$s (ID %2$d)', 'woocommerce' ), '' !== $name ? $name : __( 'Unnamed webhook', 'woocommerce' ), $webhook_id );
+ }
+
+ /**
+ * Get a link to the webhooks settings screen.
+ *
+ * @return string
+ */
+ private function get_webhooks_settings_link(): string {
+ return sprintf(
+ '<a href="%s">%s</a>',
+ esc_url( admin_url( 'admin.php?page=wc-settings&tab=advanced§ion=webhooks' ) ),
+ esc_html__( 'Review webhooks', 'woocommerce' )
+ );
+ }
+}
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/webhooks/functions.php b/plugins/woocommerce/tests/legacy/unit-tests/webhooks/functions.php
index 344659305c6..4219d42de9d 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/webhooks/functions.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/webhooks/functions.php
@@ -58,6 +58,19 @@ class WC_Tests_Webhook_Functions extends WC_Unit_Test_Case {
array( false, wc_is_webhook_valid_topic( 'missingdot' ) ),
array( false, wc_is_webhook_valid_topic( 'with space' ) ),
array( false, wc_is_webhook_valid_topic( 'action.woocommerce_login_credentials' ) ),
+ array( false, wc_is_webhook_valid_topic( 'action.woocommerce_webhook_payload.extra' ) ),
+ array( false, wc_is_webhook_valid_topic( 'action.woocommerce_mail_content.extra' ) ),
+ array( false, wc_is_webhook_valid_topic( 'action.woocommerce_form_field_password' ) ),
+ array( false, wc_is_webhook_valid_topic( 'action.woocommerce_webhook_secret' ) ),
+ array( false, wc_is_webhook_valid_topic( 'action.woocommerce_logger_days_to_retain_logs' ) ),
+ array( false, wc_is_webhook_valid_topic( 'action.woocommerce_paypal_capture_request' ) ),
+ array( false, wc_is_webhook_valid_topic( 'action.woocommerce_paypal_refund_request.extra' ) ),
+ array( true, wc_is_webhook_valid_topic( 'action.woocommerce_product_csv_importer_check_import_file_path' ) ),
+ array( true, wc_is_webhook_valid_topic( 'action.woocommerce_add_to_cart.extra' ) ),
+ array( true, wc_is_webhook_valid_topic( 'action.woocommerce_form_field_checkbox' ) ),
+ array( true, wc_is_webhook_valid_topic( 'action.woocommerce_format_log_entry' ) ),
+ array( true, wc_is_webhook_valid_topic( 'action.woocommerce_logger_log_message' ) ),
+ array( true, wc_is_webhook_valid_topic( 'action.wc_webhook_extension_event' ) ),
);
}
diff --git a/plugins/woocommerce/tests/php/includes/admin/class-wc-admin-webhooks-test.php b/plugins/woocommerce/tests/php/includes/admin/class-wc-admin-webhooks-test.php
index 93d1655b243..a2d319273bf 100644
--- a/plugins/woocommerce/tests/php/includes/admin/class-wc-admin-webhooks-test.php
+++ b/plugins/woocommerce/tests/php/includes/admin/class-wc-admin-webhooks-test.php
@@ -1,11 +1,25 @@
<?php
declare( strict_types = 1 );
+require_once WC_ABSPATH . 'includes/admin/class-wc-admin-webhooks.php';
+
/**
- * Tests for webhook bulk status changes.
+ * Tests for WC_Admin_Webhooks.
+ *
+ * @package WooCommerce\Tests\Admin
*/
class WC_Admin_Webhooks_Test extends WC_Unit_Test_Case {
+ /**
+ * Clear the submitted form after each test.
+ */
+ public function tearDown(): void {
+ $_GET = array();
+ $_POST = array();
+ $_REQUEST = array();
+ parent::tearDown();
+ }
+
/**
* @testdox Bulk actions save each supported webhook status.
* @testWith ["disabled", "active"]
@@ -226,6 +240,70 @@ class WC_Admin_Webhooks_Test extends WC_Unit_Test_Case {
);
}
+ /**
+ * @testdox Saving the webhook form untouched keeps the author and the delivery URL, however the stored URL is spelled.
+ *
+ * @testWith ["https://example.com/hook?a=1&b=2"]
+ * ["https://example.com/hook?a=1&b=2"]
+ * ["https://example.com/hook?a=1&amp;b=2"]
+ * ["https://example.com/hook?a=1"b=2"]
+ * ["https://example.com/hook?a=1 b=2"]
+ *
+ * @param string $stored_url The delivery URL stored for the webhook.
+ */
+ public function test_untouched_form_save_keeps_author_and_delivery_url( string $stored_url ): void {
+ $shop_manager_id = self::factory()->user->create( array( 'role' => 'shop_manager' ) );
+ $webhook_id = $this->create_webhook_owned_by( $shop_manager_id, $stored_url );
+
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+ $this->submit_webhook_form( $webhook_id, $this->get_displayed_delivery_url( $webhook_id ) );
+
+ $webhook = wc_get_webhook( $webhook_id );
+ $this->assertSame( $shop_manager_id, $webhook->get_user_id(), 'An untouched save should keep the author.' );
+ $this->assertSame( $stored_url, $webhook->get_delivery_url(), 'An untouched save should keep the stored delivery URL.' );
+ }
+
+ /**
+ * @testdox Saving the webhook form with a different delivery URL makes the editor the author.
+ *
+ * @testWith ["https://example.com/other-hook"]
+ * ["https://example.com/hook?a=1&b=2"]
+ *
+ * @param string $submitted_url The delivery URL the form submits.
+ */
+ public function test_form_save_with_a_new_delivery_url_makes_the_editor_the_author( string $submitted_url ): void {
+ $shop_manager_id = self::factory()->user->create( array( 'role' => 'shop_manager' ) );
+ $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) );
+ $webhook_id = $this->create_webhook_owned_by( $shop_manager_id, 'https://example.com/hook?a=1&b=2' );
+
+ wp_set_current_user( $admin_id );
+ $this->submit_webhook_form( $webhook_id, $submitted_url );
+
+ $webhook = wc_get_webhook( $webhook_id );
+ $this->assertSame( $admin_id, $webhook->get_user_id(), 'The user who changed the delivery URL should become the author.' );
+ $this->assertSame( $submitted_url, $webhook->get_delivery_url(), 'The submitted delivery URL should be stored.' );
+ }
+
+ /**
+ * @testdox Saving the webhook form untouched keeps the author when a filter changes the displayed delivery URL.
+ */
+ public function test_untouched_form_save_keeps_author_when_delivery_url_is_filtered(): void {
+ $shop_manager_id = self::factory()->user->create( array( 'role' => 'shop_manager' ) );
+ $webhook_id = $this->create_webhook_owned_by( $shop_manager_id, 'https://example.com/hook' );
+
+ add_filter(
+ 'woocommerce_webhook_delivery_url',
+ static function ( $delivery_url ) {
+ return $delivery_url . '?site=1';
+ }
+ );
+
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+ $this->submit_webhook_form( $webhook_id, $this->get_displayed_delivery_url( $webhook_id ) );
+
+ $this->assertSame( $shop_manager_id, wc_get_webhook( $webhook_id )->get_user_id(), 'An untouched save should keep the author.' );
+ }
+
/**
* Run a callback that redirects and return the location it redirected to.
*
@@ -276,4 +354,99 @@ class WC_Admin_Webhooks_Test extends WC_Unit_Test_Case {
return $webhook;
}
+
+ /**
+ * Create a paused webhook that belongs to a user.
+ *
+ * @param int $user_id Webhook author.
+ * @param string $delivery_url Delivery URL to store.
+ * @return int Webhook ID.
+ */
+ private function create_webhook_owned_by( int $user_id, string $delivery_url ): int {
+ $webhook = new WC_Webhook();
+ $webhook->set_user_id( $user_id );
+ $webhook->set_status( 'paused' );
+ $webhook->set_topic( 'customer.created' );
+ $webhook->set_delivery_url( $delivery_url );
+ $webhook->save();
+
+ return $webhook->get_id();
+ }
+
+ /**
+ * Render the webhook edit form and read the delivery URL field the way a browser does.
+ *
+ * @param int $webhook_id Webhook ID.
+ * @return string The value a browser would send back for an untouched field.
+ */
+ private function get_displayed_delivery_url( int $webhook_id ): string {
+ $_GET['edit-webhook'] = $webhook_id;
+
+ ob_start();
+ try {
+ WC_Admin_Webhooks::page_output();
+ } finally {
+ $processor = new WP_HTML_Tag_Processor( (string) ob_get_clean() );
+ unset( $GLOBALS['hide_save_button'] );
+ }
+
+ $displayed_url = null;
+ while ( $processor->next_tag( 'input' ) ) {
+ if ( 'webhook_delivery_url' === $processor->get_attribute( 'name' ) ) {
+ $displayed_url = $processor->get_attribute( 'value' );
+ break;
+ }
+ }
+
+ $this->assertIsString( $displayed_url, 'The edit form should have a delivery URL field.' );
+
+ return $displayed_url;
+ }
+
+ /**
+ * Submit the webhook edit form for a webhook, stopping at the redirect that ends the save.
+ *
+ * @param int $webhook_id Webhook ID.
+ * @param string $delivery_url Delivery URL to submit.
+ */
+ private function submit_webhook_form( int $webhook_id, string $delivery_url ): void {
+ $nonce = wp_create_nonce( 'woocommerce-settings' );
+
+ $query = array(
+ 'page' => 'wc-settings',
+ 'tab' => 'advanced',
+ 'section' => 'webhooks',
+ );
+
+ $form = array(
+ 'save' => 'Save webhook',
+ '_wpnonce' => $nonce,
+ 'webhook_id' => $webhook_id,
+ 'webhook_name' => 'Webhook',
+ 'webhook_status' => 'paused',
+ 'webhook_delivery_url' => $delivery_url,
+ 'webhook_topic' => 'customer.created',
+ );
+
+ $_GET = $query;
+ $_POST = $form;
+ $_REQUEST = array_merge( $query, $form );
+ set_current_screen( 'woocommerce_page_wc-settings' );
+
+ add_filter(
+ 'wp_redirect',
+ function () {
+ throw new RuntimeException( 'wp_redirect intercepted.' );
+ }
+ );
+
+ try {
+ ( new WC_Admin_Webhooks() )->actions();
+ } catch ( RuntimeException $e ) {
+ $this->assertSame( 'wp_redirect intercepted.', $e->getMessage() );
+ return;
+ }
+
+ $this->fail( 'The webhook form save did not redirect.' );
+ }
}
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-webhook-tests.php b/plugins/woocommerce/tests/php/includes/class-wc-webhook-tests.php
index 2e75fb8788b..beb0aafacad 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-webhook-tests.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-webhook-tests.php
@@ -5,6 +5,8 @@
use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\Enums\ProductStatus;
+use Automattic\WooCommerce\Internal\Admin\Logging\LogHandlerFileV2;
+use Automattic\WooCommerce\Internal\CustomerEmailVerification\Emails\CustomerVerifyEmail;
use Automattic\WooCommerce\RestApi\UnitTests\HPOSToggleTrait;
use Automattic\WooCommerce\Utilities\OrderUtil;
@@ -32,6 +34,9 @@ class WC_Webhook_Test extends WC_Unit_Test_Case {
* Restore the order storage a test switched with use_order_storage().
*/
public function tearDown(): void {
+ global $wc_queued_webhooks;
+
+ $wc_queued_webhooks = null;
try {
if ( null !== $this->prev_hpos_enabled ) {
$this->toggle_cot_authoritative( $this->prev_hpos_enabled );
@@ -756,6 +761,484 @@ class WC_Webhook_Test extends WC_Unit_Test_Case {
$this->assertSame( ! $expect_success, wc_get_webhook( $webhook->get_id() )->get_pending_delivery(), 'Only a successful ping should clear the pending ping.' );
}
+ /**
+ * @testdox Checkout form internals are removed before persistence and before sending, while the local hook value is preserved.
+ *
+ * @dataProvider checkout_form_arguments
+ * @param string $hook Checkout hook.
+ * @param mixed $argument The first hook argument.
+ */
+ public function test_checkout_form_internals_are_redacted( string $hook, $argument ): void {
+ $sut = $this->create_active_webhook( 'action.' . $hook . '.suffix' );
+ $sut->save();
+ $sut->enqueue();
+
+ if ( 'woocommerce_after_checkout_validation' === $hook ) {
+ do_action( $hook, $argument, new WP_Error() );
+ } elseif ( 'woocommerce_checkout_update_order_review' === $hook ) {
+ do_action( $hook, $argument );
+ } else {
+ $this->assertSame( $argument, apply_filters( $hook, $argument ) );
+ }
+ $body = $this->run_scheduled_webhook_delivery( $sut, 'fixture-password' );
+ $this->assertStringContainsString( '[redacted]', $body );
+ if ( 'woocommerce_process_checkout_field_account_password' !== $hook && 'woocommerce_process_checkout_password_field' !== $hook ) {
+ $this->assertStringContainsString( 'fixture-city', $body );
+ }
+ }
+
+ /**
+ * @testdox Queue and payload redaction use the topic supplied by the topic filter.
+ */
+ public function test_redaction_uses_filtered_topic(): void {
+ $sut = $this->create_active_webhook( 'action.woocommerce_add_to_cart' );
+ $sut->save();
+ $hook = 'woocommerce_process_checkout_field_account_password';
+ $id = $sut->get_id();
+ add_filter( 'woocommerce_webhook_topic', static fn( $topic, $webhook_id ) => $id === $webhook_id ? 'action.' . $hook : $topic, 10, 2 );
+ $sut->enqueue();
+
+ $this->assertSame( 'fixture-password', apply_filters( $hook, 'fixture-password' ), 'The checkout filter should keep the original password.' );
+ $this->assertSame( '[redacted]', $sut->build_payload( 'fixture-password' )['arg'], 'Payload redaction must also work for immediate delivery.' );
+ $this->assertStringContainsString( '[redacted]', $this->run_scheduled_webhook_delivery( $sut, 'fixture-password' ) );
+ }
+
+ /**
+ * @testdox Plugin fields are masked alongside built-in fields before queueing and delivery.
+ */
+ public function test_redacts_additional_fields_for_a_custom_hook(): void {
+ $hook = 'wc_webhook_redaction_fixture';
+ add_filter( 'woocommerce_webhook_redact_additional_fields', static fn( $fields, $source_hook ) => $hook === $source_hook ? array_merge( $fields, array( 'Gateway_Key' ) ) : $fields, 10, 2 );
+
+ $sut = $this->create_active_webhook( 'action.' . $hook );
+ $sut->save();
+ $sut->enqueue();
+ $argument = array(
+ 'gateway' => array( 'gateway_key' => 'fixture-private' ),
+ 'secret' => 'fixture-private',
+ 'currency' => 'USD',
+ );
+
+ $this->assertSame( $argument, apply_filters( $hook, $argument ) );
+ $body = json_decode( $this->run_scheduled_webhook_delivery( $sut, 'fixture-private' ), true );
+ $this->assertSame( '[redacted]', $body['arg']['gateway']['gateway_key'] );
+ $this->assertSame( '[redacted]', $body['arg']['secret'] );
+ $this->assertSame( 'USD', $body['arg']['currency'] );
+ }
+
+ /**
+ * @testdox Plugin fields in form data are masked while the format and unrelated values are preserved.
+ */
+ public function test_redacts_additional_form_fields(): void {
+ add_filter( 'woocommerce_webhook_redact_additional_fields', static fn() => array( 'gateway_key' ) );
+ $sut = $this->create_active_webhook( 'action.woocommerce_checkout_update_order_review' );
+ $payload = $sut->build_payload( '?currency=USD&&Gateway%5FKey=fixture-private&gateway_key=&flag¬e=a%3Db' );
+
+ $this->assertSame( '?currency=USD&&Gateway%5FKey=[redacted]&gateway_key=&flag¬e=a%3Db', $payload['arg'] );
+ }
+
+ /**
+ * Provide the checkout hooks that receive a password in their first argument.
+ *
+ * @return array
+ */
+ public function checkout_form_arguments(): array {
+ $posted = array(
+ 'account_password' => 'fixture-password',
+ 'billing_city' => 'fixture-city',
+ );
+
+ return array(
+ 'before validation' => array( 'woocommerce_after_checkout_validation', $posted ),
+ 'posted data' => array( 'woocommerce_checkout_posted_data', $posted ),
+ 'specific field' => array( 'woocommerce_process_checkout_field_account_password', 'fixture-password' ),
+ 'password type' => array( 'woocommerce_process_checkout_password_field', 'fixture-password' ),
+ 'serialized review' => array( 'woocommerce_checkout_update_order_review', 'billing_city=fixture-city&account%5Fpassword=fixture-password' ),
+ );
+ }
+
+ /**
+ * @testdox An HTML email footer webhook keeps the email identity but leaves out its internal properties.
+ *
+ * @dataProvider email_footer_internal_properties
+ * @param string $email_class Email class.
+ * @param string $property Internal property.
+ * @param string $email_id Expected public email ID.
+ * @phpstan-param class-string<WC_Email> $email_class
+ */
+ public function test_email_footer_leaves_out_internal_properties( string $email_class, string $property, string $email_id ): void {
+ $sut = $this->create_active_webhook( 'action.woocommerce_email_footer' );
+ $sut->save();
+ $sut->enqueue();
+
+ $user = self::factory()->user->create_and_get( array( 'role' => 'administrator' ) );
+ $email = new $email_class();
+ $email->$property = 'fixture-email-value';
+ $email->object = $user;
+ do_action( 'woocommerce_email_footer', $email );
+
+ $this->assertSame( 'fixture-email-value', $email->$property, 'The live email must retain its value.' );
+ $body = $this->run_scheduled_webhook_delivery( $sut, 'fixture-email-value' );
+ $this->assertStringNotContainsString( $user->user_pass, $body );
+ $this->assertStringContainsString( $email_id, $body );
+ }
+
+ /**
+ * Email objects with public internal properties.
+ *
+ * @return array
+ */
+ public function email_footer_internal_properties(): array {
+ return array(
+ 'password reset' => array( WC_Email_Customer_Reset_Password::class, 'reset_key', 'customer_reset_password' ),
+ 'account setup' => array( WC_Email_Customer_New_Account::class, 'set_password_url', 'customer_new_account' ),
+ 'email verification' => array( CustomerVerifyEmail::class, 'verify_url', 'customer_verify_email' ),
+ );
+ }
+
+ /**
+ * @testdox An ordinary custom action argument with a key query parameter is preserved.
+ */
+ public function test_custom_action_keeps_ordinary_url(): void {
+ $sut = $this->create_active_webhook( 'action.woocommerce_form_field_url' );
+ $url = 'https://example.com/catalog?key=blue-widget';
+
+ $this->assertSame( $url, $sut->build_payload( $url )['arg'] );
+ }
+
+ /**
+ * @testdox Immediate delivery redacts the HTTP body while existing local filters keep the original argument.
+ */
+ public function test_immediate_webhook_preserves_local_argument(): void {
+ global $wc_queued_webhooks;
+
+ $sut = $this->create_active_webhook( 'action.woocommerce_checkout_posted_data' );
+ $sut->save();
+ $sut->enqueue();
+
+ $original_arg = array( 'account_password' => 'fixture-password' );
+ $received_arg = null;
+ $body = '';
+ add_filter( 'woocommerce_webhook_deliver_async', '__return_false' );
+ add_filter(
+ 'woocommerce_webhook_http_args',
+ static function ( $args, $arg ) use ( &$received_arg ) {
+ $received_arg = $arg;
+ return $args;
+ },
+ 10,
+ 2
+ );
+ add_filter(
+ 'pre_http_request',
+ function ( $preempt, $args ) use ( &$body ) {
+ $body = $args['body'];
+ return $this->mock_http_response( 200 );
+ },
+ 10,
+ 2
+ );
+
+ apply_filters( 'woocommerce_checkout_posted_data', $original_arg );
+ wc_webhook_execute_queue();
+ $wc_queued_webhooks = null;
+
+ $this->assertSame( $original_arg, $received_arg );
+ $this->assertStringContainsString( '[redacted]', $body );
+ $this->assertStringNotContainsString( 'fixture-password', $body );
+ }
+
+ /**
+ * @testdox A queued delivery of an already stored blocked topic sends no HTTP request.
+ * @testWith ["woocommerce_login_credentials"]
+ * ["woocommerce_paypal_capture_request"]
+ * ["woocommerce_paypal_refund_request"]
+ * @param string $hook The blocked hook.
+ */
+ public function test_worker_skips_previously_allowed_topic( string $hook ): void {
+ global $wpdb;
+
+ $sut = $this->create_active_webhook( 'action.woocommerce_add_to_cart' );
+ $sut->save();
+ $wpdb->update( $wpdb->prefix . 'wc_webhooks', array( 'topic' => 'action.' . $hook . '.extra' ), array( 'webhook_id' => $sut->get_id() ) );
+ wp_cache_delete( $sut->get_id(), 'webhooks' );
+
+ add_filter(
+ 'pre_http_request',
+ function () {
+ $this->fail( 'A worker must not send a delivery for a refused topic.' );
+ }
+ );
+ wc_deliver_webhook_async( $sut->get_id(), array( 'password' => 'fixture-password' ) );
+
+ $this->assertSame( '', wc_get_webhook( $sut->get_id() )->get_topic() );
+ }
+
+ /**
+ * @testdox A remapped PayPal request filter keeps its arguments local.
+ * @testWith ["woocommerce_paypal_capture_request"]
+ * ["woocommerce_paypal_refund_request"]
+ * @param string $hook The blocked PayPal hook.
+ */
+ public function test_blocked_paypal_hook_does_not_queue_delivery( string $hook ): void {
+ global $wc_queued_webhooks;
+
+ $sut = $this->create_active_webhook( 'action.woocommerce_add_to_cart' );
+ $id = $sut->get_id();
+ add_filter( 'woocommerce_webhook_hooks', static fn( $hooks, $webhook_id ) => $id === $webhook_id ? array( $hook ) : $hooks, 10, 2 );
+ $sut->enqueue();
+
+ $request = array(
+ 'USER' => 'fixture-user',
+ 'PWD' => 'fixture-password',
+ 'SIGNATURE' => 'fixture-signature',
+ );
+ $this->assertSame( $request, apply_filters( $hook, $request ), 'The PayPal request must keep its values.' );
+ $this->assertEmpty( $wc_queued_webhooks, 'A blocked hook must not schedule a webhook even if an extension changes the subscription.' );
+ }
+
+ /**
+ * @testdox Resource payloads retain order keys and support the product objects used by bulk edits.
+ */
+ public function test_standard_resource_payloads_keep_existing_values(): void {
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+
+ $order = wc_create_order();
+ $sut = $this->create_active_webhook( 'order.created' );
+ $sut->set_user_id( get_current_user_id() );
+ $order_payload = $sut->build_payload( $order->get_id() );
+ $this->assertSame( $order->get_order_key(), $order_payload['order_key'] );
+
+ $product = WC_Helper_Product::create_simple_product();
+ $sut->set_topic( 'product.updated' );
+ $product_payload = $sut->build_payload( $product );
+ $this->assertSame( $product->get_id(), $product_payload['id'] );
+ }
+
+ /**
+ * Persist a queued webhook and run the worker with the stored arguments.
+ *
+ * @param WC_Webhook $webhook Scheduled webhook.
+ * @param string $hidden_value Value that the stored and sent copies should leave out.
+ * @return string
+ */
+ private function run_scheduled_webhook_delivery( WC_Webhook $webhook, string $hidden_value ): string {
+ global $wc_queued_webhooks;
+
+ wc_webhook_execute_queue();
+ $wc_queued_webhooks = null;
+
+ $actions = as_get_scheduled_actions(
+ array(
+ 'hook' => 'woocommerce_deliver_webhook_async',
+ 'group' => 'woocommerce-webhooks',
+ 'status' => ActionScheduler_Store::STATUS_PENDING,
+ )
+ );
+ $this->assertCount( 1, $actions, 'Exactly one delivery must be stored.' );
+ $args = reset( $actions )->get_args();
+ $this->assertSame( $webhook->get_id(), $args['webhook_id'] );
+ $this->assertStringNotContainsString( $hidden_value, wp_json_encode( $args ) );
+
+ $body = '';
+ add_filter(
+ 'pre_http_request',
+ function ( $preempt, $request ) use ( &$body ) {
+ $body = $request['body'];
+ return $this->mock_http_response( 200 );
+ },
+ 10,
+ 2
+ );
+ wc_deliver_webhook_async( $args['webhook_id'], $args['arg'] );
+
+ $this->assertNotSame( '', $body, 'The worker should send the scheduled delivery.' );
+ $this->assertStringNotContainsString( $hidden_value, $body );
+
+ return $body;
+ }
+
+ /**
+ * @testdox Two identical checkbox fields render even when the second webhook delivery is skipped.
+ */
+ public function test_duplicate_webhook_keeps_rendered_checkbox(): void {
+ global $wc_queued_webhooks;
+
+ $sut = $this->create_active_webhook( 'action.woocommerce_form_field_checkbox' );
+ $sut->enqueue();
+
+ $args = array(
+ 'type' => 'checkbox',
+ 'return' => true,
+ );
+ $first = woocommerce_form_field( 'fixture_checkbox', $args );
+ $second = woocommerce_form_field( 'fixture_checkbox', $args );
+
+ $this->assertStringContainsString( 'type="checkbox"', $first );
+ $this->assertSame( $first, $second );
+ $this->assertCount( 1, $wc_queued_webhooks );
+ $wc_queued_webhooks = null;
+ }
+
+ /**
+ * @testdox Capture named mail callbacks and keep callbacks that contain objects out of the queue.
+ */
+ public function test_mail_webhook_captures_only_named_callbacks(): void {
+ global $wc_queued_webhooks;
+
+ $hook = 'woocommerce_mail_callback';
+ $sut = $this->create_active_webhook( 'action.' . $hook );
+ $sut->enqueue();
+
+ $closure = static function (): bool {
+ return true;
+ };
+ foreach ( array( $closure, array( $sut, 'get_name' ) ) as $callback ) {
+ $this->assertSame( $callback, apply_filters( $hook, $callback ), 'The mail filter must keep the original callback.' );
+ $this->assertEmpty( $wc_queued_webhooks, 'The webhook must not queue a callback that contains an object.' );
+ }
+
+ $named_callbacks = array( 'wp_mail', array( 'WC_Cache_Helper', 'get_transient_version' ) );
+ foreach ( $named_callbacks as $callback ) {
+ $this->assertSame( $callback, apply_filters( $hook, $callback ) );
+ }
+ $this->assertSame( $named_callbacks, array_column( $wc_queued_webhooks, 'arg' ) );
+ }
+
+ /**
+ * @testdox Two log subscribers deliver one ordinary line each and ignore delivery logs.
+ */
+ public function test_log_webhooks_do_not_forward_delivery_logs(): void {
+ global $wc_queued_webhooks;
+
+ update_option( 'woocommerce_logs_logging_enabled', 'yes' );
+ update_option( 'woocommerce_logs_level_threshold', 'none' );
+ add_filter(
+ 'woocommerce_register_log_handlers',
+ static function () {
+ return array(
+ new class() extends LogHandlerFileV2 {
+ /**
+ * Run the real formatter without writing a log file.
+ *
+ * @param int $timestamp Log timestamp.
+ * @param string $level Log level.
+ * @param string $message Log message.
+ * @param array $context Log context.
+ * @return bool
+ */
+ public function handle( $timestamp, $level, $message, $context ) {
+ self::format_entry( $timestamp, $level, $message, $context );
+ return true;
+ }
+ },
+ );
+ }
+ );
+
+ $formatter = $this->create_active_webhook( 'action.woocommerce_format_log_entry' );
+ $messages = $this->create_active_webhook( 'action.woocommerce_logger_log_message' );
+ foreach ( array( $formatter, $messages ) as $sut ) {
+ $sut->save();
+ $sut->enqueue();
+ }
+
+ $delivery_logs = 0;
+ add_filter(
+ 'woocommerce_format_log_entry',
+ static function ( $entry, $details ) use ( &$delivery_logs ) {
+ if ( 'webhooks-delivery' === ( $details['context']['source'] ?? '' ) ) {
+ ++$delivery_logs;
+ }
+ return $entry;
+ },
+ 20,
+ 2
+ );
+ wc_get_logger()->info( 'Ordinary log entry for webhook test', array( 'source' => 'webhook-forwarding-test' ) );
+ $this->assertCount( 2, $wc_queued_webhooks );
+ wc_webhook_execute_queue();
+ $wc_queued_webhooks = null;
+
+ $actions = as_get_scheduled_actions(
+ array(
+ 'hook' => 'woocommerce_deliver_webhook_async',
+ 'group' => 'woocommerce-webhooks',
+ 'status' => ActionScheduler_Store::STATUS_PENDING,
+ )
+ );
+ $this->assertCount( 2, $actions );
+ $bodies = array();
+ add_filter(
+ 'pre_http_request',
+ function ( $preempt, $request ) use ( &$bodies ) {
+ $bodies[ $request['headers']['X-WC-Webhook-ID'] ][] = $request['body'];
+ return $this->mock_http_response( 200 );
+ },
+ 10,
+ 2
+ );
+
+ foreach ( $actions as $action ) {
+ $args = $action->get_args();
+ wc_deliver_webhook_async( $args['webhook_id'], $args['arg'] );
+ $this->assertEmpty( $wc_queued_webhooks, 'The worker must not capture the resulting delivery log.' );
+ }
+
+ foreach ( array( $formatter, $messages ) as $sut ) {
+ $this->assertArrayHasKey( $sut->get_id(), $bodies );
+ $this->assertCount( 1, $bodies[ $sut->get_id() ] );
+ $this->assertStringContainsString( 'Ordinary log entry for webhook test', $bodies[ $sut->get_id() ][0] );
+ }
+ $ordinary = $this->create_active_webhook( 'action.woocommerce_add_to_cart' );
+ $ordinary->save();
+ wc_deliver_webhook_async( $ordinary->get_id(), 123 );
+ $this->assertEmpty( $wc_queued_webhooks, 'Delivery logs from ordinary webhooks must also stay local.' );
+ $this->assertSame( 3, $delivery_logs, 'Delivery logs still reach the local log handler.' );
+ }
+
+ /**
+ * @testdox Saving a webhook is observable, but delivering the observer does not queue another observer.
+ * @testWith [false]
+ * [true]
+ * @param bool $remap_topic Whether to set the observer topic through a filter.
+ */
+ public function test_webhook_observer_does_not_observe_its_own_worker( bool $remap_topic ): void {
+ global $wc_queued_webhooks;
+
+ $updates = $this->create_active_webhook( $remap_topic ? 'action.woocommerce_add_to_cart' : 'action.woocommerce_webhook_updated' );
+ $statuses = $this->create_active_webhook( 'action.woocommerce_webhook_statuses' );
+ $source = $this->create_active_webhook( 'action.woocommerce_add_to_cart' );
+ $source->save();
+ // Creation marks the initial ping as pending.
+ $source->set_pending_delivery( false );
+ foreach ( array( $updates, $statuses ) as $sut ) {
+ $sut->save();
+ }
+ if ( $remap_topic ) {
+ $id = $updates->get_id();
+ add_filter( 'woocommerce_webhook_topic', static fn( $topic, $webhook_id ) => $id === $webhook_id ? 'action.woocommerce_webhook_updated' : $topic, 10, 2 );
+ }
+ $updates->enqueue();
+ $statuses->enqueue();
+
+ $source->set_name( 'Edited webhook' );
+ $source->save();
+ $this->assertCount( 1, $wc_queued_webhooks );
+ $this->assertSame( $updates, $wc_queued_webhooks[0]['webhook'] );
+ $this->assertSame( $source->get_id(), $wc_queued_webhooks[0]['arg'] );
+ $wc_queued_webhooks = null;
+
+ add_filter(
+ 'pre_http_request',
+ function () {
+ return $this->mock_http_response( 200 );
+ }
+ );
+ wc_deliver_webhook_async( $updates->get_id(), $source->get_id() );
+ $this->assertEmpty( $wc_queued_webhooks, 'Neither the load nor the save may start another observer delivery.' );
+ }
+
/**
* Build a pre_http_request response with the given status code.
*
diff --git a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-webhook-data-store-test.php b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-webhook-data-store-test.php
index 92b736cc42b..88ec2ee271e 100644
--- a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-webhook-data-store-test.php
+++ b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-webhook-data-store-test.php
@@ -46,4 +46,30 @@ class WC_Webhook_Data_Store_Test extends WC_Unit_Test_Case {
);
}
+ /**
+ * @testdox Saving an unrelated edit preserves the newer delivery URL and author.
+ */
+ public function test_unrelated_save_keeps_newer_delivery_url_and_author(): void {
+ $first_author = self::factory()->user->create();
+ $second_author = self::factory()->user->create();
+ $webhook = new WC_Webhook();
+ $webhook->set_status( 'paused' );
+ $webhook->set_delivery_url( 'https://example.com/original' );
+ $webhook->set_user_id( $first_author );
+ $webhook->save();
+
+ $earlier_copy = new WC_Webhook( $webhook->get_id() );
+ $webhook->set_delivery_url( 'https://example.com/current' );
+ $webhook->set_user_id( $second_author );
+ $webhook->save();
+
+ $earlier_copy->set_name( 'Integration webhook' );
+ $earlier_copy->save();
+
+ $saved = new WC_Webhook( $webhook->get_id() );
+ $this->assertSame( 'Integration webhook', $saved->get_name() );
+ $this->assertSame( 'https://example.com/current', $saved->get_delivery_url() );
+ $this->assertSame( $second_author, $saved->get_user_id() );
+ }
+
}
diff --git a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-webhooks-controller-tests.php b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-webhooks-controller-tests.php
index 18b612ee29b..50503926a06 100644
--- a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-webhooks-controller-tests.php
+++ b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-webhooks-controller-tests.php
@@ -350,6 +350,90 @@ class WC_REST_Webhooks_Controller_Tests extends WC_REST_Unit_Test_Case {
$this->assertSame( array_slice( $webhook_ids, $next_start, 2 ), $this->follow_link( $headers['Link'], 'next' ) );
}
+ /**
+ * @testdox Changing another user's webhook delivery URL makes the editor its author, while other edits keep the original author.
+ *
+ * @testWith [{"delivery_url": "https://example.com/shop-manager-receiver"}, true]
+ * [{"name": "Renamed by the shop manager"}, false]
+ * [{"name": "Sent back whole", "delivery_url": "https://example.com/admin-integration"}, false]
+ *
+ * @param array $changes The fields the shop manager updates.
+ * @param bool $editor_is_author Whether the shop manager should become the author.
+ */
+ public function test_payload_is_built_as_whoever_set_the_delivery_url( array $changes, bool $editor_is_author ): void {
+ $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) );
+ $shop_manager_id = self::factory()->user->create( array( 'role' => 'shop_manager' ) );
+ $customer_id = self::factory()->user->create( array( 'role' => 'customer' ) );
+ update_user_meta( $customer_id, 'loyalty_token', 'fixture-value' );
+
+ $webhook = new WC_Webhook();
+ $webhook->set_user_id( $admin_id );
+ $webhook->set_status( 'active' );
+ $webhook->set_topic( 'customer.created' );
+ $webhook->set_delivery_url( self::PING_URL_PREFIX . 'admin-integration' );
+ $webhook->save();
+
+ wp_set_current_user( $shop_manager_id );
+ $response = $this->do_rest_request( 'webhooks/' . $webhook->get_id(), 'PUT', $changes );
+ $this->assertSame( 200, $response->get_status() );
+
+ $webhook = wc_get_webhook( $webhook->get_id() );
+ $meta_keys = wp_list_pluck( $webhook->build_payload( $customer_id )['meta_data'] ?? array(), 'key' );
+
+ $this->assertSame( $editor_is_author ? $shop_manager_id : $admin_id, $webhook->get_user_id(), 'Unexpected webhook author after the edit.' );
+ $this->assertSame( ! $editor_is_author, in_array( 'loyalty_token', $meta_keys, true ), 'The payload should be built as the current author of the webhook.' );
+ }
+
+ /**
+ * @testdox Sending back the filtered URL preserves the stored URL and author.
+ */
+ public function test_filtered_delivery_url_round_trip_keeps_author(): void {
+ $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) );
+ $shop_manager_id = self::factory()->user->create( array( 'role' => 'shop_manager' ) );
+ $stored_url = self::PING_URL_PREFIX . 'admin-integration';
+ $webhook = new WC_Webhook();
+ $webhook->set_user_id( $admin_id );
+ $webhook->set_topic( 'customer.created' );
+ $webhook->set_delivery_url( $stored_url );
+ $webhook->save();
+
+ wp_set_current_user( $shop_manager_id );
+ $path = 'webhooks/' . $webhook->get_id();
+ add_filter( 'woocommerce_webhook_delivery_url', static fn( $url ) => add_query_arg( 'source', 'store', $url ) );
+ $read = $this->do_rest_get_request( $path );
+ $this->assertSame( 200, $read->get_status() );
+ $delivery_url = $read->get_data()['delivery_url'];
+ $this->assertSame( $stored_url . '?source=store', $delivery_url );
+
+ $response = $this->do_rest_request( $path, 'PUT', array( 'delivery_url' => $delivery_url ) );
+ $this->assertSame( 200, $response->get_status() );
+ $saved = wc_get_webhook( $webhook->get_id() );
+ $this->assertSame( $stored_url, $saved->get_data()['delivery_url'] );
+ $this->assertSame( $admin_id, $saved->get_user_id() );
+ }
+
+ /**
+ * @testdox Changing the delivery URL without a logged-in user keeps the existing author.
+ */
+ public function test_delivery_url_change_without_a_user_keeps_the_author(): void {
+ $admin_id = self::factory()->user->create( array( 'role' => 'administrator' ) );
+
+ $webhook = new WC_Webhook();
+ $webhook->set_user_id( $admin_id );
+ $webhook->set_topic( 'customer.created' );
+ $webhook->set_delivery_url( self::PING_URL_PREFIX . 'admin-integration' );
+ $webhook->save();
+
+ // Code that grants REST access to scheduled tasks lets a request through with no user.
+ wp_set_current_user( 0 );
+ add_filter( 'woocommerce_rest_check_permissions', '__return_true' );
+
+ $response = $this->do_rest_request( 'webhooks/' . $webhook->get_id(), 'PUT', array( 'delivery_url' => self::PING_URL_PREFIX . 'scheduled-task' ) );
+ $this->assertSame( 200, $response->get_status() );
+
+ $this->assertSame( $admin_id, wc_get_webhook( $webhook->get_id() )->get_user_id() );
+ }
+
/**
* Create webhooks, returning their IDs in creation order.
*
diff --git a/plugins/woocommerce/tests/php/src/Internal/Utilities/WebhookUtilTest.php b/plugins/woocommerce/tests/php/src/Internal/Utilities/WebhookUtilTest.php
new file mode 100644
index 00000000000..fb6d733a32d
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Utilities/WebhookUtilTest.php
@@ -0,0 +1,62 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Utilities;
+
+use Automattic\WooCommerce\Internal\Utilities\WebhookUtil;
+use WC_Unit_Test_Case;
+use WC_Webhook;
+
+/**
+ * Tests for the WebhookUtil class.
+ */
+class WebhookUtilTest extends WC_Unit_Test_Case {
+
+ /**
+ * The System Under Test.
+ *
+ * @var WebhookUtil
+ */
+ private $sut;
+
+ /**
+ * Set up test fixtures.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->sut = wc_get_container()->get( WebhookUtil::class );
+ }
+
+ /**
+ * @testdox The delete user screen explains what "Attribute all content to" does to webhooks only when WordPress offers that option.
+ *
+ * @testWith [true]
+ * [false]
+ *
+ * @param bool $user_has_content Whether the user owns content. WordPress offers to reassign content only then.
+ */
+ public function test_delete_user_warning_explains_reassignment_only_when_offered( bool $user_has_content ): void {
+ $user_id = self::factory()->user->create( array( 'role' => 'shop_manager' ) );
+
+ $webhook = new WC_Webhook();
+ $webhook->set_user_id( $user_id );
+ $webhook->set_topic( 'order.created' );
+ $webhook->set_delivery_url( 'https://example.com/webhook' );
+ $webhook->save();
+
+ if ( $user_has_content ) {
+ self::factory()->post->create( array( 'post_author' => $user_id ) );
+ }
+
+ ob_start();
+ $this->sut->maybe_render_user_with_webhooks_warning( wp_get_current_user(), array( $user_id ) );
+ $output = (string) ob_get_clean();
+
+ $this->assertStringContainsString( 'has created 1 WooCommerce webhook.', $output, 'The warning should count the webhooks of the user.' );
+ $this->assertSame(
+ $user_has_content,
+ str_contains( $output, 'Attribute all content to' ),
+ 'The reassignment text should show only when WordPress offers to reassign content.'
+ );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Webhooks/WebhookScheduledActionArgsTest.php b/plugins/woocommerce/tests/php/src/Internal/Webhooks/WebhookScheduledActionArgsTest.php
new file mode 100644
index 00000000000..3a1f114cb0b
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Webhooks/WebhookScheduledActionArgsTest.php
@@ -0,0 +1,118 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Webhooks;
+
+use WC_Unit_Test_Case;
+use WC_Webhook;
+
+/**
+ * Tests for the WebhookScheduledActionArgs class.
+ */
+class WebhookScheduledActionArgsTest extends WC_Unit_Test_Case {
+
+ /**
+ * @testdox Should show queued custom action webhook deliveries without their internal fields.
+ */
+ public function test_redacts_custom_action_delivery_args(): void {
+ $webhook = $this->create_webhook( 'action.woocommerce_checkout_posted_data' );
+
+ $html = $this->get_args_column( $webhook->get_id(), array( 'account_password' => 'fixture-value' ) );
+
+ $this->assertStringNotContainsString( 'fixture-value', $html );
+ $this->assertStringContainsString( '[redacted]', $html );
+ }
+
+ /**
+ * @testdox Masks credentials in a stored query string regardless of the current action topic.
+ */
+ public function test_redacts_stored_query_parameters_independently_of_topic(): void {
+ $webhook = $this->create_webhook( 'action.wc_webhook_display_fixture' );
+
+ $html = $this->get_args_column( $webhook->get_id(), array( 'query_string' => 'page=2&password=fixture-value' ) );
+
+ $this->assertStringNotContainsString( 'fixture-value', $html );
+ $this->assertStringContainsString( 'page=2&password=[redacted]', $html );
+ }
+
+ /**
+ * @testdox Should hide the whole argument of deliveries for deleted webhooks.
+ */
+ public function test_hides_args_of_deleted_webhooks(): void {
+ $html = $this->get_args_column( 999999, 'https://example.com/?secret_value=fixture-value' );
+
+ $this->assertStringNotContainsString( 'fixture-value', $html );
+ }
+
+ /**
+ * @testdox Should hide arguments queued under an earlier action topic after the webhook moved to a resource topic.
+ */
+ public function test_hides_non_id_args_of_resource_webhooks(): void {
+ $webhook = $this->create_webhook( 'order.created' );
+
+ $html = $this->get_args_column( $webhook->get_id(), array( 'account_password' => 'fixture-value' ) );
+
+ $this->assertStringNotContainsString( 'fixture-value', $html );
+ }
+
+ /**
+ * @testdox Should leave resource webhook deliveries, which carry an ID, as they are.
+ */
+ public function test_leaves_resource_delivery_args_unchanged(): void {
+ $webhook = $this->create_webhook( 'order.created' );
+
+ $html = $this->get_args_column( $webhook->get_id(), 42 );
+
+ $this->assertSame( 'raw: 42', $html );
+ }
+
+ /**
+ * @testdox Should show extension resource deliveries that carry an ID as they are.
+ */
+ public function test_leaves_extension_resource_ids_unchanged(): void {
+ add_filter( 'woocommerce_valid_webhook_resources', fn( $resources ) => array_merge( $resources, array( 'booking' ) ) );
+ $webhook = $this->create_webhook( 'booking.created' );
+
+ $this->assertSame( 'raw: 42', $this->get_args_column( $webhook->get_id(), 42 ) );
+ }
+
+ /**
+ * Run the Scheduled Actions args column filter for a webhook delivery row.
+ *
+ * @param int $webhook_id The webhook ID.
+ * @param mixed $arg The queued hook argument.
+ * @return string
+ */
+ private function get_args_column( int $webhook_id, $arg ): string {
+ $row = array(
+ 'hook' => 'woocommerce_deliver_webhook_async',
+ 'args' => array(
+ 'webhook_id' => $webhook_id,
+ 'arg' => $arg,
+ ),
+ );
+
+ // Action Scheduler's own column shows the raw stored argument.
+ $raw_html = 'raw: ' . wp_json_encode( $arg );
+
+ return (string) apply_filters( 'action_scheduler_list_table_column_args', $raw_html, $row );
+ }
+
+ /**
+ * Create an active webhook.
+ *
+ * @param string $topic The topic.
+ * @return WC_Webhook
+ */
+ private function create_webhook( string $topic ): WC_Webhook {
+ $webhook = new WC_Webhook();
+ $webhook->set_status( 'active' );
+ $webhook->set_topic( $topic );
+ $webhook->set_delivery_url( 'https://example.com/webhook' );
+ $webhook->set_user_id( 1 );
+ $webhook->set_pending_delivery( false );
+ $webhook->save();
+
+ return $webhook;
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Webhooks/WebhookTopicNoticesTest.php b/plugins/woocommerce/tests/php/src/Internal/Webhooks/WebhookTopicNoticesTest.php
new file mode 100644
index 00000000000..ac2181c0b75
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Webhooks/WebhookTopicNoticesTest.php
@@ -0,0 +1,161 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Webhooks;
+
+use Automattic\WooCommerce\Internal\Webhooks\WebhookTopicNotices;
+use WC_Admin_Notices;
+use WC_Data_Store;
+use WC_Unit_Test_Case;
+use WC_Webhook;
+
+/**
+ * Tests for the WebhookTopicNotices class.
+ */
+class WebhookTopicNoticesTest extends WC_Unit_Test_Case {
+
+ /**
+ * The System Under Test.
+ *
+ * @var WebhookTopicNotices
+ */
+ private $sut;
+
+ /**
+ * Whether the blocked-topics notice was already in the admin notices cache.
+ *
+ * @var bool|null
+ */
+ private $had_blocked_topics_notice;
+
+ /**
+ * Set up test fixtures.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->had_blocked_topics_notice = WC_Admin_Notices::has_notice( WebhookTopicNotices::BLOCKED_TOPICS_NOTICE );
+ delete_option( WebhookTopicNotices::TOPIC_CHECK_OPTION );
+ $this->sut = new WebhookTopicNotices();
+ }
+
+ /**
+ * Restore the notice cache. The parent rolls back the saved option.
+ */
+ public function tearDown(): void {
+ try {
+ if ( false === $this->had_blocked_topics_notice ) {
+ WC_Admin_Notices::remove_notice( WebhookTopicNotices::BLOCKED_TOPICS_NOTICE );
+ }
+ } finally {
+ parent::tearDown();
+ }
+ }
+
+ /**
+ * @testdox Should disable stored webhooks on refused topics, keep their topic, and list them in a notice.
+ */
+ public function test_disables_webhooks_on_refused_topics_and_adds_notice(): void {
+ $blocked = $this->create_webhook( 'Mail webhook', 'action.woocommerce_add_to_cart' );
+ $this->set_raw_topic( $blocked->get_id(), 'action.woocommerce_mail_content' );
+ $allowed = $this->create_webhook( 'Cart tracker', 'action.woocommerce_add_to_cart' );
+
+ $data_store = WC_Data_Store::load( 'webhook' );
+ $this->assertContains( $blocked->get_id(), $data_store->get_webhooks_ids( 'active' ) );
+ $updated_ids = array();
+ add_action(
+ 'woocommerce_webhook_updated',
+ function ( $webhook_id ) use ( &$updated_ids, $data_store ) {
+ $updated_ids[] = $webhook_id;
+ $this->assertSame( 'disabled', wc_get_webhook( $webhook_id )->get_status() );
+ $this->assertNotContains( $webhook_id, $data_store->get_webhooks_ids( 'active' ) );
+ }
+ );
+
+ $this->sut->handle_admin_init();
+ $this->sut->handle_admin_init();
+
+ $this->assertSame( array( $blocked->get_id() ), $updated_ids, 'Only the webhook that was disabled should send one update notification.' );
+ $this->assertSame( 'disabled', $this->get_raw_column( $blocked->get_id(), 'status' ), 'The webhook on a refused topic should be disabled' );
+ $this->assertSame( 'action.woocommerce_mail_content', $this->get_raw_column( $blocked->get_id(), 'topic' ), 'The stored topic should be kept' );
+ $this->assertSame( 'active', wc_get_webhook( $allowed->get_id() )->get_status(), 'A webhook on an allowed topic should stay active' );
+ $this->assertTrue( WC_Admin_Notices::has_notice( WebhookTopicNotices::BLOCKED_TOPICS_NOTICE ), 'A notice should be added' );
+ $this->assertStringContainsString( 'action.woocommerce_mail_content', (string) get_option( 'woocommerce_admin_notice_' . WebhookTopicNotices::BLOCKED_TOPICS_NOTICE ), 'The notice should name the refused topic' );
+ }
+
+ /**
+ * @testdox Lists already-disabled webhooks without claiming that their status changed.
+ */
+ public function test_notice_includes_already_disabled_webhook(): void {
+ $webhook = $this->create_webhook( 'Old PayPal webhook', 'action.woocommerce_add_to_cart' );
+ $webhook->set_status( 'disabled' );
+ $webhook->save();
+ $this->set_raw_topic( $webhook->get_id(), 'action.woocommerce_paypal_refund_request' );
+ $updates = did_action( 'woocommerce_webhook_updated' );
+
+ $this->sut->handle_admin_init();
+
+ $notice = (string) get_option( 'woocommerce_admin_notice_' . WebhookTopicNotices::BLOCKED_TOPICS_NOTICE );
+ $this->assertStringContainsString( 'Some webhooks use topics that are no longer supported.', $notice );
+ $this->assertStringContainsString( 'Old PayPal webhook', $notice );
+ $this->assertSame( 'disabled', $this->get_raw_column( $webhook->get_id(), 'status' ) );
+ $this->assertSame( $updates, did_action( 'woocommerce_webhook_updated' ), 'Already-disabled webhooks should only appear in the notice.' );
+ }
+
+ /**
+ * @testdox Should check stored webhooks only once per topic rules version.
+ */
+ public function test_checks_stored_webhooks_once(): void {
+ $this->sut->handle_admin_init();
+
+ $blocked = $this->create_webhook( 'Mail webhook', 'action.woocommerce_add_to_cart' );
+ $this->set_raw_topic( $blocked->get_id(), 'action.woocommerce_mail_content' );
+ $this->sut->handle_admin_init();
+
+ $this->assertSame( 'active', $this->get_raw_column( $blocked->get_id(), 'status' ), 'A later admin page load should not scan the webhooks again' );
+ }
+
+ /**
+ * Create an active webhook.
+ *
+ * @param string $name Webhook name.
+ * @param string $topic Webhook topic.
+ * @return WC_Webhook
+ */
+ private function create_webhook( string $name, string $topic ): WC_Webhook {
+ $webhook = new WC_Webhook();
+ $webhook->set_name( $name );
+ $webhook->set_status( 'active' );
+ $webhook->set_topic( $topic );
+ $webhook->set_delivery_url( 'https://example.com/webhook' );
+ $webhook->set_user_id( 1 );
+ $webhook->set_pending_delivery( false );
+ $webhook->save();
+
+ return $webhook;
+ }
+
+ /**
+ * Store a topic directly, as a webhook saved before the topic was refused would have it.
+ *
+ * @param int $webhook_id Webhook ID.
+ * @param string $topic Raw topic.
+ */
+ private function set_raw_topic( int $webhook_id, string $topic ): void {
+ global $wpdb;
+ $wpdb->update( "{$wpdb->prefix}wc_webhooks", array( 'topic' => $topic ), array( 'webhook_id' => $webhook_id ) );
+ wp_cache_delete( $webhook_id, 'webhooks' );
+ }
+
+ /**
+ * Read a stored webhook column.
+ *
+ * @param int $webhook_id Webhook ID.
+ * @param string $column Column name.
+ * @return string
+ */
+ private function get_raw_column( int $webhook_id, string $column ): string {
+ global $wpdb;
+ // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Column name is a test constant.
+ return (string) $wpdb->get_var( $wpdb->prepare( "SELECT {$column} FROM {$wpdb->prefix}wc_webhooks WHERE webhook_id = %d", $webhook_id ) );
+ }
+}