Commit 8b0b7e5b2cc for woocommerce

commit 8b0b7e5b2ccd2e0a151542c72443c3a143beaf01
Author: Barry Hughes <3594411+barryhughes@users.noreply.github.com>
Date:   Thu Nov 19 13:50:44 2026 -0700

    Subscriptions engine: add an owner filter to the customer contract list read (#71117)

    * Add an owner filter to the engine customer contract list read

    Api\Contracts::list_for_customer() accepts an optional extension_slug key
    (one non-empty string; "any" is refused) so a consumer can list only its own
    contracts for a customer. ContractRepository::find_by_customer_id() matches
    it with the exact, case-sensitive owner match the other owner checks use,
    before paging. The facade now filters its keys: an unknown key raises
    _doing_it_wrong() and is ignored. Status handling is unchanged.

    Refs WOOSUBS-2166.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Fail closed on the customer list owner filter and widen its tests

    ContractRepository::find_by_customer_id() now applies the owner match
    whenever the extension_slug key is present, binding the value through
    Coercion::coerce_string(). A non-string value from an internal caller
    binds an empty slug and matches nothing, instead of dropping the filter
    and listing every owner's contracts. The docblock names the match as the
    binary one the lock and write guards use.

    Tests pin a null extension_slug as required at the facade, combine the
    status and owner filters through the facade, and cover the fail-closed
    repository read.

    Refs WOOSUBS-2166.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Correct the customer list owner filter comment

    The value binds as a string: a non-scalar or false binds '' and matches
    nothing, and any other scalar binds its string form as an exact owner.
    Either way the filter never widens to every owner. Comment-only change.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    ---------

    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/packages/php/woocommerce-subscriptions-engine/changelog/add-subscriptions-engine-customer-list-owner-filter b/packages/php/woocommerce-subscriptions-engine/changelog/add-subscriptions-engine-customer-list-owner-filter
new file mode 100644
index 00000000000..5e5369b3a6b
--- /dev/null
+++ b/packages/php/woocommerce-subscriptions-engine/changelog/add-subscriptions-engine-customer-list-owner-filter
@@ -0,0 +1,4 @@
+Significance: patch
+Type: dev
+Comment: Add an optional extension_slug owner filter to the unreleased subscriptions engine customer contract list read; no changelog entry needed.
+
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
index 6b17623e101..41e7c0e3ad7 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
@@ -30,6 +30,7 @@ use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\Contract;
 use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\Cycle;
 use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator;
 use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\InvalidInputException;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ValidationErrorCode;
 use Automattic\WooCommerce\SubscriptionsEngine\Core\ValueObject\PaymentInstrumentRef;
 use Automattic\WooCommerce\SubscriptionsEngine\Integration\Storage\ContractRepository;
 use Automattic\WooCommerce\SubscriptionsEngine\Integration\Storage\DuplicateCycleException;
@@ -134,6 +135,16 @@ final class Contracts {
 		'reason'         => true,
 	);

+	/**
+	 * Keys accepted by {@see self::list_for_customer()}, as a key map.
+	 *
+	 * @var array<string, true>
+	 */
+	private const LIST_FOR_CUSTOMER_KEYS = array(
+		'status'         => true,
+		'extension_slug' => true,
+	);
+
 	/**
 	 * Take the contract's lock for `$operation`, for the synchronous section of this request.
 	 * Pass the lock to every write of the operation and release it when done; an unreleased
@@ -613,7 +624,8 @@ final class Contracts {
 	 * and addresses not loaded); a caller needing plan terms resolves `selling_plan_id`
 	 * through {@see Plans::get()}.
 	 *
-	 * The status filter applies before paging, so a page holds `$limit` matching contracts.
+	 * The status and owner filters apply before paging, so a page holds `$limit` matching
+	 * contracts. Unknown keys raise a `_doing_it_wrong()` notice and are ignored.
 	 *
 	 * @param int                  $customer_id Owning customer id.
 	 * @param int                  $limit       Maximum contracts to return.
@@ -621,22 +633,43 @@ final class Contracts {
 	 * @param array<string, mixed> $args {
 	 *     Optional. Query args.
 	 *
-	 *     @type string|string[] $status One status or a list of them ({@see \Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\ContractStatus});
-	 *                                   unregistered values are dropped, and the filter is ignored when none remain.
+	 *     @type string|string[] $status         One status or a list of them ({@see \Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\ContractStatus});
+	 *                                           unregistered values are dropped, and the filter is ignored when none remain.
+	 *     @type string          $extension_slug Owning extension slug (exact, case-sensitive match; `any` is refused).
+	 *                                           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`.
 	 */
 	public static function list_for_customer( int $customer_id, int $limit = 20, int $offset = 0, array $args = array() ): array {
-		return self::views(
-			( new ContractRepository() )->find_by_customer_id(
-				$customer_id,
-				array(
-					'limit'  => $limit,
-					'offset' => $offset,
-					'status' => $args['status'] ?? array(),
-				)
-			)
+		$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::LIST_FOR_CUSTOMER_KEYS );
+
+		$query = array(
+			'limit'  => $limit,
+			'offset' => $offset,
+			'status' => $filtered_args['status'] ?? array(),
 		);
+		if ( array_key_exists( 'extension_slug', $filtered_args ) ) {
+			$validator      = new ArgumentValidator();
+			$extension_slug = $validator->get_non_empty_string( 'extension_slug', $filtered_args['extension_slug'] );
+			if ( 'any' === $extension_slug ) {
+				$validator->add(
+					new InvalidInputException(
+						ValidationErrorCode::INVALID_VALUE,
+						'extension_slug',
+						'"extension_slug" must not be "any": leave it out to list every extension\'s contracts.'
+					)
+				);
+			}
+			try {
+				$validator->throw_errors();
+			} catch ( InvalidInputException $e ) {
+				throw ValidationException::from_core( $e ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- from_core() escapes the message.
+			}
+			$query['extension_slug'] = $extension_slug;
+		}
+
+		return self::views( ( new ContractRepository() )->find_by_customer_id( $customer_id, $query ) );
 	}

 	/**
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 9b74f059889..f1f17dfb7c6 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
@@ -1237,6 +1237,9 @@ final class ContractRepository {
 	 *     @type string|string[] $status Optional status filter: one status or a list of them
 	 *                                   ({@see ContractStatus}). Unregistered values are dropped;
 	 *                                   ignored when none remain.
+	 *     @type string $extension_slug Optional owner filter: only contracts of this extension
+	 *                                  (binary, case-sensitive match, as the lock and write
+	 *                                  guards use). Absent: every extension.
 	 * }
 	 * @return array<int, Contract> Contracts the customer owns, newest first.
 	 */
@@ -1260,8 +1263,8 @@ final class ContractRepository {
 		$table  = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACTS );
 		$select = self::CONTRACT_SELECT;

-		// One query for both shapes: the optional status filter joins the WHERE, and
-		// every value is a placeholder (table names cannot be bound, so the table is
+		// One query for every shape: the optional status and owner filters join the WHERE,
+		// and every value is a placeholder (table names cannot be bound, so the table is
 		// interpolated).
 		$where  = 'customer_id = %d';
 		$params = array( $customer_id );
@@ -1269,6 +1272,13 @@ final class ContractRepository {
 			$where .= ' AND status IN (' . implode( ', ', array_fill( 0, count( $statuses ), '%s' ) ) . ')';
 			$params = array_merge( $params, $statuses );
 		}
+		// A present key always applies and never widens to every owner: the value binds as a
+		// string, so a non-scalar or false binds '' and matches nothing (no contract can own
+		// an empty slug), and any other scalar binds its string form as an exact owner.
+		if ( array_key_exists( 'extension_slug', $args ) ) {
+			$where   .= ' AND ' . self::OWNER_MATCH;
+			$params[] = Coercion::coerce_string( $args['extension_slug'] );
+		}
 		$params[] = $limit;
 		$params[] = $offset;

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 72abf6b18fa..98a8652f353 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
@@ -2734,13 +2734,14 @@ class ContractsTest extends EngineIntegrationTestCase {
 	/**
 	 * Seed a contract for a customer at a status, returning its id.
 	 *
-	 * @param int    $customer_id Owning customer.
-	 * @param string $status      Contract status.
+	 * @param int    $customer_id    Owning customer.
+	 * @param string $status         Contract status.
+	 * @param string $extension_slug Owning extension.
 	 */
-	private function seed_for_customer( int $customer_id, string $status = ContractStatus::ACTIVE ): int {
+	private function seed_for_customer( int $customer_id, string $status = ContractStatus::ACTIVE, string $extension_slug = 'engine-tests' ): int {
 		$contract = Contract::create(
 			array(
-				'extension_slug'   => 'engine-tests',
+				'extension_slug'   => $extension_slug,
 				'customer_id'      => $customer_id,
 				'status'           => $status,
 				'currency'         => 'USD',
@@ -2933,6 +2934,84 @@ class ContractsTest extends EngineIntegrationTestCase {
 		$this->assertCount( 4, Contracts::list_for_customer( 44, 20, 0, array( 'status' => array( 'nonsense' ) ) ), 'An unregistered status is dropped, leaving no filter.' );
 	}

+	/**
+	 * @testdox list_for_customer filters by the owning extension.
+	 */
+	public function test_list_for_customer_filters_by_extension_slug(): void {
+		$mine    = $this->seed_for_customer( 46 );
+		$foreign = $this->seed_for_customer( 46, ContractStatus::ACTIVE, 'other-extension' );
+
+		$ids = static fn ( array $views ): array => array_map( static fn ( ContractView $c ): int => (int) $c->get_id(), $views );
+
+		$this->assertSame( array( $mine ), $ids( Contracts::list_for_customer( 46, 20, 0, array( 'extension_slug' => 'engine-tests' ) ) ) );
+		$this->assertSame( array( $foreign ), $ids( Contracts::list_for_customer( 46, 20, 0, array( 'extension_slug' => 'other-extension' ) ) ) );
+		$this->assertSame( array( $foreign, $mine ), $ids( Contracts::list_for_customer( 46 ) ), 'Without the key, every extension\'s contracts are listed.' );
+	}
+
+	/**
+	 * @testdox list_for_customer combines the status and owner filters.
+	 */
+	public function test_list_for_customer_combines_the_status_and_extension_slug_filters(): void {
+		$this->seed_for_customer( 49 );
+		$held = $this->seed_for_customer( 49, ContractStatus::ON_HOLD );
+		$this->seed_for_customer( 49, ContractStatus::ON_HOLD, 'other-extension' );
+
+		$views = Contracts::list_for_customer(
+			49,
+			20,
+			0,
+			array(
+				'status'         => ContractStatus::ON_HOLD,
+				'extension_slug' => 'engine-tests',
+			)
+		);
+
+		$this->assertCount( 1, $views );
+		$this->assertSame( $held, $views[0]->get_id() );
+	}
+
+	/**
+	 * @testdox list_for_customer refuses an invalid extension_slug.
+	 * @dataProvider provide_invalid_list_for_customer_slugs
+	 *
+	 * @param mixed  $extension_slug Invalid owner value.
+	 * @param string $code           Expected error code.
+	 */
+	public function test_list_for_customer_rejects_an_invalid_extension_slug( $extension_slug, string $code ): void {
+		$this->assert_validation_errors(
+			static function () use ( $extension_slug ): void {
+				Contracts::list_for_customer( 47, 20, 0, array( 'extension_slug' => $extension_slug ) );
+			},
+			array( array( $code, 'extension_slug' ) )
+		);
+	}
+
+	/**
+	 * @return array<string, array{0: mixed, 1: string}>
+	 */
+	public function provide_invalid_list_for_customer_slugs(): array {
+		return array(
+			'null'         => array( null, ValidationErrorCode::REQUIRED ),
+			'empty string' => array( '', ValidationErrorCode::REQUIRED ),
+			'integer'      => array( 5, ValidationErrorCode::INVALID_TYPE ),
+			'array'        => array( array( 'engine-tests' ), ValidationErrorCode::INVALID_TYPE ),
+			'any'          => array( 'any', ValidationErrorCode::INVALID_VALUE ),
+		);
+	}
+
+	/**
+	 * @testdox list_for_customer ignores an unknown key with a notice.
+	 */
+	public function test_list_for_customer_ignores_an_unknown_key_with_a_notice(): void {
+		$this->setExpectedIncorrectUsage( Contracts::class . '::list_for_customer' );
+		$id = $this->seed_for_customer( 48 );
+
+		$views = Contracts::list_for_customer( 48, 20, 0, array( 'owner' => 'nobody' ) );
+
+		$this->assertCount( 1, $views );
+		$this->assertSame( $id, $views[0]->get_id() );
+	}
+
 	/**
 	 * @testdox get_for_customer returns the contract when the customer owns it.
 	 */
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php
index 8070c679839..592b31c6ef0 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php
@@ -1,7 +1,7 @@
 <?php
 /**
  * Integration tests for the customer-scoped contract reads on ContractRepository:
- * find_by_customer_id (owner scoping, ordering, status filter, paging) and
+ * find_by_customer_id (owner scoping, ordering, status and extension filters, paging) and
  * find_for_customer (the ownership-filtered full read behind the asymmetric
  * not-found rule).
  *
@@ -37,13 +37,14 @@ class ContractCustomerReadTest extends EngineIntegrationTestCase {
 	/**
 	 * Insert a contract for a customer at a given status.
 	 *
-	 * @param int    $customer_id Owning customer.
-	 * @param string $status      Contract status.
+	 * @param int    $customer_id    Owning customer.
+	 * @param string $status         Contract status.
+	 * @param string $extension_slug Owning extension.
 	 */
-	private function seed( int $customer_id, string $status ): int {
+	private function seed( int $customer_id, string $status, string $extension_slug = 'engine-tests' ): int {
 		$contract = Contract::create(
 			array(
-				'extension_slug'   => 'engine-tests',
+				'extension_slug'   => $extension_slug,
 				'customer_id'      => $customer_id,
 				'status'           => $status,
 				'currency'         => 'USD',
@@ -132,6 +133,67 @@ class ContractCustomerReadTest extends EngineIntegrationTestCase {
 		$this->assertSame( array( $ids[2], $ids[3] ), $this->ids( $page_two ) );
 	}

+	public function test_honours_an_extension_slug_filter(): void {
+		$mine    = $this->seed( 16, ContractStatus::ACTIVE );
+		$foreign = $this->seed( 16, ContractStatus::ACTIVE, 'other-extension' );
+
+		$this->assertSame( array( $mine ), $this->ids( $this->sut->find_by_customer_id( 16, array( 'extension_slug' => 'engine-tests' ) ) ) );
+		$this->assertSame( array( $foreign ), $this->ids( $this->sut->find_by_customer_id( 16, array( 'extension_slug' => 'other-extension' ) ) ) );
+	}
+
+	public function test_combines_the_extension_slug_and_status_filters(): void {
+		$this->seed( 17, ContractStatus::ACTIVE );
+		$held = $this->seed( 17, ContractStatus::ON_HOLD );
+		$this->seed( 17, ContractStatus::ON_HOLD, 'other-extension' );
+
+		$results = $this->sut->find_by_customer_id(
+			17,
+			array(
+				'status'         => ContractStatus::ON_HOLD,
+				'extension_slug' => 'engine-tests',
+			)
+		);
+
+		$this->assertSame( array( $held ), $this->ids( $results ) );
+	}
+
+	public function test_pages_after_the_extension_slug_filter(): void {
+		$older = $this->seed( 18, ContractStatus::ACTIVE );
+		$newer = $this->seed( 18, ContractStatus::ACTIVE );
+		$this->seed( 18, ContractStatus::ACTIVE, 'other-extension' ); // Newest row, of another owner.
+
+		$args = array(
+			'limit'          => 1,
+			'extension_slug' => 'engine-tests',
+		);
+
+		$page_one = $this->sut->find_by_customer_id( 18, $args + array( 'offset' => 0 ) );
+		$page_two = $this->sut->find_by_customer_id( 18, $args + array( 'offset' => 1 ) );
+
+		$this->assertSame( array( $newer ), $this->ids( $page_one ), 'The newer foreign row takes no page slot.' );
+		$this->assertSame( array( $older ), $this->ids( $page_two ) );
+	}
+
+	public function test_the_extension_slug_filter_is_case_sensitive(): void {
+		$this->seed( 19, ContractStatus::ACTIVE );
+
+		$this->assertSame( array(), $this->sut->find_by_customer_id( 19, array( 'extension_slug' => 'Engine-Tests' ) ) );
+	}
+
+	public function test_a_non_string_extension_slug_matches_nothing(): void {
+		$this->seed( 22, ContractStatus::ACTIVE );
+
+		$this->assertSame( array(), $this->sut->find_by_customer_id( 22, array( 'extension_slug' => null ) ) );
+		$this->assertSame( array(), $this->sut->find_by_customer_id( 22, array( 'extension_slug' => array( 'engine-tests' ) ) ) );
+	}
+
+	public function test_lists_every_extension_without_an_extension_slug(): void {
+		$mine    = $this->seed( 21, ContractStatus::ACTIVE );
+		$foreign = $this->seed( 21, ContractStatus::ACTIVE, 'other-extension' );
+
+		$this->assertSame( array( $foreign, $mine ), $this->ids( $this->sut->find_by_customer_id( 21 ) ) );
+	}
+
 	public function test_empty_for_a_customer_with_no_contracts(): void {
 		$this->assertSame( array(), $this->sut->find_by_customer_id( 999 ) );
 	}