|
| 1 | +"""JWT token signer for generating authentication tokens.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from datetime import datetime, timezone |
| 6 | + |
| 7 | +import jwt |
| 8 | + |
| 9 | +from .config import JWTConfig |
| 10 | +from .exceptions import JWTError |
| 11 | +from .types import JWTClaims, JWTUserContext |
| 12 | + |
| 13 | + |
| 14 | +class JWTSigner: |
| 15 | + """ |
| 16 | + JWT token generator for GraphQL Federation authentication. |
| 17 | +
|
| 18 | + This class is used by the webserver to generate JWT tokens after successful |
| 19 | + HMAC authentication. The generated tokens are then forwarded to the manager |
| 20 | + via Hive Router using the X-BackendAI-Token header. |
| 21 | +
|
| 22 | + Usage: |
| 23 | + from ai.backend.common.jwt import JWTSigner, JWTConfig, JWTUserContext |
| 24 | +
|
| 25 | + config = JWTConfig(secret_key="your-secret-key") |
| 26 | + signer = JWTSigner(config) |
| 27 | +
|
| 28 | + user_context = JWTUserContext( |
| 29 | + user_id=user_uuid, |
| 30 | + access_key=access_key, |
| 31 | + role="user", |
| 32 | + domain_name="default", |
| 33 | + is_admin=False, |
| 34 | + is_superadmin=False, |
| 35 | + ) |
| 36 | + token = signer.generate_token(user_context) |
| 37 | + """ |
| 38 | + |
| 39 | + _config: JWTConfig |
| 40 | + |
| 41 | + def __init__(self, config: JWTConfig) -> None: |
| 42 | + """ |
| 43 | + Initialize JWT signer with configuration. |
| 44 | +
|
| 45 | + Args: |
| 46 | + config: JWT configuration containing secret key and other settings |
| 47 | + """ |
| 48 | + self._config = config |
| 49 | + |
| 50 | + def generate_token(self, user_context: JWTUserContext) -> str: |
| 51 | + """ |
| 52 | + Generate a JWT token from authenticated user context. |
| 53 | +
|
| 54 | + This method creates a JWT token containing all necessary user authentication |
| 55 | + information. The token is signed using HS256 with the configured secret key. |
| 56 | +
|
| 57 | + Args: |
| 58 | + user_context: User context data containing authentication information |
| 59 | +
|
| 60 | + Returns: |
| 61 | + Encoded JWT token string |
| 62 | +
|
| 63 | + Raises: |
| 64 | + JWTError: If token generation fails |
| 65 | + """ |
| 66 | + now = datetime.now(timezone.utc) |
| 67 | + |
| 68 | + claims = JWTClaims( |
| 69 | + sub=user_context.user_id, |
| 70 | + exp=now + self._config.token_expiration, |
| 71 | + iat=now, |
| 72 | + iss=self._config.issuer, |
| 73 | + access_key=user_context.access_key, |
| 74 | + role=user_context.role, |
| 75 | + domain_name=user_context.domain_name, |
| 76 | + is_admin=user_context.is_admin, |
| 77 | + is_superadmin=user_context.is_superadmin, |
| 78 | + ) |
| 79 | + |
| 80 | + try: |
| 81 | + return jwt.encode( |
| 82 | + claims.to_dict(), |
| 83 | + self._config.secret_key, |
| 84 | + algorithm=self._config.algorithm, |
| 85 | + ) |
| 86 | + except Exception as e: |
| 87 | + raise JWTError(f"JWT generation failed: {e}") from e |
0 commit comments