ttlama-cli 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.
Files changed (38) hide show
  1. ttlama_cli/__init__.py +0 -0
  2. ttlama_cli/__main__.py +6 -0
  3. ttlama_cli/api_client.py +221 -0
  4. ttlama_cli/cli.py +71 -0
  5. ttlama_cli/commands/__init__.py +256 -0
  6. ttlama_cli/commands/admin/__init__.py +22 -0
  7. ttlama_cli/commands/admin/devices.py +300 -0
  8. ttlama_cli/commands/admin/leases.py +244 -0
  9. ttlama_cli/commands/admin/profiles.py +328 -0
  10. ttlama_cli/commands/admin/users.py +460 -0
  11. ttlama_cli/commands/auth.py +469 -0
  12. ttlama_cli/commands/backend/__init__.py +18 -0
  13. ttlama_cli/commands/backend/openvpn/__init__.py +0 -0
  14. ttlama_cli/commands/backend/openvpn/peers.py +0 -0
  15. ttlama_cli/commands/backend/wireguard/__init__.py +18 -0
  16. ttlama_cli/commands/backend/wireguard/peers.py +282 -0
  17. ttlama_cli/commands/config.py +350 -0
  18. ttlama_cli/commands/user/__init__.py +29 -0
  19. ttlama_cli/commands/user/devices.py +214 -0
  20. ttlama_cli/commands/user/get.py +95 -0
  21. ttlama_cli/commands/user/leases.py +223 -0
  22. ttlama_cli/commands/user/profiles.py +84 -0
  23. ttlama_cli/config_store.py +109 -0
  24. ttlama_cli/drivers/__init__.py +19 -0
  25. ttlama_cli/drivers/_common.py +116 -0
  26. ttlama_cli/drivers/openvpn.py +59 -0
  27. ttlama_cli/drivers/wireguard.py +165 -0
  28. ttlama_cli/exc.py +78 -0
  29. ttlama_cli/objects/__init__.py +18 -0
  30. ttlama_cli/objects/requests.py +65 -0
  31. ttlama_cli/token_store.py +85 -0
  32. ttlama_cli/utils.py +30 -0
  33. ttlama_cli-0.1.0.dist-info/METADATA +310 -0
  34. ttlama_cli-0.1.0.dist-info/RECORD +38 -0
  35. ttlama_cli-0.1.0.dist-info/WHEEL +5 -0
  36. ttlama_cli-0.1.0.dist-info/entry_points.txt +2 -0
  37. ttlama_cli-0.1.0.dist-info/licenses/LICENSE +71 -0
  38. ttlama_cli-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,469 @@
1
+ """Commands for TTL-LAMa CLI.
2
+
3
+ .. prefix:: `ttlama auth`
4
+
5
+ .. CLI::
6
+ - `login`: Login to TTL-LAMa.
7
+ - `internal`: Login with an internal account.
8
+ - `logout`: Logout from TTL-LAMa.
9
+ - `status`: Display the current authentication status.
10
+ - `password-chg`: Change the password for the current user.
11
+
12
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
13
+ .. version:: 1.0.0
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import hmac
19
+ import secrets
20
+ import time
21
+ from typing import Any, cast
22
+ from http.server import BaseHTTPRequestHandler, HTTPServer
23
+ from urllib.parse import parse_qs, urlencode, urlsplit
24
+ import webbrowser
25
+
26
+ import typer
27
+ from rich.console import Console
28
+ from rich.table import Table
29
+
30
+ from ..api_client import (
31
+ authenticate_internal,
32
+ begin_oidc_device_authorization,
33
+ exchange_oidc_cli_ticket,
34
+ poll_oidc_device_authorization,
35
+ request_api,
36
+ )
37
+ from ..config_store import load_server_config
38
+ from ..token_store import (
39
+ delete_access_token,
40
+ get_access_token,
41
+ save_access_token,
42
+ )
43
+ from ..exc import (
44
+ APIError,
45
+ AuthenticationError,
46
+ AuthorizationError,
47
+ TokenStorageError,
48
+ )
49
+ from ..objects import HTTPMethod, ServerParameters, SpecificRequest
50
+ from ..utils import json_to_yaml
51
+
52
+ INVALID_RESPONSE = "The API status response is invalid."
53
+ OIDC_CALLBACK_TIMEOUT = 300
54
+ DEVICE_POLL_INCREMENT = 5
55
+
56
+ app = typer.Typer(
57
+ no_args_is_help=True,
58
+ help="Authentication to a TTL-LAMa.",
59
+ )
60
+
61
+ login_app = typer.Typer(
62
+ no_args_is_help=True,
63
+ help="Login to TTL-LAMa.",
64
+ )
65
+
66
+ app.add_typer(login_app, name="login")
67
+
68
+
69
+ class _OidcCallbackServer(HTTPServer):
70
+ """Receive one state-verified OIDC ticket on the loopback interface."""
71
+
72
+ def __init__(self, state: str) -> None:
73
+ self.expected_state = state
74
+ self.callback_ticket: str | None = None
75
+ self.callback_error: str | None = None
76
+ self.callback_received = False
77
+ super().__init__(("127.0.0.1", 0), _OidcCallbackHandler)
78
+
79
+
80
+ class _OidcCallbackHandler(BaseHTTPRequestHandler):
81
+ """Handle the local OIDC redirect without logging its query string."""
82
+
83
+ def do_GET(self) -> None: # pylint: disable=C0103
84
+ """Validate the loopback path and state, then retain only the ticket."""
85
+ server = cast(_OidcCallbackServer, self.server)
86
+ parsed = urlsplit(self.path)
87
+ parameters = parse_qs(parsed.query)
88
+ state_values = parameters.get("state", [])
89
+ ticket_values = parameters.get("ticket", [])
90
+ if parsed.path != "/callback":
91
+ self.send_error(404)
92
+ return
93
+ if (
94
+ len(state_values) != 1
95
+ or not hmac.compare_digest(state_values[0], server.expected_state)
96
+ ):
97
+ server.callback_error = "OIDC callback state did not match."
98
+ server.callback_received = True
99
+ self._respond(400, "Login response rejected.")
100
+ return
101
+ if parameters.get("error") or len(ticket_values) != 1 or not ticket_values[0]:
102
+ server.callback_error = "OIDC authentication was not completed."
103
+ server.callback_received = True
104
+ self._respond(400, "Login was not completed. Return to the CLI.")
105
+ return
106
+
107
+ server.callback_ticket = ticket_values[0]
108
+ server.callback_received = True
109
+ self._respond(200, "Authentication complete. You may close this window.")
110
+
111
+ def log_message(self, *args: Any) -> None: # type: ignore[override]
112
+ """Do not log callback URLs, which contain the temporary ticket."""
113
+
114
+ def _respond(self, http_status: int, message: str) -> None:
115
+ body = message.encode("utf-8")
116
+ self.send_response(http_status)
117
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
118
+ self.send_header("Content-Length", str(len(body)))
119
+ self.send_header("Cache-Control", "no-store")
120
+ self.send_header("Referrer-Policy", "no-referrer")
121
+ self.end_headers()
122
+ self.wfile.write(body)
123
+
124
+
125
+ def _browser_oidc_login(server: ServerParameters) -> str:
126
+ """Complete OIDC login through a local callback and one-time ticket."""
127
+ state = secrets.token_urlsafe(32)
128
+ with _OidcCallbackServer(state) as callback_server:
129
+ callback_server.timeout = 0.25
130
+ callback_url = f"http://127.0.0.1:{callback_server.server_port}/callback"
131
+ login_url = (
132
+ f"{server.server_url}:{server.server_port}/auth/login?"
133
+ + urlencode({"cli_callback_url": callback_url, "cli_state": state})
134
+ )
135
+ try:
136
+ opened = webbrowser.open(login_url)
137
+ except webbrowser.Error:
138
+ opened = False
139
+ if not opened:
140
+ typer.echo(f"Open this URL to sign in: {login_url}")
141
+
142
+ deadline = time.monotonic() + OIDC_CALLBACK_TIMEOUT
143
+ while not callback_server.callback_received and time.monotonic() < deadline:
144
+ callback_server.handle_request()
145
+
146
+ callback_ticket = callback_server.callback_ticket
147
+ callback_error = callback_server.callback_error
148
+ callback_received = callback_server.callback_received
149
+ if not callback_received:
150
+ raise APIError("Timed out waiting for the OIDC browser callback.")
151
+ if callback_error is not None or callback_ticket is None:
152
+ raise AuthenticationError(callback_error or "OIDC authentication failed.")
153
+ return exchange_oidc_cli_ticket(server, callback_ticket)
154
+
155
+
156
+ def _device_authorization_details(
157
+ response: dict[str, object],
158
+ ) -> tuple[str, str, str, int, int]:
159
+ """Validate and unpack the public fields of a device authorization response."""
160
+ device_code = response.get("device_code")
161
+ user_code = response.get("user_code")
162
+ verification_uri = response.get(
163
+ "verification_uri_complete",
164
+ response.get("verification_uri"),
165
+ )
166
+ expires_in = response.get("expires_in")
167
+ interval = response.get("interval", 5)
168
+ if (
169
+ not isinstance(device_code, str)
170
+ or not device_code
171
+ or not isinstance(user_code, str)
172
+ or not user_code
173
+ or not isinstance(verification_uri, str)
174
+ or not verification_uri
175
+ or not isinstance(expires_in, int)
176
+ or expires_in <= 0
177
+ or not isinstance(interval, int)
178
+ or interval <= 0
179
+ ):
180
+ raise APIError("OIDC device authorization response is invalid.")
181
+ return device_code, user_code, verification_uri, expires_in, interval
182
+
183
+
184
+ def _poll_distant_oidc_login(
185
+ server: ServerParameters,
186
+ device_code: str,
187
+ expires_in: int,
188
+ interval: int,
189
+ ) -> str:
190
+ """Poll until authorization succeeds, is denied, or expires."""
191
+ deadline = time.monotonic() + expires_in
192
+ while time.monotonic() < deadline:
193
+ time.sleep(interval)
194
+ result = poll_oidc_device_authorization(server, device_code)
195
+ status_value = result.get("status")
196
+ if status_value == "complete":
197
+ token = result.get("access_token")
198
+ if isinstance(token, str) and token:
199
+ return token
200
+ raise APIError("OIDC API response does not contain a valid access token.")
201
+ if status_value == "pending":
202
+ continue
203
+ if status_value == "slow_down":
204
+ interval += DEVICE_POLL_INCREMENT
205
+ continue
206
+ if status_value == "denied":
207
+ raise AuthenticationError("OIDC device authorization was denied.")
208
+ if status_value == "expired":
209
+ raise AuthenticationError("OIDC device authorization expired.")
210
+ raise APIError("OIDC device authorization response is invalid.")
211
+ raise AuthenticationError("OIDC device authorization expired.")
212
+
213
+
214
+ def _distant_oidc_login(server: ServerParameters) -> str:
215
+ """Complete OIDC login by polling the server-side device authorization relay."""
216
+ response = begin_oidc_device_authorization(server)
217
+ device_code, user_code, verification_uri, expires_in, interval = (
218
+ _device_authorization_details(response)
219
+ )
220
+ typer.echo(f"Open {verification_uri} and enter code {user_code}.")
221
+ return _poll_distant_oidc_login(server, device_code, expires_in, interval)
222
+
223
+
224
+ def _status_payload(response: object) -> dict[str, object]:
225
+ """Validate and restrict the identity and session data returned by the API."""
226
+ if not isinstance(response, dict):
227
+ raise APIError(INVALID_RESPONSE)
228
+ response_data = cast(dict[str, object], response)
229
+ raw_user = response_data.get("user")
230
+ raw_sessions = response_data.get("sessions")
231
+ if not isinstance(raw_user, dict) or not isinstance(raw_sessions, list):
232
+ raise APIError(INVALID_RESPONSE)
233
+
234
+ user_data = cast(dict[str, object], raw_user)
235
+ user = {
236
+ key: user_data.get(key)
237
+ for key in ("id", "username", "email", "is_admin")
238
+ }
239
+ sessions: list[dict[str, str]] = []
240
+ for raw_session in cast(list[object], raw_sessions):
241
+ if not isinstance(raw_session, dict):
242
+ raise APIError(INVALID_RESPONSE)
243
+ session_data = cast(dict[str, object], raw_session)
244
+ expiration = session_data.get("expires_at")
245
+ if not isinstance(expiration, str):
246
+ raise APIError(INVALID_RESPONSE)
247
+ sessions.append({"expires_at": expiration})
248
+
249
+ return {
250
+ "session": "active" if sessions else "inactive",
251
+ "user": user,
252
+ "sessions": sessions,
253
+ }
254
+
255
+
256
+ def _display_status(
257
+ status_data: dict[str, object],
258
+ *,
259
+ json_output: bool,
260
+ yaml_output: bool,
261
+ ) -> None:
262
+ """Display status as JSON, YAML, or a Rich table."""
263
+ if json_output:
264
+ typer.echo(json.dumps(status_data, ensure_ascii=False, indent=2))
265
+ return
266
+ if yaml_output:
267
+ typer.echo(json_to_yaml(json.dumps(status_data, ensure_ascii=False)))
268
+ return
269
+
270
+ typer.echo()
271
+ table = Table(title="Authentication Status", expand=True)
272
+ table.add_column("Item", style="cyan")
273
+ table.add_column("Value", style="green")
274
+ table.add_row("Session", str(status_data["session"]))
275
+ user = cast(dict[str, object] | None, status_data["user"])
276
+ if user is not None:
277
+ table.add_row("User", str(user["username"] or "-"))
278
+ table.add_row("Email", str(user["email"] or "-"))
279
+ table.add_row("Administrator", "yes" if user["is_admin"] else "no")
280
+ sessions = cast(list[dict[str, str]], status_data["sessions"])
281
+ table.add_row("Active sessions", str(len(sessions)))
282
+ for index, session in enumerate(sessions, start=1):
283
+ table.add_row(f"Expiration {index}", session["expires_at"])
284
+ Console().print(table)
285
+
286
+
287
+ @login_app.command("internal")
288
+ def login_internal(
289
+ user: str = typer.Option(
290
+ ...,
291
+ "--user",
292
+ help="Username for internal login.",
293
+ ),
294
+ ) -> None:
295
+ """Connect with an internal account to a TTL-LAMa session."""
296
+ try:
297
+ server_url, server_port = load_server_config()
298
+ token = authenticate_internal(
299
+ server_url,
300
+ server_port,
301
+ user,
302
+ typer.prompt("Password", hide_input=True),
303
+ )
304
+ save_access_token(
305
+ server_url,
306
+ server_port,
307
+ token,
308
+ )
309
+ except (APIError, AuthenticationError, TokenStorageError) as error:
310
+ typer.echo(str(error), err=True)
311
+ raise typer.Exit(code=1) from None
312
+
313
+ typer.echo("Login successful. Token saved in the system keyring.")
314
+
315
+
316
+ @login_app.command("oidc")
317
+ def login_oidc(
318
+ distant: bool = typer.Option(
319
+ False,
320
+ "--distant",
321
+ help="Use a device code for sign-in from another browser or device.",
322
+ ),
323
+ ) -> None:
324
+ """Sign in with the configured OIDC provider."""
325
+ try:
326
+ server_url, server_port = load_server_config()
327
+ server = ServerParameters(server_url=server_url, server_port=server_port)
328
+ token = _distant_oidc_login(server) if distant else _browser_oidc_login(server)
329
+ save_access_token(server_url, server_port, token)
330
+ except (
331
+ APIError,
332
+ AuthenticationError,
333
+ AuthorizationError,
334
+ TokenStorageError,
335
+ ) as error:
336
+ typer.echo(str(error), err=True)
337
+ raise typer.Exit(code=1) from None
338
+ except KeyboardInterrupt:
339
+ typer.echo("OIDC login cancelled.", err=True)
340
+ raise typer.Exit(code=1) from None
341
+
342
+ typer.echo("OIDC login successful. Token saved in the system keyring.")
343
+
344
+
345
+ @app.command("logout")
346
+ def logout() -> None:
347
+ """Revoke the current session and remove its local token."""
348
+ try:
349
+ server_url, server_port = load_server_config()
350
+ token = get_access_token(server_url, server_port)
351
+ except (FileNotFoundError, ValueError, TokenStorageError) as error:
352
+ typer.echo(str(error), err=True)
353
+ raise typer.Exit(code=1) from None
354
+
355
+ if not token:
356
+ typer.echo("No active session. Already logged out.")
357
+ return
358
+
359
+ try:
360
+ request_api(
361
+ server=ServerParameters(server_url=server_url, server_port=server_port),
362
+ token=token,
363
+ specific_request=SpecificRequest(
364
+ endpoint="auth/logout",
365
+ method=HTTPMethod.POST,
366
+ ),
367
+ )
368
+ except AuthenticationError:
369
+ try:
370
+ delete_access_token(server_url, server_port)
371
+ except TokenStorageError as error:
372
+ typer.echo(str(error), err=True)
373
+ raise typer.Exit(code=1) from None
374
+ typer.echo("The session was already inactive. Local token deleted.")
375
+ return
376
+ except (APIError, AuthorizationError) as error:
377
+ typer.echo(str(error), err=True)
378
+ raise typer.Exit(code=1) from None
379
+
380
+ try:
381
+ delete_access_token(server_url, server_port)
382
+ except TokenStorageError as error:
383
+ typer.echo(str(error), err=True)
384
+ raise typer.Exit(code=1) from None
385
+ typer.echo("Logout successful. Local token deleted.")
386
+
387
+
388
+ @app.command("status")
389
+ def status(
390
+ json_output: bool = typer.Option(False, "--json", help="Output status as JSON."),
391
+ yaml_output: bool = typer.Option(False, "--yaml", help="Output status as YAML."),
392
+ check_connected: bool = typer.Option(
393
+ False,
394
+ "--check",
395
+ help="Exit with status 1 when no active session is available.",
396
+ ),
397
+ ) -> None:
398
+ """Display the current identity and active session expirations."""
399
+ if json_output and yaml_output:
400
+ typer.echo("Choose only one output option: --json or --yaml.", err=True)
401
+ raise typer.Exit(code=1)
402
+
403
+ try:
404
+ server_url, server_port = load_server_config()
405
+ token = get_access_token(server_url, server_port)
406
+ except (FileNotFoundError, ValueError, TokenStorageError) as error:
407
+ typer.echo(str(error), err=True)
408
+ raise typer.Exit(code=1) from None
409
+
410
+ status_data: dict[str, object]
411
+ if token:
412
+ try:
413
+ response = request_api(
414
+ server=ServerParameters(server_url=server_url, server_port=server_port),
415
+ token=token,
416
+ specific_request=SpecificRequest(
417
+ endpoint="users/me",
418
+ method=HTTPMethod.GET,
419
+ ),
420
+ )
421
+ status_data = _status_payload(response)
422
+ except AuthenticationError:
423
+ typer.echo("Token invalid or expired. Login again.", err=True)
424
+ raise typer.Exit(code=1) from None
425
+ except (APIError, AuthorizationError) as error:
426
+ typer.echo(str(error), err=True)
427
+ raise typer.Exit(code=1) from None
428
+ else:
429
+ status_data = {"session": "inactive", "user": None, "sessions": []}
430
+
431
+ _display_status(status_data, json_output=json_output, yaml_output=yaml_output)
432
+ if check_connected and status_data["session"] != "active":
433
+ raise typer.Exit(code=1)
434
+
435
+
436
+ @app.command("password-chg")
437
+ def change_password() -> None:
438
+ """Change the password of the authenticated account."""
439
+ try:
440
+ server_url, server_port = load_server_config()
441
+ token = get_access_token(server_url, server_port)
442
+ if not token:
443
+ raise TokenStorageError("No access token is stored for this instance.")
444
+
445
+ current_password = typer.prompt("Current password", hide_input=True)
446
+ new_password = typer.prompt("New password", hide_input=True)
447
+ confirmation = typer.prompt("Confirm new password", hide_input=True)
448
+ if new_password != confirmation:
449
+ typer.echo("New passwords do not match.", err=True)
450
+ raise typer.Exit(code=1)
451
+
452
+ request_api(
453
+ ServerParameters(server_url=server_url, server_port=server_port),
454
+ token,
455
+ SpecificRequest(
456
+ endpoint="users/me/password",
457
+ method=HTTPMethod.PATCH,
458
+ json_body={
459
+ "current_password": current_password,
460
+ "new_password": new_password,
461
+ },
462
+ ),
463
+ )
464
+ except (FileNotFoundError, ValueError, APIError, AuthenticationError,
465
+ AuthorizationError, TokenStorageError) as error:
466
+ typer.echo(str(error), err=True)
467
+ raise typer.Exit(code=1) from None
468
+
469
+ typer.echo("Password changed. Reconnect → All sessions are revoked.")
@@ -0,0 +1,18 @@
1
+ """Backend command group for local VPN operations.
2
+
3
+ .. CLI::
4
+ - `wg` for WireGuard operations.
5
+
6
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
7
+ .. version:: 1.0.0
8
+ """
9
+
10
+ import typer
11
+
12
+ from .wireguard import app as wireguard_app
13
+
14
+ app = typer.Typer(
15
+ no_args_is_help=True,
16
+ help="Operate local VPN backends.",
17
+ )
18
+ app.add_typer(wireguard_app, name="wg")
File without changes
File without changes
@@ -0,0 +1,18 @@
1
+ """WireGuard backend commands.
2
+
3
+ .. CLI::
4
+ - `leases` for managing WireGuard peers as TTL-LAMa leases.
5
+
6
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
7
+ .. version:: 1.0.0
8
+ """
9
+
10
+ import typer
11
+
12
+ from .peers import app as leases_app
13
+
14
+ app = typer.Typer(
15
+ no_args_is_help=True,
16
+ help="Manage WireGuard peers as TTL-LAMa leases.",
17
+ )
18
+ app.add_typer(leases_app, name="leases")