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
9 changes: 9 additions & 0 deletions src/Library/Core/Util/BoundedJsonDecoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ public function decode(#[SensitiveParameter] string $json): mixed
return JsonConverter::decode($json);
}

/**
* Whether the documents given to this decoder hold more than MAX_VALUES values. The document that went beyond the
* bound was rejected before it was decoded, and so are the documents given after it.
*/
public function hasExceededMaxValues(): bool
{
return $this->remainingValues < 0;
}

/**
* Counts the brackets, braces and commas found outside the string literals.
*/
Expand Down
28 changes: 25 additions & 3 deletions src/SelectiveDisclosure/Disclosure.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -113,7 +114,8 @@ public static function forArrayElement(mixed $value, ?string $salt = null): self
* or from an array, and so whether it has the expected number of elements, is checked when the SD-JWT is
* processed.
*
* @throws InvalidSerializationException if the value is not a Disclosure
* @throws InvalidSerializationException if the value is not a Disclosure, if its JSON is nested too deeply, or if
* it holds more than BoundedJsonDecoder::MAX_VALUES JSON values
*/
public static function fromString(string $disclosure): self
{
Expand All @@ -125,7 +127,8 @@ public static function fromString(string $disclosure): self
*
* @internal
*
* @throws InvalidSerializationException if the value is not a Disclosure
* @throws InvalidSerializationException if the value is not a Disclosure, if its JSON is nested too deeply, or if
* its JSON values go beyond the budget of the decoder
*/
public static function parse(string $disclosure, BoundedJsonDecoder $decoder): self
{
Expand All @@ -140,7 +143,7 @@ public static function parse(string $disclosure, BoundedJsonDecoder $decoder): s
try {
$array = $decoder->decode($json);
} catch (Throwable $throwable) {
throw new InvalidSerializationException('The Disclosure is not valid JSON.', 0, $throwable);
throw self::decodingFailure($decoder, $throwable);
}
if (! is_array($array) || ! str_starts_with(ltrim($json, " \t\n\r"), '[')
|| ! in_array(count($array), [2, 3], true)) {
Expand Down Expand Up @@ -222,6 +225,25 @@ private static function generateSalt(): string
return Base64UrlSafe::encodeUnpadded(random_bytes(self::SALT_SIZE));
}

/**
* Why the JSON of a Disclosure was not decoded. The decoder rejects it, before decoding it, when its values and
* those decoded before it by the same decoder go beyond the budget; otherwise, json_decode() rejected it, and
* JsonConverter::decode() gave its exception the code of the JSON error.
*/
private static function decodingFailure(
BoundedJsonDecoder $decoder,
Throwable $throwable
): InvalidSerializationException {
return new InvalidSerializationException(match (true) {
$decoder->hasExceededMaxValues() => sprintf(
'With this Disclosure, there are more than %d JSON values to decode.',
BoundedJsonDecoder::MAX_VALUES
),
$throwable->getCode() === JSON_ERROR_DEPTH => 'The Disclosure is nested too deeply.',
default => 'The Disclosure is not valid JSON.',
}, 0, $throwable);
}

/**
* The JSON is decoded as Disclosure::fromString() decodes it, so that every Disclosure created can be parsed.
*
Expand Down
53 changes: 43 additions & 10 deletions src/SelectiveDisclosure/SDJWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -120,8 +121,10 @@ private function __construct(
* without the "disclosures" and "kb_jwt" header parameters
* @param list<Disclosure> $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
{
Expand Down Expand Up @@ -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
{
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -386,23 +390,52 @@ 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<string, mixed>} the SD-JWT, without Disclosure, and the parameters of the SD-JWT
*/
private static function readJson(string $json, BoundedJsonDecoder $decoder): array
{
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);
Expand Down
42 changes: 42 additions & 0 deletions tests/Component/Core/BoundedJsonDecoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use InvalidArgumentException;
use Jose\Component\Core\Util\BoundedJsonDecoder;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use function intdiv;
Expand Down Expand Up @@ -38,6 +39,47 @@ public function aDocumentBeyondTheBoundIsRejectedBeforeItIsDecoded(): void
}
}

#[Test]
public function theBoundIsExceededOnceADocumentIsRejectedForTheValuesItHolds(): void
{
$json = new BoundedJsonDecoder();
$json->decode('[' . str_repeat('0,', BoundedJsonDecoder::MAX_VALUES - 1) . '0]');

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

try {
$json->decode('[]');
static::fail('The document should have been rejected.');
} catch (InvalidArgumentException) {
}

static::assertTrue($json->hasExceededMaxValues());
}

#[Test]
#[DataProvider('documentsJsonDecodeRejects')]
public function aDocumentJsonDecodeRejectsDoesNotExceedTheBound(string $document): void
{
$json = new BoundedJsonDecoder();

try {
$json->decode($document);
static::fail('The document should have been rejected.');
} catch (InvalidArgumentException) {
}

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

/**
* @return iterable<string, array{string}>
*/
public static function documentsJsonDecodeRejects(): iterable
{
yield 'invalid JSON' => ['[0,'];
yield 'nested too deeply' => [str_repeat('[', 600) . str_repeat(']', 600)];
}

#[Test]
public function nestedContainersAreCounted(): void
{
Expand Down
30 changes: 30 additions & 0 deletions tests/SelectiveDisclosure/DisclosureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use stdClass;
use function implode;
use function range;
use function str_repeat;
use function strlen;
Expand Down Expand Up @@ -415,6 +416,35 @@ public static function malformedDisclosures(): iterable
];
}

/**
* The JSON of these Disclosures is valid: the decoder rejects them for the values they hold or for their depth.
*/
#[Test]
#[DataProvider('disclosuresBeyondTheBoundsOfTheDecoder')]
public function aDisclosureBeyondTheBoundsOfTheDecoderIsRejected(string $json, string $message): void
{
$this->expectException(InvalidSerializationException::class);
$this->expectExceptionMessage($message);
$this->expectExceptionCode(0);

Disclosure::fromString(Base64UrlSafe::encodeUnpadded($json));
}

/**
* @return iterable<string, array{string, string}>
*/
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));
Expand Down
82 changes: 81 additions & 1 deletion tests/SelectiveDisclosure/JsonValueBoundTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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.
Expand Down Expand Up @@ -67,6 +109,44 @@ public static function dataSerializations(): iterable
yield 'JWS JSON serialization' => [true, 1000, 1100];
}

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