diff --git a/backport-changelog/7.1/12264.md b/backport-changelog/7.1/12264.md new file mode 100644 index 00000000000000..c06c0f7dc10b71 --- /dev/null +++ b/backport-changelog/7.1/12264.md @@ -0,0 +1,3 @@ +https://github.com/WordPress/wordpress-develop/pull/12264 + +* https://github.com/WordPress/gutenberg/pull/79403 diff --git a/lib/compat/wordpress-7.0/class-wp-connector-registry.php b/lib/compat/wordpress-7.0/class-wp-connector-registry.php index 9a87875d4bf3c1..e42ca2c8d373a5 100644 --- a/lib/compat/wordpress-7.0/class-wp-connector-registry.php +++ b/lib/compat/wordpress-7.0/class-wp-connector-registry.php @@ -21,7 +21,7 @@ * logo_url?: non-empty-string, * type: non-empty-string, * authentication: array{ - * method: 'api_key'|'none', + * method: 'api_key'|'application_password'|'none', * credentials_url?: non-empty-string, * setting_name?: non-empty-string, * constant_name?: non-empty-string, @@ -57,12 +57,11 @@ final class WP_Connector_Registry { * Registers a new connector. * * Validates the provided arguments and stores the connector in the registry. - * For connectors with `api_key` authentication, a `setting_name` can be provided - * explicitly. If omitted, one is automatically generated using the pattern - * `connectors_{$type}_{$id}_api_key`, with hyphens in the type and ID normalized - * to underscores (e.g., connector type `spam_filtering` with ID `akismet` produces - * `connectors_spam_filtering_akismet_api_key`). This setting name is used for the - * Settings API registration and REST API exposure. + * For connectors with `api_key` or `application_password` authentication, a + * `setting_name` can be provided explicitly. When omitted, setting names are + * automatically generated using the pattern `connectors_{$type}_{$id}_{$method}`, + * with hyphens in the type and ID normalized to underscores. These setting + * names are used for Settings API registration and REST API exposure. * * Registering a connector with an ID that is already registered will trigger a * `_doing_it_wrong()` notice and return `null`. To override an existing connector, @@ -84,16 +83,24 @@ final class WP_Connector_Registry { * @type array $authentication { * Required. Authentication configuration. * - * @type string $method Required. The authentication method: 'api_key' or 'none'. + * @type string $method Required. The authentication method: 'api_key', + * 'application_password', or 'none'. * @type string $credentials_url Optional. URL where users can obtain API credentials. - * @type string $setting_name Optional. The setting name for the API key. - * When omitted, auto-generated as - * `connectors_{$type}_{$id}_api_key`. + * @type string $setting_name Optional. The setting name for the API key + * or application-password credentials. When + * omitted, auto-generated as + * `connectors_{$type}_{$id}_api_key` for API + * keys and `connectors_{$type}_{$id}_application_password` + * for application passwords. * Must be a non-empty string when provided. * @type string $constant_name Optional. PHP constant name for the API key - * (e.g. 'ANTHROPIC_API_KEY'). Only checked when provided. + * (e.g. 'ANTHROPIC_API_KEY') or for application-password + * credentials in `username:password` format. Only checked + * when provided. * @type string $env_var_name Optional. Environment variable name for the API key - * (e.g. 'ANTHROPIC_API_KEY'). Only checked when provided. + * (e.g. 'ANTHROPIC_API_KEY') or for application-password + * credentials in `username:password` format. Only checked + * when provided. * } * @type array $plugin { * Optional. Plugin data for install/activate UI. @@ -114,7 +121,7 @@ final class WP_Connector_Registry { * logo_url?: non-empty-string, * type: non-empty-string, * authentication: array{ - * method: 'api_key'|'none', + * method: 'api_key'|'application_password'|'none', * credentials_url?: non-empty-string, * setting_name?: non-empty-string, * constant_name?: non-empty-string, @@ -180,11 +187,11 @@ public function register( string $id, array $args ): ?array { return null; } - if ( empty( $args['authentication']['method'] ) || ! in_array( $args['authentication']['method'], array( 'api_key', 'none' ), true ) ) { + if ( empty( $args['authentication']['method'] ) || ! in_array( $args['authentication']['method'], array( 'api_key', 'application_password', 'none' ), true ) ) { _doing_it_wrong( __METHOD__, /* translators: %s: Connector ID. */ - sprintf( __( 'Connector "%s" authentication method must be "api_key" or "none".' ), esc_html( $id ) ), + sprintf( __( 'Connector "%s" authentication method must be "api_key", "application_password", or "none".' ), esc_html( $id ) ), '7.0.0' ); return null; @@ -208,10 +215,13 @@ public function register( string $id, array $args ): ?array { $connector['logo_url'] = $args['logo_url']; } - if ( 'api_key' === $args['authentication']['method'] ) { + $requires_credentials = in_array( $args['authentication']['method'], array( 'api_key', 'application_password' ), true ); + + if ( $requires_credentials ) { if ( ! empty( $args['authentication']['credentials_url'] ) && is_string( $args['authentication']['credentials_url'] ) ) { $connector['authentication']['credentials_url'] = $args['authentication']['credentials_url']; } + if ( isset( $args['authentication']['setting_name'] ) ) { if ( ! is_string( $args['authentication']['setting_name'] ) || '' === $args['authentication']['setting_name'] ) { _doing_it_wrong( @@ -224,8 +234,9 @@ public function register( string $id, array $args ): ?array { } $connector['authentication']['setting_name'] = $args['authentication']['setting_name']; } else { - $connector['authentication']['setting_name'] = str_replace( '-', '_', "connectors_{$connector['type']}_{$id}_api_key" ); + $connector['authentication']['setting_name'] = str_replace( '-', '_', "connectors_{$connector['type']}_{$id}_{$args['authentication']['method']}" ); } + if ( isset( $args['authentication']['constant_name'] ) ) { if ( ! is_string( $args['authentication']['constant_name'] ) || '' === $args['authentication']['constant_name'] ) { _doing_it_wrong( diff --git a/lib/compat/wordpress-7.0/connectors.php b/lib/compat/wordpress-7.0/connectors.php index b37fd5b71cb73d..48b95ba4bb7e2e 100644 --- a/lib/compat/wordpress-7.0/connectors.php +++ b/lib/compat/wordpress-7.0/connectors.php @@ -44,15 +44,17 @@ function wp_is_connector_registered( string $id ): bool { * @type string $logo_url Optional. URL to the connector's logo image. * @type string $type The connector type, e.g. 'ai_provider' or 'spam_filtering'. * @type array $authentication { - * Authentication configuration. When method is 'api_key', includes - * credentials_url, setting_name, and optionally constant_name and - * env_var_name. When 'none', only method is present. + * Authentication configuration. When method is 'api_key' or + * 'application_password', includes credentials_url, setting_name, and + * optionally constant_name and env_var_name. When 'none', only method + * is present. * - * @type string $method The authentication method: 'api_key' or 'none'. + * @type string $method The authentication method: 'api_key', + * 'application_password', or 'none'. * @type string $credentials_url Optional. URL where users can obtain API credentials. - * @type string $setting_name Optional. The setting name for the API key. - * @type string $constant_name Optional. PHP constant name for the API key. - * @type string $env_var_name Optional. Environment variable name for the API key. + * @type string $setting_name Optional. The setting name for the API key or application-password credentials. + * @type string $constant_name Optional. PHP constant name for the API key or application-password credentials. + * @type string $env_var_name Optional. Environment variable name for the API key or application-password credentials. * } * @type array $plugin { * Optional. Plugin data for install/activate UI. @@ -69,7 +71,7 @@ function wp_is_connector_registered( string $id ): bool { * logo_url?: non-empty-string, * type: non-empty-string, * authentication: array{ - * method: 'api_key'|'none', + * method: 'api_key'|'application_password'|'none', * credentials_url?: non-empty-string, * setting_name?: non-empty-string, * constant_name?: non-empty-string, @@ -110,15 +112,17 @@ function wp_get_connector( string $id ): ?array { * @type string $logo_url Optional. URL to the connector's logo image. * @type string $type The connector type, e.g. 'ai_provider' or 'spam_filtering'. * @type array $authentication { - * Authentication configuration. When method is 'api_key', includes - * credentials_url, setting_name, and optionally constant_name and - * env_var_name. When 'none', only method is present. + * Authentication configuration. When method is 'api_key' or + * 'application_password', includes credentials_url, setting_name, + * and optionally constant_name and env_var_name. When 'none', only + * method is present. * - * @type string $method The authentication method: 'api_key' or 'none'. + * @type string $method The authentication method: 'api_key', + * 'application_password', or 'none'. * @type string $credentials_url Optional. URL where users can obtain API credentials. - * @type string $setting_name Optional. The setting name for the API key. - * @type string $constant_name Optional. PHP constant name for the API key. - * @type string $env_var_name Optional. Environment variable name for the API key. + * @type string $setting_name Optional. The setting name for the API key or application-password credentials. + * @type string $constant_name Optional. PHP constant name for the API key or application-password credentials. + * @type string $env_var_name Optional. Environment variable name for the API key or application-password credentials. * } * @type array $plugin { * Optional. Plugin data for install/activate UI. @@ -136,7 +140,7 @@ function wp_get_connector( string $id ): ?array { * logo_url?: non-empty-string, * type: non-empty-string, * authentication: array{ - * method: 'api_key'|'none', + * method: 'api_key'|'application_password'|'none', * credentials_url?: non-empty-string, * setting_name?: non-empty-string, * constant_name?: non-empty-string, diff --git a/lib/compat/wordpress-7.0/default-connectors.php b/lib/compat/wordpress-7.0/default-connectors.php index 04eac230361b95..7719aadc10a929 100644 --- a/lib/compat/wordpress-7.0/default-connectors.php +++ b/lib/compat/wordpress-7.0/default-connectors.php @@ -252,6 +252,115 @@ function _gutenberg_get_api_key_source( string $setting_name, string $env_var_na return 'none'; } +/** + * Parses a `username:password` credentials string. + * + * Splits on the first colon, matching the HTTP Basic authentication + * userinfo format, so passwords may contain colons. + * + * @access private + * + * @param string $value The raw credentials string. + * @return array{username: string, password: string} Parsed credentials. Both values + * are empty when the string is malformed. + */ +function _gutenberg_parse_application_password_credentials( string $value ): array { + $separator = strpos( $value, ':' ); + // Trim so surrounding whitespace or a trailing newline (common when the + // value comes from a file or `.env`) does not become part of the credentials. + $username = false === $separator ? '' : trim( substr( $value, 0, $separator ) ); + $password = false === $separator ? '' : trim( substr( $value, $separator + 1 ) ); + + if ( '' === $username || '' === $password ) { + return array( + 'username' => '', + 'password' => '', + ); + } + + return array( + 'username' => $username, + 'password' => $password, + ); +} + +/** + * Resolves application-password credentials for a connector. + * + * Checks in order: environment variable, PHP constant, database. The + * environment variable and constant are only checked when their respective + * names are provided, and must contain the credentials as a single + * `username:password` string. A non-empty environment variable or constant + * that cannot be parsed as `username:password` is reported with + * `_doing_it_wrong()` and ignored, so resolution falls through to the next + * source. + * + * @access private + * + * @param array $auth The connector's authentication configuration. + * @return array{username: string, password: string, source: string} Resolved credentials and + * their source: 'env', 'constant', + * 'database', or 'none'. + */ +function _gutenberg_get_application_password_credentials( array $auth ): array { + // Check environment variable (only if explicitly configured). + $env_var_name = $auth['env_var_name'] ?? ''; + if ( '' !== $env_var_name ) { + $env_value = getenv( $env_var_name ); + if ( false !== $env_value && '' !== $env_value ) { + $credentials = _gutenberg_parse_application_password_credentials( $env_value ); + if ( '' !== $credentials['username'] && '' !== $credentials['password'] ) { + $credentials['source'] = 'env'; + return $credentials; + } + + _doing_it_wrong( + __FUNCTION__, + sprintf( + /* translators: %s: Environment variable name. */ + __( 'The %s environment variable must contain application password credentials in "username:password" format.', 'gutenberg' ), + esc_html( $env_var_name ) + ), + '7.0.0' + ); + } + } + + // Check PHP constant (only if explicitly configured). + $constant_name = $auth['constant_name'] ?? ''; + if ( '' !== $constant_name && defined( $constant_name ) ) { + $const_value = constant( $constant_name ); + if ( is_string( $const_value ) && '' !== $const_value ) { + $credentials = _gutenberg_parse_application_password_credentials( $const_value ); + if ( '' !== $credentials['username'] && '' !== $credentials['password'] ) { + $credentials['source'] = 'constant'; + return $credentials; + } + + _doing_it_wrong( + __FUNCTION__, + sprintf( + /* translators: %s: PHP constant name. */ + __( 'The %s constant must contain application password credentials in "username:password" format.', 'gutenberg' ), + esc_html( $constant_name ) + ), + '7.0.0' + ); + } + } + + // Check database. + $stored = get_option( $auth['setting_name'] ?? '', array() ); + $username = is_array( $stored ) && isset( $stored['username'] ) && is_string( $stored['username'] ) ? $stored['username'] : ''; + $password = is_array( $stored ) && isset( $stored['password'] ) && is_string( $stored['password'] ) ? $stored['password'] : ''; + + return array( + 'username' => $username, + 'password' => $password, + 'source' => '' !== $username && '' !== $password ? 'database' : 'none', + ); +} + /** * Masks an API key, showing only the last 4 characters. * @@ -307,13 +416,72 @@ function _gutenberg_is_ai_api_key_valid( string $key, string $provider_id ): ?bo } /** - * Masks and validates connector API keys in REST responses. + * Sanitizes stored application-password credentials for a connector. + * + * Credential fields that are missing or not strings keep their currently + * stored values, so partial updates cannot silently clear a stored secret. + * A password matching the mask that `_gutenberg_connectors_rest_settings_dispatch()` + * places in REST responses also keeps the stored password, so a masked + * settings response can be submitted back to the endpoint unchanged. + * Pass an empty string to clear a field. + * If the sanitized username is empty, both fields are discarded so partial + * credentials cannot leave an orphaned secret. + * + * @access private + * + * @param mixed $value The submitted setting value. + * @param string $option The option name being sanitized. Passed explicitly by the + * registered sanitize callback; falls back to the current + * `sanitize_option_{$option}` filter name when omitted. + * @return array{username: string, password: string} Sanitized credentials. + */ +function _gutenberg_sanitize_application_password_credentials( $value, string $option = '' ): array { + if ( ! is_array( $value ) ) { + $value = array(); + } + + if ( '' === $option ) { + $option = str_replace( 'sanitize_option_', '', (string) current_filter() ); + } + + $stored = get_option( $option ); + if ( ! is_array( $stored ) ) { + $stored = array(); + } + + $credentials = array(); + foreach ( array( 'username', 'password' ) as $field ) { + if ( isset( $value[ $field ] ) && is_string( $value[ $field ] ) ) { + $credentials[ $field ] = sanitize_text_field( $value[ $field ] ); + } else { + $credentials[ $field ] = isset( $stored[ $field ] ) && is_string( $stored[ $field ] ) ? $stored[ $field ] : ''; + } + } + + // A masked password means a client resubmitted a masked REST response. + if ( str_repeat( "\u{2022}", 16 ) === $credentials['password'] ) { + $credentials['password'] = isset( $stored['password'] ) && is_string( $stored['password'] ) ? $stored['password'] : ''; + } + + if ( '' === $credentials['username'] ) { + return array( + 'username' => '', + 'password' => '', + ); + } + + return $credentials; +} + +/** + * Masks and validates connector credentials in REST responses. * - * On every `/wp/v2/settings` response, masks connector API key values so raw - * keys are never exposed via the REST API. + * On every `/wp/v2/settings` response, masks connector API key values and the + * password field of default application-password credential objects. * - * On POST or PUT requests, validates each updated key against the provider - * before masking. If validation fails, the key is reverted to an empty string. + * On POST or PUT requests, validates each updated AI provider API key before + * masking. If validation fails, the key is reverted to an empty string. + * Application password values are masked but not validated. * * @access private * @@ -340,6 +508,18 @@ function _gutenberg_connectors_rest_settings_dispatch( WP_REST_Response $respons foreach ( wp_get_connectors() as $connector_id => $connector_data ) { $auth = $connector_data['authentication']; + + if ( 'application_password' === $auth['method'] && ! empty( $auth['setting_name'] ) ) { + $setting_name = $auth['setting_name']; + if ( array_key_exists( $setting_name, $data ) && is_array( $data[ $setting_name ] ) ) { + $password = $data[ $setting_name ]['password'] ?? ''; + if ( is_string( $password ) && '' !== $password ) { + $data[ $setting_name ]['password'] = str_repeat( "\u{2022}", 16 ); + } + } + continue; + } + if ( 'api_key' !== $auth['method'] || empty( $auth['setting_name'] ) ) { continue; } @@ -384,14 +564,14 @@ function _gutenberg_register_default_connector_settings(): void { foreach ( wp_get_connectors() as $connector_data ) { $auth = $connector_data['authentication']; - if ( 'api_key' !== $auth['method'] || empty( $auth['setting_name'] ) ) { + if ( 'api_key' !== $auth['method'] && 'application_password' !== $auth['method'] ) { continue; } - // Skip if the setting is already registered (e.g. by the connector's plugin). - if ( isset( $existing_settings[ $auth['setting_name'] ] ) ) { + if ( empty( $auth['setting_name'] ) || isset( $existing_settings[ $auth['setting_name'] ] ) ) { continue; } + $setting_name = $auth['setting_name']; if ( ! isset( $connector_data['plugin']['is_active'] ) || ! is_callable( $connector_data['plugin']['is_active'] ) ) { continue; @@ -401,26 +581,67 @@ function _gutenberg_register_default_connector_settings(): void { continue; } - register_setting( - 'connectors', - $auth['setting_name'], - array( - 'type' => 'string', - 'label' => sprintf( - /* translators: %s: Connector name. */ - __( '%s API Key', 'gutenberg' ), - $connector_data['name'] - ), - 'description' => sprintf( - /* translators: %s: Connector name. */ - __( 'API key for the %s connector.', 'gutenberg' ), - $connector_data['name'] - ), - 'default' => '', - 'show_in_rest' => true, - 'sanitize_callback' => 'sanitize_text_field', - ) - ); + if ( 'api_key' === $auth['method'] ) { + register_setting( + 'connectors', + $setting_name, + array( + 'type' => 'string', + 'label' => sprintf( + /* translators: %s: Connector name. */ + __( '%s API Key', 'gutenberg' ), + $connector_data['name'] + ), + 'description' => sprintf( + /* translators: %s: Connector name. */ + __( 'API key for the %s connector.', 'gutenberg' ), + $connector_data['name'] + ), + 'default' => '', + 'show_in_rest' => true, + 'sanitize_callback' => 'sanitize_text_field', + ) + ); + } elseif ( 'application_password' === $auth['method'] ) { + register_setting( + 'connectors', + $setting_name, + array( + 'type' => 'object', + 'label' => sprintf( + /* translators: %s: Connector name. */ + __( '%s Credentials', 'gutenberg' ), + $connector_data['name'] + ), + 'description' => sprintf( + /* translators: %s: Connector name. */ + __( 'Application password credentials for the %s connector.', 'gutenberg' ), + $connector_data['name'] + ), + 'default' => array( + 'username' => '', + 'password' => '', + ), + 'show_in_rest' => array( + 'schema' => array( + 'type' => 'object', + 'properties' => array( + 'username' => array( + 'type' => 'string', + ), + 'password' => array( + 'type' => 'string', + ), + ), + 'additionalProperties' => false, + ), + ), + 'sanitize_callback' => static function ( $value ) use ( $setting_name ) { + return _gutenberg_sanitize_application_password_credentials( $value, $setting_name ); + }, + ) + ); + } } } remove_action( 'init', '_wp_register_default_connector_settings', 20 ); @@ -522,6 +743,13 @@ function _gutenberg_get_connector_script_module_data( array $data ): array { // For non-AI connectors, consider connected if a key exists from any source. $auth_out['isConnected'] = 'none' !== $auth_out['keySource']; } + } elseif ( 'application_password' === $auth['method'] ) { + $credentials = _gutenberg_get_application_password_credentials( $auth ); + + $auth_out['settingName'] = $auth['setting_name'] ?? ''; + $auth_out['credentialsUrl'] = $auth['credentials_url'] ?? null; + $auth_out['keySource'] = $credentials['source']; + $auth_out['isConnected'] = '' !== $credentials['username'] && '' !== $credentials['password']; } $connector_out = array( diff --git a/packages/connectors/src/connector-item.tsx b/packages/connectors/src/connector-item.tsx index 8be97371363c92..6e5d34a957b093 100644 --- a/packages/connectors/src/connector-item.tsx +++ b/packages/connectors/src/connector-item.tsx @@ -12,7 +12,7 @@ import { TextControl, } from '@wordpress/components'; import { createInterpolateElement, useId, useState } from '@wordpress/element'; -import { __, sprintf } from '@wordpress/i18n'; +import { __, sprintf, type TransformedText } from '@wordpress/i18n'; /** * Internal dependencies @@ -68,6 +68,142 @@ export function ConnectorItem( { export type { ApiKeySource } from './types'; +type ConnectorHelpMessage = + | `${ string }%s${ string }` + | TransformedText< `${ string }%s${ string }` >; +type ConnectorHelpInterpolatedMessage = `${ string }${ string }`; + +function getHelpLinkLabel( helpUrl?: string, helpLabel?: string ) { + if ( helpLabel ) { + return helpLabel; + } + if ( ! helpUrl ) { + return undefined; + } + try { + return new URL( helpUrl ).hostname; + } catch { + return helpUrl; + } +} + +function createConnectorHelpLink( + helpUrl: string | undefined, + helpLabel: string | undefined, + message: ConnectorHelpMessage +) { + if ( ! helpUrl ) { + return undefined; + } + + return createInterpolateElement( + sprintf( message, '' ) as ConnectorHelpInterpolatedMessage, + { + a: ( + + { getHelpLinkLabel( helpUrl, helpLabel ) } + + ), + } + ); +} + +function useConnectorSettingsSave< TValue >( + onSave: ( ( value: TValue ) => void | Promise< void > ) | undefined, + fallbackErrorMessage: string +) { + const [ isSaving, setIsSaving ] = useState( false ); + const [ saveError, setSaveError ] = useState< string | null >( null ); + + const handleSave = async ( value: TValue ) => { + setSaveError( null ); + setIsSaving( true ); + try { + await onSave?.( value ); + } catch ( error ) { + setSaveError( + error instanceof Error ? error.message : fallbackErrorMessage + ); + } finally { + setIsSaving( false ); + } + }; + + return { + isSaving, + saveError, + setSaveError, + handleSave, + }; +} + +function ConnectorSettingsFrame( { + readOnly, + children, +}: { + readOnly: boolean; + children: ReactNode; +} ) { + return ( + + { children } + + ); +} + +function ConnectorSettingsFooter( { + readOnly, + onRemove, + canSave, + isSaving, + onSave, +}: { + readOnly: boolean; + onRemove?: () => void; + canSave: boolean; + isSaving: boolean; + onSave: () => void; +} ) { + if ( readOnly ) { + if ( ! onRemove ) { + return null; + } + + return ( + + + + ); + } + + return ( + + + + ); +} + export interface DefaultConnectorSettingsProps { onSave?: ( apiKey: string ) => void | Promise< void >; onRemove?: () => void; @@ -86,7 +222,7 @@ export interface DefaultConnectorSettingsProps { * @param props.onRemove - Callback invoked when the user removes the connector. * @param props.initialValue - Initial value for the API key field. * @param props.helpUrl - URL to documentation for obtaining an API key. - * @param props.helpLabel - Custom label for the help link. Defaults to the URL without protocol. + * @param props.helpLabel - Custom label for the help link. Defaults to the URL's hostname. * @param props.readOnly - Whether the form is in read-only mode. * @param props.keySource - The source of the API key: 'env', 'constant', 'database', or 'none'. */ @@ -100,27 +236,20 @@ export function DefaultConnectorSettings( { keySource, }: DefaultConnectorSettingsProps ) { const [ apiKey, setApiKey ] = useState( initialValue ); - const [ isSaving, setIsSaving ] = useState( false ); - const [ saveError, setSaveError ] = useState< string | null >( null ); + const { isSaving, saveError, setSaveError, handleSave } = + useConnectorSettingsSave( + onSave, + __( + 'It was not possible to connect to the provider using this key.' + ) + ); - const helpLinkLabel = helpLabel || helpUrl?.replace( /^https?:\/\//, '' ); - - const helpLink = helpUrl - ? createInterpolateElement( - sprintf( - /* translators: %s: Link to provider settings. */ - __( 'Get your API key at %s' ), - '' - ), - { - a: ( - - { helpLinkLabel } - - ), - } - ) - : undefined; + const helpLink = createConnectorHelpLink( + helpUrl, + helpLabel, + /* translators: %s: Link to provider settings. */ + __( 'Get your API key at %s' ) + ); const isExternallyConfigured = keySource === 'env' || keySource === 'constant'; @@ -138,21 +267,13 @@ export function DefaultConnectorSettings( { } if ( readOnly ) { return helpUrl - ? createInterpolateElement( - sprintf( - /* translators: %s: Link to provider settings. */ - __( - 'Your API key is stored securely. You can manage it at %s' - ), - '' - ), - { - a: ( - - { helpLinkLabel } - - ), - } + ? createConnectorHelpLink( + helpUrl, + helpLabel, + /* translators: %s: Link to provider settings. */ + __( + 'Your API key is stored securely. You can manage it at %s' + ) ) : __( 'Your API key is stored securely.' ); } @@ -166,36 +287,8 @@ export function DefaultConnectorSettings( { return helpLink; }; - const handleSave = async () => { - setSaveError( null ); - setIsSaving( true ); - try { - await onSave?.( apiKey ); - } catch ( error ) { - setSaveError( - error instanceof Error - ? error.message - : __( - 'It was not possible to connect to the provider using this key.' - ) - ); - } finally { - setIsSaving( false ); - } - }; - return ( - + - { readOnly ? ( - onRemove && ( - - - - ) - ) : ( - - - - ) } - + handleSave( apiKey ) } + /> + + ); +} + +export interface ApplicationPasswordCredentials { + username: string; + applicationPassword: string; +} + +export interface ApplicationPasswordConnectorSettingsProps { + onSave?: ( + credentials: ApplicationPasswordCredentials + ) => void | Promise< void >; + onRemove?: () => void; + initialUsername?: string; + helpUrl?: string; + helpLabel?: string; + readOnly?: boolean; + keySource?: ApiKeySource; +} + +/** + * Default settings form for application password connectors. + * + * @param props - Component props. + * @param props.onSave - Callback invoked with the username and application password. + * @param props.onRemove - Callback invoked when the credentials are removed. + * @param props.initialUsername - Initial value for the username field. + * @param props.helpUrl - URL where users can create an application password. + * @param props.helpLabel - Custom label for the help link. Defaults to the URL's hostname. + * @param props.readOnly - Whether the form is in read-only mode. + * @param props.keySource - The source of the credentials: 'env', 'constant', 'database', or 'none'. + */ +export function ApplicationPasswordConnectorSettings( { + onSave, + onRemove, + initialUsername = '', + helpUrl, + helpLabel, + readOnly = false, + keySource, +}: ApplicationPasswordConnectorSettingsProps ) { + const [ username, setUsername ] = useState( initialUsername ); + const [ applicationPassword, setApplicationPassword ] = useState( '' ); + const { isSaving, saveError, setSaveError, handleSave } = + useConnectorSettingsSave< ApplicationPasswordCredentials >( + onSave, + __( 'It was not possible to save these credentials.' ) + ); + + const help = createConnectorHelpLink( + helpUrl, + helpLabel, + /* translators: %s: Link to the remote site's application passwords screen. */ + __( 'Create an application password at %s' ) + ); + + let applicationPasswordHelp: ReactNode = help; + if ( keySource === 'env' ) { + applicationPasswordHelp = __( + 'These credentials are configured using an environment variable.' + ); + } else if ( keySource === 'constant' ) { + applicationPasswordHelp = __( + 'These credentials are configured as a constant.' + ); + } else if ( readOnly ) { + applicationPasswordHelp = __( + 'Your application password is stored securely.' + ); + } + if ( saveError ) { + applicationPasswordHelp = ( + + { saveError } + + ); + } + + return ( + + { + if ( ! readOnly ) { + setSaveError( null ); + setUsername( value ); + } + } } + placeholder={ __( 'Enter your username' ) } + disabled={ readOnly || isSaving } + autoComplete="username" + /> + { + if ( ! readOnly ) { + setSaveError( null ); + setApplicationPassword( value ); + } + } } + type="password" + placeholder={ __( 'Enter your application password' ) } + disabled={ readOnly || isSaving } + autoComplete="new-password" + help={ applicationPasswordHelp } + /> + + handleSave( { + username: username.trim(), + applicationPassword, + } ) + } + /> + ); } diff --git a/packages/connectors/src/index.ts b/packages/connectors/src/index.ts index cf06f27e9de197..04a30144f3efd0 100644 --- a/packages/connectors/src/index.ts +++ b/packages/connectors/src/index.ts @@ -5,6 +5,7 @@ export { export { ConnectorItem as __experimentalConnectorItem, DefaultConnectorSettings as __experimentalDefaultConnectorSettings, + ApplicationPasswordConnectorSettings as __experimentalApplicationPasswordConnectorSettings, } from './connector-item'; export type { ApiKeySource as __experimentalApiKeySource } from './types'; export type { ConnectorConfig, ConnectorRenderProps } from './types'; diff --git a/packages/connectors/src/types.ts b/packages/connectors/src/types.ts index d6e8969aae58d1..e5b7bd686cb08a 100644 --- a/packages/connectors/src/types.ts +++ b/packages/connectors/src/types.ts @@ -13,6 +13,13 @@ export type ConnectorAuthentication = keySource?: ApiKeySource; isConnected?: boolean; } + | { + method: 'application_password'; + settingName: string; + credentialsUrl: string | null; + keySource?: ApiKeySource; + isConnected?: boolean; + } | { method: 'none' }; export interface ConnectorPlugin { diff --git a/packages/e2e-tests/plugins/connectors-application-password.php b/packages/e2e-tests/plugins/connectors-application-password.php new file mode 100644 index 00000000000000..a73eee537fa30f --- /dev/null +++ b/packages/e2e-tests/plugins/connectors-application-password.php @@ -0,0 +1,100 @@ +register( + 'test-remote-wordpress', + array( + 'name' => 'Test Remote WordPress', + 'description' => 'Connect to example.com as a remote WordPress site.', + 'type' => 'content_source', + 'authentication' => array( + 'method' => 'application_password', + 'credentials_url' => 'https://example.com/wp-admin/profile.php', + 'setting_name' => GUTENBERG_TEST_CONNECTOR_CREDENTIALS_SETTING, + ), + ) + ); + + $registry->register( + 'test-env-configured-wordpress', + array( + 'name' => 'Test Env Configured WordPress', + 'description' => 'Connects using environment-variable credentials.', + 'type' => 'content_source', + 'authentication' => array( + 'method' => 'application_password', + 'env_var_name' => GUTENBERG_TEST_CONNECTOR_ENV_VAR_NAME, + ), + ) + ); + } +); + +add_action( + 'rest_api_init', + static function () { + register_rest_route( + 'gutenberg-test-connectors/v1', + '/application-password', + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => static function () { + return array( + 'is_registered' => wp_is_connector_registered( + 'test-remote-wordpress' + ), + ); + }, + 'permission_callback' => static function () { + return current_user_can( 'manage_options' ); + }, + ) + ); + + // Exposes the raw stored credentials so tests can assert what was + // persisted, bypassing the masking applied to /wp/v2/settings. + register_rest_route( + 'gutenberg-test-connectors/v1', + '/application-password-credentials', + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => static function () { + $credentials = get_option( + GUTENBERG_TEST_CONNECTOR_CREDENTIALS_SETTING, + array() + ); + return array( + 'username' => is_array( $credentials ) && isset( $credentials['username'] ) ? $credentials['username'] : '', + 'password' => is_array( $credentials ) && isset( $credentials['password'] ) ? $credentials['password'] : '', + ); + }, + 'permission_callback' => static function () { + return current_user_can( 'manage_options' ); + }, + ) + ); + } +); + +register_deactivation_hook( + __FILE__, + static function () { + delete_option( GUTENBERG_TEST_CONNECTOR_CREDENTIALS_SETTING ); + } +); diff --git a/routes/connectors-home/default-connectors.tsx b/routes/connectors-home/default-connectors.tsx index 5c23fe67eaa49b..fa8253457805b2 100644 --- a/routes/connectors-home/default-connectors.tsx +++ b/routes/connectors-home/default-connectors.tsx @@ -7,6 +7,7 @@ import { __experimentalRegisterConnector as registerConnector, __experimentalConnectorItem as ConnectorItem, __experimentalDefaultConnectorSettings as DefaultConnectorSettings, + __experimentalApplicationPasswordConnectorSettings as ApplicationPasswordConnectorSettings, privateApis as connectorsPrivateApis, type ConnectorConfig, type ConnectorRenderProps, @@ -19,7 +20,7 @@ import { unlock } from '@wordpress/routes-lock-unlock'; /** * Internal dependencies */ -import { useConnectorPlugin } from './use-connector-plugin'; +import { useConnectorPlugin, type PluginStatus } from './use-connector-plugin'; import { OpenAILogo, ClaudeLogo, @@ -123,6 +124,66 @@ const PluginDirectoryLink = ( { slug }: { slug: string } ) => ( const UnavailableActionBadge = () => { __( 'Not available' ) }; +interface ConnectorActionAreaProps { + isConnected: boolean; + showUnavailableBadge: boolean; + pluginSlug?: string; + isExpanded: boolean; + isBusy: boolean; + pluginStatus: PluginStatus; + actionButtonRef: { + current: HTMLButtonElement | null; + }; + handleButtonClick: () => void; + getButtonLabel: () => string; +} + +function ConnectorActionArea( { + isConnected, + showUnavailableBadge, + pluginSlug, + isExpanded, + isBusy, + pluginStatus, + actionButtonRef, + handleButtonClick, + getButtonLabel, +}: ConnectorActionAreaProps ) { + return ( + + { isConnected && } + { showUnavailableBadge && + ( pluginSlug ? ( + + ) : ( + + ) ) } + { ! showUnavailableBadge && ( + + ) } + + ); +} + +function getPluginSlug( pluginFile?: string ) { + const pluginBasename = pluginFile?.replace( /\.php$/, '' ); + return pluginBasename?.includes( '/' ) + ? pluginBasename.split( '/' )[ 0 ] + : pluginBasename; +} + function ApiKeyConnector( { name, description, @@ -134,19 +195,7 @@ function ApiKeyConnector( { authentication?.method === 'api_key' ? authentication : undefined; const settingName = auth?.settingName ?? ''; const helpUrl = auth?.credentialsUrl ?? undefined; - const pluginFile = plugin?.file?.replace( /\.php$/, '' ); - const pluginSlug = pluginFile?.includes( '/' ) - ? pluginFile.split( '/' )[ 0 ] - : pluginFile; - - let helpLabel: string | undefined; - try { - if ( helpUrl ) { - helpLabel = new URL( helpUrl ).hostname; - } - } catch { - // Invalid URL — leave helpLabel undefined. - } + const pluginSlug = getPluginSlug( plugin?.file ); const { pluginStatus, @@ -157,6 +206,7 @@ function ApiKeyConnector( { isBusy, isConnected, currentApiKey, + hasResolvedSettings, keySource, handleButtonClick, getButtonLabel, @@ -176,7 +226,6 @@ function ApiKeyConnector( { const showUnavailableBadge = ( pluginStatus === 'not-installed' && canInstallPlugins === false ) || ( pluginStatus === 'inactive' && canActivatePlugins === false ); - const showActionButton = ! showUnavailableBadge; const actionButtonRef = useRef< HTMLButtonElement >( null ); @@ -189,61 +238,148 @@ function ApiKeyConnector( { name={ name } description={ description } actionArea={ - - { isConnected && } - { showUnavailableBadge && - ( pluginSlug ? ( - - ) : ( - - ) ) } - { showActionButton && ( - - ) } - + } > - { isExpanded && pluginStatus === 'active' && ( - { - await removeApiKey(); - actionButtonRef.current?.focus(); - } - } - onSave={ async ( apiKey: string ) => { - await saveApiKey( apiKey ); - setIsExpanded( false ); - actionButtonRef.current?.focus(); - } } + { isExpanded && + pluginStatus === 'active' && + hasResolvedSettings && ( + { + await removeApiKey(); + actionButtonRef.current?.focus(); + } + } + onSave={ async ( apiKey: string ) => { + await saveApiKey( apiKey ); + setIsExpanded( false ); + actionButtonRef.current?.focus(); + } } + /> + ) } + + ); +} + +function ApplicationPasswordConnector( { + name, + description, + logo, + authentication, + plugin, +}: ConnectorRenderProps ) { + const auth = + authentication?.method === 'application_password' + ? authentication + : undefined; + const settingName = auth?.settingName ?? ''; + const helpUrl = auth?.credentialsUrl ?? undefined; + const pluginSlug = getPluginSlug( plugin?.file ); + + const { + pluginStatus, + canInstallPlugins, + canActivatePlugins, + isExpanded, + setIsExpanded, + isBusy, + isConnected, + currentUsername, + hasResolvedSettings, + keySource, + handleButtonClick, + getButtonLabel, + saveCredentials, + removeCredentials, + } = useConnectorPlugin( { + file: plugin?.file, + settingName, + connectorName: name, + isInstalled: plugin?.isInstalled, + isActivated: plugin?.isActivated, + keySource: auth?.keySource, + initialIsConnected: auth?.isConnected, + } ); + const isExternallyConfigured = + keySource === 'env' || keySource === 'constant'; + + const actionButtonRef = useRef< HTMLButtonElement >( null ); + const showUnavailableBadge = + ( pluginStatus === 'not-installed' && canInstallPlugins === false ) || + ( pluginStatus === 'inactive' && canActivatePlugins === false ); + + return ( + - ) } + } + > + { isExpanded && + pluginStatus === 'active' && + hasResolvedSettings && ( + { + await removeCredentials(); + actionButtonRef.current?.focus(); + } + } + onSave={ async ( credentials ) => { + await saveCredentials( credentials ); + setIsExpanded( false ); + actionButtonRef.current?.focus(); + } } + /> + ) } ); } @@ -281,6 +417,11 @@ export function registerDefaultConnectors() { ); if ( authentication.method === 'api_key' && ! existing?.render ) { args.render = ApiKeyConnector; + } else if ( + authentication.method === 'application_password' && + ! existing?.render + ) { + args.render = ApplicationPasswordConnector; } registerConnector( connectorName, args ); diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 836752b6e65916..7c717978b11fd6 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -11,6 +11,13 @@ import type { __experimentalApiKeySource as ApiKeySource } from '@wordpress/conn export type PluginStatus = 'checking' | 'not-installed' | 'inactive' | 'active'; +type ApplicationPasswordSettingValue = { + username: string; + password: string; +}; + +type ConnectorSettingValue = string | ApplicationPasswordSettingValue; + interface UseConnectorPluginOptions { file?: string; settingName: string; @@ -30,11 +37,18 @@ interface UseConnectorPluginReturn { isBusy: boolean; isConnected: boolean; currentApiKey: string; + currentUsername: string; + hasResolvedSettings: boolean; keySource: ApiKeySource; handleButtonClick: () => void; getButtonLabel: () => string; saveApiKey: ( apiKey: string ) => Promise< void >; removeApiKey: () => Promise< void >; + saveCredentials: ( credentials: { + username: string; + applicationPassword: string; + } ) => Promise< void >; + removeCredentials: () => Promise< void >; } export function useConnectorPlugin( { @@ -63,32 +77,58 @@ export function useConnectorPlugin( { derivedPluginStatus, canManagePlugins, currentApiKey, + currentUsername, + hasStoredCredentials, + hasResolvedSettings, canInstallPlugins, } = useSelect( ( select ) => { const store = select( coreStore ); const siteSettings = store.getEntityRecord( 'root', 'site' ) as - | Record< string, string > + | Record< + string, + | string + | { + username?: string; + password?: string; + } + > | undefined; - const apiKey = siteSettings?.[ settingName ] ?? ''; + const settingValue = siteSettings?.[ settingName ]; + const apiKey = typeof settingValue === 'string' ? settingValue : ''; + const credentials = + typeof settingValue === 'object' && settingValue !== null + ? settingValue + : undefined; + const credentialsExist = + credentials !== undefined + ? !! credentials.username && !! credentials.password + : !! apiKey; + const settingsResolved = store.hasFinishedResolution( + 'getEntityRecord', + [ 'root', 'site' ] + ); const canCreate = !! store.canUser( 'create', { kind: 'root', name: 'plugin', } ); + const common = { + currentApiKey: apiKey, + currentUsername: credentials?.username ?? '', + hasStoredCredentials: credentialsExist, + hasResolvedSettings: settingsResolved, + canInstallPlugins: canCreate, + }; + if ( ! pluginFileFromServer ) { - const hasLoaded = store.hasFinishedResolution( - 'getEntityRecord', - [ 'root', 'site' ] - ); return { - derivedPluginStatus: ( hasLoaded + ...common, + derivedPluginStatus: ( settingsResolved ? 'active' : 'checking' ) as PluginStatus, canManagePlugins: undefined as boolean | undefined, - currentApiKey: apiKey, - canInstallPlugins: canCreate, }; } @@ -105,10 +145,9 @@ export function useConnectorPlugin( { if ( ! hasFinished ) { return { + ...common, derivedPluginStatus: 'checking' as PluginStatus, canManagePlugins: undefined as boolean | undefined, - currentApiKey: apiKey, - canInstallPlugins: canCreate, }; } @@ -119,12 +158,11 @@ export function useConnectorPlugin( { plugin.status === 'active' || plugin.status === 'network-active'; return { + ...common, derivedPluginStatus: ( isPluginActive ? 'active' : 'inactive' ) as PluginStatus, canManagePlugins: true, - currentApiKey: apiKey, - canInstallPlugins: canCreate, }; } @@ -138,13 +176,18 @@ export function useConnectorPlugin( { status = 'inactive'; } return { + ...common, derivedPluginStatus: status, canManagePlugins: false, - currentApiKey: apiKey, - canInstallPlugins: canCreate, }; }, - [ pluginBasename, settingName, isInstalled, isActivated ] + [ + pluginFileFromServer, + pluginBasename, + settingName, + isInstalled, + isActivated, + ] ); const pluginStatus = pluginStatusOverride ?? derivedPluginStatus; @@ -154,14 +197,64 @@ export function useConnectorPlugin( { const isConnected = ( pluginStatus === 'active' && connectedState ) || - // After install/activate, if settings re-fetch reveals an existing key, + // After install/activate, if settings re-fetch reveals stored credentials, // update connected state (mirrors what the server would report on page load). - ( pluginStatusOverride === 'active' && !! currentApiKey ); + ( pluginStatusOverride === 'active' && hasStoredCredentials ); const { saveEntityRecord, invalidateResolution } = useDispatch( coreStore ); const { createSuccessNotice, createErrorNotice } = useDispatch( noticesStore ); + const saveConnectorSetting = ( value: ConnectorSettingValue ) => + saveEntityRecord( + 'root', + 'site', + { [ settingName ]: value }, + { throwOnError: true } + ); + + const createConnectedNotice = () => { + createSuccessNotice( + sprintf( + /* translators: %s: Name of the connector (e.g. "OpenAI"). */ + __( '%s connected successfully.' ), + connectorName + ), + { + id: 'connector-connect-success', + type: 'snackbar', + } + ); + }; + + const createDisconnectedNotice = () => { + createSuccessNotice( + sprintf( + /* translators: %s: Name of the connector (e.g. "OpenAI"). */ + __( '%s disconnected.' ), + connectorName + ), + { + id: 'connector-disconnect-success', + type: 'snackbar', + } + ); + }; + + const createDisconnectErrorNotice = () => { + createErrorNotice( + sprintf( + /* translators: %s: Name of the connector (e.g. "OpenAI"). */ + __( 'Failed to disconnect %s.' ), + connectorName + ), + { + id: 'connector-disconnect-error', + type: 'snackbar', + } + ); + }; + const installPlugin = async () => { if ( ! pluginSlug ) { return; @@ -296,12 +389,7 @@ export function useConnectorPlugin( { const saveApiKey = async ( apiKey: string ) => { const previousApiKey = currentApiKey; try { - const updatedRecord = await saveEntityRecord( - 'root', - 'site', - { [ settingName ]: apiKey }, - { throwOnError: true } - ); + const updatedRecord = await saveConnectorSetting( apiKey ); // The server rejects invalid keys in two ways: // 1. Returns the previous (unchanged) value @@ -321,17 +409,7 @@ export function useConnectorPlugin( { } setConnectedState( true ); - createSuccessNotice( - sprintf( - /* translators: %s: Name of the connector (e.g. "OpenAI"). */ - __( '%s connected successfully.' ), - connectorName - ), - { - id: 'connector-connect-success', - type: 'snackbar', - } - ); + createConnectedNotice(); } catch ( error ) { // eslint-disable-next-line no-console console.error( 'Failed to save API key:', error ); @@ -341,42 +419,66 @@ export function useConnectorPlugin( { } }; + const saveCredentials = async ( { + username, + applicationPassword, + }: { + username: string; + applicationPassword: string; + } ) => { + try { + const updatedRecord = await saveConnectorSetting( { + username, + password: applicationPassword, + } ); + const record = updatedRecord as + | Record< string, { username?: string; password?: string } > + | undefined; + const credentials = record?.[ settingName ]; + // The server sanitizes the username, so verify persistence rather + // than exact equality. + if ( ! credentials?.username || ! credentials?.password ) { + throw new Error( + __( 'It was not possible to save these credentials.' ) + ); + } + + setConnectedState( true ); + createConnectedNotice(); + } catch ( error ) { + // eslint-disable-next-line no-console + console.error( 'Failed to save credentials:', error ); + // The error is rendered with role="alert" in the UI, + // which already announces it to screen readers. + throw error; + } + }; + const removeApiKey = async () => { try { - await saveEntityRecord( - 'root', - 'site', - { [ settingName ]: '' }, - { throwOnError: true } - ); + await saveConnectorSetting( '' ); // Store auto-updates; currentApiKey reactively becomes ''. setConnectedState( false ); - createSuccessNotice( - sprintf( - /* translators: %s: Name of the connector (e.g. "OpenAI"). */ - __( '%s disconnected.' ), - connectorName - ), - { - id: 'connector-disconnect-success', - type: 'snackbar', - } - ); + createDisconnectedNotice(); } catch ( error ) { // eslint-disable-next-line no-console console.error( 'Failed to remove API key:', error ); - createErrorNotice( - sprintf( - /* translators: %s: Name of the connector (e.g. "OpenAI"). */ - __( 'Failed to disconnect %s.' ), - connectorName - ), - { - id: 'connector-disconnect-error', - type: 'snackbar', - } - ); - throw error; + createDisconnectErrorNotice(); + } + }; + + const removeCredentials = async () => { + try { + await saveConnectorSetting( { + username: '', + password: '', + } ); + setConnectedState( false ); + createDisconnectedNotice(); + } catch ( error ) { + // eslint-disable-next-line no-console + console.error( 'Failed to remove credentials:', error ); + createDisconnectErrorNotice(); } }; @@ -389,10 +491,14 @@ export function useConnectorPlugin( { isBusy, isConnected, currentApiKey, + currentUsername, + hasResolvedSettings, keySource, handleButtonClick, getButtonLabel, saveApiKey, removeApiKey, + saveCredentials, + removeCredentials, }; } diff --git a/test/e2e/specs/admin/connectors.spec.js b/test/e2e/specs/admin/connectors.spec.js index d8368261bed5d7..34f35ddb9359e1 100644 --- a/test/e2e/specs/admin/connectors.spec.js +++ b/test/e2e/specs/admin/connectors.spec.js @@ -552,6 +552,208 @@ test.describe( 'Connectors', () => { } ); } ); + test.describe( 'Application password setup flow', () => { + const PLUGIN_SLUG = 'gutenberg-test-application-password-connector'; + const CREDENTIALS_SETTING = + 'connectors_content_source_test_remote_wordpress_credentials'; + const APPLICATION_PASSWORD = 'abcd efgh ijkl mnop 1234'; + + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.activatePlugin( PLUGIN_SLUG ); + const status = await requestUtils.rest( { + path: '/gutenberg-test-connectors/v1/application-password', + } ); + // The companion Core change can land independently of this UI. + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! status.is_registered, + 'Requires application_password support in WordPress Core.' + ); + } ); + + test.afterEach( async ( { requestUtils } ) => { + await requestUtils.rest( { + path: '/wp/v2/settings', + method: 'POST', + data: { + [ CREDENTIALS_SETTING ]: { + username: '', + password: '', + }, + }, + } ); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await requestUtils.deactivatePlugin( PLUGIN_SLUG ); + } ); + + test( 'should save, mask, reload, and remove both credentials', async ( { + page, + admin, + requestUtils, + } ) => { + await admin.visitAdminPage( + SETTINGS_PAGE_PATH, + CONNECTORS_PAGE_QUERY + ); + + const card = getConnectorCardByName( + page, + 'Test Remote WordPress' + ); + await card.getByRole( 'button', { name: 'Set up' } ).click(); + + const usernameInput = card.getByRole( 'textbox', { + name: 'Username', + } ); + const passwordInput = card.getByLabel( 'Application password' ); + const saveButton = card.getByRole( 'button', { name: 'Save' } ); + + await expect( saveButton ).toBeDisabled(); + await usernameInput.fill( 'remote-user' ); + await passwordInput.fill( APPLICATION_PASSWORD ); + await expect( saveButton ).toBeEnabled(); + await expect( + card.getByRole( 'link', { + name: 'example.com', + } ) + ).toHaveAttribute( + 'href', + 'https://example.com/wp-admin/profile.php' + ); + await saveButton.click(); + + await expect( + card.getByText( 'Connected', { exact: true } ) + ).toBeVisible(); + const editButton = card.getByRole( 'button', { name: 'Edit' } ); + await expect( editButton ).toBeFocused(); + + const settings = await requestUtils.rest( { + path: '/wp/v2/settings', + } ); + expect( settings[ CREDENTIALS_SETTING ].username ).toBe( + 'remote-user' + ); + expect( settings[ CREDENTIALS_SETTING ].password ).toBe( + '\u2022'.repeat( 16 ) + ); + + await admin.visitAdminPage( + SETTINGS_PAGE_PATH, + CONNECTORS_PAGE_QUERY + ); + const reloadedCard = getConnectorCardByName( + page, + 'Test Remote WordPress' + ); + await reloadedCard.getByRole( 'button', { name: 'Edit' } ).click(); + + await expect( + reloadedCard.getByRole( 'textbox', { name: 'Username' } ) + ).toHaveValue( 'remote-user' ); + await expect( + reloadedCard.getByLabel( 'Application password' ) + ).toHaveValue( '•'.repeat( 16 ) ); + await reloadedCard + .getByRole( 'button', { name: 'Remove and replace' } ) + .click(); + + await expect( + reloadedCard.getByText( 'Connected', { exact: true } ) + ).toBeHidden(); + await expect( + reloadedCard.getByRole( 'textbox', { name: 'Username' } ) + ).toHaveValue( '' ); + + const clearedSettings = await requestUtils.rest( { + path: '/wp/v2/settings', + } ); + expect( clearedSettings[ CREDENTIALS_SETTING ] ).toEqual( { + username: '', + password: '', + } ); + } ); + + test( 'should keep the stored password when a masked settings response is saved back', async ( { + requestUtils, + } ) => { + await requestUtils.rest( { + path: '/wp/v2/settings', + method: 'POST', + data: { + [ CREDENTIALS_SETTING ]: { + username: 'remote-user', + password: APPLICATION_PASSWORD, + }, + }, + } ); + + // Read the settings back; the REST API masks the password. + const settings = await requestUtils.rest( { + path: '/wp/v2/settings', + } ); + expect( settings[ CREDENTIALS_SETTING ].password ).toBe( + '\u2022'.repeat( 16 ) + ); + + // Save the masked response back, as a read-modify-write client + // would, and confirm the stored password is not overwritten. + await requestUtils.rest( { + path: '/wp/v2/settings', + method: 'POST', + data: { + [ CREDENTIALS_SETTING ]: settings[ CREDENTIALS_SETTING ], + }, + } ); + + const storedCredentials = await requestUtils.rest( { + path: '/gutenberg-test-connectors/v1/application-password-credentials', + } ); + expect( storedCredentials ).toEqual( { + username: 'remote-user', + password: APPLICATION_PASSWORD, + } ); + } ); + + test( 'should show an environment-configured connector as connected and read-only', async ( { + page, + admin, + } ) => { + await admin.visitAdminPage( + SETTINGS_PAGE_PATH, + CONNECTORS_PAGE_QUERY + ); + + const card = getConnectorCardByName( + page, + 'Test Env Configured WordPress' + ); + await expect( + card.getByText( 'Connected', { exact: true } ) + ).toBeVisible(); + await card.getByRole( 'button', { name: 'Edit' } ).click(); + + const usernameInput = card.getByRole( 'textbox', { + name: 'Username', + } ); + await expect( usernameInput ).toBeDisabled(); + await expect( usernameInput ).toHaveValue( '•'.repeat( 16 ) ); + await expect( + card.getByLabel( 'Application password' ) + ).toBeDisabled(); + await expect( + card.getByText( + 'These credentials are configured using an environment variable.' + ) + ).toBeVisible(); + await expect( + card.getByRole( 'button', { name: 'Remove and replace' } ) + ).toBeHidden(); + } ); + } ); + test.describe( 'JS extensibility', () => { const PLUGIN_SLUG = 'gutenberg-test-connectors-js-extensibility';