diff --git a/.ci-tools/phpstan-baseline.neon b/.ci-tools/phpstan-baseline.neon index fb0eb1078..f096c8c56 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 - @@ -4812,12 +4818,28 @@ 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 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 +4860,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 @@ -5972,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 @@ -6038,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 @@ -6116,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 @@ -6128,6 +6178,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 +6285,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/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 29c1e9010..096e864b5 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 diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml deleted file mode 100644 index 9f9ff7fd0..000000000 --- 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 diff --git a/src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php b/src/Bundle/DependencyInjection/Source/KeyManagement/JKUSource.php index ba20627d0..186ae94fd 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 779f906c1..068f41d29 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/Bundle/Resources/config/Algorithms/encryption_rsa15.php b/src/Bundle/Resources/config/Algorithms/encryption_rsa15.php index 83f61e451..d5dc5fbb9 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 c0a1dc829..0db14f7a1 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/src/Bundle/Resources/config/commands.php b/src/Bundle/Resources/config/commands.php index 52f69ec32..525d7e4a6 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/Bundle/composer.json b/src/Bundle/composer.json index 334d2b337..588bd872d 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 62cd433eb..f081834e6 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" } } diff --git a/src/Library/Console/AddKeyIntoKeysetCommand.php b/src/Library/Console/AddKeyIntoKeysetCommand.php index 9ee995263..fb524036b 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/EcKeyGeneratorCommand.php b/src/Library/Console/EcKeyGeneratorCommand.php index 93002f10f..363125256 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 fffdc2336..cf51b71d7 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 cc724ccb0..b4b5aca3a 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/GetThumbprintCommand.php b/src/Library/Console/GetThumbprintCommand.php index 2be3f3c75..b6bd327d9 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 0b3a00cea..1e8b33eef 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/KeyFileLoaderCommand.php b/src/Library/Console/KeyFileLoaderCommand.php index d868062c7..0ae501447 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/KeysetAnalyzerCommand.php b/src/Library/Console/KeysetAnalyzerCommand.php index 8a4e583f5..b2df75585 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 85d55be1c..bbdeeb3ce 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/MldsaKeyGeneratorCommand.php b/src/Library/Console/MldsaKeyGeneratorCommand.php index 4962d8db0..5bf846944 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 611d9bd6e..8d3800dd6 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 8cbae543b..43748903a 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 720c2b413..24a994447 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 7e9651b45..46975637d 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 d4d4f0f19..7ef1c5f9c 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 2512df62c..120897284 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/OptimizeRsaKeyCommand.php b/src/Library/Console/OptimizeRsaKeyCommand.php index 4cd35aeea..ce3ce0a98 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/P12CertificateLoaderCommand.php b/src/Library/Console/P12CertificateLoaderCommand.php index 356467cc6..8271743e8 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/PemConverterCommand.php b/src/Library/Console/PemConverterCommand.php index 0d0a77591..615df878e 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 4a1b92318..75406c3f9 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 1ca1b4f55..7e8a516e7 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 54e466efd..a85c6fdf2 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 54a3544dd..70c6603a6 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/Console/RsaKeyGeneratorCommand.php b/src/Library/Console/RsaKeyGeneratorCommand.php index c0d16dc1f..05600c4e9 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 771c6f856..e23c609d2 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 f64acdf32..c1ada5e0a 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 4b8dbf902..5676b622c 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/src/Library/Core/Exception/JsonBoundExceededException.php b/src/Library/Core/Exception/JsonBoundExceededException.php new file mode 100644 index 000000000..aff34d2e4 --- /dev/null +++ b/src/Library/Core/Exception/JsonBoundExceededException.php @@ -0,0 +1,14 @@ + 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 de2c24d51..0e5e381a8 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 e4e5b0921..769337b84 100644 --- a/src/Library/Core/Util/BoundedJsonDecoder.php +++ b/src/Library/Core/Util/BoundedJsonDecoder.php @@ -5,16 +5,25 @@ namespace Jose\Component\Core\Util; use Jose\Component\Core\Exception\InvalidArgumentException; +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; /** * 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 JsonBoundExceededException, whose + * message names the bound; the other errors of json_decode() keep the exception of JsonConverter::decode(). + * * @internal */ final class BoundedJsonDecoder @@ -23,14 +32,126 @@ final class BoundedJsonDecoder private int $remainingValues = self::MAX_VALUES; + private bool $exceededMaxDepth = false; + + /** + * @throws JsonBoundExceededException if the document 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. + * @throws InvalidArgumentException if the document is not valid JSON + */ public function decode(#[SensitiveParameter] string $json): mixed { $this->remainingValues -= self::countValues($json); if ($this->remainingValues < 0) { - throw new InvalidArgumentException('Unsupported input.'); + throw new JsonBoundExceededException(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, true); + } catch (InvalidArgumentException $exception) { + if ($exception->getCode() !== JSON_ERROR_DEPTH) { + throw new InvalidArgumentException( + 'Unsupported input.', + $exception->getCode(), + $exception->getPrevious() + ); + } + $this->exceededMaxDepth = true; + throw new JsonBoundExceededException( + 'A JSON document of the token is nested too deeply.', + $exception->getCode(), + $exception->getPrevious() + ); } + } + + /** + * Decodes the JSON serialization of a token. A document that is not valid JSON is not such a serialization: it is + * rejected with an UnrecognizedSerializationException that keeps the message, the code and the previous exception + * of the error. A document beyond a bound is rejected as decode() rejects it. + * + * @throws JsonBoundExceededException if the document goes beyond a bound + * @throws UnrecognizedSerializationException if the document is not valid JSON + */ + public function decodeSerialization(#[SensitiveParameter] string $json): mixed + { + try { + return $this->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. + */ + public function hasExceededMaxDepth(): bool + { + return $this->exceededMaxDepth; + } - 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; + } + + /** + * 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; } /** diff --git a/src/Library/Core/Util/JsonConverter.php b/src/Library/Core/Util/JsonConverter.php index 0c3bd9f2c..f084132d9 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/Core/Util/OKPKey.php b/src/Library/Core/Util/OKPKey.php index a025dd64d..4a977c670 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; @@ -21,12 +23,16 @@ 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 function strrev; use const PHP_VERSION_ID; /** @@ -61,6 +67,28 @@ 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 + ]; + + private const ED25519_PRIME = '57896044618658097711785492504343953926634992332820282019728792003956564819949'; // 2^255 - 19 + + 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. @@ -98,6 +126,77 @@ 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); + } + + 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); + } + + /** + * 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]) { + 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); + $uv = $u->multipliedBy($v) + ->mod($p); + if ($uv->isZero()) { + return ! $isXOdd; + } + + 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::isSmallOrderEd25519Point($x) && self::isEd25519Point($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. */ @@ -171,10 +270,17 @@ 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)) + || ($curve === self::CURVE_ED448 && self::isSmallOrderEd448Point($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/Core/Util/RSAKey.php b/src/Library/Core/Util/RSAKey.php index 8c4948299..f0073aa27 100644 --- a/src/Library/Core/Util/RSAKey.php +++ b/src/Library/Core/Util/RSAKey.php @@ -19,6 +19,7 @@ use function extension_loaded; use function is_string; use function ltrim; +use function min; use function ord; use function sprintf; use function strlen; @@ -31,14 +32,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; /** @@ -46,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; @@ -79,8 +98,7 @@ private function __construct(JWK $data) if ($modulusLength > self::MAX_MODULUS_LENGTH) { throw new InvalidKeyException('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 InvalidKeyException('The key parameter "e" is too long.'); } $this->modulusLength = $modulusLength; @@ -234,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. * @@ -323,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 1d216f71a..ad169eaad 100644 --- a/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php +++ b/src/Library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php @@ -9,7 +9,6 @@ use Jose\Component\Core\Exception\LogicException; use Jose\Component\Core\Exception\RuntimeException; use Jose\Component\Core\Exception\UnsupportedAlgorithmException; -use Jose\Component\Core\Util\BigInteger; use Jose\Component\Core\Util\Hash; use Jose\Component\Core\Util\RSAKey; use SensitiveParameter; @@ -96,9 +95,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'); @@ -218,36 +215,6 @@ public static function decryptWithRSAOAEP(RSAKey $key, string $ciphertext, strin return $plaintext; } - 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. */ @@ -287,9 +254,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/src/Library/Encryption/JWEDecrypter.php b/src/Library/Encryption/JWEDecrypter.php index 208831bd5..a110f7d9b 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; @@ -29,6 +30,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 +222,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 +237,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, @@ -321,21 +331,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'); } } @@ -364,6 +379,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/src/Library/Encryption/Serializer/CompactSerializer.php b/src/Library/Encryption/Serializer/CompactSerializer.php index 3fda53803..1b36a77c1 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 @@ -57,18 +59,22 @@ 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 { $parts = explode('.', $input, 6); if (count($parts) !== 5) { - throw new InvalidSerializationException('Unsupported input'); + throw new UnrecognizedSerializationException('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 +96,16 @@ public function unserialize(string $input): JWE [new Recipient([], $encryptedKey)] ); } catch (Throwable $throwable) { - throw new InvalidSerializationException('Unsupported input', $throwable->getCode(), $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() + : 'Unsupported input', + $throwable->getCode(), + $throwable + ); } } diff --git a/src/Library/Encryption/Serializer/JSONFlattenedSerializer.php b/src/Library/Encryption/Serializer/JSONFlattenedSerializer.php index 65c397a44..9871b2ab5 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 01fe4a0f6..bb3b14433 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 2634f3f29..1955df69f 100644 --- a/src/Library/Encryption/Serializer/JWESerializerManager.php +++ b/src/Library/Encryption/Serializer/JWESerializerManager.php @@ -6,8 +6,11 @@ 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; use function func_num_args; use function sprintf; use function trigger_deprecation; @@ -60,8 +63,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 +95,50 @@ 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, 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 */ 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()); } catch (InvalidArgumentException $invalidArgumentException) { $lastError = $invalidArgumentException; + if (self::goesBackToAJsonBound($invalidArgumentException)) { + $boundError = $invalidArgumentException; + } elseif (! $invalidArgumentException instanceof UnrecognizedSerializationException) { + $recognizedError = $invalidArgumentException; + } continue; } } - throw new InvalidSerializationException('Unsupported input.', 0, $lastError); + throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $recognizedError ?? $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/KeyManagement/Analyzer/ESKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/ESKeyAnalyzer.php index a6edeaca4..5e45586c1 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,10 +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); - if (! $this->getCurve()->contains($xBI, $yBI)) { + $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 (! $curve->contains($xBI, $yBI)) { $bag->add(Message::high('Invalid key. The point is not on the curve.')); } } diff --git a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php index 4b0a43068..c9c07eaa6 100644 --- a/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/OKPKeyAnalyzer.php @@ -45,27 +45,50 @@ 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) { + $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->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 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.')); } } diff --git a/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php b/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php index 7e6c22f5a..ce2ac3bd2 100644 --- a/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php +++ b/src/Library/KeyManagement/Analyzer/RsaAnalyzer.php @@ -4,14 +4,12 @@ namespace Jose\Component\KeyManagement\Analyzer; -use Jose\Component\Core\Exception\InvalidKeyException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\Base64UrlSafe; use Override; -use function is_array; use function is_string; +use function ord; use function strlen; -use const STR_PAD_RIGHT; final readonly class RsaAnalyzer implements KeyAnalyzer { @@ -26,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'); @@ -34,11 +36,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 InvalidKeyException('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) { + $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.')); } } @@ -51,8 +56,13 @@ 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; + } + 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( @@ -65,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/src/Library/KeyManagement/JKUFactory.php b/src/Library/KeyManagement/JKUFactory.php index c21a77550..7f23260fb 100644 --- a/src/Library/KeyManagement/JKUFactory.php +++ b/src/Library/KeyManagement/JKUFactory.php @@ -6,13 +6,16 @@ use Jose\Component\Core\Exception\RuntimeException; use Jose\Component\Core\JWKSet; -use Jose\Component\Core\Util\JsonConverter; 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; @@ -24,7 +27,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 aeef7c2d8..77743836c 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 5ddcc9216..9f28185ad 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, @@ -41,5 +42,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 65c542e38..3ebe2d0b2 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; @@ -23,10 +26,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 * @@ -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 0fc73b026..a7c0d8e41 100644 --- a/src/Library/KeyManagement/X5UFactory.php +++ b/src/Library/KeyManagement/X5UFactory.php @@ -7,16 +7,19 @@ 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; 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; @@ -29,7 +32,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/Library/Signature/Algorithm/Util/RSA.php b/src/Library/Signature/Algorithm/Util/RSA.php index be9940be1..1552c5241 100644 --- a/src/Library/Signature/Algorithm/Util/RSA.php +++ b/src/Library/Signature/Algorithm/Util/RSA.php @@ -8,7 +8,6 @@ use Jose\Component\Core\Exception\MissingDependencyException; use Jose\Component\Core\Exception\RuntimeException; use Jose\Component\Core\Exception\UnsupportedAlgorithmException; -use Jose\Component\Core\Util\BigInteger; use Jose\Component\Core\Util\Hash; use Jose\Component\Core\Util\RSAKey; use SensitiveParameter; @@ -16,7 +15,6 @@ use function extension_loaded; use function ord; use function strlen; -use const STR_PAD_LEFT; /** * @internal @@ -66,9 +64,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.'); } @@ -116,16 +112,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/src/Library/Signature/Serializer/CompactSerializer.php b/src/Library/Signature/Serializer/CompactSerializer.php index 9c98e16a3..65b6052dc 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 @@ -62,18 +64,22 @@ 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 { $parts = explode('.', $input, 4); if (count($parts) !== 3) { - throw new InvalidSerializationException('Unsupported input'); + throw new UnrecognizedSerializationException('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 +99,16 @@ public function unserialize(#[SensitiveParameter] string $input): JWS return $jws->addSignature($signature, $protectedHeader, $encodedProtectedHeader); } catch (Throwable $throwable) { - throw new InvalidSerializationException('Unsupported input', $throwable->getCode(), $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() + : 'Unsupported input', + $throwable->getCode(), + $throwable + ); } } } diff --git a/src/Library/Signature/Serializer/JSONFlattenedSerializer.php b/src/Library/Signature/Serializer/JSONFlattenedSerializer.php index 9895c689c..0ba61f45c 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 73065acb3..0f3026840 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 a9312e3f6..591423580 100644 --- a/src/Library/Signature/Serializer/JWSSerializerManager.php +++ b/src/Library/Signature/Serializer/JWSSerializerManager.php @@ -6,9 +6,12 @@ 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; +use Throwable; use function func_num_args; use function sprintf; use function trigger_deprecation; @@ -59,8 +62,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 +94,50 @@ 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, 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 */ public function unserializeToken(#[SensitiveParameter] string $input): UnserializationResult { $lastError = null; + $boundError = null; + $recognizedError = 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; + } elseif (! $invalidArgumentException instanceof UnrecognizedSerializationException) { + $recognizedError = $invalidArgumentException; + } continue; } } - throw new InvalidSerializationException('Unsupported input.', 0, $lastError); + throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $recognizedError ?? $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/SelectiveDisclosure/Disclosure.php b/src/SelectiveDisclosure/Disclosure.php index 865659cb6..774758777 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; @@ -74,7 +75,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 +95,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 { @@ -111,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 { @@ -123,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 { @@ -138,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)) { @@ -221,15 +226,50 @@ private static function generateSalt(): string } /** - * @throws InvalidArgumentException if the value cannot be serialized as JSON + * 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. 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 */ 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); } + $decoder = new BoundedJsonDecoder(); + try { + $decoder->decode($json); + } catch (InvalidArgumentException $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/src/SelectiveDisclosure/SDJWT.php b/src/SelectiveDisclosure/SDJWT.php index 2eb74a4e8..a44b5b385 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); @@ -545,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 06cf73085..1029690e2 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,14 @@ * 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. 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 */ @@ -78,6 +90,22 @@ */ 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'; + + /** + * 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; /** @@ -113,6 +141,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 +169,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 +217,87 @@ 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) { + $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(); + } 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. + * + * 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 + { + $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, + ]; + $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); + } + } + /** * 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 @@ -200,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 1754b95a5..cd8a50885 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 000000000..338ac5377 --- /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/Bundle/JoseFramework/Functional/KeyManagement/JWKFactoryServiceTest.php b/tests/Bundle/JoseFramework/Functional/KeyManagement/JWKFactoryServiceTest.php index bd52ef162..092fbb834 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/Bundle/JoseFramework/Functional/Rsa15AlgorithmTest.php b/tests/Bundle/JoseFramework/Functional/Rsa15AlgorithmTest.php index 264ee0574..d82ce89bd 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 15dea0d76..d34a4cc94 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 be4707ccd..a1f1d9a24 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 000000000..a50b1e655 --- /dev/null +++ b/tests/Bundle/JoseFramework/TestBundle/Service/DeprecatedNoneConsumer.php @@ -0,0 +1,18 @@ +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')); + } +} diff --git a/tests/Component/Console/LargeJsonInputTest.php b/tests/Component/Console/LargeJsonInputTest.php new file mode 100644 index 000000000..78b9dfdf7 --- /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/BoundedJsonDecoderTest.php b/tests/Component/Core/BoundedJsonDecoderTest.php index ef90c3022..475f0f776 100644 --- a/tests/Component/Core/BoundedJsonDecoderTest.php +++ b/tests/Component/Core/BoundedJsonDecoderTest.php @@ -5,17 +5,26 @@ 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; 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 { @@ -33,16 +42,122 @@ 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()); } } + #[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()); + 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::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 + { + $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 { $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]}'); @@ -66,7 +181,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],"\\\\"]' @@ -84,7 +199,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/Core/JoseExceptionTest.php b/tests/Component/Core/JoseExceptionTest.php index 5141029b7..8936d2085 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; @@ -25,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; @@ -66,12 +68,14 @@ 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, 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/Core/JsonConverterTest.php b/tests/Component/Core/JsonConverterTest.php index 304fa3a88..80b2c62cd 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 000000000..bc7f755fb --- /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/Core/Util/OKPKeyTest.php b/tests/Component/Core/Util/OKPKeyTest.php index 514385031..27677c598 100644 --- a/tests/Component/Core/Util/OKPKeyTest.php +++ b/tests/Component/Core/Util/OKPKeyTest.php @@ -116,6 +116,160 @@ 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 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 + { + $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)); + } + + /** + * @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/Core/Util/RSAKeyTest.php b/tests/Component/Core/Util/RSAKeyTest.php index 0ec2c47dc..5fffb3bdb 100644 --- a/tests/Component/Core/Util/RSAKeyTest.php +++ b/tests/Component/Core/Util/RSAKeyTest.php @@ -19,6 +19,8 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use function array_flip; +use function array_intersect_key; use function chr; use function ord; use function sprintf; @@ -38,17 +40,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 @@ -67,8 +70,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] @@ -205,6 +210,90 @@ 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 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 { diff --git a/tests/Component/Encryption/AESKeyWrapEncryptedKeySizeTest.php b/tests/Component/Encryption/AESKeyWrapEncryptedKeySizeTest.php index e81ed7043..dfbaebb12 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, }; diff --git a/tests/Component/Encryption/JWESerializerManagerTest.php b/tests/Component/Encryption/JWESerializerManagerTest.php new file mode 100644 index 000000000..a054908b5 --- /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/Encryption/JsonValueBoundTest.php b/tests/Component/Encryption/JsonValueBoundTest.php index 6b73b421d..6f14431ef 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; @@ -22,12 +24,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 +55,65 @@ 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); } + /** + * 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( + 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 +133,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 +155,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 +204,118 @@ 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, 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 + */ + 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/Encryption/PBES2IterationCountTest.php b/tests/Component/Encryption/PBES2IterationCountTest.php index 4ebfcb521..6180ce0a8 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; + } } diff --git a/tests/Component/KeyManagement/JWKAnalyzerTest.php b/tests/Component/KeyManagement/JWKAnalyzerTest.php index d455627d6..37fbfe319 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,15 +17,19 @@ 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; 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; /** * @internal @@ -74,6 +81,130 @@ 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 = (new JWKFactory())->ec('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 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 + { + $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 { diff --git a/tests/Component/KeyManagement/LargeJsonDocumentTest.php b/tests/Component/KeyManagement/LargeJsonDocumentTest.php new file mode 100644 index 000000000..04dee13c9 --- /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/OKPKeyAnalyzerTest.php b/tests/Component/KeyManagement/OKPKeyAnalyzerTest.php index 9847ae10b..ecb48cb90 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,89 @@ 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) + ); + } + + #[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 + */ + 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}> */ @@ -204,12 +288,20 @@ 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'; + } + return new JWK([ 'kty' => 'OKP', 'crv' => $curve, - 'x' => Base64UrlSafe::encodeUnpadded(random_bytes($xSize)), + 'x' => $x, 'd' => Base64UrlSafe::encodeUnpadded(random_bytes($dSize)), ]); } diff --git a/tests/Component/KeyManagement/UrlKeySetFactoryTest.php b/tests/Component/KeyManagement/UrlKeySetFactoryTest.php index 3139b7d3c..d78a342ca 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, @@ -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] diff --git a/tests/Component/Signature/JWSSerializerManagerTest.php b/tests/Component/Signature/JWSSerializerManagerTest.php new file mode 100644 index 000000000..2aa2779aa --- /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)); + } +} diff --git a/tests/Component/Signature/JsonValueBoundTest.php b/tests/Component/Signature/JsonValueBoundTest.php index d99d4a622..daf46425f 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; @@ -22,12 +24,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 +55,65 @@ 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); } + /** + * 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( + 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 +131,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 +155,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 +218,124 @@ 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, 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 + */ + 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]'; diff --git a/tests/SelectiveDisclosure/DisclosureTest.php b/tests/SelectiveDisclosure/DisclosureTest.php index b90dd4b62..2d128c3e4 100644 --- a/tests/SelectiveDisclosure/DisclosureTest.php +++ b/tests/SelectiveDisclosure/DisclosureTest.php @@ -20,6 +20,9 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use stdClass; +use function implode; +use function range; +use function str_repeat; use function strlen; use const INF; use const JSON_THROW_ON_ERROR; @@ -31,6 +34,10 @@ final class DisclosureTest extends TestCase { private const MOBIUS = 'WyJfMjZiYzRMVC1hYzZxMktJNmNCVzVlcyIsICJmYW1pbHlfbmFtZSIsICJNw7ZiaXVzIl0'; + 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. */ @@ -199,6 +206,78 @@ 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. 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, + string $message + ): void { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + $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, 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] + #[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. */ @@ -349,8 +428,83 @@ 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)); } + + 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/IssuerBoundsTest.php b/tests/SelectiveDisclosure/IssuerBoundsTest.php new file mode 100644 index 000000000..dbbdb1ffc --- /dev/null +++ b/tests/SelectiveDisclosure/IssuerBoundsTest.php @@ -0,0 +1,444 @@ + '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($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 + * 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 + */ + 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}> + */ + 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 $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 + */ + 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 class($value) implements JsonSerializable { + public function __construct( + private readonly mixed $value + ) { + } + + public function jsonSerialize(): mixed + { + return $this->value; + } + }; + } +} diff --git a/tests/SelectiveDisclosure/JsonValueBoundTest.php b/tests/SelectiveDisclosure/JsonValueBoundTest.php index cc6639835..041511771 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. @@ -61,12 +103,88 @@ 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]; 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( @@ -82,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/SDJWTIssuerTest.php b/tests/SelectiveDisclosure/SDJWTIssuerTest.php index ca87fcd1d..ac6507f3c 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: 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 */ diff --git a/tests/SelectiveDisclosure/SDJWTVerifierTest.php b/tests/SelectiveDisclosure/SDJWTVerifierTest.php index 8308c5475..f89296b73 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 { diff --git a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php index eb0c7a2ff..bf35da38e 100644 --- a/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php +++ b/tests/SignatureAlgorithm/EdDSA/FullySpecifiedEdDSATest.php @@ -167,6 +167,36 @@ 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 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 {