Coverage for faststream/nats/security.py: 86%
132 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import warnings
2from collections.abc import Callable
3from pathlib import Path
4from typing import TYPE_CHECKING, Any, Final
6from nats.aio.client import Credentials, RawCredentials
7from typing_extensions import Self, override
9from faststream.exceptions import INSTALL_NATS_NKEYS
10from faststream.security import BaseSecurity, SASLPlaintext
12if TYPE_CHECKING:
13 from ssl import SSLContext
15try:
16 import nkeys as _nkeys
17except ImportError:
18 _nkeys = None
21def warn_deprecated_security_args(*arguments: str) -> None:
22 names = ", ".join(f"`{name}`" for name in arguments)
23 replacements = ", ".join(
24 dict.fromkeys(_LEGACY_SECURITY_TARGETS[name] for name in arguments)
25 )
26 warnings.warn(
27 f"The NATS security arguments {names} are deprecated and will be removed "
28 "in 1.0.0. Use `security=` with "
29 f"{replacements} instead.",
30 DeprecationWarning,
31 stacklevel=3,
32 )
35class NatsSecurity(BaseSecurity):
36 """Base class for NATS security configurations."""
38 __slots__ = ("tls_handshake_first", "tls_hostname")
40 def __init__(
41 self,
42 *,
43 ssl_context: "SSLContext | None" = None,
44 use_ssl: bool | None = None,
45 tls_hostname: str | None = None,
46 tls_handshake_first: bool = False,
47 ) -> None:
48 super().__init__(ssl_context=ssl_context, use_ssl=use_ssl)
49 self.tls_hostname = tls_hostname
50 self.tls_handshake_first = tls_handshake_first
53class NatsToken(NatsSecurity):
54 """NATS token authentication."""
56 __slots__ = ("token",)
58 def __init__(
59 self,
60 token: str | Callable[[], str],
61 *,
62 ssl_context: "SSLContext | None" = None,
63 use_ssl: bool | None = None,
64 tls_hostname: str | None = None,
65 tls_handshake_first: bool = False,
66 ) -> None:
67 if not callable(token) and not token: 67 ↛ 68line 67 didn't jump to line 68 because the condition on line 67 was never true
68 msg = "NATS token cannot be empty."
69 raise ValueError(msg)
71 super().__init__(
72 ssl_context=ssl_context,
73 use_ssl=use_ssl,
74 tls_hostname=tls_hostname,
75 tls_handshake_first=tls_handshake_first,
76 )
77 self.token = token
79 @override
80 def get_requirement(self) -> list[dict[str, Any]]:
81 """Get the AsyncAPI requirement for NATS token authentication."""
82 return [{"nats-token": []}]
84 @override
85 def get_schema(self) -> dict[str, dict[str, Any]]:
86 """Get the AsyncAPI schema for NATS token authentication."""
87 return {
88 "nats-token": {
89 "type": "apiKey",
90 "in": "user",
91 "description": "NATS authentication token sent as CONNECT auth_token.",
92 "x-nats-auth": "token",
93 },
94 }
97class NatsUserPassword(NatsSecurity):
98 """NATS username and password authentication."""
100 __slots__ = ("password", "username")
102 def __init__(
103 self,
104 username: str,
105 password: str,
106 *,
107 ssl_context: "SSLContext | None" = None,
108 use_ssl: bool | None = None,
109 tls_hostname: str | None = None,
110 tls_handshake_first: bool = False,
111 ) -> None:
112 super().__init__(
113 ssl_context=ssl_context,
114 use_ssl=use_ssl,
115 tls_hostname=tls_hostname,
116 tls_handshake_first=tls_handshake_first,
117 )
118 self.username = username
119 self.password = password
121 @override
122 def get_requirement(self) -> list[dict[str, Any]]:
123 """Get the AsyncAPI requirement for NATS user/password authentication."""
124 return [{"nats-user-password": []}]
126 @override
127 def get_schema(self) -> dict[str, dict[str, Any]]:
128 """Get the AsyncAPI schema for NATS user/password authentication."""
129 return {"nats-user-password": {"type": "userPassword"}}
132class NatsCredentials(NatsSecurity):
133 """NATS JWT credentials authentication."""
135 __slots__ = ("credentials",)
137 def __init__(
138 self,
139 credentials: Credentials,
140 *,
141 ssl_context: "SSLContext | None" = None,
142 use_ssl: bool | None = None,
143 tls_hostname: str | None = None,
144 tls_handshake_first: bool = False,
145 ) -> None:
146 if _nkeys is None: 146 ↛ 147line 146 didn't jump to line 147 because the condition on line 146 was never true
147 raise ImportError(INSTALL_NATS_NKEYS)
149 super().__init__(
150 ssl_context=ssl_context,
151 use_ssl=use_ssl,
152 tls_hostname=tls_hostname,
153 tls_handshake_first=tls_handshake_first,
154 )
155 self.credentials = credentials
157 @override
158 def get_requirement(self) -> list[dict[str, Any]]:
159 """Get the AsyncAPI requirement for NATS credentials authentication."""
160 return [{"nats-jwt": []}]
162 @override
163 def get_schema(self) -> dict[str, dict[str, Any]]:
164 """Get the AsyncAPI schema for NATS credentials authentication."""
165 return {
166 "nats-jwt": {
167 "type": "asymmetricEncryption",
168 "description": (
169 "NATS user JWT authentication with NKey challenge signing."
170 ),
171 "x-nats-auth": "jwt-nkey",
172 "x-nats-credential-source": "credentials-file",
173 },
174 }
176 @classmethod
177 def from_file(
178 cls,
179 credentials_file: str | Path,
180 *,
181 ssl_context: "SSLContext | None" = None,
182 use_ssl: bool | None = None,
183 tls_hostname: str | None = None,
184 tls_handshake_first: bool = False,
185 ) -> Self:
186 """Load a combined NATS credentials file."""
187 return cls(
188 credentials_file,
189 ssl_context=ssl_context,
190 use_ssl=use_ssl,
191 tls_hostname=tls_hostname,
192 tls_handshake_first=tls_handshake_first,
193 )
195 @classmethod
196 def from_files(
197 cls,
198 *,
199 jwt: str | Path,
200 seed: str | Path,
201 ssl_context: "SSLContext | None" = None,
202 use_ssl: bool | None = None,
203 tls_hostname: str | None = None,
204 tls_handshake_first: bool = False,
205 ) -> Self:
206 """Load separate NATS user JWT and seed files."""
207 return cls(
208 (str(jwt), str(seed)),
209 ssl_context=ssl_context,
210 use_ssl=use_ssl,
211 tls_hostname=tls_hostname,
212 tls_handshake_first=tls_handshake_first,
213 )
215 @classmethod
216 def from_raw(
217 cls,
218 credentials: str,
219 *,
220 ssl_context: "SSLContext | None" = None,
221 use_ssl: bool | None = None,
222 tls_hostname: str | None = None,
223 tls_handshake_first: bool = False,
224 ) -> Self:
225 """Use raw combined NATS credentials."""
226 markers = ("BEGIN NATS USER JWT", "BEGIN USER NKEY SEED")
227 if not credentials or any(marker not in credentials for marker in markers): 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 msg = "Raw NATS credentials do not contain the required markers."
229 raise ValueError(msg)
231 return cls(
232 RawCredentials(credentials),
233 ssl_context=ssl_context,
234 use_ssl=use_ssl,
235 tls_hostname=tls_hostname,
236 tls_handshake_first=tls_handshake_first,
237 )
240class NatsNKey(NatsSecurity):
241 """NATS NKey challenge-response authentication."""
243 __slots__ = ("seed", "seed_is_file")
245 def __init__(
246 self,
247 seed_file: str | Path,
248 *,
249 ssl_context: "SSLContext | None" = None,
250 use_ssl: bool | None = None,
251 tls_hostname: str | None = None,
252 tls_handshake_first: bool = False,
253 ) -> None:
254 if _nkeys is None: 254 ↛ 255line 254 didn't jump to line 255 because the condition on line 254 was never true
255 raise ImportError(INSTALL_NATS_NKEYS)
257 if not str(seed_file): 257 ↛ 258line 257 didn't jump to line 258 because the condition on line 257 was never true
258 msg = "NATS NKey seed file cannot be empty."
259 raise ValueError(msg)
261 super().__init__(
262 ssl_context=ssl_context,
263 use_ssl=use_ssl,
264 tls_hostname=tls_hostname,
265 tls_handshake_first=tls_handshake_first,
266 )
267 self.seed = str(seed_file)
268 self.seed_is_file = True
270 @override
271 def get_requirement(self) -> list[dict[str, Any]]:
272 """Get the AsyncAPI requirement for NATS NKey authentication."""
273 return [{"nats-nkey": []}]
275 @override
276 def get_schema(self) -> dict[str, dict[str, Any]]:
277 """Get the AsyncAPI schema for NATS NKey authentication."""
278 return {
279 "nats-nkey": {
280 "type": "asymmetricEncryption",
281 "description": (
282 "NATS NKey challenge-response authentication using an "
283 "Ed25519 signature."
284 ),
285 "x-nats-auth": "nkey",
286 "x-nats-algorithm": "ed25519",
287 },
288 }
290 @classmethod
291 def from_file(
292 cls,
293 seed_file: str | Path,
294 *,
295 ssl_context: "SSLContext | None" = None,
296 use_ssl: bool | None = None,
297 tls_hostname: str | None = None,
298 tls_handshake_first: bool = False,
299 ) -> Self:
300 """Load a NATS NKey seed file."""
301 return cls(
302 seed_file,
303 ssl_context=ssl_context,
304 use_ssl=use_ssl,
305 tls_hostname=tls_hostname,
306 tls_handshake_first=tls_handshake_first,
307 )
309 @classmethod
310 def from_seed(
311 cls,
312 seed: str,
313 *,
314 ssl_context: "SSLContext | None" = None,
315 use_ssl: bool | None = None,
316 tls_hostname: str | None = None,
317 tls_handshake_first: bool = False,
318 ) -> Self:
319 """Use a raw NATS NKey seed."""
320 if not seed: 320 ↛ 321line 320 didn't jump to line 321 because the condition on line 320 was never true
321 msg = "NATS NKey seed cannot be empty."
322 raise ValueError(msg)
324 security = cls(
325 seed,
326 ssl_context=ssl_context,
327 use_ssl=use_ssl,
328 tls_hostname=tls_hostname,
329 tls_handshake_first=tls_handshake_first,
330 )
331 security.seed_is_file = False
332 return security
335class NatsJWT(NatsSecurity):
336 """NATS user JWT authentication with NKey challenge signing."""
338 __slots__ = ("jwt_cb", "signature_cb")
340 def __init__(
341 self,
342 jwt_cb: Callable[[], bytes | bytearray],
343 signature_cb: Callable[[str], bytes],
344 *,
345 ssl_context: "SSLContext | None" = None,
346 use_ssl: bool | None = None,
347 tls_hostname: str | None = None,
348 tls_handshake_first: bool = False,
349 ) -> None:
350 super().__init__(
351 ssl_context=ssl_context,
352 use_ssl=use_ssl,
353 tls_hostname=tls_hostname,
354 tls_handshake_first=tls_handshake_first,
355 )
356 self.jwt_cb = jwt_cb
357 self.signature_cb = signature_cb
359 @override
360 def get_requirement(self) -> list[dict[str, Any]]:
361 """Get the AsyncAPI requirement for NATS JWT authentication."""
362 return [{"nats-jwt": []}]
364 @override
365 def get_schema(self) -> dict[str, dict[str, Any]]:
366 """Get the AsyncAPI schema for NATS JWT authentication."""
367 return {
368 "nats-jwt": {
369 "type": "asymmetricEncryption",
370 "description": (
371 "NATS user JWT authentication with NKey challenge signing."
372 ),
373 "x-nats-auth": "jwt-nkey",
374 "x-nats-credential-source": "callbacks",
375 },
376 }
379_LEGACY_SECURITY_TARGETS: Final[dict[str, str]] = {
380 "tls_hostname": NatsSecurity.__name__,
381 "token": NatsToken.__name__,
382 "signature_cb": NatsJWT.__name__,
383 "user_jwt_cb": NatsJWT.__name__,
384 "user_credentials": NatsCredentials.__name__,
385 "nkeys_seed": f"{NatsNKey.__name__}.from_file",
386 "nkeys_seed_str": f"{NatsNKey.__name__}.from_seed",
387}
390def parse_security(security: BaseSecurity | None) -> dict[str, Any]:
391 if security is None:
392 return {}
393 if isinstance(security, NatsToken):
394 return _parse_nats_token(security)
395 if isinstance(security, NatsUserPassword):
396 return _parse_nats_user_password(security)
397 if isinstance(security, NatsCredentials):
398 return _parse_nats_credentials(security)
399 if isinstance(security, NatsNKey):
400 return _parse_nats_nkey(security)
401 if isinstance(security, NatsJWT):
402 return _parse_nats_jwt(security)
403 if type(security) is NatsSecurity:
404 return _parse_nats_security(security)
405 if isinstance(security, SASLPlaintext): 405 ↛ 406line 405 didn't jump to line 406 because the condition on line 405 was never true
406 return _parse_sasl_plaintext(security)
407 if type(security) is BaseSecurity: 407 ↛ 408line 407 didn't jump to line 408 because the condition on line 407 was never true
408 return _parse_base_security(security)
409 msg = f"NatsBroker does not support {type(security)}"
410 raise NotImplementedError(msg)
413def _parse_nats_security(security: NatsSecurity) -> dict[str, Any]:
414 return {
415 "tls": security.ssl_context,
416 "tls_hostname": security.tls_hostname,
417 "tls_handshake_first": security.tls_handshake_first,
418 }
421def _parse_nats_token(security: NatsToken) -> dict[str, Any]:
422 return {
423 **_parse_nats_security(security),
424 "token": security.token,
425 }
428def _parse_nats_user_password(security: NatsUserPassword) -> dict[str, Any]:
429 return {
430 **_parse_nats_security(security),
431 "user": security.username,
432 "password": security.password,
433 }
436def _parse_nats_credentials(security: NatsCredentials) -> dict[str, Any]:
437 return {
438 **_parse_nats_security(security),
439 "user_credentials": security.credentials,
440 }
443def _parse_nats_nkey(security: NatsNKey) -> dict[str, Any]:
444 seed_key = "nkeys_seed" if security.seed_is_file else "nkeys_seed_str"
445 return {
446 **_parse_nats_security(security),
447 seed_key: security.seed,
448 }
451def _parse_nats_jwt(security: NatsJWT) -> dict[str, Any]:
452 return {
453 **_parse_nats_security(security),
454 "user_jwt_cb": security.jwt_cb,
455 "signature_cb": security.signature_cb,
456 }
459def _parse_base_security(security: BaseSecurity) -> dict[str, Any]:
460 return {
461 "tls": security.ssl_context,
462 }
465def _parse_sasl_plaintext(security: SASLPlaintext) -> dict[str, Any]:
466 return {
467 "tls": security.ssl_context,
468 "user": security.username,
469 "password": security.password,
470 }