From c6ac52dc38802a378272e982962072b944810543 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Sat, 9 May 2026 14:49:39 +0200 Subject: [PATCH] fix(env): generate encoded secrets from raw random bytes Use random_bytes before hex and base64 encoding so generated env values match the expected decoded byte lengths. Add Pest coverage for HEX and REALBASE64 magic variables. --- bootstrap/helpers/shared.php | 12 ++++++------ tests/Unit/GenerateEnvValueTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 tests/Unit/GenerateEnvValueTest.php diff --git a/bootstrap/helpers/shared.php b/bootstrap/helpers/shared.php index 06c6f4d5c..860b550dd 100644 --- a/bootstrap/helpers/shared.php +++ b/bootstrap/helpers/shared.php @@ -1400,23 +1400,23 @@ function generateEnvValue(string $command, Service|Application|null $service = n break; // This is base64, case 'REALBASE64_64': - $generatedValue = base64_encode(Str::random(64)); + $generatedValue = base64_encode(random_bytes(64)); break; case 'REALBASE64_128': - $generatedValue = base64_encode(Str::random(128)); + $generatedValue = base64_encode(random_bytes(128)); break; case 'REALBASE64': case 'REALBASE64_32': - $generatedValue = base64_encode(Str::random(32)); + $generatedValue = base64_encode(random_bytes(32)); break; case 'HEX_32': - $generatedValue = bin2hex(Str::random(16)); + $generatedValue = bin2hex(random_bytes(16)); break; case 'HEX_64': - $generatedValue = bin2hex(Str::random(32)); + $generatedValue = bin2hex(random_bytes(32)); break; case 'HEX_128': - $generatedValue = bin2hex(Str::random(64)); + $generatedValue = bin2hex(random_bytes(64)); break; case 'USER': $generatedValue = Str::random(16); diff --git a/tests/Unit/GenerateEnvValueTest.php b/tests/Unit/GenerateEnvValueTest.php new file mode 100644 index 000000000..7e7755f4d --- /dev/null +++ b/tests/Unit/GenerateEnvValueTest.php @@ -0,0 +1,29 @@ +toBeString() + ->toMatch('/^[0-9a-f]+$/'); + + expect(strlen($value))->toBe($expectedLength); +})->with([ + 'HEX_32' => ['HEX_32', 32], + 'HEX_64' => ['HEX_64', 64], + 'HEX_128' => ['HEX_128', 128], +]); + +test('real base64 magic variables generate valid base64 strings from expected byte lengths', function (string $command, int $expectedBytes) { + $value = generateEnvValue($command); + $decodedValue = base64_decode($value, true); + + expect($value)->toBeString(); + expect($decodedValue)->not->toBeFalse(); + expect(strlen($decodedValue))->toBe($expectedBytes); +})->with([ + 'REALBASE64' => ['REALBASE64', 32], + 'REALBASE64_32' => ['REALBASE64_32', 32], + 'REALBASE64_64' => ['REALBASE64_64', 64], + 'REALBASE64_128' => ['REALBASE64_128', 128], +]);