Skip to content

Commit

Permalink
Minor code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayesh committed Dec 30, 2023
1 parent 7936c95 commit bfe0666
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/StatelessCSRF.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Ayesh\StatelessCSRF;

use Random\RandomException;

use function base64_decode;
use function base64_encode;
use function count;
Expand Down Expand Up @@ -40,14 +42,19 @@ public function resetGlue(): void {
$this->data = [];
}

/**
* @throws \JsonException
*/
public function getToken(string $identifier, int $expiration = null): string {
$seed = $this->getRandomSeed();
$hash = $this->generateHash($identifier, $seed, $expiration, $this->data);
return $this->urlSafeBase64Encode($seed . '|' . $expiration . '|' . $hash);
}

/**
* @throws RandomException
*/
private function getRandomSeed(): string {
/** @noinspection PhpUnhandledExceptionInspection */
return $this->urlSafeBase64Encode(random_bytes(8));
}

Expand Down
15 changes: 12 additions & 3 deletions tests/StatelessCSRFTest.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
<?php /** @noinspection PhpUnhandledExceptionInspection */
<?php

namespace Ayesh\StatelessCSRF\Tests;

use Ayesh\StatelessCSRF\StatelessCSRF;
use Exception;
use PHPUnit\Framework\TestCase;
use Random\RandomException;

use function bin2hex;
use function random_bytes;
use function time;
Expand All @@ -15,6 +18,9 @@ public function testInit(): void {
$this->assertInstanceOf(StatelessCSRF::class, $instance);
}

/**
* @throws RandomException
*/
public function testStatelessNoGlue(): void {
$key = bin2hex(random_bytes(8));
$generator = new StatelessCSRF($key);
Expand Down Expand Up @@ -57,7 +63,7 @@ public static function getValidationDataSet(): array {
* @param string $value
* @param string $id
*
* @throws \Exception
* @throws Exception
*/
public function testSeparateInstanceValidation(string $key, string $value, string $id): void {
$secret_key = bin2hex(random_bytes(8));
Expand Down Expand Up @@ -92,7 +98,7 @@ public function testSeparateInstanceValidation(string $key, string $value, strin
* @param string $value
* @param string $id
*
* @throws \Exception
* @throws Exception
*/
public function testTokenExpiration(string $key, string $value, string $id): void {
$secret_key = bin2hex(random_bytes(8));
Expand All @@ -110,6 +116,9 @@ public function testTokenExpiration(string $key, string $value, string $id): voi
$this->assertTrue($validator->validate($id, $token, $time + 3600));
}

/**
* @throws RandomException
*/
public function testDebugInfoLeakNoSecret(): void {
$secret_key = bin2hex(random_bytes(8));
$generator = new StatelessCSRF($secret_key);
Expand Down

0 comments on commit bfe0666

Please sign in to comment.