{"record":{"id":"a7c75be5c90c5b67","repo":"thephpleague/oauth2-server","slug":"server-error","errorCode":"server_error","errorMessage":"An unexpected error has occurred","messagePattern":"An unexpected error has occurred","errorType":"http","errorClass":"OAuthServerException","httpStatus":500,"severity":"critical","filePath":"src/Grant/AbstractGrant.php","lineNumber":549,"sourceCode":"\n    /**\n     * Generate a new unique identifier.\n     *\n     * @return non-empty-string\n     *\n     * @throws OAuthServerException\n     */\n    protected function generateUniqueIdentifier(int $length = 40): string\n    {\n        try {\n            if ($length < 1) {\n                throw new DomainException('Length must be a positive integer');\n            }\n\n            return bin2hex(random_bytes($length));\n            // @codeCoverageIgnoreStart\n        } catch (TypeError | Error $e) {\n            throw OAuthServerException::serverError('An unexpected error has occurred', $e);\n        } catch (Exception $e) {\n            // If you get this message, the CSPRNG failed hard.\n            throw OAuthServerException::serverError('Could not generate a random string', $e);\n        }\n        // @codeCoverageIgnoreEnd\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function canRespondToAccessTokenRequest(ServerRequestInterface $request): bool\n    {\n        $requestParameters = (array) $request->getParsedBody();\n\n        return (\n            array_key_exists('grant_type', $requestParameters)\n            && $requestParameters['grant_type'] === $this->getIdentifier()\n        );","sourceCodeStart":531,"sourceCodeEnd":567,"githubUrl":"https://github.com/thephpleague/oauth2-server/blob/9d2f6fc0a0b5aa1bb02506971d3a4ecff2c6526c/src/Grant/AbstractGrant.php#L531-L567","documentation":"A generic 500-class server error raised inside generateUniqueIdentifier when random_bytes() or bin2hex() throws a TypeError or Error (PHP engine-level failures), typically due to invalid $length (zero/negative/non-int) or an unavailable CSPRNG. It is wrapped as OAuthServerException::serverError with the previous exception attached for diagnostics.","triggerScenarios":"Calling issueAccessToken, issueAuthCode, issueRefreshToken, or issueDeviceCode when random_bytes($length) receives an invalid argument (e.g. length <= 0 or a non-integer from misconfiguration) or when the engine raises an unexpected Error during random generation.","commonSituations":"A config value or constant supplying the token length was changed to 0 or a string, a PHP version/platform where the CSPRNG is unavailable or misconfigured (e.g. broken php.ini random settings), or a custom grant subclassing AbstractGrant passes a bad length.","solutions":["Check the previous exception in the server log to see the underlying TypeError/Error","Verify the length passed to setEncryptionKey/random generation is a positive integer (the code throws DomainException for non-positive lengths before random_bytes)","Inspect PHP configuration for the CSPRNG (open_basedir/paths to /dev/urandom, php.ini) on the server","Update PHP to a version where random_bytes is reliably available (PHP 7+ with a healthy engine install)"],"exampleFix":"// before\n$server->setAccessTokenLength(0);\n// after\n$server->setAccessTokenLength(40); // positive integer","handlingStrategy":"try-catch","validationCode":"const len = serverConfig.tokenLength;\nif (!Number.isInteger(len) || len <= 0) throw new Error('token length must be a positive integer');","typeGuard":"function isValidLength(n: unknown): n is number { return typeof n === 'number' && Number.isInteger(n) && n > 0; }","tryCatchPattern":"try {\n  return await grant.issueAccessToken(...);\n} catch (e) {\n  if (e.code === 'server_error' && e.previous) {\n    logger.error('random generation failed', e.previous);\n  }\n  throw e;\n}","preventionTips":["Keep token/identifier length configuration as a positive integer","Check server logs for the chained previous exception to find the root cause","Verify random_bytes works on deployment targets (php -r 'echo bin2hex(random_bytes(8));')","Pin a healthy PHP runtime version in CI and production"],"tags":["oauth2","random-bytes","internal-error","configuration"],"backgroundTag":"internal-invariant-violation","analyzedSha":"9d2f6fc0a0b5aa1bb02506971d3a4ecff2c6526c","analyzedAt":"2026-09-15T22:33:30.452Z","contentChangedAt":"2026-09-15T22:33:30.452Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}