Skip to content

Commit

Permalink
minor symfony#50853 [Security] random_bytes length should be an int…
Browse files Browse the repository at this point in the history
… greater than 7 (asispts)

This PR was merged into the 5.4 branch.

Discussion
----------

[Security] `random_bytes` length should be an int greater than 7

| Q             | A
| ------------- | ---
| Branch?       | 5.4
| Bug fix?      | yes
| New feature?  | no <!-- please update src/**/CHANGELOG.md files -->
| Deprecations? | no <!-- please update UPGRADE-*.md and src/**/CHANGELOG.md files -->
| Tickets       |
| License       | MIT
| Doc PR        |

`random_bytes` can only accept an `int<1, max>` value.
- See: https://3v4l.org/tHf9P
- See: https://3v4l.org/u57Ol

This PR ensures that the value passed to `random_bytes` is an integer greater than 0.

Commits
-------

9b80238 random_bytes length should be an int greater than 0
  • Loading branch information
nicolas-grekas committed Jul 4, 2023
2 parents d3b33d9 + 9b80238 commit a746442
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,28 @@ public function testGenerateToken()
$this->assertStringNotMatchesFormat('%S/%S', $token, 'is URI safe');
$this->assertStringNotMatchesFormat('%S=%S', $token, 'is URI safe');
}

/**
* @dataProvider validDataProvider
*/
public function testValidLength(int $entropy, int $length)
{
$generator = new UriSafeTokenGenerator($entropy);
$token = $generator->generateToken();
$this->assertSame($length, \strlen($token));
}

public static function validDataProvider(): \Iterator
{
yield [24, 4];
yield 'Float length' => [20, 3];
}

public function testInvalidLength()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Entropy should be greater than 7.');

new UriSafeTokenGenerator(7);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ class UriSafeTokenGenerator implements TokenGeneratorInterface
*/
public function __construct(int $entropy = 256)
{
if ($entropy <= 7) {
throw new \InvalidArgumentException('Entropy should be greater than 7.');
}

$this->entropy = $entropy;
}

Expand All @@ -38,7 +42,7 @@ public function generateToken()
// Generate an URI safe base64 encoded string that does not contain "+",
// "/" or "=" which need to be URL encoded and make URLs unnecessarily
// longer.
$bytes = random_bytes($this->entropy / 8);
$bytes = random_bytes(intdiv($this->entropy, 8));

return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}
Expand Down

0 comments on commit a746442

Please sign in to comment.