Make WordPress Core

Opened 5 months ago

Closed 6 weeks ago

Last modified 5 weeks ago

#65551 closed defect (bug) (fixed)

Connectors: Preserve stored AI provider API key when validation is indeterminate

Reported by: khokansardar Owned by: jorgefilipecosta
Priority: normal Milestone: 7.2
Component: Editor Version: 7.0
Severity: normal Keywords: has-patch has-unit-tests
Cc: Focuses: rest-api

Description

When saving connector settings via the REST API, _wp_connectors_rest_settings_dispatch() validates each updated AI provider API key with _wp_connectors_is_ai_api_key_valid().

That helper returns three states: true (valid), false (invalid), and null (could not be determined — e.g. the provider endpoint was temporarily unreachable and threw an exception).

The dispatch logic discards the key on anything that is not strictly true:

if ( true !== _wp_connectors_is_ai_api_key_valid( $value, $connector_id ) ) {
        update_option( $setting_name, '' ); // wipes a valid key
}

As a result, a transient provider outage during a settings save permanently deletes a
user's previously valid API key. "Could not verify" is treated identically to "invalid".

Fix: only discard the key on an explicit false. A null (indeterminate) result preserves
the stored key.

Steps to reproduce:

  1. Connect an AI provider with a valid API key.
  2. Re-save connector settings while the provider's validation endpoint is unreachable.
  3. Observe the stored key is reset to an empty string.

Attachments (2)

Open AI key successfully saved .png​ (13.2 KB ) - added by soniaamanat 4 months ago.
After fail validation no longer api key saved in settings.png​ (12.1 KB ) - added by soniaamanat 4 months ago.

Download all attachments as: .zip

Change History (14)

This ticket was mentioned in ​PR #12345 on ​WordPress/wordpress-develop by ​@khokansardar.


5 months ago
#1

## Summary
_wp_connectors_rest_settings_dispatch() discarded a stored AI provider API key whenever validation did not return strictly true. Since _wp_connectors_is_ai_api_key_valid() returns null when a key cannot be verified (e.g. the provider is temporarily unreachable), a transient outage during a settings save permanently wiped a valid key.

This changes the check to only discard on an explicit false result. Any other result preserves the stored key.

## Changes

  • src/wp-includes/connectors.php: discard the key only on an explicit false from _wp_connectors_is_ai_api_key_valid().
  • tests/phpunit/tests/connectors/wpConnectorsRestSettingsDispatch.php: new coverage for the dispatch handler — indeterminate preserves, invalid discards, valid preserved + masked, GET is a no-op.

## Testing

  • phpunit --group connectors → 85 tests, 219 assertions, passing.
  • Reverting the production change fails test_indeterminate_validation_preserves_key, confirming the new test guards the regression.

Trac ticket: https://core.trac.wordpress.org/ticket/65551

## Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 4.8
Used for: Ticket analysis and tests cases. All changes were reviewed, validated against the codebase, and are taken responsibility for by me.

#2 @soniaamanat
4 months ago

Tested in WordPress Playground.

I was able to reproduce the reported issue. I saved a valid OpenAI API key, then triggered a validation failure and re-saved the connector settings. After the failed validation, the previously saved API key was no longer present in the connector settings, indicating that it had been cleared instead of being preserved.

This matches the behavior described in the ticket, where an indeterminate validation result is treated the same as an invalid key.

#3 @luisdavid01
4 months ago

## Patch Testing Report

Patch tested: ​https://github.com/WordPress/wordpress-develop/pull/12345

### Environment

WordPress: 7.1-alpha-62161-src
PHP: 8.3.32
Server: nginx 1.31.2
Database: mysql 9.7.1
Browser: Helium 0.14.3.1 (Official Build, Chromium 150.0.7871.46) Arch Linux (64-bit)
OS: Operating System CachyOS 7.1.3
Theme: twentytwentyfive 1.5
MU Plugins:

  • Simulate Connector API Failure (TESTING ONLY) — custom, intercepts pre_http_request for api.openai.com returning 500/503/400 http error status code.

Plugins:
AI 1.2.0
AI Provider for OpenAI 1.0.3
Hello Dolly 1.7.2

### Steps taken

  1. Enable both plugins AI , AI provider for OpenAI
  2. Go to setting > Connectors
  3. Set up OpenAI provider with valid api key
  4. Enable the MU plugin intercepting http requests to OpenAI
  5. Attempt to re-save current api key

❌ Patch is not solving the problem: The patch logic points to a deeper issue inside _wp_connectors_is_ai_api_key_valid function consistently returning false, when hardcoding the value $valid = NULL; inside _wp_connectors_rest_settings_dispatch and replacing the calls to _wp_connectors_is_ai_api_key_valid with $valid shows that the patch doesn't delete the api key from the database which is the expected behavior but never produces null for any real-world outage condition neither exception failures nor server-side errors (HTTP 500)

### Expected result
A temporarily unreachable or erroring provider endpoint should preserve the previously stored, valid API key.
### Additional Notes
My suggested fix is to make isConfigured() (or the layer that performs the underlying HTTP call to the provider) distinguish connectivity/timeout/server-error failures from genuine authentication failures for example, by throwing on connection errors or HTTP 5xx responses so they propagate up as null, while reserving false strictly for confirmed invalid-key responses (e.g. HTTP 401/403). Without this, the dispatch-level fix in this patch is correct but effectively unreachable for the real-world outage scenario the ticket is meant to address.

Last edited 4 months ago by luisdavid01 (previous) (diff)

#4 @jorgefilipecosta
2 months ago

  • Owner set to jorgefilipecosta
  • Status new → assigned

This ticket was mentioned in ​Slack in #core-ai by jorgefilipecosta. ​View the logs.


2 months ago

This ticket was mentioned in ​PR #13870 on ​WordPress/wordpress-develop by ​@jorgefilipecosta.


6 weeks ago
#6

What

Builds on ​https://github.com/WordPress/wordpress-develop/pull/12345 and keeps its false === check, which on its own doesn't fix the outage: the official provider plugins check availability by listing models, and ListModelsApiBasedProviderAvailability::isConfigured() turns every failure into false, so an unreachable provider still wiped the key.

  • Only discard a submitted AI provider key when the provider rejects it (a 4xx other than 408 or 429). Network errors, server errors, timeouts and rate limits keep the key.
  • Validate against a fresh model list. The cached one made any key pass for up to a day on sites with a persistent object cache.
  • Keep the stored key when its mask is submitted back. The Connectors screen pre-fills the masked key when a provider shows as not connected, which is what it shows during an outage, so saving overwrote the real key before validation ran.
  • Upstream API that would let this drop the list models workaround: ​https://github.com/WordPress/php-ai-client/pull/299

Testing

Verify unit tests are passing:

vendor/bin/phpunit --group connectors

Issue found via AI-assisted code review; fix and tests drafted with AI assistance (Claude Code) and reviewed by me.

This ticket was mentioned in ​PR #13871 on ​WordPress/wordpress-develop by ​@jorgefilipecosta.


6 weeks ago
#7

What

Alternative to ​https://github.com/WordPress/wordpress-develop/pull/13870, to merge only after a php-ai-client release with ​https://github.com/WordPress/php-ai-client/pull/299 is bundled. It shows how the fix looks when php-ai-client does the credentials check.

Testing

Verify unit tests are passing:

vendor/bin/phpunit --group connectors

Issue found via AI-assisted code review; fix and tests drafted with AI assistance (Claude Code) and reviewed by me.

​@muneebashraf commented on ​PR #13870:


6 weeks ago
#8

Patch Testing Report

Patch tested: ​https://github.com/WordPress/wordpress-develop/pull/13870 (head 62d9119)

Environment

  • WordPress: trunk dc829be for the reproduction, this PR's head 62d9119 for the patch
  • PHP: 8.4.26 (CLI, Windows)
  • Database: SQLite (SQLite Database Integration 3.0.2)
  • Plugins: AI Provider for OpenAI 1.2.0 from WordPress.org
  • Test method: a PHPUnit test on the core test suite. It saves connectors_ai_openai_api_key through POST /wp/v2/settings and applies rest_post_dispatch the way WP_REST_Server::serve_request() does. A pre_http_request filter answers the provider's GET https://api.openai.com/v1/models. Each case saves the key once with a 200 response, then saves the same key again while the provider fails. "Fresh cache" flushes the object cache between the two saves (separate requests, no persistent object cache). "Persistent cache" keeps it.

Actual results

Stored key after the second save:

Provider response on re-save trunk, fresh cache trunk, persistent cache PR, fresh cache PR, persistent cache
Network error (cURL 28) wiped kept, provider not called kept kept
503 wiped kept, provider not called kept kept
500 wiped kept, provider not called kept kept
429 wiped kept, provider not called kept kept
408 wiped kept, provider not called kept kept
401 wiped kept, provider not called wiped wiped
  • ✅ Reproduced on trunk: any failure during a re-save wipes a valid key. With a persistent cache the key is never re-validated, so a key the provider rejects (401) is kept.
  • ✅ With the patch: outages, timeouts and rate limits keep the key, a 401 discards it, and the provider is called in both cache setups.
  • ✅ vendor/bin/phpunit --group connectors on the PR head: OK (124 tests, 305 assertions).

Additional notes

  • When the key is kept, _wp_connectors_is_ai_api_key_valid() reports the failure through wp_trigger_error(), for example: Network error occurred while sending GET request to https://api.openai.com/v1/models: cURL error 28: Connection timed out. With WP_DEBUG on this shows as a notice, which looks intended.
  • Not tested: the Connectors screen itself (the masked-key change that ​https://github.com/WordPress/gutenberg/pull/83889 covers), or a live OpenAI endpoint.
  • Tested on SQLite rather than MySQL. The code under test only reads and writes options.

<details>
<summary>Reproduction test</summary>

Run with the core PHPUnit config and a bootstrap that loads the AI Provider for OpenAI plugin on muplugins_loaded.

<?php
/**
 * Reproduction for #65551 with the real AI Provider for OpenAI plugin.
 *
 * Saves the OpenAI key through POST /wp/v2/settings (what the Connectors screen does)
 * while pre_http_request simulates the provider's answer to the list models request.
 */
class Repro65551Test extends WP_UnitTestCase {
        const OPTION = 'connectors_ai_openai_api_key';
        const KEY    = 'sk-repro-65551-0123456789abcdef';

        private $mode     = 'ok';
        private $requests = 0;
        private $notices  = 0;

        public function set_up() {
                parent::set_up();
                wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
                add_filter( 'pre_http_request', array( $this, 'fake_openai' ), 10, 3 );
                // Count wp_trigger_error() notices instead of letting PHPUnit turn them into exceptions.
                add_filter(
                        'wp_trigger_error_trigger_error',
                        function () {
                                ++$this->notices;
                                return false;
                        }
                );
        }

        public function fake_openai( $pre, $args, $url ) {
                if ( false === strpos( $url, 'api.openai.com' ) ) {
                        return $pre;
                }
                ++$this->requests;
                if ( 'network' === $this->mode ) {
                        return new WP_Error( 'http_request_failed', 'cURL error 28: Connection timed out' );
                }
                $code = 'ok' === $this->mode ? 200 : (int) $this->mode;
                $body = 200 === $code
                        ? wp_json_encode( array( 'object' => 'list', 'data' => array( array( 'id' => 'gpt-4o', 'object' => 'model', 'created' => 1715367049, 'owned_by' => 'system' ) ) ) )
                        : wp_json_encode( array( 'error' => array( 'message' => "Simulated $code", 'type' => 'test' ) ) );
                return array(
                        'headers'  => array( 'content-type' => 'application/json' ),
                        'body'     => $body,
                        'response' => array( 'code' => $code, 'message' => 'Simulated' ),
                        'cookies'  => array(),
                        'filename' => null,
                );
        }

        private function save_key( string $mode ): string {
                $this->mode = $mode;
                $request    = new WP_REST_Request( 'POST', '/wp/v2/settings' );
                $request->set_param( self::OPTION, self::KEY );
                // rest_do_request() skips rest_post_dispatch; apply it as WP_REST_Server::serve_request() does.
                $response = rest_do_request( $request );
                $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), rest_get_server(), $request );
                $this->assertSame( 200, $response->get_status(), 'Settings save should succeed.' );
                return (string) get_option( self::OPTION, '' );
        }

        /** @dataProvider data_modes */
        public function test_resave_during_provider_response( string $mode, bool $fresh_cache ) {
                $this->assertTrue( wp_is_connector_registered( 'openai' ), 'The OpenAI connector should be registered.' );

                // A valid key is stored first.
                $this->assertSame( self::KEY, $this->save_key( 'ok' ), 'Baseline: a valid key is stored.' );

                // Separate requests on a site without a persistent object cache start with an empty cache.
                if ( $fresh_cache ) {
                        wp_cache_flush();
                }
                $before = $this->requests;

                // Re-save the same key while the provider answers with $mode.
                $stored = $this->save_key( $mode );

                fwrite(
                        STDERR,
                        sprintf(
                                "\n[65551] cache=%-10s provider=%-7s provider_called=%-3s notice=%-3s result=%s",
                                $fresh_cache ? 'fresh' : 'persistent',
                                $mode,
                                $this->requests > $before ? 'yes' : 'no',
                                $this->notices > 0 ? 'yes' : 'no',
                                '' === $stored ? 'KEY WIPED' : 'key kept'
                        )
                );
        }

        public function data_modes() {
                $data = array();
                foreach ( array( true, false ) as $fresh_cache ) {
                        foreach ( array( 'network', '503', '500', '429', '408', '401' ) as $mode ) {
                                $data[ ( $fresh_cache ? 'fresh ' : 'persistent ' ) . $mode ] = array( $mode, $fresh_cache );
                        }
                }
                return $data;
        }
}

</details>

AI assistance: Claude Code (Claude Opus 5.5) helped write the reproduction test. The results above come from running it.

​@jorgefilipecosta commented on ​PR #12345:


6 weeks ago
#9

Thank you for proposing a fix @itzmekhokan, unfortunately this solution was not fixing the problem, when the provider is down or we are without network the condition false === _wp_connectors_is_ai_api_key_valid( $value, $connector_id ) would still match. I proposed an alternative at ​https://github.com/WordPress/wordpress-develop/pull/13870. Any feedback is welcome.

​@jorgefilipecosta commented on ​PR #13870:


6 weeks ago
#10

I kept digging into this issue and this solution still has a problem, when there is an outage we show connected:
https://github.com/user-attachments/assets/f679f21c-e863-4266-8057-0c8e1a34f7d3

While we don't know if there was a connection. I think there the root cause of the problem of storing the same key during an outage, is the UI allowing during an outage the same key to be stored instead of the normal flow of removing and then typing a new key I'm fixing that issue at ​https://github.com/WordPress/gutenberg/pull/83889.

#11 @jorgefilipecosta
6 weeks ago

  • Resolution → fixed
  • Status assigned → closed

After trying ​https://github.com/WordPress/wordpress-develop/pull/13870 which was adding considerable complexity, and bringing other issues. I ended up fixing the issue at ​https://github.com/WordPress/gutenberg/pull/83889 with a different approach. With the change there during an outage storing the same key is not possible anymore, like when the connector is connected. In both cases the keys are now not editable and need to be removed before a new key is set, that should have been to behavior from the beginning but it was not because we had a buggy condition. The fix is merged in Gutenberg and core should be fixed during the next Gutenberg package update.

#12 @sabernhardt
5 weeks ago

  • Keywords needs-testing removed
  • Milestone Awaiting Review → 7.2
Note: See TracTickets for help on using tickets.