Coverage for src/taipanstack/security/jwt.py: 100%
82 statements
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
1"""
2Secure JWT Utility module.
4Provides explicitly secure wrappers around PyJWT encoding and decoding,
5enforcing strict validation of algorithms, expiration, and audience claims.
6All operations return ``Result`` types.
7"""
9import secrets
10from collections.abc import Iterable
11from typing import TYPE_CHECKING, TypeAlias
13if TYPE_CHECKING:
14 import jwt
16import jwt
17from jwt.exceptions import PyJWTError
19from taipanstack.core.result import safe_from
21__all__ = ["decode_jwt", "encode_jwt"]
23JWTPayload: TypeAlias = dict[str, object]
25MAX_JWT_ALGORITHMS = 10
26MAX_JWT_ALGORITHM_LENGTH = 50
27MAX_JWT_AUDIENCES = 10
28MAX_JWT_AUDIENCE_LENGTH = 1024
31def _validate_encode_payload(payload: object) -> None:
32 if not isinstance(payload, dict):
33 raise TypeError("Payload must be a dictionary")
36def _validate_encode_secret(secret_key: object) -> None:
37 if not isinstance(secret_key, str):
38 raise TypeError("Secret must be a string")
41def _check_string_type_and_length(alg: object) -> str:
42 """Validate that the algorithm is a string of valid length."""
43 if not isinstance(alg, str):
44 raise TypeError("Algorithm must be a string")
46 if len(alg) > MAX_JWT_ALGORITHM_LENGTH:
47 raise ValueError("Algorithm string is too long")
49 return alg
52def _is_none_algorithm(alg: str) -> bool:
53 """Check if the algorithm is explicitly disallowed 'none'."""
54 alg_lower = alg.strip().lower()
55 return alg_lower.isascii() and secrets.compare_digest(alg_lower, "none")
58def _validate_encode_algorithm(algorithm: object) -> None:
59 valid_alg = _check_string_type_and_length(algorithm)
60 if _is_none_algorithm(valid_alg):
61 raise ValueError('Algorithm "none" is explicitly disallowed.')
64@safe_from(
65 PyJWTError,
66 ValueError,
67 TypeError,
68 NotImplementedError,
69 KeyError,
70 AttributeError,
71 Exception,
72)
73def encode_jwt(
74 payload: JWTPayload,
75 secret_key: str,
76 algorithm: str = "HS256",
77) -> str:
78 """Encode a payload into a JWT securely.
80 Explicitly rejects the "none" algorithm to prevent bypass vulnerabilities.
82 Args:
83 payload: Dictionary containing the JWT claims.
84 secret_key: The secret key for signing the token.
85 algorithm: The signing algorithm (default "HS256").
87 Returns:
88 The encoded JWT string.
90 Raises:
91 ValueError: If the "none" algorithm is specified.
92 PyJWTError: If encoding fails.
94 """
95 _validate_encode_payload(payload)
96 _validate_encode_secret(secret_key)
97 _validate_encode_algorithm(algorithm)
99 return jwt.encode(payload, secret_key, algorithm=algorithm) # nosem
102def _check_disallowed_algorithm(alg: str) -> None:
103 valid_alg = _check_string_type_and_length(alg)
104 if _is_none_algorithm(valid_alg):
105 msg = 'Algorithm "none" is explicitly disallowed for decoding.'
106 raise ValueError(msg)
109def _check_jwt_algorithms_type_and_length(algorithms: list[str]) -> list[str]:
110 """Validate that the algorithms are a list of strings of valid length."""
111 if not isinstance(algorithms, list):
112 raise TypeError("Algorithms must be a list of strings")
114 if len(algorithms) > MAX_JWT_ALGORITHMS:
115 raise ValueError("Too many algorithms provided")
117 return algorithms
120def _validate_jwt_algorithms(algorithms: list[str]) -> None:
121 valid_algs = _check_jwt_algorithms_type_and_length(algorithms)
122 for alg in valid_algs:
123 _check_disallowed_algorithm(alg)
126def _validate_jwt_audience_item(aud: object) -> None:
127 if not isinstance(aud, str):
128 raise TypeError("Audience items must be strings")
129 if len(aud) > MAX_JWT_AUDIENCE_LENGTH:
130 raise ValueError("Audience item string is too long")
133def _validate_jwt_audience_collection(
134 audience: list[str] | tuple[str, ...] | set[str],
135) -> None:
136 if len(audience) > MAX_JWT_AUDIENCES:
137 raise ValueError("Too many audience items provided")
139 for aud in audience:
140 _validate_jwt_audience_item(aud)
143def _validate_single_audience(audience: str) -> None:
144 """Validate that a single audience string is of valid length."""
145 if len(audience) > MAX_JWT_AUDIENCE_LENGTH:
146 raise ValueError("Audience string is too long")
149def _validate_jwt_audience(audience: str | Iterable[str]) -> None:
150 if isinstance(audience, str):
151 _validate_single_audience(audience)
152 return
154 if isinstance(audience, (list, tuple, set)):
155 _validate_jwt_audience_collection(audience)
156 return
158 raise TypeError("Audience must be a string or iterable of strings")
161@safe_from(
162 PyJWTError,
163 ValueError,
164 TypeError,
165 AttributeError,
166 NotImplementedError,
167 KeyError,
168 Exception,
169)
170def decode_jwt(
171 token: str,
172 secret_key: str,
173 algorithms: list[str],
174 audience: str | Iterable[str],
175) -> JWTPayload:
176 """Decode a JWT securely with strict claim validation.
178 Enforces that 'exp' (expiration) and 'aud' (audience) claims are present
179 and validated. Explicitly rejects the "none" algorithm.
181 Args:
182 token: The encoded JWT string.
183 secret_key: The secret key for verifying the signature.
184 algorithms: List of exactly accepted algorithms.
185 audience: The expected audience(s).
187 Returns:
188 The decoded payload dictionary.
190 Raises:
191 ValueError: If the "none" algorithm is present in the `algorithms` list.
192 PyJWTError: If the token is invalid, expired, or has incorrect claims.
194 """
195 if not isinstance(token, str):
196 raise TypeError("Token must be a string")
198 if not isinstance(secret_key, str):
199 raise TypeError("Secret must be a string")
201 _validate_jwt_algorithms(algorithms)
202 _validate_jwt_audience(audience)
204 return jwt.decode( # type: ignore[misc]
205 token,
206 secret_key,
207 algorithms=algorithms,
208 audience=audience,
209 options={
210 "require": ["exp", "aud"],
211 "verify_signature": True,
212 "verify_exp": True,
213 "verify_aud": True,
214 },
215 )