Commit 3ee853d2183 for woocommerce
commit 3ee853d21833149a7e3c966d558b78e513363a7a
Author: Ján Mikláš <neosinner@gmail.com>
Date: Tue Nov 17 15:15:18 2026 +0100
Add a Playwright client for admin REST requests (#71036)
* Add a Playwright client for admin REST requests
* Add changelog entry for Playwright admin REST
* Support REST namespaces and refresh stale admin nonces
* Record the admin REST helper in the package changelog
* Clear rejected admin REST nonce on retry
diff --git a/packages/js/e2e-utils-playwright/README.md b/packages/js/e2e-utils-playwright/README.md
index 823ae5002c0..a37d627c6ef 100644
--- a/packages/js/e2e-utils-playwright/README.md
+++ b/packages/js/e2e-utils-playwright/README.md
@@ -69,6 +69,26 @@ console.log(response.data);
Supported methods: `get(path, params, debug)`, `post(path, data, debug)`, `put(path, data, debug)`, `delete(path, params, debug)`
+### Logged-in admin session
+
+Use `createAdminRestClient` with an authenticated Playwright request context and a WordPress site that exposes its REST API at `wp-json/`. Pass the site URL, including any installation subdirectory, and include the namespace in each route. The helper preserves caller headers, manages the WordPress REST nonce, and returns Playwright's `APIResponse` for all HTTP statuses.
+
+The helper refreshes the nonce and retries once when WordPress returns `rest_cookie_invalid_nonce`. If the request uploads a stream, it returns that response so the caller can retry with a fresh stream.
+
+```js
+import { createAdminRestClient } from '@woocommerce/e2e-utils-playwright';
+
+const send = createAdminRestClient(adminPage.request, 'http://localhost:8889/');
+const response = await send('wc/v3/orders/123', {
+ method: 'PUT',
+ data: { status: 'completed' },
+});
+await expect(response).toBeOK();
+
+const pages = await send('wp/v2/pages', { params: { per_page: 5 } });
+await expect(pages).toBeOK();
+```
+
## Contributing to this package
This is an individual package that's part of the WooCommerce project, which is organized as a monorepo.
diff --git a/packages/js/e2e-utils-playwright/changelog/test-playwright-admin-rest b/packages/js/e2e-utils-playwright/changelog/test-playwright-admin-rest
new file mode 100644
index 00000000000..91fb9018524
--- /dev/null
+++ b/packages/js/e2e-utils-playwright/changelog/test-playwright-admin-rest
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add a Playwright helper for WordPress REST requests using a logged-in admin session.
diff --git a/packages/js/e2e-utils-playwright/src/admin-rest-client.ts b/packages/js/e2e-utils-playwright/src/admin-rest-client.ts
new file mode 100644
index 00000000000..c5ea9a25faa
--- /dev/null
+++ b/packages/js/e2e-utils-playwright/src/admin-rest-client.ts
@@ -0,0 +1,114 @@
+/**
+ * External dependencies
+ */
+import type { APIRequestContext } from '@playwright/test';
+import { Readable } from 'node:stream';
+
+type AdminRestRequestOptions = Omit<
+ NonNullable< Parameters< APIRequestContext[ 'fetch' ] >[ 1 ] >,
+ 'failOnStatusCode' | 'maxRedirects'
+>;
+
+/**
+ * Create a WordPress REST client for an authenticated Playwright admin session.
+ * It reuses a nonce and retries once if WordPress rejects it. For an upload
+ * using a stream, the caller must supply a fresh stream and retry.
+ *
+ * @param request Playwright request context with the admin session cookies.
+ * @param siteUrl WordPress site URL, including any installation subdirectory.
+ * @return A function that accepts a route relative to wp-json and returns an APIResponse.
+ */
+export function createAdminRestClient(
+ request: APIRequestContext,
+ siteUrl: string
+) {
+ const base = new URL( siteUrl );
+ if ( ! base.pathname.endsWith( '/' ) ) {
+ base.pathname += '/';
+ }
+ const restUrl = new URL( 'wp-json/', base );
+ const nonceUrl = new URL(
+ 'wp-admin/admin-ajax.php?action=rest-nonce',
+ base
+ );
+ let nonce: Promise< string > | undefined;
+
+ async function getNonce() {
+ const response = await request.get( nonceUrl.href, {
+ maxRedirects: 0,
+ failOnStatusCode: false,
+ } );
+ try {
+ const value = ( await response.text() ).trim();
+ if ( ! response.ok() || ! /^[a-f0-9]{10}$/i.test( value ) ) {
+ throw new Error(
+ `Could not get an admin REST nonce (HTTP ${ response.status() }).`
+ );
+ }
+ return value;
+ } finally {
+ await response.dispose();
+ }
+ }
+
+ function getCachedNonce() {
+ nonce ??= getNonce().catch( ( error ) => {
+ nonce = undefined;
+ throw error;
+ } );
+ return nonce;
+ }
+
+ return async ( route: string, options?: AdminRestRequestOptions ) => {
+ const endpoint = new URL( route.replace( /^\//, '' ), restUrl );
+ if (
+ endpoint.origin !== restUrl.origin ||
+ ! endpoint.pathname.startsWith( restUrl.pathname )
+ ) {
+ throw new Error(
+ 'Expected a route within the WordPress REST API.'
+ );
+ }
+
+ const headers = Object.fromEntries(
+ Object.entries( options?.headers ?? {} ).filter(
+ ( [ name ] ) => name.toLowerCase() !== 'x-wp-nonce'
+ )
+ );
+ const send = async () => {
+ const usedNonce = getCachedNonce();
+ const value = await usedNonce;
+ const response = await request.fetch( endpoint.href, {
+ ...options,
+ headers: { ...headers, 'X-WP-Nonce': value },
+ failOnStatusCode: false,
+ maxRedirects: 0,
+ } );
+ const nonceRejected =
+ response.status() === 403 &&
+ ( await response.json().catch( () => null ) )?.code ===
+ 'rest_cookie_invalid_nonce';
+ if ( nonceRejected && nonce === usedNonce ) {
+ nonce = undefined;
+ }
+ return { response, nonceRejected };
+ };
+
+ const { response, nonceRejected } = await send();
+ if ( ! nonceRejected ) {
+ return response;
+ }
+ // Playwright consumes multipart upload streams on the first request.
+ if (
+ Object.values( options?.multipart ?? {} ).some(
+ ( value ) => value instanceof Readable
+ )
+ ) {
+ return response;
+ }
+
+ await response.dispose();
+ const { response: retryResponse } = await send();
+ return retryResponse;
+ };
+}
diff --git a/packages/js/e2e-utils-playwright/src/index.ts b/packages/js/e2e-utils-playwright/src/index.ts
index c14224dd58d..5257f4db52b 100644
--- a/packages/js/e2e-utils-playwright/src/index.ts
+++ b/packages/js/e2e-utils-playwright/src/index.ts
@@ -4,6 +4,7 @@ export * from './checkout';
export * from './editor';
export * from './order';
export * from './api-client';
+export * from './admin-rest-client';
// Re-export types not already covered by module re-exports above
export type { ApiClient, AddressType } from './types';
diff --git a/packages/js/e2e-utils-playwright/src/test/admin-rest-client.test.ts b/packages/js/e2e-utils-playwright/src/test/admin-rest-client.test.ts
new file mode 100644
index 00000000000..f49e1107946
--- /dev/null
+++ b/packages/js/e2e-utils-playwright/src/test/admin-rest-client.test.ts
@@ -0,0 +1,246 @@
+/**
+ * External dependencies
+ */
+import type { APIRequestContext } from '@playwright/test';
+import { createReadStream } from 'node:fs';
+
+/**
+ * Internal dependencies
+ */
+import { createAdminRestClient } from '../admin-rest-client';
+
+function mockAdminRequest() {
+ const dispose = jest.fn().mockResolvedValue( undefined );
+ const nonceResponse = {
+ ok: () => true,
+ status: () => 200,
+ text: jest.fn().mockResolvedValue( ' 0123456789\n' ),
+ dispose,
+ };
+ const get = jest.fn().mockResolvedValue( nonceResponse );
+ const restResponse = { ok: () => true, status: () => 200 };
+ const fetch = jest.fn().mockResolvedValue( restResponse );
+
+ return {
+ request: { get, fetch } as unknown as APIRequestContext,
+ get,
+ fetch,
+ nonceResponse,
+ restResponse,
+ };
+}
+
+describe( 'createAdminRestClient', () => {
+ it( 'shares one nonce across namespaces and preserves caller headers', async () => {
+ const { request, get, fetch, nonceResponse, restResponse } =
+ mockAdminRequest();
+ const send = createAdminRestClient(
+ request,
+ 'https://example.com/shop'
+ );
+ const options = {
+ method: 'PUT',
+ data: { status: 'completed' },
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-wp-nonce': 'caller-nonce',
+ },
+ };
+
+ const responses = await Promise.all( [
+ send( 'wc/v3/orders/12', options ),
+ send( '/wp/v2/pages?per_page=6' ),
+ ] );
+
+ expect( get ).toHaveBeenCalledTimes( 1 );
+ expect( get ).toHaveBeenCalledWith(
+ 'https://example.com/shop/wp-admin/admin-ajax.php?action=rest-nonce',
+ { maxRedirects: 0, failOnStatusCode: false }
+ );
+ expect( nonceResponse.dispose ).toHaveBeenCalledTimes( 1 );
+ expect( fetch ).toHaveBeenCalledWith(
+ 'https://example.com/shop/wp-json/wc/v3/orders/12',
+ {
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-WP-Nonce': '0123456789',
+ },
+ maxRedirects: 0,
+ failOnStatusCode: false,
+ }
+ );
+ expect( fetch ).toHaveBeenCalledWith(
+ 'https://example.com/shop/wp-json/wp/v2/pages?per_page=6',
+ {
+ headers: { 'X-WP-Nonce': '0123456789' },
+ maxRedirects: 0,
+ failOnStatusCode: false,
+ }
+ );
+ expect( responses ).toEqual( [ restResponse, restResponse ] );
+ } );
+
+ it( 'rejects an invalid nonce response and lets a later call fetch a new nonce', async () => {
+ const { request, get, fetch, nonceResponse, restResponse } =
+ mockAdminRequest();
+ nonceResponse.text.mockResolvedValueOnce( '0' );
+ const send = createAdminRestClient( request, 'https://example.com' );
+
+ await expect( send( 'wc/v3/products' ) ).rejects.toThrow(
+ 'REST nonce'
+ );
+ expect( fetch ).not.toHaveBeenCalled();
+ expect( nonceResponse.dispose ).toHaveBeenCalledTimes( 1 );
+
+ await expect( send( 'wc/v3/products' ) ).resolves.toBe( restResponse );
+ expect( get ).toHaveBeenCalledTimes( 2 );
+ } );
+
+ it( 'refreshes a stale nonce once for concurrent requests', async () => {
+ const { request, get, fetch, nonceResponse, restResponse } =
+ mockAdminRequest();
+ nonceResponse.text
+ .mockResolvedValueOnce( 'aaaaaaaaaa' )
+ .mockResolvedValueOnce( 'bbbbbbbbbb' );
+ const stale = {
+ status: () => 403,
+ json: jest.fn().mockResolvedValue( {
+ code: 'rest_cookie_invalid_nonce',
+ } ),
+ dispose: jest.fn().mockResolvedValue( undefined ),
+ };
+ fetch.mockResolvedValueOnce( stale ).mockResolvedValueOnce( stale );
+ const send = createAdminRestClient( request, 'https://example.com' );
+
+ await expect(
+ Promise.all( [
+ send( 'wc-bookings/v1/products' ),
+ send( 'wp/v2/pages', {
+ method: 'POST',
+ data: { title: 'Test' },
+ } ),
+ ] )
+ ).resolves.toEqual( [ restResponse, restResponse ] );
+
+ expect( get ).toHaveBeenCalledTimes( 2 );
+ expect( stale.dispose ).toHaveBeenCalledTimes( 2 );
+ expect(
+ fetch.mock.calls.map( ( [ , options ] ) => options.headers )
+ ).toEqual( [
+ { 'X-WP-Nonce': 'aaaaaaaaaa' },
+ { 'X-WP-Nonce': 'aaaaaaaaaa' },
+ { 'X-WP-Nonce': 'bbbbbbbbbb' },
+ { 'X-WP-Nonce': 'bbbbbbbbbb' },
+ ] );
+ } );
+
+ it.each( [
+ [ 'rest_cookie_invalid_nonce', 2 ],
+ [ 'rest_forbidden', 1 ],
+ ] )(
+ 'returns HTTP 403 with %s after %i attempt(s)',
+ async ( code, attempts ) => {
+ const { request, get, fetch } = mockAdminRequest();
+ const forbidden = {
+ status: () => 403,
+ json: jest.fn().mockResolvedValue( { code } ),
+ dispose: jest.fn().mockResolvedValue( undefined ),
+ };
+ fetch.mockResolvedValue( forbidden );
+ const send = createAdminRestClient(
+ request,
+ 'https://example.com'
+ );
+
+ await expect( send( 'wp/v2/pages' ) ).resolves.toBe( forbidden );
+ expect( get ).toHaveBeenCalledTimes( attempts );
+ expect( fetch ).toHaveBeenCalledTimes( attempts );
+ expect( forbidden.dispose ).toHaveBeenCalledTimes( attempts - 1 );
+ }
+ );
+
+ it( 'returns the original error for an upload stream and refreshes on the next request', async () => {
+ const { request, get, fetch, restResponse } = mockAdminRequest();
+ const stale = {
+ status: () => 403,
+ json: jest.fn().mockResolvedValue( {
+ code: 'rest_cookie_invalid_nonce',
+ } ),
+ dispose: jest.fn(),
+ };
+ fetch.mockResolvedValueOnce( stale );
+ const send = createAdminRestClient( request, 'https://example.com' );
+ const file = createReadStream( __filename );
+
+ try {
+ await expect(
+ send( 'wp/v2/media', { method: 'POST', multipart: { file } } )
+ ).resolves.toBe( stale );
+ expect( fetch ).toHaveBeenCalledTimes( 1 );
+ expect( stale.dispose ).not.toHaveBeenCalled();
+ await expect( send( 'wp/v2/pages' ) ).resolves.toBe( restResponse );
+ expect( get ).toHaveBeenCalledTimes( 2 );
+ } finally {
+ file.destroy();
+ }
+ } );
+
+ it( 'fetches a fresh nonce for a stream upload after the retry rejects its nonce', async () => {
+ const { request, get, fetch, nonceResponse, restResponse } =
+ mockAdminRequest();
+ nonceResponse.text
+ .mockResolvedValueOnce( 'aaaaaaaaaa' )
+ .mockResolvedValueOnce( 'bbbbbbbbbb' )
+ .mockResolvedValueOnce( 'cccccccccc' );
+ const stale = {
+ status: () => 403,
+ json: jest.fn().mockResolvedValue( {
+ code: 'rest_cookie_invalid_nonce',
+ } ),
+ dispose: jest.fn().mockResolvedValue( undefined ),
+ };
+ fetch.mockResolvedValueOnce( stale ).mockResolvedValueOnce( stale );
+ const send = createAdminRestClient( request, 'https://example.com' );
+
+ await expect( send( 'wp/v2/pages' ) ).resolves.toBe( stale );
+ expect( get ).toHaveBeenCalledTimes( 2 );
+
+ const file = createReadStream( __filename );
+ try {
+ await expect(
+ send( 'wp/v2/media', { method: 'POST', multipart: { file } } )
+ ).resolves.toBe( restResponse );
+ expect( fetch ).toHaveBeenLastCalledWith(
+ 'https://example.com/wp-json/wp/v2/media',
+ expect.objectContaining( {
+ headers: { 'X-WP-Nonce': 'cccccccccc' },
+ } )
+ );
+ expect( get ).toHaveBeenCalledTimes( 3 );
+ } finally {
+ file.destroy();
+ }
+ } );
+
+ it.each( [
+ 'https://other.example/orders',
+ '../wp-admin',
+ '%2e%2e/wp-admin',
+ ] )(
+ 'rejects a route outside the WordPress REST API: %s',
+ async ( route ) => {
+ const { request, get, fetch } = mockAdminRequest();
+ const send = createAdminRestClient(
+ request,
+ 'https://example.com'
+ );
+
+ await expect( send( route ) ).rejects.toThrow(
+ 'within the WordPress REST API'
+ );
+ expect( get ).not.toHaveBeenCalled();
+ expect( fetch ).not.toHaveBeenCalled();
+ }
+ );
+} );