From c1c71d5d02f27f070f8508865ce778043b0566af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Fri, 27 Nov 2026 08:33:09 +0300 Subject: [PATCH 1/2] fix(client): parse Retry-After per RFC 9110 and never retry a cURL read source Retry-After delay-seconds is now only ASCII digits, so -5 is no longer read as a date offset and 1.5, tomorrow or now fall back to the backoff delay. The IMF-fixdate, RFC 850 and asctime forms are all read as GMT instead of in PHP's default time zone. A request is also sent once while the client's cURL options set CURLOPT_INFILE, CURLOPT_READFUNCTION or CURLOPT_READDATA, because the first attempt consumes that read source and a retry would send an empty body. --- CHANGELOG.md | 11 +++ README.md | 5 +- docs/Client-Configuration.md | 2 +- docs/Client-Retry.md | 10 ++- src/Client/Client.php | 32 +++++-- src/Client/Retry/RetryAfter.php | 96 ++++++++++++++++++--- src/Client/Retry/RetryPolicy.php | 6 ++ tests/Unit/Client/Retry/ClientRetryTest.php | 60 +++++++++++++ tests/Unit/Client/Retry/RetryAfterTest.php | 95 +++++++++++++++++++- 9 files changed, 293 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75f0085..4a321d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ All notable changes to **initphp/http** will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- `RetryAfter` now follows RFC 9110 §10.2.3. Delay-seconds is only a run of ASCII digits, so `-5` no longer becomes a date (it was read as an offset of 18000 seconds), and `1.5` or relative words such as `tomorrow` and `now` are ignored (`null`, so the client falls back to its backoff). All three HTTP-date formats (IMF-fixdate, RFC 850 and asctime) are read as GMT; asctime used to be read in PHP's default time zone, which shifted the delay by the zone's offset. +- A request is no longer retried while the client's cURL options set `CURLOPT_INFILE`, `CURLOPT_READFUNCTION` or `CURLOPT_READDATA`. The first attempt consumes that read source, so the retry sent an empty body; now the first response is returned, or the first exception is thrown. + +### Documentation + +- [Client Retry](docs/Client-Retry.md), Client Configuration, the README and the `RetryPolicy` docblock describe the stricter `Retry-After` parsing and the cURL read-source rule. + ## [5.0.0] - 2026-11-25 ### Changed (breaking) diff --git a/README.md b/README.md index 39e9455..019a802 100644 --- a/README.md +++ b/README.md @@ -180,8 +180,9 @@ Behaviour and backward-compatibility: response); a transport exception that exhausts the cap is re-thrown. - Only **idempotent methods** (`GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT`, `DELETE`) are retried by default; `POST` and `PATCH` are sent once unless you list them in - `retryableMethods`. A request whose body is not seekable is also sent once, - since a retry could not send the body again. + `retryableMethods`. A request whose body is not seekable, or whose client sets a cURL read source + (`CURLOPT_INFILE`, `CURLOPT_READFUNCTION`, `CURLOPT_READDATA`), is also sent + once, since a retry could not send the body again. - A parseable `Retry-After` header (delay-seconds or HTTP-date) on a retryable response **overrides** the computed backoff, capped at `maxDelay`, unless you disable it. diff --git a/docs/Client-Configuration.md b/docs/Client-Configuration.md index ace004b..a43826e 100644 --- a/docs/Client-Configuration.md +++ b/docs/Client-Configuration.md @@ -121,7 +121,7 @@ $client = (new Client())->withRetryPolicy(new RetryPolicy( - Retried by default: transport exceptions (`retryOnException`) and the status codes `408`, `425`, `429`, `500`, `502`, `503` and `504` (`retryableStatusCodes`). - Only **idempotent methods** are retried by default: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`. A `POST` or `PATCH` is sent once; list it in `retryableMethods` to opt in. -- A request whose body is not seekable is sent once too, because a retry could not send the body again. +- A request whose body is not seekable is sent once too, because a retry could not send the body again. The same holds while the client's cURL options set `CURLOPT_INFILE`, `CURLOPT_READFUNCTION` or `CURLOPT_READDATA`: that read source is used up by the first attempt. - A parseable `Retry-After` header on a retryable response overrides the computed backoff, up to `maxDelay`, unless `respectRetryAfter` is `false`. - A non-retryable `4xx`/`5xx` response is still **returned, never thrown**. A retryable response that exhausts `maxAttempts` is returned as-is; a transport exception that exhausts it is re-thrown. diff --git a/docs/Client-Retry.md b/docs/Client-Retry.md index 6164114..cbc4825 100644 --- a/docs/Client-Retry.md +++ b/docs/Client-Retry.md @@ -25,10 +25,11 @@ The wait is the [`Backoff`](#backoff) delay for that attempt, or the `Retry-Afte ### Which requests are retried -A retry sends the request again, so two kinds of request are **sent exactly once**, whatever the status or exception: +A retry sends the request again, so three kinds of request are **sent exactly once**, whatever the status or exception: - **A method that is not in `retryableMethods`.** By default only the idempotent methods of RFC 9110 §9.2.2 are retried: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`. `POST` and `PATCH` are not, because the server may already have acted on a request that failed on the way back, and a retry would run it twice. To retry them anyway, list them in `retryableMethods` (see below), ideally together with an idempotency key the server honours. - **A request whose body cannot be rewound.** Each attempt reads the body from the start. A stream that is not seekable (a socket, a pipe, a request body read once) is already used up after the first attempt, so a retry would send an **empty** body. Such a request is not retried; its first response is returned, or its first exception is thrown. Strings, `php://temp` and files are seekable and are retried normally. +- **A request on a client whose cURL options set a read source.** `CURLOPT_INFILE`, `CURLOPT_READFUNCTION` and `CURLOPT_READDATA` (the same option as `CURLOPT_INFILE` in ext-curl) make cURL read the body from a resource or a callback. The first attempt consumes it and it cannot be rewound, so a retry would send an empty body. While any of them is set through `setCurlOptions()`, the client sends each request once: the first response is returned, or the first exception is thrown. Clear the option (or use a client without it) to get retries back. Because `withRetryPolicy()` returns a clone, you can keep a retrying client for safe calls and a plain one for the rest. @@ -148,7 +149,7 @@ $backoff->delayFor(3); // 2.0, the lower edge of the jitter range ## `RetryAfter` -`final class RetryAfter` reads the `Retry-After` response header (RFC 7231 §7.1.3). Both methods are static and return a delay in seconds as a `?float`; `null` means "no usable value", and the client then falls back to the backoff delay. +`final class RetryAfter` reads the `Retry-After` response header (RFC 9110 §10.2.3). Both methods are static and return a delay in seconds as a `?float`; `null` means "no usable value", and the client then falls back to the backoff delay. | Method | Description | | --- | --- | @@ -160,8 +161,9 @@ $backoff->delayFor(3); // 2.0, the lower edge of the jitter range `parse()` follows these rules, in order: 1. The value is trimmed. An empty string gives `null`. -2. A value made only of digits is a number of seconds: `'120'` gives `120.0`. -3. Anything else goes to `strtotime()`. If that fails, the result is `null`. Otherwise the result is the difference to `$now`, never below `0`, so a date in the past gives `0.0`. +2. A value made only of ASCII digits (`^\d+$`) is a number of seconds: `'120'` gives `120.0`. A sign (`-5`, `+5`), a fraction (`1.5`) or an exponent (`1e3`) is not delay-seconds, and the value is not tried as a date either. +3. A value in one of the three HTTP-date formats of RFC 9110 §5.6.7 is a date: IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`), the obsolete RFC 850 form (`Sunday, 06-Nov-94 08:49:37 GMT`) and asctime (`Sun Nov 6 08:49:37 1994`). Every form is read as **GMT**; the PHP default time zone is never used, so the result does not depend on `date_default_timezone_set()` or `TZ`. In the RFC 850 form a two-digit year that would be more than 50 years ahead stands for the most recent past year with those digits. The result is the difference to `$now`, never below `0`, so a date in the past gives `0.0`. A date that does not exist (`31 Feb`) is `null`. +4. Anything else is `null`, including relative phrases such as `tomorrow`, `now` or `+1 hour`, and ISO 8601 or zoned dates. The client then uses the backoff delay. ```php use InitPHP\HTTP\Client\Retry\RetryAfter; diff --git a/src/Client/Client.php b/src/Client/Client.php index 42ccf1c..4328c35 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -49,6 +49,17 @@ */ class Client implements \Psr\Http\Client\ClientInterface { + /** + * cURL options that make cURL read the request body from a resource or a + * callback instead of the PSR-7 stream. Such a source is consumed by the + * first attempt and cannot be rewound, so a request with any of them set + * is never retried. CURLOPT_READDATA is the same option number as + * CURLOPT_INFILE in ext-curl, so listing CURLOPT_INFILE covers both. + * + * @var list + */ + private const NON_REPLAYABLE_CURL_OPTIONS = [\CURLOPT_INFILE, \CURLOPT_READFUNCTION]; + protected string $userAgent = 'InitPHP HTTP PSR-18 Client cURL'; /** @@ -510,8 +521,10 @@ public function sendRequest(RequestInterface $request): ResponseInterface // A request that must not be replayed gets a single attempt: a method // that is not idempotent may already have been acted on by the server, - // and a body that cannot be rewound would be re-sent empty. In both - // cases the first outcome (response or exception) is the answer. + // and a body that cannot be rewound (a PSR-7 stream that is not + // seekable, or a cURL read source set through CURLOPT_INFILE or + // CURLOPT_READFUNCTION) would be re-sent empty. In every case the + // first outcome (response or exception) is the answer. if (!$this->isReplayable($policy, $request)) { return $this->transport($request); } @@ -547,9 +560,12 @@ public function sendRequest(RequestInterface $request): ResponseInterface /** * Whether $request may be sent more than once under $policy: its method - * is retryable and its body can be rewound. Any failure while reading - * those two accessors counts as "not replayable"; the single attempt that - * follows reports it as a {@see RequestException}, as PSR-18 requires. + * is retryable, its body can be rewound and no cURL read source is + * configured (CURLOPT_INFILE, CURLOPT_READFUNCTION and CURLOPT_READDATA + * feed the body from a resource or callback that the first attempt has + * already consumed). Any failure while reading the request accessors + * counts as "not replayable"; the single attempt that follows reports it + * as a {@see RequestException}, as PSR-18 requires. * * @param RetryPolicy $policy * @param RequestInterface $request @@ -557,6 +573,12 @@ public function sendRequest(RequestInterface $request): ResponseInterface */ private function isReplayable(RetryPolicy $policy, RequestInterface $request): bool { + foreach (self::NON_REPLAYABLE_CURL_OPTIONS as $option) { + if (\array_key_exists($option, $this->curlOptions)) { + return false; + } + } + try { return $policy->isRetryableMethod($request->getMethod()) && $request->getBody()->isSeekable(); } catch (\Throwable $e) { diff --git a/src/Client/Retry/RetryAfter.php b/src/Client/Retry/RetryAfter.php index d33287a..1d18e75 100644 --- a/src/Client/Retry/RetryAfter.php +++ b/src/Client/Retry/RetryAfter.php @@ -15,25 +15,34 @@ namespace InitPHP\HTTP\Client\Retry; +use DateTimeImmutable; +use DateTimeZone; use Psr\Http\Message\ResponseInterface; -use function ctype_digit; +use function is_array; use function max; -use function strtotime; +use function preg_match; +use function preg_replace; use function time; use function trim; /** - * Parses the `Retry-After` response header (RFC 7231 §7.1.3) into a delay in + * Parses the `Retry-After` response header (RFC 9110 §10.2.3) into a delay in * seconds. * * The header takes one of two forms: - * - a non-negative integer number of seconds (`Retry-After: 120`), or + * - delay-seconds: one or more ASCII digits and nothing else + * (`Retry-After: 120`), or * - an HTTP-date (`Retry-After: Wed, 21 Oct 2015 07:28:00 GMT`), from which - * the delay is the difference between that instant and "now". + * the delay is the difference between that instant and "now". All three + * HTTP-date formats of RFC 9110 §5.6.7 are accepted (IMF-fixdate, the + * obsolete RFC 850 form and asctime) and are always read as GMT; PHP's + * default time zone plays no part. * - * Unparseable or absent headers yield `null`, leaving the caller free to fall - * back to its computed backoff. A past HTTP-date clamps to 0. + * Anything else (a negative or fractional number, a relative phrase such as + * `tomorrow`, an unparseable date) and an absent header yield `null`, leaving + * the caller free to fall back to its computed backoff. A past HTTP-date + * clamps to 0. */ final class RetryAfter { @@ -71,12 +80,12 @@ public static function parse(string $value, ?int $now = null): ?float return null; } - if (ctype_digit($value)) { + if (preg_match('/^\d+$/D', $value) === 1) { return (float) $value; } - $timestamp = strtotime($value); - if ($timestamp === false) { + $timestamp = self::parseHttpDate($value); + if ($timestamp === null) { return null; } @@ -84,4 +93,71 @@ public static function parse(string $value, ?int $now = null): ?float return (float) max(0, $timestamp - $reference); } + + /** + * Parse an HTTP-date (RFC 9110 §5.6.7) into a Unix timestamp, reading it as + * GMT. Returns null when the value matches none of the three formats or + * names a date that does not exist (such as 31 February). + * + * @param string $value + * @return int|null + */ + private static function parseHttpDate(string $value): ?int + { + $utc = new DateTimeZone('UTC'); + + // IMF-fixdate: Sun, 06 Nov 1994 08:49:37 GMT + if (preg_match('/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/D', $value) === 1) { + return self::fromFormat('D, d M Y H:i:s \G\M\T', $value, $utc); + } + + // RFC 850 (obsolete): Sunday, 06-Nov-94 08:49:37 GMT + if (preg_match('/^[A-Z][a-z]{5,8}, \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT$/D', $value) === 1) { + $timestamp = self::fromFormat('l, d-M-y H:i:s \G\M\T', $value, $utc); + if ($timestamp === null) { + return null; + } + + // RFC 9110 §5.6.7: a two-digit year that would land more than 50 + // years in the future stands for the most recent past year with + // the same last two digits. + $limit = new DateTimeImmutable('+50 years', $utc); + if ($timestamp > $limit->getTimestamp()) { + $shifted = (new DateTimeImmutable('@' . $timestamp))->setTimezone($utc)->modify('-100 years'); + + return $shifted->getTimestamp(); + } + + return $timestamp; + } + + // asctime: Sun Nov 6 08:49:37 1994 (the day is space-padded) + if (preg_match('/^[A-Z][a-z]{2} [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/D', $value) === 1) { + $single = preg_replace('/ {2,}/', ' ', $value); + + return $single === null ? null : self::fromFormat('D M j H:i:s Y', $single, $utc); + } + + return null; + } + + /** + * Build a timestamp from $value with $format in $zone, rejecting values + * that PHP would silently roll over (31 February, 25:00:00, ...). + * + * @param string $format + * @param string $value + * @param DateTimeZone $zone + * @return int|null + */ + private static function fromFormat(string $format, string $value, DateTimeZone $zone): ?int + { + $date = DateTimeImmutable::createFromFormat('!' . $format, $value, $zone); + $errors = DateTimeImmutable::getLastErrors(); + if ($date === false || (is_array($errors) && ($errors['warning_count'] > 0 || $errors['error_count'] > 0))) { + return null; + } + + return $date->getTimestamp(); + } } diff --git a/src/Client/Retry/RetryPolicy.php b/src/Client/Retry/RetryPolicy.php index 131c947..8c0696d 100644 --- a/src/Client/Retry/RetryPolicy.php +++ b/src/Client/Retry/RetryPolicy.php @@ -37,6 +37,12 @@ * for idempotent methods (RFC 9110 §9.2.2), so a request the server may already * have acted on is never replayed by default. The client itself stays * single-attempt unless a policy is explicitly attached. + * + * A request whose body cannot be sent twice is never retried, whatever the + * policy says: its first response is returned, or its first exception is + * thrown. That covers a body stream that is not seekable and a client whose + * cURL options set a read source (`CURLOPT_INFILE`, `CURLOPT_READFUNCTION` or + * `CURLOPT_READDATA`), because the first attempt consumes it. */ final class RetryPolicy { diff --git a/tests/Unit/Client/Retry/ClientRetryTest.php b/tests/Unit/Client/Retry/ClientRetryTest.php index 55fb612..111f7dc 100644 --- a/tests/Unit/Client/Retry/ClientRetryTest.php +++ b/tests/Unit/Client/Retry/ClientRetryTest.php @@ -424,6 +424,66 @@ public function testRequestWithNonSeekableBodyIsNotRetriedOnException(): void } } + /** + * @return array + */ + public static function curlReadSources(): array + { + return [ + 'CURLOPT_INFILE' => [\CURLOPT_INFILE, static fn() => \fopen('php://memory', 'r+')], + 'CURLOPT_READDATA' => [\CURLOPT_READDATA, static fn() => \fopen('php://memory', 'r+')], + 'CURLOPT_READFUNCTION' => [\CURLOPT_READFUNCTION, static fn() => static fn($ch, $fd, $length) => ''], + ]; + } + + /** + * @dataProvider curlReadSources + */ + public function testRequestWithCurlReadSourceIsSentOnceOnRetryableStatus(int $option, callable $value): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([$this->response(503), $this->response(200)]); + $client->setSleeper($sleeper) + ->setCurlOptions([$option => $value()]) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + $response = $client->sendRequest(new Request('PUT', 'https://api.example.com/resource')); + + self::assertSame(503, $response->getStatusCode(), 'the first response is returned'); + self::assertSame(1, $client->calls); + self::assertCount(0, $sleeper->sleeps); + } + + public function testRequestWithCurlReadSourceIsSentOnceOnTransportException(): void + { + $client = new ScriptedClient([$this->networkError(), $this->response(200)]); + $client->setSleeper(new RecordingSleeper()) + ->setCurlOptions([\CURLOPT_INFILE => \fopen('php://memory', 'r+')]) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + try { + $client->sendRequest(new Request('PUT', 'https://api.example.com/resource')); + self::fail('The first transport exception must propagate.'); + } catch (NetworkException $e) { + self::assertSame(1, $client->calls); + } + } + + public function testClearingTheCurlReadSourceRestoresRetries(): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([$this->response(503), $this->response(200)]); + $client->setSleeper($sleeper) + ->setCurlOptions([\CURLOPT_INFILE => \fopen('php://memory', 'r+')]) + ->setCurlOptions([\CURLOPT_TIMEOUT => 5]) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + $response = $client->sendRequest(new Request('PUT', 'https://api.example.com/resource')); + + self::assertSame(200, $response->getStatusCode()); + self::assertSame(2, $client->calls); + } + public function testRequestWithSeekableBodyIsStillRetried(): void { $client = new ScriptedClient([$this->response(503), $this->response(200)]); diff --git a/tests/Unit/Client/Retry/RetryAfterTest.php b/tests/Unit/Client/Retry/RetryAfterTest.php index 37b2c7a..9108973 100644 --- a/tests/Unit/Client/Retry/RetryAfterTest.php +++ b/tests/Unit/Client/Retry/RetryAfterTest.php @@ -9,8 +9,9 @@ use PHPUnit\Framework\TestCase; /** - * Unit coverage for the RFC 7231 `Retry-After` parser: delay-seconds form, - * HTTP-date form, past dates clamped to zero, and graceful null on garbage. + * Unit coverage for the RFC 9110 `Retry-After` parser: delay-seconds form, + * the three HTTP-date forms read as GMT, past dates clamped to zero, and + * graceful null on anything else. */ final class RetryAfterTest extends TestCase { @@ -45,6 +46,96 @@ public function testGarbageReturnsNull(): void self::assertNull(RetryAfter::parse(' ')); } + /** + * @return array + */ + public static function invalidValues(): array + { + return [ + 'negative' => ['-5'], + 'negative zero' => ['-0'], + 'plus sign' => ['+5'], + 'fractional' => ['1.5'], + 'exponent' => ['1e3'], + 'relative phrase' => ['tomorrow'], + 'now' => ['now'], + 'relative offset' => ['+1 hour'], + 'trailing words' => ['120 seconds'], + 'iso 8601' => ['2015-10-21T07:28:00Z'], + 'date with zone' => ['Wed, 21 Oct 2015 07:28:00 +0300'], + 'nonexistent day' => ['Tue, 31 Feb 2015 07:28:00 GMT'], + 'hour out of range' => ['Wed, 21 Oct 2015 25:00:00 GMT'], + ]; + } + + /** + * @dataProvider invalidValues + */ + public function testInvalidValuesReturnNull(string $value): void + { + self::assertNull(RetryAfter::parse($value, 1445412480)); + } + + public function testParsesRfc850Date(): void + { + $now = \strtotime('Sun, 06 Nov 1994 08:48:37 GMT'); + self::assertIsInt($now); + + $delay = RetryAfter::parse('Sunday, 06-Nov-94 08:49:37 GMT', $now); + self::assertEqualsWithDelta(60.0, $delay, 1e-9); + } + + public function testRfc850TwoDigitYearInTheFarFutureMeansThePast(): void + { + // 94 would be 2094 under a plain "20yy" reading, over 50 years ahead + // of any current date, so it stands for 1994 and clamps to zero. + self::assertSame(0.0, RetryAfter::parse('Sunday, 06-Nov-94 08:49:37 GMT')); + } + + public function testParsesAsctimeDate(): void + { + $now = \strtotime('Sun, 06 Nov 1994 08:48:37 GMT'); + self::assertIsInt($now); + + self::assertEqualsWithDelta(60.0, RetryAfter::parse('Sun Nov 6 08:49:37 1994', $now), 1e-9); + self::assertEqualsWithDelta(60.0, RetryAfter::parse('Sun Nov 06 08:49:37 1994', $now), 1e-9); + } + + public function testAsctimeDateIsReadAsGmtNotInThePhpDefaultTimeZone(): void + { + $previous = \date_default_timezone_get(); + \date_default_timezone_set('Europe/Istanbul'); // UTC+3 + try { + $now = \strtotime('Wed, 21 Oct 2015 07:28:00 GMT'); + self::assertIsInt($now); + + $delay = RetryAfter::parse('Wed Oct 21 07:29:00 2015', $now); + self::assertEqualsWithDelta(60.0, $delay, 1e-9, 'asctime carries no zone and means GMT'); + } finally { + \date_default_timezone_set($previous); + } + } + + public function testEveryHttpDateFormIsGmtUnderANonUtcDefaultTimeZone(): void + { + $previous = \date_default_timezone_get(); + \date_default_timezone_set('America/Los_Angeles'); + try { + $now = \strtotime('Sun, 06 Nov 1994 08:48:37 GMT'); + self::assertIsInt($now); + + foreach ([ + 'Sun, 06 Nov 1994 08:49:37 GMT', + 'Sunday, 06-Nov-94 08:49:37 GMT', + 'Sun Nov 6 08:49:37 1994', + ] as $value) { + self::assertEqualsWithDelta(60.0, RetryAfter::parse($value, $now), 1e-9, $value); + } + } finally { + \date_default_timezone_set($previous); + } + } + public function testFromResponseReadsHeader(): void { $response = new Response(429, ['Retry-After' => '30']); From 0f830ea98e58c2acc5fabf51445842942b507462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Fri, 27 Nov 2026 08:39:50 +0300 Subject: [PATCH 2/2] fix(client): reject a Retry-After date whose day name does not match DateTimeImmutable::createFromFormat() does not validate the D and l tokens, it shifts the date to the next such weekday, so a wrong day name was read as a date up to six days ahead. The day name is now captured and compared with the parsed date, and the date is rejected on a mismatch. The two-digit year of the RFC 850 form now follows the RFC 9110 50-year rule instead of PHP's fixed 1970 pivot, which made the old rule dead code. --- CHANGELOG.md | 2 +- docs/Client-Retry.md | 2 +- src/Client/Retry/RetryAfter.php | 78 ++++++++++++++-------- tests/Unit/Client/Retry/RetryAfterTest.php | 54 +++++++++++++-- 4 files changed, 101 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a321d4..f9fff36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- `RetryAfter` now follows RFC 9110 §10.2.3. Delay-seconds is only a run of ASCII digits, so `-5` no longer becomes a date (it was read as an offset of 18000 seconds), and `1.5` or relative words such as `tomorrow` and `now` are ignored (`null`, so the client falls back to its backoff). All three HTTP-date formats (IMF-fixdate, RFC 850 and asctime) are read as GMT; asctime used to be read in PHP's default time zone, which shifted the delay by the zone's offset. +- `RetryAfter` now follows RFC 9110 §10.2.3. Delay-seconds is only a run of ASCII digits, so `-5` no longer becomes a date (it was read as an offset of 18000 seconds), and `1.5` or relative words such as `tomorrow` and `now` are ignored (`null`, so the client falls back to its backoff). All three HTTP-date formats (IMF-fixdate, RFC 850 and asctime) are read as GMT; asctime used to be read in PHP's default time zone, which shifted the delay by the zone's offset. A date whose day name does not match its date (`Mon, 21 Oct 2015 ...`) is rejected, and the two-digit year of the RFC 850 form follows the RFC's 50-year rule instead of PHP's fixed 1970 pivot. - A request is no longer retried while the client's cURL options set `CURLOPT_INFILE`, `CURLOPT_READFUNCTION` or `CURLOPT_READDATA`. The first attempt consumes that read source, so the retry sent an empty body; now the first response is returned, or the first exception is thrown. ### Documentation diff --git a/docs/Client-Retry.md b/docs/Client-Retry.md index cbc4825..36ac5fc 100644 --- a/docs/Client-Retry.md +++ b/docs/Client-Retry.md @@ -162,7 +162,7 @@ $backoff->delayFor(3); // 2.0, the lower edge of the jitter range 1. The value is trimmed. An empty string gives `null`. 2. A value made only of ASCII digits (`^\d+$`) is a number of seconds: `'120'` gives `120.0`. A sign (`-5`, `+5`), a fraction (`1.5`) or an exponent (`1e3`) is not delay-seconds, and the value is not tried as a date either. -3. A value in one of the three HTTP-date formats of RFC 9110 §5.6.7 is a date: IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`), the obsolete RFC 850 form (`Sunday, 06-Nov-94 08:49:37 GMT`) and asctime (`Sun Nov 6 08:49:37 1994`). Every form is read as **GMT**; the PHP default time zone is never used, so the result does not depend on `date_default_timezone_set()` or `TZ`. In the RFC 850 form a two-digit year that would be more than 50 years ahead stands for the most recent past year with those digits. The result is the difference to `$now`, never below `0`, so a date in the past gives `0.0`. A date that does not exist (`31 Feb`) is `null`. +3. A value in one of the three HTTP-date formats of RFC 9110 §5.6.7 is a date: IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`), the obsolete RFC 850 form (`Sunday, 06-Nov-94 08:49:37 GMT`) and asctime (`Sun Nov 6 08:49:37 1994`). Every form is read as **GMT**; the PHP default time zone is never used, so the result does not depend on `date_default_timezone_set()` or `TZ`. In the RFC 850 form a two-digit year that would be more than 50 years ahead stands for the most recent past year with those digits. The result is the difference to `$now`, never below `0`, so a date in the past gives `0.0`. A date that does not exist (`31 Feb`) is `null`, and so is a date whose day name does not match it (`Mon, 21 Oct 2015 07:28:00 GMT` is a Wednesday). The day name must also use the form of its format: three letters in IMF-fixdate and asctime, the full name in RFC 850. 4. Anything else is `null`, including relative phrases such as `tomorrow`, `now` or `+1 hour`, and ISO 8601 or zoned dates. The client then uses the backoff delay. ```php diff --git a/src/Client/Retry/RetryAfter.php b/src/Client/Retry/RetryAfter.php index 1d18e75..f2c2e53 100644 --- a/src/Client/Retry/RetryAfter.php +++ b/src/Client/Retry/RetryAfter.php @@ -22,7 +22,6 @@ use function is_array; use function max; use function preg_match; -use function preg_replace; use function time; use function trim; @@ -84,7 +83,7 @@ public static function parse(string $value, ?int $now = null): ?float return (float) $value; } - $timestamp = self::parseHttpDate($value); + $timestamp = self::parseHttpDate($value, $now); if ($timestamp === null) { return null; } @@ -96,61 +95,82 @@ public static function parse(string $value, ?int $now = null): ?float /** * Parse an HTTP-date (RFC 9110 §5.6.7) into a Unix timestamp, reading it as - * GMT. Returns null when the value matches none of the three formats or - * names a date that does not exist (such as 31 February). + * GMT. Returns null when the value matches none of the three formats, + * names a date that does not exist (such as 31 February) or carries a day + * name that does not belong to its date (`Mon, 21 Oct 2015 ...` is a + * Wednesday). * - * @param string $value + * The day name is checked here instead of being left to + * DateTimeImmutable::createFromFormat(): its `D` and `l` tokens do not + * validate the name, they shift the date to the next such weekday. + * + * @param string $value + * @param int|null $now Reference "now" for the RFC 850 two-digit year rule. * @return int|null */ - private static function parseHttpDate(string $value): ?int + private static function parseHttpDate(string $value, ?int $now): ?int { $utc = new DateTimeZone('UTC'); // IMF-fixdate: Sun, 06 Nov 1994 08:49:37 GMT - if (preg_match('/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/D', $value) === 1) { - return self::fromFormat('D, d M Y H:i:s \G\M\T', $value, $utc); + if (preg_match('/^([A-Z][a-z]{2}), (\d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2}) GMT$/D', $value, $m) === 1) { + $date = self::fromFormat('d M Y H:i:s', $m[2], $utc); + + return self::hasWeekday($date, 'D', $m[1]) ? $date?->getTimestamp() : null; } // RFC 850 (obsolete): Sunday, 06-Nov-94 08:49:37 GMT - if (preg_match('/^[A-Z][a-z]{5,8}, \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT$/D', $value) === 1) { - $timestamp = self::fromFormat('l, d-M-y H:i:s \G\M\T', $value, $utc); - if ($timestamp === null) { - return null; - } - + if (preg_match('/^([A-Z][a-z]{5,8}), (\d{2})-([A-Z][a-z]{2})-(\d{2}) (\d{2}:\d{2}:\d{2}) GMT$/D', $value, $m) === 1) { // RFC 9110 §5.6.7: a two-digit year that would land more than 50 // years in the future stands for the most recent past year with - // the same last two digits. - $limit = new DateTimeImmutable('+50 years', $utc); - if ($timestamp > $limit->getTimestamp()) { - $shifted = (new DateTimeImmutable('@' . $timestamp))->setTimezone($utc)->modify('-100 years'); - - return $shifted->getTimestamp(); + // the same last two digits. PHP's own `y` token uses a fixed 1970 + // pivot instead, so the century is chosen here. + $limit = (new DateTimeImmutable('@' . ($now ?? time())))->modify('+50 years')->getTimestamp(); + foreach (['20', '19'] as $century) { + $date = self::fromFormat('d-M-Y H:i:s', $m[2] . '-' . $m[3] . '-' . $century . $m[4] . ' ' . $m[5], $utc); + if ($date !== null && $date->getTimestamp() <= $limit) { + break; + } } - return $timestamp; + return self::hasWeekday($date, 'l', $m[1]) ? $date?->getTimestamp() : null; } // asctime: Sun Nov 6 08:49:37 1994 (the day is space-padded) - if (preg_match('/^[A-Z][a-z]{2} [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/D', $value) === 1) { - $single = preg_replace('/ {2,}/', ' ', $value); + if (preg_match('/^([A-Z][a-z]{2}) ([A-Z][a-z]{2}) ([ \d]\d) (\d{2}:\d{2}:\d{2}) (\d{4})$/D', $value, $m) === 1) { + $date = self::fromFormat('j M Y H:i:s', trim($m[3]) . ' ' . $m[2] . ' ' . $m[5] . ' ' . $m[4], $utc); - return $single === null ? null : self::fromFormat('D M j H:i:s Y', $single, $utc); + return self::hasWeekday($date, 'D', $m[1]) ? $date?->getTimestamp() : null; } return null; } /** - * Build a timestamp from $value with $format in $zone, rejecting values - * that PHP would silently roll over (31 February, 25:00:00, ...). + * Whether $date falls on the weekday named by $name. $token is the + * DateTimeInterface::format() token for the name's form: `D` for the + * three-letter abbreviation, `l` for the full name. + * + * @param DateTimeImmutable|null $date + * @param string $token + * @param string $name + * @return bool + */ + private static function hasWeekday(?DateTimeImmutable $date, string $token, string $name): bool + { + return $date !== null && $date->format($token) === $name; + } + + /** + * Build a date from $value with $format in $zone, rejecting values that + * PHP would silently roll over (31 February, 25:00:00, ...). * * @param string $format * @param string $value * @param DateTimeZone $zone - * @return int|null + * @return DateTimeImmutable|null */ - private static function fromFormat(string $format, string $value, DateTimeZone $zone): ?int + private static function fromFormat(string $format, string $value, DateTimeZone $zone): ?DateTimeImmutable { $date = DateTimeImmutable::createFromFormat('!' . $format, $value, $zone); $errors = DateTimeImmutable::getLastErrors(); @@ -158,6 +178,6 @@ private static function fromFormat(string $format, string $value, DateTimeZone $ return null; } - return $date->getTimestamp(); + return $date; } } diff --git a/tests/Unit/Client/Retry/RetryAfterTest.php b/tests/Unit/Client/Retry/RetryAfterTest.php index 9108973..c6a80bc 100644 --- a/tests/Unit/Client/Retry/RetryAfterTest.php +++ b/tests/Unit/Client/Retry/RetryAfterTest.php @@ -65,6 +65,12 @@ public static function invalidValues(): array 'date with zone' => ['Wed, 21 Oct 2015 07:28:00 +0300'], 'nonexistent day' => ['Tue, 31 Feb 2015 07:28:00 GMT'], 'hour out of range' => ['Wed, 21 Oct 2015 25:00:00 GMT'], + 'wrong weekday (IMF-fixdate)' => ['Mon, 21 Oct 2015 07:28:00 GMT'], + 'wrong weekday (RFC 850)' => ['Monday, 21-Oct-15 07:28:00 GMT'], + 'wrong weekday (asctime)' => ['Mon Oct 21 07:28:00 2015'], + 'wrong weekday, one day off' => ['Tue, 21 Oct 2015 07:28:00 GMT'], + 'full name in IMF-fixdate' => ['Wednesday, 21 Oct 2015 07:28:00 GMT'], + 'abbreviated name in RFC 850' => ['Wed, 21-Oct-15 07:28:00 GMT'], ]; } @@ -85,11 +91,51 @@ public function testParsesRfc850Date(): void self::assertEqualsWithDelta(60.0, $delay, 1e-9); } - public function testRfc850TwoDigitYearInTheFarFutureMeansThePast(): void + public function testRfc850TwoDigitYearBeyondFiftyYearsMeansThePast(): void { - // 94 would be 2094 under a plain "20yy" reading, over 50 years ahead - // of any current date, so it stands for 1994 and clamps to zero. - self::assertSame(0.0, RetryAfter::parse('Sunday, 06-Nov-94 08:49:37 GMT')); + // With "now" in 2015, 94 would be 2094 (over 50 years ahead), so it + // stands for 1994 and the delay clamps to zero. A plain "20yy" reading + // would give a 79-year wait. + $now = \strtotime('Wed, 21 Oct 2015 07:28:00 GMT'); + self::assertIsInt($now); + + self::assertSame(0.0, RetryAfter::parse('Sunday, 06-Nov-94 08:49:37 GMT', $now)); + } + + public function testRfc850TwoDigitYearWithinFiftyYearsMeansTheFuture(): void + { + // PHP's `y` token pivots at 1970 and would read 75 as 1975 (the past). + // RFC 9110 puts 2075 within 50 years of a 2030 "now", so it is a date + // 45 years ahead. + $now = \strtotime('Tue, 01 Jan 2030 00:00:00 GMT'); + self::assertIsInt($now); + + $delay = RetryAfter::parse('Tuesday, 01-Jan-75 00:00:00 GMT', $now); + self::assertNotNull($delay); + self::assertGreaterThan(0.0, $delay); + self::assertEqualsWithDelta(\strtotime('2075-01-01 00:00:00 GMT') - $now, $delay, 1e-9); + } + + public function testRfc850TwoDigitYearJustInsideAndOutsideTheFiftyYearWindow(): void + { + $now = \strtotime('Thu, 01 Jan 2026 00:00:00 GMT'); + self::assertIsInt($now); + + // 2076-01-01 is exactly 50 years ahead: still the future. + self::assertGreaterThan(0.0, RetryAfter::parse('Wednesday, 01-Jan-76 00:00:00 GMT', $now)); + // 2077-01-01 is past the window: read as 1977, so zero. + self::assertSame(0.0, RetryAfter::parse('Saturday, 01-Jan-77 00:00:00 GMT', $now)); + } + + public function testWeekdayNameIsValidatedNotUsedToShiftTheDate(): void + { + $now = \strtotime('Sun, 06 Nov 1994 08:49:37 GMT'); + self::assertIsInt($now); + + self::assertSame(0.0, RetryAfter::parse('Sun, 06 Nov 1994 08:49:37 GMT', $now)); + self::assertNull(RetryAfter::parse('Mon, 06 Nov 1994 08:49:37 GMT', $now)); + self::assertNull(RetryAfter::parse('Monday, 06-Nov-94 08:49:37 GMT', $now)); + self::assertNull(RetryAfter::parse('Mon Nov 6 08:49:37 1994', $now)); } public function testParsesAsctimeDate(): void