knuckles-cli 0.2.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.
- knuckles_cli/__init__.py +3 -0
- knuckles_cli/__main__.py +7 -0
- knuckles_cli/api.py +252 -0
- knuckles_cli/cli.py +684 -0
- knuckles_cli/config.py +201 -0
- knuckles_cli/doctor.py +250 -0
- knuckles_cli/envfile.py +103 -0
- knuckles_cli/errors.py +43 -0
- knuckles_cli/ops.py +451 -0
- knuckles_cli/providers.py +365 -0
- knuckles_cli/py.typed +0 -0
- knuckles_cli-0.2.0.dist-info/METADATA +140 -0
- knuckles_cli-0.2.0.dist-info/RECORD +17 -0
- knuckles_cli-0.2.0.dist-info/WHEEL +5 -0
- knuckles_cli-0.2.0.dist-info/entry_points.txt +2 -0
- knuckles_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
- knuckles_cli-0.2.0.dist-info/top_level.txt +1 -0
knuckles_cli/cli.py
ADDED
|
@@ -0,0 +1,684 @@
|
|
|
1
|
+
"""The ``knuckles`` command: provision and check Knuckles tenants.
|
|
2
|
+
|
|
3
|
+
Every subcommand takes the global ``--json`` flag, which prints the
|
|
4
|
+
Knuckles API envelope (``{"data": ...}`` or ``{"error": {"code",
|
|
5
|
+
"message"}}``) so coding agents can parse results. Without it, output
|
|
6
|
+
is short human-readable text and errors go to stderr.
|
|
7
|
+
|
|
8
|
+
Exit codes: 0 success, 1 failure (API error, invalid input, or a
|
|
9
|
+
failing ``doctor`` check), 2 usage error.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import getpass
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import TYPE_CHECKING, Any
|
|
22
|
+
|
|
23
|
+
from knuckles_cli import __version__, ops
|
|
24
|
+
from knuckles_cli.api import KnucklesAPI
|
|
25
|
+
from knuckles_cli.config import (
|
|
26
|
+
Profile,
|
|
27
|
+
config_path,
|
|
28
|
+
normalize_url,
|
|
29
|
+
remove_profile,
|
|
30
|
+
resolve_profile,
|
|
31
|
+
save_profile,
|
|
32
|
+
)
|
|
33
|
+
from knuckles_cli.errors import INVALID_INPUT, CliError
|
|
34
|
+
from knuckles_cli.providers import CONFIG_GROUPS, parse_google_client_secret
|
|
35
|
+
|
|
36
|
+
if TYPE_CHECKING:
|
|
37
|
+
from collections.abc import Mapping
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class Context:
|
|
42
|
+
"""Per-invocation state shared by command handlers.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
as_json: Whether to print JSON envelopes.
|
|
46
|
+
profile: Profile name to read or write.
|
|
47
|
+
config: Path of the profile file.
|
|
48
|
+
env: Process environment.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
as_json: bool
|
|
52
|
+
profile: str
|
|
53
|
+
config: Path
|
|
54
|
+
env: Mapping[str, str]
|
|
55
|
+
|
|
56
|
+
def api(self) -> KnucklesAPI:
|
|
57
|
+
"""Build an API client from the effective profile.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
A :class:`KnucklesAPI` for the configured server.
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
CliError: ``NOT_LOGGED_IN`` if no server is configured.
|
|
64
|
+
"""
|
|
65
|
+
profile = resolve_profile(path=self.config, name=self.profile, env=self.env)
|
|
66
|
+
return KnucklesAPI(profile.url, admin_token=profile.admin_token)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class Result:
|
|
71
|
+
"""What a command hands back for printing.
|
|
72
|
+
|
|
73
|
+
Attributes:
|
|
74
|
+
data: JSON payload for ``--json`` output.
|
|
75
|
+
lines: Human-readable output lines.
|
|
76
|
+
exit_code: Process exit status.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
data: Any
|
|
80
|
+
lines: list[str]
|
|
81
|
+
exit_code: int = 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _read_secret(
|
|
85
|
+
*, file: str | None, env_var: str, label: str, env: Mapping[str, str]
|
|
86
|
+
) -> str:
|
|
87
|
+
"""Read a secret without ever taking it from argv.
|
|
88
|
+
|
|
89
|
+
Order: ``--*-file`` (``-`` means stdin), then the env var, then a
|
|
90
|
+
hidden prompt when stdin is a terminal.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
file: Path given on the command line, or ``None``.
|
|
94
|
+
env_var: Environment variable to fall back to.
|
|
95
|
+
label: Human name of the secret for prompts and errors.
|
|
96
|
+
env: Process environment.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
The secret, whitespace-trimmed.
|
|
100
|
+
|
|
101
|
+
Raises:
|
|
102
|
+
CliError: ``INVALID_INPUT`` if no source supplies a value.
|
|
103
|
+
"""
|
|
104
|
+
if file == "-":
|
|
105
|
+
value = sys.stdin.read()
|
|
106
|
+
elif file:
|
|
107
|
+
value = Path(file).read_text()
|
|
108
|
+
elif env.get(env_var):
|
|
109
|
+
value = env[env_var]
|
|
110
|
+
elif sys.stdin.isatty():
|
|
111
|
+
value = getpass.getpass(f"{label}: ")
|
|
112
|
+
else:
|
|
113
|
+
raise CliError(
|
|
114
|
+
INVALID_INPUT,
|
|
115
|
+
f"No {label} given. Pass it with a --*-file option (use - for "
|
|
116
|
+
f"stdin) or set {env_var}.",
|
|
117
|
+
)
|
|
118
|
+
value = value.strip()
|
|
119
|
+
if not value:
|
|
120
|
+
raise CliError(INVALID_INPUT, f"{label} is empty.")
|
|
121
|
+
return value
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _row_lines(row: Mapping[str, Any]) -> list[str]:
|
|
125
|
+
"""Render a redacted app-client row as ``key: value`` lines.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
row: The row.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
One line per field.
|
|
132
|
+
"""
|
|
133
|
+
lines = []
|
|
134
|
+
for key, value in row.items():
|
|
135
|
+
shown = ", ".join(value) if isinstance(value, list) else value
|
|
136
|
+
lines.append(f"{key}: {shown if shown not in (None, '') else '-'}")
|
|
137
|
+
return lines
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------- login
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cmd_login(args: argparse.Namespace, ctx: Context) -> Result:
|
|
144
|
+
"""Verify an admin token against a server, then store the profile.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
args: Parsed arguments (``url``, ``token_file``).
|
|
148
|
+
ctx: Invocation context.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
The stored profile summary.
|
|
152
|
+
"""
|
|
153
|
+
url = normalize_url(args.url)
|
|
154
|
+
token = _read_secret(
|
|
155
|
+
file=args.token_file,
|
|
156
|
+
env_var="KNUCKLES_ADMIN_TOKEN",
|
|
157
|
+
label="admin token",
|
|
158
|
+
env=ctx.env,
|
|
159
|
+
)
|
|
160
|
+
apps = KnucklesAPI(url, admin_token=token).list_apps()
|
|
161
|
+
save_profile(ctx.config, ctx.profile, Profile(url=url, admin_token=token))
|
|
162
|
+
return Result(
|
|
163
|
+
{"profile": ctx.profile, "url": url, "app_clients": len(apps)},
|
|
164
|
+
[f"Logged in to {url} as profile {ctx.profile!r} ({len(apps)} app clients)."],
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def cmd_logout(args: argparse.Namespace, ctx: Context) -> Result:
|
|
169
|
+
"""Forget a stored profile.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
args: Parsed arguments (unused).
|
|
173
|
+
ctx: Invocation context.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
Whether a profile was removed.
|
|
177
|
+
"""
|
|
178
|
+
removed = remove_profile(ctx.config, ctx.profile)
|
|
179
|
+
message = "Logged out." if removed else f"No profile {ctx.profile!r} stored."
|
|
180
|
+
return Result({"profile": ctx.profile, "removed": removed}, [message])
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# ----------------------------------------------------------------- apps
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _create(args: argparse.Namespace, ctx: Context) -> dict[str, Any]:
|
|
187
|
+
"""Create a tenant from parsed arguments.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
args: Parsed arguments (``client_id``, ``name``, ``origin``,
|
|
191
|
+
``env_file``, ``force``).
|
|
192
|
+
ctx: Invocation context.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
The created row (see :func:`knuckles_cli.ops.create_app`).
|
|
196
|
+
"""
|
|
197
|
+
return ops.create_app(
|
|
198
|
+
ctx.api(),
|
|
199
|
+
client_id=args.client_id,
|
|
200
|
+
name=args.name,
|
|
201
|
+
origins=args.origin,
|
|
202
|
+
env_file=Path(args.env_file) if args.env_file else None,
|
|
203
|
+
force=args.force,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def cmd_apps_create(args: argparse.Namespace, ctx: Context) -> Result:
|
|
208
|
+
"""Register a tenant.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
args: Parsed arguments.
|
|
212
|
+
ctx: Invocation context.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
The created row (with the one-time secret unless written to a
|
|
216
|
+
``.env`` file).
|
|
217
|
+
"""
|
|
218
|
+
data = _create(args, ctx)
|
|
219
|
+
lines = [f"Created {data['client_id']}."]
|
|
220
|
+
if "client_secret" in data:
|
|
221
|
+
lines.append(f"client_secret: {data['client_secret']}")
|
|
222
|
+
lines.append("Store it now; it is never shown again.")
|
|
223
|
+
else:
|
|
224
|
+
lines.append(f"Credentials written to {data['env_file']}.")
|
|
225
|
+
return Result(data, lines)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def cmd_init(args: argparse.Namespace, ctx: Context) -> Result:
|
|
229
|
+
"""Create a tenant and print the remaining setup steps.
|
|
230
|
+
|
|
231
|
+
Args:
|
|
232
|
+
args: Parsed arguments.
|
|
233
|
+
ctx: Invocation context.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
The created row plus ``next_steps``.
|
|
237
|
+
"""
|
|
238
|
+
data = _create(args, ctx)
|
|
239
|
+
cid = data["client_id"]
|
|
240
|
+
origin = data["allowed_origins"][0] if data["allowed_origins"] else None
|
|
241
|
+
data["next_steps"] = ops.next_steps(cid, origin)
|
|
242
|
+
lines = [f"Created {cid}."]
|
|
243
|
+
if "client_secret" in data:
|
|
244
|
+
lines += [f"client_secret: {data['client_secret']}", "Store it now."]
|
|
245
|
+
else:
|
|
246
|
+
lines.append(f"Credentials written to {data['env_file']}.")
|
|
247
|
+
lines += ["", "Next steps:"] + [f" {step}" for step in data["next_steps"]]
|
|
248
|
+
return Result(data, lines)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def cmd_apps_list(args: argparse.Namespace, ctx: Context) -> Result:
|
|
252
|
+
"""List tenants.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
args: Parsed arguments (unused).
|
|
256
|
+
ctx: Invocation context.
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
Every redacted row.
|
|
260
|
+
"""
|
|
261
|
+
apps = ctx.api().list_apps()
|
|
262
|
+
lines = [
|
|
263
|
+
f"{a['client_id']}\t{a['app_name']}\t{', '.join(a['allowed_origins'])}"
|
|
264
|
+
for a in apps
|
|
265
|
+
] or ["No app clients."]
|
|
266
|
+
return Result(apps, lines)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def cmd_apps_show(args: argparse.Namespace, ctx: Context) -> Result:
|
|
270
|
+
"""Show one tenant.
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
args: Parsed arguments (``client_id``).
|
|
274
|
+
ctx: Invocation context.
|
|
275
|
+
|
|
276
|
+
Returns:
|
|
277
|
+
The redacted row.
|
|
278
|
+
"""
|
|
279
|
+
row = ctx.api().get_app(args.client_id)
|
|
280
|
+
return Result(row, _row_lines(row))
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def cmd_apps_rotate(args: argparse.Namespace, ctx: Context) -> Result:
|
|
284
|
+
"""Rotate a tenant's client secret.
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
args: Parsed arguments (``client_id``, ``env_file``, ``force``).
|
|
288
|
+
ctx: Invocation context.
|
|
289
|
+
|
|
290
|
+
Returns:
|
|
291
|
+
The new secret, unless written to a ``.env`` file.
|
|
292
|
+
"""
|
|
293
|
+
data = ops.rotate_secret(
|
|
294
|
+
ctx.api(),
|
|
295
|
+
args.client_id,
|
|
296
|
+
env_file=Path(args.env_file) if args.env_file else None,
|
|
297
|
+
force=args.force,
|
|
298
|
+
)
|
|
299
|
+
if "env_file" in data:
|
|
300
|
+
return Result(data, [f"New secret written to {data['env_file']}."])
|
|
301
|
+
return Result(
|
|
302
|
+
data,
|
|
303
|
+
[
|
|
304
|
+
f"client_secret: {data['client_secret']}",
|
|
305
|
+
"The old secret stops working now.",
|
|
306
|
+
],
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def cmd_apps_origins(args: argparse.Namespace, ctx: Context) -> Result:
|
|
311
|
+
"""Replace a tenant's allowed origins.
|
|
312
|
+
|
|
313
|
+
Args:
|
|
314
|
+
args: Parsed arguments (``client_id``, ``origins``).
|
|
315
|
+
ctx: Invocation context.
|
|
316
|
+
|
|
317
|
+
Returns:
|
|
318
|
+
The updated row.
|
|
319
|
+
"""
|
|
320
|
+
row = ops.set_origins(ctx.api(), args.client_id, args.origins)
|
|
321
|
+
return Result(row, [f"Allowed origins: {', '.join(row['allowed_origins'])}"])
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# ------------------------------------------------------------ providers
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _patched(result: ops.ProviderResult, what: str) -> Result:
|
|
328
|
+
"""Build the output for a provider update.
|
|
329
|
+
|
|
330
|
+
Args:
|
|
331
|
+
result: The updated row and its warnings.
|
|
332
|
+
what: Name of what was configured.
|
|
333
|
+
|
|
334
|
+
Returns:
|
|
335
|
+
A result carrying the row and warnings.
|
|
336
|
+
"""
|
|
337
|
+
lines = [f"{what} configured for {result.row.get('client_id')}."]
|
|
338
|
+
lines += [f"warning: {w}" for w in result.warnings]
|
|
339
|
+
return Result(result.to_dict(), lines)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def cmd_providers_google(args: argparse.Namespace, ctx: Context) -> Result:
|
|
343
|
+
"""Configure Google sign-in from the console's JSON or by hand.
|
|
344
|
+
|
|
345
|
+
Args:
|
|
346
|
+
args: Parsed arguments.
|
|
347
|
+
ctx: Invocation context.
|
|
348
|
+
|
|
349
|
+
Returns:
|
|
350
|
+
The updated row and any redirect-origin warnings.
|
|
351
|
+
"""
|
|
352
|
+
redirect_origins: list[str] = []
|
|
353
|
+
if args.client_secret_json:
|
|
354
|
+
creds = parse_google_client_secret(Path(args.client_secret_json).read_text())
|
|
355
|
+
client_id, secret = creds.client_id, creds.client_secret
|
|
356
|
+
redirect_origins = creds.redirect_origins
|
|
357
|
+
else:
|
|
358
|
+
client_id = args.client_id
|
|
359
|
+
secret = _read_secret(
|
|
360
|
+
file=args.client_secret_file,
|
|
361
|
+
env_var="KNUCKLES_GOOGLE_CLIENT_SECRET",
|
|
362
|
+
label="Google client secret",
|
|
363
|
+
env=ctx.env,
|
|
364
|
+
)
|
|
365
|
+
result = ops.configure_google(
|
|
366
|
+
ctx.api(),
|
|
367
|
+
args.app,
|
|
368
|
+
client_id=client_id,
|
|
369
|
+
client_secret=secret,
|
|
370
|
+
redirect_origins=redirect_origins,
|
|
371
|
+
)
|
|
372
|
+
return _patched(result, "Google sign-in")
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def cmd_providers_apple(args: argparse.Namespace, ctx: Context) -> Result:
|
|
376
|
+
"""Configure Sign in with Apple from the ``.p8`` key file.
|
|
377
|
+
|
|
378
|
+
Args:
|
|
379
|
+
args: Parsed arguments.
|
|
380
|
+
ctx: Invocation context.
|
|
381
|
+
|
|
382
|
+
Returns:
|
|
383
|
+
The updated row.
|
|
384
|
+
"""
|
|
385
|
+
result = ops.configure_apple(
|
|
386
|
+
ctx.api(),
|
|
387
|
+
args.app,
|
|
388
|
+
services_id=args.services_id,
|
|
389
|
+
team_id=args.team_id,
|
|
390
|
+
p8_path=Path(args.p8),
|
|
391
|
+
key_id=args.key_id,
|
|
392
|
+
)
|
|
393
|
+
return _patched(result, "Sign in with Apple")
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def cmd_providers_email(args: argparse.Namespace, ctx: Context) -> Result:
|
|
397
|
+
"""Configure magic-link email (Resend), checking the domain first.
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
args: Parsed arguments.
|
|
401
|
+
ctx: Invocation context.
|
|
402
|
+
|
|
403
|
+
Returns:
|
|
404
|
+
The updated row and any verification warning.
|
|
405
|
+
"""
|
|
406
|
+
api_key = _read_secret(
|
|
407
|
+
file=args.api_key_file,
|
|
408
|
+
env_var="KNUCKLES_RESEND_API_KEY",
|
|
409
|
+
label="Resend API key",
|
|
410
|
+
env=ctx.env,
|
|
411
|
+
)
|
|
412
|
+
result = ops.configure_email(
|
|
413
|
+
ctx.api(),
|
|
414
|
+
args.app,
|
|
415
|
+
from_email=args.from_email,
|
|
416
|
+
api_key=api_key,
|
|
417
|
+
verify=not args.no_verify,
|
|
418
|
+
)
|
|
419
|
+
return _patched(result, "Magic-link email")
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def cmd_providers_passkey(args: argparse.Namespace, ctx: Context) -> Result:
|
|
423
|
+
"""Configure the WebAuthn relying party for passkeys.
|
|
424
|
+
|
|
425
|
+
Args:
|
|
426
|
+
args: Parsed arguments.
|
|
427
|
+
ctx: Invocation context.
|
|
428
|
+
|
|
429
|
+
Returns:
|
|
430
|
+
The updated row.
|
|
431
|
+
"""
|
|
432
|
+
result = ops.configure_passkey(
|
|
433
|
+
ctx.api(),
|
|
434
|
+
args.app,
|
|
435
|
+
origin=args.origin,
|
|
436
|
+
rp_id=args.rp_id,
|
|
437
|
+
rp_name=args.rp_name,
|
|
438
|
+
force_rp_id=args.force_rp_id,
|
|
439
|
+
)
|
|
440
|
+
return _patched(result, "Passkeys")
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def cmd_providers_clear(args: argparse.Namespace, ctx: Context) -> Result:
|
|
444
|
+
"""Clear a config group back to the operator env fallback.
|
|
445
|
+
|
|
446
|
+
Args:
|
|
447
|
+
args: Parsed arguments (``app``, ``group``, ``force_rp_id``).
|
|
448
|
+
ctx: Invocation context.
|
|
449
|
+
|
|
450
|
+
Returns:
|
|
451
|
+
The updated row.
|
|
452
|
+
"""
|
|
453
|
+
row = ops.clear_provider(
|
|
454
|
+
ctx.api(), args.app, args.group, force_rp_id=args.force_rp_id
|
|
455
|
+
)
|
|
456
|
+
return Result({"app": row}, [f"Cleared {args.group} for {args.app}."])
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
# --------------------------------------------------------------- doctor
|
|
460
|
+
|
|
461
|
+
_MARKS = {"ok": "✓", "warn": "!", "fail": "✗"}
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def cmd_doctor(args: argparse.Namespace, ctx: Context) -> Result:
|
|
465
|
+
"""Check the server and its tenants.
|
|
466
|
+
|
|
467
|
+
Args:
|
|
468
|
+
args: Parsed arguments (optional ``client_id``).
|
|
469
|
+
ctx: Invocation context.
|
|
470
|
+
|
|
471
|
+
Returns:
|
|
472
|
+
Every check; exit code 1 if any failed.
|
|
473
|
+
"""
|
|
474
|
+
report = ops.doctor(ctx.api(), args.client_id)
|
|
475
|
+
counts = report.summary
|
|
476
|
+
lines = [f"{_MARKS[c.status]} {c.name}: {c.detail}" for c in report.checks]
|
|
477
|
+
lines.append(
|
|
478
|
+
f"\n{counts['ok']} ok, {counts['warn']} warnings, {counts['fail']} failed"
|
|
479
|
+
)
|
|
480
|
+
return Result(report.to_dict(), lines, exit_code=1 if report.failed else 0)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
# --------------------------------------------------------------- parser
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
487
|
+
"""Construct the argument parser for every subcommand.
|
|
488
|
+
|
|
489
|
+
Returns:
|
|
490
|
+
The configured parser; each leaf sets ``handler``.
|
|
491
|
+
"""
|
|
492
|
+
parser = argparse.ArgumentParser(
|
|
493
|
+
prog="knuckles",
|
|
494
|
+
description="Provision and check Knuckles identity tenants.",
|
|
495
|
+
)
|
|
496
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
497
|
+
parser.add_argument("--json", action="store_true", help="Print JSON envelopes.")
|
|
498
|
+
parser.add_argument(
|
|
499
|
+
"--profile", help="Profile name (default: $KNUCKLES_PROFILE or 'default')."
|
|
500
|
+
)
|
|
501
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
502
|
+
|
|
503
|
+
login = sub.add_parser("login", help="Store a server URL and admin token.")
|
|
504
|
+
login.add_argument("--url", required=True, help="Knuckles base URL.")
|
|
505
|
+
login.add_argument(
|
|
506
|
+
"--token-file",
|
|
507
|
+
help="File holding the admin token ('-' for stdin). Defaults to "
|
|
508
|
+
"$KNUCKLES_ADMIN_TOKEN, then a hidden prompt.",
|
|
509
|
+
)
|
|
510
|
+
login.set_defaults(handler=cmd_login)
|
|
511
|
+
|
|
512
|
+
logout = sub.add_parser("logout", help="Forget the stored profile.")
|
|
513
|
+
logout.set_defaults(handler=cmd_logout)
|
|
514
|
+
|
|
515
|
+
def add_create_args(p: argparse.ArgumentParser) -> None:
|
|
516
|
+
"""Add the shared tenant-creation arguments.
|
|
517
|
+
|
|
518
|
+
Args:
|
|
519
|
+
p: Parser to extend.
|
|
520
|
+
"""
|
|
521
|
+
p.add_argument("client_id", help="New client id (lowercase slug).")
|
|
522
|
+
p.add_argument("--name", required=True, help="Human-facing app name.")
|
|
523
|
+
p.add_argument(
|
|
524
|
+
"--origin",
|
|
525
|
+
action="append",
|
|
526
|
+
default=[],
|
|
527
|
+
help="Allowed origin (repeatable), e.g. https://app.example.com.",
|
|
528
|
+
)
|
|
529
|
+
p.add_argument(
|
|
530
|
+
"--env-file",
|
|
531
|
+
help="Write KNUCKLES_URL/CLIENT_ID/CLIENT_SECRET into this .env file.",
|
|
532
|
+
)
|
|
533
|
+
p.add_argument(
|
|
534
|
+
"--force", action="store_true", help="Overwrite differing .env values."
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
init = sub.add_parser("init", help="Create a tenant and print next steps.")
|
|
538
|
+
add_create_args(init)
|
|
539
|
+
init.set_defaults(handler=cmd_init)
|
|
540
|
+
|
|
541
|
+
apps = sub.add_parser("apps", help="Manage app clients (tenants).")
|
|
542
|
+
apps_sub = apps.add_subparsers(dest="apps_command", required=True)
|
|
543
|
+
apps_sub.add_parser("list", help="List tenants.").set_defaults(
|
|
544
|
+
handler=cmd_apps_list
|
|
545
|
+
)
|
|
546
|
+
show = apps_sub.add_parser("show", help="Show one tenant.")
|
|
547
|
+
show.add_argument("client_id")
|
|
548
|
+
show.set_defaults(handler=cmd_apps_show)
|
|
549
|
+
create = apps_sub.add_parser("create", help="Register a tenant.")
|
|
550
|
+
add_create_args(create)
|
|
551
|
+
create.set_defaults(handler=cmd_apps_create)
|
|
552
|
+
rotate = apps_sub.add_parser("rotate-secret", help="Mint a new client secret.")
|
|
553
|
+
rotate.add_argument("client_id")
|
|
554
|
+
rotate.add_argument("--env-file", help="Write the new secret into this .env.")
|
|
555
|
+
rotate.add_argument(
|
|
556
|
+
"--force", action="store_true", help="Overwrite an existing secret."
|
|
557
|
+
)
|
|
558
|
+
rotate.set_defaults(handler=cmd_apps_rotate)
|
|
559
|
+
origins = apps_sub.add_parser("set-origins", help="Replace allowed origins.")
|
|
560
|
+
origins.add_argument("client_id")
|
|
561
|
+
origins.add_argument("origins", nargs="+")
|
|
562
|
+
origins.set_defaults(handler=cmd_apps_origins)
|
|
563
|
+
|
|
564
|
+
providers = sub.add_parser("providers", help="Configure sign-in methods.")
|
|
565
|
+
prov_sub = providers.add_subparsers(dest="providers_command", required=True)
|
|
566
|
+
|
|
567
|
+
google = prov_sub.add_parser("google", help="Sign in with Google.")
|
|
568
|
+
google.add_argument("app", help="Tenant client id.")
|
|
569
|
+
source = google.add_mutually_exclusive_group(required=True)
|
|
570
|
+
source.add_argument(
|
|
571
|
+
"--client-secret-json",
|
|
572
|
+
help="The client_secret_*.json downloaded from Google Cloud Console.",
|
|
573
|
+
)
|
|
574
|
+
source.add_argument("--client-id", help="Google OAuth client id (manual entry).")
|
|
575
|
+
google.add_argument(
|
|
576
|
+
"--client-secret-file",
|
|
577
|
+
help="With --client-id: file holding the secret ('-' for stdin). "
|
|
578
|
+
"Defaults to $KNUCKLES_GOOGLE_CLIENT_SECRET, then a prompt.",
|
|
579
|
+
)
|
|
580
|
+
google.set_defaults(handler=cmd_providers_google)
|
|
581
|
+
|
|
582
|
+
apple = prov_sub.add_parser("apple", help="Sign in with Apple.")
|
|
583
|
+
apple.add_argument("app", help="Tenant client id.")
|
|
584
|
+
apple.add_argument("--services-id", required=True, help="Apple Services ID.")
|
|
585
|
+
apple.add_argument("--team-id", required=True, help="Apple Developer team id.")
|
|
586
|
+
apple.add_argument("--p8", required=True, help="Path to AuthKey_<KEYID>.p8.")
|
|
587
|
+
apple.add_argument("--key-id", help="Key id, if the .p8 was renamed.")
|
|
588
|
+
apple.set_defaults(handler=cmd_providers_apple)
|
|
589
|
+
|
|
590
|
+
email = prov_sub.add_parser("email", help="Magic-link email via Resend.")
|
|
591
|
+
email.add_argument("app", help="Tenant client id.")
|
|
592
|
+
email.add_argument(
|
|
593
|
+
"--from",
|
|
594
|
+
dest="from_email",
|
|
595
|
+
required=True,
|
|
596
|
+
help="From address, e.g. 'My App <signin@mail.example.com>'.",
|
|
597
|
+
)
|
|
598
|
+
email.add_argument(
|
|
599
|
+
"--api-key-file",
|
|
600
|
+
help="File holding the Resend API key ('-' for stdin). Defaults to "
|
|
601
|
+
"$KNUCKLES_RESEND_API_KEY, then a prompt.",
|
|
602
|
+
)
|
|
603
|
+
email.add_argument(
|
|
604
|
+
"--no-verify",
|
|
605
|
+
action="store_true",
|
|
606
|
+
help="Skip the Resend domain-verification check.",
|
|
607
|
+
)
|
|
608
|
+
email.set_defaults(handler=cmd_providers_email)
|
|
609
|
+
|
|
610
|
+
passkey = prov_sub.add_parser("passkey", help="WebAuthn passkeys.")
|
|
611
|
+
passkey.add_argument("app", help="Tenant client id.")
|
|
612
|
+
passkey.add_argument("--origin", required=True, help="Site origin.")
|
|
613
|
+
passkey.add_argument("--rp-id", help="Relying-party id (default: origin host).")
|
|
614
|
+
passkey.add_argument("--rp-name", help="Name in the prompt (default: app name).")
|
|
615
|
+
passkey.add_argument(
|
|
616
|
+
"--force-rp-id",
|
|
617
|
+
action="store_true",
|
|
618
|
+
help="Allow changing an rp_id that existing passkeys are bound to.",
|
|
619
|
+
)
|
|
620
|
+
passkey.set_defaults(handler=cmd_providers_passkey)
|
|
621
|
+
|
|
622
|
+
clear = prov_sub.add_parser("clear", help="Reset a group to env fallback.")
|
|
623
|
+
clear.add_argument("app", help="Tenant client id.")
|
|
624
|
+
clear.add_argument("group", choices=sorted(CONFIG_GROUPS))
|
|
625
|
+
clear.add_argument("--force-rp-id", action="store_true")
|
|
626
|
+
clear.set_defaults(handler=cmd_providers_clear)
|
|
627
|
+
|
|
628
|
+
doctor = sub.add_parser("doctor", help="Check the server and tenants.")
|
|
629
|
+
doctor.add_argument("client_id", nargs="?", help="Check only this tenant.")
|
|
630
|
+
doctor.set_defaults(handler=cmd_doctor)
|
|
631
|
+
return parser
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _print_error(exc: CliError, *, as_json: bool) -> None:
|
|
635
|
+
"""Report a failure in the requested format.
|
|
636
|
+
|
|
637
|
+
Args:
|
|
638
|
+
exc: The error.
|
|
639
|
+
as_json: Print the API error envelope to stdout instead of
|
|
640
|
+
text to stderr.
|
|
641
|
+
"""
|
|
642
|
+
if as_json:
|
|
643
|
+
print(json.dumps({"error": {"code": exc.code, "message": exc.message}}))
|
|
644
|
+
else:
|
|
645
|
+
print(f"error: {exc.code}: {exc.message}", file=sys.stderr)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def main(argv: list[str] | None = None) -> int:
|
|
649
|
+
"""Run the CLI.
|
|
650
|
+
|
|
651
|
+
Args:
|
|
652
|
+
argv: Arguments after the program name; defaults to
|
|
653
|
+
``sys.argv[1:]``.
|
|
654
|
+
|
|
655
|
+
Returns:
|
|
656
|
+
The process exit code.
|
|
657
|
+
"""
|
|
658
|
+
parser = _build_parser()
|
|
659
|
+
try:
|
|
660
|
+
args = parser.parse_args(argv)
|
|
661
|
+
except SystemExit as exc:
|
|
662
|
+
return int(exc.code or 0)
|
|
663
|
+
|
|
664
|
+
env = os.environ
|
|
665
|
+
ctx = Context(
|
|
666
|
+
as_json=args.json,
|
|
667
|
+
profile=args.profile or env.get("KNUCKLES_PROFILE") or "default",
|
|
668
|
+
config=config_path(env),
|
|
669
|
+
env=env,
|
|
670
|
+
)
|
|
671
|
+
try:
|
|
672
|
+
result: Result = args.handler(args, ctx)
|
|
673
|
+
except CliError as exc:
|
|
674
|
+
_print_error(exc, as_json=ctx.as_json)
|
|
675
|
+
return 1
|
|
676
|
+
except OSError as exc:
|
|
677
|
+
_print_error(CliError(INVALID_INPUT, str(exc)), as_json=ctx.as_json)
|
|
678
|
+
return 1
|
|
679
|
+
|
|
680
|
+
if ctx.as_json:
|
|
681
|
+
print(json.dumps({"data": result.data}, indent=2))
|
|
682
|
+
else:
|
|
683
|
+
print("\n".join(result.lines))
|
|
684
|
+
return result.exit_code
|