diff --git a/src/Auth/JWTGenerator.php b/src/Auth/JWTGenerator.php index 9a0c1c3d..af48813c 100644 --- a/src/Auth/JWTGenerator.php +++ b/src/Auth/JWTGenerator.php @@ -13,6 +13,24 @@ */ class JWTGenerator { + /** + * Claims a user token's custom claims may not set. The token's identity comes only + * from the user ID argument (the backend treats a token without a user_id as a server + * token), and "egress" lets a token join calls without the app's role grants. + */ + private const RESERVED_USER_CLAIMS = ['user_id', 'server', 'egress']; + + /** + * The claim names the backend reads from a token. It decodes them with Go's + * encoding/json, which matches names case-insensitively with Unicode simple folding + * (so "USER_ID" and "u\u{017F}er_id" both set user_id) and lets the last matching key + * win, so a custom claim may use only the exact spelling. + */ + private const BACKEND_CLAIMS = [ + 'user_id', 'call_cids', 'channel_cids', 'role', 'egress', 'stream_check_writes', + 'scoped_call_cid', 'iss', 'sub', 'aud', 'exp', 'nbf', 'iat', 'jti', 'server', + ]; + private string $secret; private string $algorithm; @@ -60,10 +78,17 @@ public function generateServerToken(array $claims = [], ?int $expiration = null) * Generate a user token for client-side authentication. * * @param string $userId The user ID - * @param array $claims Additional claims to include + * @param array $claims Additional claims to include. They cannot set the reserved + * "user_id", "server" or "egress" claims or use another + * spelling (such as "USER_ID") of a claim the backend reads. + * A custom "iat" must be a positive whole Unix timestamp that + * is not in the future. A custom "exp" is ignored when + * $expiration is given. * @param int|null $expiration Token expiration in seconds (null for no expiration) * * @return string JWT token + * + * @throws StreamException If the user ID is empty or $claims sets a claim it may not set */ public function generateUserToken(string $userId, array $claims = [], ?int $expiration = null): string { @@ -72,19 +97,59 @@ public function generateUserToken(string $userId, array $claims = [], ?int $expi } $now = time(); + self::checkUserClaims($claims, $now); - $payload = array_merge([ - 'user_id' => $userId, - 'iat' => $now, - ], $claims); + $payload = array_merge(['iat' => $now], $claims); if ($expiration !== null) { $payload['exp'] = $now + $expiration; } + // user_id goes last, so no other key in the payload can come after it. + $payload['user_id'] = $userId; + return JWT::encode($payload, $this->secret, $this->algorithm); } + /** + * @throws StreamException If $claims sets a claim a user token may not set + */ + private static function checkUserClaims(array $claims, int $now): void + { + foreach (array_keys($claims) as $key) { + $key = (string) $key; + $folded = self::foldClaimName($key); + if ($key !== $folded && in_array($folded, self::BACKEND_CLAIMS, true)) { + throw new StreamException(sprintf('Claim "%s" is read by the backend as "%s"; use "%s"', $key, $folded, $folded)); + } + if (in_array($key, self::RESERVED_USER_CLAIMS, true)) { + throw new StreamException(sprintf('Claim "%s" is reserved and cannot be set on a user token', $key)); + } + } + + // The backend skips per-user token revocation for a token without an iat, and a + // later iat outlives revocations made before it. + if (array_key_exists('iat', $claims)) { + $iat = $claims['iat']; + $whole = is_int($iat) || (is_float($iat) && is_finite($iat) && floor($iat) === $iat); + if (!$whole || $iat <= 0 || $iat > $now) { + throw new StreamException('Claim "iat" must be a positive whole Unix timestamp that is not in the future'); + } + } + } + + /** + * Folds a claim name the way Go's encoding/json matches names. The names in + * BACKEND_CLAIMS are ASCII, and the only non-ASCII characters that fold to ASCII + * letters are the Kelvin sign (to k) and the long s (to s). + */ + private static function foldClaimName(string $name): string + { + $lower = strtr($name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + + return str_replace(["\u{212A}", "\u{017F}"], ['k', 's'], $lower); + } + /** * Verify and decode a JWT token. * diff --git a/src/Client.php b/src/Client.php index 29e392be..0eee4867 100644 --- a/src/Client.php +++ b/src/Client.php @@ -260,10 +260,13 @@ public function makeRequest( * Generate a user token for client-side authentication. * * @param string $userId The user ID - * @param array $claims Additional claims + * @param array $claims Additional claims. They cannot set the reserved "user_id" or + * "server" claims. A custom "exp" is ignored when $expiration is given. * @param int|null $expiration Token expiration in seconds (null for no expiration) * * @return string JWT token + * + * @throws StreamException If the user ID is empty or $claims sets a reserved claim */ public function createUserToken(string $userId, array $claims = [], ?int $expiration = null): string { diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 24cc7e90..583d9567 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -158,6 +158,172 @@ public function createUserTokenWithClaims(): void self::assertArrayHasKey('exp', $payload); // Should have expiration } + /** + * @return array + */ + public static function reservedUserTokenClaims(): array + { + return [ + 'empty user_id' => ['user_id', ''], + 'other user_id' => ['user_id', 'other-user'], + 'server true' => ['server', true], + 'server false' => ['server', false], + 'egress' => ['egress', true], + ]; + } + + /** + * Other spellings the backend's JSON decoder reads as a claim it uses: case variants, + * the long s (U+017F, folds to s) and the Kelvin sign (U+212A, folds to k). + * + * @return array + */ + public static function foldedClaimNames(): array + { + $names = [ + 'USER_ID', 'User_Id', "u\u{017F}er_id", "\u{017F}erver", 'SERVER', 'Egress', + "egre\u{017F}\u{017F}", 'IAT', 'Exp', 'Role', 'Call_CIDs', "stream_chec\u{212A}_writes", + ]; + + return array_combine($names, array_map(fn ($name) => [$name], $names)); + } + + /** + * @test + * + * @dataProvider foldedClaimNames + */ + public function createUserTokenRejectsFoldedClaimNames(string $claim): void + { + $client = ClientBuilder::fromEnv() + ->httpClient($this->mockHttpClient) + ->build(); + + $this->expectException(StreamException::class); + $this->expectExceptionMessage(sprintf('Claim "%s" is read by the backend as', $claim)); + + $client->createUserToken('user-123', [$claim => '']); + } + + /** + * @return array + */ + public static function invalidIatClaims(): array + { + return [ + 'zero' => [0], + 'negative' => [-1], + 'fraction' => [1.5], + 'future' => [time() + 3600], + 'string' => ['1700000000'], + 'null' => [null], + ]; + } + + /** + * @test + * + * @dataProvider invalidIatClaims + */ + public function createUserTokenRejectsInvalidIat(mixed $iat): void + { + $client = ClientBuilder::fromEnv() + ->httpClient($this->mockHttpClient) + ->build(); + + $this->expectException(StreamException::class); + $this->expectExceptionMessage('"iat"'); + + $client->createUserToken('user-123', ['iat' => $iat]); + } + + /** + * @test + */ + public function createUserTokenKeepsPastCustomIat(): void + { + $client = ClientBuilder::fromEnv() + ->httpClient($this->mockHttpClient) + ->build(); + $iat = time() - 60; + + $token = $client->createUserToken('user-123', ['iat' => $iat]); + + $payload = $client->getJWTGenerator()->verifyToken($token); + self::assertSame($iat, $payload['iat']); + } + + /** + * @test + */ + public function createUserTokenPutsUserIdLast(): void + { + $client = ClientBuilder::fromEnv() + ->httpClient($this->mockHttpClient) + ->build(); + + $token = $client->createUserToken('user-123', ['role' => 'admin', 'zzz' => 'custom'], 3600); + + // The backend's decoder lets the last matching key win, so nothing may follow user_id. + $parts = explode('.', $token); + $payload = json_decode(base64_decode(strtr($parts[1], '-_', '+/'), true), true); + self::assertSame('user-123', $payload['user_id']); + self::assertSame('user_id', array_key_last($payload)); + } + + /** + * @test + * + * @dataProvider reservedUserTokenClaims + */ + public function createUserTokenRejectsReservedClaims(string $claim, mixed $value): void + { + $client = ClientBuilder::fromEnv() + ->httpClient($this->mockHttpClient) + ->build(); + + $this->expectException(StreamException::class); + $this->expectExceptionMessage(sprintf('"%s" is reserved', $claim)); + + $client->createUserToken('user-123', [$claim => $value]); + } + + /** + * @test + */ + public function createUserTokenExpirationWinsOverCustomExp(): void + { + $client = ClientBuilder::fromEnv() + ->httpClient($this->mockHttpClient) + ->build(); + $before = time(); + + $token = $client->createUserToken('user-123', ['exp' => $before + 100 * 365 * 24 * 3600], 3600); + + $payload = $client->getJWTGenerator()->verifyToken($token); + self::assertSame('user-123', $payload['user_id']); + self::assertGreaterThanOrEqual($before + 3600, $payload['exp']); + self::assertLessThanOrEqual(time() + 3600, $payload['exp']); + } + + /** + * @test + */ + public function createUserTokenKeepsCustomExpWithoutExpiration(): void + { + $client = ClientBuilder::fromEnv() + ->httpClient($this->mockHttpClient) + ->build(); + $exp = time() + 7200; + + $token = $client->createUserToken('user-123', ['exp' => $exp, 'call_cids' => ['default:call']]); + + $payload = $client->getJWTGenerator()->verifyToken($token); + self::assertSame($exp, $payload['exp']); + self::assertSame(['default:call'], $payload['call_cids']); + self::assertArrayNotHasKey('server', $payload); + } + /** * @test */