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

1""" 

2Secure JWT Utility module. 

3 

4Provides explicitly secure wrappers around PyJWT encoding and decoding, 

5enforcing strict validation of algorithms, expiration, and audience claims. 

6All operations return ``Result`` types. 

7""" 

8 

9import secrets 

10from collections.abc import Iterable 

11from typing import TYPE_CHECKING, TypeAlias 

12 

13if TYPE_CHECKING: 

14 import jwt 

15 

16import jwt 

17from jwt.exceptions import PyJWTError 

18 

19from taipanstack.core.result import safe_from 

20 

21__all__ = ["decode_jwt", "encode_jwt"] 

22 

23JWTPayload: TypeAlias = dict[str, object] 

24 

25MAX_JWT_ALGORITHMS = 10 

26MAX_JWT_ALGORITHM_LENGTH = 50 

27MAX_JWT_AUDIENCES = 10 

28MAX_JWT_AUDIENCE_LENGTH = 1024 

29 

30 

31def _validate_encode_payload(payload: object) -> None: 

32 if not isinstance(payload, dict): 

33 raise TypeError("Payload must be a dictionary") 

34 

35 

36def _validate_encode_secret(secret_key: object) -> None: 

37 if not isinstance(secret_key, str): 

38 raise TypeError("Secret must be a string") 

39 

40 

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") 

45 

46 if len(alg) > MAX_JWT_ALGORITHM_LENGTH: 

47 raise ValueError("Algorithm string is too long") 

48 

49 return alg 

50 

51 

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") 

56 

57 

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.') 

62 

63 

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. 

79 

80 Explicitly rejects the "none" algorithm to prevent bypass vulnerabilities. 

81 

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"). 

86 

87 Returns: 

88 The encoded JWT string. 

89 

90 Raises: 

91 ValueError: If the "none" algorithm is specified. 

92 PyJWTError: If encoding fails. 

93 

94 """ 

95 _validate_encode_payload(payload) 

96 _validate_encode_secret(secret_key) 

97 _validate_encode_algorithm(algorithm) 

98 

99 return jwt.encode(payload, secret_key, algorithm=algorithm) # nosem 

100 

101 

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) 

107 

108 

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") 

113 

114 if len(algorithms) > MAX_JWT_ALGORITHMS: 

115 raise ValueError("Too many algorithms provided") 

116 

117 return algorithms 

118 

119 

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) 

124 

125 

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") 

131 

132 

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") 

138 

139 for aud in audience: 

140 _validate_jwt_audience_item(aud) 

141 

142 

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") 

147 

148 

149def _validate_jwt_audience(audience: str | Iterable[str]) -> None: 

150 if isinstance(audience, str): 

151 _validate_single_audience(audience) 

152 return 

153 

154 if isinstance(audience, (list, tuple, set)): 

155 _validate_jwt_audience_collection(audience) 

156 return 

157 

158 raise TypeError("Audience must be a string or iterable of strings") 

159 

160 

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. 

177 

178 Enforces that 'exp' (expiration) and 'aud' (audience) claims are present 

179 and validated. Explicitly rejects the "none" algorithm. 

180 

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). 

186 

187 Returns: 

188 The decoded payload dictionary. 

189 

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. 

193 

194 """ 

195 if not isinstance(token, str): 

196 raise TypeError("Token must be a string") 

197 

198 if not isinstance(secret_key, str): 

199 raise TypeError("Secret must be a string") 

200 

201 _validate_jwt_algorithms(algorithms) 

202 _validate_jwt_audience(audience) 

203 

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 )