fix(images): CTO review blockers on PR #9

Addresses four blockers from CTO review in
convo/prautoblogger/threads/2026-04-image-pipeline/04-cto-block-pr9.md:

1. PHPUnit red — 2 retry-path tests failing on bad mocks.
   The success-after-retry branch calls wp_remote_retrieve_header()
   only on the success attempt; the original mocks queued two mime
   values and popped the first (text/plain), which made the provider's
   normalize_response_body() throw "unexpected shape". Replaced the
   pop-queue with a single justReturn('image/png'). The retry-after
   header read on the 5xx/429 branch still works (coerces to int 0,
   falls back to exponential backoff).

2. XSS defense-in-depth — wrap untrusted API response bodies in
   esc_html() before they land in exception / user-facing messages.
   - class-cloudflare-image-provider.php: 4xx-throw and
     retry-exhaustion-throw now escape substr($raw, 0, 300) and
     $last_error respectively.
   - class-cloudflare-image-validator.php: network-error and
     HTTP-error-body messages now use esc_html__() on the template
     and esc_html() on the substituted values.

3. PHPCS hygiene on the 4 new files (CTO path A). Converted the
   one-line private-method docblocks to full multi-line format with
   @param / @return / @throws tags. Added a docblock to __construct.

4. File-size cap. The docblock expansion pushed
   class-cloudflare-image-provider.php over 300 lines. Extracted
   credential lookups + URL builder + log forwarders into a new
   class-cloudflare-image-support.php (101 lines). Provider is now
   271 lines, all new files under the 300-line cap.

No production behaviour changed beyond the escape wrapping. The
provider's public API, retry policy, and response handling are
identical to c823618.

File sizes after fix:
- interface-image-provider.php:         100
- class-cloudflare-image-provider.php:  271
- class-cloudflare-image-pricing.php:    78
- class-cloudflare-image-validator.php: 116
- class-cloudflare-image-support.php:   101

Agent-Session: cowork-2026-04-15-image-pipeline-commit-1a-cto-blockers
This commit is contained in:
peptiderepo
2026-04-15 14:16:39 +07:00
parent c8236189cd
commit 573520558c
4 changed files with 182 additions and 105 deletions

View File

@@ -18,6 +18,7 @@ declare(strict_types=1);
* *
* @see interface-image-provider.php Interface this class implements. * @see interface-image-provider.php Interface this class implements.
* @see class-cloudflare-image-pricing.php Cost + model id helpers. * @see class-cloudflare-image-pricing.php Cost + model id helpers.
* @see class-cloudflare-image-support.php Token, account, URL, and log helpers.
* @see class-cloudflare-image-validator.php Credential check helper. * @see class-cloudflare-image-validator.php Credential check helper.
* @see class-open-router-provider.php Sibling provider; same retry pattern. * @see class-open-router-provider.php Sibling provider; same retry pattern.
* @see ARCHITECTURE.md External API Integrations, key decision #16. * @see ARCHITECTURE.md External API Integrations, key decision #16.
@@ -37,8 +38,20 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
*/ */
private PRAutoBlogger_Cloudflare_Image_Pricing $pricing; private PRAutoBlogger_Cloudflare_Image_Pricing $pricing;
/**
* Token, account, URL, and log helpers — pulled out of this class to
* keep it under the 300-line cap.
*
* @var PRAutoBlogger_Cloudflare_Image_Support
*/
private PRAutoBlogger_Cloudflare_Image_Support $support;
/**
* Construct the provider with its default pricing + support helpers.
*/
public function __construct() { public function __construct() {
$this->pricing = new PRAutoBlogger_Cloudflare_Image_Pricing(); $this->pricing = new PRAutoBlogger_Cloudflare_Image_Pricing();
$this->support = new PRAutoBlogger_Cloudflare_Image_Support();
} }
/** /**
@@ -64,8 +77,8 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
); );
} }
$account_id = $this->get_account_id(); $account_id = $this->support->get_account_id();
$api_token = $this->get_api_token(); $api_token = $this->support->get_api_token();
$model = $this->pricing->resolve_model( (string) ( $options['model'] ?? '' ) ); $model = $this->pricing->resolve_model( (string) ( $options['model'] ?? '' ) );
$body = [ $body = [
@@ -78,7 +91,7 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
$body['seed'] = (int) $options['seed']; $body['seed'] = (int) $options['seed'];
} }
$url = $this->build_endpoint_url( $account_id, $model ); $url = $this->support->build_endpoint_url( $account_id, $model );
$headers = [ $headers = [
'Authorization' => 'Bearer ' . $api_token, 'Authorization' => 'Bearer ' . $api_token,
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
@@ -99,7 +112,7 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
if ( is_wp_error( $response ) ) { if ( is_wp_error( $response ) ) {
$last_error = $response->get_error_message(); $last_error = $response->get_error_message();
$this->log_retryable_failure( $attempt, 'network', $last_error ); $this->support->log_retryable_failure( $attempt, 'network', $last_error );
$this->sleep_for_attempt( $attempt ); $this->sleep_for_attempt( $attempt );
continue; continue;
} }
@@ -109,7 +122,7 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
if ( 429 === $status || $status >= 500 ) { if ( 429 === $status || $status >= 500 ) {
$last_error = sprintf( 'HTTP %d: %s', $status, substr( $raw, 0, 300 ) ); $last_error = sprintf( 'HTTP %d: %s', $status, substr( $raw, 0, 300 ) );
$this->log_retryable_failure( $attempt, (string) $status, $last_error ); $this->support->log_retryable_failure( $attempt, (string) $status, $last_error );
if ( $attempt < PRAUTOBLOGGER_MAX_RETRIES ) { if ( $attempt < PRAUTOBLOGGER_MAX_RETRIES ) {
$retry_after = (int) wp_remote_retrieve_header( $response, 'retry-after' ); $retry_after = (int) wp_remote_retrieve_header( $response, 'retry-after' );
$this->sleep_for_attempt( $attempt, $retry_after ); $this->sleep_for_attempt( $attempt, $retry_after );
@@ -118,13 +131,13 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
} }
if ( $status >= 400 ) { if ( $status >= 400 ) {
$this->log_client_error( $status, $api_token, $account_id, $raw ); $this->support->log_client_error( $status, $api_token, $account_id, $raw );
throw new \RuntimeException( throw new \RuntimeException(
sprintf( sprintf(
/* translators: %1$d: HTTP status, %2$s: error body. */ /* translators: %1$d: HTTP status, %2$s: error body. */
esc_html__( 'Cloudflare Workers AI error (HTTP %1$d): %2$s', 'prautoblogger' ), esc_html__( 'Cloudflare Workers AI error (HTTP %1$d): %2$s', 'prautoblogger' ),
$status, $status,
substr( $raw, 0, 300 ) esc_html( substr( $raw, 0, 300 ) )
) )
); );
} }
@@ -152,7 +165,7 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
/* translators: %1$d: max retries, %2$s: last error. */ /* translators: %1$d: max retries, %2$s: last error. */
esc_html__( 'Cloudflare Workers AI failed after %1$d attempts. Last error: %2$s', 'prautoblogger' ), esc_html__( 'Cloudflare Workers AI failed after %1$d attempts. Last error: %2$s', 'prautoblogger' ),
PRAUTOBLOGGER_MAX_RETRIES, PRAUTOBLOGGER_MAX_RETRIES,
$last_error esc_html( $last_error )
) )
); );
} }
@@ -188,7 +201,14 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
return ( new PRAutoBlogger_Cloudflare_Image_Validator() )->run(); return ( new PRAutoBlogger_Cloudflare_Image_Validator() )->run();
} }
/** Enforce the interface's dimension contract. */ /**
* Enforce the interface's dimension contract.
*
* @param int $width Width in pixels.
* @param int $height Height in pixels.
* @return void
* @throws \InvalidArgumentException If either dimension is outside [MIN, MAX].
*/
private function assert_valid_dimensions( int $width, int $height ): void { private function assert_valid_dimensions( int $width, int $height ): void {
if ( if (
$width < self::MIN_DIMENSION_PX || $width > self::MAX_DIMENSION_PX || $width < self::MIN_DIMENSION_PX || $width > self::MAX_DIMENSION_PX ||
@@ -207,7 +227,15 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
} }
} }
/** Normalize a 2xx response into [bytes, mime-type] whether raw or JSON-wrapped. */ /**
* Normalize a 2xx response into [bytes, mime-type] whether the body
* arrives as raw image bytes or as a JSON envelope with base64 image.
*
* @param string $raw Raw response body.
* @param string $mime Response Content-Type header value (may be empty).
* @return array{0: string, 1: string} [image bytes, mime type]
* @throws \RuntimeException If the body matches neither expected shape.
*/
private function normalize_response_body( string $raw, string $mime ): array { private function normalize_response_body( string $raw, string $mime ): array {
if ( '' !== $mime && 0 === stripos( $mime, 'image/' ) ) { if ( '' !== $mime && 0 === stripos( $mime, 'image/' ) ) {
return [ $raw, $mime ]; return [ $raw, $mime ];
@@ -224,55 +252,14 @@ class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Pro
); );
} }
private function build_endpoint_url( string $account_id, string $model ): string { /**
return sprintf( * Sleep between retries. Retry-After header value wins when present,
'https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s', * otherwise exponential backoff from the PRAUTOBLOGGER_* constants.
rawurlencode( $account_id ), *
ltrim( $model, '/' ) * @param int $attempt 1-based attempt number that just failed.
); * @param int $retry_after_secs Retry-After header value (0 if absent).
} * @return void
*/
private function get_api_token(): string {
$encrypted = (string) get_option( 'prautoblogger_cloudflare_ai_token', '' );
if ( '' === $encrypted ) {
return '';
}
return (string) PRAutoBlogger_Encryption::decrypt( $encrypted );
}
private function get_account_id(): string {
return trim( (string) get_option( 'prautoblogger_cloudflare_account_id', '' ) );
}
private function log_retryable_failure( int $attempt, string $failure_class, string $detail ): void {
PRAutoBlogger_Logger::instance()->warning(
sprintf(
'Cloudflare image gen %s failure (attempt %d/%d): %s',
$failure_class,
$attempt,
PRAUTOBLOGGER_MAX_RETRIES,
$detail
),
'cloudflare-image'
);
}
/** Log an unrecoverable 4xx with triage context (never the full secret). */
private function log_client_error( int $status, string $api_token, string $account_id, string $raw ): void {
PRAutoBlogger_Logger::instance()->error(
sprintf(
'Cloudflare image gen HTTP %d (token_prefix=%s, token_len=%d, account=%s): %s',
$status,
substr( $api_token, 0, 4 ),
strlen( $api_token ),
substr( $account_id, 0, 6 ),
substr( $raw, 0, 300 )
),
'cloudflare-image'
);
}
/** Sleep between retries; Retry-After header wins when present, else exponential backoff. */
private function sleep_for_attempt( int $attempt, int $retry_after_secs = 0 ): void { private function sleep_for_attempt( int $attempt, int $retry_after_secs = 0 ): void {
$backoff = PRAUTOBLOGGER_RETRY_BASE_DELAY_SECONDS * (int) pow( 2, $attempt - 1 ); $backoff = PRAUTOBLOGGER_RETRY_BASE_DELAY_SECONDS * (int) pow( 2, $attempt - 1 );
$delay = $retry_after_secs > 0 ? min( $retry_after_secs, self::RETRY_AFTER_CAP_S ) : $backoff; $delay = $retry_after_secs > 0 ? min( $retry_after_secs, self::RETRY_AFTER_CAP_S ) : $backoff;

View File

@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
/**
* Small support helpers for the Cloudflare image provider — credential
* lookups, URL building, and structured log lines.
*
* Split out of the provider so the provider stays under the 300-line cap
* and so these tiny pieces are individually testable. Pure functions plus
* one logger forward; no state.
*
* Triggered by: PRAutoBlogger_Cloudflare_Image_Provider only.
* Dependencies: PRAutoBlogger_Encryption (token decryption),
* PRAutoBlogger_Logger (WARN/ERROR forwarding).
*
* @see class-cloudflare-image-provider.php Sole caller.
*/
class PRAutoBlogger_Cloudflare_Image_Support {
/**
* Decrypt the Cloudflare API token from the settings option.
*
* @return string Plaintext token, or empty string if not set / decrypt fails.
*/
public function get_api_token(): string {
$encrypted = (string) get_option( 'prautoblogger_cloudflare_ai_token', '' );
if ( '' === $encrypted ) {
return '';
}
return (string) PRAutoBlogger_Encryption::decrypt( $encrypted );
}
/**
* Read the Cloudflare account ID from settings.
*
* @return string Account UUID, or empty string.
*/
public function get_account_id(): string {
return trim( (string) get_option( 'prautoblogger_cloudflare_account_id', '' ) );
}
/**
* Build the Workers AI run URL for a given account + model.
*
* @param string $account_id Cloudflare account UUID.
* @param string $model Fully-qualified Workers AI model id.
* @return string Fully-formed HTTPS URL.
*/
public function build_endpoint_url( string $account_id, string $model ): string {
return sprintf(
'https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s',
rawurlencode( $account_id ),
ltrim( $model, '/' )
);
}
/**
* Emit a WARN line for a retryable failure.
*
* @param int $attempt 1-based attempt number.
* @param string $failure_class Either 'network' or HTTP status code as string.
* @param string $detail Short failure detail for the log.
* @return void
*/
public function log_retryable_failure( int $attempt, string $failure_class, string $detail ): void {
PRAutoBlogger_Logger::instance()->warning(
sprintf(
'Cloudflare image gen %s failure (attempt %d/%d): %s',
$failure_class,
$attempt,
PRAUTOBLOGGER_MAX_RETRIES,
$detail
),
'cloudflare-image'
);
}
/**
* Log an unrecoverable 4xx with triage context. Never logs the full
* secret — only a 4-char token prefix and a 6-char account prefix.
*
* @param int $status HTTP status returned by Cloudflare.
* @param string $api_token Plaintext token.
* @param string $account_id Account UUID.
* @param string $raw Raw response body (truncated to 300 chars in the log).
* @return void
*/
public function log_client_error( int $status, string $api_token, string $account_id, string $raw ): void {
PRAutoBlogger_Logger::instance()->error(
sprintf(
'Cloudflare image gen HTTP %d (token_prefix=%s, token_len=%d, account=%s): %s',
$status,
substr( $api_token, 0, 4 ),
strlen( $api_token ),
substr( $account_id, 0, 6 ),
substr( $raw, 0, 300 )
),
'cloudflare-image'
);
}
}

View File

@@ -71,7 +71,11 @@ class PRAutoBlogger_Cloudflare_Image_Validator {
); );
return $this->err( return $this->err(
'wp_error:' . $msg, 'wp_error:' . $msg,
sprintf( __( 'Network error reaching Cloudflare: %s', 'prautoblogger' ), $msg ) sprintf(
/* translators: %s: transport-layer error message. */
esc_html__( 'Network error reaching Cloudflare: %s', 'prautoblogger' ),
esc_html( $msg )
)
); );
} }
@@ -90,7 +94,12 @@ class PRAutoBlogger_Cloudflare_Image_Validator {
); );
return $this->err( return $this->err(
sprintf( 'http_%d', $status ), sprintf( 'http_%d', $status ),
sprintf( __( 'Cloudflare returned HTTP %1$d. %2$s', 'prautoblogger' ), $status, substr( $body, 0, 200 ) ) sprintf(
/* translators: %1$d: HTTP status, %2$s: response body. */
esc_html__( 'Cloudflare returned HTTP %1$d. %2$s', 'prautoblogger' ),
$status,
esc_html( substr( $body, 0, 200 ) )
)
); );
} }

View File

@@ -308,39 +308,29 @@ class CloudflareImageProviderTest extends BaseTestCase {
public function test_generate_image_retries_on_5xx_then_succeeds(): void { public function test_generate_image_retries_on_5xx_then_succeeds(): void {
$this->with_token( 'test-token' ); $this->with_token( 'test-token' );
$codes = [ 500, 200 ]; $response_codes = [ 500, 200 ];
Functions\when( 'wp_remote_post' )->alias( $response_bodies = [ 'upstream hiccup', self::FAKE_IMAGE_BYTES ];
function () use ( &$codes ) {
$code = array_shift( $codes ) ?? 200;
return [
'body' => 500 === $code ? 'upstream hiccup' : self::FAKE_IMAGE_BYTES,
'response' => [ 'code' => $code ],
'headers' => [ 'content-type' => 500 === $code ? 'text/plain' : 'image/png' ],
];
}
);
$response_codes = [ 500, 200 ]; Functions\when( 'wp_remote_post' )->justReturn( [
'body' => self::FAKE_IMAGE_BYTES,
'response' => [ 'code' => 200 ],
'headers' => [ 'content-type' => 'image/png' ],
] );
Functions\when( 'wp_remote_retrieve_response_code' )->alias( Functions\when( 'wp_remote_retrieve_response_code' )->alias(
function () use ( &$response_codes ) { function () use ( &$response_codes ) {
return array_shift( $response_codes ) ?? 200; return array_shift( $response_codes ) ?? 200;
} }
); );
$response_bodies = [ 'upstream hiccup', self::FAKE_IMAGE_BYTES ];
Functions\when( 'wp_remote_retrieve_body' )->alias( Functions\when( 'wp_remote_retrieve_body' )->alias(
function () use ( &$response_bodies ) { function () use ( &$response_bodies ) {
return array_shift( $response_bodies ) ?? self::FAKE_IMAGE_BYTES; return array_shift( $response_bodies ) ?? self::FAKE_IMAGE_BYTES;
} }
); );
$mime_types = [ 'text/plain', 'image/png' ]; // wp_remote_retrieve_header is called only on the success attempt —
Functions\when( 'wp_remote_retrieve_header' )->alias( // the 5xx branch returns before any header lookup. One justReturn
function ( $_resp, $name ) use ( &$mime_types ) { // for the content-type is enough; retry-after lookups accept the
if ( 'content-type' === strtolower( (string) $name ) ) { // same stub and will coerce to (int) 0.
return array_shift( $mime_types ) ?? 'image/png'; Functions\when( 'wp_remote_retrieve_header' )->justReturn( 'image/png' );
}
return '';
}
);
$provider = new \PRAutoBlogger_Cloudflare_Image_Provider(); $provider = new \PRAutoBlogger_Cloudflare_Image_Provider();
$result = $provider->generate_image( 'a prompt', 1080, 1080 ); $result = $provider->generate_image( 'a prompt', 1080, 1080 );
@@ -392,38 +382,28 @@ class CloudflareImageProviderTest extends BaseTestCase {
public function test_generate_image_retries_on_429(): void { public function test_generate_image_retries_on_429(): void {
$this->with_token( 'test-token' ); $this->with_token( 'test-token' );
$codes = [ 429, 200 ]; $response_codes = [ 429, 200 ];
Functions\when( 'wp_remote_post' )->alias( $response_bodies = [ 'slow down', self::FAKE_IMAGE_BYTES ];
function () use ( &$codes ) {
$code = array_shift( $codes ) ?? 200; Functions\when( 'wp_remote_post' )->justReturn( [
return [ 'body' => self::FAKE_IMAGE_BYTES,
'body' => 429 === $code ? 'slow down' : self::FAKE_IMAGE_BYTES, 'response' => [ 'code' => 200 ],
'response' => [ 'code' => $code ], 'headers' => [ 'content-type' => 'image/png' ],
'headers' => [ 'content-type' => 429 === $code ? 'text/plain' : 'image/png' ], ] );
];
}
);
$response_codes = [ 429, 200 ];
Functions\when( 'wp_remote_retrieve_response_code' )->alias( Functions\when( 'wp_remote_retrieve_response_code' )->alias(
function () use ( &$response_codes ) { function () use ( &$response_codes ) {
return array_shift( $response_codes ) ?? 200; return array_shift( $response_codes ) ?? 200;
} }
); );
$response_bodies = [ 'slow down', self::FAKE_IMAGE_BYTES ];
Functions\when( 'wp_remote_retrieve_body' )->alias( Functions\when( 'wp_remote_retrieve_body' )->alias(
function () use ( &$response_bodies ) { function () use ( &$response_bodies ) {
return array_shift( $response_bodies ) ?? self::FAKE_IMAGE_BYTES; return array_shift( $response_bodies ) ?? self::FAKE_IMAGE_BYTES;
} }
); );
$mime_types = [ 'text/plain', 'image/png' ]; // Content-type is only read on the success attempt; retry-after is
Functions\when( 'wp_remote_retrieve_header' )->alias( // read on the 429 attempt and (int)-coerces anything non-numeric
function ( $_resp, $name ) use ( &$mime_types ) { // back to 0, falling through to exponential backoff.
if ( 'content-type' === strtolower( (string) $name ) ) { Functions\when( 'wp_remote_retrieve_header' )->justReturn( 'image/png' );
return array_shift( $mime_types ) ?? 'image/png';
}
return '';
}
);
$provider = new \PRAutoBlogger_Cloudflare_Image_Provider(); $provider = new \PRAutoBlogger_Cloudflare_Image_Provider();
$result = $provider->generate_image( 'a prompt', 1080, 1080 ); $result = $provider->generate_image( 'a prompt', 1080, 1080 );