Commit 057166e3157 for woocommerce
commit 057166e3157b03fc52db548652a90c2a035e065d
Author: Barry Hughes <3594411+barryhughes@users.noreply.github.com>
Date: Fri Nov 20 15:00:18 2026 -0700
Subscriptions engine: exact owner matching on every read, and throw on failed plan reads (#71280)
* Make subscriptions engine owner matching exact through binary owner columns
The extension_slug columns on plans, contracts and cycles now use the table
charset's binary collation (schema 2.9.0), so every owner match is exact for
case and accents: the plan list and count filter, the internal plan delete,
the creation-key duplicate check (UNIQUE index and fallback read) and the due
scan, which matched case-insensitively before. The CAST(... AS BINARY) owner
predicates are now redundant and go, and the plan field update goes back to
$wpdb->update(), which refuses a value too long for its column itself.
Pre-freeze, existing tables must be dropped and recreated.
WOOSUBS-2163
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Throw on a failed subscriptions engine plan read
PlanRepository::find() now checks the database error after its read, as
exists() does, so a failed read throws a RuntimeException instead of
reading as a missing plan. Plans::update() and Plans::get() no longer
report a plan as missing when the read itself failed.
WOOSUBS-2165
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Add a changelog entry for exact subscriptions engine owner matching
WOOSUBS-2163, WOOSUBS-2165
* Tests: do not assert WordPress core's translatable update error text
* Validate owner slugs at every subscriptions engine entry point
An extension_slug must now be 1-64 lowercase letters, digits, hyphens or
underscores. Every facade that takes an owner (contract lock, create,
update, cycle and meta writes, the customer list owner filter, plan create,
update, meta writes and the plan list filter) and the plans REST routes
refuse any other value with a new invalid_pattern validation error before a
query runs. The consumer and contract action registries refuse it with
_doing_it_wrong() instead of trimming it.
Case variants, spaces and accents therefore never reach SQL, so two valid
owners cannot compare equal under a case-insensitive or PAD SPACE
collation. The binary owner columns stay as a second safeguard.
WOOSUBS-2163
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Answer a failed plan read with a 500 in the plans REST route
PlansController::get_item() now catches the RuntimeException that
Plans::get() throws on a failed read, logs it and returns a 500
woocommerce_subscriptions_engine_plan_read_failed error, as update_item()
does for a failed write.
WOOSUBS-2165
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Share one slug format check across the subscriptions engine
ArgumentValidator::SLUG_PATTERN and is_slug() are now the only copy of the
1-64 lowercase letters, digits, hyphens or underscores format: owner slugs,
the registries, the contract schedule source check and the lock operation
label check all use them. get_item_field() is public so facades build list
item field paths the same way.
WOOSUBS-2163
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Refuse padded owner slugs in the plans REST routes
The plans REST routes no longer trim the extension_slug param, so a padded
or whitespace-only slug is refused with invalid_pattern, as the facades
refuse it. In the list filter only whitespace next to a comma is dropped,
as list formatting. Plans::list() documents the slug format and builds list
item field paths with ArgumentValidator::get_item_field().
Tests cover padded slugs on every plans route including update_item, name
the case in looped assertions, check what a valid slug actually does at
each facade, and add accented slugs to the registry tests.
WOOSUBS-2163
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Report every bad owner slug in a plan list filter
Plans::list() checked the slug format only after the whole list passed the
type check, so array( 'LITE', 5 ) reported only the type error. Each
non-empty string item of a list now gets the format check at its indexed
field, while empty and non-string items keep the list check's error.
WOOSUBS-2163
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Document that engine repositories take validated arguments
ContractRepository and PlanRepository are storage behind the Api facades:
arguments, owner slugs included, are validated once at the public boundary
and not checked again. Mark both classes internal and describe
PlanRepository::delete()'s optional owner as a scope.
WOOSUBS-2163
Co-Authored-By: Claude Code <noreply@anthropic.com>
---------
Co-authored-by: Claude Code <noreply@anthropic.com>
diff --git a/packages/php/woocommerce-subscriptions-engine/changelog/update-subscriptions-engine-owner-collation-and-plan-read b/packages/php/woocommerce-subscriptions-engine/changelog/update-subscriptions-engine-owner-collation-and-plan-read
new file mode 100644
index 00000000000..2501e6a2f54
--- /dev/null
+++ b/packages/php/woocommerce-subscriptions-engine/changelog/update-subscriptions-engine-owner-collation-and-plan-read
@@ -0,0 +1,4 @@
+Significance: patch
+Type: dev
+Comment: Validate owner slugs and make owner matching exact in the unreleased subscriptions engine, and throw on failed plan reads; no changelog entry needed.
+
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/ContractActions.php b/packages/php/woocommerce-subscriptions-engine/src/Api/ContractActions.php
index 6888d189d07..91b388e8cc2 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/ContractActions.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/ContractActions.php
@@ -9,6 +9,7 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\SubscriptionsEngine\Api;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator;
use Automattic\WooCommerce\SubscriptionsEngine\Integration\Rest\ContractActionRegistry;
use Automattic\WooCommerce\SubscriptionsEngine\Integration\Support\ArgumentFilter;
@@ -41,7 +42,7 @@ final class ContractActions {
* An invalid or duplicate registration raises a `_doing_it_wrong()` notice and is not
* registered (the first registration is kept). Unknown keys raise a notice and are ignored.
*
- * @param string $extension_slug Owning extension slug; matches the contracts' `extension_slug`.
+ * @param string $extension_slug Owning extension slug (1-64 of `[a-z0-9_-]`); matches the contracts' `extension_slug`.
* @param string $action Action slug: lowercase letters, numbers, hyphens and underscores.
* @param array<string, mixed> $args `callback` (required): `callable( ContractView $contract, array $action_args ): ContractView|WP_Error`.
* `permission` (required): a capability, checked as `current_user_can( $permission, $contract )`
@@ -60,8 +61,8 @@ final class ContractActions {
$action_args = $filtered_args['args'] ?? array();
$is_available = $filtered_args['is_available'] ?? null;
- if ( '' === trim( $extension_slug ) ) {
- self::reject( 'The extension slug must not be empty.' );
+ if ( ! ArgumentValidator::is_slug( $extension_slug ) ) {
+ self::reject( sprintf( 'The extension slug "%s" must be 1-64 lowercase letters, digits, hyphens or underscores.', $extension_slug ) );
return;
}
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
index 41e7c0e3ad7..c19b0270894 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
@@ -156,7 +156,7 @@ final class Contracts {
* @param string $extension_slug The expected owner (the contract's owning extension).
* @param string $operation Operation label (1-64 of `[a-z0-9_-]`), shown to callers that conflict.
* @return ContractLock|null The held lock; null when another operation holds it or no contract of that extension has the id.
- * @throws ValidationException If `$extension_slug` is empty.
+ * @throws ValidationException If `$extension_slug` is not a valid extension slug (1-64 of `[a-z0-9_-]`).
* @throws InvalidArgumentException If the label is invalid: refused after the slug, alone.
*/
public static function lock( int $contract_id, string $extension_slug, string $operation ): ?ContractLock {
@@ -192,8 +192,11 @@ final class Contracts {
$validator = new ArgumentValidator();
$operation = $validator->get_string( 'operation', $filtered_options['operation'] ?? self::CREATE_OPERATION );
$extension_slug = $validator->get_nullable_string( 'extension_slug', $filtered_args['extension_slug'] ?? null );
- $creation_key = $validator->get_nullable_string( 'creation_key', $filtered_args['creation_key'] ?? null );
- $fields = self::get_contract_fields( $validator, $filtered_args );
+ if ( null !== $extension_slug && '' !== $extension_slug ) {
+ $validator->get_extension_slug( 'extension_slug', $extension_slug );
+ }
+ $creation_key = $validator->get_nullable_string( 'creation_key', $filtered_args['creation_key'] ?? null );
+ $fields = self::get_contract_fields( $validator, $filtered_args );
try {
$validator->throw_errors();
$contract = Contract::create(
@@ -245,7 +248,7 @@ final class Contracts {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::CONTRACT_KEYS );
$validator = new ArgumentValidator();
- $extension_slug = (string) $validator->get_non_empty_string( 'extension_slug', $filtered_args['extension_slug'] ?? null );
+ $extension_slug = (string) $validator->get_extension_slug( 'extension_slug', $filtered_args['extension_slug'] ?? null );
$changes = self::get_contract_fields( $validator, $filtered_args );
try {
$validator->throw_errors();
@@ -357,7 +360,7 @@ final class Contracts {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::CYCLE_KEYS );
$validator = new ArgumentValidator();
- $extension_slug = (string) $validator->get_non_empty_string( 'extension_slug', $filtered_args['extension_slug'] ?? null );
+ $extension_slug = (string) $validator->get_extension_slug( 'extension_slug', $filtered_args['extension_slug'] ?? null );
$cycle_args = array(
'contract_id' => $contract_id,
'kind' => $filtered_args['kind'] ?? null,
@@ -422,7 +425,7 @@ final class Contracts {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::TRANSITION_KEYS );
$validator = new ArgumentValidator();
- $extension_slug = (string) $validator->get_non_empty_string( 'extension_slug', $filtered_args['extension_slug'] ?? null );
+ $extension_slug = (string) $validator->get_extension_slug( 'extension_slug', $filtered_args['extension_slug'] ?? null );
$from_status = $validator->get_non_empty_string( 'from_status', $filtered_args['from_status'] ?? null );
$to_status = $validator->get_non_empty_string( 'to_status', $filtered_args['to_status'] ?? null );
$changes = array();
@@ -466,7 +469,7 @@ final class Contracts {
* @param bool $unique When true, add nothing if the key already exists.
* @param ContractLock|null $lock The caller's lock on this contract, or null for an internal one.
* @return int|null The meta row id; null when `$unique` and the key exists.
- * @throws ValidationException If `$extension_slug` or `$key` is empty, with both reported.
+ * @throws ValidationException If `$extension_slug` is not a valid extension slug or `$key` is empty, with both reported.
* @throws InvalidArgumentException If no contract of that extension has the id, or the lock is for another contract or extension.
* @throws ContractLockedException If another operation holds the lock, or `$lock` was lost.
* @throws \RuntimeException If the key is longer than the meta_key column (255 characters).
@@ -490,7 +493,7 @@ final class Contracts {
* value ('' and false included) matches literally.
* @param ContractLock|null $lock The caller's lock on this contract, or null for an internal one.
* @return bool True when a value was added or changed; false when nothing changed.
- * @throws ValidationException If `$extension_slug` or `$key` is empty, with both reported.
+ * @throws ValidationException If `$extension_slug` is not a valid extension slug or `$key` is empty, with both reported.
* @throws InvalidArgumentException If no contract of that extension has the id, or the lock is for another contract or extension.
* @throws ContractLockedException If another operation holds the lock, or `$lock` was lost.
* @throws \RuntimeException If the key is longer than the meta_key column (255 characters).
@@ -513,7 +516,7 @@ final class Contracts {
* Any other value ('' and false included) matches literally.
* @param ContractLock|null $lock The caller's lock on this contract, or null for an internal one.
* @return bool True when at least one value was deleted; false also when no contract of that extension has the id.
- * @throws ValidationException If `$extension_slug` or `$key` is empty, with both reported.
+ * @throws ValidationException If `$extension_slug` is not a valid extension slug or `$key` is empty, with both reported.
* @throws InvalidArgumentException If the lock is for another contract or extension.
* @throws ContractLockedException If another operation holds the lock, or `$lock` was lost.
*/
@@ -639,7 +642,7 @@ final class Contracts {
* Absent: every extension.
* }
* @return array<int, ContractView> The customer's contracts, newest first.
- * @throws ValidationException If `extension_slug` is empty, not a string, or `any`.
+ * @throws ValidationException If `extension_slug` is empty, not a string, not a valid extension slug, or `any`.
*/
public static function list_for_customer( int $customer_id, int $limit = 20, int $offset = 0, array $args = array() ): array {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::LIST_FOR_CUSTOMER_KEYS );
@@ -651,7 +654,7 @@ final class Contracts {
);
if ( array_key_exists( 'extension_slug', $filtered_args ) ) {
$validator = new ArgumentValidator();
- $extension_slug = $validator->get_non_empty_string( 'extension_slug', $filtered_args['extension_slug'] );
+ $extension_slug = $validator->get_extension_slug( 'extension_slug', $filtered_args['extension_slug'] );
if ( 'any' === $extension_slug ) {
$validator->add(
new InvalidInputException(
@@ -720,11 +723,11 @@ final class Contracts {
*
* @param string $extension_slug The expected owner.
* @param string|null $key Meta key, or null for a write that takes none.
- * @throws ValidationException If the owner or the key is empty.
+ * @throws ValidationException If the owner is not a valid extension slug or the key is empty.
*/
private static function assert_scope( string $extension_slug, ?string $key = null ): void {
$validator = new ArgumentValidator();
- $validator->get_non_empty_string( 'extension_slug', $extension_slug );
+ $validator->get_extension_slug( 'extension_slug', $extension_slug );
if ( null !== $key ) {
$validator->get_non_empty_string( 'key', $key );
}
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php
index 101348dace1..4a3a1954cc3 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php
@@ -109,7 +109,10 @@ final class Plans {
$validator = new ArgumentValidator();
$extension_slug = $validator->get_nullable_string( 'extension_slug', $filtered_args['extension_slug'] ?? null );
- $fields = self::get_plan_fields( $validator, $filtered_args + array( 'name' => '' ) );
+ if ( null !== $extension_slug && '' !== $extension_slug ) {
+ $validator->get_extension_slug( 'extension_slug', $extension_slug );
+ }
+ $fields = self::get_plan_fields( $validator, $filtered_args + array( 'name' => '' ) );
try {
$validator->throw_errors();
} catch ( InvalidInputException $e ) {
@@ -159,13 +162,14 @@ final class Plans {
* with the engine code, `field` and `params`), or the owning extension
* refuses the plan; entity and extension refusals arrive in one exception.
* @throws RuntimeException If a validation callback throws (the callback's throwable is chained
- * as the previous exception) or the update fails (no previous exception).
+ * as the previous exception), or the plan read or the update fails (no
+ * previous exception).
*/
public static function update( int $plan_id, array $args ): ?PlanView {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::PLAN_KEYS );
$validator = new ArgumentValidator();
- $extension_slug = $validator->get_non_empty_string( 'extension_slug', $filtered_args['extension_slug'] ?? null );
+ $extension_slug = $validator->get_extension_slug( 'extension_slug', $filtered_args['extension_slug'] ?? null );
$changes = self::get_plan_fields( $validator, $filtered_args );
try {
$validator->throw_errors();
@@ -214,7 +218,7 @@ final class Plans {
* @param bool $unique When true, add nothing if the key already exists. Advisory: no
* unique index, so concurrent adds can both write.
* @return int|null The meta row id; null when `$unique` and the key exists.
- * @throws ValidationException If `$extension_slug` or `$key` is empty, with both reported.
+ * @throws ValidationException If `$extension_slug` is not a valid extension slug or `$key` is empty, with both reported.
* @throws InvalidArgumentException If no plan of that extension has the id.
* @throws RuntimeException If the key is longer than the meta_key column (255 characters).
*/
@@ -236,7 +240,7 @@ final class Plans {
* @param mixed $prev_value Only update values equal to this; null updates all. Any other
* value ('' and false included) matches literally.
* @return bool True when a value was added or changed; false when nothing changed.
- * @throws ValidationException If `$extension_slug` or `$key` is empty, with both reported.
+ * @throws ValidationException If `$extension_slug` is not a valid extension slug or `$key` is empty, with both reported.
* @throws InvalidArgumentException If no plan of that extension has the id.
* @throws RuntimeException If the key is longer than the meta_key column (255 characters).
*/
@@ -257,7 +261,7 @@ final class Plans {
* @param mixed $value Only delete values equal to this; null deletes every value for the key.
* Any other value ('' and false included) matches literally.
* @return bool True when at least one value was deleted; false also when no plan of that extension has the id.
- * @throws ValidationException If `$extension_slug` or `$key` is empty, with both reported.
+ * @throws ValidationException If `$extension_slug` is not a valid extension slug or `$key` is empty, with both reported.
*/
public static function delete_meta( int $plan_id, string $extension_slug, string $key, $value = null ): bool {
self::assert_scope( $extension_slug, $key );
@@ -283,6 +287,7 @@ final class Plans {
*
* @param int $plan_id Plan id.
* @return PlanView|null The plan, or null when none exists.
+ * @throws RuntimeException If the read fails.
*/
public static function get( int $plan_id ): ?PlanView {
$plan = ( new PlanRepository() )->find( $plan_id );
@@ -300,8 +305,9 @@ final class Plans {
* @param array<string, mixed> $args {
* Optional. Query args.
*
- * @type string|string[] $extension_slug Owning extension slug, or a list of them (duplicates are
- * ignored; `any` is refused). Absent: every extension.
+ * @type string|string[] $extension_slug Owning extension slug, or a list of them, each 1-64 of
+ * `[a-z0-9_-]` (duplicates are ignored; `any` is refused).
+ * Absent: every extension.
* @type string|string[] $status Plan status, or a list of them. Absent: every status.
* @type int[] $ids Only these plan ids: a list of positive integers (digit
* strings are cast). A non-list or a non-positive id throws.
@@ -310,7 +316,8 @@ final class Plans {
* }
* @return array<int, PlanView>
* @throws ValidationException If a value is invalid, with every invalid value reported: an empty
- * or non-string slug or status, `any` as a slug, a non-positive or
+ * or non-string slug or status, a slug that is not a valid extension
+ * slug (1-64 of `[a-z0-9_-]`), `any` as a slug, a non-positive or
* non-integer id or limit, a negative or non-integer offset.
*/
public static function list( array $args = array() ): array {
@@ -324,7 +331,20 @@ final class Plans {
'offset' => $validator->get_non_negative_int( 'offset', $filtered_args['offset'] ?? 0 ),
);
if ( array_key_exists( 'extension_slug', $filtered_args ) ) {
- $extension_slugs = array_values( array_unique( (array) $validator->get_string_list( 'extension_slug', $filtered_args['extension_slug'] ) ) );
+ $raw_slugs = $filtered_args['extension_slug'];
+ $extension_slugs = (array) $validator->get_string_list( 'extension_slug', $raw_slugs );
+ if ( is_array( $raw_slugs ) && array_values( $raw_slugs ) === $raw_slugs ) {
+ // Each non-empty string item gets the format check even when another item failed the
+ // list check; empty and non-string items already carry that check's error.
+ foreach ( $raw_slugs as $index => $slug ) {
+ if ( is_string( $slug ) && '' !== $slug ) {
+ $validator->get_extension_slug( ArgumentValidator::get_item_field( 'extension_slug', $index ), $slug );
+ }
+ }
+ } elseif ( is_string( $raw_slugs ) && '' !== $raw_slugs ) {
+ $validator->get_extension_slug( 'extension_slug', $raw_slugs );
+ }
+ $extension_slugs = array_values( array_unique( $extension_slugs ) );
if ( in_array( 'any', $extension_slugs, true ) ) {
$validator->add(
new InvalidInputException(
@@ -362,11 +382,11 @@ final class Plans {
*
* @param string $extension_slug The expected owner.
* @param string $key Meta key.
- * @throws ValidationException If the owner or the key is empty.
+ * @throws ValidationException If the owner is not a valid extension slug or the key is empty.
*/
private static function assert_scope( string $extension_slug, string $key ): void {
$validator = new ArgumentValidator();
- $validator->get_non_empty_string( 'extension_slug', $extension_slug );
+ $validator->get_extension_slug( 'extension_slug', $extension_slug );
$validator->get_non_empty_string( 'key', $key );
try {
$validator->throw_errors();
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php
index f3454b8693b..23c727f7fc8 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php
@@ -16,6 +16,7 @@ use Automattic\WooCommerce\SubscriptionsEngine\Api\ValidationException;
use Automattic\WooCommerce\SubscriptionsEngine\Api\View\PlanView;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\Plan;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\PlanStatus;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\Coercion;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\InvalidInputException;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ValidationErrorCode;
@@ -279,7 +280,11 @@ final class PlansController extends WP_REST_Controller {
return $extension_slug;
}
- $plan = Plans::get( Coercion::coerce_int( $request->get_param( 'id' ) ) );
+ try {
+ $plan = Plans::get( Coercion::coerce_int( $request->get_param( 'id' ) ) );
+ } catch ( RuntimeException $e ) {
+ return $this->read_failed_error( $e );
+ }
if ( null === $plan || $extension_slug !== $plan->get_extension_slug() ) {
return $this->not_found_error();
}
@@ -550,6 +555,24 @@ final class PlansController extends WP_REST_Controller {
return $map;
}
+ /**
+ * Error for a failed plan read: logged, then a generic 500 so database details stay out of the response.
+ *
+ * @param RuntimeException $e Failure.
+ */
+ private function read_failed_error( RuntimeException $e ): WP_Error {
+ wc_get_logger()->error(
+ sprintf( 'PlansController: the plan read failed: %s', $e->getMessage() ),
+ array( 'source' => self::LOG_SOURCE )
+ );
+
+ return new WP_Error(
+ 'woocommerce_subscriptions_engine_plan_read_failed',
+ __( 'The plan could not be read.', 'woocommerce' ),
+ array( 'status' => 500 )
+ );
+ }
+
/**
* Map a failed write to a 500. The facade wraps a throwing validation callback
* (the cause is chained, and the facade logs it); a failed insert or update carries
@@ -800,7 +823,7 @@ final class PlansController extends WP_REST_Controller {
if ( null === $raw ) {
return $this->get_extension_slug_error( ValidationErrorCode::REQUIRED, 'extension_slug is required.' );
}
- $raw_string = trim( Coercion::coerce_string( $raw ) );
+ $raw_string = Coercion::coerce_string( $raw );
if ( '' === $raw_string ) {
return $this->get_extension_slug_error( ValidationErrorCode::REQUIRED, 'extension_slug is required.' );
}
@@ -810,11 +833,17 @@ final class PlansController extends WP_REST_Controller {
}
$slugs = array();
- foreach ( explode( ',', $raw_string ) as $possible_slug ) {
- $slug = trim( $possible_slug );
- if ( '' === $slug || 'any' === $slug || ! $this->is_valid_extension_slug( $slug ) ) {
+ // Whitespace next to a comma is list formatting (`a, b`) and is dropped; any other
+ // whitespace stays part of the slug and is refused, as at the facades.
+ foreach ( (array) preg_split( '/\s*,\s*/', $raw_string ) as $slug ) {
+ $slug = (string) $slug;
+ if ( '' === $slug || 'any' === $slug ) {
return $this->get_extension_slug_error( ValidationErrorCode::INVALID_VALUE, 'extension_slug must be "any" or a comma-separated list of extension slugs.' );
}
+ $slug_error = $this->get_extension_slug_pattern_error( $slug );
+ if ( null !== $slug_error ) {
+ return $slug_error;
+ }
$slugs[ $slug ] = $slug;
}
@@ -836,16 +865,15 @@ final class PlansController extends WP_REST_Controller {
if ( ! is_string( $raw ) ) {
return $this->get_extension_slug_error( ValidationErrorCode::INVALID_TYPE, 'extension_slug must be a string.', array( 'type' => 'string' ) );
}
- $raw_string = trim( $raw );
- if ( '' === $raw_string ) {
+ if ( '' === $raw ) {
return $this->get_extension_slug_error( ValidationErrorCode::REQUIRED, 'extension_slug is required.' );
}
- if ( 'any' === $raw_string || false !== strpos( $raw_string, ',' ) || ! $this->is_valid_extension_slug( $raw_string ) ) {
+ if ( 'any' === $raw || false !== strpos( $raw, ',' ) ) {
return $this->get_extension_slug_error( ValidationErrorCode::INVALID_VALUE, 'extension_slug must be a concrete extension slug.' );
}
- return $raw_string;
+ return $this->get_extension_slug_pattern_error( $raw ) ?? $raw;
}
/**
@@ -862,12 +890,18 @@ final class PlansController extends WP_REST_Controller {
}
/**
- * Whether a value is a valid extension slug.
+ * The validation error for a slug that is not a valid extension slug, or null for a valid one.
*
* @param string $slug Possible extension slug.
*/
- private function is_valid_extension_slug( string $slug ): bool {
- return '' !== $slug && sanitize_key( $slug ) === $slug;
+ private function get_extension_slug_pattern_error( string $slug ): ?WP_Error {
+ try {
+ ArgumentValidator::validate_extension_slug( 'extension_slug', $slug );
+ } catch ( InvalidInputException $e ) {
+ return $this->get_validation_error( ValidationException::from_core( $e ) );
+ }
+
+ return null;
}
/**
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php b/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php
index ab64bfc7d24..88339579f31 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php
@@ -122,6 +122,12 @@ final class ValidationException extends InvalidArgumentException {
return wp_sprintf( __( 'Must be one of %l.', 'woocommerce' ), array_values( array_filter( $params['allowed'], 'is_string' ) ) );
}
break;
+ case ValidationErrorCode::INVALID_PATTERN:
+ if ( isset( $params['pattern'] ) && is_string( $params['pattern'] ) ) {
+ /* translators: %s: the required format, as a regular expression. */
+ return sprintf( __( 'Must match the pattern %s.', 'woocommerce' ), $params['pattern'] );
+ }
+ break;
case ValidationErrorCode::NOT_REGISTERED:
if ( isset( $params['value'] ) && is_scalar( $params['value'] ) ) {
/* translators: %s: the status that is not registered. */
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Core/Entity/Contract.php b/packages/php/woocommerce-subscriptions-engine/src/Core/Entity/Contract.php
index 2af628e5883..e8b0975ba2c 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Core/Entity/Contract.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Core/Entity/Contract.php
@@ -25,6 +25,7 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\SubscriptionsEngine\Core\Entity;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\MoneyScale;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\Coercion;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\InvalidInputException;
@@ -932,7 +933,7 @@ final class Contract {
* @param string $schedule_source Schedule source to check.
*/
private static function get_schedule_source_error( string $schedule_source ): ?InvalidInputException {
- if ( 1 !== preg_match( '/^[a-z0-9_-]{1,64}$/D', $schedule_source ) ) {
+ if ( ! ArgumentValidator::is_slug( $schedule_source ) ) {
return new InvalidInputException(
ValidationErrorCode::INVALID_VALUE,
'schedule_source',
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php
index b20cf12b349..17d7d1f5fd7 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php
@@ -29,6 +29,13 @@ defined( 'ABSPATH' ) || exit;
*/
final class ArgumentValidator {
+ /**
+ * Format of an engine slug, in JSON-schema syntax: 1-64 lowercase letters, digits, hyphens or
+ * underscores. Extension slugs (the owner), schedule sources and lock operation labels share it;
+ * 64 is the width of their columns.
+ */
+ public const SLUG_PATTERN = '^[a-z0-9_-]{1,64}$';
+
/**
* Errors recorded by the collecting form, in recording order.
*
@@ -102,6 +109,21 @@ final class ArgumentValidator {
}
}
+ /**
+ * Collecting {@see self::validate_extension_slug()}: the slug, or null when refused.
+ *
+ * @param string $key Field name.
+ * @param mixed $value Caller value.
+ */
+ public function get_extension_slug( string $key, $value ): ?string {
+ try {
+ return self::validate_extension_slug( $key, $value );
+ } catch ( InvalidInputException $e ) {
+ $this->add( $e );
+ return null;
+ }
+ }
+
/**
* Collecting {@see self::validate_nullable_string()}: the value, or null when refused.
*
@@ -319,6 +341,33 @@ final class ArgumentValidator {
return $value;
}
+ /**
+ * Validate and return an extension slug: a non-empty string matching
+ * {@see self::SLUG_PATTERN}. No trimming or case folding: a slug that differs is
+ * refused, so one owner has one spelling.
+ *
+ * @param string $key Field name.
+ * @param mixed $value Caller value.
+ * @throws InvalidInputException If the value is missing, empty, not a string or not a valid slug.
+ */
+ public static function validate_extension_slug( string $key, $value ): string {
+ $slug = self::validate_non_empty_string( $key, $value );
+ if ( ! self::is_slug( $slug ) ) {
+ throw self::get_invalid_input( ValidationErrorCode::INVALID_PATTERN, $key, 'must be 1-64 lowercase letters, digits, hyphens or underscores', array( 'pattern' => self::SLUG_PATTERN ) );
+ }
+
+ return $slug;
+ }
+
+ /**
+ * Whether a string matches {@see self::SLUG_PATTERN}.
+ *
+ * @param string $slug Possible slug.
+ */
+ public static function is_slug( string $slug ): bool {
+ return 1 === preg_match( '/' . self::SLUG_PATTERN . '/D', $slug );
+ }
+
/**
* Validate and return a string, or null.
*
@@ -581,7 +630,7 @@ final class ArgumentValidator {
* @param string $key Field name.
* @param int|string $index Item index or map key.
*/
- private static function get_item_field( string $key, $index ): string {
+ public static function get_item_field( string $key, $index ): string {
return $key . '.' . $index;
}
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php
index f4a8a6282e3..ea7375b03b3 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php
@@ -46,6 +46,12 @@ final class ValidationErrorCode {
*/
public const INVALID_VALUE = 'invalid_value';
+ /**
+ * A string does not match its required format. Params: `pattern`, the format as a
+ * regular expression in JSON-schema syntax.
+ */
+ public const INVALID_PATTERN = 'invalid_pattern';
+
/**
* A status is not registered. Params: `value` (the refused status).
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Ownership/ConsumerRegistry.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Ownership/ConsumerRegistry.php
index 77a13162c1a..334e94d14c1 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Ownership/ConsumerRegistry.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Ownership/ConsumerRegistry.php
@@ -17,6 +17,7 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\SubscriptionsEngine\Integration\Ownership;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator;
use Automattic\WooCommerce\SubscriptionsEngine\Integration\Dispatch\DueDispatcher;
use Automattic\WooCommerce\SubscriptionsEngine\Integration\Support\ArgumentFilter;
@@ -42,9 +43,10 @@ final class ConsumerRegistry {
private static $consumers = array();
/**
- * Register a consumer extension by its (trimmed, non-empty) slug. A repeat registration, an
- * unknown key or a non-callable handler gets `_doing_it_wrong()`: the first registration is
- * kept and an invalid key is dropped. Register by `init`; a handler registered after
+ * Register a consumer extension by its slug (1-64 lowercase letters, digits, hyphens or
+ * underscores, as every engine owner slug). An invalid slug, a repeat registration, an unknown key
+ * or a non-callable handler gets `_doing_it_wrong()`: an invalid slug registers nothing, the first
+ * registration is kept and an invalid key is dropped. Register by `init`; a handler registered after
* `wp_loaded` schedules the recurring due scan right away.
*
* @param string $slug The consumer extension's registered slug.
@@ -62,8 +64,8 @@ final class ConsumerRegistry {
* the due moment stops that.
*/
public static function register( string $slug, array $config = array() ): void {
- $slug = trim( $slug );
- if ( '' === $slug ) {
+ if ( ! ArgumentValidator::is_slug( $slug ) ) {
+ self::reject( sprintf( 'Consumer slug "%s" must be 1-64 lowercase letters, digits, hyphens or underscores; nothing is registered.', $slug ) );
return;
}
@@ -99,7 +101,6 @@ final class ConsumerRegistry {
* @param string $slug The consumer extension's registered slug.
*/
public static function unregister( string $slug ): void {
- $slug = trim( $slug );
$had_handler = isset( self::$consumers[ $slug ]['contract_due_handler'] );
unset( self::$consumers[ $slug ] );
@@ -114,7 +115,7 @@ final class ConsumerRegistry {
* @param string $slug The consumer extension's registered slug.
*/
public static function get_contract_due_handler( string $slug ): ?callable {
- return self::$consumers[ trim( $slug ) ]['contract_due_handler'] ?? null;
+ return self::$consumers[ $slug ]['contract_due_handler'] ?? null;
}
/**
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
index f1f17dfb7c6..ef69b00a6a1 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
@@ -31,6 +31,7 @@ use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\Contract;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\ContractStatus;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\Cycle;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\CycleStatus;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\Coercion;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\InvalidInputException;
use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ValidationErrorCode;
@@ -41,6 +42,10 @@ defined( 'ABSPATH' ) || exit;
/**
* Live contract repository with targeted cycle access.
+ *
+ * @internal Storage behind the `Api\` facades, not a supported extension surface. Arguments are
+ * validated once, at the public boundary: owner slugs and other values arrive validated
+ * and are not checked again here.
*/
final class ContractRepository {
@@ -76,10 +81,10 @@ final class ContractRepository {
private const HOLDS_LOCK = 'lock_token = %s AND locked_until_gmt > UTC_TIMESTAMP()';
/**
- * SQL condition: the row's owner is exactly the bound slug. The binary cast makes the match
- * case-sensitive, as the engine's PHP comparisons of the owner are.
+ * SQL condition: the row's owner is exactly the bound slug. The column's binary collation makes
+ * the match case-sensitive, as the engine's PHP comparisons of the owner are.
*/
- private const OWNER_MATCH = 'extension_slug = CAST(%s AS BINARY)';
+ private const OWNER_MATCH = 'extension_slug = %s';
/**
* Contract columns a lock may be conditioned on ({@see self::acquire_lock()}), mapped to the
@@ -1143,7 +1148,7 @@ final class ContractRepository {
* @throws \InvalidArgumentException If the label is not a valid slug.
*/
private static function assert_operation( string $operation ): void {
- if ( 1 !== preg_match( '/^[a-z0-9_-]{1,64}$/D', $operation ) ) {
+ if ( ! ArgumentValidator::is_slug( $operation ) ) {
throw new \InvalidArgumentException( 'A lock operation label must be 1-64 lowercase letters, digits, underscores or hyphens.' );
}
}
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php
index 4532b50d478..b75e98f1db7 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php
@@ -17,14 +17,18 @@ defined( 'ABSPATH' ) || exit;
/**
* Plan repository.
+ *
+ * @internal Storage behind the `Api\` facades, not a supported extension surface. Arguments are
+ * validated once, at the public boundary: owner slugs and other values arrive validated
+ * and are not checked again here.
*/
final class PlanRepository {
/**
- * SQL condition on the `p` alias: the plan's owner is exactly the bound slug. The binary cast
- * makes the match case-sensitive, as the engine's PHP comparisons of the owner are.
+ * SQL condition on the `p` alias: the plan's owner is exactly the bound slug. The column's
+ * binary collation makes the match case-sensitive, as the engine's PHP comparisons of the owner are.
*/
- private const OWNER_MATCH = 'p.extension_slug = CAST(%s AS BINARY)';
+ private const OWNER_MATCH = 'p.extension_slug = %s';
/**
* Policy columns stored as JSON.
@@ -92,6 +96,7 @@ final class PlanRepository {
* @param int $id Plan id.
* @param string|null $extension_slug Owning extension slug to scope the read to; null reads any extension.
* @return Plan|null Hydrated plan, or null if not found (also when it belongs to another extension).
+ * @throws \RuntimeException If the read fails: a failed read must not look like a missing plan.
*/
public function find( int $id, ?string $extension_slug = null ): ?Plan {
global $wpdb;
@@ -109,6 +114,9 @@ final class PlanRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
$row = $wpdb->get_row( $sql, ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( sprintf( 'Failed to read plan %d: %s', (int) $id, esc_html( $wpdb->last_error ) ) );
+ }
if ( null === $row ) {
return null;
@@ -224,40 +232,30 @@ final class PlanRepository {
throw new \RuntimeException( 'Cannot update a plan that has no extension slug.' );
}
- $table = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_PLANS );
$row = $this->get_row_data( $plan );
$columns = array();
foreach ( $fields as $field ) {
if ( 'extension_slug' === $field || ! array_key_exists( $field, $row ) ) {
throw new \InvalidArgumentException( esc_html( sprintf( 'Cannot update plan field "%s".', $field ) ) );
}
- if ( is_string( $row[ $field ] ) ) {
- ColumnFit::assert_fits_column( $table, $field, $row[ $field ] );
- }
$columns[ $field ] = $row[ $field ];
}
- $now = gmdate( 'Y-m-d H:i:s' );
+ $now = gmdate( 'Y-m-d H:i:s' );
+ $columns['date_updated_gmt'] = $now;
- $set = array();
- $values = array();
- foreach ( array_merge( $columns, array( 'date_updated_gmt' => $now ) ) as $column => $value ) {
- if ( null === $value ) {
- $set[] = "`{$column}` = NULL";
- } else {
- $set[] = "`{$column}` = %s";
- $values[] = $value;
- }
- }
- $values[] = $id;
- $values[] = $extension_slug;
-
- $sql = "UPDATE {$table} p SET " . implode( ', ', $set ) . ' WHERE p.id = %d AND ' . self::OWNER_MATCH;
-
- // Not `$wpdb->update()`: its WHERE cannot express the binary owner match. Column names come
- // from the plan's own row data; every value is a placeholder.
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
- $updated = $wpdb->query( $wpdb->prepare( $sql, $values ) );
+ // A value that does not fit its column makes `$wpdb->update()` return false, so nothing is written.
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
+ $updated = $wpdb->update(
+ SchemaInstaller::get_table_name( SchemaInstaller::TABLE_PLANS ),
+ $columns,
+ array(
+ 'id' => $id,
+ 'extension_slug' => $extension_slug,
+ ),
+ null,
+ array( '%d', '%s' )
+ );
if ( false === $updated ) {
throw new \RuntimeException( sprintf( 'Failed to update plan %d: %s', (int) $id, esc_html( $wpdb->last_error ) ) );
@@ -304,14 +302,13 @@ final class PlanRepository {
}
/**
- * Delete a plan and its meta rows by id and (optionally) extension slug.
- * Most usages from applications should specify the extension slug
- * to guard against cross-application operations.
+ * Delete a plan and its meta rows by id. With `$extension_slug` the delete is scoped to that
+ * owner: a plan of another extension is not deleted. Callers pass a validated slug.
*
* A failed delete throws, so a caller's transaction can roll back.
*
* @param int $id Plan id.
- * @param string|null $extension_slug Extension slug for the plan.
+ * @param string|null $extension_slug Owner to scope the delete to, or null for any owner.
* @return bool True when a row was removed.
* @throws \RuntimeException If the plan row or its meta rows fail to delete.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php
index 06e2bf23a4b..30a9ce3325d 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php
@@ -62,13 +62,16 @@ final class SchemaInstaller {
* a `write_seq` counter bumped by every row write, and a binary-collated
* `creation_key` with a `creation (extension_slug, creation_key)` UNIQUE index;
* contracts and cycles drop `claimed_until`. Pre-freeze, recreate the tables.
+ * 2.9.0 - owner columns compare binary: `extension_slug` on plans, contracts and cycles uses
+ * the table charset's `_bin` collation, so every owner match and the `creation`
+ * UNIQUE index are exact for case and accents. Pre-freeze, recreate the tables.
*
* Pre-freeze, tables are recreated rather than migrated. dbDelta adds columns but
* does not change an existing column's nullability or drop unused ones, so a dev box
* on an earlier schema must drop and recreate the tables (and clear VERSION_OPTION)
* to pick up such changes - in-place ALTERs and backfills arrive with the freeze.
*/
- private const VERSION = '2.8.0';
+ private const VERSION = '2.9.0';
/**
* Option key tracking the installed schema version.
@@ -223,6 +226,13 @@ final class SchemaInstaller {
// Mirrors the HPOS orders meta table indexes, including its meta_value prefix length.
$meta_value_index_length = max( min( absint( apply_filters( 'woocommerce_database_max_index_length', 191 ) ), 767 ) - 8 - 100 - 1, 20 );
+ // Owner columns and the creation key compare binary: values differing only in case or
+ // accents are distinct, as in the engine's PHP comparisons. For owners this backs up the
+ // facades, which refuse any slug outside `[a-z0-9_-]{1,64}`. The collation ignores trailing
+ // spaces, so they are refused at the boundary: in owner slugs by the facades, and creation
+ // keys are trimmed by the entity.
+ $binary_collate = '' === $charset ? '' : " COLLATE {$charset}_bin";
+
// The three policies are opaque JSON payloads of the owning extension; the engine
// checks their shape only. `extension_slug` is the owner (nullable while owner
// registration semantics are still open). `extension_status` keys owner-scoped
@@ -234,7 +244,7 @@ final class SchemaInstaller {
delivery_policy JSON NULL,
pricing_policy JSON NULL,
status VARCHAR(20) NOT NULL DEFAULT 'active',
- extension_slug VARCHAR(64) NULL,
+ extension_slug VARCHAR(64){$binary_collate} NULL,
date_created_gmt DATETIME NOT NULL,
date_updated_gmt DATETIME NOT NULL,
PRIMARY KEY (id),
@@ -267,17 +277,16 @@ final class SchemaInstaller {
// write, so a write that matches the row always changes it (zero rows = not matched).
// `creation` makes an extension's optional `creation_key` unique (NULL keys never
// collide); 64 + 100 characters stay within the 767-byte key limit of older InnoDB
- // row formats. The key is opaque, so it compares binary: keys differing only in case
- // or accents are distinct. The collation ignores trailing spaces, so the entity trims keys.
- $creation_key_collate = '' === $charset ? '' : " COLLATE {$charset}_bin";
- $contracts_sql = "CREATE TABLE {$contracts} (
+ // row formats. The key is opaque, so it compares binary, as the owner does; the entity
+ // trims keys because the collation ignores trailing spaces.
+ $contracts_sql = "CREATE TABLE {$contracts} (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
status VARCHAR(20) NOT NULL,
customer_id BIGINT UNSIGNED NULL,
currency CHAR(3) NULL,
selling_plan_id BIGINT UNSIGNED NULL,
origin_order_id BIGINT UNSIGNED NULL,
- extension_slug VARCHAR(64) NULL,
+ extension_slug VARCHAR(64){$binary_collate} NULL,
payment_method VARCHAR(100) NULL,
payment_method_title VARCHAR(200) NULL,
payment_token_id BIGINT UNSIGNED NULL,
@@ -287,7 +296,7 @@ final class SchemaInstaller {
locked_until_gmt DATETIME NULL,
lock_operation VARCHAR(64) NULL,
write_seq BIGINT UNSIGNED NOT NULL DEFAULT 0,
- creation_key VARCHAR(100){$creation_key_collate} NULL,
+ creation_key VARCHAR(100){$binary_collate} NULL,
plan_snapshot_id BIGINT UNSIGNED NULL,
items_snapshot_id BIGINT UNSIGNED NULL,
billing_total DECIMAL(26,8) NOT NULL DEFAULT 0,
@@ -376,7 +385,7 @@ final class SchemaInstaller {
plan_snapshot_id BIGINT UNSIGNED NULL,
items_snapshot_id BIGINT UNSIGNED NULL,
order_id BIGINT UNSIGNED NULL,
- extension_slug VARCHAR(64) NULL,
+ extension_slug VARCHAR(64){$binary_collate} NULL,
retry_at DATETIME NULL,
date_created_gmt DATETIME NOT NULL,
date_updated_gmt DATETIME NOT NULL,
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractActionsTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractActionsTest.php
index 6dd3c5a4aa5..7f6275b7537 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractActionsTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractActionsTest.php
@@ -135,6 +135,12 @@ class ContractActionsTest extends EngineIntegrationTestCase {
public function invalid_registrations(): array {
return array(
'empty extension slug' => array( ' ', 'pause', array() ),
+ 'slug trailing space' => array( 'lite ', 'pause', array() ),
+ 'slug with capitals' => array( 'LITE', 'pause', array() ),
+ 'slug inner space' => array( 'li te', 'pause', array() ),
+ 'slug with an accent' => array( 'lité', 'pause', array() ),
+ 'slug empty' => array( '', 'pause', array() ),
+ 'slug 65 characters' => array( str_repeat( 'a', 65 ), 'pause', array() ),
'action with capitals' => array( self::EXTENSION_SLUG, 'Pause', array() ),
'action with a slash' => array( self::EXTENSION_SLUG, 'pause/now', array() ),
'action with a newline' => array( self::EXTENSION_SLUG, "pause\n", array() ),
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
index 98a8652f353..6cc3f64457c 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
@@ -1225,28 +1225,43 @@ class ContractsTest extends EngineIntegrationTestCase {
}
/**
- * @testdox The owner matches exactly: a slug differing only in case reads as another extension.
+ * @testdox A case variant of the owner slug is refused at the boundary and changes nothing.
*/
- public function test_the_owner_match_is_case_sensitive(): void {
+ public function test_a_case_variant_owner_slug_is_refused(): void {
$id = $this->contract_with_currency();
$upper = strtoupper( self::EXTENSION_SLUG );
+ Contracts::add_meta( $id, self::EXTENSION_SLUG, 'k', 'v' );
+ $before = Contracts::get( $id );
+ $this->assertNotNull( $before );
- $this->assertNull( Contracts::lock( $id, $upper, 'hold' ) );
- $this->assertNull(
- Contracts::update(
- $id,
- array(
- 'extension_slug' => $upper,
- 'billing_total' => '9',
- )
- )
+ $calls = array(
+ 'lock' => static function () use ( $id, $upper ): void {
+ Contracts::lock( $id, $upper, 'hold' );
+ },
+ 'update' => static function () use ( $id, $upper ): void {
+ Contracts::update(
+ $id,
+ array(
+ 'extension_slug' => $upper,
+ 'billing_total' => '9',
+ )
+ );
+ },
+ 'add_meta' => static function () use ( $id, $upper ): void {
+ Contracts::add_meta( $id, $upper, 'k', 'theirs' );
+ },
+ 'delete_meta' => static function () use ( $id, $upper ): void {
+ Contracts::delete_meta( $id, $upper, 'k' );
+ },
);
- $this->assertNull( Contracts::update( $id, array( 'extension_slug' => $upper ) ), 'The fieldless path agrees.' );
- Contracts::add_meta( $id, self::EXTENSION_SLUG, 'k', 'v' );
- $this->assertFalse( Contracts::delete_meta( $id, $upper, 'k' ) );
+ foreach ( $calls as $call ) {
+ $this->assert_validation_errors( $call, array( array( ValidationErrorCode::INVALID_PATTERN, 'extension_slug' ) ) );
+ }
+
+ $after = Contracts::get( $id );
+ $this->assertNotNull( $after );
+ $this->assertSame( $before->get_billing_total(), $after->get_billing_total() );
$this->assertSame( 'v', Contracts::get_meta( $id, 'k', true ), 'The case variant deletes nothing.' );
- $this->expectException( InvalidArgumentException::class );
- Contracts::add_meta( $id, $upper, 'k', 'v' );
}
/**
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/OwnerSlugValidationTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/OwnerSlugValidationTest.php
new file mode 100644
index 00000000000..8ddab4df568
--- /dev/null
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/OwnerSlugValidationTest.php
@@ -0,0 +1,406 @@
+<?php
+/**
+ * Integration tests for the owner slug format check at every facade entry point.
+ *
+ * @package Automattic\WooCommerce\SubscriptionsEngine
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\SubscriptionsEngine\Tests\Integration\Api;
+
+use EngineIntegrationTestCase;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\ContractLock;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\Contracts;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\Plans;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\ValidationException;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\View\ContractView;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\View\CycleView;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\View\PlanView;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\CycleStatus;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ValidationErrorCode;
+
+/**
+ * An `extension_slug` outside `[a-z0-9_-]{1,64}` is refused before any engine table is read or
+ * written, at every facade that takes an owner.
+ *
+ * @covers \Automattic\WooCommerce\SubscriptionsEngine\Api\Contracts
+ * @covers \Automattic\WooCommerce\SubscriptionsEngine\Api\Plans
+ * @covers \Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator
+ */
+class OwnerSlugValidationTest extends EngineIntegrationTestCase {
+
+ /**
+ * A valid owner slug.
+ */
+ private const OWNER = 'acme-subs';
+
+ /**
+ * Customer of the contract.
+ */
+ private const CUSTOMER_ID = 41;
+
+ /**
+ * Id of a contract of {@see self::OWNER}.
+ *
+ * @var int
+ */
+ private $contract_id;
+
+ /**
+ * Id of a plan of {@see self::OWNER}.
+ *
+ * @var int
+ */
+ private $plan_id;
+
+ /**
+ * Id of a pending cycle of the contract.
+ *
+ * @var int
+ */
+ private $cycle_id;
+
+ /**
+ * The lock taken when the contract was created, still held.
+ *
+ * @var ContractLock
+ */
+ private $lock;
+
+ /**
+ * Create a contract (kept locked) and a plan of the valid owner.
+ */
+ public function setUp(): void {
+ parent::setUp();
+
+ $created = Contracts::create(
+ array(
+ 'extension_slug' => self::OWNER,
+ 'customer_id' => self::CUSTOMER_ID,
+ )
+ );
+ $this->assertIsArray( $created );
+ $this->contract_id = (int) $created['contract']->get_id();
+ $this->lock = $created['lock'];
+
+ $cycle = Contracts::add_cycle( $this->contract_id, $this->cycle_args( self::OWNER ), $this->lock );
+ $this->assertNotNull( $cycle );
+ $this->cycle_id = (int) $cycle->get_id();
+
+ $this->plan_id = $this->make_plan( array( 'extension_slug' => self::OWNER ) );
+ }
+
+ /**
+ * Release the contract lock.
+ */
+ public function tearDown(): void {
+ $this->lock->release();
+
+ parent::tearDown();
+ }
+
+ /**
+ * @testdox $entry refuses an invalid owner slug with invalid_pattern before any engine query.
+ * @dataProvider provide_entry_points
+ *
+ * @param string $entry Entry point name.
+ */
+ public function test_an_invalid_owner_slug_is_refused_before_any_query( string $entry ): void {
+ foreach ( array( 'lite ', ' lite', 'LITE', 'li te', 'lité', str_repeat( 'a', 65 ) ) as $slug ) {
+ $queries = $this->count_engine_queries(
+ function () use ( $entry, $slug ): void {
+ $this->assert_refused_with_pattern_error( $entry, $slug );
+ }
+ );
+
+ $this->assertSame( 0, $queries, sprintf( '%s with "%s" ran an engine query.', $entry, $slug ) );
+ }
+ }
+
+ /**
+ * @testdox $entry accepts a valid owner slug and does its work.
+ * @dataProvider provide_entry_points
+ *
+ * @param string $entry Entry point name.
+ */
+ public function test_a_valid_owner_slug_is_accepted( string $entry ): void {
+ if ( 'Contracts::lock' === $entry ) {
+ $this->lock->release();
+ }
+ if ( 'Contracts::delete_meta' === $entry ) {
+ Contracts::add_meta( $this->contract_id, self::OWNER, 'note', 'x', false, $this->lock );
+ }
+ if ( 'Plans::delete_meta' === $entry ) {
+ Plans::add_meta( $this->plan_id, self::OWNER, 'note', 'x' );
+ }
+
+ $result = $this->call( $entry, self::OWNER );
+
+ switch ( $entry ) {
+ case 'Contracts::lock':
+ $this->assertInstanceOf( ContractLock::class, $result );
+ $this->lock = $result;
+ return;
+ case 'Contracts::create':
+ $this->assertIsArray( $result );
+ $this->assertInstanceOf( ContractView::class, $result['contract'] );
+ $this->assertInstanceOf( ContractLock::class, $result['lock'] );
+ $this->assertSame( self::OWNER, $result['contract']->get_extension_slug() );
+ $result['lock']->release();
+ return;
+ case 'Contracts::update':
+ $this->assertInstanceOf( ContractView::class, $result );
+ $this->assertSame( 'EUR', $result->get_currency() );
+ return;
+ case 'Contracts::add_cycle':
+ $this->assertInstanceOf( CycleView::class, $result );
+ return;
+ case 'Contracts::add_meta':
+ $this->assertIsInt( $result );
+ $this->assertSame( 'x', Contracts::get_meta( $this->contract_id, 'note', true ) );
+ return;
+ case 'Contracts::list_for_customer':
+ $this->assertSame( array( $this->contract_id ), self::get_ids( $result ) );
+ return;
+ case 'Plans::create':
+ $this->assertInstanceOf( PlanView::class, $result );
+ $this->assertSame( self::OWNER, $result->get_extension_slug() );
+ return;
+ case 'Plans::update':
+ $this->assertInstanceOf( PlanView::class, $result );
+ $this->assertSame( 'Renamed', $result->get_name() );
+ return;
+ case 'Plans::add_meta':
+ $this->assertIsInt( $result );
+ $this->assertSame( 'x', Plans::get_meta( $this->plan_id, 'note', true ) );
+ return;
+ case 'Plans::list':
+ $this->assertSame( array( $this->plan_id ), self::get_ids( $result ) );
+ return;
+ }
+
+ // transition_cycle, update_meta and delete_meta report a write with true.
+ $this->assertTrue( $result );
+ }
+
+ /**
+ * @return array<string, array{0: string}>
+ */
+ public function provide_entry_points(): array {
+ $entries = array(
+ 'Contracts::lock',
+ 'Contracts::create',
+ 'Contracts::update',
+ 'Contracts::add_cycle',
+ 'Contracts::transition_cycle',
+ 'Contracts::add_meta',
+ 'Contracts::update_meta',
+ 'Contracts::delete_meta',
+ 'Contracts::list_for_customer',
+ 'Plans::create',
+ 'Plans::update',
+ 'Plans::add_meta',
+ 'Plans::update_meta',
+ 'Plans::delete_meta',
+ 'Plans::list',
+ );
+
+ return array_combine(
+ $entries,
+ array_map(
+ static function ( string $entry ): array {
+ return array( $entry );
+ },
+ $entries
+ )
+ );
+ }
+
+ /**
+ * @testdox Plans::list reports an invalid slug in a list by its index.
+ */
+ public function test_plans_list_reports_an_invalid_list_item_by_index(): void {
+ try {
+ Plans::list( array( 'extension_slug' => array( self::OWNER, 'LITE' ) ) );
+ $this->fail( 'Expected a ValidationException.' );
+ } catch ( ValidationException $e ) {
+ $this->assertSame( array( 'extension_slug.1' ), $this->get_pattern_error_fields( $e ) );
+ }
+ }
+
+ /**
+ * @testdox Plans::list reports a malformed slug item even when another item has the wrong type.
+ */
+ public function test_plans_list_reports_every_bad_list_item(): void {
+ try {
+ Plans::list( array( 'extension_slug' => array( 'LITE', 5 ) ) );
+ $this->fail( 'Expected a ValidationException.' );
+ } catch ( ValidationException $e ) {
+ $this->assertSame( array( 'extension_slug.0' ), $this->get_pattern_error_fields( $e ) );
+ $type_fields = array();
+ foreach ( $e->get_errors()->get_all_error_data( ValidationErrorCode::INVALID_TYPE ) as $data ) {
+ $type_fields[] = is_array( $data ) ? ( $data['field'] ?? null ) : null;
+ }
+ $this->assertSame( array( 'extension_slug.1' ), $type_fields );
+ }
+ }
+
+ /**
+ * Call an entry point with `$slug` as the owner and otherwise valid arguments.
+ *
+ * @param string $entry Entry point name.
+ * @param string $slug Owner slug.
+ * @return mixed The entry point's return value.
+ */
+ private function call( string $entry, string $slug ) {
+ switch ( $entry ) {
+ case 'Contracts::lock':
+ return Contracts::lock( $this->contract_id, $slug, 'test' );
+ case 'Contracts::create':
+ return Contracts::create( array( 'extension_slug' => $slug ) );
+ case 'Contracts::update':
+ return Contracts::update(
+ $this->contract_id,
+ array(
+ 'extension_slug' => $slug,
+ 'currency' => 'EUR',
+ ),
+ $this->lock
+ );
+ case 'Contracts::add_cycle':
+ return Contracts::add_cycle( $this->contract_id, $this->cycle_args( $slug ), $this->lock );
+ case 'Contracts::transition_cycle':
+ return Contracts::transition_cycle(
+ $this->cycle_id,
+ array(
+ 'extension_slug' => $slug,
+ 'from_status' => CycleStatus::PENDING,
+ 'to_status' => CycleStatus::BILLED,
+ ),
+ $this->lock
+ );
+ case 'Contracts::add_meta':
+ return Contracts::add_meta( $this->contract_id, $slug, 'note', 'x', false, $this->lock );
+ case 'Contracts::update_meta':
+ return Contracts::update_meta( $this->contract_id, $slug, 'note', 'x', null, $this->lock );
+ case 'Contracts::delete_meta':
+ return Contracts::delete_meta( $this->contract_id, $slug, 'note', null, $this->lock );
+ case 'Contracts::list_for_customer':
+ return Contracts::list_for_customer( self::CUSTOMER_ID, 20, 0, array( 'extension_slug' => $slug ) );
+ case 'Plans::create':
+ return Plans::create(
+ array(
+ 'extension_slug' => $slug,
+ 'name' => 'Monthly',
+ )
+ );
+ case 'Plans::update':
+ return Plans::update(
+ $this->plan_id,
+ array(
+ 'extension_slug' => $slug,
+ 'name' => 'Renamed',
+ )
+ );
+ case 'Plans::add_meta':
+ return Plans::add_meta( $this->plan_id, $slug, 'note', 'x' );
+ case 'Plans::update_meta':
+ return Plans::update_meta( $this->plan_id, $slug, 'note', 'x' );
+ case 'Plans::delete_meta':
+ return Plans::delete_meta( $this->plan_id, $slug, 'note' );
+ case 'Plans::list':
+ return Plans::list( array( 'extension_slug' => $slug ) );
+ }
+
+ $this->fail( sprintf( 'Unknown entry point %s.', $entry ) );
+ }
+
+ /**
+ * Valid pending-cycle args owned by `$slug`.
+ *
+ * @param string $slug Owner slug.
+ * @return array<string, mixed>
+ */
+ private function cycle_args( string $slug ): array {
+ return array(
+ 'extension_slug' => $slug,
+ 'status' => CycleStatus::PENDING,
+ 'starts_at_gmt' => '2026-01-01 00:00:00',
+ 'ends_at_gmt' => '2026-02-01 00:00:00',
+ 'currency' => 'USD',
+ );
+ }
+
+ /**
+ * Assert the entry point refuses `$slug` with an `invalid_pattern` error on `extension_slug`.
+ *
+ * @param string $entry Entry point name.
+ * @param string $slug Owner slug.
+ */
+ private function assert_refused_with_pattern_error( string $entry, string $slug ): void {
+ try {
+ $this->call( $entry, $slug );
+ } catch ( ValidationException $e ) {
+ $this->assertSame( array( 'extension_slug' ), $this->get_pattern_error_fields( $e ), sprintf( '%s with "%s".', $entry, $slug ) );
+ return;
+ }
+
+ $this->fail( sprintf( '%s accepted "%s".', $entry, $slug ) );
+ }
+
+ /**
+ * Ids of a list of views.
+ *
+ * @param mixed $views Contract or plan views.
+ * @return array<int, int|null>
+ */
+ private static function get_ids( $views ): array {
+ self::assertIsArray( $views );
+
+ return array_map(
+ static function ( $view ): ?int {
+ return $view instanceof ContractView || $view instanceof PlanView ? $view->get_id() : null;
+ },
+ $views
+ );
+ }
+
+ /**
+ * Fields of the `invalid_pattern` errors a validation exception carries.
+ *
+ * @param ValidationException $e Exception.
+ * @return array<int, mixed>
+ */
+ private function get_pattern_error_fields( ValidationException $e ): array {
+ $fields = array();
+ foreach ( $e->get_errors()->get_all_error_data( ValidationErrorCode::INVALID_PATTERN ) as $data ) {
+ $fields[] = is_array( $data ) ? ( $data['field'] ?? null ) : null;
+ }
+
+ return $fields;
+ }
+
+ /**
+ * Run `$run` and count the statements it sends to engine tables.
+ *
+ * @param callable $run Code to run.
+ */
+ private function count_engine_queries( callable $run ): int {
+ $count = 0;
+ $watch = static function ( $query ) use ( &$count ) {
+ if ( is_string( $query ) && 1 === preg_match( '/wc_subscription_|wc_selling_plan/', $query ) ) {
+ ++$count;
+ }
+ return $query;
+ };
+ add_filter( 'query', $watch );
+ try {
+ $run();
+ } finally {
+ remove_filter( 'query', $watch );
+ }
+
+ return $count;
+ }
+}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php
index 690d0f3271c..cb325af9603 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php
@@ -547,15 +547,17 @@ class PlansTest extends EngineIntegrationTestCase {
)
);
$this->assertNull( Plans::update( $id, array( 'extension_slug' => 'other-extension' ) ), 'A fieldless update is scoped too.' );
- $this->assertNull(
- Plans::update(
- $id,
- array(
- 'extension_slug' => strtoupper( self::OWNER ),
- 'name' => 'Hijacked',
- )
- ),
- 'The owner matches exactly: a case variant is another extension.'
+ $this->assert_validation_errors(
+ function () use ( $id ): void {
+ Plans::update(
+ $id,
+ array(
+ 'extension_slug' => strtoupper( self::OWNER ),
+ 'name' => 'Hijacked',
+ )
+ );
+ },
+ array( array( ValidationErrorCode::INVALID_PATTERN, 'extension_slug' ) )
);
$this->assertSame( 0, $validated, 'The validate action never sees a plan of another extension.' );
@@ -1172,6 +1174,37 @@ class PlansTest extends EngineIntegrationTestCase {
$this->assertNull( Plans::get( 0 ) );
}
+ /**
+ * @testdox update and get throw on a failed plan read instead of reporting the plan missing.
+ */
+ public function test_update_and_get_throw_on_a_failed_plan_read(): void {
+ $id = $this->create();
+
+ $this->fail_next_query( '/^\s*SELECT p\.\* FROM \S*selling_plans p /' );
+ try {
+ Plans::update(
+ $id,
+ array(
+ 'extension_slug' => self::OWNER,
+ 'name' => 'Renamed',
+ )
+ );
+ $this->fail( 'Expected update() to throw.' );
+ } catch ( RuntimeException $e ) {
+ $this->assertStringContainsString( "Failed to read plan {$id}", $e->getMessage() );
+ }
+
+ $this->fail_next_query( '/^\s*SELECT \* FROM \S*selling_plans WHERE id/' );
+ try {
+ Plans::get( $id );
+ $this->fail( 'Expected get() to throw.' );
+ } catch ( RuntimeException $e ) {
+ $this->assertStringContainsString( "Failed to read plan {$id}", $e->getMessage() );
+ }
+
+ $this->assertSame( 'Monthly', $this->stored( $id )->get_name() );
+ }
+
/**
* @testdox list without args returns every extension's plans in every status, oldest id first.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php
index 1ff3ac39196..d108d881fc6 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php
@@ -1296,11 +1296,14 @@ class PlansControllerTest extends EngineIntegrationTestCase {
foreach ( array( 'any,' . self::EXTENSION_SLUG, self::EXTENSION_SLUG . ',', ',' . self::EXTENSION_SLUG, 'lite,,test' ) as $extension_slug ) {
$list = $this->request( 'GET', self::BASE, array(), array( 'extension_slug' => $extension_slug ) );
- $this->assert_invalid_param( $list, 'extension_slug', 'invalid_value' );
+ $this->assert_invalid_param( $list, 'extension_slug', 'invalid_value', sprintf( 'extension_slug "%s"', $extension_slug ) );
}
+ $empty = $this->request( 'GET', self::BASE, array(), array( 'extension_slug' => '' ) );
+ $this->assert_invalid_param( $empty, 'extension_slug', 'required' );
+
$blank = $this->request( 'GET', self::BASE, array(), array( 'extension_slug' => ' ' ) );
- $this->assert_invalid_param( $blank, 'extension_slug', 'required' );
+ $this->assert_invalid_param( $blank, 'extension_slug', 'invalid_pattern', 'Whitespace is refused, not trimmed away.' );
}
public function test_list_with_any_extension_slug_returns_all_plans(): void {
@@ -1455,6 +1458,64 @@ class PlansControllerTest extends EngineIntegrationTestCase {
}
}
+ public function test_extension_slugs_outside_the_slug_format_are_refused_with_invalid_pattern(): void {
+ wp_set_current_user( $this->admin_id );
+
+ $id = $this->create_plan( 'Scoped' );
+
+ foreach ( array( 'LITE', 'li te', ' ' . self::EXTENSION_SLUG . ' ', str_repeat( 'a', 65 ) ) as $extension_slug ) {
+ $this->assert_invalid_param( $this->request( 'GET', self::BASE . '/' . $id, array(), array( 'extension_slug' => $extension_slug ) ), 'extension_slug', 'invalid_pattern', sprintf( 'GET item, "%s"', $extension_slug ) );
+ $this->assert_invalid_param( $this->request( 'GET', self::BASE, array(), array( 'extension_slug' => $extension_slug ) ), 'extension_slug', 'invalid_pattern', sprintf( 'GET list, "%s"', $extension_slug ) );
+ // Inside a comma list, spaces next to a comma are list formatting, so only unpadded slugs are refused there.
+ if ( trim( $extension_slug ) === $extension_slug ) {
+ $this->assert_invalid_param( $this->request( 'GET', self::BASE, array(), array( 'extension_slug' => self::EXTENSION_SLUG . ',' . $extension_slug . ',woocommerce-subscriptions-test' ) ), 'extension_slug', 'invalid_pattern', sprintf( 'GET list item, "%s"', $extension_slug ) );
+ }
+ $this->assert_invalid_param(
+ $this->request(
+ 'POST',
+ self::BASE,
+ array(
+ 'extension_slug' => $extension_slug,
+ 'name' => 'Invalid owner',
+ )
+ ),
+ 'extension_slug',
+ 'invalid_pattern',
+ sprintf( 'POST, "%s"', $extension_slug )
+ );
+ $this->assert_invalid_param(
+ $this->request(
+ 'PATCH',
+ self::BASE . '/' . $id,
+ array(
+ 'extension_slug' => $extension_slug,
+ 'name' => 'Invalid owner',
+ )
+ ),
+ 'extension_slug',
+ 'invalid_pattern',
+ sprintf( 'PATCH, "%s"', $extension_slug )
+ );
+ }
+
+ $stored = Plans::get( $id );
+ $this->assertNotNull( $stored );
+ $this->assertSame( 'Scoped', $stored->get_name(), 'A refused PATCH writes nothing.' );
+ }
+
+ public function test_get_item_answers_a_failed_plan_read_with_a_500(): void {
+ wp_set_current_user( $this->admin_id );
+
+ $id = $this->create_plan( 'Stored' );
+ $this->fail_next_query( '/^\s*SELECT \* FROM \S*selling_plans WHERE id/' );
+
+ $response = $this->request( 'GET', self::BASE . '/' . $id, array(), array( 'extension_slug' => self::EXTENSION_SLUG ) );
+
+ $this->assertSame( 500, $response->get_status() );
+ $this->assertSame( 'woocommerce_subscriptions_engine_plan_read_failed', $this->response_data( $response )['code'] );
+ $this->assertStringNotContainsString( 'table_that_does_not_exist', (string) wp_json_encode( $response->get_data() ), 'Database details stay out of the response.' );
+ }
+
public function test_single_plan_routes_404_a_plan_of_another_extension_slug_or_an_unknown_id(): void {
wp_set_current_user( $this->admin_id );
@@ -1656,15 +1717,16 @@ class PlansControllerTest extends EngineIntegrationTestCase {
* @param WP_REST_Response $response Response.
* @param string $arg Top-level arg.
* @param string $code Expected detail error code.
+ * @param string $message Failure message naming the case.
* @return array<array-key, mixed> The response data.
*/
- private function assert_invalid_param( WP_REST_Response $response, string $arg, string $code ): array {
- $this->assertSame( 400, $response->get_status() );
+ private function assert_invalid_param( WP_REST_Response $response, string $arg, string $code, string $message = '' ): array {
+ $this->assertSame( 400, $response->get_status(), $message );
$data = $this->response_data( $response );
$this->assertSame( 'rest_invalid_param', $data['code'] );
$this->assertIsString( $this->nested( $data, array( 'data', 'params', $arg ) ) );
$this->assertNotSame( '', $this->nested( $data, array( 'data', 'params', $arg ) ) );
- $this->assertSame( $code, $this->nested( $data, array( 'data', 'details', $arg, 'code' ) ) );
+ $this->assertSame( $code, $this->nested( $data, array( 'data', 'details', $arg, 'code' ) ), $message );
return $data;
}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php
index ccbd4be3206..e7b70ebf0d5 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php
@@ -25,12 +25,13 @@ class ValidationExceptionTest extends EngineIntegrationTestCase {
* Params a message for each code needs.
*/
private const SAMPLE_PARAMS = array(
- ValidationErrorCode::REQUIRED => array(),
- ValidationErrorCode::INVALID_TYPE => array( 'type' => 'string' ),
- ValidationErrorCode::OUT_OF_BOUNDS => array( 'min' => 1 ),
- ValidationErrorCode::NOT_IN_ENUM => array( 'allowed' => array( 'day', 'week' ) ),
- ValidationErrorCode::INVALID_VALUE => array(),
- ValidationErrorCode::NOT_REGISTERED => array( 'value' => 'seasonal' ),
+ ValidationErrorCode::REQUIRED => array(),
+ ValidationErrorCode::INVALID_TYPE => array( 'type' => 'string' ),
+ ValidationErrorCode::OUT_OF_BOUNDS => array( 'min' => 1 ),
+ ValidationErrorCode::NOT_IN_ENUM => array( 'allowed' => array( 'day', 'week' ) ),
+ ValidationErrorCode::INVALID_VALUE => array(),
+ ValidationErrorCode::INVALID_PATTERN => array( 'pattern' => '^[a-z]+$' ),
+ ValidationErrorCode::NOT_REGISTERED => array( 'value' => 'seasonal' ),
);
/**
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Ownership/ConsumerRegistryTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Ownership/ConsumerRegistryTest.php
index d5d998dc485..8c8c3166994 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Ownership/ConsumerRegistryTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Ownership/ConsumerRegistryTest.php
@@ -114,25 +114,52 @@ class ConsumerRegistryTest extends EngineIntegrationTestCase {
ConsumerRegistry::register( 'lite', array( 'contract_due_handler' => $first ) );
ConsumerRegistry::register( 'lite', array( 'contract_due_handler' => static function (): void {} ) );
- ConsumerRegistry::register( ' lite ' );
$this->assertSame( $first, ConsumerRegistry::get_contract_due_handler( 'lite' ) );
$this->assertSame( array( 'lite' ), ConsumerRegistry::get_slugs_with_contract_due_handler() );
}
/**
- * @testdox An empty or whitespace-only slug is ignored and a slug is stored trimmed.
+ * @testdox A slug that is not 1-64 lowercase letters, digits, hyphens or underscores raises a notice and registers nothing.
+ * @dataProvider provide_invalid_slugs
+ *
+ * @param string $slug Invalid slug.
*/
- public function test_register_ignores_blank_slugs_and_trims(): void {
+ public function test_register_refuses_an_invalid_slug( string $slug ): void {
+ $this->setExpectedIncorrectUsage( self::REGISTER );
+
+ ConsumerRegistry::register( $slug, array( 'contract_due_handler' => static function (): void {} ) );
+
+ $this->assertSame( array(), ConsumerRegistry::get_slugs_with_contract_due_handler() );
+ }
+
+ /**
+ * @return array<string, array{0: string}>
+ */
+ public function provide_invalid_slugs(): array {
+ return array(
+ 'empty' => array( '' ),
+ 'whitespace' => array( " \t\n" ),
+ 'trailing space' => array( 'lite ' ),
+ 'surrounded' => array( ' woocommerce-subscriptions-lite ' ),
+ 'capitals' => array( 'LITE' ),
+ 'inner space' => array( 'li te' ),
+ 'accent' => array( 'lité' ),
+ '65 characters' => array( str_repeat( 'a', 65 ) ),
+ );
+ }
+
+ /**
+ * @testdox A valid slug is stored and looked up exactly as given.
+ */
+ public function test_register_stores_the_slug_as_given(): void {
$handler = static function (): void {};
- ConsumerRegistry::register( '' );
- ConsumerRegistry::register( " \t\n", array( 'contract_due_handler' => $handler ) );
- $this->assertSame( array(), ConsumerRegistry::get_slugs_with_contract_due_handler(), 'A blank slug must not register.' );
+ ConsumerRegistry::register( 'woocommerce-subscriptions-lite', array( 'contract_due_handler' => $handler ) );
- ConsumerRegistry::register( ' woocommerce-subscriptions-lite ', array( 'contract_due_handler' => $handler ) );
- $this->assertSame( array( 'woocommerce-subscriptions-lite' ), ConsumerRegistry::get_slugs_with_contract_due_handler(), 'The slug is stored trimmed.' );
- $this->assertSame( $handler, ConsumerRegistry::get_contract_due_handler( ' woocommerce-subscriptions-lite ' ) );
+ $this->assertSame( array( 'woocommerce-subscriptions-lite' ), ConsumerRegistry::get_slugs_with_contract_due_handler() );
+ $this->assertSame( $handler, ConsumerRegistry::get_contract_due_handler( 'woocommerce-subscriptions-lite' ) );
+ $this->assertNull( ConsumerRegistry::get_contract_due_handler( ' woocommerce-subscriptions-lite ' ), 'Lookups are exact.' );
}
/**
@@ -150,7 +177,10 @@ class ConsumerRegistryTest extends EngineIntegrationTestCase {
$this->assertSame( array( 'premium' ), ConsumerRegistry::get_slugs_with_contract_due_handler(), 'An unknown slug is a no-op.' );
ConsumerRegistry::unregister( ' premium ' );
- $this->assertSame( array(), ConsumerRegistry::get_slugs_with_contract_due_handler(), 'The slug is trimmed, matching register().' );
+ $this->assertSame( array( 'premium' ), ConsumerRegistry::get_slugs_with_contract_due_handler(), 'The slug matches exactly, as register() stores it.' );
+
+ ConsumerRegistry::unregister( 'premium' );
+ $this->assertSame( array(), ConsumerRegistry::get_slugs_with_contract_due_handler() );
}
/**
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php
index 78c7db3955f..d92084e0c34 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php
@@ -1116,6 +1116,23 @@ class ContractRepositoryTest extends EngineIntegrationTestCase {
$this->assertSame( '2026-06-15 00:00:00', $contract->get_next_payment_gmt(), 'The waiting contract keeps its due moment.' );
}
+ /**
+ * @testdox find_due matches the owner exactly: a contract of a slug differing only in case is not selected.
+ */
+ public function test_find_due_skips_a_case_variant_owner(): void {
+ global $wpdb;
+
+ $now = new \DateTimeImmutable( '2026-07-15 00:00:00', new \DateTimeZone( 'UTC' ) );
+ $owned = $this->insert_contract_due_at( '2026-06-15 00:00:00', ContractStatus::ACTIVE );
+ $variant = $this->insert_contract_due_at( '2026-06-15 00:00:00', ContractStatus::ACTIVE );
+ // The facades refuse such a slug; the row stands for data written around them.
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
+ $wpdb->update( SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACTS ), array( 'extension_slug' => strtoupper( self::OWNER ) ), array( 'id' => $variant ) );
+
+ $this->assertSame( array( $owned ), $this->due_ids( $now, 50 ) );
+ $this->assertSame( array( $variant ), $this->due_ids( $now, 50, array( strtoupper( self::OWNER ) ) ) );
+ }
+
/**
* @testdox find_due returns nothing when no owner is listed.
*/
@@ -2571,12 +2588,38 @@ class ContractRepositoryTest extends EngineIntegrationTestCase {
$this->assertSame( '1', $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE creation_key = %s AND extension_slug = %s", 'order:42', 'lite' ) ) );
$this->assertNotNull( $this->sut->insert( $this->keyed_contract( 'other-ext', 'order:42' ), 'checkout' ), 'Another extension may use the same key.' );
+ $this->assertNotNull( $this->sut->insert( $this->keyed_contract( 'LITE', 'order:42' ), 'checkout' ), 'An owner differing only in case is another extension.' );
$this->assertNotNull( $this->sut->insert( $this->keyed_contract( 'lite', 'Order:42' ), 'checkout' ), 'Keys differing only in case are distinct.' );
$this->assertNotNull( $this->sut->insert( $this->keyed_contract( 'lite', 'ördér:42' ), 'checkout' ), 'Keys differing only in accents are distinct.' );
$this->assertNotNull( $this->sut->insert( $this->keyed_contract( 'lite', null ), 'checkout' ) );
$this->assertNotNull( $this->sut->insert( $this->keyed_contract( 'lite', null ), 'checkout' ), 'Null keys never collide.' );
}
+ /**
+ * @testdox acquire_lock matches the owner exactly: a slug differing only in case takes no lock.
+ */
+ public function test_acquire_lock_matches_the_owner_exactly(): void {
+ $id = $this->insert_released( $this->keyed_contract( 'lite', null ) );
+
+ $this->assertNull( $this->sut->acquire_lock( $id, 'LITE', 'test' ) );
+ $this->assertNull( $this->get_lock_holder( $id )['operation'] );
+
+ $lock = $this->sut->acquire_lock( $id, 'lite', 'test' );
+ $this->assertNotNull( $lock );
+ $lock->release();
+ }
+
+ /**
+ * @testdox The creation-key fallback read matches the owner exactly.
+ */
+ public function test_creation_key_fallback_read_matches_the_owner_exactly(): void {
+ $this->insert_released( $this->keyed_contract( 'lite', 'order:43' ) );
+
+ $this->assertTrue( $this->call_private( $this->sut, 'has_creation_key', 'lite', 'order:43' ) );
+ $this->assertFalse( $this->call_private( $this->sut, 'has_creation_key', 'LITE', 'order:43' ) );
+ $this->assertFalse( $this->call_private( $this->sut, 'has_creation_key', 'lite', 'ORDER:43' ) );
+ }
+
/**
* @testdox insert() creates the contract locked from birth.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php
index 4e62c1bb526..51169cc2f10 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php
@@ -311,7 +311,7 @@ class PlanMetaTest extends EngineIntegrationTestCase {
// The UPDATE changes no row, so update_fields() reads whether the plan exists.
$change_nothing = static function ( string $query ) use ( $plans ): string {
- return 0 === strpos( $query, "UPDATE {$plans} p " ) ? $query . ' AND 0 = 1' : $query;
+ return 0 === strpos( $query, "UPDATE `{$plans}` SET " ) ? $query . ' AND 0 = 1' : $query;
};
add_filter( 'query', $change_nothing );
@@ -333,7 +333,7 @@ class PlanMetaTest extends EngineIntegrationTestCase {
*/
public function provide_failing_plan_update_queries(): array {
return array(
- 'update' => array( 'UPDATE {plans} p ', 'Failed to update plan' ),
+ 'update' => array( 'UPDATE `{plans}` SET ', 'Failed to update plan' ),
'existence read after it' => array( 'SELECT p.id FROM {plans} p ', 'Failed to read plan' ),
);
}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php
index cbb7abe23d9..d7ac0af6a0a 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php
@@ -209,6 +209,35 @@ class PlanRepositoryTest extends EngineIntegrationTestCase {
$this->assertInstanceOf( Plan::class, $repo->find( $id ), 'An unscoped read finds a plan of any extension.' );
}
+ /**
+ * @testdox find throws on a failed read, scoped or not, instead of reading the plan as missing.
+ * @dataProvider provide_failing_find_reads
+ *
+ * @param string $pattern Regex of the read to break.
+ * @param string|null $extension_slug Owner to scope the read to, or null.
+ */
+ public function test_find_throws_on_a_failed_read( string $pattern, ?string $extension_slug ): void {
+ $repo = new PlanRepository();
+ $id = $this->insert_plan( $repo, 'Stored' );
+
+ $this->fail_next_query( $pattern );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( "Failed to read plan {$id}" );
+
+ $repo->find( $id, $extension_slug );
+ }
+
+ /**
+ * @return array<string, array{0: string, 1: string|null}>
+ */
+ public function provide_failing_find_reads(): array {
+ return array(
+ 'unscoped' => array( '/^\s*SELECT \* FROM \S*selling_plans WHERE id/', null ),
+ 'scoped' => array( '/^\s*SELECT p\.\* FROM \S*selling_plans p /', 'lite' ),
+ );
+ }
+
/**
* @testdox update_fields writes nothing and returns false when the row belongs to another extension.
*/
@@ -237,6 +266,28 @@ class PlanRepositoryTest extends EngineIntegrationTestCase {
$this->assertSame( $before->to_storage(), $after->to_storage() );
}
+ /**
+ * @testdox update_fields writes nothing and returns false when the row's owner differs only in case.
+ */
+ public function test_update_fields_writes_nothing_to_a_row_of_a_case_variant_owner(): void {
+ global $wpdb;
+
+ $repo = new PlanRepository();
+ $id = $this->insert_plan( $repo, 'Original' );
+ $plan = $repo->find( $id );
+ $this->assertInstanceOf( Plan::class, $plan );
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
+ $wpdb->update( $wpdb->prefix . 'wc_selling_plans', array( 'extension_slug' => 'LITE' ), array( 'id' => $id ) );
+
+ $plan->set_name( 'Renamed' );
+ $this->assertFalse( $repo->update_fields( $plan, array( 'name' ) ) );
+
+ $after = $repo->find( $id );
+ $this->assertInstanceOf( Plan::class, $after );
+ $this->assertSame( 'Original', $after->get_name() );
+ }
+
/**
* @testdox update_fields refuses a name too long for its column, as insert does, and writes nothing.
*/
@@ -260,7 +311,7 @@ class PlanRepositoryTest extends EngineIntegrationTestCase {
$repo->update_fields( $plan, array( 'name' ) );
$this->fail( 'Expected update_fields to refuse the name.' );
} catch ( \RuntimeException $e ) {
- $this->assertStringContainsString( 'longer than the column allows', $e->getMessage() );
+ $this->assertStringContainsString( 'Failed to update plan', $e->getMessage() );
}
$stored = $repo->find( $id );
@@ -484,6 +535,24 @@ class PlanRepositoryTest extends EngineIntegrationTestCase {
$this->assertSame( array( $lite_id, $other_id ), array_map( static fn ( Plan $plan ): ?int => $plan->get_id(), $both ) );
}
+ /**
+ * @testdox query and count match the owner exactly: a slug differing only in case is another extension.
+ */
+ public function test_query_extension_slugs_match_the_owner_case_sensitively(): void {
+ $repo = new PlanRepository();
+
+ $lite_id = $this->insert_plan( $repo, 'Lite plan', 'lite' );
+ $this->insert_plan( $repo, 'Case variant plan', 'LITE' );
+ $other_id = $this->insert_plan( $repo, 'Other plan', 'other-extension' );
+
+ $this->assertSame( array( $lite_id ), self::ids( $repo->query( array( 'extension_slugs' => array( 'lite' ) ) ) ) );
+ $this->assertSame( 1, $repo->count( array( 'extension_slugs' => array( 'lite' ) ) ) );
+
+ $both = array( 'extension_slugs' => array( 'lite', 'other-extension' ) );
+ $this->assertSame( array( $lite_id, $other_id ), self::ids( $repo->query( $both ) ) );
+ $this->assertSame( 2, $repo->count( $both ) );
+ }
+
public function test_query_singular_extension_slug_arg_is_unknown_and_ignored(): void {
$repo = new PlanRepository();
@@ -561,4 +630,19 @@ class PlanRepositoryTest extends EngineIntegrationTestCase {
$this->assertTrue( $repo->delete( $id ) );
$this->assertNull( $repo->find( $id ) );
}
+
+ /**
+ * @testdox delete scoped to a slug differing only in case keeps the plan and its meta.
+ */
+ public function test_delete_under_a_case_variant_owner_keeps_the_plan(): void {
+ $repo = new PlanRepository();
+
+ $id = $this->insert_plan( $repo, 'Kept' );
+ $repo->add_meta( $id, 'lite', 'note', 'kept' );
+
+ $this->assertFalse( $repo->delete( $id, 'LITE' ) );
+ $this->assertInstanceOf( Plan::class, $repo->find( $id ) );
+ $this->assertSame( array( 'kept' ), $repo->get_meta( $id, 'note' ) );
+ $this->assertTrue( $repo->delete( $id, 'lite' ) );
+ }
}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php
index a1b70b12ca7..787ce296bdb 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php
@@ -291,10 +291,10 @@ class SchemaInstallerTest extends EngineIntegrationTestCase {
}
/**
- * @testdox The schema version is 2.8.0 (contract lock).
+ * @testdox The schema version is 2.9.0 (binary owner columns).
*/
- public function test_schema_version_is_2_8_0(): void {
- $this->assertSame( '2.8.0', SchemaInstaller::get_version() );
+ public function test_schema_version_is_2_9_0(): void {
+ $this->assertSame( '2.9.0', SchemaInstaller::get_version() );
}
/**
@@ -382,6 +382,34 @@ class SchemaInstallerTest extends EngineIntegrationTestCase {
$this->assertSame( $wpdb->charset . '_bin', $row['Collation'] ?? null );
}
+ /**
+ * @testdox The owner column of the $logical table compares binary, in the table charset.
+ * @dataProvider provide_owner_tables
+ *
+ * @param string $logical Logical table identifier.
+ */
+ public function test_owner_column_is_binary_collated( string $logical ): void {
+ global $wpdb;
+
+ $table = SchemaInstaller::get_table_name( $logical );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ $row = $wpdb->get_row( $wpdb->prepare( "SHOW FULL COLUMNS FROM {$table} LIKE %s", 'extension_slug' ), ARRAY_A );
+
+ $this->assertIsArray( $row );
+ $this->assertSame( $wpdb->charset . '_bin', $row['Collation'] ?? null );
+ }
+
+ /**
+ * @return array<string, array{0: string}>
+ */
+ public function provide_owner_tables(): array {
+ return array(
+ 'plans' => array( SchemaInstaller::TABLE_PLANS ),
+ 'contracts' => array( SchemaInstaller::TABLE_CONTRACTS ),
+ 'cycles' => array( SchemaInstaller::TABLE_CYCLES ),
+ );
+ }
+
/**
* @testdox Contract identity columns are nullable until the extension supplies them.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php b/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php
index 370480302a0..e3d93d261db 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php
@@ -46,6 +46,9 @@ class ArgumentValidatorTest extends TestCase {
'null currency' => array( 'validate_currency', array( null ), null ),
'string' => array( 'validate_string', array( 'status', 'active' ), 'active' ),
'non-empty string' => array( 'validate_non_empty_string', array( 'extension_slug', 'acme' ), 'acme' ),
+ 'extension slug' => array( 'validate_extension_slug', array( 'extension_slug', 'woocommerce-subscriptions-lite' ), 'woocommerce-subscriptions-lite' ),
+ 'extension slug chars' => array( 'validate_extension_slug', array( 'extension_slug', 'acme_2-x' ), 'acme_2-x' ),
+ 'extension slug 64' => array( 'validate_extension_slug', array( 'extension_slug', str_repeat( 'a', 64 ) ), str_repeat( 'a', 64 ) ),
'nullable string' => array( 'validate_nullable_string', array( 'title', null ), null ),
'nullable id as digits' => array( 'validate_nullable_id', array( 'order_id', '42' ), 42 ),
'nullable id null' => array( 'validate_nullable_id', array( 'order_id', null ), null ),
@@ -131,6 +134,7 @@ class ArgumentValidatorTest extends TestCase {
$type_array = array( 'type' => 'array' );
$type_object = array( 'type' => 'object' );
$min_one = array( 'min' => 1 );
+ $slug_pattern = array( 'pattern' => '^[a-z0-9_-]{1,64}$' );
return array(
'currency' => array( 'validate_currency', array( 'eur' ), ValidationErrorCode::INVALID_VALUE, 'currency', array() ),
@@ -140,6 +144,15 @@ class ArgumentValidatorTest extends TestCase {
'non-empty not string' => array( 'validate_non_empty_string', array( 'extension_slug', 5 ), ValidationErrorCode::INVALID_TYPE, 'extension_slug', $type_string ),
'non-empty null' => array( 'validate_non_empty_string', array( 'extension_slug', null ), ValidationErrorCode::REQUIRED, 'extension_slug', array() ),
'non-empty empty' => array( 'validate_non_empty_string', array( 'extension_slug', '' ), ValidationErrorCode::REQUIRED, 'extension_slug', array() ),
+ 'slug trailing space' => array( 'validate_extension_slug', array( 'extension_slug', 'lite ' ), ValidationErrorCode::INVALID_PATTERN, 'extension_slug', $slug_pattern ),
+ 'slug leading space' => array( 'validate_extension_slug', array( 'extension_slug', ' lite' ), ValidationErrorCode::INVALID_PATTERN, 'extension_slug', $slug_pattern ),
+ 'slug inner space' => array( 'validate_extension_slug', array( 'extension_slug', 'li te' ), ValidationErrorCode::INVALID_PATTERN, 'extension_slug', $slug_pattern ),
+ 'slug uppercase' => array( 'validate_extension_slug', array( 'extension_slug', 'LITE' ), ValidationErrorCode::INVALID_PATTERN, 'extension_slug', $slug_pattern ),
+ 'slug accent' => array( 'validate_extension_slug', array( 'extension_slug', 'lité' ), ValidationErrorCode::INVALID_PATTERN, 'extension_slug', $slug_pattern ),
+ 'slug newline' => array( 'validate_extension_slug', array( 'extension_slug', "lite\n" ), ValidationErrorCode::INVALID_PATTERN, 'extension_slug', $slug_pattern ),
+ 'slug 65 characters' => array( 'validate_extension_slug', array( 'extension_slug', str_repeat( 'a', 65 ) ), ValidationErrorCode::INVALID_PATTERN, 'extension_slug', $slug_pattern ),
+ 'slug empty' => array( 'validate_extension_slug', array( 'extension_slug', '' ), ValidationErrorCode::REQUIRED, 'extension_slug', array() ),
+ 'slug not string' => array( 'validate_extension_slug', array( 'extension_slug', 5 ), ValidationErrorCode::INVALID_TYPE, 'extension_slug', $type_string ),
'positive int type' => array( 'validate_positive_int', array( 'quantity', null ), ValidationErrorCode::INVALID_TYPE, 'quantity', $type_integer ),
'positive int zero' => array( 'validate_positive_int', array( 'quantity', 0 ), ValidationErrorCode::OUT_OF_BOUNDS, 'quantity', $min_one ),
'nullable id type' => array( 'validate_nullable_id', array( 'order_id', "5\n" ), ValidationErrorCode::INVALID_TYPE, 'order_id', $type_integer ),