|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Jose\Tests\Component\Encryption; |
| 6 | + |
| 7 | +use InvalidArgumentException; |
| 8 | +use Jose\Component\Encryption\Serializer\CompactSerializer; |
| 9 | +use PHPUnit\Framework\Attributes\Test; |
| 10 | +use PHPUnit\Framework\TestCase; |
| 11 | +use function memory_get_peak_usage; |
| 12 | +use function memory_get_usage; |
| 13 | +use function memory_reset_peak_usage; |
| 14 | +use function str_repeat; |
| 15 | + |
| 16 | +/** |
| 17 | + * @internal |
| 18 | + */ |
| 19 | +final class CompactSerializerTest extends TestCase |
| 20 | +{ |
| 21 | + #[Test] |
| 22 | + public function aTokenWithTooManySegmentsIsRejected(): void |
| 23 | + { |
| 24 | + $this->expectException(InvalidArgumentException::class); |
| 25 | + $this->expectExceptionMessage('Unsupported input'); |
| 26 | + |
| 27 | + (new CompactSerializer())->unserialize('eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0.....'); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * A delimiter-heavy token must be rejected without expanding it into one array entry per delimiter. The |
| 32 | + * threshold is deliberately generous: the unbounded split of this input allocates roughly twenty-five times its |
| 33 | + * size, while the bounded one stays proportional to it. |
| 34 | + */ |
| 35 | + #[Test] |
| 36 | + public function aDelimiterHeavyTokenIsRejectedWithoutExhaustingMemory(): void |
| 37 | + { |
| 38 | + $token = str_repeat('.', 2_000_000); |
| 39 | + $serializer = new CompactSerializer(); |
| 40 | + memory_reset_peak_usage(); |
| 41 | + $before = memory_get_usage(); |
| 42 | + |
| 43 | + try { |
| 44 | + $serializer->unserialize($token); |
| 45 | + static::fail('The token should have been rejected.'); |
| 46 | + } catch (InvalidArgumentException $e) { |
| 47 | + static::assertSame('Unsupported input', $e->getMessage()); |
| 48 | + } |
| 49 | + |
| 50 | + static::assertLessThan(8_000_000, memory_get_peak_usage() - $before); |
| 51 | + } |
| 52 | +} |
0 commit comments