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,290 @@
1
+ import json
2
+ import time
3
+ from pathlib import Path
4
+
5
+ import click
6
+ from rich.panel import Panel
7
+ from rich.table import Table
8
+
9
+ from jwt_toolkit.cli.algorithms import ensure_signing_algorithm, is_hmac
10
+ from jwt_toolkit.cli.console import console
11
+ from jwt_toolkit.cli.decoding import (
12
+ JSON_SCHEMA_VERSION,
13
+ render_algorithm_error,
14
+ resolve_token,
15
+ safe_decode,
16
+ )
17
+ from jwt_toolkit.cli.panels import print_error
18
+ from jwt_toolkit.core.crypto import verify_asymmetric, verify_signature
19
+ from jwt_toolkit.core.errors import UnsupportedAlgorithmError
20
+ from jwt_toolkit.core.jwks import resolve_jwks_key
21
+
22
+ # Verify command — checks the signature and validates claims (exp, nbf, iat, iss, aud).
23
+ # Three key-source modes, mutually exclusive:
24
+ # --secret HMAC secret (HS* tokens)
25
+ # --public-key PEM public key (RS*/PS*/ES* tokens)
26
+ # --jwks-url JWKS endpoint or file:// path; key resolved by the token's kid
27
+
28
+ RESULT_COLORS = {
29
+ "PASS": "bold green",
30
+ "FAIL": "bold red",
31
+ "WARN": "yellow",
32
+ }
33
+
34
+ # Small leeway used when checking iat-in-future — matches the auditor's constant.
35
+ _IAT_FUTURE_LEEWAY_SECONDS = 60
36
+
37
+
38
+ @click.command(help="Verify a JWT's signature and standard claims (exp, nbf, iat, iss, aud).")
39
+ @click.argument("token")
40
+ @click.option(
41
+ "--secret",
42
+ default=None,
43
+ help="HMAC secret to verify against (HS256/HS384/HS512). Mutually exclusive with --public-key.",
44
+ )
45
+ @click.option(
46
+ "--public-key",
47
+ "public_key_path",
48
+ default=None,
49
+ type=click.Path(exists=True, dir_okay=False, readable=True, path_type=Path),
50
+ help="Path to a PEM-encoded public key (RS*/PS*/ES*). Mutually exclusive with --secret.",
51
+ )
52
+ @click.option(
53
+ "--jwks-url",
54
+ "jwks_url",
55
+ default=None,
56
+ help=(
57
+ "JWKS endpoint (https://, http://, or file://). The token's kid header "
58
+ "selects the verification key. Mutually exclusive with --secret/--public-key."
59
+ ),
60
+ )
61
+ @click.option("--issuer", default=None, help="Expected issuer (iss claim)")
62
+ @click.option("--audience", default=None, help="Expected audience (aud claim)")
63
+ @click.option(
64
+ "--leeway",
65
+ default=0,
66
+ show_default=True,
67
+ type=click.IntRange(0),
68
+ help="Clock-skew tolerance in seconds for exp/nbf checks",
69
+ )
70
+ @click.option(
71
+ "--json",
72
+ "as_json",
73
+ is_flag=True,
74
+ help="Emit a machine-readable JSON report.",
75
+ )
76
+ def verify(
77
+ token: str,
78
+ secret: str | None,
79
+ public_key_path: Path | None,
80
+ jwks_url: str | None,
81
+ issuer: str | None,
82
+ audience: str | None,
83
+ leeway: int,
84
+ as_json: bool,
85
+ ):
86
+ token = resolve_token(token)
87
+
88
+ decoded = safe_decode(token, as_json=as_json)
89
+ try:
90
+ alg = ensure_signing_algorithm(decoded.header)
91
+ except UnsupportedAlgorithmError as exc:
92
+ render_algorithm_error(exc)
93
+ raise SystemExit(2) from exc
94
+
95
+ _validate_key_inputs(alg, secret=secret, public_key_path=public_key_path, jwks_url=jwks_url)
96
+
97
+ rows: list[tuple[str, str, str]] = []
98
+ failed = False
99
+
100
+ try:
101
+ sig_valid = _verify_signature(
102
+ decoded,
103
+ alg,
104
+ secret=secret,
105
+ public_key_path=public_key_path,
106
+ jwks_url=jwks_url,
107
+ )
108
+ except ValueError as exc:
109
+ print_error(
110
+ "Could not verify signature with the provided key",
111
+ str(exc),
112
+ title="Key Error",
113
+ )
114
+ raise SystemExit(2) from exc
115
+
116
+ if sig_valid:
117
+ rows.append(("PASS", "signature", "Signature is valid"))
118
+ else:
119
+ rows.append(("FAIL", "signature", "Signature is invalid, wrong key or tampered token"))
120
+ failed = True
121
+
122
+ failed |= _check_temporal_claims(decoded.payload, rows, leeway=leeway)
123
+ if issuer is not None:
124
+ failed |= _check_issuer(decoded.payload, issuer, rows)
125
+ if audience is not None:
126
+ failed |= _check_audience(decoded.payload, audience, rows)
127
+
128
+ if as_json:
129
+ _emit_json(rows, failed=failed)
130
+ else:
131
+ _render_results(rows, failed=failed)
132
+
133
+
134
+ def _validate_key_inputs(
135
+ alg: str,
136
+ *,
137
+ secret: str | None,
138
+ public_key_path: Path | None,
139
+ jwks_url: str | None,
140
+ ) -> None:
141
+ # Enforce exactly-one key source. Counting truthy options is clearer than
142
+ # nested pairwise checks once a third mode enters the picture.
143
+ sources = sum(x is not None for x in (secret, public_key_path, jwks_url))
144
+ if sources > 1:
145
+ print_error(
146
+ "Pass only one of --secret, --public-key, or --jwks-url",
147
+ title="Invalid Input",
148
+ )
149
+ raise SystemExit(2)
150
+
151
+ if is_hmac(alg):
152
+ if jwks_url is not None or public_key_path is not None:
153
+ print_error(
154
+ f"{alg} is an HMAC algorithm — use --secret",
155
+ title="Invalid Input",
156
+ )
157
+ raise SystemExit(2)
158
+ if not secret:
159
+ print_error(
160
+ f"{alg} requires --secret",
161
+ "Provide the HMAC secret the token was signed with.",
162
+ title="Invalid Input",
163
+ )
164
+ raise SystemExit(2)
165
+ return
166
+
167
+ # Asymmetric path — accept either a PEM file or a JWKS URL.
168
+ if public_key_path is None and jwks_url is None:
169
+ print_error(
170
+ f"{alg} requires --public-key or --jwks-url",
171
+ "Provide a PEM-encoded public key, or a JWKS endpoint the token's kid resolves against.",
172
+ title="Invalid Input",
173
+ )
174
+ raise SystemExit(2)
175
+ if secret is not None:
176
+ print_error(
177
+ f"{alg} is an asymmetric algorithm — use --public-key or --jwks-url, not --secret",
178
+ title="Invalid Input",
179
+ )
180
+ raise SystemExit(2)
181
+
182
+
183
+ def _verify_signature(
184
+ decoded,
185
+ alg: str,
186
+ *,
187
+ secret: str | None,
188
+ public_key_path: Path | None,
189
+ jwks_url: str | None,
190
+ ) -> bool:
191
+ if is_hmac(alg):
192
+ return verify_signature(
193
+ decoded.header_b64, decoded.payload_b64, decoded.signature, secret or "", alg
194
+ )
195
+ if jwks_url is not None:
196
+ kid = decoded.header.get("kid")
197
+ pem_bytes = resolve_jwks_key(jwks_url, kid=kid, alg=alg)
198
+ else:
199
+ pem_bytes = public_key_path.read_bytes() # type: ignore[union-attr]
200
+ return verify_asymmetric(
201
+ decoded.header_b64, decoded.payload_b64, decoded.signature, pem_bytes, alg
202
+ )
203
+
204
+
205
+ def _check_temporal_claims(
206
+ payload: dict, rows: list[tuple[str, str, str]], *, leeway: int = 0
207
+ ) -> bool:
208
+ now = time.time()
209
+ failed = False
210
+
211
+ exp = payload.get("exp")
212
+ if exp is None:
213
+ rows.append(("WARN", "exp", "No expiry claim"))
214
+ elif not isinstance(exp, (int, float)):
215
+ rows.append(("FAIL", "exp", f"exp is not a number: {exp!r}"))
216
+ failed = True
217
+ elif exp + leeway < now:
218
+ rows.append(("FAIL", "exp", "Token is expired"))
219
+ failed = True
220
+ else:
221
+ rows.append(("PASS", "exp", "Token is not expired"))
222
+
223
+ nbf = payload.get("nbf")
224
+ if nbf is not None:
225
+ if not isinstance(nbf, (int, float)):
226
+ rows.append(("FAIL", "nbf", f"nbf is not a number: {nbf!r}"))
227
+ failed = True
228
+ elif nbf > now + leeway:
229
+ rows.append(("FAIL", "nbf", "Token is not yet valid (nbf is in the future)"))
230
+ failed = True
231
+
232
+ iat = payload.get("iat")
233
+ if iat is not None:
234
+ if not isinstance(iat, (int, float)):
235
+ rows.append(("WARN", "iat", f"iat is not a number: {iat!r}"))
236
+ elif iat > now + _IAT_FUTURE_LEEWAY_SECONDS + leeway:
237
+ rows.append(("WARN", "iat", "iat is in the future — clock skew or forged token"))
238
+
239
+ return failed
240
+
241
+
242
+ def _check_issuer(payload: dict, issuer: str, rows: list[tuple[str, str, str]]) -> bool:
243
+ if payload.get("iss") == issuer:
244
+ rows.append(("PASS", "iss", f"Issuer matches '{issuer}'"))
245
+ return False
246
+ rows.append(
247
+ ("FAIL", "iss", f"Issuer mismatch: expected '{issuer}', got '{payload.get('iss')}'")
248
+ )
249
+ return True
250
+
251
+
252
+ def _check_audience(payload: dict, audience: str, rows: list[tuple[str, str, str]]) -> bool:
253
+ # aud can be a string or a list per RFC 7519.
254
+ aud = payload.get("aud")
255
+ aud_list = [aud] if isinstance(aud, str) else (aud if isinstance(aud, list) else [])
256
+ if audience in aud_list:
257
+ rows.append(("PASS", "aud", f"Audience matches '{audience}'"))
258
+ return False
259
+ rows.append(("FAIL", "aud", f"Audience mismatch: expected '{audience}', got {aud!r}"))
260
+ return True
261
+
262
+
263
+ def _emit_json(rows: list[tuple[str, str, str]], *, failed: bool) -> None:
264
+ document = {
265
+ "schema_version": JSON_SCHEMA_VERSION,
266
+ "valid": not failed,
267
+ "checks": [
268
+ {"result": result, "check": check, "detail": detail} for result, check, detail in rows
269
+ ],
270
+ }
271
+ click.echo(json.dumps(document, indent=2))
272
+ raise SystemExit(1 if failed else 0)
273
+
274
+
275
+ def _render_results(rows: list[tuple[str, str, str]], *, failed: bool) -> None:
276
+ table = Table(title="Verification Checks", show_lines=True)
277
+ table.add_column("Result", style="bold", width=8)
278
+ table.add_column("Check", width=12)
279
+ table.add_column("Detail")
280
+
281
+ for result, check, detail in rows:
282
+ color = RESULT_COLORS[result]
283
+ table.add_row(f"[{color}]{result}[/{color}]", check, detail)
284
+
285
+ console.print(table)
286
+
287
+ if failed:
288
+ console.print(Panel("[bold red]INVALID[/bold red]", border_style="red"))
289
+ raise SystemExit(1)
290
+ console.print(Panel("[bold green]VALID[/bold green]", border_style="green"))
File without changes