From 03f1f6bb5a699da3459908a744b281b8cda75a32 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 8 Nov 2026 22:39:51 +0100 Subject: [PATCH 01/32] fix(sd-jwt): refuse at issuance the SD-JWTs the Holder and the Verifier reject SDJWTIssuer issued SD-JWTs whose processed payload is deeper than the 64 levels of DisclosureProcessor, or whose Disclosures hold more JSON values than the budget of BoundedJsonDecoder: the Holder and the Verifier then refused them. Before signing, the Issuer now parses an SD-JWT that has the payload, the Disclosures, the serialization and the unprotected headers of the one to issue, then processes it as SDJWT::select() does. Both bounds come from the classes that enforce them, and such claims are refused with an InvalidArgumentException. Fixes #805 --- src/SelectiveDisclosure/SDJWTIssuer.php | 81 +++++ .../SelectiveDisclosure/IssuerBoundsTest.php | 314 ++++++++++++++++++ 2 files changed, 395 insertions(+) create mode 100644 tests/SelectiveDisclosure/IssuerBoundsTest.php diff --git a/src/SelectiveDisclosure/SDJWTIssuer.php b/src/SelectiveDisclosure/SDJWTIssuer.php index 06cf7308..7f879998 100644 --- a/src/SelectiveDisclosure/SDJWTIssuer.php +++ b/src/SelectiveDisclosure/SDJWTIssuer.php @@ -5,9 +5,12 @@ namespace Jose\SelectiveDisclosure; use Jose\Component\Core\Exception\InvalidArgumentException; +use Jose\Component\Core\Exception\InvalidSerializationException; +use Jose\Component\Core\Exception\InvalidTokenException; use Jose\Component\Core\Exception\UnsupportedAlgorithmException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\Base64UrlSafe; +use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\JsonConverter; use Jose\Component\Core\Util\NamedInformationHash; use Jose\Component\Signature\Algorithm\SignatureAlgorithm; @@ -23,6 +26,7 @@ use function array_map; use function array_splice; use function array_unique; +use function array_values; use function count; use function in_array; use function is_array; @@ -58,6 +62,13 @@ * unprotected header of the first signature. The unprotected headers cannot have the "disclosures" and "kb_jwt" * parameters themselves. * + * The claims whose SD-JWT the Holder and the Verifier of this library would reject are refused before signing: the + * Disclosures are parsed, as the Holder and the Verifier parse them, from an SD-JWT that has the serialization and the + * unprotected headers of the one to issue, and its payload is processed with them, as SDJWT::select() does. The bounds + * are thus those of SDJWT::fromString(), the JSON values decoded with the Disclosures, and of the Disclosure + * processing, the depth of the processed payload, in which an object counts with the levels of its JSON and a + * Disclosable adds no level. + * * @see https://www.rfc-editor.org/rfc/rfc9901.html#section-4 * @see https://www.rfc-editor.org/rfc/rfc9901.html#section-8 */ @@ -78,6 +89,12 @@ */ private const DECOY_SIZE = 16; + /** + * A part of a JWS that stands for a protected header or a signature in the SD-JWT the bounds are checked on: the + * parts are base64url strings, which hold no JSON value of their own. + */ + private const PLACEHOLDER_PART = 'A'; + private int $maximumDecoyDigests; /** @@ -113,6 +130,7 @@ public function issue(array $claims, JWK $signatureKey, array $protectedHeader): { self::checkProtectedHeader($this->jwsBuilder, $protectedHeader); [$payload, $disclosures] = $this->payload($claims); + self::checkBounds(SDJWT::create(self::placeholderCompactJws($payload), $disclosures)); $jws = $this->jwsBuilder ->withPayload($payload) ->addSignature($signatureKey, $protectedHeader) @@ -140,6 +158,7 @@ public function issueJson(array $claims, IssuerSignature $signature, IssuerSigna } } [$payload, $disclosures] = $this->payload($claims); + self::checkBounds(self::placeholderJsonSdJwt($payload, $signatures, $disclosures)); $builder = $this->jwsBuilder->withPayload($payload); foreach ($signatures as $issuerSignature) { $builder = $builder->addSignature( @@ -187,6 +206,68 @@ private function payload(array $claims): array return [JsonConverter::encode($payload), $disclosures]; } + /** + * Parses the given SD-JWT as the Holder and the Verifier would, then processes its payload with its Disclosures, as + * the Holder does to select them. + * + * @throws InvalidArgumentException if the Holder or the Verifier would reject the SD-JWT + */ + private static function checkBounds(SDJWT $placeholder): void + { + try { + $sdJwt = SDJWT::fromString($placeholder->toString()); + } catch (InvalidSerializationException $exception) { + throw new InvalidArgumentException(sprintf( + 'The Disclosures of the SD-JWT hold more JSON values than the %d the Holder and the Verifier decode.', + BoundedJsonDecoder::MAX_VALUES + ), 0, $exception); + } + try { + $sdJwt->select(); + } catch (InvalidTokenException $exception) { + throw new InvalidArgumentException($exception->getMessage(), 0, $exception); + } + } + + /** + * A JWS in compact serialization with the given payload, whose protected header and signature are placeholders. + */ + private static function placeholderCompactJws(string $payload): string + { + return self::PLACEHOLDER_PART . '.' . Base64UrlSafe::encodeUnpadded($payload) . '.' . self::PLACEHOLDER_PART; + } + + /** + * An SD-JWT in the JWS JSON serialization with the given payload, signatures and Disclosures, whose protected + * headers and signatures are placeholders: its JSON values are those of the SD-JWT to issue. + * + * @param array $signatures + * @param list $disclosures + */ + private static function placeholderJsonSdJwt(string $payload, array $signatures, array $disclosures): SDJWT + { + $entries = array_values(array_map(static function (IssuerSignature $signature): array { + $entry = [ + 'protected' => self::PLACEHOLDER_PART, + ]; + if ($signature->getHeader() !== []) { + $entry['header'] = $signature->getHeader(); + } + + return $entry + [ + 'signature' => self::PLACEHOLDER_PART, + ]; + }, $signatures)); + $token = [ + 'payload' => Base64UrlSafe::encodeUnpadded($payload), + ]; + $token += count($entries) === 1 ? $entries[0] : [ + 'signatures' => $entries, + ]; + + return SDJWT::create(JsonConverter::encode($token), $disclosures); + } + /** * An object is kept as it is, and the reserved claim names are looked for in its JSON, which is the same in the * payload and in a Disclosure. An enum that is not JsonSerializable has no member but its name and its value: it is diff --git a/tests/SelectiveDisclosure/IssuerBoundsTest.php b/tests/SelectiveDisclosure/IssuerBoundsTest.php new file mode 100644 index 00000000..ddaf8505 --- /dev/null +++ b/tests/SelectiveDisclosure/IssuerBoundsTest.php @@ -0,0 +1,314 @@ + 'ES256', + 'typ' => 'example+sd-jwt', + ]; + + #[DataProvider('dataShapes')] + #[Test] + public function claimsOfSixtyFourLevelsAreIssuedAndVerified(string $shape, bool $json): void + { + $sdJwt = self::issue(self::claims($shape, 64), $json); + + $verified = self::verifier(jsonSerializations: $json)->verify($sdJwt->toString(), self::issuerKey()->toPublic()); + + static::assertArrayHasKey('claim', $verified->getClaims()); + static::assertCount(count($sdJwt->getDisclosures()), $sdJwt->select(['claim'])->getDisclosures()); + } + + #[DataProvider('dataShapes')] + #[Test] + public function claimsOfSixtyFiveLevelsAreRefused(string $shape, bool $json): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(self::DEPTH_MESSAGE); + + self::issue(self::claims($shape, 65), $json); + } + + #[DataProvider('dataSerializations')] + #[Test] + public function aChainOfAThousandDisclosuresIsRefused(bool $json): void + { + $this->expectException(InvalidArgumentException::class); + + self::issue(self::claims('properties', 1000), $json); + } + + #[Test] + public function theRefusalChainsTheRejectionOfTheHolderAndTheVerifier(): void + { + $rejections = []; + foreach ([self::claims('arrays', 65), self::disclosableIntegers(2049)] as $claims) { + try { + self::issue($claims, false); + } catch (InvalidArgumentException $exception) { + $rejections[] = $exception->getPrevious(); + } + } + + static::assertCount(2, $rejections); + static::assertInstanceOf(InvalidTokenException::class, $rejections[0]); + static::assertSame(self::DEPTH_MESSAGE, $rejections[0]->getMessage()); + static::assertInstanceOf(InvalidSerializationException::class, $rejections[1]); + } + + /** + * The signatures given by name are collected by the variadic parameter under their name. + */ + #[Test] + public function signaturesGivenByNameAreChecked(): void + { + $sdJwt = self::issuer()->issueJson( + self::claims('properties', 3), + new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER), + second: new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER, [ + 'kid' => 'key', + ]) + ); + + $verified = self::verifier(jsonSerializations: true)->verify($sdJwt->toString(), self::issuerKey()->toPublic()); + + static::assertArrayHasKey('claim', $verified->getClaims()); + } + + /** + * Each Disclosure of an array element of an integer holds two JSON values: 2048 of them fill the budget. + */ + #[Test] + public function theDisclosuresOfACompactSdJwtFillingTheBudgetAreIssuedAndParsed(): void + { + $sdJwt = self::issue(self::disclosableIntegers(2048), false); + + static::assertCount(2048, SDJWT::fromString($sdJwt->toString())->getDisclosures()); + } + + #[DataProvider('dataSerializations')] + #[Test] + public function disclosuresBeyondTheBudgetAreRefused(bool $json): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(self::BUDGET_MESSAGE); + + self::issue(self::disclosableIntegers(2049), $json); + } + + /** + * In the JWS JSON serialization, the values of the JSON document count too: the Issuer issues an SD-JWT exactly + * when the Holder and the Verifier can parse it, whatever its unprotected headers. Each Disclosure adds a comma to + * the "disclosures" array: about 1360 of them fill the budget. + */ + #[DataProvider('dataUnprotectedHeaders')] + #[Test] + public function aJsonSdJwtIsIssuedExactlyWhenItCanBeParsed(array $header, bool $general): void + { + $outcomes = []; + for ($count = 1350; $count <= 1370; ++$count) { + $claims = self::disclosableIntegers($count); + $signatures = [new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER, $header)]; + if ($general) { + $signatures[] = new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER, $header); + } + try { + $sdJwt = self::issuer()->issueJson($claims, ...$signatures); + } catch (InvalidArgumentException) { + $outcomes[] = 'refused'; + continue; + } + try { + SDJWT::fromString($sdJwt->toString()); + $outcomes[] = 'issued'; + } catch (InvalidSerializationException) { + $outcomes[] = 'issued but not parsed'; + } + } + + static::assertNotContains('issued but not parsed', $outcomes); + static::assertContains('issued', $outcomes); + static::assertContains('refused', $outcomes); + } + + /** + * An object counts with the levels of its JSON, as the Verifier decodes it. + */ + #[Test] + public function theLevelsOfTheJsonOfAnObjectAreCounted(): void + { + self::issue([ + 'iss' => 'https://issuer.example.com', + 'claim' => self::jsonSerializable(self::arrays(0, 63)), + ], false); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(self::DEPTH_MESSAGE); + + self::issue([ + 'iss' => 'https://issuer.example.com', + 'claim' => new Disclosable(self::jsonSerializable(self::arrays(0, 64))), + ], false); + } + + /** + * @return iterable + */ + public static function dataShapes(): iterable + { + foreach (self::dataSerializations() as $serialization => [$json]) { + yield sprintf('nested arrays, %s', $serialization) => ['arrays', $json]; + yield sprintf('chained Disclosures of object properties, %s', $serialization) => ['properties', $json]; + yield sprintf('chained Disclosures of array elements, %s', $serialization) => ['elements', $json]; + } + } + + /** + * @return iterable + */ + public static function dataSerializations(): iterable + { + yield 'compact' => [false]; + yield 'JWS JSON serialization' => [true]; + } + + /** + * @return iterable, bool}> + */ + public static function dataUnprotectedHeaders(): iterable + { + yield 'flattened, no unprotected header' => [[], false]; + yield 'flattened, an unprotected header' => [[ + 'kid' => 'key', + 'x' => [1, 2, 3], + ], false]; + yield 'general, unprotected headers' => [[ + 'kid' => 'key', + 'x' => [1, 2, 3], + ], true]; + } + + /** + * @param array $claims + */ + private static function issue(array $claims, bool $json): SDJWT + { + return $json + ? self::issuer()->issueJson($claims, new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER)) + : self::issuer()->issue($claims, self::issuerKey(), self::PROTECTED_HEADER); + } + + /** + * Claims whose processed payload has the given number of levels, the payload itself included. + * + * @return array + */ + private static function claims(string $shape, int $levels): array + { + $claim = match ($shape) { + 'arrays' => self::arrays(0, $levels - 1), + 'properties' => self::properties($levels - 1), + 'elements' => self::elements($levels - 1), + }; + + return [ + 'iss' => 'https://issuer.example.com', + 'claim' => $claim, + ]; + } + + /** + * A selectively disclosable claim whose value is an object with a selectively disclosable claim, and so on: each + * Disclosable but the last one discloses an object, one level. + */ + private static function properties(int $objects): Disclosable + { + $value = new Disclosable(0); + for ($index = 0; $index < $objects; ++$index) { + $value = new Disclosable([ + 'claim' => $value, + ]); + } + + return $value; + } + + /** + * An array whose selectively disclosable element is an array with a selectively disclosable element, and so on. + * + * @return list + */ + private static function elements(int $arrays): array + { + $value = 0; + for ($index = 0; $index < $arrays; ++$index) { + $value = [new Disclosable($value)]; + } + + return $value; + } + + /** + * @return array + */ + private static function disclosableIntegers(int $count): array + { + return [ + 'iss' => 'https://issuer.example.com', + 'claim' => array_map(static fn (int $value): Disclosable => new Disclosable($value), array_fill(0, $count, 1)), + ]; + } + + private static function arrays(mixed $value, int $arrays): mixed + { + for ($index = 0; $index < $arrays; ++$index) { + $value = [$value]; + } + + return $value; + } + + private static function jsonSerializable(mixed $value): JsonSerializable + { + return new readonly class($value) implements JsonSerializable { + public function __construct( + private mixed $value + ) { + } + + public function jsonSerialize(): mixed + { + return $this->value; + } + }; + } +} From 3bf9ff242c4307ccd0f9b981f266ecd18e598a12 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 8 Nov 2026 22:52:51 +0100 Subject: [PATCH 02/32] fix(sd-jwt): create only the Disclosures that can be parsed Disclosure::forObjectProperty() and Disclosure::forArrayElement() wrote the JSON of any value, while Disclosure::fromString() decodes it with a BoundedJsonDecoder: at most 4096 values, and at most 511 levels of arrays and objects, the array of the Disclosure included. A value of 511 nested arrays, an object whose JSON has 511 levels, 300 arrays around an object of 300 levels or a list of 4095 integers gave a Disclosure that this library then rejected as "not valid JSON", and SDJWTIssuer issued SD-JWTs that the Holder and the Verifier could not parse. Both factories now decode the JSON of the Disclosure with a new BoundedJsonDecoder before returning it, and refuse the value with an InvalidArgumentException when the Disclosure cannot be parsed. The levels are thus counted from the array of the Disclosure, for the arrays and the objects of the value alike, and the bounds are those of the parser. Fixes #808 --- src/SelectiveDisclosure/Disclosure.php | 24 +++- tests/SelectiveDisclosure/DisclosureTest.php | 112 ++++++++++++++++++ tests/SelectiveDisclosure/SDJWTIssuerTest.php | 31 +++++ 3 files changed, 163 insertions(+), 4 deletions(-) diff --git a/src/SelectiveDisclosure/Disclosure.php b/src/SelectiveDisclosure/Disclosure.php index 865659cb..3f6b722b 100644 --- a/src/SelectiveDisclosure/Disclosure.php +++ b/src/SelectiveDisclosure/Disclosure.php @@ -74,7 +74,8 @@ private function __construct( /** * Creates the Disclosure of an object property. The salt is generated when it is not given. * - * @throws InvalidArgumentException if the claim name is reserved or the value cannot be serialized as JSON + * @throws InvalidArgumentException if the claim name is reserved, if the value cannot be serialized as JSON, or if + * the Disclosure could not be parsed */ public static function forObjectProperty(string $claimName, mixed $value, ?string $salt = null): self { @@ -93,7 +94,8 @@ public static function forObjectProperty(string $claimName, mixed $value, ?strin /** * Creates the Disclosure of an array element. The salt is generated when it is not given. * - * @throws InvalidArgumentException if the value cannot be serialized as JSON + * @throws InvalidArgumentException if the value cannot be serialized as JSON, or if the Disclosure could not be + * parsed */ public static function forArrayElement(mixed $value, ?string $salt = null): self { @@ -221,15 +223,29 @@ private static function generateSalt(): string } /** - * @throws InvalidArgumentException if the value cannot be serialized as JSON + * The JSON is decoded as Disclosure::fromString() decodes it, so that every Disclosure created can be parsed. + * + * @throws InvalidArgumentException if the value cannot be serialized as JSON, or if the Disclosure could not be + * parsed */ private static function serialize(mixed $value): string { try { - return self::toJson(self::toJsonValue($value)); + $json = self::toJson(self::toJsonValue($value)); } catch (JsonException $exception) { throw new InvalidArgumentException('The value cannot be serialized as JSON.', 0, $exception); } + try { + (new BoundedJsonDecoder())->decode($json); + } catch (InvalidArgumentException $exception) { + throw new InvalidArgumentException( + 'The value is nested too deeply or holds too many JSON values: its Disclosure could not be parsed.', + 0, + $exception + ); + } + + return $json; } /** diff --git a/tests/SelectiveDisclosure/DisclosureTest.php b/tests/SelectiveDisclosure/DisclosureTest.php index b90dd4b6..95dc2dfc 100644 --- a/tests/SelectiveDisclosure/DisclosureTest.php +++ b/tests/SelectiveDisclosure/DisclosureTest.php @@ -20,6 +20,8 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use stdClass; +use function range; +use function str_repeat; use function strlen; use const INF; use const JSON_THROW_ON_ERROR; @@ -31,6 +33,8 @@ final class DisclosureTest extends TestCase { private const MOBIUS = 'WyJfMjZiYzRMVC1hYzZxMktJNmNCVzVlcyIsICJmYW1pbHlfbmFtZSIsICJNw7ZiaXVzIl0'; + private const UNPARSABLE = 'The value is nested too deeply or holds too many JSON values: its Disclosure could not be parsed.'; + /** * RFC 9901 section 4.2.1 and 4.2.3: the Disclosure of an object property and its digest. */ @@ -199,6 +203,68 @@ public static function valuesThatCannotBeSerialized(): iterable ]]; } + /** + * The levels of a Disclosure are counted from its own array, for the arrays and the objects of the value alike, and + * its JSON values share one budget, as when Disclosure::fromString() parses it. + */ + #[Test] + #[DataProvider('valuesBeyondTheBoundsOfTheParser')] + public function aValueWhoseDisclosureCannotBeParsedIsRefused(bool $property, string $shape, int $size): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(self::UNPARSABLE); + $this->expectExceptionCode(0); + + self::create($property, self::value($shape, $size)); + } + + /** + * @return iterable + */ + public static function valuesBeyondTheBoundsOfTheParser(): iterable + { + yield 'an array element of 511 nested arrays' => [false, 'arrays', 511]; + yield 'an array element of 10000 nested arrays' => [false, 'arrays', 10000]; + yield 'an array element of an object of 511 levels' => [false, 'object', 511]; + yield 'an array element of 300 arrays around an object of 300 levels' => [false, 'arrays around an object', 300]; + yield 'an array element of 4095 integers' => [false, 'integers', 4095]; + yield 'an object property of 511 nested arrays' => [true, 'arrays', 511]; + yield 'an object property of an object of 511 levels' => [true, 'object', 511]; + yield 'an object property of 4094 integers' => [true, 'integers', 4094]; + } + + #[Test] + #[DataProvider('valuesWithinTheBoundsOfTheParser')] + public function aValueWithinTheBoundsOfTheParserIsDisclosed(bool $property, string $shape, int $size): void + { + $value = self::value($shape, $size); + + $disclosure = Disclosure::fromString(self::create($property, $value)->toString()); + + static::assertSame( + json_decode(json_encode($value, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR), + $disclosure->getValue() + ); + } + + /** + * The brackets, braces, commas, quotes and backslashes of a string are not JSON values. + * + * @return iterable + */ + public static function valuesWithinTheBoundsOfTheParser(): iterable + { + yield 'an array element of 510 nested arrays' => [false, 'arrays', 510]; + yield 'an array element of an object of 510 levels' => [false, 'object', 510]; + yield 'an array element of 255 arrays around an object of 255 levels' => [false, 'arrays around an object', 255]; + yield 'an array element of 4094 integers' => [false, 'integers', 4094]; + yield 'an array element of a string of brackets, braces, commas, quotes and backslashes' => [false, 'string', 10000]; + yield 'an object property of 510 nested arrays' => [true, 'arrays', 510]; + yield 'an object property of an object of 510 levels' => [true, 'object', 510]; + yield 'an object property of 4093 integers' => [true, 'integers', 4093]; + yield 'an object property of a string of brackets, braces, commas, quotes and backslashes' => [true, 'string', 10000]; + } + /** * JSON allows white space before the array; the Disclosure is accepted as it is. */ @@ -353,4 +419,50 @@ private static function encode(mixed $value): string { return Base64UrlSafe::encodeUnpadded(json_encode($value, JSON_THROW_ON_ERROR)); } + + private static function create(bool $property, mixed $value): Disclosure + { + return $property ? Disclosure::forObjectProperty('claim', $value, 'salt') : Disclosure::forArrayElement( + $value, + 'salt' + ); + } + + /** + * A value of the given shape: the size is a number of levels, of integers or of groups of characters. + */ + private static function value(string $shape, int $size): mixed + { + return match ($shape) { + 'arrays' => self::arrays(1, $size), + 'object' => self::object($size), + 'arrays around an object' => self::arrays(self::object($size), $size), + 'integers' => range(1, $size), + 'string' => str_repeat('[{,"\\', $size), + }; + } + + private static function arrays(mixed $value, int $arrays): mixed + { + for ($index = 0; $index < $arrays; ++$index) { + $value = [$value]; + } + + return $value; + } + + /** + * An object whose JSON has the given number of levels. + */ + private static function object(int $levels): stdClass + { + $value = 1; + for ($index = 0; $index < $levels; ++$index) { + $object = new stdClass(); + $object->claim = $value; + $value = $object; + } + + return $value; + } } diff --git a/tests/SelectiveDisclosure/SDJWTIssuerTest.php b/tests/SelectiveDisclosure/SDJWTIssuerTest.php index ca87fcd1..ab6416aa 100644 --- a/tests/SelectiveDisclosure/SDJWTIssuerTest.php +++ b/tests/SelectiveDisclosure/SDJWTIssuerTest.php @@ -577,6 +577,37 @@ public function aDisclosableValueIsOnlyAllowedAsAClaimOrAnArrayElement(): void ]); } + /** + * The Holder and the Verifier could not parse the Disclosure of 600 nested arrays. + */ + #[Test] + #[DataProvider('disclosablePositions')] + public function aDisclosableValueWhoseDisclosureCannotBeParsedIsRefused(bool $arrayElement): void + { + $value = 1; + for ($index = 0; $index < 600; ++$index) { + $value = [$value]; + } + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The value is nested too deeply or holds too many JSON values: its Disclosure could not be parsed.'); + + self::issuer()->issue([ + 'claim' => $arrayElement ? [new Disclosable($value)] : new Disclosable($value), + ], self::issuerKey(), [ + 'alg' => 'ES256', + ]); + } + + /** + * @return iterable + */ + public static function disclosablePositions(): iterable + { + yield 'a claim' => [false]; + yield 'an array element' => [true]; + } + /** * @return array */ From 0063d2680713ff0a441cdee0e501cec270d50581 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 08:03:41 +0100 Subject: [PATCH 03/32] test(sd-jwt): keep the anonymous JsonSerializable valid on PHP 8.2 Anonymous readonly classes need PHP 8.3: the property is readonly instead, as in SDJWTIssuerTest. --- tests/SelectiveDisclosure/IssuerBoundsTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/SelectiveDisclosure/IssuerBoundsTest.php b/tests/SelectiveDisclosure/IssuerBoundsTest.php index ddaf8505..3df7aac7 100644 --- a/tests/SelectiveDisclosure/IssuerBoundsTest.php +++ b/tests/SelectiveDisclosure/IssuerBoundsTest.php @@ -299,9 +299,9 @@ private static function arrays(mixed $value, int $arrays): mixed private static function jsonSerializable(mixed $value): JsonSerializable { - return new readonly class($value) implements JsonSerializable { + return new class($value) implements JsonSerializable { public function __construct( - private mixed $value + private readonly mixed $value ) { } From 6872121bcec0616859c66e35b548a4b7a576f385 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 08:04:00 +0100 Subject: [PATCH 04/32] Remove the Scorecards workflow The OpenSSF Scorecard action only accepts the default branch, so every push to the other maintained branches ended in a failed run. The workflow is already disabled on GitHub; 5.0.x will lose the file with the next merge-up. --- .github/workflows/scorecards.yml | 44 -------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 .github/workflows/scorecards.yml diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml deleted file mode 100644 index 9f9ff7fd..00000000 --- a/.github/workflows/scorecards.yml +++ /dev/null @@ -1,44 +0,0 @@ -name: Scorecards supply-chain security - -on: - schedule: - - cron: '34 4 * * 6' - push: - branches: [ "*.*.x" ] - -permissions: read-all - -jobs: - analysis: - name: Scorecards analysis - runs-on: ubuntu-latest - permissions: - security-events: write - id-token: write - contents: read - actions: read - - steps: - - name: "Checkout code" - uses: actions/checkout@v4 - with: - persist-credentials: false - - - name: "Run analysis" - uses: ossf/scorecard-action@v2.4.2 - with: - results_file: results.sarif - results_format: sarif - publish_results: true - - - name: "Upload artifact" - uses: actions/upload-artifact@v4.6.2 - with: - name: SARIF file - path: results.sarif - retention-days: 5 - - - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@v3 - with: - sarif_file: results.sarif From 5af8fc4e4726c4bdf4fd13ad8145e730ffbe44f8 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 08:16:47 +0100 Subject: [PATCH 05/32] fix(console): inject the key factory into the generator commands through a setter #712 gave GeneratorCommand a constructor taking the key factory as its second argument, and kept the factory in a protected readonly property. 4.2 has neither, and both reach the commands an application extends: - a subclass that declares its own non-readonly $jwkFactory property, private or not, typed or not, no longer loads: PHP refuses to redeclare a readonly property; - the second argument of the constructor takes the place of the one that recent versions of the Symfony command accept for an invokable command ($code): passing one raises a TypeError. The factory is now held in a private property, set by setJwkFactory() and read through getJwkFactory(), which falls back to a default factory so that the commands stay usable outside of a container. The constructor is the one inherited from the Symfony command again. The bundle calls the setter on every generator command it registers, the ML-DSA ones included. Follow-up to #712 --- src/Bundle/Resources/config/commands.php | 11 +- src/Library/Console/EcKeyGeneratorCommand.php | 3 +- .../Console/EcKeysetGeneratorCommand.php | 2 +- src/Library/Console/GeneratorCommand.php | 23 ++-- src/Library/Console/KeyFileLoaderCommand.php | 3 +- .../Console/MldsaKeyGeneratorCommand.php | 3 +- .../Console/MldsaKeysetGeneratorCommand.php | 2 +- .../Console/NoneKeyGeneratorCommand.php | 3 +- .../Console/OctKeyGeneratorCommand.php | 3 +- .../Console/OctKeysetGeneratorCommand.php | 2 +- .../Console/OkpKeyGeneratorCommand.php | 3 +- .../Console/OkpKeysetGeneratorCommand.php | 2 +- .../Console/P12CertificateLoaderCommand.php | 3 +- .../Console/RsaKeyGeneratorCommand.php | 3 +- .../Console/RsaKeysetGeneratorCommand.php | 2 +- .../Console/SecretKeyGeneratorCommand.php | 3 +- .../Console/X509CertificateLoaderCommand.php | 3 +- .../KeyManagement/JWKFactoryServiceTest.php | 9 +- .../Console/GeneratorCommandBcTest.php | 106 ++++++++++++++++++ 19 files changed, 162 insertions(+), 27 deletions(-) create mode 100644 tests/Component/Console/GeneratorCommandBcTest.php diff --git a/src/Bundle/Resources/config/commands.php b/src/Bundle/Resources/config/commands.php index 52f69ec3..525d7e4a 100644 --- a/src/Bundle/Resources/config/commands.php +++ b/src/Bundle/Resources/config/commands.php @@ -5,6 +5,7 @@ use Jose\Component\Console\AddKeyIntoKeysetCommand; use Jose\Component\Console\EcKeyGeneratorCommand; use Jose\Component\Console\EcKeysetGeneratorCommand; +use Jose\Component\Console\GeneratorCommand; use Jose\Component\Console\GetThumbprintCommand; use Jose\Component\Console\KeyAnalyzerCommand; use Jose\Component\Console\KeyFileLoaderCommand; @@ -28,11 +29,17 @@ use Jose\Component\Console\RsaKeysetGeneratorCommand; use Jose\Component\Console\SecretKeyGeneratorCommand; use Jose\Component\Console\X509CertificateLoaderCommand; +use Jose\Component\KeyManagement\JWKFactoryInterface; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; +use function Symfony\Component\DependencyInjection\Loader\Configurator\service; return function (ContainerConfigurator $container): void { - $container = $container->services() - ->defaults() + $services = $container->services(); + + $services->instanceof(GeneratorCommand::class) + ->call('setJwkFactory', [service(JWKFactoryInterface::class)]); + + $container = $services->defaults() ->private() ->autoconfigure() ->autowire(); diff --git a/src/Library/Console/EcKeyGeneratorCommand.php b/src/Library/Console/EcKeyGeneratorCommand.php index 93002f10..36312525 100644 --- a/src/Library/Console/EcKeyGeneratorCommand.php +++ b/src/Library/Console/EcKeyGeneratorCommand.php @@ -31,7 +31,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $args = $this->getOptions($input); - $jwk = $this->jwkFactory->ec($curve, $args); + $jwk = $this->getJwkFactory() + ->ec($curve, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/EcKeysetGeneratorCommand.php b/src/Library/Console/EcKeysetGeneratorCommand.php index fffdc233..cf51b71d 100644 --- a/src/Library/Console/EcKeysetGeneratorCommand.php +++ b/src/Library/Console/EcKeysetGeneratorCommand.php @@ -39,7 +39,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $keyset = new JWKSet([]); for ($i = 0; $i < $quantity; ++$i) { $args = $this->getOptions($input); - $keyset = $keyset->with($this->jwkFactory->ec($curve, $args)); + $keyset = $keyset->with($this->getJwkFactory()->ec($curve, $args)); } $this->prepareJsonOutput($input, $output, $keyset); diff --git a/src/Library/Console/GeneratorCommand.php b/src/Library/Console/GeneratorCommand.php index cc724ccb..b4b5aca3 100644 --- a/src/Library/Console/GeneratorCommand.php +++ b/src/Library/Console/GeneratorCommand.php @@ -15,17 +15,16 @@ abstract class GeneratorCommand extends ObjectOutputCommand { - protected readonly JWKFactoryInterface $jwkFactory; - /** - * The key factory is the second argument, and not the first as in the other commands of the library, so that the - * name inherited from the Symfony command stays where it was: "new EcKeyGeneratorCommand('my:command')" keeps - * working. + * The factory is injected through a setter and held in a private property, so that nothing this abstract command + * publishes changes: the constructor inherited from the Symfony command keeps the signature it always had, and a + * subclass that already declares a member of that name is left alone. */ - public function __construct(?string $name = null, ?JWKFactoryInterface $jwkFactory = null) + private ?JWKFactoryInterface $jwkFactory = null; + + public function setJwkFactory(JWKFactoryInterface $jwkFactory): void { - parent::__construct($name); - $this->jwkFactory = $jwkFactory ?? new JWKFactory(); + $this->jwkFactory = $jwkFactory; } #[Override] @@ -72,6 +71,14 @@ protected function getOptions(InputInterface $input): array return $args; } + /** + * Falls back to a default factory, so that the commands stay usable outside of a container. + */ + protected function getJwkFactory(): JWKFactoryInterface + { + return $this->jwkFactory ??= new JWKFactory(); + } + private function generateKeyID(): string { return Base64UrlSafe::encode(random_bytes(32)); diff --git a/src/Library/Console/KeyFileLoaderCommand.php b/src/Library/Console/KeyFileLoaderCommand.php index d868062c..0ae50144 100644 --- a/src/Library/Console/KeyFileLoaderCommand.php +++ b/src/Library/Console/KeyFileLoaderCommand.php @@ -37,7 +37,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $args = $this->getOptions($input); - $jwk = $this->jwkFactory->fromKeyFile($file, $password, $args); + $jwk = $this->getJwkFactory() + ->fromKeyFile($file, $password, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/MldsaKeyGeneratorCommand.php b/src/Library/Console/MldsaKeyGeneratorCommand.php index 4962d8db..5bf84694 100644 --- a/src/Library/Console/MldsaKeyGeneratorCommand.php +++ b/src/Library/Console/MldsaKeyGeneratorCommand.php @@ -31,7 +31,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $args = $this->getOptions($input); - $jwk = $this->jwkFactory->mldsa($algorithm, $args); + $jwk = $this->getJwkFactory() + ->mldsa($algorithm, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/MldsaKeysetGeneratorCommand.php b/src/Library/Console/MldsaKeysetGeneratorCommand.php index 611d9bd6..8d3800dd 100644 --- a/src/Library/Console/MldsaKeysetGeneratorCommand.php +++ b/src/Library/Console/MldsaKeysetGeneratorCommand.php @@ -44,7 +44,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $keyset = new JWKSet([]); for ($i = 0; $i < $quantity; ++$i) { $args = $this->getOptions($input); - $keyset = $keyset->with($this->jwkFactory->mldsa($algorithm, $args)); + $keyset = $keyset->with($this->getJwkFactory()->mldsa($algorithm, $args)); } $this->prepareJsonOutput($input, $output, $keyset); diff --git a/src/Library/Console/NoneKeyGeneratorCommand.php b/src/Library/Console/NoneKeyGeneratorCommand.php index 8cbae543..43748903 100644 --- a/src/Library/Console/NoneKeyGeneratorCommand.php +++ b/src/Library/Console/NoneKeyGeneratorCommand.php @@ -20,7 +20,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int { $args = $this->getOptions($input); - $jwk = $this->jwkFactory->none($args); + $jwk = $this->getJwkFactory() + ->none($args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/OctKeyGeneratorCommand.php b/src/Library/Console/OctKeyGeneratorCommand.php index 720c2b41..24a99444 100644 --- a/src/Library/Console/OctKeyGeneratorCommand.php +++ b/src/Library/Console/OctKeyGeneratorCommand.php @@ -30,7 +30,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $args = $this->getOptions($input); - $jwk = $this->jwkFactory->oct($size, $args); + $jwk = $this->getJwkFactory() + ->oct($size, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/OctKeysetGeneratorCommand.php b/src/Library/Console/OctKeysetGeneratorCommand.php index 7e9651b4..46975637 100644 --- a/src/Library/Console/OctKeysetGeneratorCommand.php +++ b/src/Library/Console/OctKeysetGeneratorCommand.php @@ -38,7 +38,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $keyset = new JWKSet([]); for ($i = 0; $i < $quantity; ++$i) { $args = $this->getOptions($input); - $keyset = $keyset->with($this->jwkFactory->oct($size, $args)); + $keyset = $keyset->with($this->getJwkFactory()->oct($size, $args)); } $this->prepareJsonOutput($input, $output, $keyset); diff --git a/src/Library/Console/OkpKeyGeneratorCommand.php b/src/Library/Console/OkpKeyGeneratorCommand.php index d4d4f0f1..7ef1c5f9 100644 --- a/src/Library/Console/OkpKeyGeneratorCommand.php +++ b/src/Library/Console/OkpKeyGeneratorCommand.php @@ -31,7 +31,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $args = $this->getOptions($input); - $jwk = $this->jwkFactory->okp($curve, $args); + $jwk = $this->getJwkFactory() + ->okp($curve, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/OkpKeysetGeneratorCommand.php b/src/Library/Console/OkpKeysetGeneratorCommand.php index 2512df62..12089728 100644 --- a/src/Library/Console/OkpKeysetGeneratorCommand.php +++ b/src/Library/Console/OkpKeysetGeneratorCommand.php @@ -42,7 +42,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $keyset = new JWKSet([]); for ($i = 0; $i < $quantity; ++$i) { $args = $this->getOptions($input); - $keyset = $keyset->with($this->jwkFactory->okp($curve, $args)); + $keyset = $keyset->with($this->getJwkFactory()->okp($curve, $args)); } $this->prepareJsonOutput($input, $output, $keyset); diff --git a/src/Library/Console/P12CertificateLoaderCommand.php b/src/Library/Console/P12CertificateLoaderCommand.php index 356467cc..8271743e 100644 --- a/src/Library/Console/P12CertificateLoaderCommand.php +++ b/src/Library/Console/P12CertificateLoaderCommand.php @@ -36,7 +36,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int throw new InvalidArgumentException('Invalid secret'); } $args = $this->getOptions($input); - $jwk = $this->jwkFactory->fromPKCS12CertificateFile($file, $password, $args); + $jwk = $this->getJwkFactory() + ->fromPKCS12CertificateFile($file, $password, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/RsaKeyGeneratorCommand.php b/src/Library/Console/RsaKeyGeneratorCommand.php index c0d16dc1..05600c4e 100644 --- a/src/Library/Console/RsaKeyGeneratorCommand.php +++ b/src/Library/Console/RsaKeyGeneratorCommand.php @@ -30,7 +30,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int throw new InvalidArgumentException('Invalid size'); } - $jwk = $this->jwkFactory->rsa($size, $args); + $jwk = $this->getJwkFactory() + ->rsa($size, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/RsaKeysetGeneratorCommand.php b/src/Library/Console/RsaKeysetGeneratorCommand.php index 771c6f85..e23c609d 100644 --- a/src/Library/Console/RsaKeysetGeneratorCommand.php +++ b/src/Library/Console/RsaKeysetGeneratorCommand.php @@ -38,7 +38,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $keyset = new JWKSet([]); for ($i = 0; $i < $quantity; ++$i) { $args = $this->getOptions($input); - $keyset = $keyset->with($this->jwkFactory->rsa($size, $args)); + $keyset = $keyset->with($this->getJwkFactory()->rsa($size, $args)); } $this->prepareJsonOutput($input, $output, $keyset); diff --git a/src/Library/Console/SecretKeyGeneratorCommand.php b/src/Library/Console/SecretKeyGeneratorCommand.php index f64acdf3..c1ada5e0 100644 --- a/src/Library/Console/SecretKeyGeneratorCommand.php +++ b/src/Library/Console/SecretKeyGeneratorCommand.php @@ -52,7 +52,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $args = $this->getOptions($input); - $jwk = $this->jwkFactory->fromSecret($secret, $args); + $jwk = $this->getJwkFactory() + ->fromSecret($secret, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/src/Library/Console/X509CertificateLoaderCommand.php b/src/Library/Console/X509CertificateLoaderCommand.php index 4b8dbf90..5676b622 100644 --- a/src/Library/Console/X509CertificateLoaderCommand.php +++ b/src/Library/Console/X509CertificateLoaderCommand.php @@ -37,7 +37,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int } } - $jwk = $this->jwkFactory->fromCertificateFile($file, $args); + $jwk = $this->getJwkFactory() + ->fromCertificateFile($file, $args); $this->prepareJsonOutput($input, $output, $jwk); return self::SUCCESS; diff --git a/tests/Bundle/JoseFramework/Functional/KeyManagement/JWKFactoryServiceTest.php b/tests/Bundle/JoseFramework/Functional/KeyManagement/JWKFactoryServiceTest.php index bd52ef16..092fbb83 100644 --- a/tests/Bundle/JoseFramework/Functional/KeyManagement/JWKFactoryServiceTest.php +++ b/tests/Bundle/JoseFramework/Functional/KeyManagement/JWKFactoryServiceTest.php @@ -4,11 +4,13 @@ namespace Jose\Tests\Bundle\JoseFramework\Functional\KeyManagement; +use Jose\Component\Console\GeneratorCommand; use Jose\Component\Console\RsaKeyGeneratorCommand; use Jose\Component\KeyManagement\JWKFactory; use Jose\Component\KeyManagement\JWKFactoryInterface; use Jose\Tests\Bundle\JoseFramework\WebTestCase; use PHPUnit\Framework\Attributes\Test; +use ReflectionProperty; /** * The key factory is a service of the bundle and is aliased with its interface, so that it can be autowired and @@ -50,7 +52,10 @@ public static function theGeneratorCommandsReceiveTheKeyFactory(): void $container = $client->getContainer(); - static::assertTrue($container->has(RsaKeyGeneratorCommand::class)); - static::assertInstanceOf(RsaKeyGeneratorCommand::class, $container->get(RsaKeyGeneratorCommand::class)); + $command = $container->get(RsaKeyGeneratorCommand::class); + $property = new ReflectionProperty(GeneratorCommand::class, 'jwkFactory'); + + static::assertInstanceOf(RsaKeyGeneratorCommand::class, $command); + static::assertSame($container->get(JWKFactoryInterface::class), $property->getValue($command)); } } diff --git a/tests/Component/Console/GeneratorCommandBcTest.php b/tests/Component/Console/GeneratorCommandBcTest.php new file mode 100644 index 00000000..8682bc35 --- /dev/null +++ b/tests/Component/Console/GeneratorCommandBcTest.php @@ -0,0 +1,106 @@ +getConstructor(); + + static::assertNotNull($constructor); + static::assertSame(Command::class, $constructor->getDeclaringClass()->getName()); + } + + #[Test] + public function theAbstractCommandDeclaresNoPropertyASubclassCouldClashWith(): void + { + $reflection = new ReflectionClass(GeneratorCommand::class); + $properties = array_filter( + $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED), + static fn (ReflectionProperty $property): bool => $property->getDeclaringClass() + ->getName() === GeneratorCommand::class + ); + + static::assertSame([], $properties); + } + + #[Test] + public function aCommandKeepsTheNameGivenToItsConstructor(): void + { + $command = new EcKeyGeneratorCommand('my:command'); + + static::assertSame('my:command', $command->getName()); + } + + #[Test] + public function aSubclassWithItsOwnConstructorStillBuildsAndRuns(): void + { + $command = new class('my:command') extends GeneratorCommand { + public function __construct(?string $name = null) + { + parent::__construct($name); + } + + #[Override] + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->prepareJsonOutput($input, $output, $this->getJwkFactory()->oct(256)); + + return self::SUCCESS; + } + }; + + $output = new BufferedOutput(); + $command->run(new ArrayInput([]), $output); + + static::assertSame('my:command', $command->getName()); + static::assertSame('oct', JWK::createFromJson($output->fetch())->get('kty')); + } + + #[Test] + public function anInjectedFactoryReplacesTheDefaultOne(): void + { + $factory = static::createStub(JWKFactoryInterface::class); + $factory->method('ec') + ->willReturn(new JWK([ + 'kty' => 'oct', + 'k' => 'aW5qZWN0ZWQ', + ])); + $command = new EcKeyGeneratorCommand(); + $command->setJwkFactory($factory); + + $output = new BufferedOutput(); + $command->run(new ArrayInput([ + 'curve' => 'P-256', + ]), $output); + + static::assertSame('aW5qZWN0ZWQ', JWK::createFromJson($output->fetch())->get('k')); + } +} From 81b91bb512d1704054146b8cfe94a80cd3903082 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 08:36:08 +0100 Subject: [PATCH 06/32] fix(sd-jwt): tell the decoding bounds apart from invalid JSON Disclosure::fromString() and SDJWT::fromString() reported every Disclosure that the BoundedJsonDecoder rejected as "not valid JSON", and SDJWT::fromString() and SDJWT::create() reported every JWS JSON serialization it rejected as "must be a JSON object", even when the JSON was valid but held more than 4096 values or was nested too deeply. As the Disclosures of an SD-JWT share the budget, the Disclosure blamed was the one on which the budget ran out, however small. BoundedJsonDecoder::hasExceededMaxValues() tells whether the budget was exceeded. A Disclosure or a JWS JSON serialization rejected for its values or for its depth now says so, and an SD-JWT whose Disclosures go beyond the budget is rejected as a whole. The exception classes and codes are unchanged, and invalid JSON keeps its message. --- src/Library/Core/Util/BoundedJsonDecoder.php | 9 ++ src/SelectiveDisclosure/Disclosure.php | 28 ++++++- src/SelectiveDisclosure/SDJWT.php | 53 +++++++++--- .../Component/Core/BoundedJsonDecoderTest.php | 42 ++++++++++ tests/SelectiveDisclosure/DisclosureTest.php | 30 +++++++ .../JsonValueBoundTest.php | 82 ++++++++++++++++++- 6 files changed, 230 insertions(+), 14 deletions(-) diff --git a/src/Library/Core/Util/BoundedJsonDecoder.php b/src/Library/Core/Util/BoundedJsonDecoder.php index e4e5b092..1758e273 100644 --- a/src/Library/Core/Util/BoundedJsonDecoder.php +++ b/src/Library/Core/Util/BoundedJsonDecoder.php @@ -33,6 +33,15 @@ public function decode(#[SensitiveParameter] string $json): mixed return JsonConverter::decode($json); } + /** + * Whether the documents given to this decoder hold more than MAX_VALUES values. The document that went beyond the + * bound was rejected before it was decoded, and so are the documents given after it. + */ + public function hasExceededMaxValues(): bool + { + return $this->remainingValues < 0; + } + /** * Counts the brackets, braces and commas found outside the string literals. */ diff --git a/src/SelectiveDisclosure/Disclosure.php b/src/SelectiveDisclosure/Disclosure.php index 3f6b722b..de0409ea 100644 --- a/src/SelectiveDisclosure/Disclosure.php +++ b/src/SelectiveDisclosure/Disclosure.php @@ -31,6 +31,7 @@ use function random_bytes; use function sprintf; use function str_starts_with; +use const JSON_ERROR_DEPTH; use const JSON_PRESERVE_ZERO_FRACTION; use const JSON_THROW_ON_ERROR; use const JSON_UNESCAPED_SLASHES; @@ -113,7 +114,8 @@ public static function forArrayElement(mixed $value, ?string $salt = null): self * or from an array, and so whether it has the expected number of elements, is checked when the SD-JWT is * processed. * - * @throws InvalidSerializationException if the value is not a Disclosure + * @throws InvalidSerializationException if the value is not a Disclosure, if its JSON is nested too deeply, or if + * it holds more than BoundedJsonDecoder::MAX_VALUES JSON values */ public static function fromString(string $disclosure): self { @@ -125,7 +127,8 @@ public static function fromString(string $disclosure): self * * @internal * - * @throws InvalidSerializationException if the value is not a Disclosure + * @throws InvalidSerializationException if the value is not a Disclosure, if its JSON is nested too deeply, or if + * its JSON values go beyond the budget of the decoder */ public static function parse(string $disclosure, BoundedJsonDecoder $decoder): self { @@ -140,7 +143,7 @@ public static function parse(string $disclosure, BoundedJsonDecoder $decoder): s try { $array = $decoder->decode($json); } catch (Throwable $throwable) { - throw new InvalidSerializationException('The Disclosure is not valid JSON.', 0, $throwable); + throw self::decodingFailure($decoder, $throwable); } if (! is_array($array) || ! str_starts_with(ltrim($json, " \t\n\r"), '[') || ! in_array(count($array), [2, 3], true)) { @@ -222,6 +225,25 @@ private static function generateSalt(): string return Base64UrlSafe::encodeUnpadded(random_bytes(self::SALT_SIZE)); } + /** + * Why the JSON of a Disclosure was not decoded. The decoder rejects it, before decoding it, when its values and + * those decoded before it by the same decoder go beyond the budget; otherwise, json_decode() rejected it, and + * JsonConverter::decode() gave its exception the code of the JSON error. + */ + private static function decodingFailure( + BoundedJsonDecoder $decoder, + Throwable $throwable + ): InvalidSerializationException { + return new InvalidSerializationException(match (true) { + $decoder->hasExceededMaxValues() => sprintf( + 'With this Disclosure, there are more than %d JSON values to decode.', + BoundedJsonDecoder::MAX_VALUES + ), + $throwable->getCode() === JSON_ERROR_DEPTH => 'The Disclosure is nested too deeply.', + default => 'The Disclosure is not valid JSON.', + }, 0, $throwable); + } + /** * The JSON is decoded as Disclosure::fromString() decodes it, so that every Disclosure created can be parsed. * diff --git a/src/SelectiveDisclosure/SDJWT.php b/src/SelectiveDisclosure/SDJWT.php index 2eb74a4e..a98007b9 100644 --- a/src/SelectiveDisclosure/SDJWT.php +++ b/src/SelectiveDisclosure/SDJWT.php @@ -33,6 +33,7 @@ use function str_starts_with; use function strpos; use function substr; +use const JSON_ERROR_DEPTH; /** * An SD-JWT, or an SD-JWT+KB, in the compact format of RFC 9901 section 4 or in the JWS JSON serialization of @@ -120,8 +121,10 @@ private function __construct( * without the "disclosures" and "kb_jwt" header parameters * @param list $disclosures * - * @throws InvalidSerializationException if the Issuer-signed JWT is not a JWS in compact or JSON serialization, or - * if the Key Binding JWT is not a JWS in compact serialization + * @throws InvalidSerializationException if the Issuer-signed JWT is not a JWS in compact or JSON serialization, if + * its JWS JSON serialization is nested too deeply or holds more than + * BoundedJsonDecoder::MAX_VALUES JSON values, or if the Key Binding JWT is + * not a JWS in compact serialization */ public static function create(string $issuerSignedJwt, array $disclosures = [], ?string $keyBindingJwt = null): self { @@ -149,7 +152,8 @@ public static function create(string $issuerSignedJwt, array $disclosures = [], * serialization. In the compact format, the parts are checked one after the other while the string is read, so * that a malformed input is rejected as soon as the malformed part is met. * - * @throws InvalidSerializationException if the string is not an SD-JWT + * @throws InvalidSerializationException if the string is not an SD-JWT, if its JSON is nested too deeply, or if it + * holds more than BoundedJsonDecoder::MAX_VALUES JSON values */ public static function fromString(string $sdJwt): self { @@ -171,7 +175,7 @@ public static function fromString(string $sdJwt): self if ($separator === $offset) { throw new InvalidSerializationException('A Disclosure of the SD-JWT is empty.'); } - $disclosures[] = Disclosure::parse(substr($sdJwt, $offset, $separator - $offset), $decoder); + $disclosures[] = self::parseDisclosure(substr($sdJwt, $offset, $separator - $offset), $decoder); $offset = $separator + 1; } $keyBindingJwt = substr($sdJwt, $offset); @@ -372,7 +376,7 @@ private static function fromJson(string $json, BoundedJsonDecoder $decoder): sel 'The "disclosures" header parameter must be an array of strings.' ); } - $disclosures[] = Disclosure::parse($disclosure, $decoder); + $disclosures[] = self::parseDisclosure($disclosure, $decoder); } if (! array_key_exists('kb_jwt', $parameters)) { return $sdJwt->with($disclosures, null); @@ -386,11 +390,37 @@ private static function fromJson(string $json, BoundedJsonDecoder $decoder): sel return $sdJwt->with($disclosures, $keyBindingJwt); } + /** + * Parses a Disclosure of the SD-JWT. The Disclosures share the budget of the decoder: when they go beyond it, the + * SD-JWT is rejected as a whole, whichever Disclosure goes beyond it. + * + * @throws InvalidSerializationException if the value is not a Disclosure, if its JSON is nested too deeply, or if + * the SD-JWT holds more than BoundedJsonDecoder::MAX_VALUES JSON values + */ + private static function parseDisclosure(string $disclosure, BoundedJsonDecoder $decoder): Disclosure + { + try { + return Disclosure::parse($disclosure, $decoder); + } catch (InvalidSerializationException $exception) { + if (! $decoder->hasExceededMaxValues()) { + throw $exception; + } + throw new InvalidSerializationException(sprintf( + 'The SD-JWT holds more JSON values than the %d that are decoded.', + BoundedJsonDecoder::MAX_VALUES + ), 0, $exception); + } + } + /** * Reads an Issuer-signed JWT in the flattened or the general JWS JSON serialization. The parameters of the SD-JWT * are removed from the unprotected header of the first signature and returned apart; the headers of the other * signatures cannot have them. * + * The JWS JSON serialization is the first document given to the decoder: when the decoder rejects it for the + * values it holds, it holds more than BoundedJsonDecoder::MAX_VALUES. When json_decode() rejects it, + * JsonConverter::decode() gives its exception the code of the JSON error. + * * @return array{self, array} the SD-JWT, without Disclosure, and the parameters of the SD-JWT */ private static function readJson(string $json, BoundedJsonDecoder $decoder): array @@ -398,11 +428,14 @@ private static function readJson(string $json, BoundedJsonDecoder $decoder): arr try { $token = $decoder->decode($json); } catch (Throwable $throwable) { - throw new InvalidSerializationException( - 'The JWS JSON serialization must be a JSON object.', - 0, - $throwable - ); + throw new InvalidSerializationException(match (true) { + $decoder->hasExceededMaxValues() => sprintf( + 'The JWS JSON serialization holds more JSON values than the %d that are decoded.', + BoundedJsonDecoder::MAX_VALUES + ), + $throwable->getCode() === JSON_ERROR_DEPTH => 'The JWS JSON serialization is nested too deeply.', + default => 'The JWS JSON serialization must be a JSON object.', + }, 0, $throwable); } $token = self::jsonObject($token, 'The JWS JSON serialization must be a JSON object.'); $general = array_key_exists('signatures', $token); diff --git a/tests/Component/Core/BoundedJsonDecoderTest.php b/tests/Component/Core/BoundedJsonDecoderTest.php index ef90c302..6ea0700e 100644 --- a/tests/Component/Core/BoundedJsonDecoderTest.php +++ b/tests/Component/Core/BoundedJsonDecoderTest.php @@ -6,6 +6,7 @@ use InvalidArgumentException; use Jose\Component\Core\Util\BoundedJsonDecoder; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use function intdiv; @@ -38,6 +39,47 @@ public function aDocumentBeyondTheBoundIsRejectedBeforeItIsDecoded(): void } } + #[Test] + public function theBoundIsExceededOnceADocumentIsRejectedForTheValuesItHolds(): void + { + $json = new BoundedJsonDecoder(); + $json->decode('[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES - 1) . '0]'); + + static::assertFalse($json->hasExceededMaxValues()); + + try { + $json->decode('[]'); + static::fail('The document should have been rejected.'); + } catch (InvalidArgumentException) { + } + + static::assertTrue($json->hasExceededMaxValues()); + } + + #[Test] + #[DataProvider('documentsJsonDecodeRejects')] + public function aDocumentJsonDecodeRejectsDoesNotExceedTheBound(string $document): void + { + $json = new BoundedJsonDecoder(); + + try { + $json->decode($document); + static::fail('The document should have been rejected.'); + } catch (InvalidArgumentException) { + } + + static::assertFalse($json->hasExceededMaxValues()); + } + + /** + * @return iterable + */ + public static function documentsJsonDecodeRejects(): iterable + { + yield 'invalid JSON' => ['[0,']; + yield 'nested too deeply' => [str_repeat('[', 600) . str_repeat(']', 600)]; + } + #[Test] public function nestedContainersAreCounted(): void { diff --git a/tests/SelectiveDisclosure/DisclosureTest.php b/tests/SelectiveDisclosure/DisclosureTest.php index 95dc2dfc..194bd89e 100644 --- a/tests/SelectiveDisclosure/DisclosureTest.php +++ b/tests/SelectiveDisclosure/DisclosureTest.php @@ -20,6 +20,7 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use stdClass; +use function implode; use function range; use function str_repeat; use function strlen; @@ -415,6 +416,35 @@ public static function malformedDisclosures(): iterable ]; } + /** + * The JSON of these Disclosures is valid: the decoder rejects them for the values they hold or for their depth. + */ + #[Test] + #[DataProvider('disclosuresBeyondTheBoundsOfTheDecoder')] + public function aDisclosureBeyondTheBoundsOfTheDecoderIsRejected(string $json, string $message): void + { + $this->expectException(InvalidSerializationException::class); + $this->expectExceptionMessage($message); + $this->expectExceptionCode(0); + + Disclosure::fromString(Base64UrlSafe::encodeUnpadded($json)); + } + + /** + * @return iterable + */ + public static function disclosuresBeyondTheBoundsOfTheDecoder(): iterable + { + yield 'more than 4096 JSON values' => [ + '["salt", [' . implode(', ', range(1, 4095)) . ']]', + 'With this Disclosure, there are more than 4096 JSON values to decode.', + ]; + yield 'nested too deeply' => [ + '["salt", ' . str_repeat('[', 511) . '1' . str_repeat(']', 511) . ']', + 'The Disclosure is nested too deeply.', + ]; + } + private static function encode(mixed $value): string { return Base64UrlSafe::encodeUnpadded(json_encode($value, JSON_THROW_ON_ERROR)); diff --git a/tests/SelectiveDisclosure/JsonValueBoundTest.php b/tests/SelectiveDisclosure/JsonValueBoundTest.php index cc663983..e76930bc 100644 --- a/tests/SelectiveDisclosure/JsonValueBoundTest.php +++ b/tests/SelectiveDisclosure/JsonValueBoundTest.php @@ -25,7 +25,8 @@ final class JsonValueBoundTest extends SelectiveDisclosureTestCase { /** * Each Disclosure of an object property holds three values, plus a comma in the "disclosures" array of the JWS JSON - * serialization: the Disclosures of one SD-JWT share a budget of 4096. + * serialization: the Disclosures of one SD-JWT share a budget of 4096. The SD-JWT is rejected as a whole, whichever + * Disclosure goes beyond the budget. */ #[DataProvider('dataSerializations')] #[Test] @@ -34,10 +35,51 @@ public function theDisclosuresOfAnSdJwtShareTheBound(bool $json, int $accepted, static::assertCount($accepted, SDJWT::fromString(self::sdJwt($accepted, $json))->getDisclosures()); $this->expectException(InvalidSerializationException::class); + $this->expectExceptionMessage('The SD-JWT holds more JSON values than the 4096 that are decoded.'); + $this->expectExceptionCode(0); SDJWT::fromString(self::sdJwt($rejected, $json)); } + /** + * A single Disclosure can also go beyond the budget. A Disclosure nested too deeply is named. + */ + #[DataProvider('disclosuresBeyondTheBoundsOfTheDecoder')] + #[Test] + public function anSdJwtWithADisclosureBeyondTheBoundsOfTheDecoderIsRejected(string $json, string $message): void + { + $token = self::token(self::sign([ + 'iss' => 'https://issuer.example.com', + ]), [Base64UrlSafe::encodeUnpadded($json)]); + + $this->expectException(InvalidSerializationException::class); + $this->expectExceptionMessage($message); + $this->expectExceptionCode(0); + + SDJWT::fromString($token); + } + + /** + * The JWS JSON serialization is decoded before the Disclosures, by the same decoder. + */ + #[DataProvider('jwsJsonSerializationsBeyondTheBoundsOfTheDecoder')] + #[Test] + public function aJwsJsonSerializationBeyondTheBoundsOfTheDecoderIsRejected( + bool $issuerSignedJwt, + string $json, + string $message + ): void { + $this->expectException(InvalidSerializationException::class); + $this->expectExceptionMessage($message); + $this->expectExceptionCode(0); + + if ($issuerSignedJwt) { + SDJWT::create($json); + } else { + SDJWT::fromString($json); + } + } + /** * Once decoded, the nested arrays take about a hundred times the size of the Disclosure. The threshold is * deliberately generous. @@ -67,6 +109,44 @@ public static function dataSerializations(): iterable yield 'JWS JSON serialization' => [true, 1000, 1100]; } + /** + * @return iterable + */ + public static function disclosuresBeyondTheBoundsOfTheDecoder(): iterable + { + yield 'more than 4096 JSON values' => [ + '["salt", [' . str_repeat('0, ', 4094) . '0]]', + 'The SD-JWT holds more JSON values than the 4096 that are decoded.', + ]; + yield 'nested too deeply' => [ + '["salt", ' . str_repeat('[', 511) . '0' . str_repeat(']', 511) . ']', + 'The Disclosure is nested too deeply.', + ]; + } + + /** + * @return iterable + */ + public static function jwsJsonSerializationsBeyondTheBoundsOfTheDecoder(): iterable + { + $values = 'The JWS JSON serialization holds more JSON values than the 4096 that are decoded.'; + $depth = 'The JWS JSON serialization is nested too deeply.'; + $manyValues = self::jwsJsonSerialization('[' . str_repeat('0,', 4096) . '0]'); + $deep = self::jwsJsonSerialization(str_repeat('[', 600) . str_repeat(']', 600)); + yield 'an SD-JWT holding more than 4096 JSON values' => [false, $manyValues, $values]; + yield 'an SD-JWT nested too deeply' => [false, $deep, $depth]; + yield 'an Issuer-signed JWT holding more than 4096 JSON values' => [true, $manyValues, $values]; + yield 'an Issuer-signed JWT nested too deeply' => [true, $deep, $depth]; + } + + /** + * A JWS JSON serialization whose unprotected header holds the given JSON value. + */ + private static function jwsJsonSerialization(string $value): string + { + return '{"payload":"e30","protected":"eyJhbGciOiJFUzI1NiJ9","header":{"x":' . $value . '},"signature":"AA"}'; + } + private static function sdJwt(int $disclosureCount, bool $json): string { $disclosures = array_map( From 5d55912b5f6b281f915d662d2d5feadea8923ac4 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 08:53:00 +0100 Subject: [PATCH 07/32] fix(sd-jwt): name the bound a Disclosure factory hits Disclosure::forObjectProperty() and Disclosure::forArrayElement() gave one message for both bounds of the decoder when the Disclosure of a value could not be parsed: "The value is nested too deeply or holds too many JSON values". BoundedJsonDecoder::hasExceededMaxValues() now tells whether the budget of 4096 values was exceeded; otherwise, since json_encode() wrote the JSON, json_decode() rejected it for its depth. Each bound has its own message. The exception class and code are unchanged. --- src/SelectiveDisclosure/Disclosure.php | 16 ++++---- tests/SelectiveDisclosure/DisclosureTest.php | 40 ++++++++++++------- tests/SelectiveDisclosure/SDJWTIssuerTest.php | 2 +- 3 files changed, 36 insertions(+), 22 deletions(-) diff --git a/src/SelectiveDisclosure/Disclosure.php b/src/SelectiveDisclosure/Disclosure.php index de0409ea..77475877 100644 --- a/src/SelectiveDisclosure/Disclosure.php +++ b/src/SelectiveDisclosure/Disclosure.php @@ -245,7 +245,9 @@ private static function decodingFailure( } /** - * The JSON is decoded as Disclosure::fromString() decodes it, so that every Disclosure created can be parsed. + * The JSON is decoded as Disclosure::fromString() decodes it, so that every Disclosure created can be parsed. The + * decoder rejects it, before decoding it, when it holds more than BoundedJsonDecoder::MAX_VALUES values; otherwise, + * json_decode() can only reject it for its depth, since json_encode() wrote it. * * @throws InvalidArgumentException if the value cannot be serialized as JSON, or if the Disclosure could not be * parsed @@ -257,14 +259,14 @@ private static function serialize(mixed $value): string } catch (JsonException $exception) { throw new InvalidArgumentException('The value cannot be serialized as JSON.', 0, $exception); } + $decoder = new BoundedJsonDecoder(); try { - (new BoundedJsonDecoder())->decode($json); + $decoder->decode($json); } catch (InvalidArgumentException $exception) { - throw new InvalidArgumentException( - 'The value is nested too deeply or holds too many JSON values: its Disclosure could not be parsed.', - 0, - $exception - ); + throw new InvalidArgumentException($decoder->hasExceededMaxValues() ? sprintf( + 'The value holds too many JSON values: its Disclosure would hold more than the %d that are decoded.', + BoundedJsonDecoder::MAX_VALUES + ) : 'The value is nested too deeply: its Disclosure could not be parsed.', 0, $exception); } return $json; diff --git a/tests/SelectiveDisclosure/DisclosureTest.php b/tests/SelectiveDisclosure/DisclosureTest.php index 194bd89e..2d128c3e 100644 --- a/tests/SelectiveDisclosure/DisclosureTest.php +++ b/tests/SelectiveDisclosure/DisclosureTest.php @@ -34,7 +34,9 @@ final class DisclosureTest extends TestCase { private const MOBIUS = 'WyJfMjZiYzRMVC1hYzZxMktJNmNCVzVlcyIsICJmYW1pbHlfbmFtZSIsICJNw7ZiaXVzIl0'; - private const UNPARSABLE = 'The value is nested too deeply or holds too many JSON values: its Disclosure could not be parsed.'; + private const TOO_DEEP = 'The value is nested too deeply: its Disclosure could not be parsed.'; + + private const TOO_MANY_VALUES = 'The value holds too many JSON values: its Disclosure would hold more than the 4096 that are decoded.'; /** * RFC 9901 section 4.2.1 and 4.2.3: the Disclosure of an object property and its digest. @@ -206,32 +208,42 @@ public static function valuesThatCannotBeSerialized(): iterable /** * The levels of a Disclosure are counted from its own array, for the arrays and the objects of the value alike, and - * its JSON values share one budget, as when Disclosure::fromString() parses it. + * its JSON values share one budget, as when Disclosure::fromString() parses it. The values are counted before the + * JSON is decoded: 10000 nested arrays are refused for their values. */ #[Test] #[DataProvider('valuesBeyondTheBoundsOfTheParser')] - public function aValueWhoseDisclosureCannotBeParsedIsRefused(bool $property, string $shape, int $size): void - { + public function aValueWhoseDisclosureCannotBeParsedIsRefused( + bool $property, + string $shape, + int $size, + string $message + ): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage(self::UNPARSABLE); + $this->expectExceptionMessage($message); $this->expectExceptionCode(0); self::create($property, self::value($shape, $size)); } /** - * @return iterable + * @return iterable */ public static function valuesBeyondTheBoundsOfTheParser(): iterable { - yield 'an array element of 511 nested arrays' => [false, 'arrays', 511]; - yield 'an array element of 10000 nested arrays' => [false, 'arrays', 10000]; - yield 'an array element of an object of 511 levels' => [false, 'object', 511]; - yield 'an array element of 300 arrays around an object of 300 levels' => [false, 'arrays around an object', 300]; - yield 'an array element of 4095 integers' => [false, 'integers', 4095]; - yield 'an object property of 511 nested arrays' => [true, 'arrays', 511]; - yield 'an object property of an object of 511 levels' => [true, 'object', 511]; - yield 'an object property of 4094 integers' => [true, 'integers', 4094]; + yield 'an array element of 511 nested arrays' => [false, 'arrays', 511, self::TOO_DEEP]; + yield 'an array element of 10000 nested arrays' => [false, 'arrays', 10000, self::TOO_MANY_VALUES]; + yield 'an array element of an object of 511 levels' => [false, 'object', 511, self::TOO_DEEP]; + yield 'an array element of 300 arrays around an object of 300 levels' => [ + false, + 'arrays around an object', + 300, + self::TOO_DEEP, + ]; + yield 'an array element of 4095 integers' => [false, 'integers', 4095, self::TOO_MANY_VALUES]; + yield 'an object property of 511 nested arrays' => [true, 'arrays', 511, self::TOO_DEEP]; + yield 'an object property of an object of 511 levels' => [true, 'object', 511, self::TOO_DEEP]; + yield 'an object property of 4094 integers' => [true, 'integers', 4094, self::TOO_MANY_VALUES]; } #[Test] diff --git a/tests/SelectiveDisclosure/SDJWTIssuerTest.php b/tests/SelectiveDisclosure/SDJWTIssuerTest.php index ab6416aa..ac6507f3 100644 --- a/tests/SelectiveDisclosure/SDJWTIssuerTest.php +++ b/tests/SelectiveDisclosure/SDJWTIssuerTest.php @@ -590,7 +590,7 @@ public function aDisclosableValueWhoseDisclosureCannotBeParsedIsRefused(bool $ar } $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The value is nested too deeply or holds too many JSON values: its Disclosure could not be parsed.'); + $this->expectExceptionMessage('The value is nested too deeply: its Disclosure could not be parsed.'); self::issuer()->issue([ 'claim' => $arrayElement ? [new Disclosable($value)] : new Disclosable($value), From 16d327dd1c27ed73ca5bfdca0708f1f1c4230d12 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 09:00:55 +0100 Subject: [PATCH 08/32] fix(sd-jwt): refuse the unparsable unprotected headers as the other claims SDJWTIssuer::issueJson() checks its SD-JWT on a placeholder that the Holder and the Verifier would parse. SDJWT::create() rejected the placeholder with an InvalidSerializationException when an unprotected header was nested too deeply, held more than 4096 JSON values or was a list, and that exception escaped, while the Issuer refuses everything else with an InvalidArgumentException. Near the bound, an unprotected header of 4090 values was refused with a message that blamed the Disclosures, even without any. The JSON of the placeholder is now decoded first, as the Holder and the Verifier decode it, and every failure to parse it is refused with an InvalidArgumentException. In the JWS JSON serialization, the budget message names the unprotected headers with the Disclosures. --- src/SelectiveDisclosure/SDJWTIssuer.php | 44 +++++- .../SelectiveDisclosure/IssuerBoundsTest.php | 132 +++++++++++++++++- 2 files changed, 168 insertions(+), 8 deletions(-) diff --git a/src/SelectiveDisclosure/SDJWTIssuer.php b/src/SelectiveDisclosure/SDJWTIssuer.php index 7f879998..0dac093c 100644 --- a/src/SelectiveDisclosure/SDJWTIssuer.php +++ b/src/SelectiveDisclosure/SDJWTIssuer.php @@ -67,7 +67,8 @@ * unprotected headers of the one to issue, and its payload is processed with them, as SDJWT::select() does. The bounds * are thus those of SDJWT::fromString(), the JSON values decoded with the Disclosures, and of the Disclosure * processing, the depth of the processed payload, in which an object counts with the levels of its JSON and a - * Disclosable adds no level. + * Disclosable adds no level. In the JWS JSON serialization, the unprotected headers are parsed with the Disclosures: + * their JSON values count, and their depth is bounded. * * @see https://www.rfc-editor.org/rfc/rfc9901.html#section-4 * @see https://www.rfc-editor.org/rfc/rfc9901.html#section-8 @@ -95,6 +96,16 @@ */ private const PLACEHOLDER_PART = 'A'; + /** + * The refusal of the claims whose SD-JWT holds more JSON values than the Holder and the Verifier decode. In the + * JWS JSON serialization, the values of the unprotected headers count with those of the Disclosures. + */ + private const COMPACT_BUDGET_MESSAGE = 'The Disclosures of the SD-JWT hold more JSON values than the %d the Holder and the Verifier decode.'; + + private const JSON_BUDGET_MESSAGE = 'The Disclosures and the unprotected headers of the SD-JWT hold more JSON values than the %d the Holder and the Verifier decode.'; + + private const HEADER_DEPTH_MESSAGE = 'The unprotected headers of the SD-JWT are nested more deeply than the Holder and the Verifier decode.'; + private int $maximumDecoyDigests; /** @@ -217,10 +228,10 @@ private static function checkBounds(SDJWT $placeholder): void try { $sdJwt = SDJWT::fromString($placeholder->toString()); } catch (InvalidSerializationException $exception) { - throw new InvalidArgumentException(sprintf( - 'The Disclosures of the SD-JWT hold more JSON values than the %d the Holder and the Verifier decode.', - BoundedJsonDecoder::MAX_VALUES - ), 0, $exception); + $message = $placeholder->getSerialization() === CompactSerializer::NAME + ? self::COMPACT_BUDGET_MESSAGE + : self::JSON_BUDGET_MESSAGE; + throw new InvalidArgumentException(sprintf($message, BoundedJsonDecoder::MAX_VALUES), 0, $exception); } try { $sdJwt->select(); @@ -241,8 +252,14 @@ private static function placeholderCompactJws(string $payload): string * An SD-JWT in the JWS JSON serialization with the given payload, signatures and Disclosures, whose protected * headers and signatures are placeholders: its JSON values are those of the SD-JWT to issue. * + * Before the Disclosures are added, the unprotected headers are its only JSON values besides its structure. Its + * JSON is decoded as the Holder and the Verifier decode it: since json_encode() wrote it, it can only be rejected + * for the values it holds or for its depth. It is then parsed, as they parse it. + * * @param array $signatures * @param list $disclosures + * + * @throws InvalidArgumentException if the Holder and the Verifier could not parse the unprotected headers */ private static function placeholderJsonSdJwt(string $payload, array $signatures, array $disclosures): SDJWT { @@ -264,8 +281,21 @@ private static function placeholderJsonSdJwt(string $payload, array $signatures, $token += count($entries) === 1 ? $entries[0] : [ 'signatures' => $entries, ]; - - return SDJWT::create(JsonConverter::encode($token), $disclosures); + $json = JsonConverter::encode($token); + $decoder = new BoundedJsonDecoder(); + try { + $decoder->decode($json); + } catch (InvalidArgumentException $exception) { + $message = $decoder->hasExceededMaxValues() + ? sprintf(self::JSON_BUDGET_MESSAGE, BoundedJsonDecoder::MAX_VALUES) + : self::HEADER_DEPTH_MESSAGE; + throw new InvalidArgumentException($message, 0, $exception); + } + try { + return SDJWT::create($json, $disclosures); + } catch (InvalidSerializationException $exception) { + throw new InvalidArgumentException($exception->getMessage(), 0, $exception); + } } /** diff --git a/tests/SelectiveDisclosure/IssuerBoundsTest.php b/tests/SelectiveDisclosure/IssuerBoundsTest.php index 3df7aac7..dbbdb1ff 100644 --- a/tests/SelectiveDisclosure/IssuerBoundsTest.php +++ b/tests/SelectiveDisclosure/IssuerBoundsTest.php @@ -13,9 +13,13 @@ use JsonSerializable; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; +use Throwable; +use function array_diff; use function array_fill; use function array_map; +use function array_values; use function count; +use function range; use function sprintf; /** @@ -31,6 +35,10 @@ final class IssuerBoundsTest extends SelectiveDisclosureTestCase private const BUDGET_MESSAGE = 'The Disclosures of the SD-JWT hold more JSON values than the 4096 the Holder and the Verifier decode.'; + private const JSON_BUDGET_MESSAGE = 'The Disclosures and the unprotected headers of the SD-JWT hold more JSON values than the 4096 the Holder and the Verifier decode.'; + + private const HEADER_DEPTH_MESSAGE = 'The unprotected headers of the SD-JWT are nested more deeply than the Holder and the Verifier decode.'; + private const PROTECTED_HEADER = [ 'alg' => 'ES256', 'typ' => 'example+sd-jwt', @@ -120,11 +128,80 @@ public function theDisclosuresOfACompactSdJwtFillingTheBudgetAreIssuedAndParsed( public function disclosuresBeyondTheBudgetAreRefused(bool $json): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage(self::BUDGET_MESSAGE); + $this->expectExceptionMessage($json ? self::JSON_BUDGET_MESSAGE : self::BUDGET_MESSAGE); self::issue(self::disclosableIntegers(2049), $json); } + /** + * In the JWS JSON serialization, the unprotected headers are parsed with the Disclosures: the claims are refused + * when the Holder and the Verifier could not parse them, as the other claims they could not parse. + * + * @param array $header + */ + #[DataProvider('dataUnprotectedHeadersTheHolderAndTheVerifierReject')] + #[Test] + public function anUnprotectedHeaderTheHolderAndTheVerifierRejectIsRefused( + array $header, + bool $general, + string $message + ): void { + try { + self::issuer()->issueJson([ + 'iss' => 'https://issuer.example.com', + ], ...self::signatures($header, $general)); + } catch (Throwable $exception) { + static::assertSame(InvalidArgumentException::class, $exception::class); + static::assertSame($message, $exception->getMessage()); + static::assertSame(0, $exception->getCode()); + + return; + } + static::fail('The claims should have been refused.'); + } + + /** + * Around the depth and the number of values that the Holder and the Verifier decode, the Issuer issues an SD-JWT + * exactly when they can parse it, and refuses the others with an InvalidArgumentException. + */ + #[DataProvider('dataJsonSerializations')] + #[Test] + public function anSdJwtWithUnprotectedHeadersIsIssuedExactlyWhenItCanBeParsed(bool $general): void + { + $headers = []; + for ($levels = 505; $levels <= 512; ++$levels) { + $headers[] = [ + 'x' => self::arrays(0, $levels), + ]; + } + for ($count = 4080; $count <= 4100; ++$count) { + $headers[] = [ + 'x' => range(1, $count), + ]; + } + $outcomes = []; + foreach ($headers as $header) { + try { + $sdJwt = self::issuer()->issueJson([ + 'iss' => 'https://issuer.example.com', + ], ...self::signatures($header, $general)); + } catch (Throwable $exception) { + $outcomes[] = $exception::class === InvalidArgumentException::class ? 'refused' : $exception::class; + continue; + } + try { + SDJWT::fromString($sdJwt->toString()); + $outcomes[] = 'issued'; + } catch (InvalidSerializationException) { + $outcomes[] = 'issued but not parsed'; + } + } + + static::assertSame([], array_values(array_diff($outcomes, ['issued', 'refused']))); + static::assertContains('issued', $outcomes); + static::assertContains('refused', $outcomes); + } + /** * In the JWS JSON serialization, the values of the JSON document count too: the Issuer issues an SD-JWT exactly * when the Holder and the Verifier can parse it, whatever its unprotected headers. Each Disclosure adds a comma to @@ -201,6 +278,42 @@ public static function dataSerializations(): iterable yield 'JWS JSON serialization' => [true]; } + /** + * @return iterable + */ + public static function dataJsonSerializations(): iterable + { + yield 'flattened' => [false]; + yield 'general' => [true]; + } + + /** + * The first signature of the general serialization has no unprotected header: the header of the second one is + * parsed as well. + * + * @return iterable, bool, string}> + */ + public static function dataUnprotectedHeadersTheHolderAndTheVerifierReject(): iterable + { + yield 'flattened, a list' => [['a', 'b'], false, 'The "header" member must be a JSON object.']; + yield 'general, a list' => [['a', 'b'], true, 'The "header" member must be a JSON object.']; + yield 'flattened, nested too deeply' => [[ + 'x' => self::arrays(0, 510), + ], false, self::HEADER_DEPTH_MESSAGE]; + yield 'general, nested too deeply' => [[ + 'x' => self::arrays(0, 508), + ], true, self::HEADER_DEPTH_MESSAGE]; + yield 'flattened, too many values' => [[ + 'x' => range(1, 5000), + ], false, self::JSON_BUDGET_MESSAGE]; + yield 'general, too many values' => [[ + 'x' => range(1, 5000), + ], true, self::JSON_BUDGET_MESSAGE]; + yield 'flattened, too many values with the "disclosures" parameter' => [[ + 'x' => range(1, 4090), + ], false, self::JSON_BUDGET_MESSAGE]; + } + /** * @return iterable, bool}> */ @@ -217,6 +330,23 @@ public static function dataUnprotectedHeaders(): iterable ], true]; } + /** + * @param array $header + * + * @return list + */ + private static function signatures(array $header, bool $general): array + { + if (! $general) { + return [new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER, $header)]; + } + + return [ + new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER), + new IssuerSignature(self::issuerKey(), self::PROTECTED_HEADER, $header), + ]; + } + /** * @param array $claims */ From f4f96fbab6744d39b7e2eb2298a60721b7f2900a Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 09:10:56 +0100 Subject: [PATCH 09/32] fix(serializers): name the bound a token goes beyond when it is decoded The JWS and JWE serializers rejected every token whose JSON the BoundedJsonDecoder refused with "Unsupported input": invalid JSON, more than 4096 values, or a document nested too deeply. The decoder now names the bound, with "The JSON documents of the token hold more JSON values than the 4096 that are decoded." or "A JSON document of the token is nested too deeply.", and BoundedJsonDecoder::hasExceededMaxDepth() tells the second case apart. The JSON serializers let the exception of the decoder through, as before. The compact serializers now keep its message for these two bounds. Invalid JSON keeps "Unsupported input", and the exception classes and codes are unchanged. --- src/Library/Core/Util/BoundedJsonDecoder.php | 38 ++++++- .../Serializer/CompactSerializer.php | 14 ++- .../Serializer/CompactSerializer.php | 14 ++- .../Component/Core/BoundedJsonDecoderTest.php | 58 +++++++++- .../Encryption/JsonValueBoundTest.php | 96 ++++++++++++++++- .../Signature/JsonValueBoundTest.php | 102 +++++++++++++++++- 6 files changed, 306 insertions(+), 16 deletions(-) diff --git a/src/Library/Core/Util/BoundedJsonDecoder.php b/src/Library/Core/Util/BoundedJsonDecoder.php index 1758e273..dc6d9e16 100644 --- a/src/Library/Core/Util/BoundedJsonDecoder.php +++ b/src/Library/Core/Util/BoundedJsonDecoder.php @@ -7,14 +7,19 @@ use Jose\Component\Core\Exception\InvalidArgumentException; use SensitiveParameter; use function preg_replace; +use function sprintf; use function str_replace; use function substr_count; +use const JSON_ERROR_DEPTH; /** * Decodes the JSON documents of one token, which together may hold at most MAX_VALUES values. json_decode() only * limits the depth: a document of brackets decodes to a hundred times its size, and colliding member names make it * quadratic. * + * A document rejected for the values it holds or for its depth is rejected with a message that names the bound; the + * other errors of json_decode() keep the exception of JsonConverter::decode(). + * * @internal */ final class BoundedJsonDecoder @@ -23,14 +28,43 @@ final class BoundedJsonDecoder private int $remainingValues = self::MAX_VALUES; + private bool $exceededMaxDepth = false; + + /** + * @throws InvalidArgumentException if the document is not valid JSON, if it is nested too deeply, or if the + * documents given to this decoder hold more than MAX_VALUES values. The code of + * the exception is that of the JSON error, 0 for the values. + */ public function decode(#[SensitiveParameter] string $json): mixed { $this->remainingValues -= self::countValues($json); if ($this->remainingValues < 0) { - throw new InvalidArgumentException('Unsupported input.'); + throw new InvalidArgumentException(sprintf( + 'The JSON documents of the token hold more JSON values than the %d that are decoded.', + self::MAX_VALUES + )); + } + try { + return JsonConverter::decode($json); + } catch (InvalidArgumentException $exception) { + if ($exception->getCode() !== JSON_ERROR_DEPTH) { + throw $exception; + } + $this->exceededMaxDepth = true; + throw new InvalidArgumentException( + 'A JSON document of the token is nested too deeply.', + $exception->getCode(), + $exception->getPrevious() + ); } + } - return JsonConverter::decode($json); + /** + * Whether a document given to this decoder was rejected for its depth. + */ + public function hasExceededMaxDepth(): bool + { + return $this->exceededMaxDepth; } /** diff --git a/src/Library/Encryption/Serializer/CompactSerializer.php b/src/Library/Encryption/Serializer/CompactSerializer.php index 3fda5380..9aa4d0cd 100644 --- a/src/Library/Encryption/Serializer/CompactSerializer.php +++ b/src/Library/Encryption/Serializer/CompactSerializer.php @@ -57,6 +57,9 @@ public function serialize(JWE $jwe, ?int $recipientIndex = null): string * detect and reject any longer input. Without that bound, a delimiter-heavy string would be expanded into one * array entry per delimiter before the segment count is checked, which costs about twenty-five times the size * of the input in memory. + * + * A protected header that holds too many JSON values or is nested too deeply is rejected with the message of the + * JSON decoder, which names the bound; any other failure is an unsupported input. */ #[Override] public function unserialize(string $input): JWE @@ -66,9 +69,10 @@ public function unserialize(string $input): JWE throw new InvalidSerializationException('Unsupported input'); } + $decoder = new BoundedJsonDecoder(); try { $encodedSharedProtectedHeader = $parts[0]; - $sharedProtectedHeader = (new BoundedJsonDecoder())->decode( + $sharedProtectedHeader = $decoder->decode( Base64UrlSafe::decodeNoPadding($encodedSharedProtectedHeader) ); if (! is_array($sharedProtectedHeader)) { @@ -90,7 +94,13 @@ public function unserialize(string $input): JWE [new Recipient([], $encryptedKey)] ); } catch (Throwable $throwable) { - throw new InvalidSerializationException('Unsupported input', $throwable->getCode(), $throwable); + throw new InvalidSerializationException( + $decoder->hasExceededMaxValues() || $decoder->hasExceededMaxDepth() + ? $throwable->getMessage() + : 'Unsupported input', + $throwable->getCode(), + $throwable + ); } } diff --git a/src/Library/Signature/Serializer/CompactSerializer.php b/src/Library/Signature/Serializer/CompactSerializer.php index 9c98e16a..c8299027 100644 --- a/src/Library/Signature/Serializer/CompactSerializer.php +++ b/src/Library/Signature/Serializer/CompactSerializer.php @@ -62,6 +62,9 @@ public function serialize(JWS $jws, ?int $signatureIndex = null): string * detect and reject any longer input. Without that bound, a delimiter-heavy string would be expanded into one * array entry per delimiter before the segment count is checked, which costs about twenty-five times the size * of the input in memory. + * + * A protected header that holds too many JSON values or is nested too deeply is rejected with the message of the + * JSON decoder, which names the bound; any other failure is an unsupported input. */ #[Override] public function unserialize(#[SensitiveParameter] string $input): JWS @@ -71,9 +74,10 @@ public function unserialize(#[SensitiveParameter] string $input): JWS throw new InvalidSerializationException('Unsupported input'); } + $decoder = new BoundedJsonDecoder(); try { $encodedProtectedHeader = $parts[0]; - $protectedHeader = (new BoundedJsonDecoder())->decode(Base64UrlSafe::decodeNoPadding($parts[0])); + $protectedHeader = $decoder->decode(Base64UrlSafe::decodeNoPadding($parts[0])); if (! is_array($protectedHeader)) { throw new InvalidSerializationException('Bad protected header.'); } @@ -93,7 +97,13 @@ public function unserialize(#[SensitiveParameter] string $input): JWS return $jws->addSignature($signature, $protectedHeader, $encodedProtectedHeader); } catch (Throwable $throwable) { - throw new InvalidSerializationException('Unsupported input', $throwable->getCode(), $throwable); + throw new InvalidSerializationException( + $decoder->hasExceededMaxValues() || $decoder->hasExceededMaxDepth() + ? $throwable->getMessage() + : 'Unsupported input', + $throwable->getCode(), + $throwable + ); } } } diff --git a/tests/Component/Core/BoundedJsonDecoderTest.php b/tests/Component/Core/BoundedJsonDecoderTest.php index 6ea0700e..87d3eee3 100644 --- a/tests/Component/Core/BoundedJsonDecoderTest.php +++ b/tests/Component/Core/BoundedJsonDecoderTest.php @@ -6,17 +6,24 @@ use InvalidArgumentException; use Jose\Component\Core\Util\BoundedJsonDecoder; +use JsonException; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use function intdiv; use function str_repeat; +use const JSON_ERROR_DEPTH; +use const JSON_ERROR_SYNTAX; /** * @internal */ final class BoundedJsonDecoderTest extends TestCase { + private const TOO_MANY_VALUES = 'The JSON documents of the token hold more JSON values than the 4096 that are decoded.'; + + private const TOO_DEEP = 'A JSON document of the token is nested too deeply.'; + #[Test] public function aDocumentAtTheBoundIsDecoded(): void { @@ -34,7 +41,7 @@ public function aDocumentBeyondTheBoundIsRejectedBeforeItIsDecoded(): void (new BoundedJsonDecoder())->decode($document); static::fail('The document should have been rejected.'); } catch (InvalidArgumentException $e) { - static::assertSame('Unsupported input.', $e->getMessage()); + static::assertSame(self::TOO_MANY_VALUES, $e->getMessage()); static::assertNull($e->getPrevious()); } } @@ -54,6 +61,49 @@ public function theBoundIsExceededOnceADocumentIsRejectedForTheValuesItHolds(): } static::assertTrue($json->hasExceededMaxValues()); + static::assertFalse($json->hasExceededMaxDepth()); + } + + /** + * The decoder names the bound and keeps the code and the error of json_decode(). + */ + #[Test] + public function aDocumentNestedTooDeeplyIsRejectedForItsDepth(): void + { + $json = new BoundedJsonDecoder(); + $json->decode('[[0]]'); + + static::assertFalse($json->hasExceededMaxDepth()); + + try { + $json->decode(str_repeat('[', 600) . str_repeat(']', 600)); + static::fail('The document should have been rejected.'); + } catch (InvalidArgumentException $e) { + static::assertSame(self::TOO_DEEP, $e->getMessage()); + static::assertSame(JSON_ERROR_DEPTH, $e->getCode()); + static::assertInstanceOf(JsonException::class, $e->getPrevious()); + static::assertSame('Maximum stack depth exceeded', $e->getPrevious()->getMessage()); + } + + static::assertTrue($json->hasExceededMaxDepth()); + static::assertFalse($json->hasExceededMaxValues()); + } + + #[Test] + public function anInvalidDocumentKeepsTheErrorOfTheJsonConverter(): void + { + $json = new BoundedJsonDecoder(); + + try { + $json->decode('[0,'); + static::fail('The document should have been rejected.'); + } catch (InvalidArgumentException $e) { + static::assertSame('Unsupported input.', $e->getMessage()); + static::assertSame(JSON_ERROR_SYNTAX, $e->getCode()); + } + + static::assertFalse($json->hasExceededMaxDepth()); + static::assertFalse($json->hasExceededMaxValues()); } #[Test] @@ -84,7 +134,7 @@ public static function documentsJsonDecodeRejects(): iterable public function nestedContainersAreCounted(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input.'); + $this->expectExceptionMessage(self::TOO_MANY_VALUES); $group = str_repeat('[', 100) . str_repeat(']', 100); (new BoundedJsonDecoder())->decode('{"x":[' . str_repeat($group . ',', 41) . '0]}'); @@ -108,7 +158,7 @@ public function theContentOfStringsIsNotCounted(): void public function aStringEndingWithAnEscapedBackslashDoesNotHideTheValuesThatFollowIt(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input.'); + $this->expectExceptionMessage(self::TOO_MANY_VALUES); (new BoundedJsonDecoder())->decode( '["\\\\",[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES) . '0],"\\\\"]' @@ -126,7 +176,7 @@ public function theDocumentsOfOneTokenShareTheBound(): void static::assertCount($half, (new BoundedJsonDecoder())->decode($document)); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input.'); + $this->expectExceptionMessage(self::TOO_MANY_VALUES); $json->decode('[]'); } diff --git a/tests/Component/Encryption/JsonValueBoundTest.php b/tests/Component/Encryption/JsonValueBoundTest.php index 6b73b421..7f56b5d9 100644 --- a/tests/Component/Encryption/JsonValueBoundTest.php +++ b/tests/Component/Encryption/JsonValueBoundTest.php @@ -22,12 +22,17 @@ use function range; use function sprintf; use function str_repeat; +use const JSON_ERROR_DEPTH; /** * @internal */ final class JsonValueBoundTest extends EncryptionTestCase { + private const TOO_MANY_VALUES = 'The JSON documents of the token hold more JSON values than the 4096 that are decoded.'; + + private const TOO_DEEP = 'A JSON document of the token is nested too deeply.'; + /** * The member names are multiples of 131072: they all fall into the first bucket of a PHP array. */ @@ -48,11 +53,41 @@ public function anEncryptedTokenWhoseProtectedHeaderHoldsTooManyMembersIsRejecte $token = $serializer->serialize($jwe, 0); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input'); + $this->expectExceptionMessage(self::TOO_MANY_VALUES); $serializer->unserialize($token); } + /** + * The protected header and the JSON document are decoded with a depth of 512, as by the JSON converter: the token + * is rejected with the code of the JSON error. + */ + #[DataProvider('dataTokensNestedTooDeeply')] + #[Test] + public function aTokenNestedTooDeeplyIsRejected(JWESerializer $serializer, string $token): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(self::TOO_DEEP); + $this->expectExceptionCode(JSON_ERROR_DEPTH); + + $serializer->unserialize($token); + } + + #[DataProvider('dataInvalidJsonDocuments')] + #[Test] + public function aTokenWhoseJsonIsInvalidIsAnUnsupportedInput( + JWESerializer $serializer, + string $token, + string $message + ): void { + try { + $serializer->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidArgumentException $e) { + static::assertSame($message, $e->getMessage()); + } + } + #[DataProvider('dataJsonSerializers')] #[Test] public function anEncryptedTokenWhoseUnprotectedHeaderHoldsTooManyMembersIsRejected( @@ -72,7 +107,7 @@ public function anEncryptedTokenWhoseUnprotectedHeaderHoldsTooManyMembersIsRejec $token = $serializer->serialize($jwe, 0); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input.'); + $this->expectExceptionMessage(self::TOO_MANY_VALUES); $serializer->unserialize($token); } @@ -94,7 +129,7 @@ public function aTokenMadeOfNestedArraysIsRejectedWithoutExhaustingMemory(): voi $serializer->unserialize($token); static::fail('The token should have been rejected.'); } catch (InvalidArgumentException $e) { - static::assertStringStartsWith('Unsupported input', $e->getMessage()); + static::assertSame(self::TOO_MANY_VALUES, $e->getMessage()); } static::assertLessThan(8_000_000, memory_get_peak_usage() - $before); @@ -143,6 +178,61 @@ public static function dataJsonSerializers(): iterable yield 'general' => [new JSONGeneralSerializer()]; } + /** + * Six hundred nested arrays hold far fewer values than the bound. + * + * @return iterable + */ + public static function dataTokensNestedTooDeeply(): iterable + { + $arrays = str_repeat('[', 600) . str_repeat(']', 600); + $protectedHeader = Base64UrlSafe::encodeUnpadded('{"alg":"A128KW","enc":"A128GCM"}'); + $deepProtectedHeader = Base64UrlSafe::encodeUnpadded('{"alg":"A128KW","enc":"A128GCM","x":' . $arrays . '}'); + $parts = '"iv":"AAAA","ciphertext":"AAAA","tag":"AAAA"'; + + yield 'compact, protected header' => [new CompactSerializer(), $deepProtectedHeader . '.AAAA.AAAA.AAAA.AAAA']; + yield 'flattened, protected header' => [ + new JSONFlattenedSerializer(), + sprintf('{"protected":"%s","encrypted_key":"AAAA",%s}', $deepProtectedHeader, $parts), + ]; + yield 'flattened, unprotected header' => [ + new JSONFlattenedSerializer(), + sprintf( + '{"protected":"%s","unprotected":{"x":%s},"encrypted_key":"AAAA",%s}', + $protectedHeader, + $arrays, + $parts + ), + ]; + yield 'general, protected header' => [ + new JSONGeneralSerializer(), + sprintf('{"protected":"%s","recipients":[{"encrypted_key":"AAAA"}],%s}', $deepProtectedHeader, $parts), + ]; + yield 'general, unprotected header' => [ + new JSONGeneralSerializer(), + sprintf( + '{"protected":"%s","unprotected":{"x":%s},"recipients":[{"encrypted_key":"AAAA"}],%s}', + $protectedHeader, + $arrays, + $parts + ), + ]; + } + + /** + * @return iterable + */ + public static function dataInvalidJsonDocuments(): iterable + { + yield 'compact, protected header' => [ + new CompactSerializer(), + Base64UrlSafe::encodeUnpadded('{"alg":') . '.AAAA.AAAA.AAAA.AAAA', + 'Unsupported input', + ]; + yield 'flattened' => [new JSONFlattenedSerializer(), '{"protected":', 'Unsupported input.']; + yield 'general' => [new JSONGeneralSerializer(), '{"protected":', 'Unsupported input.']; + } + /** * @return array */ diff --git a/tests/Component/Signature/JsonValueBoundTest.php b/tests/Component/Signature/JsonValueBoundTest.php index d99d4a62..cf8e700f 100644 --- a/tests/Component/Signature/JsonValueBoundTest.php +++ b/tests/Component/Signature/JsonValueBoundTest.php @@ -22,12 +22,17 @@ use function range; use function sprintf; use function str_repeat; +use const JSON_ERROR_DEPTH; /** * @internal */ final class JsonValueBoundTest extends SignatureTestCase { + private const TOO_MANY_VALUES = 'The JSON documents of the token hold more JSON values than the 4096 that are decoded.'; + + private const TOO_DEEP = 'A JSON document of the token is nested too deeply.'; + /** * The member names are multiples of 131072: they all fall into the first bucket of a PHP array. */ @@ -48,11 +53,41 @@ public function aSignedTokenWhoseProtectedHeaderHoldsTooManyMembersIsRejected(JW $token = $serializer->serialize($jws, 0); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input'); + $this->expectExceptionMessage(self::TOO_MANY_VALUES); + + $serializer->unserialize($token); + } + + /** + * The protected header and the JSON document are decoded with a depth of 512, as by the JSON converter: the token + * is rejected with the code of the JSON error. + */ + #[DataProvider('dataTokensNestedTooDeeply')] + #[Test] + public function aTokenNestedTooDeeplyIsRejected(JWSSerializer $serializer, string $token): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(self::TOO_DEEP); + $this->expectExceptionCode(JSON_ERROR_DEPTH); $serializer->unserialize($token); } + #[DataProvider('dataInvalidJsonDocuments')] + #[Test] + public function aTokenWhoseJsonIsInvalidIsAnUnsupportedInput( + JWSSerializer $serializer, + string $token, + string $message + ): void { + try { + $serializer->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidArgumentException $e) { + static::assertSame($message, $e->getMessage()); + } + } + /** * Once decoded, the nested arrays take about a hundred times the size of the token, wherever they are. The * threshold is deliberately generous. @@ -70,7 +105,7 @@ public function aTokenMadeOfNestedArraysIsRejectedWithoutExhaustingMemory( $serializer->unserialize($token); static::fail('The token should have been rejected.'); } catch (InvalidArgumentException $e) { - static::assertStringStartsWith('Unsupported input', $e->getMessage()); + static::assertSame(self::TOO_MANY_VALUES, $e->getMessage()); } static::assertLessThan(8_000_000, memory_get_peak_usage() - $before); @@ -94,7 +129,7 @@ public function theProtectedHeadersOfAllSignaturesShareTheBound(): void $token = $serializer->serialize($builder->build()); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input.'); + $this->expectExceptionMessage(self::TOO_MANY_VALUES); $serializer->unserialize($token); } @@ -157,6 +192,67 @@ public static function dataJsonSerializers(): iterable yield 'general' => [new JSONGeneralSerializer()]; } + /** + * Six hundred nested arrays hold far fewer values than the bound. + * + * @return iterable + */ + public static function dataTokensNestedTooDeeply(): iterable + { + $arrays = str_repeat('[', 600) . str_repeat(']', 600); + $protectedHeader = Base64UrlSafe::encodeUnpadded('{"alg":"HS256"}'); + $deepProtectedHeader = Base64UrlSafe::encodeUnpadded('{"alg":"HS256","x":' . $arrays . '}'); + $signature = Base64UrlSafe::encodeUnpadded(str_repeat("\x01", 32)); + + yield 'compact, protected header' => [new CompactSerializer(), $deepProtectedHeader . '.e30.' . $signature]; + yield 'flattened, protected header' => [ + new JSONFlattenedSerializer(), + sprintf('{"payload":"e30","protected":"%s","signature":"%s"}', $deepProtectedHeader, $signature), + ]; + yield 'flattened, unprotected header' => [ + new JSONFlattenedSerializer(), + sprintf( + '{"payload":"e30","protected":"%s","header":{"x":%s},"signature":"%s"}', + $protectedHeader, + $arrays, + $signature + ), + ]; + yield 'general, protected header' => [ + new JSONGeneralSerializer(), + sprintf( + '{"payload":"e30","signatures":[{"protected":"%s","signature":"%s"}]}', + $deepProtectedHeader, + $signature + ), + ]; + yield 'general, unprotected header' => [ + new JSONGeneralSerializer(), + sprintf( + '{"payload":"e30","signatures":[{"protected":"%s","header":{"x":%s},"signature":"%s"}]}', + $protectedHeader, + $arrays, + $signature + ), + ]; + } + + /** + * @return iterable + */ + public static function dataInvalidJsonDocuments(): iterable + { + $signature = Base64UrlSafe::encodeUnpadded(str_repeat("\x01", 32)); + + yield 'compact, protected header' => [ + new CompactSerializer(), + Base64UrlSafe::encodeUnpadded('{"alg":') . '.e30.' . $signature, + 'Unsupported input', + ]; + yield 'flattened' => [new JSONFlattenedSerializer(), '{"payload":', 'Unsupported input.']; + yield 'general' => [new JSONGeneralSerializer(), '{"payload":', 'Unsupported input.']; + } + public static function dataNestedArrays(): iterable { $arrays = '[' . str_repeat(str_repeat('[', 500) . str_repeat(']', 500) . ',', 1000) . '0]'; From 5c1ae54b0e546b3038f6748935ad6711e1e01862 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 09:35:51 +0100 Subject: [PATCH 10/32] fix(serializers): chain the bound a token goes beyond in the serializer managers When no serializer could convert a token, JWSSerializerManager and JWESerializerManager chained the exception of the last serializer they tried. Only the serializer of the format of the token decodes it far enough to reach a bound of the JSON decoder, so the reason was lost whenever another serializer came after that one. A compact token was then rejected as invalid JSON by a JSON serializer, and a flattened token whose protected header went beyond a bound was rejected by the general serializer for its missing members. The decoder now throws a JsonBoundExceededException, a subclass of InvalidArgumentException, for its two bounds. The managers chain the last exception that goes back to one, and the exception of the last serializer otherwise. Their own exception is unchanged. --- .../Exception/JsonBoundExceededException.php | 14 ++++ src/Library/Core/Util/BoundedJsonDecoder.php | 16 ++-- .../Serializer/JWESerializerManager.php | 33 ++++++-- .../Serializer/JWSSerializerManager.php | 33 ++++++-- .../Component/Core/BoundedJsonDecoderTest.php | 23 +++++ tests/Component/Core/JoseExceptionTest.php | 2 + .../Encryption/JsonValueBoundTest.php | 83 +++++++++++++++++++ .../Signature/JsonValueBoundTest.php | 83 +++++++++++++++++++ 8 files changed, 270 insertions(+), 17 deletions(-) create mode 100644 src/Library/Core/Exception/JsonBoundExceededException.php diff --git a/src/Library/Core/Exception/JsonBoundExceededException.php b/src/Library/Core/Exception/JsonBoundExceededException.php new file mode 100644 index 00000000..aff34d2e --- /dev/null +++ b/src/Library/Core/Exception/JsonBoundExceededException.php @@ -0,0 +1,14 @@ +remainingValues -= self::countValues($json); if ($this->remainingValues < 0) { - throw new InvalidArgumentException(sprintf( + throw new JsonBoundExceededException(sprintf( 'The JSON documents of the token hold more JSON values than the %d that are decoded.', self::MAX_VALUES )); @@ -51,7 +53,7 @@ public function decode(#[SensitiveParameter] string $json): mixed throw $exception; } $this->exceededMaxDepth = true; - throw new InvalidArgumentException( + throw new JsonBoundExceededException( 'A JSON document of the token is nested too deeply.', $exception->getCode(), $exception->getPrevious() diff --git a/src/Library/Encryption/Serializer/JWESerializerManager.php b/src/Library/Encryption/Serializer/JWESerializerManager.php index 2634f3f2..2ba64041 100644 --- a/src/Library/Encryption/Serializer/JWESerializerManager.php +++ b/src/Library/Encryption/Serializer/JWESerializerManager.php @@ -6,8 +6,10 @@ use InvalidArgumentException; use Jose\Component\Core\Exception\InvalidSerializationException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Exception\UnsupportedSerializerException; use Jose\Component\Encryption\JWE; +use Throwable; use function func_num_args; use function sprintf; use function trigger_deprecation; @@ -60,8 +62,8 @@ public function serialize(string $name, JWE $jws, ?int $recipientIndex = null): /** * Loads data and return a JWE object. Throws an exception if none of the serializer was able to convert the input. * - * When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous - * exception, so that the actual reason of the failure remains available to the caller. + * When no serializer is able to convert the input, the exception of one of them is chained as the previous + * exception, as unserializeToken() chains it. * * @param string $input A string that represents a JWE * @param string|null $name the name of the serializer if the input is unserialized. Passing that argument is @@ -92,24 +94,45 @@ public function unserialize(string $input, ?string &$name = null): JWE * Loads data and returns the JWE object it represents, together with the name of the serializer that was able to * convert it. * - * When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous - * exception, so that the actual reason of the failure remains available to the caller. + * When no serializer is able to convert the input, the exception of one of them is chained as the previous + * exception, so that the actual reason of the failure remains available to the caller. Only the serializer of the + * format of the input decodes it far enough to reach a bound of the JSON decoder: the last exception that goes back + * to such a bound is chained, and the exception of the last serializer otherwise. * * @param string $input A string that represents a JWE */ public function unserializeToken(string $input): UnserializationResult { $lastError = null; + $boundError = null; foreach ($this->serializers as $serializer) { try { return new UnserializationResult($serializer->unserialize($input), $serializer->name()); } catch (InvalidArgumentException $invalidArgumentException) { $lastError = $invalidArgumentException; + if (self::goesBackToAJsonBound($invalidArgumentException)) { + $boundError = $invalidArgumentException; + } continue; } } - throw new InvalidSerializationException('Unsupported input.', 0, $lastError); + throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $lastError); + } + + /** + * Whether the exception, or one of the exceptions it chains, rejects the input for a bound of the JSON decoder. + */ + private static function goesBackToAJsonBound(?Throwable $throwable): bool + { + while ($throwable !== null) { + if ($throwable instanceof JsonBoundExceededException) { + return true; + } + $throwable = $throwable->getPrevious(); + } + + return false; } } diff --git a/src/Library/Signature/Serializer/JWSSerializerManager.php b/src/Library/Signature/Serializer/JWSSerializerManager.php index a9312e3f..7174c8ec 100644 --- a/src/Library/Signature/Serializer/JWSSerializerManager.php +++ b/src/Library/Signature/Serializer/JWSSerializerManager.php @@ -6,9 +6,11 @@ use InvalidArgumentException; use Jose\Component\Core\Exception\InvalidSerializationException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Exception\UnsupportedSerializerException; use Jose\Component\Signature\JWS; use SensitiveParameter; +use Throwable; use function func_num_args; use function sprintf; use function trigger_deprecation; @@ -59,8 +61,8 @@ public function serialize(string $name, JWS $jws, ?int $signatureIndex = null): /** * Loads data and return a JWS object. * - * When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous - * exception, so that the actual reason of the failure remains available to the caller. + * When no serializer is able to convert the input, the exception of one of them is chained as the previous + * exception, as unserializeToken() chains it. * * @param string $input A string that represents a JWS * @param string|null $name the name of the serializer if the input is unserialized. Passing that argument is @@ -91,24 +93,45 @@ public function unserialize(#[SensitiveParameter] string $input, ?string &$name * Loads data and returns the JWS object it represents, together with the name of the serializer that was able to * convert it. * - * When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous - * exception, so that the actual reason of the failure remains available to the caller. + * When no serializer is able to convert the input, the exception of one of them is chained as the previous + * exception, so that the actual reason of the failure remains available to the caller. Only the serializer of the + * format of the input decodes it far enough to reach a bound of the JSON decoder: the last exception that goes back + * to such a bound is chained, and the exception of the last serializer otherwise. * * @param string $input A string that represents a JWS */ public function unserializeToken(#[SensitiveParameter] string $input): UnserializationResult { $lastError = null; + $boundError = null; foreach ($this->serializers as $serializer) { try { return new UnserializationResult($serializer->unserialize($input), $serializer->name()); } catch (InvalidArgumentException $invalidArgumentException) { $lastError = $invalidArgumentException; + if (self::goesBackToAJsonBound($invalidArgumentException)) { + $boundError = $invalidArgumentException; + } continue; } } - throw new InvalidSerializationException('Unsupported input.', 0, $lastError); + throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $lastError); + } + + /** + * Whether the exception, or one of the exceptions it chains, rejects the input for a bound of the JSON decoder. + */ + private static function goesBackToAJsonBound(?Throwable $throwable): bool + { + while ($throwable !== null) { + if ($throwable instanceof JsonBoundExceededException) { + return true; + } + $throwable = $throwable->getPrevious(); + } + + return false; } } diff --git a/tests/Component/Core/BoundedJsonDecoderTest.php b/tests/Component/Core/BoundedJsonDecoderTest.php index 87d3eee3..475f0f77 100644 --- a/tests/Component/Core/BoundedJsonDecoderTest.php +++ b/tests/Component/Core/BoundedJsonDecoderTest.php @@ -5,6 +5,7 @@ namespace Jose\Tests\Component\Core; use InvalidArgumentException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Util\BoundedJsonDecoder; use JsonException; use PHPUnit\Framework\Attributes\DataProvider; @@ -100,12 +101,34 @@ public function anInvalidDocumentKeepsTheErrorOfTheJsonConverter(): void } catch (InvalidArgumentException $e) { static::assertSame('Unsupported input.', $e->getMessage()); static::assertSame(JSON_ERROR_SYNTAX, $e->getCode()); + static::assertNotInstanceOf(JsonBoundExceededException::class, $e); } static::assertFalse($json->hasExceededMaxDepth()); static::assertFalse($json->hasExceededMaxValues()); } + /** + * The class of the exception tells the two bounds apart from invalid JSON, whatever its message. + */ + #[Test] + #[DataProvider('documentsBeyondABound')] + public function aDocumentBeyondABoundIsRejectedWithAJsonBoundExceededException(string $document): void + { + $this->expectException(JsonBoundExceededException::class); + + (new BoundedJsonDecoder())->decode($document); + } + + /** + * @return iterable + */ + public static function documentsBeyondABound(): iterable + { + yield 'more than 4096 values' => ['[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES) . '0]']; + yield 'nested too deeply' => [str_repeat('[', 600) . str_repeat(']', 600)]; + } + #[Test] #[DataProvider('documentsJsonDecodeRejects')] public function aDocumentJsonDecodeRejectsDoesNotExceedTheBound(string $document): void diff --git a/tests/Component/Core/JoseExceptionTest.php b/tests/Component/Core/JoseExceptionTest.php index 5141029b..317f370e 100644 --- a/tests/Component/Core/JoseExceptionTest.php +++ b/tests/Component/Core/JoseExceptionTest.php @@ -18,6 +18,7 @@ use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\Exception\InvalidTokenException; use Jose\Component\Core\Exception\JoseException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Exception\LogicException as JoseLogicException; use Jose\Component\Core\Exception\MissingDependencyException; use Jose\Component\Core\Exception\MissingPayloadException; @@ -66,6 +67,7 @@ final class JoseExceptionTest extends TestCase InvalidPayloadException::class => InvalidArgumentException::class, InvalidSerializationException::class => InvalidArgumentException::class, InvalidTokenException::class => RuntimeException::class, + JsonBoundExceededException::class => InvalidArgumentException::class, JoseLogicException::class => LogicException::class, MissingDependencyException::class => RuntimeException::class, MissingPayloadLogicException::class => LogicException::class, diff --git a/tests/Component/Encryption/JsonValueBoundTest.php b/tests/Component/Encryption/JsonValueBoundTest.php index 7f56b5d9..6f14431e 100644 --- a/tests/Component/Encryption/JsonValueBoundTest.php +++ b/tests/Component/Encryption/JsonValueBoundTest.php @@ -5,6 +5,7 @@ namespace Jose\Tests\Component\Encryption; use InvalidArgumentException; +use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; @@ -12,6 +13,7 @@ use Jose\Component\Encryption\Serializer\JSONFlattenedSerializer; use Jose\Component\Encryption\Serializer\JSONGeneralSerializer; use Jose\Component\Encryption\Serializer\JWESerializer; +use Jose\Component\Encryption\Serializer\JWESerializerManager; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use function array_fill_keys; @@ -73,6 +75,30 @@ public function aTokenNestedTooDeeplyIsRejected(JWESerializer $serializer, strin $serializer->unserialize($token); } + /** + * Only the serializer of the format of the token decodes it far enough to reach a bound of the JSON decoder: the + * manager chains its exception, whatever the order of the serializers. Without such an exception, it chains the + * exception of the last serializer. + * + * @param list $serializers + */ + #[DataProvider('dataTokensForTheSerializerManager')] + #[Test] + public function theSerializerManagerChainsTheExceptionOfTheBound( + array $serializers, + string $token, + string $message + ): void { + try { + (new JWESerializerManager($serializers))->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidSerializationException $e) { + static::assertSame('Unsupported input.', $e->getMessage()); + static::assertSame(0, $e->getCode()); + static::assertSame($message, $e->getPrevious()?->getMessage()); + } + } + #[DataProvider('dataInvalidJsonDocuments')] #[Test] public function aTokenWhoseJsonIsInvalidIsAnUnsupportedInput( @@ -219,6 +245,63 @@ public static function dataTokensNestedTooDeeply(): iterable ]; } + /** + * @return iterable, string, string}> + */ + public static function dataTokensForTheSerializerManager(): iterable + { + $compactFirst = [new CompactSerializer(), new JSONFlattenedSerializer(), new JSONGeneralSerializer()]; + $compactLast = [new JSONFlattenedSerializer(), new JSONGeneralSerializer(), new CompactSerializer()]; + $values = '[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES) . '0]'; + $arrays = str_repeat('[', 600) . str_repeat(']', 600); + $manyValues = Base64UrlSafe::encodeUnpadded('{"alg":"A128KW","enc":"A128GCM","x":' . $values . '}'); + $deep = Base64UrlSafe::encodeUnpadded('{"alg":"A128KW","enc":"A128GCM","x":' . $arrays . '}'); + $parts = '"encrypted_key":"AAAA","iv":"AAAA","ciphertext":"AAAA","tag":"AAAA"'; + $flattened = static fn (string $protectedHeader): string => sprintf( + '{"protected":"%s",%s}', + $protectedHeader, + $parts + ); + $document = sprintf( + '{"protected":"%s","unprotected":{"x":%s},%s}', + Base64UrlSafe::encodeUnpadded('{"alg":"A128KW","enc":"A128GCM"}'), + $values, + $parts + ); + + yield 'compact, too many values, compact first' => [ + $compactFirst, + $manyValues . '.AAAA.AAAA.AAAA.AAAA', + self::TOO_MANY_VALUES, + ]; + yield 'compact, nested too deeply, compact first' => [ + $compactFirst, + $deep . '.AAAA.AAAA.AAAA.AAAA', + self::TOO_DEEP, + ]; + yield 'compact, too many values, compact last' => [ + $compactLast, + $manyValues . '.AAAA.AAAA.AAAA.AAAA', + self::TOO_MANY_VALUES, + ]; + yield 'flattened, protected header with too many values' => [ + $compactFirst, + $flattened($manyValues), + self::TOO_MANY_VALUES, + ]; + yield 'flattened, protected header nested too deeply' => [$compactFirst, $flattened($deep), self::TOO_DEEP]; + yield 'flattened, document with too many values, compact last' => [ + $compactLast, + $document, + self::TOO_MANY_VALUES, + ]; + yield 'not a token: the exception of the last serializer' => [ + $compactFirst, + 'This is not a token', + 'Unsupported input.', + ]; + } + /** * @return iterable */ diff --git a/tests/Component/Signature/JsonValueBoundTest.php b/tests/Component/Signature/JsonValueBoundTest.php index cf8e700f..daf46425 100644 --- a/tests/Component/Signature/JsonValueBoundTest.php +++ b/tests/Component/Signature/JsonValueBoundTest.php @@ -5,6 +5,7 @@ namespace Jose\Tests\Component\Signature; use InvalidArgumentException; +use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; @@ -12,6 +13,7 @@ use Jose\Component\Signature\Serializer\JSONFlattenedSerializer; use Jose\Component\Signature\Serializer\JSONGeneralSerializer; use Jose\Component\Signature\Serializer\JWSSerializer; +use Jose\Component\Signature\Serializer\JWSSerializerManager; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use function array_fill_keys; @@ -73,6 +75,30 @@ public function aTokenNestedTooDeeplyIsRejected(JWSSerializer $serializer, strin $serializer->unserialize($token); } + /** + * Only the serializer of the format of the token decodes it far enough to reach a bound of the JSON decoder: the + * manager chains its exception, whatever the order of the serializers. Without such an exception, it chains the + * exception of the last serializer. + * + * @param list $serializers + */ + #[DataProvider('dataTokensForTheSerializerManager')] + #[Test] + public function theSerializerManagerChainsTheExceptionOfTheBound( + array $serializers, + string $token, + string $message + ): void { + try { + (new JWSSerializerManager($serializers))->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidSerializationException $e) { + static::assertSame('Unsupported input.', $e->getMessage()); + static::assertSame(0, $e->getCode()); + static::assertSame($message, $e->getPrevious()?->getMessage()); + } + } + #[DataProvider('dataInvalidJsonDocuments')] #[Test] public function aTokenWhoseJsonIsInvalidIsAnUnsupportedInput( @@ -237,6 +263,63 @@ public static function dataTokensNestedTooDeeply(): iterable ]; } + /** + * @return iterable, string, string}> + */ + public static function dataTokensForTheSerializerManager(): iterable + { + $compactFirst = [new CompactSerializer(), new JSONFlattenedSerializer(), new JSONGeneralSerializer()]; + $compactLast = [new JSONFlattenedSerializer(), new JSONGeneralSerializer(), new CompactSerializer()]; + $values = '[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES) . '0]'; + $arrays = str_repeat('[', 600) . str_repeat(']', 600); + $manyValues = Base64UrlSafe::encodeUnpadded('{"alg":"HS256","x":' . $values . '}'); + $deep = Base64UrlSafe::encodeUnpadded('{"alg":"HS256","x":' . $arrays . '}'); + $signature = Base64UrlSafe::encodeUnpadded(str_repeat("\x01", 32)); + $flattened = static fn (string $protectedHeader): string => sprintf( + '{"payload":"e30","protected":"%s","signature":"%s"}', + $protectedHeader, + $signature + ); + $document = sprintf( + '{"payload":"e30","protected":"%s","header":{"x":%s},"signature":"%s"}', + Base64UrlSafe::encodeUnpadded('{"alg":"HS256"}'), + $values, + $signature + ); + + yield 'compact, too many values, compact first' => [ + $compactFirst, + $manyValues . '.e30.' . $signature, + self::TOO_MANY_VALUES, + ]; + yield 'compact, nested too deeply, compact first' => [ + $compactFirst, + $deep . '.e30.' . $signature, + self::TOO_DEEP, + ]; + yield 'compact, too many values, compact last' => [ + $compactLast, + $manyValues . '.e30.' . $signature, + self::TOO_MANY_VALUES, + ]; + yield 'flattened, protected header with too many values' => [ + $compactFirst, + $flattened($manyValues), + self::TOO_MANY_VALUES, + ]; + yield 'flattened, protected header nested too deeply' => [$compactFirst, $flattened($deep), self::TOO_DEEP]; + yield 'flattened, document with too many values, compact last' => [ + $compactLast, + $document, + self::TOO_MANY_VALUES, + ]; + yield 'not a token: the exception of the last serializer' => [ + $compactFirst, + 'This is not a token', + 'Unsupported input.', + ]; + } + /** * @return iterable */ From 6ee5c8e3c64abd958e7dea742864e8d77dd2f93a Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 10:51:03 +0100 Subject: [PATCH 11/32] fix(serializers): chain the reason of the serializer a token belongs to When no serializer could convert a token, the managers chained the exception of a bound or, without one, that of the last serializer they tried. A token rejected by the serializer of its format for another reason was then reported with the exception of a serializer of another format, which had only rejected the token as foreign. A compact token whose protected header is not a JSON object was reported as invalid JSON by the general serializer. A serializer now rejects an input of another serialization with an UnrecognizedSerializationException, a subclass of InvalidSerializationException. That is a compact serialization of another number of parts or whose protected header part is not base64url, or a JSON document that is not valid JSON, not an object, or without the members of the serialization. The managers chain the exception of a bound first, then the last exception without that mark, and the exception of the last serializer otherwise. Messages and codes are unchanged. --- .../UnrecognizedSerializationException.php | 14 + src/Library/Core/Util/BoundedJsonDecoder.php | 24 ++ .../Serializer/CompactSerializer.php | 7 +- .../Serializer/JSONFlattenedSerializer.php | 8 +- .../Serializer/JSONGeneralSerializer.php | 8 +- .../Serializer/JWESerializerManager.php | 12 +- .../Serializer/CompactSerializer.php | 7 +- .../Serializer/JSONFlattenedSerializer.php | 10 +- .../Serializer/JSONGeneralSerializer.php | 10 +- .../Serializer/JWSSerializerManager.php | 12 +- tests/Component/Core/JoseExceptionTest.php | 2 + .../Encryption/JWESerializerManagerTest.php | 307 +++++++++++++++++ .../Signature/JWSSerializerManagerTest.php | 313 ++++++++++++++++++ 13 files changed, 706 insertions(+), 28 deletions(-) create mode 100644 src/Library/Core/Exception/UnrecognizedSerializationException.php create mode 100644 tests/Component/Encryption/JWESerializerManagerTest.php create mode 100644 tests/Component/Signature/JWSSerializerManagerTest.php diff --git a/src/Library/Core/Exception/UnrecognizedSerializationException.php b/src/Library/Core/Exception/UnrecognizedSerializationException.php new file mode 100644 index 00000000..4c9ef5e7 --- /dev/null +++ b/src/Library/Core/Exception/UnrecognizedSerializationException.php @@ -0,0 +1,14 @@ +decode($json); + } catch (JsonBoundExceededException $exception) { + throw $exception; + } catch (InvalidArgumentException $exception) { + throw new UnrecognizedSerializationException( + $exception->getMessage(), + $exception->getCode(), + $exception->getPrevious() + ); + } + } + /** * Whether a document given to this decoder was rejected for its depth. */ diff --git a/src/Library/Encryption/Serializer/CompactSerializer.php b/src/Library/Encryption/Serializer/CompactSerializer.php index 9aa4d0cd..1b36a77c 100644 --- a/src/Library/Encryption/Serializer/CompactSerializer.php +++ b/src/Library/Encryption/Serializer/CompactSerializer.php @@ -6,6 +6,7 @@ use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\Exception\LogicException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Encryption\JWE; @@ -14,6 +15,7 @@ use Throwable; use function count; use function is_array; +use function preg_match; use function sprintf; final readonly class CompactSerializer implements JWESerializer @@ -66,7 +68,7 @@ public function unserialize(string $input): JWE { $parts = explode('.', $input, 6); if (count($parts) !== 5) { - throw new InvalidSerializationException('Unsupported input'); + throw new UnrecognizedSerializationException('Unsupported input'); } $decoder = new BoundedJsonDecoder(); @@ -94,6 +96,9 @@ public function unserialize(string $input): JWE [new Recipient([], $encryptedKey)] ); } catch (Throwable $throwable) { + if (preg_match('/^[A-Za-z0-9_-]*\z/', $parts[0]) !== 1) { + throw new UnrecognizedSerializationException('Unsupported input', $throwable->getCode(), $throwable); + } throw new InvalidSerializationException( $decoder->hasExceededMaxValues() || $decoder->hasExceededMaxDepth() ? $throwable->getMessage() diff --git a/src/Library/Encryption/Serializer/JSONFlattenedSerializer.php b/src/Library/Encryption/Serializer/JSONFlattenedSerializer.php index 65c397a4..9871b2ab 100644 --- a/src/Library/Encryption/Serializer/JSONFlattenedSerializer.php +++ b/src/Library/Encryption/Serializer/JSONFlattenedSerializer.php @@ -4,7 +4,7 @@ namespace Jose\Component\Encryption\Serializer; -use Jose\Component\Core\Exception\InvalidSerializationException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\JsonConverter; @@ -64,9 +64,9 @@ public function serialize(JWE $jwe, ?int $recipientIndex = null): string public function unserialize(string $input): JWE { $json = new BoundedJsonDecoder(); - $data = $json->decode($input); + $data = $json->decodeSerialization($input); if (! is_array($data)) { - throw new InvalidSerializationException('Unsupported input.'); + throw new UnrecognizedSerializationException('Unsupported input.'); } $this->checkData($data); @@ -95,7 +95,7 @@ public function unserialize(string $input): JWE private function checkData(?array $data): void { if ($data === null || ! isset($data['ciphertext']) || isset($data['recipients'])) { - throw new InvalidSerializationException('Unsupported input.'); + throw new UnrecognizedSerializationException('Unsupported input.'); } } diff --git a/src/Library/Encryption/Serializer/JSONGeneralSerializer.php b/src/Library/Encryption/Serializer/JSONGeneralSerializer.php index 01fe4a0f..bb3b1443 100644 --- a/src/Library/Encryption/Serializer/JSONGeneralSerializer.php +++ b/src/Library/Encryption/Serializer/JSONGeneralSerializer.php @@ -4,8 +4,8 @@ namespace Jose\Component\Encryption\Serializer; -use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\Exception\LogicException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\JsonConverter; @@ -72,9 +72,9 @@ public function serialize(JWE $jwe, ?int $recipientIndex = null): string public function unserialize(string $input): JWE { $json = new BoundedJsonDecoder(); - $data = $json->decode($input); + $data = $json->decodeSerialization($input); if (! is_array($data)) { - throw new InvalidSerializationException('Unsupported input.'); + throw new UnrecognizedSerializationException('Unsupported input.'); } $this->checkData($data); @@ -104,7 +104,7 @@ public function unserialize(string $input): JWE private function checkData(?array $data): void { if ($data === null || ! isset($data['ciphertext']) || ! isset($data['recipients'])) { - throw new InvalidSerializationException('Unsupported input.'); + throw new UnrecognizedSerializationException('Unsupported input.'); } } diff --git a/src/Library/Encryption/Serializer/JWESerializerManager.php b/src/Library/Encryption/Serializer/JWESerializerManager.php index 2ba64041..1955df69 100644 --- a/src/Library/Encryption/Serializer/JWESerializerManager.php +++ b/src/Library/Encryption/Serializer/JWESerializerManager.php @@ -7,6 +7,7 @@ use InvalidArgumentException; use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\Exception\JsonBoundExceededException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Exception\UnsupportedSerializerException; use Jose\Component\Encryption\JWE; use Throwable; @@ -96,8 +97,10 @@ public function unserialize(string $input, ?string &$name = null): JWE * * When no serializer is able to convert the input, the exception of one of them is chained as the previous * exception, so that the actual reason of the failure remains available to the caller. Only the serializer of the - * format of the input decodes it far enough to reach a bound of the JSON decoder: the last exception that goes back - * to such a bound is chained, and the exception of the last serializer otherwise. + * format of the input decodes it far enough to reach a bound of the JSON decoder, and a serializer rejects an input + * of another serialization with an UnrecognizedSerializationException. The manager chains the last exception that + * goes back to a bound, else the last exception of a serializer that recognized the input, else the exception of + * the last serializer. * * @param string $input A string that represents a JWE */ @@ -105,6 +108,7 @@ public function unserializeToken(string $input): UnserializationResult { $lastError = null; $boundError = null; + $recognizedError = null; foreach ($this->serializers as $serializer) { try { return new UnserializationResult($serializer->unserialize($input), $serializer->name()); @@ -112,13 +116,15 @@ public function unserializeToken(string $input): UnserializationResult $lastError = $invalidArgumentException; if (self::goesBackToAJsonBound($invalidArgumentException)) { $boundError = $invalidArgumentException; + } elseif (! $invalidArgumentException instanceof UnrecognizedSerializationException) { + $recognizedError = $invalidArgumentException; } continue; } } - throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $lastError); + throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $recognizedError ?? $lastError); } /** diff --git a/src/Library/Signature/Serializer/CompactSerializer.php b/src/Library/Signature/Serializer/CompactSerializer.php index c8299027..65b6052d 100644 --- a/src/Library/Signature/Serializer/CompactSerializer.php +++ b/src/Library/Signature/Serializer/CompactSerializer.php @@ -6,6 +6,7 @@ use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\Exception\LogicException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Signature\JWS; @@ -14,6 +15,7 @@ use Throwable; use function count; use function is_array; +use function preg_match; use function sprintf; final readonly class CompactSerializer extends Serializer @@ -71,7 +73,7 @@ public function unserialize(#[SensitiveParameter] string $input): JWS { $parts = explode('.', $input, 4); if (count($parts) !== 3) { - throw new InvalidSerializationException('Unsupported input'); + throw new UnrecognizedSerializationException('Unsupported input'); } $decoder = new BoundedJsonDecoder(); @@ -97,6 +99,9 @@ public function unserialize(#[SensitiveParameter] string $input): JWS return $jws->addSignature($signature, $protectedHeader, $encodedProtectedHeader); } catch (Throwable $throwable) { + if (preg_match('/^[A-Za-z0-9_-]*\z/', $parts[0]) !== 1) { + throw new UnrecognizedSerializationException('Unsupported input', $throwable->getCode(), $throwable); + } throw new InvalidSerializationException( $decoder->hasExceededMaxValues() || $decoder->hasExceededMaxDepth() ? $throwable->getMessage() diff --git a/src/Library/Signature/Serializer/JSONFlattenedSerializer.php b/src/Library/Signature/Serializer/JSONFlattenedSerializer.php index 9895c689..0ba61f45 100644 --- a/src/Library/Signature/Serializer/JSONFlattenedSerializer.php +++ b/src/Library/Signature/Serializer/JSONFlattenedSerializer.php @@ -5,6 +5,7 @@ namespace Jose\Component\Signature\Serializer; use Jose\Component\Core\Exception\InvalidSerializationException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\JsonConverter; @@ -58,12 +59,9 @@ public function serialize(JWS $jws, ?int $signatureIndex = null): string public function unserialize(#[SensitiveParameter] string $input): JWS { $json = new BoundedJsonDecoder(); - $data = $json->decode($input); - if (! is_array($data)) { - throw new InvalidSerializationException('Unsupported input.'); - } - if (! isset($data['signature'])) { - throw new InvalidSerializationException('Unsupported input.'); + $data = $json->decodeSerialization($input); + if (! is_array($data) || ! isset($data['signature'])) { + throw new UnrecognizedSerializationException('Unsupported input.'); } $signature = Base64UrlSafe::decodeNoPadding($data['signature']); diff --git a/src/Library/Signature/Serializer/JSONGeneralSerializer.php b/src/Library/Signature/Serializer/JSONGeneralSerializer.php index 73065acb..0f302684 100644 --- a/src/Library/Signature/Serializer/JSONGeneralSerializer.php +++ b/src/Library/Signature/Serializer/JSONGeneralSerializer.php @@ -7,6 +7,7 @@ use Jose\Component\Core\Exception\InvalidPayloadException; use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\Exception\LogicException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Util\Base64UrlSafe; use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\JsonConverter; @@ -75,12 +76,9 @@ public function serialize(JWS $jws, ?int $signatureIndex = null): string public function unserialize(#[SensitiveParameter] string $input): JWS { $json = new BoundedJsonDecoder(); - $data = $json->decode($input); - if (! is_array($data)) { - throw new InvalidSerializationException('Unsupported input.'); - } - if (! isset($data['signatures'])) { - throw new InvalidSerializationException('Unsupported input.'); + $data = $json->decodeSerialization($input); + if (! is_array($data) || ! isset($data['signatures'])) { + throw new UnrecognizedSerializationException('Unsupported input.'); } $isPayloadEncoded = null; diff --git a/src/Library/Signature/Serializer/JWSSerializerManager.php b/src/Library/Signature/Serializer/JWSSerializerManager.php index 7174c8ec..59142358 100644 --- a/src/Library/Signature/Serializer/JWSSerializerManager.php +++ b/src/Library/Signature/Serializer/JWSSerializerManager.php @@ -7,6 +7,7 @@ use InvalidArgumentException; use Jose\Component\Core\Exception\InvalidSerializationException; use Jose\Component\Core\Exception\JsonBoundExceededException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Exception\UnsupportedSerializerException; use Jose\Component\Signature\JWS; use SensitiveParameter; @@ -95,8 +96,10 @@ public function unserialize(#[SensitiveParameter] string $input, ?string &$name * * When no serializer is able to convert the input, the exception of one of them is chained as the previous * exception, so that the actual reason of the failure remains available to the caller. Only the serializer of the - * format of the input decodes it far enough to reach a bound of the JSON decoder: the last exception that goes back - * to such a bound is chained, and the exception of the last serializer otherwise. + * format of the input decodes it far enough to reach a bound of the JSON decoder, and a serializer rejects an input + * of another serialization with an UnrecognizedSerializationException. The manager chains the last exception that + * goes back to a bound, else the last exception of a serializer that recognized the input, else the exception of + * the last serializer. * * @param string $input A string that represents a JWS */ @@ -104,6 +107,7 @@ public function unserializeToken(#[SensitiveParameter] string $input): Unseriali { $lastError = null; $boundError = null; + $recognizedError = null; foreach ($this->serializers as $serializer) { try { return new UnserializationResult($serializer->unserialize($input), $serializer->name()); @@ -111,13 +115,15 @@ public function unserializeToken(#[SensitiveParameter] string $input): Unseriali $lastError = $invalidArgumentException; if (self::goesBackToAJsonBound($invalidArgumentException)) { $boundError = $invalidArgumentException; + } elseif (! $invalidArgumentException instanceof UnrecognizedSerializationException) { + $recognizedError = $invalidArgumentException; } continue; } } - throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $lastError); + throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $recognizedError ?? $lastError); } /** diff --git a/tests/Component/Core/JoseExceptionTest.php b/tests/Component/Core/JoseExceptionTest.php index 317f370e..8936d208 100644 --- a/tests/Component/Core/JoseExceptionTest.php +++ b/tests/Component/Core/JoseExceptionTest.php @@ -26,6 +26,7 @@ use Jose\Component\Core\Exception\MissingPayloadRuntimeException; use Jose\Component\Core\Exception\RangeException as JoseRangeException; use Jose\Component\Core\Exception\RuntimeException as JoseRuntimeException; +use Jose\Component\Core\Exception\UnrecognizedSerializationException; use Jose\Component\Core\Exception\UnsupportedAlgorithmException; use Jose\Component\Core\Exception\UnsupportedCurveException; use Jose\Component\Core\Exception\UnsupportedSerializerException; @@ -74,6 +75,7 @@ final class JoseExceptionTest extends TestCase MissingPayloadRuntimeException::class => RuntimeException::class, JoseRangeException::class => RangeException::class, JoseRuntimeException::class => RuntimeException::class, + UnrecognizedSerializationException::class => InvalidArgumentException::class, UnsupportedAlgorithmException::class => InvalidArgumentException::class, UnsupportedCurveException::class => InvalidArgumentException::class, UnsupportedSerializerException::class => InvalidArgumentException::class, diff --git a/tests/Component/Encryption/JWESerializerManagerTest.php b/tests/Component/Encryption/JWESerializerManagerTest.php new file mode 100644 index 00000000..a054908b --- /dev/null +++ b/tests/Component/Encryption/JWESerializerManagerTest.php @@ -0,0 +1,307 @@ +expectException(UnrecognizedSerializationException::class); + $this->expectExceptionMessage($message); + + $serializer->unserialize($input); + } + + #[DataProvider('invalidTokensOfTheSerialization')] + #[Test] + public function aSerializerRejectsAnInvalidTokenOfItsSerializationWithoutTheMark( + JWESerializer $serializer, + string $token + ): void { + try { + $serializer->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidArgumentException $exception) { + static::assertNotInstanceOf(UnrecognizedSerializationException::class, $exception); + } + } + + /** + * @param list $serializers + */ + #[DataProvider('tokensForTheManager')] + #[Test] + public function theManagerChainsTheExceptionOfTheSerializerTheTokenBelongsTo( + array $serializers, + string $token, + string $message, + string $reason, + bool $recognized + ): void { + try { + (new JWESerializerManager($serializers))->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidSerializationException $exception) { + static::assertSame('Unsupported input.', $exception->getMessage()); + static::assertSame(0, $exception->getCode()); + $previous = $exception->getPrevious(); + static::assertNotNull($previous); + static::assertSame($message, $previous->getMessage()); + static::assertSame($reason, self::reason($previous)); + static::assertSame($recognized, ! $previous instanceof UnrecognizedSerializationException); + } + } + + /** + * A serializer of another library may reject every input: the bound of a token of a serializer of this library + * comes first, and a serializer that marks the inputs it does not recognize is skipped. + */ + #[Test] + public function theSerializersOfAnotherLibraryDoNotHideTheReason(): void + { + $compact = new CompactSerializer(); + $values = '[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES) . '0]'; + $beyondTheBound = Base64UrlSafe::encodeUnpadded( + '{"alg":"A128KW","enc":"A128GCM","x":' . $values . '}' + ) . '.AAAA.AAAA.AAAA.AAAA'; + $unmarked = self::serializerOfAnotherLibrary(new InvalidArgumentException('Not a token of this library.')); + $marked = self::serializerOfAnotherLibrary( + new UnrecognizedSerializationException('Not a token of this library.') + ); + + static::assertSame( + 'The JSON documents of the token hold more JSON values than the 4096 that are decoded.', + self::chainedReason([$compact, $unmarked], $beyondTheBound) + ); + static::assertSame('Unsupported input.', self::chainedReason([$compact, $marked], self::badProtectedHeader())); + } + + /** + * @return iterable + */ + public static function inputsOfAnotherSerialization(): iterable + { + $compact = new CompactSerializer(); + $flattened = new JSONFlattenedSerializer(); + $general = new JSONGeneralSerializer(); + $compactToken = self::protectedHeader() . '.AAAA.AAAA.AAAA.AAAA'; + $flattenedToken = self::flattened(self::protectedHeader()); + $generalToken = self::general(self::protectedHeader()); + + yield 'compact, not a token' => [$compact, 'This is not a token', 'Unsupported input']; + yield 'compact, three parts' => [$compact, 'e30.AAAA.AAAA', 'Unsupported input']; + yield 'compact, a flattened token' => [$compact, $flattenedToken, 'Unsupported input']; + yield 'compact, JSON with four dots' => [ + $compact, + sprintf( + '{"protected":"%s","unprotected":{"jku":"https://a.example.com/x.json","kid":"y.z"},%s}', + self::protectedHeader(), + self::PARTS + ), + 'Unsupported input', + ]; + yield 'flattened, not a token' => [$flattened, 'This is not a token', 'Unsupported input.']; + yield 'flattened, a compact token' => [$flattened, $compactToken, 'Unsupported input.']; + yield 'flattened, a list' => [$flattened, '[1]', 'Unsupported input.']; + yield 'flattened, a general token' => [$flattened, $generalToken, 'Unsupported input.']; + yield 'general, not a token' => [$general, 'This is not a token', 'Unsupported input.']; + yield 'general, a compact token' => [$general, $compactToken, 'Unsupported input.']; + yield 'general, a string' => [$general, '"x"', 'Unsupported input.']; + yield 'general, a flattened token' => [$general, $flattenedToken, 'Unsupported input.']; + } + + /** + * @return iterable + */ + public static function invalidTokensOfTheSerialization(): iterable + { + $invalidJson = Base64UrlSafe::encodeUnpadded('{'); + + yield 'compact, a protected header that is not an object' => [ + new CompactSerializer(), + self::badProtectedHeader(), + ]; + yield 'compact, a protected header that is not JSON' => [ + new CompactSerializer(), + $invalidJson . '.AAAA.AAAA.AAAA.AAAA', + ]; + yield 'compact, a protected header of an impossible length' => [ + new CompactSerializer(), + 'e30AA.AAAA.AAAA.AAAA.AAAA', + ]; + yield 'compact, an initialization vector of an impossible length' => [ + new CompactSerializer(), + self::protectedHeader() . '.AAAA.A.AAAA.AAAA', + ]; + yield 'flattened, a protected header that is not JSON' => [ + new JSONFlattenedSerializer(), + self::flattened($invalidJson), + ]; + yield 'general, a protected header that is not JSON' => [ + new JSONGeneralSerializer(), + self::general($invalidJson), + ]; + } + + /** + * @return iterable, string, string, string, bool}> + */ + public static function tokensForTheManager(): iterable + { + $orders = [ + 'compact first' => [new CompactSerializer(), new JSONFlattenedSerializer(), new JSONGeneralSerializer()], + 'compact last' => [new JSONFlattenedSerializer(), new JSONGeneralSerializer(), new CompactSerializer()], + 'general first' => [new JSONGeneralSerializer(), new CompactSerializer(), new JSONFlattenedSerializer()], + ]; + $invalidJson = Base64UrlSafe::encodeUnpadded('{'); + $tokens = [ + 'a compact token whose protected header is not an object' => [ + self::badProtectedHeader(), + 'Unsupported input', + 'Unsupported input.', + ], + 'a compact token whose protected header is not JSON' => [ + $invalidJson . '.AAAA.AAAA.AAAA.AAAA', + 'Unsupported input', + 'Syntax error', + ], + 'a flattened token whose protected header is not JSON' => [ + self::flattened($invalidJson), + 'Unsupported input.', + 'Syntax error', + ], + 'a general token whose protected header is not JSON' => [ + self::general($invalidJson), + 'Unsupported input.', + 'Syntax error', + ], + ]; + foreach ($orders as $order => $serializers) { + foreach ($tokens as $name => [$token, $message, $reason]) { + yield sprintf('%s, %s', $name, $order) => [$serializers, $token, $message, $reason, true]; + } + yield sprintf('not a token, %s: the exception of the last serializer', $order) => [ + $serializers, + 'This is not a token', + $order === 'compact last' ? 'Unsupported input' : 'Unsupported input.', + $order === 'compact last' ? 'Unsupported input' : 'Syntax error', + false, + ]; + } + } + + /** + * @param list $serializers + */ + private static function chainedReason(array $serializers, string $token): string + { + try { + (new JWESerializerManager($serializers))->unserialize($token); + } catch (InvalidSerializationException $exception) { + $previous = $exception->getPrevious(); + static::assertNotNull($previous); + + return self::reason($previous); + } + static::fail('The token should have been rejected.'); + } + + /** + * The message of the innermost exception of the chain. + */ + private static function reason(Throwable $exception): string + { + while ($exception->getPrevious() !== null) { + $exception = $exception->getPrevious(); + } + + return $exception->getMessage(); + } + + private static function serializerOfAnotherLibrary(Throwable $rejection): JWESerializer + { + return new class($rejection) implements JWESerializer { + public function __construct( + private readonly Throwable $rejection + ) { + } + + public function name(): string + { + return 'another_library'; + } + + public function displayName(): string + { + return 'Another library'; + } + + public function serialize(JWE $jws, ?int $recipientIndex = null): string + { + return ''; + } + + public function unserialize(string $input): JWE + { + throw $this->rejection; + } + }; + } + + private static function badProtectedHeader(): string + { + return Base64UrlSafe::encodeUnpadded('"x"') . '.AAAA.AAAA.AAAA.AAAA'; + } + + private static function flattened(string $protectedHeader): string + { + return sprintf('{"protected":"%s","encrypted_key":"AAAA",%s}', $protectedHeader, self::PARTS); + } + + private static function general(string $protectedHeader): string + { + return sprintf( + '{"protected":"%s","recipients":[{"encrypted_key":"AAAA"}],%s}', + $protectedHeader, + self::PARTS + ); + } + + private static function protectedHeader(): string + { + return Base64UrlSafe::encodeUnpadded('{"alg":"A128KW","enc":"A128GCM"}'); + } +} diff --git a/tests/Component/Signature/JWSSerializerManagerTest.php b/tests/Component/Signature/JWSSerializerManagerTest.php new file mode 100644 index 00000000..2aa2779a --- /dev/null +++ b/tests/Component/Signature/JWSSerializerManagerTest.php @@ -0,0 +1,313 @@ +expectException(UnrecognizedSerializationException::class); + $this->expectExceptionMessage($message); + + $serializer->unserialize($input); + } + + #[DataProvider('invalidTokensOfTheSerialization')] + #[Test] + public function aSerializerRejectsAnInvalidTokenOfItsSerializationWithoutTheMark( + JWSSerializer $serializer, + string $token + ): void { + try { + $serializer->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidArgumentException $exception) { + static::assertNotInstanceOf(UnrecognizedSerializationException::class, $exception); + } + } + + /** + * @param list $serializers + */ + #[DataProvider('tokensForTheManager')] + #[Test] + public function theManagerChainsTheExceptionOfTheSerializerTheTokenBelongsTo( + array $serializers, + string $token, + string $message, + string $reason, + bool $recognized + ): void { + try { + (new JWSSerializerManager($serializers))->unserialize($token); + static::fail('The token should have been rejected.'); + } catch (InvalidSerializationException $exception) { + static::assertSame('Unsupported input.', $exception->getMessage()); + static::assertSame(0, $exception->getCode()); + $previous = $exception->getPrevious(); + static::assertNotNull($previous); + static::assertSame($message, $previous->getMessage()); + static::assertSame($reason, self::reason($previous)); + static::assertSame($recognized, ! $previous instanceof UnrecognizedSerializationException); + } + } + + /** + * A serializer of another library may reject every input: the bound of a token of a serializer of this library + * comes first, and a serializer that marks the inputs it does not recognize is skipped. + */ + #[Test] + public function theSerializersOfAnotherLibraryDoNotHideTheReason(): void + { + $compact = new CompactSerializer(); + $values = '[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES) . '0]'; + $beyondTheBound = Base64UrlSafe::encodeUnpadded( + '{"alg":"HS256","x":' . $values . '}' + ) . '.e30.' . self::signature(); + $unmarked = self::serializerOfAnotherLibrary(new InvalidArgumentException('Not a token of this library.')); + $marked = self::serializerOfAnotherLibrary( + new UnrecognizedSerializationException('Not a token of this library.') + ); + + static::assertSame( + 'The JSON documents of the token hold more JSON values than the 4096 that are decoded.', + self::chainedReason([$compact, $unmarked], $beyondTheBound) + ); + static::assertSame( + 'Bad protected header.', + self::chainedReason([$compact, $marked], self::badProtectedHeader()) + ); + } + + /** + * @return iterable + */ + public static function inputsOfAnotherSerialization(): iterable + { + $compact = new CompactSerializer(); + $flattened = new JSONFlattenedSerializer(); + $general = new JSONGeneralSerializer(); + $compactToken = self::protectedHeader() . '.e30.' . self::signature(); + $flattenedToken = self::flattened(self::protectedHeader()); + $generalToken = self::general(self::protectedHeader()); + + yield 'compact, not a token' => [$compact, 'This is not a token', 'Unsupported input']; + yield 'compact, two parts' => [$compact, 'e30.e30', 'Unsupported input']; + yield 'compact, a flattened token' => [$compact, $flattenedToken, 'Unsupported input']; + yield 'compact, JSON with two dots' => [ + $compact, + sprintf( + '{"payload":"e30","protected":"%s","header":{"kid":"a.b.c"},"signature":"%s"}', + self::protectedHeader(), + self::signature() + ), + 'Unsupported input', + ]; + yield 'flattened, not a token' => [$flattened, 'This is not a token', 'Unsupported input.']; + yield 'flattened, a compact token' => [$flattened, $compactToken, 'Unsupported input.']; + yield 'flattened, a list' => [$flattened, '[1]', 'Unsupported input.']; + yield 'flattened, a general token' => [$flattened, $generalToken, 'Unsupported input.']; + yield 'general, not a token' => [$general, 'This is not a token', 'Unsupported input.']; + yield 'general, a compact token' => [$general, $compactToken, 'Unsupported input.']; + yield 'general, a string' => [$general, '"x"', 'Unsupported input.']; + yield 'general, a flattened token' => [$general, $flattenedToken, 'Unsupported input.']; + } + + /** + * @return iterable + */ + public static function invalidTokensOfTheSerialization(): iterable + { + $invalidJson = Base64UrlSafe::encodeUnpadded('{'); + + yield 'compact, a protected header that is not an object' => [ + new CompactSerializer(), + self::badProtectedHeader(), + ]; + yield 'compact, a protected header that is not JSON' => [ + new CompactSerializer(), + $invalidJson . '.e30.' . self::signature(), + ]; + yield 'compact, a protected header of an impossible length' => [ + new CompactSerializer(), + 'e30AA.e30.' . self::signature(), + ]; + yield 'flattened, a protected header that is not JSON' => [ + new JSONFlattenedSerializer(), + self::flattened($invalidJson), + ]; + yield 'general, a protected header that is not JSON' => [ + new JSONGeneralSerializer(), + self::general($invalidJson), + ]; + yield 'general, a signature without its signature' => [ + new JSONGeneralSerializer(), + sprintf('{"payload":"e30","signatures":[{"protected":"%s"}]}', self::protectedHeader()), + ]; + } + + /** + * @return iterable, string, string, string, bool}> + */ + public static function tokensForTheManager(): iterable + { + $orders = [ + 'compact first' => [new CompactSerializer(), new JSONFlattenedSerializer(), new JSONGeneralSerializer()], + 'compact last' => [new JSONFlattenedSerializer(), new JSONGeneralSerializer(), new CompactSerializer()], + 'general first' => [new JSONGeneralSerializer(), new CompactSerializer(), new JSONFlattenedSerializer()], + ]; + $invalidJson = Base64UrlSafe::encodeUnpadded('{'); + $tokens = [ + 'a compact token whose protected header is not an object' => [ + self::badProtectedHeader(), + 'Unsupported input', + 'Bad protected header.', + ], + 'a compact token whose protected header is not JSON' => [ + $invalidJson . '.e30.' . self::signature(), + 'Unsupported input', + 'Syntax error', + ], + 'a flattened token whose protected header is not JSON' => [ + self::flattened($invalidJson), + 'Unsupported input.', + 'Syntax error', + ], + 'a general token whose protected header is not JSON' => [ + self::general($invalidJson), + 'Unsupported input.', + 'Syntax error', + ], + ]; + foreach ($orders as $order => $serializers) { + foreach ($tokens as $name => [$token, $message, $reason]) { + yield sprintf('%s, %s', $name, $order) => [$serializers, $token, $message, $reason, true]; + } + yield sprintf('not a token, %s: the exception of the last serializer', $order) => [ + $serializers, + 'This is not a token', + $order === 'compact last' ? 'Unsupported input' : 'Unsupported input.', + $order === 'compact last' ? 'Unsupported input' : 'Syntax error', + false, + ]; + } + } + + /** + * @param list $serializers + */ + private static function chainedReason(array $serializers, string $token): string + { + try { + (new JWSSerializerManager($serializers))->unserialize($token); + } catch (InvalidSerializationException $exception) { + $previous = $exception->getPrevious(); + static::assertNotNull($previous); + + return self::reason($previous); + } + static::fail('The token should have been rejected.'); + } + + /** + * The message of the innermost exception of the chain. + */ + private static function reason(Throwable $exception): string + { + while ($exception->getPrevious() !== null) { + $exception = $exception->getPrevious(); + } + + return $exception->getMessage(); + } + + private static function serializerOfAnotherLibrary(Throwable $rejection): JWSSerializer + { + return new class($rejection) implements JWSSerializer { + public function __construct( + private readonly Throwable $rejection + ) { + } + + public function name(): string + { + return 'another_library'; + } + + public function displayName(): string + { + return 'Another library'; + } + + public function serialize(JWS $jws, ?int $signatureIndex = null): string + { + return ''; + } + + public function unserialize(string $input): JWS + { + throw $this->rejection; + } + }; + } + + private static function badProtectedHeader(): string + { + return Base64UrlSafe::encodeUnpadded('"x"') . '.e30.' . self::signature(); + } + + private static function flattened(string $protectedHeader): string + { + return sprintf('{"payload":"e30","protected":"%s","signature":"%s"}', $protectedHeader, self::signature()); + } + + private static function general(string $protectedHeader): string + { + return sprintf( + '{"payload":"e30","signatures":[{"protected":"%s","signature":"%s"}]}', + $protectedHeader, + self::signature() + ); + } + + private static function protectedHeader(): string + { + return Base64UrlSafe::encodeUnpadded('{"alg":"HS256"}'); + } + + private static function signature(): string + { + return Base64UrlSafe::encodeUnpadded(str_repeat("\x01", 32)); + } +} From 645d0cc8c7d69b3c6f6d4b525e8ecbf305b8bb81 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 11:12:58 +0100 Subject: [PATCH 12/32] fix(json): bound the JSON documents decoded outside of a token JsonConverter::decode() counted no value: a document of a few megabytes full of colliding member names costs seconds of CPU, as for the tokens before GHSA-2xq2. It decodes the key sets that JKUFactory and X5UFactory fetch from a URL, without any limit on their size. Its message was "Unsupported input." whatever the error. JWK::createFromJson(), JWKSet::createFromJson() and JWKFactory::fromJsonObject() called json_decode() directly, without bound either, and their JsonException recorded the JSON of the key among the arguments of its trace. These four methods now read a second argument, with func_get_arg(1) until 5.0.0 declares it: true decodes a document of any number of values, false refuses one of more than 4096 with a JsonBoundExceededException, and without it, or with null, such a document is decoded with a deprecation, as 5.0.0 refuses it by default. JKUFactory and X5UFactory read the same policy as a third constructor argument, and the bundle gets a "jose.jku_factory.allow_large_key_sets" option. JsonConverter::decode() names the error of json_decode(), and refuses a document nested too deeply with a JsonBoundExceededException; the codes and the chained JsonException are kept. The three key factories keep their JsonException, thrown again as a copy without the key in its trace. The tokens keep "Unsupported input.". The console commands and the environment variable processor decode the operator's own documents without bound. The SD-JWT Verifier bounds the payload of the Key Binding JWT, signed by the Holder; that of the Issuer-signed JWT, signed by the Issuer and holding a digest for each Disclosure, is decoded without bound. --- .ci-tools/phpstan-baseline.neon | 12 +- .../Source/KeyManagement/JKUSource.php | 16 +- .../EnvVarProcessor/KeyEnvVarProcessor.php | 4 +- .../Console/AddKeyIntoKeysetCommand.php | 4 +- src/Library/Console/GetThumbprintCommand.php | 2 +- src/Library/Console/KeyAnalyzerCommand.php | 2 +- src/Library/Console/KeysetAnalyzerCommand.php | 2 +- src/Library/Console/MergeKeysetCommand.php | 2 +- src/Library/Console/OptimizeRsaKeyCommand.php | 2 +- src/Library/Console/PemConverterCommand.php | 2 +- src/Library/Console/Pkcs8ConverterCommand.php | 2 +- src/Library/Console/PublicKeyCommand.php | 2 +- src/Library/Console/PublicKeysetCommand.php | 2 +- src/Library/Console/RotateKeysetCommand.php | 4 +- src/Library/Core/JWK.php | 22 +- src/Library/Core/JWKSet.php | 22 +- src/Library/Core/Util/BoundedJsonDecoder.php | 56 +++- src/Library/Core/Util/JsonConverter.php | 30 +- src/Library/KeyManagement/JKUFactory.php | 3 +- src/Library/KeyManagement/JWKFactory.php | 25 +- .../KeyManagement/UrlKeySetFactory.php | 1 + .../KeyManagement/UrlKeySetFactoryTrait.php | 37 ++ src/Library/KeyManagement/X5UFactory.php | 3 +- src/SelectiveDisclosure/SDJWT.php | 8 +- src/SelectiveDisclosure/SDJWTIssuer.php | 2 +- src/SelectiveDisclosure/SDJWTVerifier.php | 15 +- .../JKUFactoryLargeKeySetsTest.php | 213 ++++++++++++ .../Component/Console/LargeJsonInputTest.php | 107 ++++++ tests/Component/Core/JsonConverterTest.php | 140 ++++++++ tests/Component/Core/KeyJsonDocumentTest.php | 214 ++++++++++++ .../KeyManagement/LargeJsonDocumentTest.php | 315 ++++++++++++++++++ .../KeyManagement/UrlKeySetFactoryTest.php | 4 +- .../JsonValueBoundTest.php | 51 +++ .../SelectiveDisclosure/SDJWTVerifierTest.php | 25 ++ 34 files changed, 1305 insertions(+), 46 deletions(-) create mode 100644 tests/Bundle/JoseFramework/Functional/KeyManagement/JKUFactoryLargeKeySetsTest.php create mode 100644 tests/Component/Console/LargeJsonInputTest.php create mode 100644 tests/Component/Core/KeyJsonDocumentTest.php create mode 100644 tests/Component/KeyManagement/LargeJsonDocumentTest.php diff --git a/.ci-tools/phpstan-baseline.neon b/.ci-tools/phpstan-baseline.neon index fb0eb107..702c6ce8 100644 --- a/.ci-tools/phpstan-baseline.neon +++ b/.ci-tools/phpstan-baseline.neon @@ -1434,6 +1434,12 @@ parameters: count: 1 path: ../src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php + - + rawMessage: Cannot access offset 'allow_large_key_sets' on mixed. + identifier: offsetAccess.nonOffsetAccessible + count: 1 + path: ../src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php + - rawMessage: Cannot access offset 'client' on mixed. identifier: offsetAccess.nonOffsetAccessible @@ -1461,7 +1467,7 @@ parameters: - rawMessage: 'Cannot call method booleanNode() on mixed.' identifier: method.nonObject - count: 1 + count: 2 path: ../src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php - @@ -1479,13 +1485,13 @@ parameters: - rawMessage: 'Cannot call method end() on mixed.' identifier: method.nonObject - count: 5 + count: 6 path: ../src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php - rawMessage: 'Cannot call method info() on mixed.' identifier: method.nonObject - count: 2 + count: 3 path: ../src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php - diff --git a/src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php b/src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php index ba20627d..186ae94f 100644 --- a/src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php +++ b/src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php @@ -29,10 +29,15 @@ public function load(array $configs, ContainerBuilder $container): void $loader->load('jku_source.php'); $loader->load('jku_commands.php'); $container->setAlias('jose.http_client', $configs[$this->name()]['client']); - if (isset($configs[$this->name()]['follow_redirects'])) { + $followRedirects = $configs[$this->name()]['follow_redirects'] ?? null; + $allowLargeKeySets = $configs[$this->name()]['allow_large_key_sets'] ?? null; + if ($followRedirects !== null || $allowLargeKeySets !== null) { foreach ([JKUFactory::class, X5UFactory::class] as $factory) { - $container->getDefinition($factory) - ->addArgument($configs[$this->name()]['follow_redirects']); + $definition = $container->getDefinition($factory) + ->addArgument($followRedirects); + if ($allowLargeKeySets !== null) { + $definition->addArgument($allowLargeKeySets); + } } } } @@ -49,6 +54,11 @@ public function getNodeDefinition(NodeDefinition $node): void ->info('HTTP Client used to retrieve key sets.') ->isRequired() ->end() + ->booleanNode('allow_large_key_sets') + ->info( + 'True loads the key sets of more than 4096 JSON values, false refuses them. When it is not set, they are loaded with a deprecation, as 5.0.0 refuses them by default.' + ) + ->end() ->booleanNode('follow_redirects') ->info( 'False refuses the redirects of the key set URLs, true follows them. When it is not set, they are followed with a deprecation, as 5.0.0 refuses them by default.' diff --git a/src/Bundle/EnvVarProcessor/KeyEnvVarProcessor.php b/src/Bundle/EnvVarProcessor/KeyEnvVarProcessor.php index 779f906c..068f41d2 100644 --- a/src/Bundle/EnvVarProcessor/KeyEnvVarProcessor.php +++ b/src/Bundle/EnvVarProcessor/KeyEnvVarProcessor.php @@ -20,8 +20,8 @@ public function getEnv(string $prefix, string $name, Closure $getEnv): mixed $env = $getEnv($name); return match ($prefix) { - 'jwk' => JWK::createFromJson($env), - 'jwkset' => JWKSet::createFromJson($env), + 'jwk' => JWK::createFromJson($env, true), + 'jwkset' => JWKSet::createFromJson($env, true), default => throw new RuntimeException(sprintf('Unsupported prefix "%s".', $prefix)), }; } diff --git a/src/Library/Console/AddKeyIntoKeysetCommand.php b/src/Library/Console/AddKeyIntoKeysetCommand.php index 9ee99526..fb524036 100644 --- a/src/Library/Console/AddKeyIntoKeysetCommand.php +++ b/src/Library/Console/AddKeyIntoKeysetCommand.php @@ -47,7 +47,7 @@ private function getKeyset(InputInterface $input): JWKSet if (! is_string($jwkset)) { throw new InvalidKeySetException('The argument must be a valid JWKSet.'); } - $json = JsonConverter::decode($jwkset); + $json = JsonConverter::decode($jwkset, true); if (! is_array($json)) { throw new InvalidKeySetException('The argument must be a valid JWKSet.'); } @@ -61,7 +61,7 @@ private function getKey(InputInterface $input): JWK if (! is_string($jwk)) { throw new InvalidKeyException('The argument must be a valid JWK.'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidKeyException('The argument must be a valid JWK.'); } diff --git a/src/Library/Console/GetThumbprintCommand.php b/src/Library/Console/GetThumbprintCommand.php index 2be3f3c7..b6bd327d 100644 --- a/src/Library/Console/GetThumbprintCommand.php +++ b/src/Library/Console/GetThumbprintCommand.php @@ -54,7 +54,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (! is_string($hash)) { throw new InvalidArgumentException('Invalid hash algorithm'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidArgumentException('Invalid input.'); } diff --git a/src/Library/Console/KeyAnalyzerCommand.php b/src/Library/Console/KeyAnalyzerCommand.php index 0b3a00ce..1e8b33ee 100644 --- a/src/Library/Console/KeyAnalyzerCommand.php +++ b/src/Library/Console/KeyAnalyzerCommand.php @@ -70,7 +70,7 @@ private function getKey(InputInterface $input): JWK if (! is_string($jwk)) { throw new InvalidKeyException('Invalid JWK'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidKeyException('Invalid JWK.'); } diff --git a/src/Library/Console/KeysetAnalyzerCommand.php b/src/Library/Console/KeysetAnalyzerCommand.php index 8a4e583f..b2df7558 100644 --- a/src/Library/Console/KeysetAnalyzerCommand.php +++ b/src/Library/Console/KeysetAnalyzerCommand.php @@ -85,7 +85,7 @@ private function getKeyset(InputInterface $input): JWKSet if (! is_string($jwkset)) { throw new InvalidKeySetException('Invalid JWKSet'); } - $json = JsonConverter::decode($jwkset); + $json = JsonConverter::decode($jwkset, true); if (! is_array($json)) { throw new InvalidKeySetException('Invalid JWKSet'); } diff --git a/src/Library/Console/MergeKeysetCommand.php b/src/Library/Console/MergeKeysetCommand.php index 85d55be1..bbdeeb3c 100644 --- a/src/Library/Console/MergeKeysetCommand.php +++ b/src/Library/Console/MergeKeysetCommand.php @@ -35,7 +35,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $keySets = $input->getArgument('jwksets'); $newJwkset = new JWKSet([]); foreach ($keySets as $keySet) { - $json = JsonConverter::decode($keySet); + $json = JsonConverter::decode($keySet, true); if (! is_array($json)) { throw new InvalidKeySetException('The argument must be a valid JWKSet.'); } diff --git a/src/Library/Console/OptimizeRsaKeyCommand.php b/src/Library/Console/OptimizeRsaKeyCommand.php index 4cd35aee..ce3ce0a9 100644 --- a/src/Library/Console/OptimizeRsaKeyCommand.php +++ b/src/Library/Console/OptimizeRsaKeyCommand.php @@ -33,7 +33,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (! is_string($jwk)) { throw new InvalidKeyException('Invalid JWK'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidKeyException('Invalid JWK'); } diff --git a/src/Library/Console/PemConverterCommand.php b/src/Library/Console/PemConverterCommand.php index 0d0a7759..615df878 100644 --- a/src/Library/Console/PemConverterCommand.php +++ b/src/Library/Console/PemConverterCommand.php @@ -34,7 +34,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (! is_string($jwk)) { throw new InvalidKeyException('Invalid JWK'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidKeyException('Invalid JWK.'); } diff --git a/src/Library/Console/Pkcs8ConverterCommand.php b/src/Library/Console/Pkcs8ConverterCommand.php index 4a1b9231..75406c3f 100644 --- a/src/Library/Console/Pkcs8ConverterCommand.php +++ b/src/Library/Console/Pkcs8ConverterCommand.php @@ -39,7 +39,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (! is_string($jwk)) { throw new InvalidKeyException('Invalid JWK'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidKeyException('Invalid JWK.'); } diff --git a/src/Library/Console/PublicKeyCommand.php b/src/Library/Console/PublicKeyCommand.php index 1ca1b4f5..7e8a516e 100644 --- a/src/Library/Console/PublicKeyCommand.php +++ b/src/Library/Console/PublicKeyCommand.php @@ -47,7 +47,7 @@ private function getKey(InputInterface $input): JWK if (! is_string($jwk)) { throw new InvalidKeyException('Invalid JWK'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidKeyException('Invalid JWK'); } diff --git a/src/Library/Console/PublicKeysetCommand.php b/src/Library/Console/PublicKeysetCommand.php index 54e466ef..a85c6fdf 100644 --- a/src/Library/Console/PublicKeysetCommand.php +++ b/src/Library/Console/PublicKeysetCommand.php @@ -50,7 +50,7 @@ private function getKeyset(InputInterface $input): JWKSet if (! is_string($jwkset)) { throw new InvalidKeySetException('Invalid JWKSet'); } - $json = JsonConverter::decode($jwkset); + $json = JsonConverter::decode($jwkset, true); if (! is_array($json)) { throw new InvalidKeySetException('Invalid JWKSet'); } diff --git a/src/Library/Console/RotateKeysetCommand.php b/src/Library/Console/RotateKeysetCommand.php index 54a3544d..70c6603a 100644 --- a/src/Library/Console/RotateKeysetCommand.php +++ b/src/Library/Console/RotateKeysetCommand.php @@ -54,7 +54,7 @@ private function getKeyset(InputInterface $input): JWKSet if (! is_string($jwkset)) { throw new InvalidKeySetException('Invalid JWKSet'); } - $json = JsonConverter::decode($jwkset); + $json = JsonConverter::decode($jwkset, true); if (! is_array($json)) { throw new InvalidKeySetException('Invalid JWKSet'); } @@ -68,7 +68,7 @@ private function getKey(InputInterface $input): JWK if (! is_string($jwk)) { throw new InvalidKeyException('Invalid JWK'); } - $json = JsonConverter::decode($jwk); + $json = JsonConverter::decode($jwk, true); if (! is_array($json)) { throw new InvalidKeyException('Invalid JWK'); } diff --git a/src/Library/Core/JWK.php b/src/Library/Core/JWK.php index 8ede819b..f1842043 100644 --- a/src/Library/Core/JWK.php +++ b/src/Library/Core/JWK.php @@ -8,10 +8,15 @@ use Jose\Component\Core\Exception\InvalidKeyException; use Jose\Component\Core\Exception\UnsupportedAlgorithmException; use Jose\Component\Core\Util\Base64UrlSafe; +use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\InheritanceChecker; +use JsonException; use JsonSerializable; use Override; +use SensitiveParameter; use function array_key_exists; +use function func_get_arg; +use function func_num_args; use function in_array; use function is_array; use function is_string; @@ -51,10 +56,23 @@ public function __construct(array $values) /** * Creates a JWK object using the given Json string. + * + * A second argument, read with func_get_arg(1) until it is part of the signature in 5.0.0, bounds the values of + * the document: true decodes a document of any number of values, false refuses a document of more than + * BoundedJsonDecoder::MAX_VALUES values, and without it, or with null, such a document is decoded with a + * deprecation, as 5.0.0 refuses it by default. The JsonException of json_decode() is thrown again as a copy: + * the arguments recorded in its trace include the document, and the key with it. + * + * @throws JsonException if the document is not valid JSON */ - public static function createFromJson(string $json): self + public static function createFromJson(#[SensitiveParameter] string $json): self { - $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + BoundedJsonDecoder::checkDocument($json, func_num_args() > 1 ? func_get_arg(1) : null, __METHOD__); + try { + $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException $exception) { + throw new JsonException($exception->getMessage(), $exception->getCode()); + } if (! is_array($data)) { throw new InvalidArgumentException('Invalid argument.'); } diff --git a/src/Library/Core/JWKSet.php b/src/Library/Core/JWKSet.php index de2c24d5..0e5e381a 100644 --- a/src/Library/Core/JWKSet.php +++ b/src/Library/Core/JWKSet.php @@ -10,11 +10,16 @@ use Jose\Component\Core\Exception\InvalidArgumentException; use Jose\Component\Core\Exception\InvalidKeyException; use Jose\Component\Core\Exception\InvalidKeySetException; +use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\InheritanceChecker; +use JsonException; use JsonSerializable; +use SensitiveParameter; use Traversable; use function array_key_exists; use function count; +use function func_get_arg; +use function func_num_args; use function in_array; use function is_array; use function is_int; @@ -73,10 +78,23 @@ public static function createFromKeyData(array $data): self /** * Creates a JWKSet object using the given Json string. + * + * A second argument, read with func_get_arg(1) until it is part of the signature in 5.0.0, bounds the values of + * the document: true decodes a document of any number of values, false refuses a document of more than + * BoundedJsonDecoder::MAX_VALUES values, and without it, or with null, such a document is decoded with a + * deprecation, as 5.0.0 refuses it by default. The JsonException of json_decode() is thrown again as a copy: + * the arguments recorded in its trace include the document, and the key with it. + * + * @throws JsonException if the document is not valid JSON */ - public static function createFromJson(string $json): self + public static function createFromJson(#[SensitiveParameter] string $json): self { - $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + BoundedJsonDecoder::checkDocument($json, func_num_args() > 1 ? func_get_arg(1) : null, __METHOD__); + try { + $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException $exception) { + throw new JsonException($exception->getMessage(), $exception->getCode()); + } if (! is_array($data)) { throw new InvalidKeySetException('Invalid argument.'); } diff --git a/src/Library/Core/Util/BoundedJsonDecoder.php b/src/Library/Core/Util/BoundedJsonDecoder.php index 6142d391..769337b8 100644 --- a/src/Library/Core/Util/BoundedJsonDecoder.php +++ b/src/Library/Core/Util/BoundedJsonDecoder.php @@ -8,10 +8,12 @@ use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Exception\UnrecognizedSerializationException; use SensitiveParameter; +use function is_bool; use function preg_replace; use function sprintf; use function str_replace; use function substr_count; +use function trigger_deprecation; use const JSON_ERROR_DEPTH; /** @@ -48,10 +50,14 @@ public function decode(#[SensitiveParameter] string $json): mixed )); } try { - return JsonConverter::decode($json); + return JsonConverter::decode($json, true); } catch (InvalidArgumentException $exception) { if ($exception->getCode() !== JSON_ERROR_DEPTH) { - throw $exception; + throw new InvalidArgumentException( + 'Unsupported input.', + $exception->getCode(), + $exception->getPrevious() + ); } $this->exceededMaxDepth = true; throw new JsonBoundExceededException( @@ -102,6 +108,52 @@ public function hasExceededMaxValues(): bool return $this->remainingValues < 0; } + /** + * Applies the second argument of a public method that decodes a JSON document on its own, read with + * func_get_arg(1) until it is part of the signature in 5.0.0: true decodes a document of any number of values, + * false refuses a document of more than MAX_VALUES values, and null, or no argument, decodes such a document with + * a deprecation, as 5.0.0 refuses it by default. + * + * @param string $method the method that decodes the document, such as "Jose\Component\Core\JWK::createFromJson" + * + * @throws InvalidArgumentException if the argument is neither a boolean nor null + * @throws JsonBoundExceededException if the argument is false and the document holds more than MAX_VALUES values + */ + public static function checkDocument(#[SensitiveParameter] string $json, mixed $unbounded, string $method): void + { + if ($unbounded !== null && ! is_bool($unbounded)) { + throw new InvalidArgumentException(sprintf( + 'The second argument of "%s()" must be a boolean: true decodes a document of any number of values, false refuses one of more than %d.', + $method, + self::MAX_VALUES + )); + } + if ($unbounded === true || ! self::exceedsMaxValues($json)) { + return; + } + if ($unbounded === false) { + throw new JsonBoundExceededException(sprintf( + 'The JSON document holds more JSON values than the %d that are decoded.', + self::MAX_VALUES + )); + } + trigger_deprecation( + 'web-token/jwt-framework', + '4.3.0', + 'Decoding a JSON document of more than %d values is deprecated and "%s()" will refuse it by default in 5.0.0. Pass true as the second argument to keep decoding it, or false to refuse it now.', + self::MAX_VALUES, + $method + ); + } + + /** + * Whether a JSON document holds more than MAX_VALUES values, counted as decode() counts them. + */ + public static function exceedsMaxValues(#[SensitiveParameter] string $json): bool + { + return self::countValues($json) > self::MAX_VALUES; + } + /** * Counts the brackets, braces and commas found outside the string literals. */ diff --git a/src/Library/Core/Util/JsonConverter.php b/src/Library/Core/Util/JsonConverter.php index 0c3bd9f2..f084132d 100644 --- a/src/Library/Core/Util/JsonConverter.php +++ b/src/Library/Core/Util/JsonConverter.php @@ -5,9 +5,14 @@ namespace Jose\Component\Core\Util; use Jose\Component\Core\Exception\InvalidArgumentException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use JsonException; use SensitiveParameter; use Throwable; +use function func_get_arg; +use function func_num_args; +use function sprintf; +use const JSON_ERROR_DEPTH; use const JSON_THROW_ON_ERROR; use const JSON_UNESCAPED_SLASHES; use const JSON_UNESCAPED_UNICODE; @@ -24,17 +29,36 @@ public static function encode(mixed $payload): string } /** - * The exception of json_decode() is chained as a copy: the arguments recorded in its trace include the document. + * Decodes a JSON document. A second argument, read with func_get_arg(1) until it is part of the signature in 5.0.0, + * bounds its values: true decodes a document of any number of values, false refuses a document of more than + * BoundedJsonDecoder::MAX_VALUES values, and without it, or with null, such a document is decoded with a + * deprecation, as 5.0.0 refuses it by default. + * + * The message of an exception names the error of json_decode(), whose exception is chained as a copy: the + * arguments recorded in its trace include the document. The code is that of the JSON error. + * + * @throws JsonBoundExceededException if the document is nested too deeply, or if it holds too many values and the + * second argument is false + * @throws InvalidArgumentException if the document is not valid JSON, or if the second argument is not a boolean */ public static function decode(#[SensitiveParameter] string $payload): mixed { + BoundedJsonDecoder::checkDocument($payload, func_num_args() > 1 ? func_get_arg(1) : null, __METHOD__); try { return json_decode($payload, true, 512, JSON_THROW_ON_ERROR); } catch (Throwable $throwable) { + $previous = new JsonException($throwable->getMessage(), $throwable->getCode()); + if ($throwable->getCode() === JSON_ERROR_DEPTH) { + throw new JsonBoundExceededException( + 'The JSON document is nested too deeply.', + $throwable->getCode(), + $previous + ); + } throw new InvalidArgumentException( - 'Unsupported input.', + sprintf('The JSON document is not valid: %s.', $throwable->getMessage()), $throwable->getCode(), - new JsonException($throwable->getMessage(), $throwable->getCode()) + $previous ); } } diff --git a/src/Library/KeyManagement/JKUFactory.php b/src/Library/KeyManagement/JKUFactory.php index c21a7755..a7c15685 100644 --- a/src/Library/KeyManagement/JKUFactory.php +++ b/src/Library/KeyManagement/JKUFactory.php @@ -6,7 +6,6 @@ use Jose\Component\Core\Exception\RuntimeException; use Jose\Component\Core\JWKSet; -use Jose\Component\Core\Util\JsonConverter; use function is_array; /** @@ -24,7 +23,7 @@ class JKUFactory public function loadFromUrl(string $url, array $header = []): JWKSet { $content = $this->getContent($url, $header); - $data = JsonConverter::decode($content); + $data = $this->decodeKeySet($content); if (! is_array($data)) { throw new RuntimeException('Invalid content.'); } diff --git a/src/Library/KeyManagement/JWKFactory.php b/src/Library/KeyManagement/JWKFactory.php index aeef7c2d..77743836 100644 --- a/src/Library/KeyManagement/JWKFactory.php +++ b/src/Library/KeyManagement/JWKFactory.php @@ -11,16 +11,23 @@ use Jose\Component\Core\JWKSet; use Jose\Component\Core\Util\AKPKey; use Jose\Component\Core\Util\Base64UrlSafe; +use Jose\Component\Core\Util\BoundedJsonDecoder; use Jose\Component\Core\Util\ECKey; use Jose\Component\Core\Util\InheritanceChecker; use Jose\Component\Core\Util\OKPKey; use Jose\Component\KeyManagement\KeyConverter\KeyConverter; use Jose\Component\KeyManagement\KeyConverter\RSAKey; +use JsonException; use OpenSSLCertificate; use Override; +use SensitiveParameter; use Throwable; use function array_key_exists; +use function array_slice; use function extension_loaded; +use function func_get_arg; +use function func_get_args; +use function func_num_args; use function is_array; use function is_string; use function trigger_deprecation; @@ -132,7 +139,7 @@ public static function createFromJsonObject(string $value): JWK|JWKSet { self::deprecateStaticCall('createFromJsonObject', 'fromJsonObject'); - return (new self())->fromJsonObject($value); + return (new self())->fromJsonObject($value, ...array_slice(func_get_args(), 1)); } /** @@ -381,10 +388,22 @@ public function none(array $values = []): JWK return new JWK($values); } + /** + * A second argument, read with func_get_arg(1) until it is part of the signature in 5.0.0, bounds the values of + * the document: true decodes a document of any number of values, false refuses a document of more than + * BoundedJsonDecoder::MAX_VALUES values, and without it, or with null, such a document is decoded with a + * deprecation, as 5.0.0 refuses it by default. The JsonException of json_decode() is thrown again as a copy: + * the arguments recorded in its trace include the document, and the key with it. + */ #[Override] - public function fromJsonObject(string $value): JWK|JWKSet + public function fromJsonObject(#[SensitiveParameter] string $value): JWK|JWKSet { - $json = json_decode($value, true, 512, JSON_THROW_ON_ERROR); + BoundedJsonDecoder::checkDocument($value, func_num_args() > 1 ? func_get_arg(1) : null, __METHOD__); + try { + $json = json_decode($value, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException $exception) { + throw new JsonException($exception->getMessage(), $exception->getCode()); + } if (! is_array($json)) { throw new InvalidKeyException('Invalid key or key set.'); } diff --git a/src/Library/KeyManagement/UrlKeySetFactory.php b/src/Library/KeyManagement/UrlKeySetFactory.php index 5ddcc921..b08b6556 100644 --- a/src/Library/KeyManagement/UrlKeySetFactory.php +++ b/src/Library/KeyManagement/UrlKeySetFactory.php @@ -41,5 +41,6 @@ public function __construct(HttpClientInterface $client) $this->client = $client; $this->followRedirects = true; + $this->allowLargeKeySets = null; } } diff --git a/src/Library/KeyManagement/UrlKeySetFactoryTrait.php b/src/Library/KeyManagement/UrlKeySetFactoryTrait.php index 65c542e3..47fbfd58 100644 --- a/src/Library/KeyManagement/UrlKeySetFactoryTrait.php +++ b/src/Library/KeyManagement/UrlKeySetFactoryTrait.php @@ -5,7 +5,10 @@ namespace Jose\Component\KeyManagement; use Jose\Component\Core\Exception\InvalidArgumentException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Exception\RuntimeException; +use Jose\Component\Core\Util\BoundedJsonDecoder; +use Jose\Component\Core\Util\JsonConverter; use Psr\Cache\CacheItemPoolInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; use Throwable; @@ -43,11 +46,17 @@ trait UrlKeySetFactoryTrait private readonly ?bool $followRedirects; + private readonly ?bool $allowLargeKeySets; + /** * A second argument sets how the redirects of the key set URL are handled: true follows them as the HTTP client * does, false refuses them and the redirected request is never sent. Without it, or with null, they are followed, * but a key set fetched through a redirect triggers a deprecation, as 5.0.0 refuses redirects by default. That * argument is not part of the signature until 5.0.0 and is read with func_num_args()/func_get_arg(1). + * + * A third argument sets how a key set of more than BoundedJsonDecoder::MAX_VALUES JSON values is handled: true + * loads it, false refuses it. Without it, or with null, it is loaded with a deprecation, as 5.0.0 refuses it by + * default. That argument is read with func_get_arg(2) until 5.0.0. */ public function __construct(HttpClientInterface $client) { @@ -59,6 +68,13 @@ public function __construct(HttpClientInterface $client) ); } $this->followRedirects = $followRedirects; + $allowLargeKeySets = func_num_args() > 2 ? func_get_arg(2) : null; + if ($allowLargeKeySets !== null && ! is_bool($allowLargeKeySets)) { + throw new InvalidArgumentException( + 'The policy for large key sets must be a boolean: true loads them, false refuses them.' + ); + } + $this->allowLargeKeySets = $allowLargeKeySets; } /** @@ -152,4 +168,25 @@ private function sendRequest(string $url, array $header): string return $response->getContent(); } + + /** + * Decodes the key set fetched from a URL, as the third argument of the constructor says: a key set of more than + * BoundedJsonDecoder::MAX_VALUES JSON values is loaded, refused, or loaded with a deprecation. + * + * @throws JsonBoundExceededException if the key set holds too many JSON values and large key sets are refused + */ + private function decodeKeySet(string $content): mixed + { + if ($this->allowLargeKeySets === null && BoundedJsonDecoder::exceedsMaxValues($content)) { + trigger_deprecation( + 'web-token/jwt-framework', + '4.3.0', + 'Loading a key set of more than %d JSON values is deprecated and "%s" will refuse it by default in 5.0.0. Pass true as the third argument of the constructor to keep loading it, or false to refuse it now. With the bundle, set the "jose.jku_factory.allow_large_key_sets" option.', + BoundedJsonDecoder::MAX_VALUES, + static::class + ); + } + + return JsonConverter::decode($content, $this->allowLargeKeySets !== false); + } } diff --git a/src/Library/KeyManagement/X5UFactory.php b/src/Library/KeyManagement/X5UFactory.php index 0fc73b02..41fc1109 100644 --- a/src/Library/KeyManagement/X5UFactory.php +++ b/src/Library/KeyManagement/X5UFactory.php @@ -7,7 +7,6 @@ use Jose\Component\Core\Exception\RuntimeException; use Jose\Component\Core\JWK; use Jose\Component\Core\JWKSet; -use Jose\Component\Core\Util\JsonConverter; use Jose\Component\KeyManagement\KeyConverter\KeyConverter; use function assert; use function is_array; @@ -29,7 +28,7 @@ class X5UFactory public function loadFromUrl(string $url, array $header = []): JWKSet { $content = $this->getContent($url, $header); - $data = JsonConverter::decode($content); + $data = $this->decodeKeySet($content); if (! is_array($data)) { throw new RuntimeException('Invalid content.'); } diff --git a/src/SelectiveDisclosure/SDJWT.php b/src/SelectiveDisclosure/SDJWT.php index a98007b9..a44b5b38 100644 --- a/src/SelectiveDisclosure/SDJWT.php +++ b/src/SelectiveDisclosure/SDJWT.php @@ -578,14 +578,18 @@ private function json(array $parameters): string } /** - * Decodes the payload of the Issuer-signed JWT, without verifying its signature. + * Decodes the payload of the Issuer-signed JWT, without verifying its signature. The Issuer signs it, and it holds + * a digest for each Disclosure: it is not bounded as the JSON documents of a token are. * * @return array */ private function payload(): array { try { - $payload = JsonConverter::decode(Base64UrlSafe::decodeNoPadding(explode('.', $this->issuerSignedJwt)[1])); + $payload = JsonConverter::decode( + Base64UrlSafe::decodeNoPadding(explode('.', $this->issuerSignedJwt)[1]), + true + ); } catch (Throwable $throwable) { throw new InvalidTokenException('The payload of the Issuer-signed JWT cannot be decoded.', 0, $throwable); } diff --git a/src/SelectiveDisclosure/SDJWTIssuer.php b/src/SelectiveDisclosure/SDJWTIssuer.php index 0dac093c..1029690e 100644 --- a/src/SelectiveDisclosure/SDJWTIssuer.php +++ b/src/SelectiveDisclosure/SDJWTIssuer.php @@ -311,7 +311,7 @@ private function conceal(mixed $value, array &$disclosures): mixed throw new InvalidArgumentException('A Disclosable cannot be the value of another Disclosable.'); } if (is_object($value) && ($value instanceof JsonSerializable || ! $value instanceof UnitEnum)) { - self::checkClaimNames(JsonConverter::decode(JsonConverter::encode($value))); + self::checkClaimNames(JsonConverter::decode(JsonConverter::encode($value), true)); } if (! is_array($value)) { return $value; diff --git a/src/SelectiveDisclosure/SDJWTVerifier.php b/src/SelectiveDisclosure/SDJWTVerifier.php index 1754b95a..cd8a5088 100644 --- a/src/SelectiveDisclosure/SDJWTVerifier.php +++ b/src/SelectiveDisclosure/SDJWTVerifier.php @@ -12,6 +12,7 @@ use Jose\Component\Checker\TypeChecker; use Jose\Component\Core\Exception\InvalidArgumentException; use Jose\Component\Core\Exception\InvalidTokenException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Exception\LogicException; use Jose\Component\Core\Exception\UnsupportedAlgorithmException; use Jose\Component\Core\JWK; @@ -168,7 +169,7 @@ private function process(SDJWT $sdJwt, JWK|JWKSet $issuerKeys): array throw new InvalidTokenException('The Issuer-signed JWT cannot be verified.', 0, $throwable); } self::checkSignatureAlgorithm($this->issuerSignedJwtLoader, $loaded, 'Issuer-signed JWT'); - $payload = self::payload($loaded->getJws(), 'Issuer-signed JWT'); + $payload = self::payload($loaded->getJws(), 'Issuer-signed JWT', true); $hashAlgorithm = DisclosureProcessor::declaredHashAlgorithm($payload); if (! in_array($hashAlgorithm, $this->hashAlgorithms, true)) { throw new InvalidTokenException(sprintf( @@ -199,7 +200,7 @@ private function checkKeyBindingJwt(JWS $keyBindingJwt, SDJWT $sdJwt, string $au } catch (InvalidHeaderException $exception) { throw new InvalidTokenException('The Key Binding JWT must be of type "kb+jwt".', 0, $exception); } - $claims = self::payload($keyBindingJwt, 'Key Binding JWT'); + $claims = self::payload($keyBindingJwt, 'Key Binding JWT', false); $issuedAt = $claims['iat'] ?? null; if (! is_int($issuedAt) && ! is_float($issuedAt)) { throw new InvalidTokenException('The "iat" claim of the Key Binding JWT must be a number.'); @@ -279,13 +280,19 @@ private static function holderKey(array $claims): JWK } /** + * The payload of the Issuer-signed JWT is signed by the Issuer and holds a digest for each Disclosure: it is not + * bounded. That of the Key Binding JWT, signed by the Holder, holds a few claims: it is decoded with the bound of + * the JSON documents of a token. + * * @return array */ - private static function payload(JWS $jws, string $token): array + private static function payload(JWS $jws, string $token, bool $unbounded): array { $message = sprintf('The payload of the %s must be a JSON object.', $token); try { - $payload = JsonConverter::decode((string) $jws->getPayload()); + $payload = JsonConverter::decode((string) $jws->getPayload(), $unbounded); + } catch (JsonBoundExceededException $exception) { + throw new InvalidTokenException(sprintf('The payload of the %s cannot be decoded.', $token), 0, $exception); } catch (Throwable $throwable) { throw new InvalidTokenException($message, 0, $throwable); } diff --git a/tests/Bundle/JoseFramework/Functional/KeyManagement/JKUFactoryLargeKeySetsTest.php b/tests/Bundle/JoseFramework/Functional/KeyManagement/JKUFactoryLargeKeySetsTest.php new file mode 100644 index 00000000..338ac537 --- /dev/null +++ b/tests/Bundle/JoseFramework/Functional/KeyManagement/JKUFactoryLargeKeySetsTest.php @@ -0,0 +1,213 @@ +kernel !== null) { + $this->kernel->shutdown(); + (new Filesystem())->remove($this->kernel->getVarDir()); + $this->kernel = null; + } + + parent::tearDown(); + } + + /** + * @param class-string $factory + */ + #[Test] + #[DataProvider('factories')] + public function theFactoriesRefuseLargeKeySetsWhenTheOptionIsFalse(string $factory): void + { + $service = $this->getFactory($factory, self::largeDocument($factory), [ + 'allow_large_key_sets' => false, + ]); + + $this->expectException(JsonBoundExceededException::class); + + $service->loadFromUrl(self::URL); + } + + #[Test] + public function theFactoriesLoadLargeKeySetsSilentlyWhenTheOptionIsTrue(): void + { + $service = $this->getFactory(JKUFactory::class, self::largeDocument(JKUFactory::class), [ + 'allow_large_key_sets' => true, + ]); + + $keySet = null; + $deprecations = $this->collectDeprecations(static function () use ($service, &$keySet): void { + $keySet = $service->loadFromUrl(self::URL); + }); + + static::assertSame([], $deprecations); + static::assertInstanceOf(JWKSet::class, $keySet); + } + + /** + * @param class-string $factory + */ + #[Test] + #[DataProvider('factories')] + public function theFactoriesLoadLargeKeySetsWithADeprecationWhenTheOptionIsNotSet(string $factory): void + { + $service = $this->getFactory($factory, self::largeDocument($factory), []); + + $deprecations = $this->collectDeprecations(static function () use ($service): void { + try { + $service->loadFromUrl(self::URL); + } catch (Throwable) { + } + }); + + static::assertSame([sprintf(self::DEPRECATION, $factory)], $deprecations); + } + + /** + * The redirect policy stays the second argument of the factories when only the large key sets option is set. + */ + #[Test] + public function theRedirectPolicyKeepsItsPlaceBesideTheLargeKeySetsOption(): void + { + $service = $this->getFactory(JKUFactory::class, '{"keys":[]}', [ + 'follow_redirects' => false, + 'allow_large_key_sets' => true, + ], true); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Unable to get the key set: redirects are refused.'); + + $service->loadFromUrl(self::URL); + } + + /** + * @return iterable}> + */ + public static function factories(): iterable + { + yield 'JKU' => [JKUFactory::class]; + yield 'X5U' => [X5UFactory::class]; + } + + /** + * A document of 4097 values: a key set for JKUFactory, and an object of certificates for X5UFactory, whose array + * of values is not a certificate. + * + * @param class-string $factory + */ + private static function largeDocument(string $factory): string + { + return $factory === JKUFactory::class + ? '{"keys":[{"kty":"oct","k":"AAAA","x":[' . str_repeat('0,', 4091) . '0]}]}' + : '{"key":[' . str_repeat('0,', 4095) . '0]}'; + } + + /** + * Boots a kernel whose key set client answers every request with the given document, and returns the factory + * service. + * + * @template T of JKUFactory|X5UFactory + * + * @param class-string $factory + * @param array $options + * + * @return T + */ + private function getFactory( + string $factory, + string $document, + array $options, + bool $redirected = false + ): JKUFactory|X5UFactory { + $this->kernel = new IsolatedKernel(static function (ContainerBuilder $container) use ( + $document, + $options, + $redirected + ): void { + $container->register('app.key_set_client', MockHttpClient::class) + ->setArguments([ + new Definition(MockResponse::class, [ + $document, + $redirected ? [ + 'redirect_count' => 1, + 'url' => 'http://127.0.0.1:8080/keys', + ] : [], + ]), + ]); + $container->loadFromExtension('jose', [ + 'jku_factory' => [ + 'enabled' => true, + 'client' => 'app.key_set_client', + ] + $options, + ]); + }); + $this->kernel->boot(); + + $service = $this->kernel->getContainer() + ->get($factory); + static::assertInstanceOf($factory, $service); + + return $service; + } + + /** + * @param callable(): void $callback + * + * @return list + */ + private function collectDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $type, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_USER_DEPRECATED); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } +} diff --git a/tests/Component/Console/LargeJsonInputTest.php b/tests/Component/Console/LargeJsonInputTest.php new file mode 100644 index 00000000..78b9dfdf --- /dev/null +++ b/tests/Component/Console/LargeJsonInputTest.php @@ -0,0 +1,107 @@ + $arguments + */ + #[Test] + #[DataProvider('commands')] + public function aCommandDecodesALargeKeyWithoutDeprecation(Command $command, array $arguments): void + { + $deprecations = []; + set_error_handler(static function (int $type, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_USER_DEPRECATED); + + try { + $exitCode = $command->run(new ArrayInput($arguments), new BufferedOutput()); + } finally { + restore_error_handler(); + } + + static::assertSame(Command::SUCCESS, $exitCode); + static::assertSame([], $deprecations); + } + + /** + * @return iterable}> + */ + public static function commands(): iterable + { + $padding = range(1, 5000); + $ec = (new JWKFactory())->ec('P-256', [ + 'padding' => $padding, + ])->all(); + $rsa = (new JWKFactory())->rsa(2048, [ + 'padding' => $padding, + ])->all(); + $key = JsonConverter::encode($ec); + $keySet = JsonConverter::encode([ + 'keys' => [$ec], + ]); + + yield 'thumbprint' => [new GetThumbprintCommand(), [ + 'jwk' => $key, + ]]; + yield 'key analyzer' => [new KeyAnalyzerCommand(new KeyAnalyzerManager()), [ + 'jwk' => $key, + ]]; + yield 'key set analyzer' => [ + new KeysetAnalyzerCommand(new KeysetAnalyzerManager(), new KeyAnalyzerManager()), + [ + 'jwkset' => $keySet, + ], + ]; + yield 'RSA optimization' => [new OptimizeRsaKeyCommand(), [ + 'jwk' => JsonConverter::encode($rsa), + ]]; + yield 'PEM conversion' => [new PemConverterCommand(), [ + 'jwk' => $key, + ]]; + yield 'PKCS#8 conversion' => [new Pkcs8ConverterCommand(), [ + 'jwk' => $key, + ]]; + yield 'public key' => [new PublicKeyCommand(), [ + 'jwk' => $key, + ]]; + yield 'public key set' => [new PublicKeysetCommand(), [ + 'jwkset' => $keySet, + ]]; + } +} diff --git a/tests/Component/Core/JsonConverterTest.php b/tests/Component/Core/JsonConverterTest.php index 304fa3a8..80b2c62c 100644 --- a/tests/Component/Core/JsonConverterTest.php +++ b/tests/Component/Core/JsonConverterTest.php @@ -4,15 +4,34 @@ namespace Jose\Tests\Component\Core; +use Jose\Component\Core\Exception\InvalidArgumentException; +use Jose\Component\Core\Exception\JsonBoundExceededException; use Jose\Component\Core\Util\JsonConverter; +use JsonException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use function restore_error_handler; +use function set_error_handler; +use function sprintf; +use function str_repeat; +use const E_USER_DEPRECATED; +use const JSON_ERROR_CTRL_CHAR; +use const JSON_ERROR_DEPTH; +use const JSON_ERROR_SYNTAX; +use const JSON_ERROR_UTF8; /** * @internal */ final class JsonConverterTest extends TestCase { + private const DEPRECATION = 'Since web-token/jwt-framework 4.3.0: Decoding a JSON document of more than 4096 values is deprecated and "Jose\Component\Core\Util\JsonConverter::decode()" will refuse it by default in 5.0.0. Pass true as the second argument to keep decoding it, or false to refuse it now.'; + + private const REFUSED = 'The JSON document holds more JSON values than the 4096 that are decoded.'; + + private const INVALID_ARGUMENT = 'The second argument of "Jose\Component\Core\Util\JsonConverter::decode()" must be a boolean: true decodes a document of any number of values, false refuses one of more than 4096.'; + #[Test] public function iCanConvertAnObjectIntoAJsonString(): void { @@ -23,4 +42,125 @@ public function iCanConvertAnObjectIntoAJsonString(): void 'foo' => 'BAR', ], JsonConverter::decode('{"foo":"BAR"}')); } + + /** + * The message names the error of json_decode(), whose exception is chained as a copy with its code. + */ + #[Test] + #[DataProvider('invalidDocuments')] + public function anInvalidDocumentIsRejectedWithTheErrorOfJsonDecode(string $json, string $error, int $code): void + { + try { + JsonConverter::decode($json); + static::fail('The document should have been rejected.'); + } catch (InvalidArgumentException $exception) { + static::assertSame(InvalidArgumentException::class, $exception::class); + static::assertSame('The JSON document is not valid: ' . $error . '.', $exception->getMessage()); + static::assertSame($code, $exception->getCode()); + static::assertInstanceOf(JsonException::class, $exception->getPrevious()); + static::assertSame($error, $exception->getPrevious()->getMessage()); + } + } + + #[Test] + public function aDocumentNestedTooDeeplyIsRejectedForItsDepth(): void + { + $this->expectException(JsonBoundExceededException::class); + $this->expectExceptionMessage('The JSON document is nested too deeply.'); + $this->expectExceptionCode(JSON_ERROR_DEPTH); + + JsonConverter::decode(str_repeat('[', 600) . str_repeat(']', 600)); + } + + /** + * Without a second argument, or with null, a document of more than 4096 values is decoded with a deprecation, as + * 5.0.0 refuses it by default. True decodes it silently, false refuses it. + * + * @param list $arguments + */ + #[Test] + #[DataProvider('bounds')] + public function theValuesOfADocumentAreBoundedAsTheSecondArgumentSays( + array $arguments, + int $values, + string $outcome + ): void { + $document = '[' . str_repeat('0,', $values - 1) . '0]'; + $decoded = null; + $exception = null; + $deprecations = self::collectDeprecations(static function () use ($document, $arguments, &$decoded, &$exception): void { + try { + $decoded = JsonConverter::decode($document, ...$arguments); + } catch (InvalidArgumentException $failure) { + $exception = $failure; + } + }); + + static::assertSame($outcome === 'deprecated' ? [self::DEPRECATION] : [], $deprecations); + match ($outcome) { + 'decoded', 'deprecated' => static::assertCount($values, $decoded), + 'refused' => static::assertSame([JsonBoundExceededException::class, self::REFUSED, 0], [ + $exception::class, + $exception->getMessage(), + $exception->getCode(), + ]), + 'invalid argument' => static::assertSame([InvalidArgumentException::class, self::INVALID_ARGUMENT], [ + $exception::class, + $exception->getMessage(), + ]), + }; + } + + /** + * @return iterable + */ + public static function invalidDocuments(): iterable + { + yield 'syntax' => ['{', 'Syntax error', JSON_ERROR_SYNTAX]; + yield 'invalid UTF-8' => ["\"\xff\"", 'Malformed UTF-8 characters, possibly incorrectly encoded', JSON_ERROR_UTF8]; + yield 'control character' => ["\"\x01\"", 'Control character error, possibly incorrectly encoded', JSON_ERROR_CTRL_CHAR]; + } + + /** + * @return iterable, int, string}> + */ + public static function bounds(): iterable + { + $arguments = [ + 'without a second argument' => [], + 'null' => [null], + 'true' => [true], + 'false' => [false], + ]; + foreach ($arguments as $name => $argument) { + yield sprintf('%s, 4096 values', $name) => [$argument, 4096, 'decoded']; + } + yield 'without a second argument, 4097 values' => [[], 4097, 'deprecated']; + yield 'null, 4097 values' => [[null], 4097, 'deprecated']; + yield 'true, 4097 values' => [[true], 4097, 'decoded']; + yield 'false, 4097 values' => [[false], 4097, 'refused']; + yield 'a string, 4096 values' => [['false'], 4096, 'invalid argument']; + yield 'an integer, 4097 values' => [[0], 4097, 'invalid argument']; + } + + /** + * @return list + */ + private static function collectDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $type, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_USER_DEPRECATED); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } } diff --git a/tests/Component/Core/KeyJsonDocumentTest.php b/tests/Component/Core/KeyJsonDocumentTest.php new file mode 100644 index 00000000..bc7f755f --- /dev/null +++ b/tests/Component/Core/KeyJsonDocumentTest.php @@ -0,0 +1,214 @@ + $class + * @param list $arguments + */ + #[Test] + #[DataProvider('bounds')] + public function theValuesOfAKeyDocumentAreBoundedAsTheSecondArgumentSays( + string $class, + array $arguments, + int $values, + string $outcome + ): void { + $document = self::document($class, $values); + $created = null; + $exception = null; + $deprecations = self::collectDeprecations(static function () use ( + $class, + $document, + $arguments, + &$created, + &$exception + ): void { + try { + $created = $class::createFromJson($document, ...$arguments); + } catch (InvalidArgumentException $failure) { + $exception = $failure; + } + }); + + $method = $class . '::createFromJson'; + static::assertSame($outcome === 'deprecated' ? [sprintf(self::DEPRECATION, $method)] : [], $deprecations); + match ($outcome) { + 'created', 'deprecated' => static::assertInstanceOf($class, $created), + 'refused' => static::assertSame([JsonBoundExceededException::class, self::REFUSED], [ + $exception::class, + $exception->getMessage(), + ]), + 'invalid argument' => static::assertSame( + [InvalidArgumentException::class, sprintf(self::INVALID_ARGUMENT, $method)], + [$exception::class, $exception->getMessage()] + ), + }; + } + + /** + * The exception of json_decode() records the document among the arguments of its trace, and the key would be + * logged with it. + * + * @param class-string $class + */ + #[Test] + #[DataProvider('documentsWithASecret')] + public function anInvalidDocumentKeepsItsJsonExceptionWithoutTheKey(string $class, string $document): void + { + $exception = self::failureOf(static fn (): JWK|JWKSet => $class::createFromJson($document)); + + static::assertSame([JsonException::class, 'Syntax error', JSON_ERROR_SYNTAX], [ + $exception::class, + $exception->getMessage(), + $exception->getCode(), + ]); + static::assertTrue(self::argumentsAreRecorded($exception)); + static::assertSame([], self::callsHolding($exception, self::SECRET)); + } + + /** + * json_decode() reads 511 levels: a key of 512 levels is refused with its JsonException. + * + * @param class-string $class + */ + #[Test] + #[DataProvider('depths')] + public function theDepthOfAKeyDocumentIsBoundedByJsonDecode(string $class, string $document, bool $created): void + { + if (! $created) { + $this->expectException(JsonException::class); + $this->expectExceptionMessage('Maximum stack depth exceeded'); + } + + static::assertInstanceOf($class, $class::createFromJson($document)); + } + + /** + * @return iterable, string, bool}> + */ + public static function depths(): iterable + { + yield 'JWK, 511 levels' => [JWK::class, '{"kty":"oct","k":"AAAA","x":' . self::arrays(510) . '}', true]; + yield 'JWK, 512 levels' => [JWK::class, '{"kty":"oct","k":"AAAA","x":' . self::arrays(511) . '}', false]; + yield 'JWKSet, 511 levels' => [ + JWKSet::class, + '{"keys":[{"kty":"oct","k":"AAAA","x":' . self::arrays(508) . '}]}', + true, + ]; + yield 'JWKSet, 512 levels' => [ + JWKSet::class, + '{"keys":[{"kty":"oct","k":"AAAA","x":' . self::arrays(509) . '}]}', + false, + ]; + } + + /** + * @return iterable, list, int, string}> + */ + public static function bounds(): iterable + { + foreach ([JWK::class, JWKSet::class] as $class) { + foreach ([ + 'without a second argument' => [], + 'null' => [null], + 'true' => [true], + 'false' => [false], + ] as $name => $arguments) { + yield sprintf('%s, %s, 4096 values', $class, $name) => [$class, $arguments, 4096, 'created']; + } + yield sprintf('%s, without a second argument, 4097 values', $class) => [$class, [], 4097, 'deprecated']; + yield sprintf('%s, null, 4097 values', $class) => [$class, [null], 4097, 'deprecated']; + yield sprintf('%s, true, 4097 values', $class) => [$class, [true], 4097, 'created']; + yield sprintf('%s, false, 4097 values', $class) => [$class, [false], 4097, 'refused']; + yield sprintf('%s, a string, 4096 values', $class) => [$class, ['true'], 4096, 'invalid argument']; + } + } + + /** + * @return iterable, string}> + */ + public static function documentsWithASecret(): iterable + { + yield 'JWK' => [JWK::class, '{"kty":"oct","k":"' . self::SECRET . '"']; + yield 'JWKSet' => [JWKSet::class, '{"keys":[{"kty":"oct","k":"' . self::SECRET . '"}]']; + } + + /** + * A key document of the given number of values: the array of the "x" member fills it. + * + * @param class-string $class + */ + private static function document(string $class, int $values): string + { + return $class === JWK::class + ? '{"kty":"oct","k":"AAAA","x":' . self::values($values - 3) . '}' + : '{"keys":[{"kty":"oct","k":"AAAA","x":' . self::values($values - 5) . '}]}'; + } + + private static function arrays(int $levels): string + { + return str_repeat('[', $levels) . '0' . str_repeat(']', $levels); + } + + private static function values(int $count): string + { + return '[' . str_repeat('0,', $count - 1) . '0]'; + } + + /** + * @return list + */ + private static function collectDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $type, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_USER_DEPRECATED); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } +} diff --git a/tests/Component/KeyManagement/LargeJsonDocumentTest.php b/tests/Component/KeyManagement/LargeJsonDocumentTest.php new file mode 100644 index 00000000..04dee13c --- /dev/null +++ b/tests/Component/KeyManagement/LargeJsonDocumentTest.php @@ -0,0 +1,315 @@ + $arguments + */ + #[Test] + #[DataProvider('bounds')] + public function theValuesOfAJsonObjectAreBoundedAsTheSecondArgumentSays( + array $arguments, + int $values, + string $outcome + ): void { + $document = '{"kty":"oct","k":"AAAA","x":' . self::values($values - 3) . '}'; + $created = null; + $exception = null; + $deprecations = self::collectDeprecations(static function () use ( + $document, + $arguments, + &$created, + &$exception + ): void { + try { + $created = (new JWKFactory())->fromJsonObject($document, ...$arguments); + } catch (InvalidArgumentException $failure) { + $exception = $failure; + } + }); + + static::assertSame($outcome === 'deprecated' ? [self::DEPRECATION] : [], $deprecations); + match ($outcome) { + 'created', 'deprecated' => static::assertInstanceOf(JWK::class, $created), + 'refused' => static::assertSame([JsonBoundExceededException::class, self::REFUSED], [ + $exception::class, + $exception->getMessage(), + ]), + 'invalid argument' => static::assertSame( + 'The second argument of "Jose\Component\KeyManagement\JWKFactory::fromJsonObject()" must be a boolean: true decodes a document of any number of values, false refuses one of more than 4096.', + $exception->getMessage() + ), + }; + } + + #[Test] + public function theDepthOfAJsonObjectIsBoundedByJsonDecode(): void + { + static::assertInstanceOf( + JWK::class, + (new JWKFactory())->fromJsonObject('{"kty":"oct","k":"AAAA","x":' . self::arrays(510) . '}') + ); + + $this->expectException(JsonException::class); + $this->expectExceptionMessage('Maximum stack depth exceeded'); + + (new JWKFactory())->fromJsonObject('{"kty":"oct","k":"AAAA","x":' . self::arrays(511) . '}'); + } + + /** + * The deprecated static factory passes its second argument on. + */ + #[Test] + public function theDeprecatedStaticFactoryPassesTheSecondArgumentOn(): void + { + $exception = null; + self::collectDeprecations(static function () use (&$exception): void { + try { + JWKFactory::createFromJsonObject('{"kty":"oct","k":"AAAA","x":' . self::values(4094) . '}', false); + } catch (JsonBoundExceededException $failure) { + $exception = $failure; + } + }); + + static::assertInstanceOf(JsonBoundExceededException::class, $exception); + } + + #[Test] + public function anInvalidJsonObjectKeepsItsJsonExceptionWithoutTheKey(): void + { + $exception = self::failureOf( + static fn (): JWK|JWKSet => (new JWKFactory())->fromJsonObject('{"kty":"oct","k":"' . self::SECRET . '"') + ); + + static::assertSame([JsonException::class, 'Syntax error', JSON_ERROR_SYNTAX], [ + $exception::class, + $exception->getMessage(), + $exception->getCode(), + ]); + static::assertTrue(self::argumentsAreRecorded($exception)); + static::assertSame([], self::callsHolding($exception, self::SECRET)); + } + + /** + * A key set of a URL is decoded with a deprecation when the factory has no policy for large key sets. + * + * @param class-string $factory + * @param list $policy + */ + #[Test] + #[DataProvider('largeKeySetPolicies')] + public function aLargeKeySetOfAUrlIsLoadedAsThePolicySays(string $factory, array $policy, string $outcome): void + { + $instance = new $factory(self::client(self::largeDocument($factory)), ...$policy); + $exception = null; + $deprecations = self::collectDeprecations(static function () use ($instance, &$exception): void { + try { + $instance->loadFromUrl(self::URL); + } catch (Throwable $failure) { + $exception = $failure; + } + }); + + static::assertSame($outcome === 'deprecated' ? [sprintf(self::URL_DEPRECATION, $factory)] : [], $deprecations); + if ($outcome === 'refused') { + static::assertInstanceOf(JsonBoundExceededException::class, $exception); + static::assertSame(self::REFUSED, $exception->getMessage()); + } else { + static::assertNotInstanceOf(JsonBoundExceededException::class, $exception); + } + } + + /** + * @param class-string $factory + * @param list $policy + */ + #[Test] + #[DataProvider('smallKeySetPolicies')] + public function aKeySetWithinTheBoundIsLoadedSilently(string $factory, string $document, array $policy): void + { + $instance = new $factory(self::client($document), ...$policy); + $keySet = null; + $deprecations = self::collectDeprecations(static function () use ($instance, &$keySet): void { + $keySet = $instance->loadFromUrl(self::URL); + }); + + static::assertSame([], $deprecations); + static::assertInstanceOf(JWKSet::class, $keySet); + } + + /** + * @param class-string $factory + */ + #[Test] + #[DataProvider('factories')] + public function thePolicyForLargeKeySetsMustBeABoolean(string $factory): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'The policy for large key sets must be a boolean: true loads them, false refuses them.' + ); + + new $factory(self::client('{}'), null, 'false'); + } + + /** + * @return iterable, int, string}> + */ + public static function bounds(): iterable + { + foreach ([ + 'without a second argument' => [], + 'null' => [null], + 'true' => [true], + 'false' => [false], + ] as $name => $arguments) { + yield sprintf('%s, 4096 values', $name) => [$arguments, 4096, 'created']; + } + yield 'without a second argument, 4097 values' => [[], 4097, 'deprecated']; + yield 'null, 4097 values' => [[null], 4097, 'deprecated']; + yield 'true, 4097 values' => [[true], 4097, 'created']; + yield 'false, 4097 values' => [[false], 4097, 'refused']; + yield 'a string, 4096 values' => [['true'], 4096, 'invalid argument']; + } + + /** + * @return iterable, list, string}> + */ + public static function largeKeySetPolicies(): iterable + { + foreach ([JKUFactory::class, X5UFactory::class] as $factory) { + yield sprintf('%s, without a third argument', $factory) => [$factory, [], 'deprecated']; + yield sprintf('%s, null', $factory) => [$factory, [null, null], 'deprecated']; + yield sprintf('%s, true', $factory) => [$factory, [null, true], 'loaded']; + yield sprintf('%s, false', $factory) => [$factory, [null, false], 'refused']; + } + } + + /** + * @return iterable, string, list}> + */ + public static function smallKeySetPolicies(): iterable + { + $documents = [ + JKUFactory::class => '{"keys":[{"kty":"oct","kid":"key","k":"dGFyZ2V0"}]}', + X5UFactory::class => json_encode([ + 'key' => file_get_contents(__DIR__ . '/RSA/PEM/2048b-rsa-example-cert.pem'), + ], JSON_THROW_ON_ERROR), + ]; + foreach ($documents as $factory => $document) { + foreach ([ + 'without a third argument' => [], + 'null' => [null, null], + 'true' => [null, true], + 'false' => [null, false], + ] as $name => $policy) { + yield sprintf('%s, %s', $factory, $name) => [$factory, $document, $policy]; + } + } + } + + /** + * @return iterable}> + */ + public static function factories(): iterable + { + yield 'JKU' => [JKUFactory::class]; + yield 'X5U' => [X5UFactory::class]; + } + + /** + * A document of 4097 values: a key set for JKUFactory, and an object of certificates for X5UFactory, whose array + * of values is not a certificate. + * + * @param class-string $factory + */ + private static function largeDocument(string $factory): string + { + return $factory === JKUFactory::class + ? '{"keys":[{"kty":"oct","k":"AAAA","x":' . self::values(4092) . '}]}' + : '{"key":' . self::values(4096) . '}'; + } + + private static function arrays(int $levels): string + { + return str_repeat('[', $levels) . '0' . str_repeat(']', $levels); + } + + private static function values(int $count): string + { + return '[' . str_repeat('0,', $count - 1) . '0]'; + } + + private static function client(string $document): MockHttpClient + { + return new MockHttpClient(static fn (): MockResponse => new MockResponse($document)); + } + + /** + * @return list + */ + private static function collectDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $type, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_USER_DEPRECATED); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } +} diff --git a/tests/Component/KeyManagement/UrlKeySetFactoryTest.php b/tests/Component/KeyManagement/UrlKeySetFactoryTest.php index 3139b7d3..04bfb2ef 100644 --- a/tests/Component/KeyManagement/UrlKeySetFactoryTest.php +++ b/tests/Component/KeyManagement/UrlKeySetFactoryTest.php @@ -63,7 +63,7 @@ public function iCanGetAKeySetFromAJWKUrl(): void public function theJWKUrlIsValidButDoesNotContainAKeySet(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input.'); + $this->expectExceptionMessage('The JSON document is not valid: Syntax error.'); $response = new MockResponse('Hello World!', [ 'http_code' => 200, @@ -110,7 +110,7 @@ public function iCanGetAKeySetFromAX509Url(): void public function theX509UrlIsValidButDoesNotContainAKeySet(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unsupported input.'); + $this->expectExceptionMessage('The JSON document is not valid: Syntax error.'); $response = new MockResponse('Hello World!', [ 'http_code' => 200, diff --git a/tests/SelectiveDisclosure/JsonValueBoundTest.php b/tests/SelectiveDisclosure/JsonValueBoundTest.php index e76930bc..04151177 100644 --- a/tests/SelectiveDisclosure/JsonValueBoundTest.php +++ b/tests/SelectiveDisclosure/JsonValueBoundTest.php @@ -103,6 +103,44 @@ public function aDisclosureMadeOfNestedArraysIsRejectedWithoutExhaustingMemory() static::assertLessThan(8_000_000, memory_get_peak_usage() - $before); } + /** + * The Issuer signs the payload of the Issuer-signed JWT, which holds a digest for each Disclosure: the Holder and the + * Verifier decode it without the bound of the JSON documents of a token. + */ + /** + * The Issuer looks for the reserved claim names in the JSON of an object it issues in clear, which it decodes + * without bound. + */ + #[Test] + public function anObjectOfMoreThan4096ValuesIsIssuedInClear(): void + { + $sdJwt = self::issuer()->issue([ + 'iss' => 'https://issuer.example.com', + 'claim' => (object) [ + 'values' => range(1, 5000), + ], + ], self::issuerKey(), [ + 'alg' => 'ES256', + ]); + + static::assertCount( + 5000, + self::verifier()->verify($sdJwt->toString(), self::issuerKey()->toPublic())->getClaims()['claim']['values'] + ); + } + + #[Test] + public function anIssuerSignedJwtOfMoreThan4096ValuesIsProcessedAndVerified(): void + { + $token = self::token(self::sign(self::claims(5000))); + + static::assertSame('sha-256', SDJWT::fromString($token)->getHashAlgorithm()); + static::assertCount( + 5000, + self::verifier()->verify($token, self::issuerKey()->toPublic())->getClaims()['claim'] + ); + } + public static function dataSerializations(): iterable { yield 'compact' => [false, 1300, 1400]; @@ -162,4 +200,17 @@ private static function sdJwt(int $disclosureCount, bool $json): string $disclosures ); } + + /** + * Claims whose JSON holds the given number of integers, and a few more values. + * + * @return array + */ + private static function claims(int $integers): array + { + return [ + 'iss' => 'https://issuer.example.com', + 'claim' => range(1, $integers), + ]; + } } diff --git a/tests/SelectiveDisclosure/SDJWTVerifierTest.php b/tests/SelectiveDisclosure/SDJWTVerifierTest.php index 8308c547..f89296b7 100644 --- a/tests/SelectiveDisclosure/SDJWTVerifierTest.php +++ b/tests/SelectiveDisclosure/SDJWTVerifierTest.php @@ -5,6 +5,7 @@ namespace Jose\Tests\SelectiveDisclosure; use Jose\Component\Core\Exception\InvalidArgumentException; +use Jose\Component\Core\Exception\InvalidTokenException; use Jose\Component\Core\Exception\LogicException; use Jose\Component\Core\Exception\UnsupportedAlgorithmException; use Jose\Component\Core\JWK; @@ -17,6 +18,7 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use function array_slice; +use function range; /** * The verification of RFC 9901 sections 7.1 and 7.3. Every rejection is checked against an SD-JWT that is otherwise @@ -463,6 +465,29 @@ public function aKeyBindingJwtProtectedByAMacIsRejected(): void self::assertRejected('The Key Binding JWT must be signed with a digital signature algorithm.', static fn () => self::verifier()->verifyWithKeyBinding($presentation, self::issuerKey(), self::AUDIENCE, self::NONCE)); } + /** + * The Holder signs the Key Binding JWT, whose payload holds a few claims: it is decoded with the bound of the JSON + * documents of a token, while the payload of the Issuer-signed JWT is not. + */ + #[Test] + public function aKeyBindingJwtOfMoreThan4096ValuesIsRejected(): void + { + $sdJwt = SDJWT::fromString(self::token(self::sign([ + 'cnf' => [ + 'jwk' => self::holderKey()->toPublic()->all(), + ], + ]))); + $presentation = self::token($sdJwt->getIssuerSignedJwt(), [], self::keyBindingJwt($sdJwt, [ + 'x' => range(1, 5000), + ])); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage('The payload of the Key Binding JWT cannot be decoded.'); + $this->expectExceptionCode(0); + + self::verifier()->verifyWithKeyBinding($presentation, self::issuerKey(), self::AUDIENCE, self::NONCE); + } + #[Test] public function theHeaderCheckersOfTheIssuerSignedJwtLoaderAreApplied(): void { From 58c95a9d3a7b50a0362d06947c10bd7a7a810e73 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 21:38:42 +0100 Subject: [PATCH 13/32] fix(composer): require web-token/jwt-library ^4.3 in the bundle and experimental packages The bundle and the experimental packages of 4.3 use classes of the library that 4.2 does not have: 29 for the bundle, 7 for the experimental package. Both still required web-token/jwt-library ^4.0, so updating web-token/jwt-bundle alone, without its dependencies, kept the library 4.2. The container then failed to compile because the Ed25519 class was missing, and the experimental ES256K could not be loaded because its parent class was missing. Both packages now require ^4.3. The other combinations keep working: the bundle 4.2 and the experimental package 4.2 with the library 4.3, and the bundle 4.3 with the experimental package 4.2. --- src/Bundle/composer.json | 2 +- src/Experimental/composer.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Bundle/composer.json b/src/Bundle/composer.json index 334d2b33..588bd872 100644 --- a/src/Bundle/composer.json +++ b/src/Bundle/composer.json @@ -46,7 +46,7 @@ "symfony/event-dispatcher": "^7.0|^8.0", "symfony/http-client-contracts": "^3.4", "symfony/http-kernel": "^7.0|^8.0", - "web-token/jwt-library": "^4.0" + "web-token/jwt-library": "^4.3" }, "suggest": { "symfony/serializer": "Use the Symfony serializer to serialize/unserialize JWS and JWE tokens.", diff --git a/src/Experimental/composer.json b/src/Experimental/composer.json index 62cd433e..f081834e 100644 --- a/src/Experimental/composer.json +++ b/src/Experimental/composer.json @@ -40,6 +40,6 @@ "require": { "php": ">=8.2", "ext-openssl": "*", - "web-token/jwt-library": "^4.0" + "web-token/jwt-library": "^4.3" } } From b1e2cd8ccc2e33e205bd77d517b6053c53f98323 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 21:43:23 +0100 Subject: [PATCH 14/32] fix(key-management): JKUFactory and X5UFactory extend UrlKeySetFactory again In 4.2, JKUFactory and X5UFactory extended UrlKeySetFactory. Since #710 they only used the trait that holds the fetching code, so in 4.3 they were no longer instances of that class: an instanceof check returned false, and a parameter typed against UrlKeySetFactory refused them with a TypeError. The backward compatibility promise only allows a new parent class when the former one remains an ancestor. Both classes extend UrlKeySetFactory again and still use the trait. They keep their own constructor, so the deprecated constructor of UrlKeySetFactory never runs: neither the two factories nor the classes of an application that extend them trigger a deprecation, including under Symfony's DebugClassLoader. A class that extends UrlKeySetFactory directly still does. In 5.0.0, UrlKeySetFactory is removed and the two factories no longer extend it. --- .ci-tools/phpstan-baseline.neon | 22 ++++++++++++++++ src/Library/KeyManagement/JKUFactory.php | 6 ++++- .../KeyManagement/UrlKeySetFactory.php | 19 +++++++------- .../KeyManagement/UrlKeySetFactoryTrait.php | 8 +++--- src/Library/KeyManagement/X5UFactory.php | 6 ++++- .../KeyManagement/UrlKeySetFactoryTest.php | 25 ++++++++++++++++--- 6 files changed, 68 insertions(+), 18 deletions(-) diff --git a/.ci-tools/phpstan-baseline.neon b/.ci-tools/phpstan-baseline.neon index fb0eb107..43418942 100644 --- a/.ci-tools/phpstan-baseline.neon +++ b/.ci-tools/phpstan-baseline.neon @@ -6128,6 +6128,17 @@ parameters: count: 1 path: ../src/Library/KeyManagement/Analyzer/ZxcvbnKeyAnalyzer.php + - + rawMessage: ''' + Class Jose\Component\KeyManagement\JKUFactory extends deprecated class Jose\Component\KeyManagement\UrlKeySetFactory: + since 4.3.0 and will be removed in 5.0.0. Use JKUFactory or X5UFactory and type against them, or write + a factory of your own: an HTTP client is all that is needed to fetch the document. In 5.0.0, JKUFactory + and X5UFactory no longer extend this class. + ''' + identifier: class.extendsDeprecatedClass + count: 1 + path: ../src/Library/KeyManagement/JKUFactory.php + - rawMessage: 'Parameter #1 $details of static method Jose\Component\KeyManagement\KeyConverter\RSAKey::createFromKeyDetails() expects array, mixed given.' identifier: argument.type @@ -6224,6 +6235,17 @@ parameters: count: 1 path: ../src/Library/KeyManagement/KeyConverter/RSAKey.php + - + rawMessage: ''' + Class Jose\Component\KeyManagement\X5UFactory extends deprecated class Jose\Component\KeyManagement\UrlKeySetFactory: + since 4.3.0 and will be removed in 5.0.0. Use JKUFactory or X5UFactory and type against them, or write + a factory of your own: an HTTP client is all that is needed to fetch the document. In 5.0.0, JKUFactory + and X5UFactory no longer extend this class. + ''' + identifier: class.extendsDeprecatedClass + count: 1 + path: ../src/Library/KeyManagement/X5UFactory.php + - rawMessage: 'Call to internal static method ParagonIE_Sodium_Core_Ed25519::publickey_from_secretkey().' identifier: staticMethod.internal diff --git a/src/Library/KeyManagement/JKUFactory.php b/src/Library/KeyManagement/JKUFactory.php index c21a7755..f521bee1 100644 --- a/src/Library/KeyManagement/JKUFactory.php +++ b/src/Library/KeyManagement/JKUFactory.php @@ -10,9 +10,13 @@ use function is_array; /** + * Extends the deprecated UrlKeySetFactory only for the code typed against that class: the fetching code comes from + * UrlKeySetFactoryTrait, so the constructor of UrlKeySetFactory never runs and its deprecation is not triggered. In + * 5.0.0, UrlKeySetFactory is removed and this class no longer extends it. + * * @see \Jose\Tests\Component\KeyManagement\UrlKeySetFactoryTest */ -class JKUFactory +class JKUFactory extends UrlKeySetFactory { use UrlKeySetFactoryTrait; diff --git a/src/Library/KeyManagement/UrlKeySetFactory.php b/src/Library/KeyManagement/UrlKeySetFactory.php index 5ddcc921..a985b31a 100644 --- a/src/Library/KeyManagement/UrlKeySetFactory.php +++ b/src/Library/KeyManagement/UrlKeySetFactory.php @@ -8,16 +8,17 @@ use function trigger_deprecation; /** - * Base class JKUFactory and X5UFactory used to extend. + * Base class of JKUFactory and X5UFactory. * - * Those two classes now carry their own implementation, so nothing in this package extends this one any more and - * neither of them emits the deprecation below. What is deprecated is this class as a public extension point: it - * never had a behaviour of its own beyond fetching a URL and caching the response, and the cache it offers - - * a PSR-6 pool with a fixed lifetime, unaware of the cache directives of the endpoint - is better handled by the - * HTTP client it is given. + * Those two classes still extend it, so that the code typed against this class keeps receiving them, but they carry + * their own implementation: they never run the constructor below and neither of them emits its deprecation. What is + * deprecated is this class as a public extension point: it never had a behaviour of its own beyond fetching a URL and + * caching the response, and the cache it offers - a PSR-6 pool with a fixed lifetime, unaware of the cache directives + * of the endpoint - is better handled by the HTTP client it is given. * - * @deprecated since 4.3.0 and will be removed in 5.0.0. Use JKUFactory or X5UFactory, which no longer extend this - * class, or write a factory of your own: an HTTP client is all that is needed to fetch the document. + * @deprecated since 4.3.0 and will be removed in 5.0.0. Use JKUFactory or X5UFactory and type against them, or write + * a factory of your own: an HTTP client is all that is needed to fetch the document. In 5.0.0, JKUFactory + * and X5UFactory no longer extend this class. */ abstract class UrlKeySetFactory { @@ -32,7 +33,7 @@ public function __construct(HttpClientInterface $client) trigger_deprecation( 'web-token/jwt-framework', '4.3.0', - 'The class "%s" is deprecated and will be removed in 5.0.0. "%s" extends it: use "%s" or "%s", which do not extend it any more, or fetch the document with the HTTP client directly.', + 'The class "%s" is deprecated and will be removed in 5.0.0. "%s" extends it: use "%s" or "%s" instead, or fetch the document with the HTTP client directly.', self::class, static::class, JKUFactory::class, diff --git a/src/Library/KeyManagement/UrlKeySetFactoryTrait.php b/src/Library/KeyManagement/UrlKeySetFactoryTrait.php index 65c542e3..74ea760a 100644 --- a/src/Library/KeyManagement/UrlKeySetFactoryTrait.php +++ b/src/Library/KeyManagement/UrlKeySetFactoryTrait.php @@ -23,10 +23,10 @@ * header parameters of a token are chosen by its sender: a URL read from them must be in an exact list of trusted * URLs, and be fetched with redirects refused. * - * This is the shared implementation of JKUFactory and X5UFactory, which used to inherit it from UrlKeySetFactory. - * That class is deprecated and removed in 5.0.0; a trait carries the same code without giving the two factories a - * base class they would then have to keep. It is an implementation detail of those two classes: it is not covered - * by the backward compatibility promise and must not be used outside of this package. + * This is the shared implementation of JKUFactory and X5UFactory. They still extend UrlKeySetFactory, which uses this + * trait too, but use it themselves: they never run the deprecated constructor of that class, and keep the same code + * when that class is removed in 5.0.0. It is an implementation detail of those classes: it is not covered by the + * backward compatibility promise and must not be used outside of this package. * * @internal * diff --git a/src/Library/KeyManagement/X5UFactory.php b/src/Library/KeyManagement/X5UFactory.php index 0fc73b02..7a45dae4 100644 --- a/src/Library/KeyManagement/X5UFactory.php +++ b/src/Library/KeyManagement/X5UFactory.php @@ -14,9 +14,13 @@ use function is_string; /** + * Extends the deprecated UrlKeySetFactory only for the code typed against that class: the fetching code comes from + * UrlKeySetFactoryTrait, so the constructor of UrlKeySetFactory never runs and its deprecation is not triggered. In + * 5.0.0, UrlKeySetFactory is removed and this class no longer extends it. + * * @see \Jose\Tests\Component\KeyManagement\UrlKeySetFactoryTest */ -class X5UFactory +class X5UFactory extends UrlKeySetFactory { use UrlKeySetFactoryTrait; diff --git a/tests/Component/KeyManagement/UrlKeySetFactoryTest.php b/tests/Component/KeyManagement/UrlKeySetFactoryTest.php index 3139b7d3..44a3d46e 100644 --- a/tests/Component/KeyManagement/UrlKeySetFactoryTest.php +++ b/tests/Component/KeyManagement/UrlKeySetFactoryTest.php @@ -137,10 +137,29 @@ public function theUrlIsNotValidAndX509CertificatesCannotBeLoaded(): void } #[Test] - public function theFactoriesDoNotExtendTheDeprecatedBaseClass(): void + public function theFactoriesStillExtendTheDeprecatedBaseClass(): void { - static::assertNotInstanceOf(UrlKeySetFactory::class, $this->getJKUFactory()); - static::assertNotInstanceOf(UrlKeySetFactory::class, $this->getX5UFactory()); + $typedAgainstTheBaseClass = static fn (UrlKeySetFactory $factory): UrlKeySetFactory => $factory; + + static::assertSame($this->getJKUFactory(), $typedAgainstTheBaseClass($this->getJKUFactory())); + static::assertSame($this->getX5UFactory(), $typedAgainstTheBaseClass($this->getX5UFactory())); + } + + #[Test] + public function creatingTheFactoriesDoesNotTriggerADeprecation(): void + { + $client = $this->getHttpClient(); + + $deprecations = $this->collectDeprecations(static function () use ($client): void { + new JKUFactory($client); + new X5UFactory($client); + new JKUFactory($client, true); + new X5UFactory($client, false); + new class($client) extends JKUFactory {}; + new class($client) extends X5UFactory {}; + }); + + static::assertSame([], $deprecations); } #[Test] From 088e151faa0632a296dd7b66bfc652806116c066 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 9 Nov 2026 21:48:09 +0100 Subject: [PATCH 15/32] fix(bundle): keep the service ids of the library "none" and "RSA1_5" classes, deprecated Up to 4.2, the bundle registered the "none" and "RSA1_5" algorithms under the ids of their library classes, Jose\Component\Signature\Algorithm\None and Jose\Component\Encryption\Algorithm\KeyEncryption\RSA15. Since the two algorithms moved to the jwt-unsecured and jwt-rsa15 packages, the bundle registered the classes of those packages instead and the former ids no longer existed: an application service that referenced one of them, or autowired the library class, failed to compile. The former ids are registered again as deprecated services without the "jose.algorithm" tag, like the experimental ES256K: the "none" and "RSA1_5" aliases are still served by the classes of the new packages. Using one of them triggers the deprecation of the service, then that of the class. Both are removed in 5.0.0, with the library classes. --- .ci-tools/phpstan-baseline.neon | 20 ++++++ .../config/Algorithms/encryption_rsa15.php | 8 +++ .../config/Algorithms/signature_none.php | 8 +++ .../Functional/Rsa15AlgorithmTest.php | 64 +++++++++++++++++++ .../Functional/UnsecuredAlgorithmTest.php | 64 +++++++++++++++++++ .../TestBundle/Resources/config/services.php | 10 +++ .../Service/DeprecatedNoneConsumer.php | 18 ++++++ .../Service/DeprecatedRSA15Consumer.php | 18 ++++++ 8 files changed, 210 insertions(+) create mode 100644 tests/Bundle/JoseFramework/TestBundle/Service/DeprecatedNoneConsumer.php create mode 100644 tests/Bundle/JoseFramework/TestBundle/Service/DeprecatedRSA15Consumer.php diff --git a/.ci-tools/phpstan-baseline.neon b/.ci-tools/phpstan-baseline.neon index fb0eb107..14d15473 100644 --- a/.ci-tools/phpstan-baseline.neon +++ b/.ci-tools/phpstan-baseline.neon @@ -4818,6 +4818,16 @@ parameters: count: 1 path: ../src/Bundle/Helper/ConfigurationHelper.php + - + rawMessage: ''' + Access to constant on deprecated class Jose\Component\Encryption\Algorithm\KeyEncryption\RSA15: + since 4.3.0, will be removed in 5.0.0. The RSA1_5 algorithm moved to the "web-token/jwt-rsa15" + package: use Jose\Rsa15\KeyEncryption\RSA15 instead. + ''' + identifier: classConstant.deprecatedClass + count: 1 + path: ../src/Bundle/Resources/config/Algorithms/encryption_rsa15.php + - rawMessage: ''' Access to constant on deprecated class Jose\Component\Signature\Algorithm\EdDSA: @@ -4838,6 +4848,16 @@ parameters: count: 1 path: ../src/Bundle/Resources/config/Algorithms/signature_experimental.php + - + rawMessage: ''' + Access to constant on deprecated class Jose\Component\Signature\Algorithm\None: + since 4.3.0, will be removed in 5.0.0. The "none" algorithm moved to the "web-token/jwt-unsecured" + package: use Jose\Unsecured\Signature\None instead. + ''' + identifier: classConstant.deprecatedClass + count: 1 + path: ../src/Bundle/Resources/config/Algorithms/signature_none.php + - rawMessage: Access to constant on internal class Jose\Component\Core\Util\Ecc\NistCurve. identifier: classConstant.internalClass diff --git a/src/Bundle/Resources/config/Algorithms/encryption_rsa15.php b/src/Bundle/Resources/config/Algorithms/encryption_rsa15.php index 83f61e45..d5dc5fbb 100644 --- a/src/Bundle/Resources/config/Algorithms/encryption_rsa15.php +++ b/src/Bundle/Resources/config/Algorithms/encryption_rsa15.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Jose\Component\Encryption\Algorithm\KeyEncryption\RSA15 as LibraryRSA15; use Jose\Rsa15\KeyEncryption\RSA15; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; @@ -16,4 +17,11 @@ ->tag('jose.algorithm', [ 'alias' => 'RSA1_5', ]); + + $container->set(LibraryRSA15::class) + ->deprecate( + 'web-token/jwt-framework', + '4.3.0', + 'The "%service_id%" service is deprecated and will be removed in 5.0.0: the "RSA1_5" algorithm is now shipped by the "web-token/jwt-rsa15" package and registered as "' . RSA15::class . '", under the same "RSA1_5" alias.' + ); }; diff --git a/src/Bundle/Resources/config/Algorithms/signature_none.php b/src/Bundle/Resources/config/Algorithms/signature_none.php index c0a1dc82..0db14f7a 100644 --- a/src/Bundle/Resources/config/Algorithms/signature_none.php +++ b/src/Bundle/Resources/config/Algorithms/signature_none.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Jose\Component\Signature\Algorithm\None as LibraryNone; use Jose\Unsecured\Signature\None; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; @@ -16,4 +17,11 @@ ->tag('jose.algorithm', [ 'alias' => 'none', ]); + + $container->set(LibraryNone::class) + ->deprecate( + 'web-token/jwt-framework', + '4.3.0', + 'The "%service_id%" service is deprecated and will be removed in 5.0.0: the "none" algorithm is now shipped by the "web-token/jwt-unsecured" package and registered as "' . None::class . '", under the same "none" alias.' + ); }; diff --git a/tests/Bundle/JoseFramework/Functional/Rsa15AlgorithmTest.php b/tests/Bundle/JoseFramework/Functional/Rsa15AlgorithmTest.php index 264ee057..d82ce89b 100644 --- a/tests/Bundle/JoseFramework/Functional/Rsa15AlgorithmTest.php +++ b/tests/Bundle/JoseFramework/Functional/Rsa15AlgorithmTest.php @@ -5,9 +5,14 @@ namespace Jose\Tests\Bundle\JoseFramework\Functional; use Jose\Component\Core\AlgorithmManagerFactory; +use Jose\Component\Encryption\Algorithm\KeyEncryption\RSA15 as LibraryRSA15; use Jose\Rsa15\KeyEncryption\RSA15; +use Jose\Tests\Bundle\JoseFramework\TestBundle\Service\DeprecatedRSA15Consumer; use Jose\Tests\Bundle\JoseFramework\WebTestCase; use PHPUnit\Framework\Attributes\Test; +use function restore_error_handler; +use function set_error_handler; +use const E_USER_DEPRECATED; /** * The "RSA1_5" algorithm of the jose-rsa15 package is registered by its own configuration file. That file is only @@ -45,4 +50,63 @@ public function theRsa15AlgorithmIsTheOneOfTheRsa15Package(): void static::assertInstanceOf(RSA15::class, $factory->create(['RSA1_5'])->get('RSA1_5')); } + + /** + * Until 4.2, the bundle registered the algorithm under the id of the library class, which an application could + * reference or autowire. That class moved to the jose-rsa15 package in 4.3: the "RSA1_5" alias is served by the + * class of the package, and the library class survives as a deprecated service until 5.0.0: using it triggers + * the deprecation of the service, then that of the class. + */ + #[Test] + public function theLibraryClassIsStillADeprecatedService(): void + { + static::ensureKernelShutdown(); + $container = static::createClient() + ->getContainer(); + + /** @var AlgorithmManagerFactory $factory */ + $factory = $container->get(AlgorithmManagerFactory::class); + static::assertSame(RSA15::class, $factory->create(['RSA1_5'])->get('RSA1_5')::class); + + $consumer = null; + $deprecations = $this->collectDeprecations(static function () use ($container, &$consumer): void { + $consumer = $container->get(DeprecatedRSA15Consumer::class); + }); + + static::assertInstanceOf(DeprecatedRSA15Consumer::class, $consumer); + static::assertSame(LibraryRSA15::class, $consumer->algorithm::class); + static::assertSame('RSA1_5', $consumer->algorithm->name()); + static::assertCount(2, $deprecations); + static::assertSame( + 'Since web-token/jwt-framework 4.3.0: The "' . LibraryRSA15::class . '" service is deprecated and will be removed in 5.0.0: the "RSA1_5" algorithm is now shipped by the "web-token/jwt-rsa15" package and registered as "' . RSA15::class . '", under the same "RSA1_5" alias.', + $deprecations[0] + ); + static::assertStringStartsWith( + 'Since web-token/jwt-framework 4.3.0: The class "' . LibraryRSA15::class . '" is deprecated', + $deprecations[1] + ); + } + + /** + * @param callable(): void $callback + * + * @return list + */ + private function collectDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $type, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_USER_DEPRECATED); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } } diff --git a/tests/Bundle/JoseFramework/Functional/UnsecuredAlgorithmTest.php b/tests/Bundle/JoseFramework/Functional/UnsecuredAlgorithmTest.php index 15dea0d7..d34a4cc9 100644 --- a/tests/Bundle/JoseFramework/Functional/UnsecuredAlgorithmTest.php +++ b/tests/Bundle/JoseFramework/Functional/UnsecuredAlgorithmTest.php @@ -5,9 +5,14 @@ namespace Jose\Tests\Bundle\JoseFramework\Functional; use Jose\Component\Core\AlgorithmManagerFactory; +use Jose\Component\Signature\Algorithm\None as LibraryNone; +use Jose\Tests\Bundle\JoseFramework\TestBundle\Service\DeprecatedNoneConsumer; use Jose\Tests\Bundle\JoseFramework\WebTestCase; use Jose\Unsecured\Signature\None; use PHPUnit\Framework\Attributes\Test; +use function restore_error_handler; +use function set_error_handler; +use const E_USER_DEPRECATED; /** * The "none" algorithm of the jose-unsecured package is registered by its own configuration file. That file is only @@ -45,4 +50,63 @@ public function theNoneAlgorithmIsTheOneOfTheUnsecuredPackage(): void static::assertInstanceOf(None::class, $factory->create(['none'])->get('none')); } + + /** + * Until 4.2, the bundle registered the algorithm under the id of the library class, which an application could + * reference or autowire. That class moved to the jose-unsecured package in 4.3: the "none" alias is served by the + * class of the package, and the library class survives as a deprecated service until 5.0.0: using it triggers + * the deprecation of the service, then that of the class. + */ + #[Test] + public function theLibraryClassIsStillADeprecatedService(): void + { + static::ensureKernelShutdown(); + $container = static::createClient() + ->getContainer(); + + /** @var AlgorithmManagerFactory $factory */ + $factory = $container->get(AlgorithmManagerFactory::class); + static::assertSame(None::class, $factory->create(['none'])->get('none')::class); + + $consumer = null; + $deprecations = $this->collectDeprecations(static function () use ($container, &$consumer): void { + $consumer = $container->get(DeprecatedNoneConsumer::class); + }); + + static::assertInstanceOf(DeprecatedNoneConsumer::class, $consumer); + static::assertSame(LibraryNone::class, $consumer->algorithm::class); + static::assertSame('none', $consumer->algorithm->name()); + static::assertCount(2, $deprecations); + static::assertSame( + 'Since web-token/jwt-framework 4.3.0: The "' . LibraryNone::class . '" service is deprecated and will be removed in 5.0.0: the "none" algorithm is now shipped by the "web-token/jwt-unsecured" package and registered as "' . None::class . '", under the same "none" alias.', + $deprecations[0] + ); + static::assertStringStartsWith( + 'Since web-token/jwt-framework 4.3.0: The class "' . LibraryNone::class . '" is deprecated', + $deprecations[1] + ); + } + + /** + * @param callable(): void $callback + * + * @return list + */ + private function collectDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $type, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_USER_DEPRECATED); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } } diff --git a/tests/Bundle/JoseFramework/TestBundle/Resources/config/services.php b/tests/Bundle/JoseFramework/TestBundle/Resources/config/services.php index be4707cc..a1f1d9a2 100644 --- a/tests/Bundle/JoseFramework/TestBundle/Resources/config/services.php +++ b/tests/Bundle/JoseFramework/TestBundle/Resources/config/services.php @@ -10,6 +10,8 @@ use Jose\Tests\Bundle\JoseFramework\TestBundle\Checker\CustomChecker; use Jose\Tests\Bundle\JoseFramework\TestBundle\Checker\MaximumLifetime; use Jose\Tests\Bundle\JoseFramework\TestBundle\Service\DeprecatedES256KConsumer; +use Jose\Tests\Bundle\JoseFramework\TestBundle\Service\DeprecatedNoneConsumer; +use Jose\Tests\Bundle\JoseFramework\TestBundle\Service\DeprecatedRSA15Consumer; use Jose\Tests\Bundle\JoseFramework\TestBundle\Service\NestedTokenServiceConsumer; use Jose\Tests\Bundle\JoseFramework\TestBundle\Service\SelectiveDisclosureServiceConsumer; use Psr\Clock\ClockInterface; @@ -56,6 +58,14 @@ ->public() ; + $container->set(DeprecatedNoneConsumer::class) + ->public() + ; + + $container->set(DeprecatedRSA15Consumer::class) + ->public() + ; + $container->set(JWEDecrypterFactory::class); $container->set(JWELoaderFactory::class) ->public() diff --git a/tests/Bundle/JoseFramework/TestBundle/Service/DeprecatedNoneConsumer.php b/tests/Bundle/JoseFramework/TestBundle/Service/DeprecatedNoneConsumer.php new file mode 100644 index 00000000..a50b1e65 --- /dev/null +++ b/tests/Bundle/JoseFramework/TestBundle/Service/DeprecatedNoneConsumer.php @@ -0,0 +1,18 @@ + Date: Tue, 10 Nov 2026 18:25:29 +0300 Subject: [PATCH 16/32] fix(key-mgmt): analyze RSA n and e and EC coordinates by their integer value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RsaAnalyzer counted the modulus as 8 × octets and read the exponent with unpack('l'), so leading zero octets (RFC 7518 §2 forbids them, Base64urlUInt) let a key with n = 15 and e = 1 pass with no message. Both values are now read as big-endian integers with BigInteger. ESKeyAnalyzer checked the point with Curve::contains(), which reduces modulo p, so a coordinate >= p passed while OpenSSL refuses the key. Coordinates are now required to be lower than the field prime. --- .../KeyManagement/Analyzer/ESKeyAnalyzer.php | 7 +++ .../KeyManagement/Analyzer/RsaAnalyzer.php | 26 ++++++----- .../KeyManagement/JWKAnalyzerTest.php | 44 +++++++++++++++++++ 3 files changed, 67 insertions(+), 10 deletions(-) diff --git a/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php index a6edeaca..a606ee23 100644 --- a/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php @@ -60,6 +60,13 @@ public function analyze(JWK $jwk, MessageBag $bag): void } $xBI = BigInteger::fromBase(bin2hex($x), 16); $yBI = BigInteger::fromBase(bin2hex($y), 16); + $prime = $this->getCurve() + ->getPrime(); + if ($xBI->isGreaterThanOrEqualTo($prime) || $yBI->isGreaterThanOrEqualTo($prime)) { + $bag->add(Message::high('Invalid key. The components "x" and "y" shall be lower than the field prime.')); + + return; + } if (! $this->getCurve()->contains($xBI, $yBI)) { $bag->add(Message::high('Invalid key. The point is not on the curve.')); } diff --git a/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php b/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php index 5a76a5fa..b0ab368a 100644 --- a/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php @@ -4,14 +4,11 @@ namespace Jose\Component\KeyManagement\Analyzer; -use InvalidArgumentException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\Base64UrlSafe; +use Jose\Component\Core\Util\BigInteger; use Override; -use function is_array; use function is_string; -use function strlen; -use const STR_PAD_RIGHT; final readonly class RsaAnalyzer implements KeyAnalyzer { @@ -34,11 +31,14 @@ private function checkExponent(JWK $jwk, MessageBag $bag): void return; } - $exponent = unpack('l', str_pad(Base64UrlSafe::decodeNoPadding($e), 4, "\0", STR_PAD_RIGHT)); - if (! is_array($exponent) || ! isset($exponent[1])) { - throw new InvalidArgumentException('Unable to get the private key'); + $e = Base64UrlSafe::decodeNoPadding($e); + if ($e === '') { + $bag->add(Message::high('The exponent is not valid.')); + + return; } - if ($exponent[1] < 65537) { + $exponent = BigInteger::createFromBinaryString($e); + if ($exponent->lowerThan(BigInteger::createFromDecimal(65537))) { $bag->add(Message::high('The exponent is too low. It should be at least 65537.')); } } @@ -51,8 +51,14 @@ private function checkModulus(JWK $jwk, MessageBag $bag): void return; } - $n = 8 * strlen(Base64UrlSafe::decodeNoPadding($n)); - if ($n < 2048) { + $n = Base64UrlSafe::decodeNoPadding($n); + if ($n === '') { + $bag->add(Message::high('The modulus is not valid.')); + + return; + } + $modulus = BigInteger::createFromBinaryString($n); + if ($modulus->get()->getBitLength() < 2048) { $bag->add(Message::high('The key length is less than 2048 bits.')); } if ($jwk->has('d') && (! $jwk->has('p') || ! $jwk->has('q') || ! $jwk->has('dp') || ! $jwk->has( diff --git a/tests/Component/KeyManagement/JWKAnalyzerTest.php b/tests/Component/KeyManagement/JWKAnalyzerTest.php index 121afac5..1c8c0dec 100644 --- a/tests/Component/KeyManagement/JWKAnalyzerTest.php +++ b/tests/Component/KeyManagement/JWKAnalyzerTest.php @@ -4,7 +4,10 @@ namespace Jose\Tests\Component\KeyManagement; +use Brick\Math\BigInteger; use Jose\Component\Core\JWK; +use Jose\Component\Core\Util\Base64UrlSafe; +use Jose\Component\Core\Util\Ecc\NistCurve; use Jose\Component\KeyManagement\Analyzer\AlgorithmAnalyzer; use Jose\Component\KeyManagement\Analyzer\ES256KeyAnalyzer; use Jose\Component\KeyManagement\Analyzer\ES384KeyAnalyzer; @@ -14,6 +17,7 @@ use Jose\Component\KeyManagement\Analyzer\HS512KeyAnalyzer; use Jose\Component\KeyManagement\Analyzer\KeyAnalyzerManager; use Jose\Component\KeyManagement\Analyzer\KeyIdentifierAnalyzer; +use Jose\Component\KeyManagement\Analyzer\Message; use Jose\Component\KeyManagement\Analyzer\NoneAnalyzer; use Jose\Component\KeyManagement\Analyzer\OctAnalyzer; use Jose\Component\KeyManagement\Analyzer\RsaAnalyzer; @@ -23,6 +27,7 @@ use PHPUnit\Framework\Attributes\DoesNotPerformAssertions; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use const STR_PAD_LEFT; /** * @internal @@ -74,6 +79,45 @@ public function theRsaKeyHasALowExponent(): void static::fail('The low exponent should be catched'); } + #[Test] + public function theRsaKeyWithLeadingZeroOctetsIsAnalyzedByItsValue(): void + { + $key = new JWK([ + 'kty' => 'RSA', + 'n' => Base64UrlSafe::encodeUnpadded(str_repeat("\0", 255) . "\x0f"), + 'e' => Base64UrlSafe::encodeUnpadded("\0\0\0\1"), + ]); + $messages = $this->getKeyAnalyzer() + ->analyze($key); + + $texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all()); + static::assertContains('The key length is less than 2048 bits.', $texts); + static::assertContains('The exponent is too low. It should be at least 65537.', $texts); + } + + #[Test] + public function theEcKeyWithACoordinateAboveTheFieldPrimeIsRejected(): void + { + $key = JWKFactory::createECKey('P-521'); + $prime = NistCurve::curve521()->getPrime(); + $y = BigInteger::fromBase(bin2hex(Base64UrlSafe::decodeNoPadding($key->get('y'))), 16)->plus($prime); + $y = str_pad(hex2bin(str_pad($y->toBase(16), 132, '0', STR_PAD_LEFT)), 66, "\0", STR_PAD_LEFT); + $key = new JWK([ + 'kty' => 'EC', + 'crv' => 'P-521', + 'x' => $key->get('x'), + 'y' => Base64UrlSafe::encodeUnpadded($y), + ]); + $messages = $this->getKeyAnalyzer() + ->analyze($key); + + $texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all()); + static::assertContains( + 'Invalid key. The components "x" and "y" shall be lower than the field prime.', + $texts + ); + } + #[Test] public function iCanAnalyzeAnOctKeyAndGetMessages(): void { From c35731c40c97f2552fbd7264c1f28806a70fabca Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Tue, 10 Nov 2026 17:22:27 +0100 Subject: [PATCH 17/32] fix(key-mgmt): measure the RSA modulus and exponent on their octets RsaAnalyzer converted "n" and "e" into big integers. The analyzed keys may come from a third party and nothing bounds their length: without GMP, a modulus of 2048 octets cost 0.57 s with BCMath and 109 s in pure PHP, and 32 KiB cost 155 s with BCMath. The bit length of the modulus is now read from its octets, leading zero octets ignored, as RSAKey does. The exponent is converted only when it fits in three octets: a longer value is at least 2^24. The verdicts are those of the previous commit. The new tests cover the bounds: 2047 and 2048-bit moduli, exponents with leading zero octets or longer than four octets. --- .../KeyManagement/Analyzer/RsaAnalyzer.php | 29 ++++++-- .../KeyManagement/JWKAnalyzerTest.php | 66 +++++++++++++++++++ 2 files changed, 90 insertions(+), 5 deletions(-) diff --git a/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php b/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php index b0ab368a..ce2ac3bd 100644 --- a/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php @@ -6,9 +6,10 @@ use Jose\Component\Core\JWK; use Jose\Component\Core\Util\Base64UrlSafe; -use Jose\Component\Core\Util\BigInteger; use Override; use function is_string; +use function ord; +use function strlen; final readonly class RsaAnalyzer implements KeyAnalyzer { @@ -23,6 +24,10 @@ public function analyze(JWK $jwk, MessageBag $bag): void $this->checkModulus($jwk, $bag); } + /** + * The exponent is compared on its octets, without its leading zero octets: a value longer than three octets is at + * least 2^24, so only a value of three octets or less is converted into an integer. + */ private function checkExponent(JWK $jwk, MessageBag $bag): void { $e = $jwk->get('e'); @@ -37,8 +42,8 @@ private function checkExponent(JWK $jwk, MessageBag $bag): void return; } - $exponent = BigInteger::createFromBinaryString($e); - if ($exponent->lowerThan(BigInteger::createFromDecimal(65537))) { + $e = ltrim($e, "\0"); + if (strlen($e) <= 3 && hexdec(bin2hex($e)) < 65537) { $bag->add(Message::high('The exponent is too low. It should be at least 65537.')); } } @@ -57,8 +62,7 @@ private function checkModulus(JWK $jwk, MessageBag $bag): void return; } - $modulus = BigInteger::createFromBinaryString($n); - if ($modulus->get()->getBitLength() < 2048) { + if (self::getBitLength($n) < 2048) { $bag->add(Message::high('The key length is less than 2048 bits.')); } if ($jwk->has('d') && (! $jwk->has('p') || ! $jwk->has('q') || ! $jwk->has('dp') || ! $jwk->has( @@ -71,4 +75,19 @@ private function checkModulus(JWK $jwk, MessageBag $bag): void ); } } + + /** + * Returns the bit length of a Base64urlUInt value (RFC 7518, section 2) from its octets, leading zero octets + * ignored. The analyzed keys may come from a third party with a modulus of any length: converting it into a big + * integer costs seconds to minutes without GMP, while this costs nothing. + */ + private static function getBitLength(string $value): int + { + $value = ltrim($value, "\0"); + if ($value === '') { + return 0; + } + + return 8 * (strlen($value) - 1) + strlen(decbin(ord($value[0]))); + } } diff --git a/tests/Component/KeyManagement/JWKAnalyzerTest.php b/tests/Component/KeyManagement/JWKAnalyzerTest.php index 1c8c0dec..ffce3b77 100644 --- a/tests/Component/KeyManagement/JWKAnalyzerTest.php +++ b/tests/Component/KeyManagement/JWKAnalyzerTest.php @@ -24,9 +24,11 @@ use Jose\Component\KeyManagement\Analyzer\UsageAnalyzer; use Jose\Component\KeyManagement\Analyzer\ZxcvbnKeyAnalyzer; use Jose\Component\KeyManagement\JWKFactory; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\DoesNotPerformAssertions; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use function in_array; use const STR_PAD_LEFT; /** @@ -118,6 +120,70 @@ public function theEcKeyWithACoordinateAboveTheFieldPrimeIsRejected(): void ); } + #[Test] + #[DataProvider('rsaModuli')] + public function theRsaKeyLengthIsTheBitLengthOfTheModulus(string $n, bool $tooShort): void + { + $key = new JWK([ + 'kty' => 'RSA', + 'n' => Base64UrlSafe::encodeUnpadded($n), + 'e' => 'AQAB', + ]); + $messages = $this->getKeyAnalyzer() + ->analyze($key); + + $texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all()); + static::assertSame($tooShort, in_array('The key length is less than 2048 bits.', $texts, true)); + } + + /** + * @return iterable + */ + public static function rsaModuli(): iterable + { + yield '2048 bits' => ["\x80" . str_repeat("\xff", 255), false]; + yield '2048 bits with a leading zero octet' => ["\0\x80" . str_repeat("\xff", 255), false]; + yield '2049 bits' => ["\x01" . str_repeat("\xff", 256), false]; + yield '2047 bits on 256 octets' => ["\x7f" . str_repeat("\xff", 255), true]; + yield '2041 bits on 256 octets' => ["\x01" . str_repeat("\xff", 255), true]; + yield '2040 bits' => [str_repeat("\xff", 255), true]; + } + + #[Test] + #[DataProvider('rsaExponents')] + public function theRsaExponentIsComparedByItsValue(string $e, bool $tooLow): void + { + $key = new JWK([ + 'kty' => 'RSA', + 'n' => Base64UrlSafe::encodeUnpadded("\x80" . str_repeat("\xff", 255)), + 'e' => Base64UrlSafe::encodeUnpadded($e), + ]); + $messages = $this->getKeyAnalyzer() + ->analyze($key); + + $texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all()); + static::assertSame( + $tooLow, + in_array('The exponent is too low. It should be at least 65537.', $texts, true) + ); + } + + /** + * @return iterable + */ + public static function rsaExponents(): iterable + { + yield '65537' => ["\x01\x00\x01", false]; + yield '65537 with leading zero octets' => ["\0\0\x01\x00\x01", false]; + yield '65536' => ["\x01\x00\x00", true]; + yield '3' => ["\x03", true]; + yield 'zero' => ["\0", true]; + yield '2^24 - 1' => ["\xff\xff\xff", false]; + yield '2^24' => ["\x01\x00\x00\x00", false]; + yield '2^32 + 1' => ["\x01\x00\x00\x00\x01", false]; + yield '2^32 - 1' => ["\xff\xff\xff\xff", false]; + } + #[Test] public function iCanAnalyzeAnOctKeyAndGetMessages(): void { From dafe07464d5e38a1fc3ee9a84c8d07daf21dae53 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Tue, 10 Nov 2026 17:22:27 +0100 Subject: [PATCH 18/32] fix(key-mgmt): stop the EC analysis on coordinates of the wrong size ESKeyAnalyzer reported coordinates of the wrong size, then converted them into big integers anyway. Without GMP, coordinates of 1 KiB cost 27.5 s in pure PHP and 8 KiB cost 2 s with BCMath. The analysis now stops after the size message, as it does for empty coordinates, and the curve is created once. --- .../KeyManagement/Analyzer/ESKeyAnalyzer.php | 12 ++++++++--- .../KeyManagement/JWKAnalyzerTest.php | 21 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php index a606ee23..5e45586c 100644 --- a/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php @@ -15,6 +15,10 @@ abstract readonly class ESKeyAnalyzer implements KeyAnalyzer { + /** + * Coordinates of the wrong size are reported and not converted into integers: the analyzed keys may come from a + * third party, and converting coordinates of any length costs seconds without GMP. + */ #[Override] public function analyze(JWK $jwk, MessageBag $bag): void { @@ -57,17 +61,19 @@ public function analyze(JWK $jwk, MessageBag $bag): void $this->getKeySize() )) ); + + return; } $xBI = BigInteger::fromBase(bin2hex($x), 16); $yBI = BigInteger::fromBase(bin2hex($y), 16); - $prime = $this->getCurve() - ->getPrime(); + $curve = $this->getCurve(); + $prime = $curve->getPrime(); if ($xBI->isGreaterThanOrEqualTo($prime) || $yBI->isGreaterThanOrEqualTo($prime)) { $bag->add(Message::high('Invalid key. The components "x" and "y" shall be lower than the field prime.')); return; } - if (! $this->getCurve()->contains($xBI, $yBI)) { + if (! $curve->contains($xBI, $yBI)) { $bag->add(Message::high('Invalid key. The point is not on the curve.')); } } diff --git a/tests/Component/KeyManagement/JWKAnalyzerTest.php b/tests/Component/KeyManagement/JWKAnalyzerTest.php index ffce3b77..e5594fd3 100644 --- a/tests/Component/KeyManagement/JWKAnalyzerTest.php +++ b/tests/Component/KeyManagement/JWKAnalyzerTest.php @@ -120,6 +120,27 @@ public function theEcKeyWithACoordinateAboveTheFieldPrimeIsRejected(): void ); } + #[Test] + public function theEcKeyWithCoordinatesOfTheWrongSizeIsNotAnalyzedFurther(): void + { + $key = new JWK([ + 'kty' => 'EC', + 'crv' => 'P-256', + 'x' => Base64UrlSafe::encodeUnpadded(str_repeat("\xff", 33)), + 'y' => Base64UrlSafe::encodeUnpadded(str_repeat("\xff", 33)), + ]); + $messages = $this->getKeyAnalyzer() + ->analyze($key); + + $texts = array_map(static fn (Message $message): string => $message->getMessage(), $messages->all()); + static::assertContains('Invalid key. The components "x" and "y" size shall be 256 bits.', $texts); + static::assertNotContains( + 'Invalid key. The components "x" and "y" shall be lower than the field prime.', + $texts + ); + static::assertNotContains('Invalid key. The point is not on the curve.', $texts); + } + #[Test] #[DataProvider('rsaModuli')] public function theRsaKeyLengthIsTheBitLengthOfTheModulus(string $n, bool $tooShort): void From 3d4c72ef284b12580cccd22a5cc72ce017540a19 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Tue, 10 Nov 2026 18:24:34 +0100 Subject: [PATCH 19/32] ci(github): use a closing keyword in the pull request template "Resolves issue #823" does not link a pull request to the issue: GitHub expects the keyword directly before the reference, and the word "issue" in between breaks it. #824 targeted the default branch with that line and was never linked to #823. The template now reads "Resolves #", and its comment says to repeat the keyword for each issue, since one keyword links only the reference that follows it. --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 29c1e901..096e864b 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,5 +1,5 @@ Target branch: -Resolves issue # +Resolves # - [ ] It is a Bug fix From e960c7ce34253a44832ae300d606e4003f47f4b3 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 23 Nov 2026 19:53:49 +0100 Subject: [PATCH 20/32] fix(core): bound the RSA public exponent to 64 bits whatever the modulus RSAKey bounded the public exponent "e" to 64 bits above a modulus of 3072 bits only, as OpenSSL does, and to the length of the modulus below it. A key of 3072 bits whose exponent was as long as its modulus was therefore accepted, and the public operation PS*, RSA-OAEP and RSA1_5 compute in PHP costs as many squarings as "e" has bits: with GMP, a PS256 signature under such a key, which the sender of a DPoP proof chooses, took 30.9 ms to reject, against 0.7 ms with a 64-bit exponent; with BCMath, 1.48 s against 52 ms. The exponent is now refused beyond 64 bits whatever the modulus, and beyond the length of the modulus as before. The dearest key left is one of 16384 bits with a 64-bit exponent: 8.6 ms with GMP, 1.18 s with BCMath, as before this change. A key with a larger exponent is refused although FIPS 186-5 allows exponents below 2^256: generators draw 65537, and Go and BoringSSL already refuse exponents above 2^31 - 1 and 33 bits. --- src/Library/Core/Util/RSAKey.php | 12 +++++------- tests/Component/Core/Util/RSAKeyTest.php | 15 +++++++++------ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/Library/Core/Util/RSAKey.php b/src/Library/Core/Util/RSAKey.php index b7d44658..c84c0e61 100644 --- a/src/Library/Core/Util/RSAKey.php +++ b/src/Library/Core/Util/RSAKey.php @@ -18,6 +18,7 @@ use function array_key_exists; use function count; use function ltrim; +use function min; use function ord; use function sprintf; use function strlen; @@ -28,14 +29,12 @@ final class RSAKey { /** - * The limits of OpenSSL, in bytes: a modulus of 16384 bits at most, and a public exponent no longer than the - * modulus and of 64 bits at most above 3072 bits. RSA-PSS and RSAES compute the public operation in PHP, at a cost - * set by these lengths. + * In bytes: a modulus of 16384 bits at most, the limit of OpenSSL, and a public exponent no longer than the modulus + * and of 64 bits at most whatever the modulus, a limit OpenSSL applies above 3072 bits only. RSA-PSS and RSAES + * compute the public operation in PHP, at a cost set by these lengths. */ private const MAX_MODULUS_LENGTH = 2048; - private const SMALL_MODULUS_LENGTH = 384; - private const MAX_PUBLIC_EXPONENT_LENGTH = 8; private null|Sequence $sequence = null; @@ -71,8 +70,7 @@ private function __construct(JWK $data) if ($modulusLength > self::MAX_MODULUS_LENGTH) { throw new InvalidArgumentException('The key parameter "n" is too long.'); } - $limit = $modulusLength > self::SMALL_MODULUS_LENGTH ? self::MAX_PUBLIC_EXPONENT_LENGTH : $modulusLength; - if ($this->getMemberLength('e') > $limit) { + if ($this->getMemberLength('e') > min($modulusLength, self::MAX_PUBLIC_EXPONENT_LENGTH)) { throw new InvalidArgumentException('The key parameter "e" is too long.'); } $this->modulusLength = $modulusLength; diff --git a/tests/Component/Core/Util/RSAKeyTest.php b/tests/Component/Core/Util/RSAKeyTest.php index a65af1f0..37418fc4 100644 --- a/tests/Component/Core/Util/RSAKeyTest.php +++ b/tests/Component/Core/Util/RSAKeyTest.php @@ -32,17 +32,18 @@ protected function tearDown(): void } #[Test] - public function theLimitsOfOpenSSLAreAccepted(): void + public function theLargestKeysAreAccepted(): void { static::assertSame(2048, RSAKey::createFromJWK(self::key(2048, 8))->getModulusLength()); static::assertSame(385, RSAKey::createFromJWK(self::key(385, 8))->getModulusLength()); - static::assertSame(384, RSAKey::createFromJWK(self::key(384, 384))->getModulusLength()); - static::assertSame(256, RSAKey::createFromJWK(self::key(256, 9))->getModulusLength()); + static::assertSame(384, RSAKey::createFromJWK(self::key(384, 8))->getModulusLength()); + static::assertSame(256, RSAKey::createFromJWK(self::key(256, 8))->getModulusLength()); + static::assertSame(4, RSAKey::createFromJWK(self::key(4, 4))->getModulusLength()); } #[Test] #[DataProvider('oversizedKeys')] - public function aKeyBeyondTheLimitsOfOpenSSLIsRejected( + public function aKeyBeyondTheLimitsIsRejected( int $modulusLength, int $exponentLength, string $member @@ -61,8 +62,10 @@ public static function oversizedKeys(): iterable yield 'modulus of 16392 bits' => [2049, 3, 'n']; yield 'exponent of 72 bits, modulus of 16384 bits' => [2048, 9, 'e']; yield 'exponent of 72 bits, modulus of 3080 bits' => [385, 9, 'e']; - yield 'exponent longer than a modulus of 3072 bits' => [384, 385, 'e']; - yield 'exponent longer than a modulus of 2048 bits' => [256, 257, 'e']; + yield 'exponent of 72 bits, modulus of 3072 bits' => [384, 9, 'e']; + yield 'exponent of 72 bits, modulus of 2048 bits' => [256, 9, 'e']; + yield 'exponent as long as a modulus of 3072 bits' => [384, 384, 'e']; + yield 'exponent longer than a modulus of 32 bits' => [4, 5, 'e']; } #[Test] From 4029d7e69ad1535def6ecf827538a39c12d6e311 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Mon, 23 Nov 2026 19:58:04 +0100 Subject: [PATCH 21/32] ci: add to the PHPStan baseline the three conditions PHPStan 2.3.7 reports on 4.2.x The phpqa image rebuilt on 2026-11-20 ships PHPStan 2.3.7, which reports a mixed value as the condition of the ternaries of the processHeaders() methods of JSONFlattenedSerializer and JSONGeneralSerializer and of the if of MixedPublicAndPrivateKeys: the Static Analysis job failed on 4.2.x whatever the change. The baseline, generated by castor phpstan-baseline, gains those three entries and nothing else. --- .ci-tools/phpstan-baseline.neon | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.ci-tools/phpstan-baseline.neon b/.ci-tools/phpstan-baseline.neon index ebcee86f..a7cae84f 100644 --- a/.ci-tools/phpstan-baseline.neon +++ b/.ci-tools/phpstan-baseline.neon @@ -5154,6 +5154,12 @@ parameters: count: 1 path: ../src/Library/Encryption/Serializer/JSONFlattenedSerializer.php + - + rawMessage: 'Only booleans are allowed in a ternary operator condition, mixed given.' + identifier: ternary.condNotBoolean + count: 1 + path: ../src/Library/Encryption/Serializer/JSONFlattenedSerializer.php + - rawMessage: 'Parameter #1 $encodedString of static method Jose\Component\Core\Util\Base64UrlSafe::decodeNoPadding() expects string, mixed given.' identifier: argument.type @@ -5220,6 +5226,12 @@ parameters: count: 1 path: ../src/Library/Encryption/Serializer/JSONGeneralSerializer.php + - + rawMessage: 'Only booleans are allowed in a ternary operator condition, mixed given.' + identifier: ternary.condNotBoolean + count: 1 + path: ../src/Library/Encryption/Serializer/JSONGeneralSerializer.php + - rawMessage: 'Parameter #1 $encodedString of static method Jose\Component\Core\Util\Base64UrlSafe::decodeNoPadding() expects string, mixed given.' identifier: argument.type @@ -5298,6 +5310,12 @@ parameters: count: 1 path: ../src/Library/KeyManagement/Analyzer/MixedPublicAndPrivateKeys.php + - + rawMessage: 'Only booleans are allowed in an if condition, mixed given.' + identifier: if.condNotBoolean + count: 1 + path: ../src/Library/KeyManagement/Analyzer/MixedPublicAndPrivateKeys.php + - rawMessage: 'Parameter #2 ...$values of function sprintf expects bool|float|int|string|null, mixed given.' identifier: argument.type From 53eee3f66f4ed9098b53308533fabe49fd68d681 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 8 Nov 2026 10:45:52 +0100 Subject: [PATCH 22/32] Compute the RSA public operation with OpenSSL PS256, PS384 and PS512 verification and RSA-OAEP, RSA-OAEP-256 and RSA1_5 encryption raised the signature or the encoded message to the public exponent with brick/math. Without GMP, that costs seconds even with ordinary keys, whoever provides them: in pure PHP, a PS256 verification took 3 s with an RSA-2048 key and 15 s with an RSA-4096 key, and with BCMath a 3072-bit key whose exponent is as long as the modulus took 0.9 s. RSAKey::applyPublicKey() now computes input^e mod n with OpenSSL (OPENSSL_NO_PADDING) when the extension is loaded, and with brick/math otherwise. OpenSSL applies its own limits to the key, and the cost no longer depends on the calculator: about 0.2 ms per operation with an RSA-2048 key, with GMP, with BCMath or with neither. The public key is handed to OpenSSL as a PEM, which is now written without pki-framework, whose DER lengths go through brick/math: toPEM() for a public key drops from 0.23 ms to 0.03 ms, which RS256, RS384 and RS512 benefit from as well, and the PEM is the same byte for byte. With GMP, a PS256 verification with an RSA-2048 key takes 0.19 ms, against 0.11 ms before. Private key operations are unchanged. An input as large as the modulus, or a key that OpenSSL refuses (a public exponent as long as the modulus but larger), now raises a RuntimeException. Reported by Anthropic's OSS Scanner (ANT-2026-9EHC9J38 and ANT-2026-WD2XF3WZ). (cherry picked from commit 9323191c3224aff9832fc13a4be963c453165637) --- src/Library/Core/Util/RSAKey.php | 71 +++++++++++++--- .../Algorithm/KeyEncryption/Util/RSACrypt.php | 22 +---- src/Library/Signature/Algorithm/Util/RSA.php | 4 +- tests/Component/Core/Util/RSAKeyTest.php | 82 +++++++++++++++++++ 4 files changed, 143 insertions(+), 36 deletions(-) diff --git a/src/Library/Core/Util/RSAKey.php b/src/Library/Core/Util/RSAKey.php index c84c0e61..d4f77582 100644 --- a/src/Library/Core/Util/RSAKey.php +++ b/src/Library/Core/Util/RSAKey.php @@ -7,21 +7,24 @@ use InvalidArgumentException; use Jose\Component\Core\JWK; use RuntimeException; -use SpomkyLabs\Pki\ASN1\Component\Length; use SpomkyLabs\Pki\ASN1\DERData; use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence; -use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString; use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer; use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString; use SpomkyLabs\Pki\CryptoEncoding\PEM; use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Asymmetric\RSAEncryptionAlgorithmIdentifier; use function array_key_exists; +use function chr; use function count; +use function extension_loaded; +use function is_string; use function ltrim; use function min; use function ord; use function sprintf; use function strlen; +use const OPENSSL_NO_PADDING; +use const STR_PAD_LEFT; /** * @internal @@ -37,6 +40,11 @@ final class RSAKey private const MAX_PUBLIC_EXPONENT_LENGTH = 8; + /** + * AlgorithmIdentifier of rsaEncryption (1.2.840.113549.1.1.1) with NULL parameters, in DER. + */ + private const RSA_ALGORITHM_IDENTIFIER = "\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00"; + private null|Sequence $sequence = null; private readonly array $values; @@ -188,18 +196,40 @@ public function toPEM(): string return PEM::create(PEM::TYPE_PRIVATE_KEY, $this->sequence->toDER()) ->string(); } - $this->sequence = Sequence::create( - RSAEncryptionAlgorithmIdentifier::create()->toASN1(), - BitString::create( - Sequence::create( - $this->fromBase64ToInteger($this->values['n']), - $this->fromBase64ToInteger($this->values['e']) - )->toDER() - ) + $publicKey = self::encodeDER( + 0x30, + $this->fromBase64ToInteger($this->values['n'])->toDER() . $this->fromBase64ToInteger( + $this->values['e'] + )->toDER() ); - return PEM::create(PEM::TYPE_PUBLIC_KEY, $this->sequence->toDER()) - ->string(); + return PEM::create( + PEM::TYPE_PUBLIC_KEY, + self::encodeDER(0x30, self::RSA_ALGORITHM_IDENTIFIER . self::encodeDER(0x03, "\0" . $publicKey)) + )->string(); + } + + /** + * Computes input^e mod n (RSAEP, RSAVP1) on big-endian strings as long as the modulus. OpenSSL computes it when the + * extension is loaded, so that the cost does not depend on the brick/math calculator. + */ + public static function applyPublicKey(self $key, string $input): string + { + $public = self::toPublic($key); + if (strlen($input) !== $public->getModulusLength()) { + throw new RuntimeException('The input must be as long as the modulus.'); + } + if (! extension_loaded('openssl')) { + $output = self::exponentiate($public, BigInteger::createFromBinaryString($input))->toBytes(); + + return str_pad($output, $public->getModulusLength(), "\0", STR_PAD_LEFT); + } + $output = ''; + if (! openssl_public_encrypt($input, $output, $public->toPEM(), OPENSSL_NO_PADDING) || ! is_string($output)) { + throw new RuntimeException('Unable to apply the public key.'); + } + + return $output; } /** @@ -320,6 +350,21 @@ private function fromBase64ToInteger(string $value): DERData $value = "\0" . $value; } - return DERData::create("\x02" . Length::create(strlen($value))->toDER() . $value); + return DERData::create(self::encodeDER(0x02, $value)); + } + + /** + * Encodes a DER element without the big integers pki-framework uses for lengths: a public key is written for every + * RSA public key operation. + */ + private static function encodeDER(int $tag, string $content): string + { + $length = strlen($content); + if ($length < 0x80) { + return chr($tag) . chr($length) . $content; + } + $lengthOctets = ltrim(pack('N', $length), "\0"); + + return chr($tag) . chr(0x80 | strlen($lengthOctets)) . $lengthOctets . $content; } } diff --git a/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php b/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php index 8e777490..1d5a058e 100644 --- a/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php +++ b/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php @@ -85,10 +85,7 @@ public static function encryptWithRSA15(RSAKey $key, string $data): string $type = 2; $data = chr(0) . chr($type) . $ps . chr(0) . $data; - $binaryData = BigInteger::createFromBinaryString($data); - $c = self::getRSAEP($key, $binaryData); - - return self::convertIntegerToOctetString($c, $key->getModulusLength()); + return RSAKey::applyPublicKey($key, $data); } public static function decryptWithRSA15(RSAKey $key, string $c, ?int $expectedKeyLength = null): string @@ -224,18 +221,6 @@ private static function convertOctetStringToInteger(string $x): BigInteger return BigInteger::createFromBinaryString($x); } - /** - * RSA EP. - */ - private static function getRSAEP(RSAKey $key, BigInteger $m): BigInteger - { - if ($m->compare(BigInteger::createFromDecimal(0)) < 0 || $m->compare($key->getModulus()) >= 0) { - throw new RuntimeException(); - } - - return RSAKey::exponentiate($key, $m); - } - /** * RSA DP. */ @@ -279,10 +264,7 @@ private static function encryptRSAESOAEP(RSAKey $key, string $m, Hash $hash): st $maskedSeed = $seed ^ $seedMask; $em = chr(0) . $maskedSeed . $maskedDB; - $m = self::convertOctetStringToInteger($em); - $c = self::getRSAEP($key, $m); - - return self::convertIntegerToOctetString($c, $key->getModulusLength()); + return RSAKey::applyPublicKey($key, $em); } /** diff --git a/src/Library/Signature/Algorithm/Util/RSA.php b/src/Library/Signature/Algorithm/Util/RSA.php index 2d6118fa..df3b1149 100644 --- a/src/Library/Signature/Algorithm/Util/RSA.php +++ b/src/Library/Signature/Algorithm/Util/RSA.php @@ -108,9 +108,7 @@ public static function verifyWithPSS( if (strlen($signature) !== $key->getModulusLength()) { throw new RuntimeException(); } - $s2 = BigInteger::createFromBinaryString($signature); - $m2 = RSAKey::exponentiate($key, $s2); - $em = self::convertIntegerToOctetString($m2, $key->getModulusLength()); + $em = RSAKey::applyPublicKey($key, $signature); $modBits = 8 * $key->getModulusLength(); return self::verifyEMSAPSS($message, $em, $modBits - 1, Hash::get($hash)); diff --git a/tests/Component/Core/Util/RSAKeyTest.php b/tests/Component/Core/Util/RSAKeyTest.php index 37418fc4..f8c16f44 100644 --- a/tests/Component/Core/Util/RSAKeyTest.php +++ b/tests/Component/Core/Util/RSAKeyTest.php @@ -10,6 +10,7 @@ use InvalidArgumentException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\Base64UrlSafe; +use Jose\Component\Core\Util\BigInteger; use Jose\Component\Core\Util\RSAKey; use Jose\Component\Encryption\Algorithm\KeyEncryption\RSAOAEP256; use Jose\Component\Signature\Algorithm\PS256; @@ -17,9 +18,14 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use RuntimeException; +use function chr; +use function ord; use function sprintf; use function str_repeat; +use function strlen; use const OPENSSL_KEYTYPE_RSA; +use const STR_PAD_LEFT; /** * @internal @@ -146,6 +152,82 @@ public function thePemHoldsTheMembersOfTheKey(): void ], openssl_pkey_get_details($public)['rsa'] ?? null); } + #[Test] + public function thePublicOperationIsTheModularExponentiationOfTheInput(): void + { + [$key, $members] = self::generateKey(2048); + $modulus = $members['n']; + $public = RSAKey::createFromJWK($key->toPublic()); + $private = RSAKey::createFromJWK($key); + + foreach ([ + str_repeat("\0", 256), + str_repeat("\0", 255) . "\1", + substr($modulus, 0, -1) . chr(ord($modulus[-1]) - 1), + "\0" . random_bytes(255), + "\0" . random_bytes(255), + ] as $input) { + $expected = RSAKey::exponentiate($public, BigInteger::createFromBinaryString($input))->toBytes(); + $expected = str_pad($expected, 256, "\0", STR_PAD_LEFT); + + static::assertSame($expected, RSAKey::applyPublicKey($public, $input)); + static::assertSame($expected, RSAKey::applyPublicKey($private, $input)); + } + } + + /** + * @param callable(string): string $input + */ + #[Test] + #[DataProvider('nonRepresentatives')] + public function aValueThatIsNotARepresentativeIsRejected(callable $input): void + { + [$key, $members] = self::generateKey(2048); + + $this->expectException(RuntimeException::class); + + RSAKey::applyPublicKey(RSAKey::createFromJWK($key->toPublic()), $input($members['n'])); + } + + /** + * @return iterable + */ + public static function nonRepresentatives(): iterable + { + yield 'the modulus' => [ + static fn (string $modulus): string => $modulus, + ]; + yield 'above the modulus' => [ + static fn (string $modulus): string => str_repeat("\xFF", strlen($modulus)), + ]; + yield 'shorter than the modulus' => [ + static fn (string $modulus): string => substr($modulus, 1), + ]; + yield 'longer than the modulus' => [ + static fn (string $modulus): string => "\0" . $modulus, + ]; + } + + #[Test] + public function rsaPssVerificationAndRsaOaepEncryptionDoNotDependOnTheCalculator(): void + { + [$key] = self::generateKey(4096); + $signature = (new PS256())->sign($key, 'input'); + $cek = random_bytes(32); + self::useCalculator(new NativeCalculator()); + $start = self::cpuTime(); + + $verified = (new PS256())->verify($key->toPublic(), 'input', $signature); + $additionalHeader = []; + $encryptedKey = (new RSAOAEP256())->encryptKey($key->toPublic(), $cek, [], $additionalHeader); + $elapsed = self::cpuTime() - $start; + self::useCalculator(null); + + static::assertTrue($verified); + static::assertLessThan(1, $elapsed); + static::assertSame($cek, (new RSAOAEP256())->decryptKey($key, $encryptedKey, [])); + } + private static function key(int $modulusLength, int $exponentLength): JWK { return new JWK([ From cf84b60b474a2663fbdbb5e01c4a601db9ba5d8f Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 10:20:05 +0100 Subject: [PATCH 23/32] Compute the RSA private operation with OpenSSL RSA-OAEP, RSA-OAEP-256 and RSA1_5 decryption raised the encrypted key to the private exponent with brick/math. The sender of a token chooses that encrypted key, and the key it is encrypted to is public, so anyone could make an application pay for a private key operation with each token: with an RSA-2048 key, about 130 s in pure PHP and 0.12 s with BCMath, against 3 ms with GMP. RSAKey::applyPrivateKey() now computes input^d mod n with OpenSSL (OPENSSL_NO_PADDING) when the extension is loaded, and with brick/math otherwise. The key is handed to OpenSSL by its members through openssl_pkey_new(), so a key without its CRT members works as before, and OpenSSL blinds the operation. A forged token now costs about 2 ms with any calculator. The padding checks stay in PHP and are unchanged. An input as large as the modulus still raises a RuntimeException, now with a message. --- src/Library/Core/Util/RSAKey.php | 84 +++++++++++++++++++ .../Algorithm/KeyEncryption/Util/RSACrypt.php | 39 +-------- tests/Component/Core/Util/RSAKeyTest.php | 71 ++++++++++++++++ 3 files changed, 157 insertions(+), 37 deletions(-) diff --git a/src/Library/Core/Util/RSAKey.php b/src/Library/Core/Util/RSAKey.php index d4f77582..acb8c935 100644 --- a/src/Library/Core/Util/RSAKey.php +++ b/src/Library/Core/Util/RSAKey.php @@ -45,6 +45,26 @@ final class RSAKey */ private const RSA_ALGORITHM_IDENTIFIER = "\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00"; + /** + * The members of a private key, as openssl_pkey_new() names them. + */ + private const OPENSSL_MEMBERS = [ + 'n' => 'n', + 'e' => 'e', + 'd' => 'd', + ]; + + /** + * The CRT members, handed to OpenSSL only when all of them are present, as exponentiate() uses them. + */ + private const OPENSSL_CRT_MEMBERS = [ + 'p' => 'p', + 'q' => 'q', + 'dp' => 'dmp1', + 'dq' => 'dmq1', + 'qi' => 'iqmp', + ]; + private null|Sequence $sequence = null; private readonly array $values; @@ -232,6 +252,38 @@ public static function applyPublicKey(self $key, string $input): string return $output; } + /** + * Computes input^d mod n (RSADP, RSASP1) on big-endian strings as long as the modulus. OpenSSL computes it, blinded, + * when the extension is loaded, so that the cost does not depend on the brick/math calculator: without GMP, the + * private key operation took minutes in pure PHP, for every token the sender of which chooses the input. The key is + * handed to OpenSSL by its members, so a key without its CRT members is accepted as before. + */ + public static function applyPrivateKey(self $key, string $input): string + { + if (strlen($input) !== $key->getModulusLength()) { + throw new RuntimeException('The input must be as long as the modulus.'); + } + if (! extension_loaded('openssl')) { + $output = self::exponentiate($key, BigInteger::createFromBinaryString($input))->toBytes(); + + return str_pad($output, $key->getModulusLength(), "\0", STR_PAD_LEFT); + } + $privateKey = openssl_pkey_new([ + 'rsa' => $key->toOpenSSLMembers(), + ]); + $output = ''; + if ($privateKey === false || ! openssl_private_decrypt( + $input, + $output, + $privateKey, + OPENSSL_NO_PADDING + ) || ! is_string($output)) { + throw new RuntimeException('Unable to apply the private key.'); + } + + return $output; + } + /** * Exponentiate with or without Chinese Remainder Theorem. Operation with primes 'p' and 'q' is appox. 2x faster. * @@ -321,6 +373,38 @@ private function populatePrivateBigIntegers(): void $this->privateBigIntegersPopulated = true; } + /** + * @return array + */ + private function toOpenSSLMembers(): array + { + $members = $this->decodeMembers(self::OPENSSL_MEMBERS); + $crtMembers = $this->decodeMembers(self::OPENSSL_CRT_MEMBERS); + if (count($crtMembers) === count(self::OPENSSL_CRT_MEMBERS)) { + $members += $crtMembers; + } + + return $members; + } + + /** + * @param array $names + * + * @return array + */ + private function decodeMembers(array $names): array + { + $members = []; + foreach ($names as $member => $name) { + $value = $this->values[$member] ?? null; + if (is_string($value)) { + $members[$name] = Base64UrlSafe::decodeNoPadding($value); + } + } + + return $members; + } + private function getMemberLength(string $member): int { $value = Base64UrlSafe::decodeNoPadding($this->values[$member]); diff --git a/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php b/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php index 1d5a058e..8d2e2022 100644 --- a/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php +++ b/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php @@ -5,7 +5,6 @@ namespace Jose\Component\Encryption\Algorithm\KeyEncryption\Util; use InvalidArgumentException; -use Jose\Component\Core\Util\BigInteger; use Jose\Component\Core\Util\Hash; use Jose\Component\Core\Util\RSAKey; use LogicException; @@ -93,9 +92,7 @@ public static function decryptWithRSA15(RSAKey $key, string $c, ?int $expectedKe if (strlen($c) !== $key->getModulusLength()) { throw new InvalidArgumentException('Unable to decrypt'); } - $c = BigInteger::createFromBinaryString($c); - $m = self::getRSADP($key, $c); - $em = self::convertIntegerToOctetString($m, $key->getModulusLength()); + $em = RSAKey::applyPrivateKey($key, $c); if ($expectedKeyLength === null) { if (ord($em[0]) !== 0 || ord($em[1]) > 2) { throw new InvalidArgumentException('Unable to decrypt'); @@ -203,36 +200,6 @@ public static function decryptWithRSAOAEP(RSAKey $key, string $ciphertext, strin ); } - private static function convertIntegerToOctetString(BigInteger $x, int $xLen): string - { - $x = $x->toBytes(); - if (strlen($x) > $xLen) { - throw new RuntimeException('Invalid length.'); - } - - return str_pad($x, $xLen, chr(0), STR_PAD_LEFT); - } - - /** - * Octet-String-to-Integer primitive. - */ - private static function convertOctetStringToInteger(string $x): BigInteger - { - return BigInteger::createFromBinaryString($x); - } - - /** - * RSA DP. - */ - private static function getRSADP(RSAKey $key, BigInteger $c): BigInteger - { - if ($c->compare(BigInteger::createFromDecimal(0)) < 0 || $c->compare($key->getModulus()) >= 0) { - throw new RuntimeException(); - } - - return RSAKey::exponentiate($key, $c); - } - /** * MGF1. */ @@ -272,9 +239,7 @@ private static function encryptRSAESOAEP(RSAKey $key, string $m, Hash $hash): st */ private static function getRSAESOAEP(RSAKey $key, string $c, Hash $hash): string { - $c = self::convertOctetStringToInteger($c); - $m = self::getRSADP($key, $c); - $em = self::convertIntegerToOctetString($m, $key->getModulusLength()); + $em = RSAKey::applyPrivateKey($key, $c); $lHash = $hash->hash(''); $maskedSeed = substr($em, 1, $hash->getLength()); $maskedDB = substr($em, $hash->getLength() + 1); diff --git a/tests/Component/Core/Util/RSAKeyTest.php b/tests/Component/Core/Util/RSAKeyTest.php index f8c16f44..ed4651ba 100644 --- a/tests/Component/Core/Util/RSAKeyTest.php +++ b/tests/Component/Core/Util/RSAKeyTest.php @@ -19,6 +19,8 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; +use function array_flip; +use function array_intersect_key; use function chr; use function ord; use function sprintf; @@ -208,6 +210,75 @@ public static function nonRepresentatives(): iterable ]; } + /** + * @param list $members + */ + #[Test] + #[DataProvider('privateKeyMembers')] + public function thePrivateOperationIsTheModularExponentiationOfTheInput(array $members): void + { + [$key, $values] = self::generateKey(2048); + $modulus = $values['n']; + $public = RSAKey::createFromJWK($key->toPublic()); + $private = RSAKey::createFromJWK(new JWK(array_intersect_key($key->all(), array_flip(['kty', ...$members])))); + + foreach ([ + str_repeat("\0", 256), + str_repeat("\0", 255) . "\1", + substr($modulus, 0, -1) . chr(ord($modulus[-1]) - 1), + "\0" . random_bytes(255), + "\0" . random_bytes(255), + ] as $input) { + $expected = RSAKey::exponentiate($private, BigInteger::createFromBinaryString($input))->toBytes(); + $expected = str_pad($expected, 256, "\0", STR_PAD_LEFT); + + static::assertSame($expected, RSAKey::applyPrivateKey($private, $input)); + static::assertSame($input, RSAKey::applyPublicKey($public, RSAKey::applyPrivateKey($private, $input))); + } + } + + /** + * @return iterable}> + */ + public static function privateKeyMembers(): iterable + { + yield 'every member' => [['n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi']]; + yield 'without the CRT members' => [['n', 'e', 'd']]; + yield 'with only some of the CRT members' => [['n', 'e', 'd', 'p', 'q']]; + } + + /** + * @param callable(string): string $input + */ + #[Test] + #[DataProvider('nonRepresentatives')] + public function aValueThatIsNotARepresentativeIsRejectedByThePrivateKey(callable $input): void + { + [$key, $members] = self::generateKey(2048); + + $this->expectException(RuntimeException::class); + + RSAKey::applyPrivateKey(RSAKey::createFromJWK($key), $input($members['n'])); + } + + #[Test] + public function rsaOaepDecryptionDoesNotDependOnTheCalculator(): void + { + [$key] = self::generateKey(4096); + $cek = random_bytes(32); + $additionalHeader = []; + $encryptedKey = (new RSAOAEP256())->encryptKey($key->toPublic(), $cek, [], $additionalHeader); + self::useCalculator(new NativeCalculator()); + $start = self::cpuTime(); + + $decrypted = (new RSAOAEP256())->decryptKey($key, $encryptedKey, []); + $elapsed = self::cpuTime() - $start; + self::useCalculator(null); + + static::assertSame($cek, $decrypted); + static::assertLessThan(1, $elapsed); + } + #[Test] public function rsaPssVerificationAndRsaOaepEncryptionDoNotDependOnTheCalculator(): void { From d57870159d432cad30ca04dc31c5412389aa16c9 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 10:33:44 +0100 Subject: [PATCH 24/32] Sign with RSA-PSS through OpenSSL PS256, PS384 and PS512 signing applied the private key with brick/math: with an RSA-2048 key, about 125 s per signature in pure PHP and 0.15 s with BCMath. It now goes through RSAKey::applyPrivateKey(), like RSA-OAEP and RSA1_5 decryption, and costs a few milliseconds with any calculator. The signatures are the same: only the RSA primitive moves to OpenSSL. --- src/Library/Signature/Algorithm/Util/RSA.php | 16 +--------------- tests/Component/Core/Util/RSAKeyTest.php | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/Library/Signature/Algorithm/Util/RSA.php b/src/Library/Signature/Algorithm/Util/RSA.php index df3b1149..0fa29c2a 100644 --- a/src/Library/Signature/Algorithm/Util/RSA.php +++ b/src/Library/Signature/Algorithm/Util/RSA.php @@ -5,7 +5,6 @@ namespace Jose\Component\Signature\Algorithm\Util; use InvalidArgumentException; -use Jose\Component\Core\Util\BigInteger; use Jose\Component\Core\Util\Hash; use Jose\Component\Core\Util\RSAKey; use RuntimeException; @@ -14,7 +13,6 @@ use function extension_loaded; use function ord; use function strlen; -use const STR_PAD_LEFT; /** * @internal @@ -64,9 +62,7 @@ public static function sign(RSAKey $key, string $message, string $hash, int $mod public static function signWithPSS(RSAKey $key, string $message, string $hash): string { $em = self::encodeEMSAPSS($message, 8 * $key->getModulusLength() - 1, Hash::get($hash)); - $message = BigInteger::createFromBinaryString($em); - $signature = RSAKey::exponentiate($key, $message); - $result = self::convertIntegerToOctetString($signature, $key->getModulusLength()); + $result = RSAKey::applyPrivateKey($key, $em); if ($result === '') { throw new InvalidArgumentException('Invalid signature.'); } @@ -114,16 +110,6 @@ public static function verifyWithPSS( return self::verifyEMSAPSS($message, $em, $modBits - 1, Hash::get($hash)); } - private static function convertIntegerToOctetString(BigInteger $x, int $xLen): string - { - $x = $x->toBytes(); - if (strlen($x) > $xLen) { - throw new RuntimeException(); - } - - return str_pad($x, $xLen, chr(0), STR_PAD_LEFT); - } - /** * MGF1. */ diff --git a/tests/Component/Core/Util/RSAKeyTest.php b/tests/Component/Core/Util/RSAKeyTest.php index ed4651ba..01d8234b 100644 --- a/tests/Component/Core/Util/RSAKeyTest.php +++ b/tests/Component/Core/Util/RSAKeyTest.php @@ -279,6 +279,21 @@ public function rsaOaepDecryptionDoesNotDependOnTheCalculator(): void static::assertLessThan(1, $elapsed); } + #[Test] + public function rsaPssSigningDoesNotDependOnTheCalculator(): void + { + [$key] = self::generateKey(4096); + self::useCalculator(new NativeCalculator()); + $start = self::cpuTime(); + + $signature = (new PS256())->sign($key, 'input'); + $elapsed = self::cpuTime() - $start; + self::useCalculator(null); + + static::assertTrue((new PS256())->verify($key->toPublic(), 'input', $signature)); + static::assertLessThan(1, $elapsed); + } + #[Test] public function rsaPssVerificationAndRsaOaepEncryptionDoNotDependOnTheCalculator(): void { From 3c980dd2fe2a409e6d7338b277c6119887a55110 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 10:40:08 +0100 Subject: [PATCH 25/32] ci: add to the PHPStan baseline the four errors reported on 4.3.x whatever the change The Static Analysis job fails on 4.3.x for reasons outside the code: - PHPStan 2.3.7, shipped by the phpqa image since its rebuild of 2026-11-20, reports a mixed value as the condition of the ternaries of the processHeaders() methods of JSONFlattenedSerializer and JSONGeneralSerializer and of the if of MixedPublicAndPrivateKeys, as on 4.2.x (4029d7e6); - symfony/dependency-injection 8.2.0 declares the $config argument of ContainerBuilder::prependExtensionConfig() as array, while ConfigurationHelper::updateJoseConfiguration() passes an array. The baseline, generated by castor phpstan-baseline with the current image, gains those four entries and nothing else. --- .ci-tools/phpstan-baseline.neon | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/.ci-tools/phpstan-baseline.neon b/.ci-tools/phpstan-baseline.neon index 605db95d..f096c8c5 100644 --- a/.ci-tools/phpstan-baseline.neon +++ b/.ci-tools/phpstan-baseline.neon @@ -4818,6 +4818,12 @@ parameters: count: 1 path: ../src/Bundle/Helper/ConfigurationHelper.php + - + rawMessage: 'Parameter #2 $config of method Symfony\Component\DependencyInjection\ContainerBuilder::prependExtensionConfig() expects array, array given.' + identifier: argument.type + count: 1 + path: ../src/Bundle/Helper/ConfigurationHelper.php + - rawMessage: 'Parameter #2 ...$arrays of function array_merge expects array, mixed given.' identifier: argument.type @@ -5998,6 +6004,12 @@ parameters: count: 1 path: ../src/Library/Encryption/Serializer/JSONFlattenedSerializer.php + - + rawMessage: 'Only booleans are allowed in a ternary operator condition, mixed given.' + identifier: ternary.condNotBoolean + count: 1 + path: ../src/Library/Encryption/Serializer/JSONFlattenedSerializer.php + - rawMessage: 'Parameter #1 $encodedString of static method Jose\Component\Core\Util\Base64UrlSafe::decodeNoPadding() expects string, mixed given.' identifier: argument.type @@ -6064,6 +6076,12 @@ parameters: count: 1 path: ../src/Library/Encryption/Serializer/JSONGeneralSerializer.php + - + rawMessage: 'Only booleans are allowed in a ternary operator condition, mixed given.' + identifier: ternary.condNotBoolean + count: 1 + path: ../src/Library/Encryption/Serializer/JSONGeneralSerializer.php + - rawMessage: 'Parameter #1 $encodedString of static method Jose\Component\Core\Util\Base64UrlSafe::decodeNoPadding() expects string, mixed given.' identifier: argument.type @@ -6142,6 +6160,12 @@ parameters: count: 1 path: ../src/Library/KeyManagement/Analyzer/MixedPublicAndPrivateKeys.php + - + rawMessage: 'Only booleans are allowed in an if condition, mixed given.' + identifier: if.condNotBoolean + count: 1 + path: ../src/Library/KeyManagement/Analyzer/MixedPublicAndPrivateKeys.php + - rawMessage: 'Parameter #2 ...$values of function sprintf expects bool|float|int|string|null, mixed given.' identifier: argument.type From d65a08ed6ec49d3eabb16bc352462d6939cbd66a Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 10:10:10 +0100 Subject: [PATCH 26/32] fix(encryption): check the size of an AES-GCM wrapped key before unwrapping it A128GCMKW, A192GCMKW and A256GCMKW hand the whole encrypted key to openssl_decrypt(), which decrypts it before checking the authentication tag, for every key of the key set. The size check added for the AES Key Wrap algorithms skipped them, so a token with an encrypted key of any size was rejected only after work and memory proportional to that size. AES-GCM key wrapping returns as many bytes as it wraps, its tag being the "tag" header parameter: JWEDecrypter now compares the size of the encrypted key with the CEK size before calling these algorithms. The tokens it rejects are the ones it already rejected, either because the tag did not match or because the unwrapped key had the wrong size: only the failure passed to the callable of decrypt() and chained by the loaders changes. Reported by inanna-malick, as a follow-up of ANT-2026-GFP863VS. --- src/Library/Encryption/JWEDecrypter.php | 20 ++++++++++++------- .../AESKeyWrapEncryptedKeySizeTest.php | 7 +++++-- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/Library/Encryption/JWEDecrypter.php b/src/Library/Encryption/JWEDecrypter.php index 208831bd..76ed8d53 100644 --- a/src/Library/Encryption/JWEDecrypter.php +++ b/src/Library/Encryption/JWEDecrypter.php @@ -17,6 +17,7 @@ use Jose\Component\Core\Util\KeyChecker; use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithm; use Jose\Component\Encryption\Algorithm\KeyEncryption\AbstractECDHAESKW; +use Jose\Component\Encryption\Algorithm\KeyEncryption\AESGCMKW; use Jose\Component\Encryption\Algorithm\KeyEncryption\AESKW; use Jose\Component\Encryption\Algorithm\KeyEncryption\DirectEncryption; use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyAgreement; @@ -321,21 +322,26 @@ private function checkCekSize( } /** - * AES Key Wrap adds 64 bits to the key it wraps. Any other size is rejected before the key derivation, the key - * agreement and the unwrapping, which processes the whole encrypted key before checking its integrity. + * AES Key Wrap adds 64 bits to the key it wraps. AES-GCM key wrapping adds nothing, its authentication tag being + * the "tag" header parameter. Any other size is rejected before the key derivation, the key agreement and the + * unwrapping, which processes the whole encrypted key before checking its integrity, once per key of the key set. */ private function checkWrappedKeySize( KeyEncryptionAlgorithm $keyEncryptionAlgorithm, Recipient $recipient, ContentEncryptionAlgorithm $contentEncryptionAlgorithm ): void { - if (! $keyEncryptionAlgorithm instanceof AESKW - && ! $keyEncryptionAlgorithm instanceof PBES2AESKW - && ! $keyEncryptionAlgorithm instanceof AbstractECDHAESKW - ) { + $addedSize = match (true) { + $keyEncryptionAlgorithm instanceof AESGCMKW => 0, + $keyEncryptionAlgorithm instanceof AESKW, + $keyEncryptionAlgorithm instanceof PBES2AESKW, + $keyEncryptionAlgorithm instanceof AbstractECDHAESKW => 64, + default => null, + }; + if ($addedSize === null) { return; } - if (strlen($recipient->getEncryptedKey() ?? '') * 8 !== $contentEncryptionAlgorithm->getCEKSize() + 64) { + if (strlen($recipient->getEncryptedKey() ?? '') * 8 !== $contentEncryptionAlgorithm->getCEKSize() + $addedSize) { throw new InvalidArgumentException('Invalid encrypted key size'); } } diff --git a/tests/Component/Encryption/AESKeyWrapEncryptedKeySizeTest.php b/tests/Component/Encryption/AESKeyWrapEncryptedKeySizeTest.php index e81ed704..dfbaebb1 100644 --- a/tests/Component/Encryption/AESKeyWrapEncryptedKeySizeTest.php +++ b/tests/Component/Encryption/AESKeyWrapEncryptedKeySizeTest.php @@ -166,6 +166,9 @@ public static function dataAlgorithms(): iterable yield 'ECDH-ES+A256KW' => ['ECDH-ES+A256KW', 'A256CBC-HS512']; yield 'ECDH-SS+A128KW' => ['ECDH-SS+A128KW', 'A192GCM']; yield 'ECDH-SS+A256KW' => ['ECDH-SS+A256KW', 'A256GCM']; + yield 'A128GCMKW' => ['A128GCMKW', 'A128CBC-HS256']; + yield 'A192GCMKW' => ['A192GCMKW', 'A192GCM']; + yield 'A256GCMKW' => ['A256GCMKW', 'A256CBC-HS512']; } public static function dataKeyAgreementAlgorithms(): iterable @@ -245,8 +248,8 @@ private static function decryptionKeys(string $alg): array private static function sharedKey(string $alg): JWK { $size = match ($alg) { - 'A128KW' => 16, - 'A192KW' => 24, + 'A128KW', 'A128GCMKW' => 16, + 'A192KW', 'A192GCMKW' => 24, default => 32, }; From 144a8e790591640c996da2aad8ec5d54eb2b88b2 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 10:12:16 +0100 Subject: [PATCH 27/32] fix(encryption): deprecate deriving the passwords of a key set beyond the PBES2 cap JWEDecrypter tries the keys of a key set one after the other and derives each password with the iteration count of the token. The PBES2 cap bounds one derivation, and since the recipients of a token share it, one recipient tried with one key: a recipient at the cap tried with a key set holding N passwords costs N derivations at the cap. Deriving more iterations in total than the share of a recipient with the keys of a key set is now deprecated. From 5.0.0, the passwords tried for a recipient share that part of the cap, and the ones beyond it are not tried. Only the keys that are derived count: keys of another type, and keys rejected for their usage or their algorithm, are left out, so a key set holding one password next to other keys keeps the whole share. Nothing is rejected: the tokens decrypted before are still decrypted. Reported by inanna-malick, as a follow-up of ANT-2026-P0RDGIIJ. --- src/Library/Encryption/JWEDecrypter.php | 45 ++++++++++ .../Encryption/PBES2IterationCountTest.php | 88 +++++++++++++++++++ 2 files changed, 133 insertions(+) diff --git a/src/Library/Encryption/JWEDecrypter.php b/src/Library/Encryption/JWEDecrypter.php index 208831bd..f239110f 100644 --- a/src/Library/Encryption/JWEDecrypter.php +++ b/src/Library/Encryption/JWEDecrypter.php @@ -29,6 +29,7 @@ use SensitiveParameter; use Throwable; use function func_num_args; +use function in_array; use function intdiv; use function is_callable; use function is_int; @@ -220,6 +221,7 @@ private function decryptRecipientKey( $this->checkIvSize($jwe->getIV(), $content_encryption_algorithm->getIVSize()); + $iterations = 0; foreach ($jwkset->all() as $recipientKey) { try { if ($key_encryption_algorithm instanceof KeyAgreement @@ -234,6 +236,13 @@ private function decryptRecipientKey( KeyChecker::checkKeyAlgorithm($recipientKey, $content_encryption_algorithm->name()); } $this->checkIterationCount($key_encryption_algorithm, $completeHeader, $jwe->countRecipients()); + $iterations = $this->countIterations( + $key_encryption_algorithm, + $recipientKey, + $completeHeader, + $jwe->countRecipients(), + $iterations + ); $cek = $this->decryptCEK( $key_encryption_algorithm, $content_encryption_algorithm, @@ -364,6 +373,42 @@ private function checkIterationCount( } } + /** + * The keys of a key set are tried one after the other, and each password is derived with the iteration count of + * the token: a recipient at the cap costs as many derivations as the key set holds passwords. From 5.0.0, the + * passwords tried for a recipient share its part of the cap, and the ones beyond it are not tried. Only the keys + * that are derived are counted: keys of another type, and keys rejected for their usage or their algorithm, are not. + * + * @param array $completeHeader + */ + private function countIterations( + KeyEncryptionAlgorithm $keyEncryptionAlgorithm, + JWK $key, + array $completeHeader, + int $recipientCount, + int $iterations + ): int { + $count = $completeHeader['p2c'] ?? null; + if (! $keyEncryptionAlgorithm instanceof PBES2AESKW + || ! is_int($count) + || ! in_array($key->get('kty'), $keyEncryptionAlgorithm->allowedKeyTypes(), true) + ) { + return $iterations; + } + $maxCount = intdiv($keyEncryptionAlgorithm->getMaxCount(), $recipientCount); + if ($iterations <= $maxCount && $iterations + $count > $maxCount) { + trigger_deprecation( + 'web-token/jwt-library', + '4.3.0', + 'Trying more than %d iterations of "%s" in total with the keys of a key set for one recipient is deprecated: from 5.0.0, the keys share the maximum iteration count of the algorithm and the next ones are not tried. Raise that maximum to keep trying them.', + $maxCount, + $keyEncryptionAlgorithm->name() + ); + } + + return $iterations + $count; + } + private function checkIvSize(?string $iv, int $requiredIvSize): void { if ($iv === null && $requiredIvSize !== 0) { diff --git a/tests/Component/Encryption/PBES2IterationCountTest.php b/tests/Component/Encryption/PBES2IterationCountTest.php index 4ebfcb52..6180ce0a 100644 --- a/tests/Component/Encryption/PBES2IterationCountTest.php +++ b/tests/Component/Encryption/PBES2IterationCountTest.php @@ -7,11 +7,14 @@ use ArrayObject; use Jose\Component\Core\AlgorithmManager; use Jose\Component\Core\JWK; +use Jose\Component\Core\JWKSet; use Jose\Component\Core\Util\Base64UrlSafe; +use Jose\Component\Core\Util\ECKey; use Jose\Component\Core\Util\JsonConverter; use Jose\Component\Encryption\Algorithm\ContentEncryption\A128GCM; use Jose\Component\Encryption\Algorithm\KeyEncryption\PBES2AESKW; use Jose\Component\Encryption\Algorithm\KeyEncryption\PBES2HS256A128KW; +use Jose\Component\Encryption\DecryptionResult; use Jose\Component\Encryption\JWEBuilder; use Jose\Component\Encryption\JWEDecrypter; use Jose\Component\Encryption\JWELoader; @@ -19,6 +22,11 @@ use PHPUnit\Framework\Attributes\Test; use RuntimeException; use stdClass; +use function array_fill; +use function array_map; +use function intdiv; +use function sprintf; +use const E_USER_DEPRECATED; /** * @internal @@ -108,6 +116,65 @@ public static function dataIterationCounts(): iterable yield 'three recipients above a third of the cap' => [3, 3_334, false]; } + /** + * The first recipient of the token is encrypted for the key named "right" of the key set. + * + * @param list $keys + */ + #[DataProvider('dataKeySets')] + #[Test] + public function thePasswordsOfAKeySetTriedBeyondTheCapAreDeprecated( + int $recipients, + int $count, + array $keys, + bool $deprecated + ): void { + $password = $this->createPassword(); + $token = $this->createToken(new PBES2HS256A128KW(16, $count), array_fill(0, $recipients, $password)); + $keySet = new JWKSet(array_map(fn (string $key): JWK => match ($key) { + 'right' => $password, + 'wrong' => $this->createPassword(), + 'EC' => ECKey::createECKey('P-256'), + default => new JWK([ + 'kty' => 'oct', + ($key === 'sig' ? 'use' : 'alg') => $key, + 'k' => Base64UrlSafe::encodeUnpadded(random_bytes(32)), + ]), + }, $keys)); + $jweDecrypter = new JWEDecrypter(new AlgorithmManager([ + new CountingPBES2HS256A128KW(new ArrayObject(), 10_000), + new A128GCM(), + ]), null); + $jwe = $this->getJWESerializerManager() + ->unserialize($token); + + $result = null; + $deprecations = $this->collectDeprecations(static function () use ($jweDecrypter, $jwe, $keySet, &$result): void { + $result = $jweDecrypter->decrypt($jwe, $keySet, 0); + }); + + static::assertInstanceOf(DecryptionResult::class, $result); + static::assertTrue($result->isDecrypted()); + static::assertSame('Live long and prosper.', $result->getJwe()->getPayload()); + static::assertSame($deprecated ? [sprintf( + 'Since web-token/jwt-library 4.3.0: Trying more than %d iterations of "PBES2-HS256+A128KW" in total with the keys of a key set for one recipient is deprecated: from 5.0.0, the keys share the maximum iteration count of the algorithm and the next ones are not tried. Raise that maximum to keep trying them.', + intdiv(10_000, $recipients) + )] : [], $deprecations); + } + + public static function dataKeySets(): iterable + { + yield 'two passwords within the cap' => [1, 5_000, ['wrong', 'right'], false]; + yield 'two passwords beyond the cap' => [1, 5_001, ['wrong', 'right'], true]; + yield 'ten passwords within the cap' => [1, 1_000, [...array_fill(0, 9, 'wrong'), 'right'], false]; + yield 'six passwords beyond the cap' => [1, 4_000, [...array_fill(0, 5, 'wrong'), 'right'], true]; + yield 'two passwords at the cap before a third one' => [1, 5_000, ['wrong', 'wrong', 'right'], true]; + yield 'decrypted by the first password' => [1, 6_000, ['right', 'wrong'], false]; + yield 'keys that are not derived' => [1, 6_000, ['EC', 'HS256', 'sig', 'right'], false]; + yield 'two recipients within their share' => [2, 2_500, ['wrong', 'right'], false]; + yield 'two recipients beyond their share' => [2, 2_501, ['wrong', 'right'], true]; + } + /** * @param JWK[] $passwords */ @@ -135,4 +202,25 @@ private function createPassword(): JWK 'k' => Base64UrlSafe::encodeUnpadded(random_bytes(32)), ]); } + + /** + * @return list + */ + private function collectDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $errno, string $errstr) use (&$deprecations): bool { + $deprecations[] = $errstr; + + return true; + }, E_USER_DEPRECATED); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } } From 382f6e1edbd44fc97991c757f48ecbf2eb11e5d0 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 10:59:15 +0100 Subject: [PATCH 28/32] ci: add to the PHPStan baseline the error symfony/dependency-injection 8.2 reports on 4.2.x symfony/dependency-injection 8.2.0 declares the $config argument of ContainerBuilder::prependExtensionConfig() as array, while ConfigurationHelper::updateJoseConfiguration() passes an array. The Static Analysis job therefore fails on 4.2.x whatever the change, and the tests it gates are skipped. 4.3.x got the same entry in #832. The baseline, generated by castor phpstan-baseline with the current image, gains that entry and nothing else. --- .ci-tools/phpstan-baseline.neon | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.ci-tools/phpstan-baseline.neon b/.ci-tools/phpstan-baseline.neon index a7cae84f..d9928035 100644 --- a/.ci-tools/phpstan-baseline.neon +++ b/.ci-tools/phpstan-baseline.neon @@ -3906,6 +3906,12 @@ parameters: count: 1 path: ../src/Bundle/Helper/ConfigurationHelper.php + - + rawMessage: 'Parameter #2 $config of method Symfony\Component\DependencyInjection\ContainerBuilder::prependExtensionConfig() expects array, array given.' + identifier: argument.type + count: 1 + path: ../src/Bundle/Helper/ConfigurationHelper.php + - rawMessage: 'Parameter #2 ...$arrays of function array_merge expects array, mixed given.' identifier: argument.type From 8d4d0dde8ff3b164e0173635fc8bab4e9224ed33 Mon Sep 17 00:00:00 2001 From: lav45 Date: Tue, 10 Nov 2026 19:17:45 +0300 Subject: [PATCH 29/32] fix(okp): refuse the Ed25519 public keys of small order without sodium OpenSSL loads an Ed25519 public key whose point is of small order, and with the neutral point as key it verifies the signature R = the neutral point, S = 0 for any input. Without ext-sodium, AbstractEdDSA::verify() goes through OKPKey::verifyWithOpenSSL(), so Ed25519 and EdDSA accepted such a forged signature. With sodium, sodium_crypto_sign_verify_detached() refuses it. OKPKey::isSmallOrderEd25519Point() compares "x", sign bit cleared, with the 7 encodings libsodium refuses (ge25519_has_small_order()): the 8 points of order 1, 2, 4 and 8 and the non-canonical encodings of y = 0 and y = 1. It needs no extension. verifyWithOpenSSL() returns false for such a key, and OKPKeyAnalyzer reports it whichever backend is loaded. --- src/Library/Core/Util/OKPKey.php | 28 +++++++++++ .../KeyManagement/Analyzer/OKPKeyAnalyzer.php | 18 +++++-- tests/Component/Core/Util/OKPKeyTest.php | 47 +++++++++++++++++++ .../KeyManagement/OKPKeyAnalyzerTest.php | 27 +++++++++++ .../EdDSA/FullySpecifiedEdDSATest.php | 15 ++++++ 5 files changed, 130 insertions(+), 5 deletions(-) diff --git a/src/Library/Core/Util/OKPKey.php b/src/Library/Core/Util/OKPKey.php index a025dd64..9a02d78f 100644 --- a/src/Library/Core/Util/OKPKey.php +++ b/src/Library/Core/Util/OKPKey.php @@ -21,10 +21,13 @@ use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RFC8410\Curve448\Ed448PublicKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RFC8410\Curve448\X448PrivateKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RFC8410\Curve448\X448PublicKey; +use function bin2hex; +use function chr; use function extension_loaded; use function in_array; use function is_array; use function is_string; +use function ord; use function sprintf; use function strlen; use const PHP_VERSION_ID; @@ -61,6 +64,16 @@ self::CURVE_X448 => 56, ]; + private const ED25519_SMALL_ORDER_POINTS = [ + '0000000000000000000000000000000000000000000000000000000000000000', // y = 0, order 4 + '0100000000000000000000000000000000000000000000000000000000000000', // y = 1, order 1 + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', // order 8 + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', // order 8 + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p - 1, order 2 + 'edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p, order 4 + 'eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p + 1, order 1 + ]; + /** * The OpenSSL key type of each curve, as numbered by ext-openssl. The OPENSSL_KEYTYPE_* constants only exist * since PHP 8.4, which is also the first version able to use them. @@ -98,6 +111,16 @@ public static function supportsSodium(string $curve): bool return extension_loaded('sodium') && in_array($curve, [self::CURVE_ED25519, self::CURVE_X25519], true); } + public static function isSmallOrderEd25519Point(string $x): bool + { + if (strlen($x) !== self::KEY_SIZES[self::CURVE_ED25519]) { + return false; + } + $x[31] = chr(ord($x[31]) & 0x7F); + + return in_array(bin2hex($x), self::ED25519_SMALL_ORDER_POINTS, true); + } + /** * Tells whether the given curve can be used on this platform, with either backend. */ @@ -175,6 +198,11 @@ public static function signWithOpenSSL(JWK $privateKey, string $input): string */ public static function verifyWithOpenSSL(JWK $publicKey, #[SensitiveParameter] string $input, string $signature): bool { + $curve = self::getParameter($publicKey, 'crv'); + $x = Base64UrlSafe::decodeNoPadding(self::getParameter($publicKey, 'x')); + if ($curve === self::CURVE_ED25519 && self::isSmallOrderEd25519Point($x)) { + return false; + } $key = openssl_pkey_get_public(self::convertPublicKeyToPEM($publicKey)); if ($key === false) { throw new InvalidKeyException('Unable to load the public key.'); diff --git a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php index 4b0a4306..4d21289d 100644 --- a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php @@ -45,28 +45,36 @@ public function analyze(JWK $jwk, MessageBag $bag): void return; } - $this->checkComponentSize($jwk, 'x', OKPKey::KEY_SIZES[$crv], $bag); + $x = $this->decodeComponent($jwk, 'x', OKPKey::KEY_SIZES[$crv], $bag); + if ($x !== null && $crv === OKPKey::CURVE_ED25519 && OKPKey::isSmallOrderEd25519Point($x)) { + $bag->add(Message::high('Invalid key. The point of the Ed25519 public key is of small order.')); + } if ($jwk->has('d')) { - $this->checkComponentSize($jwk, 'd', OKPKey::KEY_SIZES[$crv], $bag); + $this->decodeComponent($jwk, 'd', OKPKey::KEY_SIZES[$crv], $bag); } $this->checkAlgorithm($jwk, $crv, $bag); } - private function checkComponentSize(JWK $jwk, string $component, int $size, MessageBag $bag): void + private function decodeComponent(JWK $jwk, string $component, int $size, MessageBag $bag): ?string { $value = $jwk->find($component); if (! is_string($value)) { $bag->add(Message::high(sprintf('Invalid key. The component "%s" shall be a string.', $component))); - return; + return null; } - if (strlen(Base64UrlSafe::decodeNoPadding($value)) !== $size) { + $value = Base64UrlSafe::decodeNoPadding($value); + if (strlen($value) !== $size) { $bag->add(Message::high(sprintf( 'Invalid key. The component "%s" size shall be %d bytes.', $component, $size ))); + + return null; } + + return $value; } private function checkAlgorithm(JWK $jwk, string $crv, MessageBag $bag): void diff --git a/tests/Component/Core/Util/OKPKeyTest.php b/tests/Component/Core/Util/OKPKeyTest.php index 51438503..bbe716d0 100644 --- a/tests/Component/Core/Util/OKPKeyTest.php +++ b/tests/Component/Core/Util/OKPKeyTest.php @@ -116,6 +116,53 @@ public function ed25519SignedWithOpenSSLMatchesTheRfc8037Vector(): void static::assertFalse(OKPKey::verifyWithOpenSSL($key->toPublic(), $input, substr($signature, 0, 63))); } + /** + * @return iterable + */ + public static function ed25519PointsOfSmallOrder(): iterable + { + yield 'y = 0, order 4' => ['0000000000000000000000000000000000000000000000000000000000000000']; + yield 'y = 1, order 1' => ['0100000000000000000000000000000000000000000000000000000000000000']; + yield 'order 8' => ['26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05']; + yield 'order 8, other y' => ['c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a']; + yield 'y = p - 1, order 2' => ['ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f']; + yield 'y = p, order 4' => ['edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f']; + yield 'y = p + 1, order 1' => ['eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f']; + yield 'order 8, sign bit set' => ['26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85']; + yield 'y = 1, sign bit set' => ['0100000000000000000000000000000000000000000000000000000000000080']; + } + + #[Test] + #[DataProvider('ed25519PointsOfSmallOrder')] + public function anEd25519PointOfSmallOrderIsRecognized(string $x): void + { + static::assertTrue(OKPKey::isSmallOrderEd25519Point(hex2bin($x))); + } + + #[Test] + public function theRfc8037Ed25519PublicKeyIsNotOfSmallOrder(): void + { + $x = Base64UrlSafe::decodeNoPadding(self::rfc8037Key()->getString('x')); + + static::assertFalse(OKPKey::isSmallOrderEd25519Point($x)); + static::assertFalse(OKPKey::isSmallOrderEd25519Point("\x01" . str_repeat("\0", 30))); + } + + #[Test] + public function aSignatureWithAnEd25519KeyOfSmallOrderIsNotVerifiedWithOpenSSL(): void + { + $this->requireOpenSSL(); + $neutralPoint = "\x01" . str_repeat("\0", 31); + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded($neutralPoint), + ]); + $signature = $neutralPoint . str_repeat("\0", 32); + + static::assertFalse(OKPKey::verifyWithOpenSSL($key, 'any input', $signature)); + } + #[Test] public function ed25519SignaturesMadeWithOpenSSLAndSodiumAreInterchangeable(): void { diff --git a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php index 9847ae10..d0da4c4b 100644 --- a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php +++ b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php @@ -15,6 +15,7 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use function sprintf; +use function str_repeat; /** * @internal @@ -109,6 +110,32 @@ public function aNonStringComponentIsReported(): void ); } + /** + * @return iterable + */ + public static function ed25519PointsOfSmallOrder(): iterable + { + yield 'neutral point, order 1' => ["\x01" . str_repeat("\0", 31)]; + yield 'y = 0, order 4' => [str_repeat("\0", 32)]; + yield 'y = -1, order 2' => ["\xec" . str_repeat("\xff", 30) . "\x7f"]; + } + + #[Test] + #[DataProvider('ed25519PointsOfSmallOrder')] + public function anEd25519KeyOfSmallOrderIsReported(string $x): void + { + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded($x), + ]); + + static::assertSame( + ['high: Invalid key. The point of the Ed25519 public key is of small order.'], + self::analyze(new OKPKeyAnalyzer(), $key) + ); + } + /** * @return iterable}> */ diff --git a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php index eb0c7a2f..ff68416e 100644 --- a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php +++ b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php @@ -167,6 +167,21 @@ public function aTruncatedOrTamperedEd25519SignatureIsFalse(): void static::assertFalse($algorithm->verify($key, 'payload', $tampered)); } + #[Test] + #[DataProvider('ed25519Algorithms')] + public function aSignatureWithAnEd25519KeyOfSmallOrderIsFalse(SignatureAlgorithm $algorithm): void + { + $neutralPoint = "\x01" . str_repeat("\0", 31); + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded($neutralPoint), + ]); + $signature = $neutralPoint . str_repeat("\0", 32); + + static::assertFalse($algorithm->verify($key, 'payload', $signature)); + } + #[Test] public function ed25519RefusesAnEd448Key(): void { From a1a5c83cc9df1a175ccbbc88c8e611a751a017c4 Mon Sep 17 00:00:00 2001 From: lav45 Date: Tue, 10 Nov 2026 19:51:48 +0300 Subject: [PATCH 30/32] fix(key-mgmt): report an Ed25519 key whose "x" is no valid public key OKPKeyAnalyzer only checked the size of "x" and the points of small order, so an Ed25519 key whose "x" decodes to no point of the curve raised no message, while every signature verification with it fails. OKPKey::isValidEd25519PublicKey() uses sodium when it is loaded: sodium_crypto_sign_ed25519_pk_to_curve25519() also requires the point to be in the prime-order subgroup. Without sodium, OKPKey::isEd25519Point() decodes "x" as RFC 8032 section 5.1.3 does, with brick/math: y lower than p and (y^2 - 1) / (d y^2 + 1) a square modulo p. A point outside the prime-order subgroup is then only reported with sodium. The tests build the "x" of a well-formed Ed25519 key from the RFC 8037 key, as random bytes are a point of the curve only half of the time. --- src/Library/Core/Util/OKPKey.php | 50 +++++++++++++++++++ .../KeyManagement/Analyzer/OKPKeyAnalyzer.php | 16 +++++- tests/Component/Core/Util/OKPKeyTest.php | 50 +++++++++++++++++++ .../KeyManagement/OKPKeyAnalyzerTest.php | 39 ++++++++++++++- 4 files changed, 152 insertions(+), 3 deletions(-) diff --git a/src/Library/Core/Util/OKPKey.php b/src/Library/Core/Util/OKPKey.php index 9a02d78f..26268da5 100644 --- a/src/Library/Core/Util/OKPKey.php +++ b/src/Library/Core/Util/OKPKey.php @@ -4,12 +4,14 @@ namespace Jose\Component\Core\Util; +use Brick\Math\BigInteger; use Jose\Component\Core\Exception\InvalidKeyException; use Jose\Component\Core\Exception\MissingDependencyException; use Jose\Component\Core\Exception\RuntimeException; use Jose\Component\Core\Exception\UnsupportedCurveException; use Jose\Component\Core\JWK; use SensitiveParameter; +use SodiumException; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKeyInfo; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKey; @@ -30,6 +32,7 @@ use function ord; use function sprintf; use function strlen; +use function strrev; use const PHP_VERSION_ID; /** @@ -74,6 +77,10 @@ 'eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', // y = p + 1, order 1 ]; + private const ED25519_PRIME = '57896044618658097711785492504343953926634992332820282019728792003956564819949'; // 2^255 - 19 + + private const ED25519_D = '37095705934669439343138083508754565189542113879843219016388785533085940283555'; // -121665 / 121666 + /** * The OpenSSL key type of each curve, as numbered by ext-openssl. The OPENSSL_KEYTYPE_* constants only exist * since PHP 8.4, which is also the first version able to use them. @@ -121,6 +128,49 @@ public static function isSmallOrderEd25519Point(string $x): bool return in_array(bin2hex($x), self::ED25519_SMALL_ORDER_POINTS, true); } + public static function isEd25519Point(string $x): bool + { + if (strlen($x) !== self::KEY_SIZES[self::CURVE_ED25519]) { + return false; + } + $isXOdd = (ord($x[31]) & 0x80) !== 0; + $x[31] = chr(ord($x[31]) & 0x7F); + $p = BigInteger::of(self::ED25519_PRIME); + $y = BigInteger::fromBase(bin2hex(strrev($x)), 16); + if ($y->isGreaterThanOrEqualTo($p)) { + return false; + } + $ySquare = $y->power(2) + ->mod($p); + $u = $ySquare->minus(1) + ->mod($p); + $v = BigInteger::of(self::ED25519_D)->multipliedBy($ySquare) + ->plus(1) + ->mod($p); + $xSquare = $u->multipliedBy($v->modPow($p->minus(2), $p)) + ->mod($p); + if ($xSquare->isZero()) { + return ! $isXOdd; + } + + return $xSquare->modPow($p->minus(1)->dividedBy(2), $p) + ->isEqualTo(1); + } + + public static function isValidEd25519PublicKey(string $x): bool + { + if (! self::supportsSodium(self::CURVE_ED25519)) { + return self::isEd25519Point($x) && ! self::isSmallOrderEd25519Point($x); + } + try { + sodium_crypto_sign_ed25519_pk_to_curve25519($x); + } catch (SodiumException) { + return false; + } + + return true; + } + /** * Tells whether the given curve can be used on this platform, with either backend. */ diff --git a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php index 4d21289d..1693ad2a 100644 --- a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php @@ -46,8 +46,8 @@ public function analyze(JWK $jwk, MessageBag $bag): void return; } $x = $this->decodeComponent($jwk, 'x', OKPKey::KEY_SIZES[$crv], $bag); - if ($x !== null && $crv === OKPKey::CURVE_ED25519 && OKPKey::isSmallOrderEd25519Point($x)) { - $bag->add(Message::high('Invalid key. The point of the Ed25519 public key is of small order.')); + if ($x !== null && $crv === OKPKey::CURVE_ED25519) { + $this->checkEd25519Point($x, $bag); } if ($jwk->has('d')) { $this->decodeComponent($jwk, 'd', OKPKey::KEY_SIZES[$crv], $bag); @@ -77,6 +77,18 @@ private function decodeComponent(JWK $jwk, string $component, int $size, Message return $value; } + private function checkEd25519Point(string $x, MessageBag $bag): void + { + if (OKPKey::isSmallOrderEd25519Point($x)) { + $bag->add(Message::high('Invalid key. The point of the Ed25519 public key is of small order.')); + + return; + } + if (! OKPKey::isValidEd25519PublicKey($x)) { + $bag->add(Message::high('Invalid key. The point is not a valid Ed25519 public key.')); + } + } + private function checkAlgorithm(JWK $jwk, string $crv, MessageBag $bag): void { $alg = $jwk->find('alg'); diff --git a/tests/Component/Core/Util/OKPKeyTest.php b/tests/Component/Core/Util/OKPKeyTest.php index bbe716d0..ff1b0829 100644 --- a/tests/Component/Core/Util/OKPKeyTest.php +++ b/tests/Component/Core/Util/OKPKeyTest.php @@ -148,6 +148,56 @@ public function theRfc8037Ed25519PublicKeyIsNotOfSmallOrder(): void static::assertFalse(OKPKey::isSmallOrderEd25519Point("\x01" . str_repeat("\0", 30))); } + #[Test] + public function theRfc8037Ed25519PublicKeyIsAPoint(): void + { + $x = Base64UrlSafe::decodeNoPadding(self::rfc8037Key()->getString('x')); + + static::assertTrue(OKPKey::isEd25519Point($x)); + } + + /** + * @return iterable + */ + public static function ed25519Encodings(): iterable + { + yield 'y = 1, x = 0' => ['0100000000000000000000000000000000000000000000000000000000000000', true]; + yield 'y = 0' => ['0000000000000000000000000000000000000000000000000000000000000000', true]; + yield 'y = p - 1, x = 0' => ['ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', true]; + yield 'order 8, sign bit set' => ['26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', true]; + yield 'y = 2' => ['0200000000000000000000000000000000000000000000000000000000000000', false]; + yield 'y = p' => ['edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', false]; + yield 'y = 1, x = 0 with the sign bit set' => [ + '0100000000000000000000000000000000000000000000000000000000000080', + false, + ]; + yield 'too short' => ['01000000000000000000000000000000000000000000000000000000000000', false]; + } + + #[Test] + #[DataProvider('ed25519Encodings')] + public function anEd25519EncodingIsAPointOnlyWhenItDecodes(string $x, bool $expected): void + { + static::assertSame($expected, OKPKey::isEd25519Point(hex2bin($x))); + } + + #[Test] + public function anEd25519PublicKeyIsValidWhenItIsAPointNotOfSmallOrder(): void + { + $rfc8037 = Base64UrlSafe::decodeNoPadding(self::rfc8037Key()->getString('x')); + $mixedOrder = hex2bin('9c94cb2663e2140be35aafbbcc90981dc72785ea5e9046d19a3e770c3b8fba79'); + + static::assertTrue(OKPKey::isEd25519Point($mixedOrder)); + static::assertTrue(OKPKey::isValidEd25519PublicKey($rfc8037)); + static::assertFalse(OKPKey::isValidEd25519PublicKey("\x01" . str_repeat("\0", 31))); + static::assertFalse(OKPKey::isValidEd25519PublicKey("\x02" . str_repeat("\0", 31))); + static::assertFalse(OKPKey::isValidEd25519PublicKey("\x01" . str_repeat("\0", 30))); + static::assertSame( + ! OKPKey::supportsSodium(OKPKey::CURVE_ED25519), + OKPKey::isValidEd25519PublicKey($mixedOrder) + ); + } + #[Test] public function aSignatureWithAnEd25519KeyOfSmallOrderIsNotVerifiedWithOpenSSL(): void { diff --git a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php index d0da4c4b..b61389cd 100644 --- a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php +++ b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php @@ -136,6 +136,38 @@ public function anEd25519KeyOfSmallOrderIsReported(string $x): void ); } + #[Test] + public function anEd25519KeyThatIsNoPointIsReported(): void + { + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded("\x02" . str_repeat("\0", 31)), + ]); + + static::assertSame( + ['high: Invalid key. The point is not a valid Ed25519 public key.'], + self::analyze(new OKPKeyAnalyzer(), $key) + ); + } + + #[Test] + public function anEd25519KeyOutsideThePrimeOrderSubgroupIsReportedWithSodiumOnly(): void + { + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed25519', + 'x' => Base64UrlSafe::encodeUnpadded( + hex2bin('9c94cb2663e2140be35aafbbcc90981dc72785ea5e9046d19a3e770c3b8fba79') + ), + ]); + $expected = OKPKey::supportsSodium(OKPKey::CURVE_ED25519) + ? ['high: Invalid key. The point is not a valid Ed25519 public key.'] + : []; + + static::assertSame($expected, self::analyze(new OKPKeyAnalyzer(), $key)); + } + /** * @return iterable}> */ @@ -233,10 +265,15 @@ private static function analyze(KeyAnalyzer $analyzer, JWK $key): array private static function key(string $curve, int $xSize, int $dSize): JWK { + $x = Base64UrlSafe::encodeUnpadded(random_bytes($xSize)); + if ($curve === OKPKey::CURVE_ED25519 && $xSize === OKPKey::KEY_SIZES[$curve]) { + $x = '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo'; // RFC 8037 appendix A.1 + } + return new JWK([ 'kty' => 'OKP', 'crv' => $curve, - 'x' => Base64UrlSafe::encodeUnpadded(random_bytes($xSize)), + 'x' => $x, 'd' => Base64UrlSafe::encodeUnpadded(random_bytes($dSize)), ]); } From a7f5644e051b34bda98eaeccabf831453b7f5047 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 12:18:13 +0100 Subject: [PATCH 31/32] fix(okp): refuse the Ed448 public keys of small order OpenSSL accepts a forged Ed448 signature for a public key of order 4: with "x" the encoding of y = 0 (x = 1 or -1), the signature R = that point, S = 0 verifies for any input, on OpenSSL 3.5 and 4.1. Ed448 has no sodium backend, so the Ed448 algorithm accepted it whatever the extensions loaded. OKPKey::isSmallOrderEd448Point() compares "x", sign bit cleared, with the encodings of y = 0, 1 and p - 1 and the non-canonical encodings of y = 0 and y = 1. verifyWithOpenSSL() returns false for such a key, and OKPKeyAnalyzer reports it. --- src/Library/Core/Util/OKPKey.php | 24 +++++++- .../KeyManagement/Analyzer/OKPKeyAnalyzer.php | 3 + tests/Component/Core/Util/OKPKeyTest.php | 57 +++++++++++++++++++ .../KeyManagement/OKPKeyAnalyzerTest.php | 25 ++++++++ .../EdDSA/FullySpecifiedEdDSATest.php | 15 +++++ 5 files changed, 122 insertions(+), 2 deletions(-) diff --git a/src/Library/Core/Util/OKPKey.php b/src/Library/Core/Util/OKPKey.php index 26268da5..ddabbf27 100644 --- a/src/Library/Core/Util/OKPKey.php +++ b/src/Library/Core/Util/OKPKey.php @@ -81,6 +81,14 @@ private const ED25519_D = '37095705934669439343138083508754565189542113879843219016388785533085940283555'; // -121665 / 121666 + private const ED448_SMALL_ORDER_POINTS = [ + '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', // y = 0, order 4 + '010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', // y = 1, order 1 + 'fefffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff00', // y = p - 1, order 2 + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff00', // y = p, order 4 + '00000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00', // y = p + 1, order 1 + ]; + /** * The OpenSSL key type of each curve, as numbered by ext-openssl. The OPENSSL_KEYTYPE_* constants only exist * since PHP 8.4, which is also the first version able to use them. @@ -128,6 +136,16 @@ public static function isSmallOrderEd25519Point(string $x): bool return in_array(bin2hex($x), self::ED25519_SMALL_ORDER_POINTS, true); } + public static function isSmallOrderEd448Point(string $x): bool + { + if (strlen($x) !== self::KEY_SIZES[self::CURVE_ED448]) { + return false; + } + $x[56] = chr(ord($x[56]) & 0x7F); + + return in_array(bin2hex($x), self::ED448_SMALL_ORDER_POINTS, true); + } + public static function isEd25519Point(string $x): bool { if (strlen($x) !== self::KEY_SIZES[self::CURVE_ED25519]) { @@ -244,13 +262,15 @@ public static function signWithOpenSSL(JWK $privateKey, string $input): string /** * Verifies the signature of the input with the public key, with OpenSSL (PureEdDSA, RFC 8032). Needs PHP 8.4, - * see supportsOpenSSL(). A malformed signature is false, not an exception. + * see supportsOpenSSL(). A malformed signature is false, not an exception. A public key of small order is + * false too: OpenSSL accepts a forged signature for it. */ public static function verifyWithOpenSSL(JWK $publicKey, #[SensitiveParameter] string $input, string $signature): bool { $curve = self::getParameter($publicKey, 'crv'); $x = Base64UrlSafe::decodeNoPadding(self::getParameter($publicKey, 'x')); - if ($curve === self::CURVE_ED25519 && self::isSmallOrderEd25519Point($x)) { + if (($curve === self::CURVE_ED25519 && self::isSmallOrderEd25519Point($x)) + || ($curve === self::CURVE_ED448 && self::isSmallOrderEd448Point($x))) { return false; } $key = openssl_pkey_get_public(self::convertPublicKeyToPEM($publicKey)); diff --git a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php index 1693ad2a..c9c07eaa 100644 --- a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php @@ -49,6 +49,9 @@ public function analyze(JWK $jwk, MessageBag $bag): void if ($x !== null && $crv === OKPKey::CURVE_ED25519) { $this->checkEd25519Point($x, $bag); } + if ($x !== null && $crv === OKPKey::CURVE_ED448 && OKPKey::isSmallOrderEd448Point($x)) { + $bag->add(Message::high('Invalid key. The point of the Ed448 public key is of small order.')); + } if ($jwk->has('d')) { $this->decodeComponent($jwk, 'd', OKPKey::KEY_SIZES[$crv], $bag); } diff --git a/tests/Component/Core/Util/OKPKeyTest.php b/tests/Component/Core/Util/OKPKeyTest.php index ff1b0829..27677c59 100644 --- a/tests/Component/Core/Util/OKPKeyTest.php +++ b/tests/Component/Core/Util/OKPKeyTest.php @@ -213,6 +213,63 @@ public function aSignatureWithAnEd25519KeyOfSmallOrderIsNotVerifiedWithOpenSSL() static::assertFalse(OKPKey::verifyWithOpenSSL($key, 'any input', $signature)); } + /** + * @return iterable + */ + public static function ed448PointsOfSmallOrder(): iterable + { + yield 'y = 0, order 4' => [str_repeat('00', 57)]; + yield 'y = 0, sign bit set' => [str_repeat('00', 56) . '80']; + yield 'y = 1, order 1' => ['01' . str_repeat('00', 56)]; + yield 'y = 1, sign bit set' => ['01' . str_repeat('00', 55) . '80']; + yield 'y = p - 1, order 2' => ['fe' . str_repeat('ff', 27) . 'fe' . str_repeat('ff', 27) . '00']; + yield 'y = p, order 4' => [str_repeat('ff', 28) . 'fe' . str_repeat('ff', 27) . '00']; + yield 'y = p + 1, order 1' => [str_repeat('00', 28) . str_repeat('ff', 28) . '00']; + } + + #[Test] + #[DataProvider('ed448PointsOfSmallOrder')] + public function anEd448PointOfSmallOrderIsRecognized(string $x): void + { + static::assertTrue(OKPKey::isSmallOrderEd448Point(hex2bin($x))); + } + + #[Test] + public function theRfc8032Ed448PublicKeyIsNotOfSmallOrder(): void + { + $x = hex2bin( + '5fd7449b59b461fd2ce787ec616ad46a1da1342485a70e1f8a0ea75d80e96778edf124769b46c7061bd6783df1e50f6cd1fa1abeafe8256180' + ); + + static::assertFalse(OKPKey::isSmallOrderEd448Point($x)); + static::assertFalse(OKPKey::isSmallOrderEd448Point(str_repeat("\0", 56) . "\x01")); + static::assertFalse(OKPKey::isSmallOrderEd448Point(str_repeat("\0", 56))); + } + + /** + * @return iterable + */ + public static function ed448KeysOfOrder4(): iterable + { + yield 'x = -1, y = 0' => [str_repeat("\0", 57)]; + yield 'x = 1, y = 0' => [str_repeat("\0", 56) . "\x80"]; + } + + #[Test] + #[DataProvider('ed448KeysOfOrder4')] + public function aSignatureWithAnEd448KeyOfSmallOrderIsNotVerifiedWithOpenSSL(string $x): void + { + $this->requireOpenSSL(); + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed448', + 'x' => Base64UrlSafe::encodeUnpadded($x), + ]); + $signature = $x . str_repeat("\0", 57); + + static::assertFalse(OKPKey::verifyWithOpenSSL($key, 'any input', $signature)); + } + #[Test] public function ed25519SignaturesMadeWithOpenSSLAndSodiumAreInterchangeable(): void { diff --git a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php index b61389cd..29fc4301 100644 --- a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php +++ b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php @@ -168,6 +168,31 @@ public function anEd25519KeyOutsideThePrimeOrderSubgroupIsReportedWithSodiumOnly static::assertSame($expected, self::analyze(new OKPKeyAnalyzer(), $key)); } + /** + * @return iterable + */ + public static function ed448PointsOfSmallOrder(): iterable + { + yield 'neutral point, order 1' => ["\x01" . str_repeat("\0", 56)]; + yield 'x = 1, y = 0, order 4' => [str_repeat("\0", 56) . "\x80"]; + } + + #[Test] + #[DataProvider('ed448PointsOfSmallOrder')] + public function anEd448KeyOfSmallOrderIsReported(string $x): void + { + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed448', + 'x' => Base64UrlSafe::encodeUnpadded($x), + ]); + + static::assertSame( + ['high: Invalid key. The point of the Ed448 public key is of small order.'], + self::analyze(new OKPKeyAnalyzer(), $key) + ); + } + /** * @return iterable}> */ diff --git a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php index ff68416e..bf35da38 100644 --- a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php +++ b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php @@ -182,6 +182,21 @@ public function aSignatureWithAnEd25519KeyOfSmallOrderIsFalse(SignatureAlgorithm static::assertFalse($algorithm->verify($key, 'payload', $signature)); } + #[Test] + public function aSignatureWithAnEd448KeyOfSmallOrderIsFalse(): void + { + $this->requireEd448(); + $pointOfOrder4 = str_repeat("\0", 57); + $key = new JWK([ + 'kty' => 'OKP', + 'crv' => 'Ed448', + 'x' => Base64UrlSafe::encodeUnpadded($pointOfOrder4), + ]); + $signature = $pointOfOrder4 . str_repeat("\0", 57); + + static::assertFalse((new Ed448())->verify($key, 'payload', $signature)); + } + #[Test] public function ed25519RefusesAnEd448Key(): void { From d63ca5b8f0ce3e59d2ecdecb505824c45fd34e14 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sun, 29 Nov 2026 12:29:41 +0100 Subject: [PATCH 32/32] fix(okp): decode an Ed25519 point with a single exponentiation isEd25519Point() inverted v by Fermat and then raised u / v to (p - 1) / 2: two modPow on 255-bit numbers, 8.4 s with the native calculator of brick/math. As v = d y^2 + 1 is never zero, u / v is a square exactly when u * v is one: the inversion goes away and the call takes half the time. isValidEd25519PublicKey() checks the points of small order before decoding "x", and its docblock says that the prime-order subgroup is only checked with sodium. The comment of the test helper moves to its docblock. --- src/Library/Core/Util/OKPKey.php | 16 ++++++++++++---- .../KeyManagement/OKPKeyAnalyzerTest.php | 5 ++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/Library/Core/Util/OKPKey.php b/src/Library/Core/Util/OKPKey.php index 26268da5..f7905e79 100644 --- a/src/Library/Core/Util/OKPKey.php +++ b/src/Library/Core/Util/OKPKey.php @@ -128,6 +128,10 @@ public static function isSmallOrderEd25519Point(string $x): bool return in_array(bin2hex($x), self::ED25519_SMALL_ORDER_POINTS, true); } + /** + * Decodes "x" as RFC 8032 section 5.1.3 does. As v is never zero, u / v is a square exactly when u * v is one, + * which spares an inversion. + */ public static function isEd25519Point(string $x): bool { if (strlen($x) !== self::KEY_SIZES[self::CURVE_ED25519]) { @@ -147,20 +151,24 @@ public static function isEd25519Point(string $x): bool $v = BigInteger::of(self::ED25519_D)->multipliedBy($ySquare) ->plus(1) ->mod($p); - $xSquare = $u->multipliedBy($v->modPow($p->minus(2), $p)) + $uv = $u->multipliedBy($v) ->mod($p); - if ($xSquare->isZero()) { + if ($uv->isZero()) { return ! $isXOdd; } - return $xSquare->modPow($p->minus(1)->dividedBy(2), $p) + return $uv->modPow($p->minus(1)->dividedBy(2), $p) ->isEqualTo(1); } + /** + * Tells whether "x" is a point of the curve that is not of small order. With sodium, the point must also be in the + * prime-order subgroup. + */ public static function isValidEd25519PublicKey(string $x): bool { if (! self::supportsSodium(self::CURVE_ED25519)) { - return self::isEd25519Point($x) && ! self::isSmallOrderEd25519Point($x); + return ! self::isSmallOrderEd25519Point($x) && self::isEd25519Point($x); } try { sodium_crypto_sign_ed25519_pk_to_curve25519($x); diff --git a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php index b61389cd..82d6225f 100644 --- a/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php +++ b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php @@ -263,11 +263,14 @@ private static function analyze(KeyAnalyzer $analyzer, JWK $key): array return $messages; } + /** + * A well-formed Ed25519 key takes the "x" of RFC 8037 appendix A.1: random bytes are a point only half of the time. + */ private static function key(string $curve, int $xSize, int $dSize): JWK { $x = Base64UrlSafe::encodeUnpadded(random_bytes($xSize)); if ($curve === OKPKey::CURVE_ED25519 && $xSize === OKPKey::KEY_SIZES[$curve]) { - $x = '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo'; // RFC 8037 appendix A.1 + $x = '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo'; } return new JWK([