Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Library/Core/Exception/JsonBoundExceededException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Jose\Component\Core\Exception;

/**
* Thrown when the JSON documents of a token go beyond the bounds this library decodes: more JSON values than
* BoundedJsonDecoder::MAX_VALUES, or a document nested more deeply than json_decode() reads. The JSON may be valid: the
* token is rejected for its size or its depth, not for its syntax.
*/
class JsonBoundExceededException extends InvalidArgumentException
{
}
16 changes: 9 additions & 7 deletions src/Library/Core/Util/BoundedJsonDecoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Jose\Component\Core\Util;

use Jose\Component\Core\Exception\InvalidArgumentException;
use Jose\Component\Core\Exception\JsonBoundExceededException;
use SensitiveParameter;
use function preg_replace;
use function sprintf;
Expand All @@ -17,8 +18,8 @@
* limits the depth: a document of brackets decodes to a hundred times its size, and colliding member names make it
* quadratic.
*
* A document rejected for the values it holds or for its depth is rejected with a message that names the bound; the
* other errors of json_decode() keep the exception of JsonConverter::decode().
* 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
*/
Expand All @@ -31,15 +32,16 @@ final class BoundedJsonDecoder
private bool $exceededMaxDepth = false;

/**
* @throws InvalidArgumentException if the document is not valid JSON, if it is nested too deeply, or if the
* documents given to this decoder hold more than MAX_VALUES values. The code of
* the exception is that of the JSON error, 0 for the values.
* @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(sprintf(
throw new JsonBoundExceededException(sprintf(
'The JSON documents of the token hold more JSON values than the %d that are decoded.',
self::MAX_VALUES
));
Expand All @@ -51,7 +53,7 @@ public function decode(#[SensitiveParameter] string $json): mixed
throw $exception;
}
$this->exceededMaxDepth = true;
throw new InvalidArgumentException(
throw new JsonBoundExceededException(
'A JSON document of the token is nested too deeply.',
$exception->getCode(),
$exception->getPrevious()
Expand Down
33 changes: 28 additions & 5 deletions src/Library/Encryption/Serializer/JWESerializerManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

use InvalidArgumentException;
use Jose\Component\Core\Exception\InvalidSerializationException;
use Jose\Component\Core\Exception\JsonBoundExceededException;
use Jose\Component\Core\Exception\UnsupportedSerializerException;
use Jose\Component\Encryption\JWE;
use Throwable;
use function func_num_args;
use function sprintf;
use function trigger_deprecation;
Expand Down Expand Up @@ -60,8 +62,8 @@ public function serialize(string $name, JWE $jws, ?int $recipientIndex = null):
/**
* Loads data and return a JWE object. Throws an exception if none of the serializer was able to convert the input.
*
* When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous
* exception, so that the actual reason of the failure remains available to the caller.
* When no serializer is able to convert the input, the exception of one of them is chained as the previous
* exception, as unserializeToken() chains it.
*
* @param string $input A string that represents a JWE
* @param string|null $name the name of the serializer if the input is unserialized. Passing that argument is
Expand Down Expand Up @@ -92,24 +94,45 @@ public function unserialize(string $input, ?string &$name = null): JWE
* Loads data and returns the JWE object it represents, together with the name of the serializer that was able to
* convert it.
*
* When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous
* exception, so that the actual reason of the failure remains available to the caller.
* When no serializer is able to convert the input, the exception of one of them is chained as the previous
* exception, so that the actual reason of the failure remains available to the caller. Only the serializer of the
* format of the input decodes it far enough to reach a bound of the JSON decoder: the last exception that goes back
* to such a bound is chained, and the exception of the last serializer otherwise.
*
* @param string $input A string that represents a JWE
*/
public function unserializeToken(string $input): UnserializationResult
{
$lastError = null;
$boundError = null;
foreach ($this->serializers as $serializer) {
try {
return new UnserializationResult($serializer->unserialize($input), $serializer->name());
} catch (InvalidArgumentException $invalidArgumentException) {
$lastError = $invalidArgumentException;
if (self::goesBackToAJsonBound($invalidArgumentException)) {
$boundError = $invalidArgumentException;
}

continue;
}
}

throw new InvalidSerializationException('Unsupported input.', 0, $lastError);
throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $lastError);
}

/**
* Whether the exception, or one of the exceptions it chains, rejects the input for a bound of the JSON decoder.
*/
private static function goesBackToAJsonBound(?Throwable $throwable): bool
{
while ($throwable !== null) {
if ($throwable instanceof JsonBoundExceededException) {
return true;
}
$throwable = $throwable->getPrevious();
}

return false;
}
}
33 changes: 28 additions & 5 deletions src/Library/Signature/Serializer/JWSSerializerManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@

use InvalidArgumentException;
use Jose\Component\Core\Exception\InvalidSerializationException;
use Jose\Component\Core\Exception\JsonBoundExceededException;
use Jose\Component\Core\Exception\UnsupportedSerializerException;
use Jose\Component\Signature\JWS;
use SensitiveParameter;
use Throwable;
use function func_num_args;
use function sprintf;
use function trigger_deprecation;
Expand Down Expand Up @@ -59,8 +61,8 @@ public function serialize(string $name, JWS $jws, ?int $signatureIndex = null):
/**
* Loads data and return a JWS object.
*
* When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous
* exception, so that the actual reason of the failure remains available to the caller.
* When no serializer is able to convert the input, the exception of one of them is chained as the previous
* exception, as unserializeToken() chains it.
*
* @param string $input A string that represents a JWS
* @param string|null $name the name of the serializer if the input is unserialized. Passing that argument is
Expand Down Expand Up @@ -91,24 +93,45 @@ public function unserialize(#[SensitiveParameter] string $input, ?string &$name
* Loads data and returns the JWS object it represents, together with the name of the serializer that was able to
* convert it.
*
* When no serializer is able to convert the input, the exception thrown by the last one is chained as the previous
* exception, so that the actual reason of the failure remains available to the caller.
* When no serializer is able to convert the input, the exception of one of them is chained as the previous
* exception, so that the actual reason of the failure remains available to the caller. Only the serializer of the
* format of the input decodes it far enough to reach a bound of the JSON decoder: the last exception that goes back
* to such a bound is chained, and the exception of the last serializer otherwise.
*
* @param string $input A string that represents a JWS
*/
public function unserializeToken(#[SensitiveParameter] string $input): UnserializationResult
{
$lastError = null;
$boundError = null;
foreach ($this->serializers as $serializer) {
try {
return new UnserializationResult($serializer->unserialize($input), $serializer->name());
} catch (InvalidArgumentException $invalidArgumentException) {
$lastError = $invalidArgumentException;
if (self::goesBackToAJsonBound($invalidArgumentException)) {
$boundError = $invalidArgumentException;
}

continue;
}
}

throw new InvalidSerializationException('Unsupported input.', 0, $lastError);
throw new InvalidSerializationException('Unsupported input.', 0, $boundError ?? $lastError);
}

/**
* Whether the exception, or one of the exceptions it chains, rejects the input for a bound of the JSON decoder.
*/
private static function goesBackToAJsonBound(?Throwable $throwable): bool
{
while ($throwable !== null) {
if ($throwable instanceof JsonBoundExceededException) {
return true;
}
$throwable = $throwable->getPrevious();
}

return false;
}
}
23 changes: 23 additions & 0 deletions tests/Component/Core/BoundedJsonDecoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Jose\Tests\Component\Core;

use InvalidArgumentException;
use Jose\Component\Core\Exception\JsonBoundExceededException;
use Jose\Component\Core\Util\BoundedJsonDecoder;
use JsonException;
use PHPUnit\Framework\Attributes\DataProvider;
Expand Down Expand Up @@ -100,12 +101,34 @@ public function anInvalidDocumentKeepsTheErrorOfTheJsonConverter(): void
} catch (InvalidArgumentException $e) {
static::assertSame('Unsupported input.', $e->getMessage());
static::assertSame(JSON_ERROR_SYNTAX, $e->getCode());
static::assertNotInstanceOf(JsonBoundExceededException::class, $e);
}

static::assertFalse($json->hasExceededMaxDepth());
static::assertFalse($json->hasExceededMaxValues());
}

/**
* The class of the exception tells the two bounds apart from invalid JSON, whatever its message.
*/
#[Test]
#[DataProvider('documentsBeyondABound')]
public function aDocumentBeyondABoundIsRejectedWithAJsonBoundExceededException(string $document): void
{
$this->expectException(JsonBoundExceededException::class);

(new BoundedJsonDecoder())->decode($document);
}

/**
* @return iterable<string, array{string}>
*/
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
Expand Down
2 changes: 2 additions & 0 deletions tests/Component/Core/JoseExceptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -66,6 +67,7 @@ final class JoseExceptionTest extends TestCase
InvalidPayloadException::class => InvalidArgumentException::class,
InvalidSerializationException::class => InvalidArgumentException::class,
InvalidTokenException::class => RuntimeException::class,
JsonBoundExceededException::class => InvalidArgumentException::class,
JoseLogicException::class => LogicException::class,
MissingDependencyException::class => RuntimeException::class,
MissingPayloadLogicException::class => LogicException::class,
Expand Down
83 changes: 83 additions & 0 deletions tests/Component/Encryption/JsonValueBoundTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
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;
use Jose\Component\Encryption\Serializer\CompactSerializer;
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;
Expand Down Expand Up @@ -73,6 +75,30 @@ public function aTokenNestedTooDeeplyIsRejected(JWESerializer $serializer, strin
$serializer->unserialize($token);
}

/**
* Only the serializer of the format of the token decodes it far enough to reach a bound of the JSON decoder: the
* manager chains its exception, whatever the order of the serializers. Without such an exception, it chains the
* exception of the last serializer.
*
* @param list<JWESerializer> $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(
Expand Down Expand Up @@ -219,6 +245,63 @@ public static function dataTokensNestedTooDeeply(): iterable
];
}

/**
* @return iterable<string, array{list<JWESerializer>, 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<string, array{JWESerializer, string, string}>
*/
Expand Down
Loading
Loading