|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace DreamFactory\Core\Script\Tests\Security; |
| 4 | + |
| 5 | +use PHPUnit\Framework\TestCase; |
| 6 | + |
| 7 | +/** |
| 8 | + * Verifies that script engine token generation uses cryptographically secure |
| 9 | + * random_bytes() instead of the predictable uniqid(). |
| 10 | + * |
| 11 | + * uniqid() is microtime-based (~20 bits of entropy), allowing token prediction. |
| 12 | + * random_bytes(32) provides 256 bits of entropy. |
| 13 | + */ |
| 14 | +class ScriptTokenEntropyTest extends TestCase |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @dataProvider engineClassProvider |
| 18 | + */ |
| 19 | + public function testEngineUsesRandomBytesNotUniqid(string $className): void |
| 20 | + { |
| 21 | + $reflection = new \ReflectionClass($className); |
| 22 | + $source = file_get_contents($reflection->getFileName()); |
| 23 | + |
| 24 | + $this->assertStringNotContainsString( |
| 25 | + 'uniqid()', |
| 26 | + $source, |
| 27 | + "$className must not use uniqid() for token generation (insufficient entropy)" |
| 28 | + ); |
| 29 | + |
| 30 | + $this->assertStringContainsString( |
| 31 | + 'random_bytes', |
| 32 | + $source, |
| 33 | + "$className must use random_bytes() for cryptographically secure token generation" |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Verify the token format: bin2hex(random_bytes(32)) produces a 64-char hex string. |
| 39 | + */ |
| 40 | + public function testTokenFormat(): void |
| 41 | + { |
| 42 | + $token = bin2hex(random_bytes(32)); |
| 43 | + $this->assertEquals(64, strlen($token), 'Token should be 64 hex characters (256 bits)'); |
| 44 | + $this->assertMatchesRegularExpression('/^[0-9a-f]{64}$/', $token); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Verify uniqueness across 100 tokens (basic sanity check). |
| 49 | + */ |
| 50 | + public function testTokenUniqueness(): void |
| 51 | + { |
| 52 | + $tokens = []; |
| 53 | + for ($i = 0; $i < 100; $i++) { |
| 54 | + $tokens[] = bin2hex(random_bytes(32)); |
| 55 | + } |
| 56 | + $this->assertCount(100, array_unique($tokens), 'All 100 tokens should be unique'); |
| 57 | + } |
| 58 | + |
| 59 | + public static function engineClassProvider(): array |
| 60 | + { |
| 61 | + return [ |
| 62 | + 'NodeJs' => [\DreamFactory\Core\Script\Engines\NodeJs::class], |
| 63 | + 'Python' => [\DreamFactory\Core\Script\Engines\Python::class], |
| 64 | + 'Python3' => [\DreamFactory\Core\Script\Engines\Python3::class], |
| 65 | + ]; |
| 66 | + } |
| 67 | +} |
0 commit comments