|
| 1 | +import abc |
| 2 | +import asyncio |
| 3 | +import os |
| 4 | +import time |
| 5 | +from typing import Literal |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | +from ._exceptions import AuthenticationError |
| 9 | + |
| 10 | + |
| 11 | +class AuthBase(abc.ABC): |
| 12 | + """ |
| 13 | + Abstract base class for authentication methods. |
| 14 | + """ |
| 15 | + |
| 16 | + BASE_URL = "https://mp.speechmatics.com" |
| 17 | + |
| 18 | + @abc.abstractmethod |
| 19 | + async def get_auth_headers(self) -> dict[str, str]: |
| 20 | + """ |
| 21 | + Get authentication headers asynchronously. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + A dictionary of authentication headers. |
| 25 | + """ |
| 26 | + raise NotImplementedError |
| 27 | + |
| 28 | + |
| 29 | +class StaticKeyAuth(AuthBase): |
| 30 | + """ |
| 31 | + Authentication using a static API key. |
| 32 | +
|
| 33 | + This is the traditional authentication method where the same |
| 34 | + API key is used for all requests. |
| 35 | +
|
| 36 | + Args: |
| 37 | + api_key: The Speechmatics API key. |
| 38 | +
|
| 39 | + Examples: |
| 40 | + >>> auth = StaticKeyAuth("your-api-key") |
| 41 | + >>> headers = await auth.get_auth_headers() |
| 42 | + >>> print(headers) |
| 43 | + {'Authorization': 'Bearer your-api-key'} |
| 44 | + """ |
| 45 | + |
| 46 | + def __init__(self, api_key: Optional[str] = None): |
| 47 | + self._api_key = api_key or os.environ.get("SPEECHMATICS_API_KEY") |
| 48 | + |
| 49 | + if not self._api_key: |
| 50 | + raise ValueError("API key required: provide api_key or set SPEECHMATICS_API_KEY") |
| 51 | + |
| 52 | + async def get_auth_headers(self) -> dict[str, str]: |
| 53 | + return {"Authorization": f"Bearer {self._api_key}"} |
| 54 | + |
| 55 | + |
| 56 | +class JWTAuth(AuthBase): |
| 57 | + """ |
| 58 | + Authentication using temporary JWT tokens. |
| 59 | +
|
| 60 | + Generates short-lived JWTs for enhanced security. |
| 61 | +
|
| 62 | + Args: |
| 63 | + api_key: The main Speechmatics API key used to generate JWTs. |
| 64 | + ttl: Time-to-live for tokens between 60 and 86400 seconds. |
| 65 | + For security reasons, we suggest using the shortest TTL possible. |
| 66 | + region: Self-Service customers are restricted to "eu". |
| 67 | + Enterprise customers can use this to specify which region the temporary key should be enabled in. |
| 68 | + client_ref: Optional client reference for JWT token. |
| 69 | + This parameter must be used if the temporary keys are exposed to the end-user's client |
| 70 | + to prevent a user from accessing the data of a different user. |
| 71 | + mp_url: Optional management platform URL override. |
| 72 | + request_id: Optional request ID for debugging purposes. |
| 73 | +
|
| 74 | + Examples: |
| 75 | + >>> auth = JWTAuth("your-api-key") |
| 76 | + >>> headers = await auth.get_auth_headers() |
| 77 | + >>> print(headers) |
| 78 | + {'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIs...'} |
| 79 | + """ |
| 80 | + |
| 81 | + def __init__( |
| 82 | + self, |
| 83 | + api_key: Optional[str] = None, |
| 84 | + *, |
| 85 | + ttl: int = 60, |
| 86 | + region: Literal["eu", "usa", "au"] = "eu", |
| 87 | + client_ref: Optional[str] = None, |
| 88 | + mp_url: Optional[str] = None, |
| 89 | + request_id: Optional[str] = None, |
| 90 | + ): |
| 91 | + self._api_key = api_key or os.environ.get("SPEECHMATICS_API_KEY") |
| 92 | + self._ttl = ttl |
| 93 | + self._region = region |
| 94 | + self._client_ref = client_ref |
| 95 | + self._request_id = request_id |
| 96 | + self._mp_url = mp_url or os.getenv("SM_MANAGEMENT_PLATFORM_URL", self.BASE_URL) |
| 97 | + |
| 98 | + if not self._api_key: |
| 99 | + raise ValueError( |
| 100 | + "API key required: please provide api_key or set SPEECHMATICS_API_KEY environment variable" |
| 101 | + ) |
| 102 | + |
| 103 | + if not 60 <= self._ttl <= 86_400: |
| 104 | + raise ValueError("ttl must be between 60 and 86400 seconds") |
| 105 | + |
| 106 | + self._cached_token: Optional[str] = None |
| 107 | + self._token_expires_at: float = 0 |
| 108 | + self._token_lock = asyncio.Lock() |
| 109 | + |
| 110 | + async def get_auth_headers(self) -> dict[str, str]: |
| 111 | + """Get JWT auth headers with caching.""" |
| 112 | + async with self._token_lock: |
| 113 | + current_time = time.time() |
| 114 | + if current_time >= self._token_expires_at - 10: |
| 115 | + self._cached_token = await self._generate_token() |
| 116 | + self._token_expires_at = current_time + self._ttl |
| 117 | + |
| 118 | + return {"Authorization": f"Bearer {self._cached_token}"} |
| 119 | + |
| 120 | + async def _generate_token(self) -> str: |
| 121 | + try: |
| 122 | + import aiohttp |
| 123 | + except ImportError: |
| 124 | + raise ImportError( |
| 125 | + "aiohttp is required for JWT authentication. Please install it with `pip install 'speechmatics-batch[jwt]'`" |
| 126 | + ) |
| 127 | + |
| 128 | + endpoint = f"{self._mp_url}/v1/api_keys" |
| 129 | + params = {"type": "batch"} |
| 130 | + payload = {"ttl": self._ttl, "region": str(self._region)} |
| 131 | + |
| 132 | + if self._client_ref: |
| 133 | + payload["client_ref"] = self._client_ref |
| 134 | + |
| 135 | + headers = { |
| 136 | + "Authorization": f"Bearer {self._api_key}", |
| 137 | + "Content-Type": "application/json", |
| 138 | + } |
| 139 | + |
| 140 | + if self._request_id: |
| 141 | + headers["X-Request-Id"] = self._request_id |
| 142 | + |
| 143 | + try: |
| 144 | + async with aiohttp.ClientSession() as session: |
| 145 | + async with session.post( |
| 146 | + endpoint, |
| 147 | + params=params, |
| 148 | + json=payload, |
| 149 | + headers=headers, |
| 150 | + timeout=aiohttp.ClientTimeout(total=10), |
| 151 | + ) as response: |
| 152 | + if response.status != 201: |
| 153 | + text = await response.text() |
| 154 | + raise AuthenticationError(f"Failed to generate JWT: HTTP {response.status}: {text}") |
| 155 | + |
| 156 | + data = await response.json() |
| 157 | + return str(data["key_value"]) |
| 158 | + |
| 159 | + except aiohttp.ClientError as e: |
| 160 | + raise AuthenticationError(f"Network error generating JWT: {e}") |
| 161 | + except Exception as e: |
| 162 | + raise AuthenticationError(f"Unexpected error generating JWT: {e}") |
0 commit comments