Skip to content

Commit

Permalink
Merge branch '6.2' into 6.3
Browse files Browse the repository at this point in the history
* 6.2:
  cs fix
  [Messenger] Fix passing options set via tags to handler descriptors
  random_bytes length should be an int greater than 0
  enforce UTC timezone in test
  [DependencyInjection] Fix autocasting null env values to empty string
  Fix executable bit
  Fix executable bit
  Readme: Replace Stack Overflow with GitHub Discussions
  [DoctrineBridge] Remove outdated comment
  [DependencyInjection] Fix annotation
  [SecurityBundle] Do not translate `Bearer` header’s `error_description`
  [String] Fix Inflector for 'status'
  [DependencyInjection] Fix resource tracking for lazy services
  [EventDispatcher] [EventDispatcher] Throw exception when listener method cannot be resolved
  • Loading branch information
nicolas-grekas committed Jul 5, 2023
2 parents 1f505c9 + 5f2850e commit 63d7b09
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
24 changes: 24 additions & 0 deletions Tests/TokenGenerator/UriSafeTokenGeneratorTest.php
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);
}
}
6 changes: 5 additions & 1 deletion TokenGenerator/UriSafeTokenGenerator.php
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 @@ -35,7 +39,7 @@ public function generateToken(): string
// 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 63d7b09

Please sign in to comment.