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.
- jwt_toolkit/__init__.py +0 -0
- jwt_toolkit/cli/__init__.py +110 -0
- jwt_toolkit/cli/algorithms.py +66 -0
- jwt_toolkit/cli/banner.py +277 -0
- jwt_toolkit/cli/console.py +35 -0
- jwt_toolkit/cli/decoding.py +83 -0
- jwt_toolkit/cli/panels.py +28 -0
- jwt_toolkit/commands/__init__.py +0 -0
- jwt_toolkit/commands/audit.py +269 -0
- jwt_toolkit/commands/crack.py +322 -0
- jwt_toolkit/commands/decode.py +54 -0
- jwt_toolkit/commands/download_wordlists.py +216 -0
- jwt_toolkit/commands/forge.py +133 -0
- jwt_toolkit/commands/generate_secret.py +72 -0
- jwt_toolkit/commands/sign.py +146 -0
- jwt_toolkit/commands/verify.py +290 -0
- jwt_toolkit/core/__init__.py +0 -0
- jwt_toolkit/core/auditor.py +602 -0
- jwt_toolkit/core/crypto.py +229 -0
- jwt_toolkit/core/decoder.py +70 -0
- jwt_toolkit/core/encoding.py +22 -0
- jwt_toolkit/core/errors.py +25 -0
- jwt_toolkit/core/forge.py +260 -0
- jwt_toolkit/core/jwks.py +197 -0
- jwt_toolkit-0.1.0.dist-info/METADATA +116 -0
- jwt_toolkit-0.1.0.dist-info/RECORD +29 -0
- jwt_toolkit-0.1.0.dist-info/WHEEL +4 -0
- jwt_toolkit-0.1.0.dist-info/entry_points.txt +2 -0
- jwt_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import ssl
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.request
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from rich.progress import (
|
|
9
|
+
BarColumn,
|
|
10
|
+
DownloadColumn,
|
|
11
|
+
Progress,
|
|
12
|
+
SpinnerColumn,
|
|
13
|
+
TextColumn,
|
|
14
|
+
TimeElapsedColumn,
|
|
15
|
+
TimeRemainingColumn,
|
|
16
|
+
TransferSpeedColumn,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from jwt_toolkit.cli.console import console
|
|
20
|
+
from jwt_toolkit.cli.panels import print_error, print_success
|
|
21
|
+
|
|
22
|
+
# Download command — fetches the latest common-secrets wordlist from the jwt-toolkit repo.
|
|
23
|
+
|
|
24
|
+
_WORDLIST_URL = (
|
|
25
|
+
"https://raw.githubusercontent.com/KhaledSaeed18/jwt-toolkit/main/wordlists/common-secrets.txt"
|
|
26
|
+
)
|
|
27
|
+
_FILENAME = "common-secrets.txt"
|
|
28
|
+
|
|
29
|
+
# SHA-256 of the bundled wordlist at _WORDLIST_URL. Verified against local copy.
|
|
30
|
+
# Only used when downloading from the default URL; custom --source URLs skip this check.
|
|
31
|
+
_WORDLIST_SHA256 = "1b4bae820e98073b7148412425ea27e00cd1c4d0900ad446bdae146665ea758a"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _open_url(url: str):
|
|
35
|
+
try:
|
|
36
|
+
return urllib.request.urlopen(url, timeout=30)
|
|
37
|
+
except ssl.SSLCertVerificationError:
|
|
38
|
+
console.print(
|
|
39
|
+
"[bold yellow]WARNING[/bold yellow]: TLS certificate verification failed for "
|
|
40
|
+
f"[dim]{url}[/dim]. Continuing with an unverified connection — "
|
|
41
|
+
"the download cannot be authenticated by TLS. "
|
|
42
|
+
"Check your CA bundle or use a trusted network.",
|
|
43
|
+
)
|
|
44
|
+
ctx = ssl._create_unverified_context()
|
|
45
|
+
return urllib.request.urlopen(url, context=ctx, timeout=30)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _download(url: str, dest: Path) -> int:
|
|
49
|
+
with Progress(
|
|
50
|
+
SpinnerColumn(),
|
|
51
|
+
TextColumn("[bold]common-secrets.txt[/bold]"),
|
|
52
|
+
BarColumn(),
|
|
53
|
+
DownloadColumn(),
|
|
54
|
+
TransferSpeedColumn(),
|
|
55
|
+
TimeRemainingColumn(),
|
|
56
|
+
TimeElapsedColumn(),
|
|
57
|
+
console=console, # type: ignore[arg-type] # _ConsoleProxy duck-types Console
|
|
58
|
+
transient=True,
|
|
59
|
+
) as progress:
|
|
60
|
+
try:
|
|
61
|
+
response = _open_url(url)
|
|
62
|
+
except urllib.error.HTTPError as exc:
|
|
63
|
+
raise click.ClickException(f"HTTP {exc.code} {exc.reason}: {url}") from exc
|
|
64
|
+
except urllib.error.URLError as exc:
|
|
65
|
+
raise click.ClickException(f"Network error: {exc.reason}") from exc
|
|
66
|
+
|
|
67
|
+
content_length = response.headers.get("Content-Length")
|
|
68
|
+
total = int(content_length) if content_length else None
|
|
69
|
+
task = progress.add_task("Downloading…", total=total)
|
|
70
|
+
|
|
71
|
+
written = 0
|
|
72
|
+
try:
|
|
73
|
+
with dest.open("wb") as f:
|
|
74
|
+
while True:
|
|
75
|
+
chunk = response.read(65_536)
|
|
76
|
+
if not chunk:
|
|
77
|
+
break
|
|
78
|
+
f.write(chunk)
|
|
79
|
+
written += len(chunk)
|
|
80
|
+
progress.update(task, advance=len(chunk))
|
|
81
|
+
except KeyboardInterrupt:
|
|
82
|
+
dest.unlink(missing_ok=True)
|
|
83
|
+
console.print("\n[yellow]Download cancelled[/yellow]")
|
|
84
|
+
raise SystemExit(1) from None
|
|
85
|
+
|
|
86
|
+
return written
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _sha256(path: Path) -> str:
|
|
90
|
+
h = hashlib.sha256()
|
|
91
|
+
with path.open("rb") as f:
|
|
92
|
+
for chunk in iter(lambda: f.read(65_536), b""):
|
|
93
|
+
h.update(chunk)
|
|
94
|
+
return h.hexdigest()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _count_lines(path: Path) -> int:
|
|
98
|
+
count = 0
|
|
99
|
+
with path.open("rb") as f:
|
|
100
|
+
for _ in f:
|
|
101
|
+
count += 1
|
|
102
|
+
return count
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _fmt_bytes(n: int) -> str:
|
|
106
|
+
if n >= 1_048_576:
|
|
107
|
+
return f"{n / 1_048_576:.1f} MB"
|
|
108
|
+
if n >= 1_024:
|
|
109
|
+
return f"{n / 1_024:.1f} KB"
|
|
110
|
+
return f"{n} B"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@click.command(
|
|
114
|
+
"download-wordlists",
|
|
115
|
+
help=(
|
|
116
|
+
"Download the latest common-secrets wordlist.\n\n"
|
|
117
|
+
"Fetches common-secrets.txt from the jwt-toolkit repository "
|
|
118
|
+
"so you always have the most up-to-date list of weak JWT secrets."
|
|
119
|
+
),
|
|
120
|
+
)
|
|
121
|
+
@click.option(
|
|
122
|
+
"--output-dir",
|
|
123
|
+
default="wordlists",
|
|
124
|
+
show_default=True,
|
|
125
|
+
type=click.Path(),
|
|
126
|
+
help="Directory to save the wordlist",
|
|
127
|
+
)
|
|
128
|
+
@click.option(
|
|
129
|
+
"--force",
|
|
130
|
+
is_flag=True,
|
|
131
|
+
default=False,
|
|
132
|
+
help="Overwrite existing file without prompting",
|
|
133
|
+
)
|
|
134
|
+
@click.option(
|
|
135
|
+
"--source",
|
|
136
|
+
default=None,
|
|
137
|
+
metavar="URL",
|
|
138
|
+
help=(
|
|
139
|
+
"Custom URL to download from instead of the default jwt-toolkit repository. "
|
|
140
|
+
"Integrity verification is skipped for custom sources."
|
|
141
|
+
),
|
|
142
|
+
)
|
|
143
|
+
def download_wordlists(output_dir: str, force: bool, source: str | None):
|
|
144
|
+
url = source or _WORDLIST_URL
|
|
145
|
+
verify_integrity = source is None
|
|
146
|
+
|
|
147
|
+
dest_dir = Path(output_dir).resolve()
|
|
148
|
+
|
|
149
|
+
try:
|
|
150
|
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
except OSError as exc:
|
|
152
|
+
print_error(
|
|
153
|
+
"Cannot create output directory",
|
|
154
|
+
f"Path : {dest_dir}",
|
|
155
|
+
f"Error : {exc.strerror}",
|
|
156
|
+
title="Directory Error",
|
|
157
|
+
)
|
|
158
|
+
raise SystemExit(2) from exc
|
|
159
|
+
|
|
160
|
+
dest = dest_dir / _FILENAME
|
|
161
|
+
|
|
162
|
+
if dest.exists() and not force:
|
|
163
|
+
size = dest.stat().st_size
|
|
164
|
+
console.print(
|
|
165
|
+
f"[yellow]Already exists:[/yellow] {dest} ({_fmt_bytes(size)})\n"
|
|
166
|
+
f"[dim]Use --force to overwrite with the latest version[/dim]"
|
|
167
|
+
)
|
|
168
|
+
return
|
|
169
|
+
|
|
170
|
+
if source:
|
|
171
|
+
console.print(f"[dim]Source : {url}[/dim]")
|
|
172
|
+
console.print(f"[dim]Saving to: {dest}[/dim]")
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
written = _download(url, dest)
|
|
176
|
+
except click.ClickException:
|
|
177
|
+
raise
|
|
178
|
+
except OSError as exc:
|
|
179
|
+
print_error(
|
|
180
|
+
"Could not write file",
|
|
181
|
+
f"Path : {dest}",
|
|
182
|
+
f"Error : {exc}",
|
|
183
|
+
title="Write Error",
|
|
184
|
+
)
|
|
185
|
+
raise SystemExit(2) from exc
|
|
186
|
+
|
|
187
|
+
if verify_integrity:
|
|
188
|
+
actual = _sha256(dest)
|
|
189
|
+
if actual != _WORDLIST_SHA256:
|
|
190
|
+
dest.unlink(missing_ok=True)
|
|
191
|
+
print_error(
|
|
192
|
+
"Integrity check failed — file deleted",
|
|
193
|
+
f"Expected : {_WORDLIST_SHA256}",
|
|
194
|
+
f"Got : {actual}",
|
|
195
|
+
"The downloaded file does not match the pinned checksum.",
|
|
196
|
+
"This may indicate a compromised source or a wordlist update.",
|
|
197
|
+
"If the wordlist was intentionally updated, report this at "
|
|
198
|
+
"https://github.com/KhaledSaeed18/jwt-toolkit/issues",
|
|
199
|
+
title="Integrity Error",
|
|
200
|
+
)
|
|
201
|
+
raise SystemExit(2)
|
|
202
|
+
|
|
203
|
+
lines = _count_lines(dest)
|
|
204
|
+
|
|
205
|
+
print_success(
|
|
206
|
+
_FILENAME,
|
|
207
|
+
f"Saved to : {dest}",
|
|
208
|
+
f"Size : {_fmt_bytes(written)}",
|
|
209
|
+
f"Entries : {lines:,} lines",
|
|
210
|
+
*([f"Checksum : {_WORDLIST_SHA256} ✓"] if verify_integrity else []),
|
|
211
|
+
title="[bold green]Downloaded[/bold green]",
|
|
212
|
+
footer=(
|
|
213
|
+
"[dim]Use with crack:[/dim]",
|
|
214
|
+
f"[bold]jwt-toolkit crack <token> {dest}[/bold]",
|
|
215
|
+
),
|
|
216
|
+
)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import click
|
|
5
|
+
from rich.panel import Panel
|
|
6
|
+
from rich.table import Table
|
|
7
|
+
|
|
8
|
+
from jwt_toolkit.cli.console import console
|
|
9
|
+
from jwt_toolkit.cli.decoding import JSON_SCHEMA_VERSION, resolve_token, safe_decode
|
|
10
|
+
from jwt_toolkit.cli.panels import print_error
|
|
11
|
+
from jwt_toolkit.core.forge import (
|
|
12
|
+
ALL_VARIANT_NAMES,
|
|
13
|
+
KEY_BASED_VARIANT_NAMES,
|
|
14
|
+
STATIC_VARIANT_NAMES,
|
|
15
|
+
Variant,
|
|
16
|
+
forge_one,
|
|
17
|
+
generate_variants,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
# Forge command — generates defensive test-case variants of a JWT so the user
|
|
21
|
+
# can confirm their verifier rejects each one. Output is grouped by variant.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_INTRO = (
|
|
25
|
+
"These variants are designed to be REJECTED by a correctly configured verifier. "
|
|
26
|
+
"Feed each one at your verifier and confirm it returns a failure. "
|
|
27
|
+
"If any variant is accepted, the verifier has the matching vulnerability."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@click.command(
|
|
32
|
+
help=(
|
|
33
|
+
"Emit defensive attack-shaped variants of a JWT for self-audit. "
|
|
34
|
+
"Every variant should be rejected by a correct verifier."
|
|
35
|
+
)
|
|
36
|
+
)
|
|
37
|
+
@click.argument("token")
|
|
38
|
+
@click.option(
|
|
39
|
+
"--public-key",
|
|
40
|
+
"public_key_path",
|
|
41
|
+
default=None,
|
|
42
|
+
type=click.Path(exists=True, dir_okay=False, readable=True, path_type=Path),
|
|
43
|
+
help=(
|
|
44
|
+
"PEM public key. Required for the hs_rs_confusion variant (CVE-2016-10555). "
|
|
45
|
+
"Without it, only the key-free variants are produced."
|
|
46
|
+
),
|
|
47
|
+
)
|
|
48
|
+
@click.option(
|
|
49
|
+
"--mode",
|
|
50
|
+
"mode",
|
|
51
|
+
default=None,
|
|
52
|
+
type=click.Choice(list(ALL_VARIANT_NAMES), case_sensitive=False),
|
|
53
|
+
help="Emit only the named variant instead of all of them.",
|
|
54
|
+
)
|
|
55
|
+
@click.option(
|
|
56
|
+
"--json",
|
|
57
|
+
"as_json",
|
|
58
|
+
is_flag=True,
|
|
59
|
+
help="Emit a machine-readable JSON document instead of the rich table.",
|
|
60
|
+
)
|
|
61
|
+
def forge(token: str, public_key_path: Path | None, mode: str | None, as_json: bool):
|
|
62
|
+
token = resolve_token(token)
|
|
63
|
+
decoded = safe_decode(token, as_json=as_json)
|
|
64
|
+
|
|
65
|
+
pem: bytes | None = public_key_path.read_bytes() if public_key_path is not None else None
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
variants = _select_variants(decoded, pem=pem, mode=mode)
|
|
69
|
+
except ValueError as exc:
|
|
70
|
+
print_error(str(exc), title="Forge Error")
|
|
71
|
+
raise SystemExit(2) from exc
|
|
72
|
+
|
|
73
|
+
if as_json:
|
|
74
|
+
_emit_json(variants, has_public_key=pem is not None)
|
|
75
|
+
else:
|
|
76
|
+
_emit_rich(variants, has_public_key=pem is not None)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _select_variants(decoded, *, pem: bytes | None, mode: str | None) -> list[Variant]:
|
|
80
|
+
if mode is not None:
|
|
81
|
+
return [forge_one(mode, decoded, public_key_pem=pem)]
|
|
82
|
+
names = STATIC_VARIANT_NAMES if pem is None else STATIC_VARIANT_NAMES + KEY_BASED_VARIANT_NAMES
|
|
83
|
+
return generate_variants(decoded, public_key_pem=pem, names=names)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _emit_json(variants: list[Variant], *, has_public_key: bool) -> None:
|
|
87
|
+
document = {
|
|
88
|
+
"schema_version": JSON_SCHEMA_VERSION,
|
|
89
|
+
"intent": "defensive_test_cases",
|
|
90
|
+
"expected_outcome": "every variant must be rejected by the verifier under test",
|
|
91
|
+
"public_key_supplied": has_public_key,
|
|
92
|
+
"variants": [
|
|
93
|
+
{
|
|
94
|
+
"name": v.name,
|
|
95
|
+
"description": v.description,
|
|
96
|
+
"cve": v.cve,
|
|
97
|
+
"token": v.token,
|
|
98
|
+
}
|
|
99
|
+
for v in variants
|
|
100
|
+
],
|
|
101
|
+
}
|
|
102
|
+
click.echo(json.dumps(document, indent=2))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _emit_rich(variants: list[Variant], *, has_public_key: bool) -> None:
|
|
106
|
+
console.print(Panel(_INTRO, title="Forge — defensive test cases", border_style="blue"))
|
|
107
|
+
|
|
108
|
+
table = Table(title="Variants", show_lines=True)
|
|
109
|
+
table.add_column("Name", style="bold", width=20)
|
|
110
|
+
table.add_column("CVE", style="dim", width=14)
|
|
111
|
+
table.add_column("Description")
|
|
112
|
+
for v in variants:
|
|
113
|
+
table.add_row(v.name, v.cve or "—", v.description)
|
|
114
|
+
console.print(table)
|
|
115
|
+
|
|
116
|
+
for v in variants:
|
|
117
|
+
cve_suffix = f" [dim]({v.cve})[/dim]" if v.cve else ""
|
|
118
|
+
console.print(
|
|
119
|
+
Panel(
|
|
120
|
+
v.token,
|
|
121
|
+
title=f"[bold]{v.name}[/bold]{cve_suffix}",
|
|
122
|
+
border_style="yellow",
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
if not has_public_key:
|
|
127
|
+
console.print(
|
|
128
|
+
Panel(
|
|
129
|
+
"[dim]Pass --public-key to also emit the hs_rs_confusion variant "
|
|
130
|
+
"(CVE-2016-10555).[/dim]",
|
|
131
|
+
border_style="cyan",
|
|
132
|
+
)
|
|
133
|
+
)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import secrets
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from jwt_toolkit.cli.panels import print_error, print_success
|
|
8
|
+
|
|
9
|
+
# Generate-secret command — emits a cryptographically strong random secret in
|
|
10
|
+
# hex or base64, with a strength label derived from the bit length.
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# (headline, predicate, suggestion) — first match wins. `suggestion` may be a
|
|
14
|
+
# callable for rules whose hint depends on the actual value passed.
|
|
15
|
+
_VALIDATIONS: tuple[tuple[str, Callable[[int], bool], str | Callable[[int], str]], ...] = (
|
|
16
|
+
("--bits must be a positive number", lambda b: b <= 0, "Try instead : 256 bits"),
|
|
17
|
+
("--bits must be 4096 or fewer", lambda b: b > 4096, "Maximum : 4096 bits"),
|
|
18
|
+
("--bits is too small to be secure", lambda b: b < 64, "Minimum : 64 bits"),
|
|
19
|
+
(
|
|
20
|
+
"--bits must be a multiple of 8",
|
|
21
|
+
lambda b: b % 8 != 0,
|
|
22
|
+
lambda b: f"Try instead : {(b // 8 + 1) * 8} bits",
|
|
23
|
+
),
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _validate_bits(bits: int) -> None:
|
|
28
|
+
for headline, predicate, suggestion in _VALIDATIONS:
|
|
29
|
+
if not predicate(bits):
|
|
30
|
+
continue
|
|
31
|
+
hint = suggestion(bits) if callable(suggestion) else suggestion
|
|
32
|
+
print_error(
|
|
33
|
+
headline,
|
|
34
|
+
f"You passed : {bits} bits",
|
|
35
|
+
hint,
|
|
36
|
+
title="Invalid Input",
|
|
37
|
+
)
|
|
38
|
+
raise SystemExit(2)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _strength_for(bits: int) -> str:
|
|
42
|
+
if bits >= 256:
|
|
43
|
+
return "strong"
|
|
44
|
+
if bits >= 128:
|
|
45
|
+
return "moderate"
|
|
46
|
+
return "weak, use at least 128 bits"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@click.command(help="Generate a cryptographically strong random secret for signing JWTs.")
|
|
50
|
+
@click.option(
|
|
51
|
+
"--bits", default=256, show_default=True, help="Secret length in bits (must be a multiple of 8)"
|
|
52
|
+
)
|
|
53
|
+
@click.option(
|
|
54
|
+
"--encoding",
|
|
55
|
+
type=click.Choice(["hex", "base64"]),
|
|
56
|
+
default="hex",
|
|
57
|
+
show_default=True,
|
|
58
|
+
help="Output encoding",
|
|
59
|
+
)
|
|
60
|
+
def generate_secret(bits: int, encoding: str):
|
|
61
|
+
_validate_bits(bits)
|
|
62
|
+
|
|
63
|
+
raw = secrets.token_bytes(bits // 8)
|
|
64
|
+
output = raw.hex() if encoding == "hex" else base64.urlsafe_b64encode(raw).decode()
|
|
65
|
+
|
|
66
|
+
print_success(
|
|
67
|
+
output,
|
|
68
|
+
f"Encoding : {encoding}",
|
|
69
|
+
f"Length : {bits} bits ({bits // 8} bytes)",
|
|
70
|
+
f"Entropy : {bits} bits — {_strength_for(bits)}",
|
|
71
|
+
title="Generated Secret",
|
|
72
|
+
)
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import click
|
|
5
|
+
|
|
6
|
+
from jwt_toolkit.cli.algorithms import is_asymmetric, is_hmac
|
|
7
|
+
from jwt_toolkit.cli.panels import print_error
|
|
8
|
+
from jwt_toolkit.core.crypto import (
|
|
9
|
+
ALL_SIGNING_ALGORITHMS,
|
|
10
|
+
)
|
|
11
|
+
from jwt_toolkit.core.crypto import (
|
|
12
|
+
sign as _sign_hmac,
|
|
13
|
+
)
|
|
14
|
+
from jwt_toolkit.core.crypto import (
|
|
15
|
+
sign_asymmetric as _sign_asymmetric,
|
|
16
|
+
)
|
|
17
|
+
from jwt_toolkit.core.encoding import base64url_encode
|
|
18
|
+
|
|
19
|
+
# Sign command — construct and mint a JWT from a header+payload and either an
|
|
20
|
+
# HMAC secret or a PEM-encoded private key.
|
|
21
|
+
|
|
22
|
+
_ALG_CHOICES = sorted(ALL_SIGNING_ALGORITHMS)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@click.command(help="Mint a new JWT signed with an HMAC secret or an asymmetric private key.")
|
|
26
|
+
@click.option("--payload", "payload_json", required=True, help="JWT payload as a JSON string")
|
|
27
|
+
@click.option(
|
|
28
|
+
"--secret",
|
|
29
|
+
default=None,
|
|
30
|
+
help="HMAC secret (HS256/HS384/HS512). Mutually exclusive with --private-key.",
|
|
31
|
+
)
|
|
32
|
+
@click.option(
|
|
33
|
+
"--private-key",
|
|
34
|
+
"private_key_path",
|
|
35
|
+
default=None,
|
|
36
|
+
type=click.Path(exists=True, dir_okay=False, readable=True, path_type=Path),
|
|
37
|
+
help="Path to a PEM-encoded private key (RS*/PS*/ES*). Mutually exclusive with --secret.",
|
|
38
|
+
)
|
|
39
|
+
@click.option(
|
|
40
|
+
"--alg",
|
|
41
|
+
default="HS256",
|
|
42
|
+
show_default=True,
|
|
43
|
+
type=click.Choice(_ALG_CHOICES, case_sensitive=False),
|
|
44
|
+
help="Signing algorithm (ignored if --header overrides 'alg').",
|
|
45
|
+
)
|
|
46
|
+
@click.option(
|
|
47
|
+
"--header",
|
|
48
|
+
"header_json",
|
|
49
|
+
default=None,
|
|
50
|
+
help='Override the JWT header as a JSON string. Default: {"alg":"<alg>","typ":"JWT"}',
|
|
51
|
+
)
|
|
52
|
+
def sign(
|
|
53
|
+
payload_json: str,
|
|
54
|
+
secret: str | None,
|
|
55
|
+
private_key_path: Path | None,
|
|
56
|
+
alg: str,
|
|
57
|
+
header_json: str | None,
|
|
58
|
+
):
|
|
59
|
+
payload = _parse_json_arg(payload_json, label="payload")
|
|
60
|
+
header = (
|
|
61
|
+
{"alg": alg.upper(), "typ": "JWT"}
|
|
62
|
+
if header_json is None
|
|
63
|
+
else _parse_json_arg(header_json, label="header")
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
sign_alg = str(header.get("alg", alg)).upper()
|
|
67
|
+
if sign_alg not in ALL_SIGNING_ALGORITHMS:
|
|
68
|
+
print_error(
|
|
69
|
+
f"Unsupported algorithm: {sign_alg}",
|
|
70
|
+
f"Supported: {', '.join(_ALG_CHOICES)}",
|
|
71
|
+
title="Algorithm Error",
|
|
72
|
+
)
|
|
73
|
+
raise SystemExit(2)
|
|
74
|
+
|
|
75
|
+
_validate_key_inputs(sign_alg, secret=secret, private_key_path=private_key_path)
|
|
76
|
+
|
|
77
|
+
header_b64 = base64url_encode(json.dumps(header, separators=(",", ":")).encode())
|
|
78
|
+
payload_b64 = base64url_encode(json.dumps(payload, separators=(",", ":")).encode())
|
|
79
|
+
|
|
80
|
+
if is_hmac(sign_alg):
|
|
81
|
+
signature = _sign_hmac(header_b64, payload_b64, secret or "", sign_alg)
|
|
82
|
+
else:
|
|
83
|
+
try:
|
|
84
|
+
pem_bytes = private_key_path.read_bytes() # type: ignore[union-attr]
|
|
85
|
+
signature = _sign_asymmetric(header_b64, payload_b64, pem_bytes, sign_alg)
|
|
86
|
+
except ValueError as exc:
|
|
87
|
+
print_error(
|
|
88
|
+
"Could not sign with the provided private key",
|
|
89
|
+
str(exc),
|
|
90
|
+
title="Key Error",
|
|
91
|
+
)
|
|
92
|
+
raise SystemExit(2) from exc
|
|
93
|
+
|
|
94
|
+
click.echo(f"{header_b64}.{payload_b64}.{signature}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _parse_json_arg(raw: str, *, label: str) -> dict:
|
|
98
|
+
try:
|
|
99
|
+
return json.loads(raw)
|
|
100
|
+
except json.JSONDecodeError as exc:
|
|
101
|
+
print_error(
|
|
102
|
+
f"Invalid {label} JSON",
|
|
103
|
+
f"JSON error: {exc.msg}",
|
|
104
|
+
title="Invalid Input",
|
|
105
|
+
)
|
|
106
|
+
raise SystemExit(2) from exc
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _validate_key_inputs(alg: str, *, secret: str | None, private_key_path: Path | None) -> None:
|
|
110
|
+
if secret is not None and private_key_path is not None:
|
|
111
|
+
print_error(
|
|
112
|
+
"Pass either --secret or --private-key, not both",
|
|
113
|
+
title="Invalid Input",
|
|
114
|
+
)
|
|
115
|
+
raise SystemExit(2)
|
|
116
|
+
|
|
117
|
+
if is_hmac(alg):
|
|
118
|
+
if not secret:
|
|
119
|
+
print_error(
|
|
120
|
+
f"{alg} requires --secret",
|
|
121
|
+
"Provide the HMAC secret to sign with.",
|
|
122
|
+
title="Invalid Input",
|
|
123
|
+
)
|
|
124
|
+
raise SystemExit(2)
|
|
125
|
+
if private_key_path is not None:
|
|
126
|
+
print_error(
|
|
127
|
+
f"{alg} is an HMAC algorithm — use --secret, not --private-key",
|
|
128
|
+
title="Invalid Input",
|
|
129
|
+
)
|
|
130
|
+
raise SystemExit(2)
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
if is_asymmetric(alg):
|
|
134
|
+
if private_key_path is None:
|
|
135
|
+
print_error(
|
|
136
|
+
f"{alg} requires --private-key",
|
|
137
|
+
"Provide a PEM-encoded private key (PKCS#8 or traditional).",
|
|
138
|
+
title="Invalid Input",
|
|
139
|
+
)
|
|
140
|
+
raise SystemExit(2)
|
|
141
|
+
if secret is not None:
|
|
142
|
+
print_error(
|
|
143
|
+
f"{alg} is an asymmetric algorithm — use --private-key, not --secret",
|
|
144
|
+
title="Invalid Input",
|
|
145
|
+
)
|
|
146
|
+
raise SystemExit(2)
|