jwt-toolkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,602 @@
1
+ import re
2
+ import time
3
+ from collections.abc import Iterable, Iterator
4
+ from dataclasses import dataclass, field
5
+ from enum import Enum
6
+
7
+ # Auditor module — static security analysis of a decoded JWT header and payload.
8
+
9
+ # Symmetric algorithms — vulnerable to offline brute-force if the secret is weak.
10
+ SYMMETRIC_ALGORITHMS = {"HS256", "HS384", "HS512"}
11
+
12
+ # Asymmetric algorithms — public/private key pairs, no shared secret to crack.
13
+ ASYMMETRIC_ALGORITHMS = {
14
+ "RS256",
15
+ "RS384",
16
+ "RS512",
17
+ "ES256",
18
+ "ES384",
19
+ "ES512",
20
+ "PS256",
21
+ "PS384",
22
+ "PS512",
23
+ }
24
+
25
+ # Lifetime tiers, evaluated longest-first so the most severe match wins.
26
+ # Severity is derived in _audit_expiry to keep the table flat and editable.
27
+ _LIFETIME_TIERS: tuple[tuple[int, str], ...] = (
28
+ (60 * 60 * 24 * 30, "more than 30 days"),
29
+ (60 * 60 * 24, "more than 24 hours"),
30
+ (60 * 60, "more than 1 hour"),
31
+ )
32
+
33
+ # Small clock-skew leeway when judging "iat in the future" — most systems drift a bit.
34
+ _IAT_FUTURE_LEEWAY_SECONDS = 60
35
+
36
+ # Header parameters that smuggle a key into the token itself.
37
+ # An attacker who controls these can sometimes coerce the verifier into trusting their key.
38
+ _KEY_SMUGGLING_HEADERS = ("jwk", "jku", "x5u", "x5c")
39
+
40
+ # CVE references attached to findings whose shape matches a known disclosed vulnerability.
41
+ # Keep the catalogue narrow — only well-known CVEs that map cleanly to a single header pattern.
42
+ _CVE_ALG_NONE = "CVE-2015-2951"
43
+ _CVE_HS_RS_CONFUSION = "CVE-2016-10555"
44
+ _CVE_JWK_INJECTION = "CVE-2018-0114"
45
+
46
+ # Characters that have caused real-world `kid` injection bugs
47
+ # (path traversal, SQLi, command injection, null-byte truncation).
48
+ # "/" is intentionally excluded — it is a legitimate path separator in
49
+ # key IDs like "prod-key/v1"; ".." already catches actual path traversal.
50
+ _KID_DANGEROUS_CHARS = ("..", "\\", "\x00", "'", '"', ";", "`", "$(")
51
+
52
+ # Acceptable `typ` values per RFC 7519 / RFC 9068 (access tokens).
53
+ _VALID_TYP_VALUES = {"JWT", "AT+JWT"}
54
+
55
+ # Heuristics for sensitive-value scanning. Conservative on purpose — we'd rather
56
+ # miss a borderline case than spam the report with false positives.
57
+ _EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
58
+ _DIGITS_ONLY_RE = re.compile(r"^\d{13,19}$")
59
+
60
+ # Field names that should never appear in a JWT payload (encoded, not encrypted).
61
+ SENSITIVE_FIELDS = {
62
+ "password",
63
+ "passwd",
64
+ "pwd",
65
+ "secret",
66
+ "api_key",
67
+ "apikey",
68
+ "token",
69
+ "access_token",
70
+ "refresh_token",
71
+ "ssn",
72
+ "credit_card",
73
+ "card_number",
74
+ "cvv",
75
+ "email", # email is borderline but common enough to flag
76
+ }
77
+
78
+
79
+ # Severity levels — ordered so higher-severity findings sort first.
80
+ class Severity(Enum):
81
+ CRITICAL = "CRITICAL"
82
+ WARN = "WARN"
83
+ INFO = "INFO"
84
+ PASS = "PASS"
85
+
86
+
87
+ # Letter grade derived from the set of findings.
88
+ class Grade(Enum):
89
+ A = "A"
90
+ B = "B"
91
+ C = "C"
92
+ F = "F"
93
+
94
+
95
+ # Stable sort order for findings — CRITICAL first, PASS last.
96
+ _SEVERITY_ORDER = {
97
+ Severity.CRITICAL: 0,
98
+ Severity.WARN: 1,
99
+ Severity.INFO: 2,
100
+ Severity.PASS: 3,
101
+ }
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class Finding:
106
+ severity: Severity
107
+ field: str
108
+ message: str
109
+ # Short, actionable next step. Optional so legacy callers stay valid.
110
+ recommendation: str | None = None
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Report:
115
+ findings: tuple[Finding, ...]
116
+ grade: Grade
117
+ counts: dict[Severity, int] = field(default_factory=dict)
118
+
119
+
120
+ # Public entry point. The command layer should only ever call this — never the
121
+ # individual `_audit_*` helpers or `audit()` directly — so grading and sorting
122
+ # stay in lockstep with the findings.
123
+ def run_audit(
124
+ header: dict,
125
+ payload: dict,
126
+ *,
127
+ required_claims: frozenset[str] = frozenset(),
128
+ ) -> Report:
129
+ findings = tuple(
130
+ sorted(
131
+ audit(header, payload, required_claims=required_claims),
132
+ key=_finding_sort_key,
133
+ )
134
+ )
135
+ return Report(
136
+ findings=findings,
137
+ grade=_grade(findings),
138
+ counts=_count_by_severity(findings),
139
+ )
140
+
141
+
142
+ # Legacy in-module entry point. Kept because `run_audit` composes it.
143
+ def audit(
144
+ header: dict,
145
+ payload: dict,
146
+ *,
147
+ required_claims: frozenset[str] = frozenset(),
148
+ ) -> list[Finding]:
149
+ findings: list[Finding] = []
150
+ findings.extend(_audit_algorithm(header))
151
+ findings.extend(_audit_typ(header))
152
+ findings.extend(_audit_kid_injection(header))
153
+ findings.extend(_audit_header_key_smuggling(header))
154
+ findings.extend(_audit_alg_key_confusion(header))
155
+ findings.extend(_audit_crit(header))
156
+ findings.extend(_audit_b64(header))
157
+ findings.extend(_audit_expiry(payload))
158
+ findings.extend(_audit_nbf(payload))
159
+ findings.extend(_audit_iat(payload))
160
+ findings.extend(_audit_jti(payload))
161
+ findings.extend(_audit_claims(payload, required_claims=required_claims))
162
+ findings.extend(_audit_sensitive_fields(payload))
163
+ findings.extend(_audit_sensitive_values(payload))
164
+ return findings
165
+
166
+
167
+ # Grading
168
+
169
+
170
+ # Single source of truth for grade boundaries. `--strict` lives at the command
171
+ # layer; this function never sees it.
172
+ def _grade(findings: Iterable[Finding]) -> Grade:
173
+ findings = tuple(findings)
174
+ if any(f.severity is Severity.CRITICAL for f in findings):
175
+ return Grade.F
176
+ warns = sum(1 for f in findings if f.severity is Severity.WARN)
177
+ if warns >= 3:
178
+ return Grade.C
179
+ if warns >= 1:
180
+ return Grade.B
181
+ return Grade.A
182
+
183
+
184
+ def _count_by_severity(findings: Iterable[Finding]) -> dict[Severity, int]:
185
+ counts = dict.fromkeys(Severity, 0)
186
+ for f in findings:
187
+ counts[f.severity] += 1
188
+ return counts
189
+
190
+
191
+ def _finding_sort_key(f: Finding) -> tuple[int, str]:
192
+ # Group by severity, then alphabetise by field for deterministic output.
193
+ return (_SEVERITY_ORDER[f.severity], f.field)
194
+
195
+
196
+ # Header checks
197
+ def _audit_algorithm(header: dict) -> list[Finding]:
198
+ alg = str(header.get("alg", "")).upper()
199
+ if alg == "NONE":
200
+ return [
201
+ Finding(
202
+ Severity.CRITICAL,
203
+ "alg",
204
+ f"alg:none means the token carries no signature ({_CVE_ALG_NONE})",
205
+ "Reject tokens whose header advertises alg:none at the verifier.",
206
+ )
207
+ ]
208
+ if alg in SYMMETRIC_ALGORITHMS:
209
+ return [
210
+ Finding(
211
+ Severity.WARN,
212
+ "alg",
213
+ f"{alg} is symmetric — the shared secret must be strong or it can be brute-forced",
214
+ "Use a cryptographically strong secret (jwt-toolkit generate-secret) "
215
+ "or migrate to an asymmetric algorithm.",
216
+ )
217
+ ]
218
+ if alg in ASYMMETRIC_ALGORITHMS:
219
+ return [Finding(Severity.PASS, "alg", f"{alg} uses asymmetric keys")]
220
+ return [
221
+ Finding(
222
+ Severity.WARN,
223
+ "alg",
224
+ f"Unknown algorithm: {alg or '(missing)'}",
225
+ "Pin the verifier to an explicit allow-list of algorithms.",
226
+ )
227
+ ]
228
+
229
+
230
+ def _audit_typ(header: dict) -> list[Finding]:
231
+ if "typ" not in header:
232
+ return [
233
+ Finding(
234
+ Severity.INFO,
235
+ "typ",
236
+ "No typ header — consumers cannot distinguish JWTs from other JOSE objects",
237
+ )
238
+ ]
239
+ typ = str(header["typ"]).upper()
240
+ if typ in _VALID_TYP_VALUES:
241
+ return [Finding(Severity.PASS, "typ", f"typ={header['typ']}")]
242
+ return [
243
+ Finding(
244
+ Severity.WARN,
245
+ "typ",
246
+ f"Unexpected typ value: {typ!r}",
247
+ "Set typ to 'JWT' or 'at+jwt' so verifiers can reject unrelated tokens.",
248
+ )
249
+ ]
250
+
251
+
252
+ def _audit_kid_injection(header: dict) -> list[Finding]:
253
+ kid = header.get("kid")
254
+ if kid is None:
255
+ return []
256
+ if not isinstance(kid, str):
257
+ return [
258
+ Finding(
259
+ Severity.WARN,
260
+ "kid",
261
+ f"kid is not a string ({type(kid).__name__}) — verifiers may mishandle it",
262
+ )
263
+ ]
264
+ hit = next((c for c in _KID_DANGEROUS_CHARS if c in kid), None)
265
+ if hit is not None:
266
+ return [
267
+ Finding(
268
+ Severity.CRITICAL,
269
+ "kid",
270
+ f"kid contains dangerous sequence {hit!r} — possible injection attempt",
271
+ "Look up keys by exact match against an allow-list; never concatenate kid "
272
+ "into a path, SQL query, or shell command.",
273
+ )
274
+ ]
275
+ return [Finding(Severity.PASS, "kid", "kid looks well-formed")]
276
+
277
+
278
+ def _audit_header_key_smuggling(header: dict) -> list[Finding]:
279
+ findings: list[Finding] = []
280
+ for name in _KEY_SMUGGLING_HEADERS:
281
+ if name not in header:
282
+ continue
283
+ value = header[name]
284
+ if name == "jwk":
285
+ findings.append(
286
+ Finding(
287
+ Severity.CRITICAL,
288
+ "jwk",
289
+ f"Header embeds a JWK — an attacker can ship their own key with the token ({_CVE_JWK_INJECTION})",
290
+ "Ignore the embedded jwk header; resolve keys from a server-side trust store.",
291
+ )
292
+ )
293
+ continue
294
+ # jku, x5u, x5c — URLs to remote key material.
295
+ url = str(value) if not isinstance(value, list) else (value[0] if value else "")
296
+ if isinstance(url, str) and url.lower().startswith("http://"):
297
+ findings.append(
298
+ Finding(
299
+ Severity.CRITICAL,
300
+ name,
301
+ f"{name} uses plain HTTP — key material can be MITM'd",
302
+ f"Require HTTPS for {name}, and pin to an allow-list of hosts.",
303
+ )
304
+ )
305
+ else:
306
+ findings.append(
307
+ Finding(
308
+ Severity.WARN,
309
+ name,
310
+ f"{name} header references external key material",
311
+ f"Pin {name} to an allow-list of trusted hosts; never blindly fetch.",
312
+ )
313
+ )
314
+ return findings
315
+
316
+
317
+ # Cross-check: HS* algorithm combined with header-supplied key material is the
318
+ # classic key-confusion shape — the verifier may resolve the "public key" from
319
+ # the header and then use it as an HMAC secret.
320
+ def _audit_alg_key_confusion(header: dict) -> list[Finding]:
321
+ alg = str(header.get("alg", "")).upper()
322
+ if alg not in SYMMETRIC_ALGORITHMS:
323
+ return []
324
+ smuggled = [name for name in _KEY_SMUGGLING_HEADERS if name in header]
325
+ if not smuggled:
326
+ return []
327
+ return [
328
+ Finding(
329
+ Severity.CRITICAL,
330
+ "alg",
331
+ f"alg={alg} combined with {', '.join(smuggled)} header(s) — "
332
+ f"classic key-confusion shape ({_CVE_HS_RS_CONFUSION})",
333
+ "Pin the verifier to one algorithm family per key; never resolve HMAC "
334
+ "secrets from header-supplied key material.",
335
+ )
336
+ ]
337
+
338
+
339
+ def _audit_crit(header: dict) -> list[Finding]:
340
+ if "crit" not in header:
341
+ return []
342
+ crit = header["crit"]
343
+ if not isinstance(crit, list) or not all(isinstance(x, str) for x in crit):
344
+ return [
345
+ Finding(
346
+ Severity.CRITICAL,
347
+ "crit",
348
+ "crit header is malformed — RFC 7515 requires a non-empty list of strings",
349
+ "Reject the token; a malformed crit is unparseable and unsafe to ignore.",
350
+ )
351
+ ]
352
+ if not crit:
353
+ return [
354
+ Finding(
355
+ Severity.WARN,
356
+ "crit",
357
+ "crit header is an empty list — RFC 7515 requires at least one entry",
358
+ "Reject tokens with an empty crit list.",
359
+ )
360
+ ]
361
+ dangling = [name for name in crit if name not in header]
362
+ if dangling:
363
+ return [
364
+ Finding(
365
+ Severity.CRITICAL,
366
+ "crit",
367
+ f"crit lists parameter(s) not present in the header: {dangling}",
368
+ "Reject the token — every name in crit must be a recognised, present header parameter.",
369
+ )
370
+ ]
371
+ return [
372
+ Finding(
373
+ Severity.WARN,
374
+ "crit",
375
+ f"crit header is present ({crit}) — many verifiers silently ignore it",
376
+ "Confirm the verifier rejects tokens whose crit extensions it does not implement.",
377
+ )
378
+ ]
379
+
380
+
381
+ def _audit_b64(header: dict) -> list[Finding]:
382
+ if "b64" not in header:
383
+ return []
384
+ b64 = header["b64"]
385
+ if b64 is False:
386
+ return [
387
+ Finding(
388
+ Severity.WARN,
389
+ "b64",
390
+ "b64:false (RFC 7797) — payload is not base64url-encoded; "
391
+ "many verifiers mishandle this form",
392
+ "Reject tokens with b64:false unless the verifier explicitly implements RFC 7797.",
393
+ )
394
+ ]
395
+ if b64 is True:
396
+ return [
397
+ Finding(
398
+ Severity.INFO,
399
+ "b64",
400
+ "b64:true is the default — the header is redundant but harmless",
401
+ )
402
+ ]
403
+ return [
404
+ Finding(
405
+ Severity.WARN,
406
+ "b64",
407
+ f"b64 header has non-boolean value ({type(b64).__name__}) — RFC 7797 requires a boolean",
408
+ )
409
+ ]
410
+
411
+
412
+ # Payload checks
413
+ def _audit_expiry(payload: dict) -> list[Finding]:
414
+ exp = payload.get("exp")
415
+ iat = payload.get("iat")
416
+ if exp is None:
417
+ return [
418
+ Finding(
419
+ Severity.WARN,
420
+ "exp",
421
+ "No exp claim — token never expires",
422
+ "Always set exp; short-lived tokens limit blast radius if leaked.",
423
+ )
424
+ ]
425
+ if not isinstance(exp, (int, float)):
426
+ return [Finding(Severity.WARN, "exp", f"exp is not numeric ({type(exp).__name__})")]
427
+
428
+ now = time.time()
429
+ if exp < now:
430
+ return [Finding(Severity.CRITICAL, "exp", "Token is expired")]
431
+
432
+ # Lifetime measured from iat when available, otherwise from now.
433
+ lifetime = exp - (iat if isinstance(iat, (int, float)) else now)
434
+ for threshold, suffix in _LIFETIME_TIERS:
435
+ if lifetime > threshold:
436
+ severity = (
437
+ Severity.CRITICAL
438
+ if threshold >= 60 * 60 * 24 * 30
439
+ else Severity.WARN
440
+ if threshold >= 60 * 60 * 24
441
+ else Severity.INFO
442
+ )
443
+ return [
444
+ Finding(
445
+ severity,
446
+ "exp",
447
+ f"Token lifetime is {suffix}",
448
+ "Shorten the TTL; pair access tokens with a refresh-token rotation flow.",
449
+ )
450
+ ]
451
+ return [Finding(Severity.PASS, "exp", "Token expiry looks reasonable")]
452
+
453
+
454
+ def _audit_nbf(payload: dict) -> list[Finding]:
455
+ nbf = payload.get("nbf")
456
+ if nbf is None:
457
+ return []
458
+ if not isinstance(nbf, (int, float)):
459
+ return [Finding(Severity.WARN, "nbf", f"nbf is not numeric ({type(nbf).__name__})")]
460
+ if time.time() < nbf:
461
+ return [Finding(Severity.CRITICAL, "nbf", "Token is not yet valid (nbf is in the future)")]
462
+ return [Finding(Severity.PASS, "nbf", "Token is past its not-before time")]
463
+
464
+
465
+ def _audit_iat(payload: dict) -> list[Finding]:
466
+ iat = payload.get("iat")
467
+ if iat is None:
468
+ return []
469
+ if not isinstance(iat, (int, float)):
470
+ return [Finding(Severity.WARN, "iat", f"iat is not numeric ({type(iat).__name__})")]
471
+ exp = payload.get("exp")
472
+ if isinstance(exp, (int, float)) and exp < iat:
473
+ return [
474
+ Finding(
475
+ Severity.CRITICAL,
476
+ "iat",
477
+ "exp is earlier than iat — token is malformed and may be rejected unpredictably",
478
+ )
479
+ ]
480
+ if iat > time.time() + _IAT_FUTURE_LEEWAY_SECONDS:
481
+ return [
482
+ Finding(
483
+ Severity.WARN,
484
+ "iat",
485
+ "iat is in the future — clock skew or a forged token",
486
+ )
487
+ ]
488
+ return [Finding(Severity.PASS, "iat", "iat looks sane")]
489
+
490
+
491
+ def _audit_jti(payload: dict) -> list[Finding]:
492
+ if "jti" not in payload:
493
+ return [
494
+ Finding(
495
+ Severity.INFO,
496
+ "jti",
497
+ "No jti claim — replay-defense via a token blocklist is harder",
498
+ "Issue a unique jti per token so revocation and replay-detection are possible.",
499
+ )
500
+ ]
501
+ return []
502
+
503
+
504
+ def _audit_claims(
505
+ payload: dict,
506
+ *,
507
+ required_claims: frozenset[str] = frozenset(),
508
+ ) -> list[Finding]:
509
+ findings = []
510
+ for claim in ("iss", "aud", "iat"):
511
+ if claim not in payload:
512
+ severity = Severity.WARN if claim in required_claims else Severity.INFO
513
+ findings.append(Finding(severity, claim, f"Missing {claim} claim"))
514
+ return findings
515
+
516
+
517
+ def _audit_sensitive_fields(payload: dict) -> list[Finding]:
518
+ return [
519
+ Finding(
520
+ Severity.WARN,
521
+ key,
522
+ f"Payload contains sensitive field {key!r} — JWTs are encoded, not encrypted",
523
+ "Move secrets out of the payload; pass them via a confidential side-channel.",
524
+ )
525
+ for key in payload
526
+ if key.lower() in SENSITIVE_FIELDS
527
+ ]
528
+
529
+
530
+ def _audit_sensitive_values(payload: dict) -> list[Finding]:
531
+ # Walks nested dicts/lists looking for values that *look* like PII even when
532
+ # the surrounding field name doesn't tip us off. Top-level keys already
533
+ # caught by _audit_sensitive_fields are skipped to avoid duplicate findings.
534
+ # Multiple hits of the same type are grouped into one finding to keep the
535
+ # report readable when a payload has many PII fields.
536
+ email_paths: list[str] = []
537
+ card_paths: list[str] = []
538
+ seen_paths: set[str] = set()
539
+ skip_roots = {key for key in payload if key.lower() in SENSITIVE_FIELDS}
540
+
541
+ for path, value in _walk(payload):
542
+ root = path.split(".", 1)[0].split("[", 1)[0]
543
+ if root in skip_roots or path in seen_paths or not isinstance(value, str):
544
+ continue
545
+ if _EMAIL_RE.match(value):
546
+ email_paths.append(path)
547
+ seen_paths.add(path)
548
+ elif _DIGITS_ONLY_RE.match(value) and _looks_like_card(value):
549
+ card_paths.append(path)
550
+ seen_paths.add(path)
551
+
552
+ findings: list[Finding] = []
553
+ if email_paths:
554
+ label = "paths" if len(email_paths) > 1 else "path"
555
+ findings.append(
556
+ Finding(
557
+ Severity.WARN,
558
+ "payload",
559
+ f"Email-like value{'' if len(email_paths) == 1 else 's'} at {label}: "
560
+ + ", ".join(email_paths),
561
+ "Avoid embedding PII in JWT payloads; use an opaque subject identifier.",
562
+ )
563
+ )
564
+ if card_paths:
565
+ label = "paths" if len(card_paths) > 1 else "path"
566
+ findings.append(
567
+ Finding(
568
+ Severity.CRITICAL,
569
+ "payload",
570
+ f"Credit-card-like value{'' if len(card_paths) == 1 else 's'} "
571
+ f"(Luhn-valid) at {label}: " + ", ".join(card_paths),
572
+ "Never place card data in a JWT — it is base64, not encryption.",
573
+ )
574
+ )
575
+ return findings
576
+
577
+
578
+ def _walk(node, prefix: str = "") -> Iterator[tuple[str, object]]:
579
+ # Yields (dotted_path, value) for every leaf and container in a JSON-like tree.
580
+ if isinstance(node, dict):
581
+ for key, value in node.items():
582
+ child_path = f"{prefix}.{key}" if prefix else str(key)
583
+ yield child_path, value
584
+ yield from _walk(value, child_path)
585
+ elif isinstance(node, list):
586
+ for idx, value in enumerate(node):
587
+ child_path = f"{prefix}[{idx}]"
588
+ yield child_path, value
589
+ yield from _walk(value, child_path)
590
+
591
+
592
+ def _looks_like_card(digits: str) -> bool:
593
+ # Luhn checksum — keeps false positives down on long numeric IDs.
594
+ total = 0
595
+ for i, ch in enumerate(reversed(digits)):
596
+ n = ord(ch) - 48
597
+ if i % 2 == 1:
598
+ n *= 2
599
+ if n > 9:
600
+ n -= 9
601
+ total += n
602
+ return total % 10 == 0