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/ops.py ADDED
@@ -0,0 +1,451 @@
1
+ """Tenant operations shared by the ``knuckles`` CLI and ``knuckles-mcp``.
2
+
3
+ Each function takes a :class:`~knuckles_cli.api.KnucklesAPI` plus plain
4
+ arguments and returns plain data. None of them parse arguments, read
5
+ stdin, or print, so both the command line and the MCP server can call
6
+ them (Decision #027).
7
+
8
+ Secrets are passed in already read: how a secret is obtained (a file,
9
+ an env var, a prompt) is the caller's concern. Functions that receive
10
+ a new tenant secret from the server write it to an ``.env`` file when
11
+ one is given and drop it from the returned data.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ from knuckles_cli.doctor import Check, check_app, check_server
20
+ from knuckles_cli.envfile import check_env, write_env
21
+ from knuckles_cli.errors import EMAIL_DOMAIN_UNVERIFIED, INVALID_INPUT, CliError
22
+ from knuckles_cli.providers import (
23
+ CONFIG_GROUPS,
24
+ apple_key_id_from_filename,
25
+ check_resend_domain,
26
+ email_address_of,
27
+ origin_of,
28
+ passkey_config,
29
+ validate_apple_identifier,
30
+ validate_apple_private_key,
31
+ validate_services_id,
32
+ )
33
+
34
+ if TYPE_CHECKING:
35
+ from collections.abc import Iterable
36
+ from pathlib import Path
37
+
38
+ from knuckles_cli.api import KnucklesAPI
39
+
40
+
41
+ @dataclass
42
+ class ProviderResult:
43
+ """Outcome of a provider update.
44
+
45
+ Attributes:
46
+ row: The updated, redacted app-client row.
47
+ warnings: Non-fatal problems the operator should see.
48
+ """
49
+
50
+ row: dict[str, Any]
51
+ warnings: list[str] = field(default_factory=list)
52
+
53
+ def to_dict(self) -> dict[str, Any]:
54
+ """Serialize for JSON output.
55
+
56
+ Returns:
57
+ ``{"app": row, "warnings": [...]}``.
58
+ """
59
+ return {"app": self.row, "warnings": self.warnings}
60
+
61
+
62
+ @dataclass
63
+ class DoctorReport:
64
+ """Every doctor check plus a status tally.
65
+
66
+ Attributes:
67
+ checks: Checks in the order they ran.
68
+ """
69
+
70
+ checks: list[Check]
71
+
72
+ @property
73
+ def summary(self) -> dict[str, int]:
74
+ """Count checks by status.
75
+
76
+ Returns:
77
+ ``{"ok": n, "warn": n, "fail": n}``.
78
+ """
79
+ return {
80
+ s: sum(c.status == s for c in self.checks) for s in ("ok", "warn", "fail")
81
+ }
82
+
83
+ @property
84
+ def failed(self) -> bool:
85
+ """Whether any check failed.
86
+
87
+ Returns:
88
+ ``True`` if at least one check has status ``fail``.
89
+ """
90
+ return self.summary["fail"] > 0
91
+
92
+ def to_dict(self) -> dict[str, Any]:
93
+ """Serialize for JSON output.
94
+
95
+ Returns:
96
+ ``{"checks": [...], "summary": {...}}``.
97
+ """
98
+ return {"checks": [c.to_dict() for c in self.checks], "summary": self.summary}
99
+
100
+
101
+ def _write_credentials(
102
+ path: Path, *, url: str, client_id: str, secret: str, force: bool
103
+ ) -> None:
104
+ """Write the three consuming-app variables into a ``.env`` file.
105
+
106
+ Args:
107
+ path: The ``.env`` file.
108
+ url: Knuckles base URL.
109
+ client_id: Tenant ``client_id``.
110
+ secret: Plaintext client secret.
111
+ force: Overwrite differing values.
112
+ """
113
+ write_env(
114
+ path,
115
+ {
116
+ "KNUCKLES_URL": url,
117
+ "KNUCKLES_CLIENT_ID": client_id,
118
+ "KNUCKLES_CLIENT_SECRET": secret,
119
+ },
120
+ force=force,
121
+ )
122
+
123
+
124
+ def create_app(
125
+ api: KnucklesAPI,
126
+ *,
127
+ client_id: str,
128
+ name: str,
129
+ origins: Iterable[str],
130
+ env_file: Path | None = None,
131
+ force: bool = False,
132
+ ) -> dict[str, Any]:
133
+ """Create a tenant, optionally writing its credentials to ``.env``.
134
+
135
+ The ``.env`` file is checked for conflicts before the tenant is
136
+ created, so a refusal leaves the server untouched.
137
+
138
+ Args:
139
+ api: Admin API client.
140
+ client_id: New tenant id.
141
+ name: Human-readable app name.
142
+ origins: Allowed browser origins (normalized to bare origins).
143
+ env_file: ``.env`` to receive the credentials, or ``None`` to
144
+ return the secret instead.
145
+ force: Overwrite differing values already in ``env_file``.
146
+
147
+ Returns:
148
+ The created row. It carries ``client_secret`` only when no
149
+ ``env_file`` was given; otherwise it carries ``env_file``.
150
+ """
151
+ normalized = [origin_of(o) for o in origins]
152
+ if env_file:
153
+ check_env(
154
+ env_file,
155
+ {
156
+ "KNUCKLES_URL": api.base_url,
157
+ "KNUCKLES_CLIENT_ID": client_id,
158
+ "KNUCKLES_CLIENT_SECRET": None,
159
+ },
160
+ force=force,
161
+ )
162
+ created = api.create_app(
163
+ client_id=client_id, app_name=name, allowed_origins=normalized
164
+ )
165
+ if env_file:
166
+ secret = str(created.pop("client_secret"))
167
+ _write_credentials(
168
+ env_file,
169
+ url=api.base_url,
170
+ client_id=client_id,
171
+ secret=secret,
172
+ force=force,
173
+ )
174
+ created["env_file"] = str(env_file)
175
+ return created
176
+
177
+
178
+ def next_steps(client_id: str, origin: str | None) -> list[str]:
179
+ """List the CLI commands that finish setting up a new tenant.
180
+
181
+ Args:
182
+ client_id: The tenant id.
183
+ origin: The tenant's primary origin, if any.
184
+
185
+ Returns:
186
+ Shell commands in the order an operator would run them.
187
+ """
188
+ return [
189
+ f"knuckles providers email {client_id} --from 'Your App <signin@your-domain>'",
190
+ f"knuckles providers google {client_id} "
191
+ "--client-secret-json client_secret.json",
192
+ f"knuckles providers apple {client_id} --services-id com.example.web "
193
+ "--team-id TEAMID --p8 AuthKey_KEYID.p8",
194
+ f"knuckles providers passkey {client_id} --origin {origin or '<origin>'}",
195
+ f"knuckles doctor {client_id}",
196
+ "pip install knuckles-client # or: npm install @knuckles/client",
197
+ ]
198
+
199
+
200
+ def rotate_secret(
201
+ api: KnucklesAPI,
202
+ client_id: str,
203
+ *,
204
+ env_file: Path | None = None,
205
+ force: bool = False,
206
+ ) -> dict[str, Any]:
207
+ """Mint a new client secret; the old one stops working immediately.
208
+
209
+ Args:
210
+ api: Admin API client.
211
+ client_id: The tenant id.
212
+ env_file: ``.env`` to receive the new secret, or ``None`` to
213
+ return it instead.
214
+ force: Replace a ``KNUCKLES_CLIENT_SECRET`` already in
215
+ ``env_file``.
216
+
217
+ Returns:
218
+ The rotation result, carrying ``client_secret`` only when no
219
+ ``env_file`` was given; otherwise it carries ``env_file``.
220
+ """
221
+ if env_file:
222
+ check_env(env_file, {"KNUCKLES_CLIENT_SECRET": None}, force=force)
223
+ data = api.rotate_secret(client_id)
224
+ if env_file:
225
+ write_env(
226
+ env_file,
227
+ {"KNUCKLES_CLIENT_SECRET": str(data.pop("client_secret"))},
228
+ force=True,
229
+ )
230
+ data["env_file"] = str(env_file)
231
+ return data
232
+
233
+
234
+ def set_origins(
235
+ api: KnucklesAPI, client_id: str, origins: Iterable[str]
236
+ ) -> dict[str, Any]:
237
+ """Replace a tenant's allowed origins.
238
+
239
+ Args:
240
+ api: Admin API client.
241
+ client_id: The tenant id.
242
+ origins: New origin list (normalized to bare origins).
243
+
244
+ Returns:
245
+ The updated row.
246
+ """
247
+ return api.set_origins(client_id, [origin_of(o) for o in origins])
248
+
249
+
250
+ def configure_google(
251
+ api: KnucklesAPI,
252
+ app: str,
253
+ *,
254
+ client_id: str,
255
+ client_secret: str,
256
+ redirect_origins: Iterable[str] = (),
257
+ ) -> ProviderResult:
258
+ """Store a tenant's Google OAuth client.
259
+
260
+ Args:
261
+ api: Admin API client.
262
+ app: The tenant id.
263
+ client_id: Google OAuth client id.
264
+ client_secret: Google OAuth client secret.
265
+ redirect_origins: Origins of the redirect URIs registered in
266
+ Google Cloud Console, used to warn about ones the tenant
267
+ would reject.
268
+
269
+ Returns:
270
+ The updated row and a warning per redirect origin that is not
271
+ an allowed origin of the tenant.
272
+ """
273
+ allowed = {o.lower() for o in api.get_app(app)["allowed_origins"]}
274
+ warnings = [
275
+ f"Google redirect origin {o} is not an allowed origin of {app}; "
276
+ "add it with `knuckles apps set-origins` or sign-in starts will be rejected."
277
+ for o in redirect_origins
278
+ if o not in allowed
279
+ ]
280
+ row = api.update_app(
281
+ app,
282
+ {
283
+ "google_oauth_client_id": client_id,
284
+ "google_oauth_client_secret": client_secret,
285
+ },
286
+ )
287
+ return ProviderResult(row, warnings)
288
+
289
+
290
+ def configure_apple(
291
+ api: KnucklesAPI,
292
+ app: str,
293
+ *,
294
+ services_id: str,
295
+ team_id: str,
296
+ p8_path: Path,
297
+ key_id: str | None = None,
298
+ ) -> ProviderResult:
299
+ """Store a tenant's Sign in with Apple credentials from a ``.p8`` file.
300
+
301
+ Args:
302
+ api: Admin API client.
303
+ app: The tenant id.
304
+ services_id: Apple Services ID for the website.
305
+ team_id: Apple Developer team id.
306
+ p8_path: Path to the ``AuthKey_<KEYID>.p8`` file.
307
+ key_id: Key id, if the file was renamed.
308
+
309
+ Returns:
310
+ The updated row.
311
+
312
+ Raises:
313
+ CliError: ``INVALID_INPUT`` if the key id cannot be determined
314
+ or any value is malformed.
315
+ """
316
+ pem = p8_path.read_text()
317
+ validate_apple_private_key(pem)
318
+ resolved_key_id = key_id or apple_key_id_from_filename(str(p8_path))
319
+ if not resolved_key_id:
320
+ raise CliError(
321
+ INVALID_INPUT,
322
+ "Could not read the key id from the filename; pass the key id.",
323
+ )
324
+ fields = {
325
+ "apple_oauth_client_id": validate_services_id(services_id),
326
+ "apple_oauth_team_id": validate_apple_identifier(team_id, "team id"),
327
+ "apple_oauth_key_id": validate_apple_identifier(resolved_key_id, "key id"),
328
+ "apple_oauth_private_key": pem,
329
+ }
330
+ return ProviderResult(api.update_app(app, fields))
331
+
332
+
333
+ def configure_email(
334
+ api: KnucklesAPI,
335
+ app: str,
336
+ *,
337
+ from_email: str,
338
+ api_key: str,
339
+ verify: bool = True,
340
+ ) -> ProviderResult:
341
+ """Store a tenant's Resend sender, checking the domain first.
342
+
343
+ Args:
344
+ api: Admin API client.
345
+ app: The tenant id.
346
+ from_email: From address, e.g. ``"My App <signin@mail.example.com>"``.
347
+ api_key: Resend API key.
348
+ verify: Check with Resend that the sending domain is verified.
349
+
350
+ Returns:
351
+ The updated row and any verification warning.
352
+
353
+ Raises:
354
+ CliError: ``EMAIL_DOMAIN_UNVERIFIED`` when Resend reports the
355
+ sending domain is missing or unverified.
356
+ """
357
+ domain = email_address_of(from_email).rsplit("@", 1)[1].lower()
358
+ warnings: list[str] = []
359
+ if verify:
360
+ status, detail = check_resend_domain(api_key, domain)
361
+ if status == "fail":
362
+ raise CliError(EMAIL_DOMAIN_UNVERIFIED, detail)
363
+ if status == "warn":
364
+ warnings.append(detail)
365
+ row = api.update_app(
366
+ app, {"resend_api_key": api_key, "resend_from_email": from_email}
367
+ )
368
+ return ProviderResult(row, warnings)
369
+
370
+
371
+ def configure_passkey(
372
+ api: KnucklesAPI,
373
+ app: str,
374
+ *,
375
+ origin: str,
376
+ rp_id: str | None = None,
377
+ rp_name: str | None = None,
378
+ force_rp_id: bool = False,
379
+ ) -> ProviderResult:
380
+ """Store a tenant's WebAuthn relying party.
381
+
382
+ Args:
383
+ api: Admin API client.
384
+ app: The tenant id.
385
+ origin: The site origin passkeys are used on.
386
+ rp_id: Relying-party id; defaults to the origin's host.
387
+ rp_name: Name shown in the passkey prompt; defaults to the
388
+ tenant's app name.
389
+ force_rp_id: Allow changing an rp_id existing passkeys use.
390
+
391
+ Returns:
392
+ The updated row.
393
+ """
394
+ name = rp_name or str(api.get_app(app)["app_name"])
395
+ fields: dict[str, Any] = passkey_config(origin=origin, rp_id=rp_id, rp_name=name)
396
+ fields["force_webauthn_rp_id"] = force_rp_id
397
+ return ProviderResult(api.update_app(app, fields))
398
+
399
+
400
+ def clear_provider(
401
+ api: KnucklesAPI, app: str, group: str, *, force_rp_id: bool = False
402
+ ) -> dict[str, Any]:
403
+ """Reset one config group to NULL (the operator env fallback).
404
+
405
+ Args:
406
+ api: Admin API client.
407
+ app: The tenant id.
408
+ group: ``email``, ``google``, ``apple`` or ``passkey``.
409
+ force_rp_id: Required to clear a passkey rp_id that registered
410
+ passkeys depend on.
411
+
412
+ Returns:
413
+ The updated row.
414
+
415
+ Raises:
416
+ CliError: ``INVALID_INPUT`` for an unknown group.
417
+ """
418
+ if group not in CONFIG_GROUPS:
419
+ raise CliError(
420
+ INVALID_INPUT,
421
+ f"Unknown group {group!r}; use one of {', '.join(CONFIG_GROUPS)}.",
422
+ )
423
+ spec = CONFIG_GROUPS[group]
424
+ fields: dict[str, Any] = dict.fromkeys(spec.columns)
425
+ if spec.name == "passkey":
426
+ fields["force_webauthn_rp_id"] = force_rp_id
427
+ return api.update_app(app, fields)
428
+
429
+
430
+ def doctor(api: KnucklesAPI, client_id: str | None = None) -> DoctorReport:
431
+ """Check the server and its tenants.
432
+
433
+ Args:
434
+ api: API client; tenant checks need an admin token.
435
+ client_id: Check only this tenant, or every tenant if ``None``.
436
+
437
+ Returns:
438
+ Every check that ran.
439
+ """
440
+ checks = check_server(api)
441
+ if not api.has_admin_token:
442
+ checks.append(Check("admin", "warn", "No admin token; tenant checks skipped."))
443
+ return DoctorReport(checks)
444
+ try:
445
+ rows = [api.get_app(client_id)] if client_id else api.list_apps()
446
+ except CliError as exc:
447
+ checks.append(Check("admin", "fail", f"{exc.code}: {exc.message}"))
448
+ else:
449
+ for row in rows:
450
+ checks.extend(check_app(row))
451
+ return DoctorReport(checks)