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,460 @@
1
+ """User management commands for the TTL-LAMa CLI.
2
+
3
+ .. CLI:: `ttlama admin **users**`
4
+ - `list`: list all users.
5
+ - `--device`: filter users by device ID.
6
+ - `--lease`: filter users by lease ID.
7
+ - `--profile`: filter users by profile ID.
8
+ - `--json`: output the list of users in JSON format.
9
+ - `--yaml`: output the list of users in YAML format.
10
+ - `get`: retrieve a specific user by ID.
11
+ - `--json`: output the user data in JSON format.
12
+ - `--yaml`: output the user data in YAML format.
13
+ - `create`: create a new user.
14
+ - `--file`: path to a JSON or YAML file containing the user data.
15
+ - `update`: update an existing user.
16
+ - `--user`: ID of the user to update.
17
+ - `--file`: path to a JSON or YAML file containing the user data.
18
+ - `delete`: delete a user.
19
+ - `--user`: ID of the user to delete.
20
+ - `assign`: assign a profile to a user.
21
+ - `--user`: ID of the user.
22
+ - `--profile`: ID of the profile.
23
+ - `unassign`: revoke a user's profile assignment.
24
+ - `--user`: ID of the user.
25
+ - `--profile`: ID of the profile.
26
+
27
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
28
+ .. version:: 1.0.0
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ from pathlib import Path
34
+ from typing import cast
35
+
36
+ import typer
37
+ from rich.console import Console
38
+ from rich.table import Table
39
+
40
+ from .. import (
41
+ display_structured_output,
42
+ get_server_and_token as _get_server_and_token,
43
+ load_data_file as _load_data_file,
44
+ validate_output_options,
45
+ )
46
+ from ...api_client import request_api
47
+ from ...objects import HTTPMethod, SpecificRequest, ServerParameters
48
+ from ...objects.requests import JSONValue
49
+ from ...exc import (
50
+ APIError,
51
+ AuthenticationError,
52
+ AuthorizationError,
53
+ handle_api_error,
54
+ )
55
+ from ...utils import json_to_yaml
56
+
57
+ users_app = typer.Typer(
58
+ no_args_is_help=True,
59
+ help="User management commands for the TTL-LAMa CLI.",
60
+ )
61
+
62
+ EDITABLE_USER_FIELDS = {"username", "email", "enabled", "is_admin"}
63
+
64
+
65
+ def _load_user_file(file_path: Path) -> dict[str, JSONValue]:
66
+ """Load a user request body from a JSON or YAML file.
67
+
68
+ :param file_path: Path to the JSON or YAML user data file.
69
+ :type file_path: Path
70
+ :returns: Dictionary representing the user request body.
71
+ :rtype: dict[str, JSONValue]
72
+ """
73
+ return _load_data_file(file_path, "user")
74
+
75
+
76
+ def _create_filters(
77
+ device: int | None = None,
78
+ lease: int | None = None,
79
+ profile: int | None = None
80
+ ) -> dict[str, int] | None:
81
+ """Create a dictionary of filters for the API request.
82
+
83
+ :param device: Device ID to filter by.
84
+ :type device: int | None
85
+ :param lease: Lease ID to filter by.
86
+ :type lease: int | None
87
+ :param profile: Profile ID to filter by.
88
+ :type profile: int | None
89
+ :return: Dictionary of filters, or None if no filters are set.
90
+ :rtype: dict[str, int] | None
91
+ """
92
+ filters = {
93
+ key: value
94
+ for key, value in {
95
+ "device": device,
96
+ "lease": lease,
97
+ "profile": profile
98
+ }.items()
99
+ if value is not None
100
+ }
101
+ return filters or None
102
+
103
+ @users_app.command("ls")
104
+ def list_users(
105
+ device: int | None = typer.Option(
106
+ None,
107
+ "--device",
108
+ help="Specify the device to list users from."
109
+ ),
110
+ lease: int | None = typer.Option(
111
+ None,
112
+ "--lease",
113
+ help="Specify the lease to list users from."
114
+ ),
115
+ profile: int | None = typer.Option(
116
+ None,
117
+ "--profile",
118
+ help="Specify the profile to list users from."
119
+ ),
120
+ json_output: bool = typer.Option(
121
+ False,
122
+ "--json",
123
+ help="Output the list of users in JSON format."
124
+ ),
125
+ yaml_output: bool = typer.Option(
126
+ False,
127
+ "--yaml",
128
+ help="Output the list of users in YAML format."
129
+ ),
130
+ ) -> None:
131
+ """Manage users in the TTL-LAMa CLI.
132
+
133
+ :param device: Filter by device ID.
134
+ :type device: int | None
135
+ :param lease: Filter by lease ID.
136
+ :type lease: int | None
137
+ :param profile: Filter by profile ID.
138
+ :type profile: int | None
139
+ :param json_output: Whether to output the list of users in JSON format.
140
+ :type json_output: bool
141
+ :param yaml_output: Whether to output the list of users in YAML format.
142
+ :type yaml_output: bool
143
+ """
144
+ validate_output_options(json_output, yaml_output)
145
+ url, port, token = _get_server_and_token()
146
+ filters = _create_filters(device=device, lease=lease, profile=profile)
147
+ users = None
148
+
149
+ request = SpecificRequest(
150
+ method=HTTPMethod.GET,
151
+ endpoint="admin/users",
152
+ params=filters or None,
153
+ )
154
+ try:
155
+ users = request_api(
156
+ server=ServerParameters(server_url=url, server_port=port),
157
+ token=token,
158
+ specific_request=request
159
+ )
160
+ if not users:
161
+ typer.echo("No users found.")
162
+ raise typer.Exit(code=1)
163
+ if not isinstance(users, list):
164
+ typer.echo("The API response isn't a user list.")
165
+ raise typer.Exit(code=1)
166
+ except (AuthorizationError, AuthenticationError, APIError) as e:
167
+ handle_api_error(e)
168
+
169
+ user_rows = cast(list[dict[str, object]], users)
170
+ if display_structured_output(
171
+ user_rows,
172
+ json_output=json_output,
173
+ yaml_output=yaml_output,
174
+ yaml_root="users",
175
+ ):
176
+ return
177
+
178
+ typer.echo()
179
+ table = Table(title="Users", expand=True)
180
+ table.add_column("User ID", justify="left", style="cyan", no_wrap=True, overflow="ellipsis")
181
+ table.add_column("Username", style="green", overflow="ellipsis")
182
+ table.add_column("Active", justify="center", style="red", overflow="ellipsis")
183
+ table.add_column("Admin", justify="center", style="red", overflow="ellipsis")
184
+ for u in user_rows:
185
+ table.add_row(
186
+ str(u.get("id", "")),
187
+ str(u.get("username", "")),
188
+ str(u.get("enabled", "")),
189
+ str(u.get("is_admin", "")),
190
+ )
191
+ console = Console()
192
+ console.print(table)
193
+
194
+
195
+ @users_app.command("create")
196
+ def create_user(
197
+ file_path: Path = typer.Option(
198
+ ...,
199
+ "--file",
200
+ help="Path to a JSON or YAML file containing user data.",
201
+ ),
202
+ ) -> None:
203
+ """Create a user from a JSON or YAML file.
204
+
205
+ :param file_path: Path to a JSON or YAML file containing user data.
206
+ :type file_path: Path
207
+ """
208
+ user_data = _load_user_file(file_path)
209
+ url, port, token = _get_server_and_token()
210
+
211
+ request = SpecificRequest(
212
+ method=HTTPMethod.POST,
213
+ endpoint="admin/users",
214
+ json_body=user_data,
215
+ )
216
+ result: dict[str, object] | list[dict[str, object]] | None = None
217
+ try:
218
+ result = request_api(
219
+ server=ServerParameters(server_url=url, server_port=port),
220
+ token=token,
221
+ specific_request=request,
222
+ )
223
+ except (AuthorizationError, AuthenticationError, APIError) as error:
224
+ handle_api_error(error)
225
+
226
+ typer.echo("User created successfully.")
227
+ if isinstance(result, dict):
228
+ generated_password = result.get("generated_password")
229
+ if isinstance(generated_password, str):
230
+ typer.echo(f"Generated password (shown only once): {generated_password}")
231
+ typer.echo("Save it now; it cannot be retrieved later.")
232
+
233
+
234
+ @users_app.command("update")
235
+ def update_user(
236
+ user_id: str = typer.Option(
237
+ ...,
238
+ "--user",
239
+ help="Specify the ID of the user to update.",
240
+ ),
241
+ file_path: Path = typer.Option(
242
+ ...,
243
+ "--file",
244
+ help="Path to a JSON or YAML file containing fields to update.",
245
+ ),
246
+ ) -> None:
247
+ """Update a user from a JSON or YAML file.
248
+
249
+ :param user_id: The ID of the user to update.
250
+ :type user_id: str
251
+ :param file_path: Path to a JSON or YAML file containing fields to update.
252
+ :type file_path: Path
253
+ """
254
+ user_data = _load_user_file(file_path)
255
+ if user_data.get("unlink_oidc"):
256
+ typer.echo(
257
+ "Warning: unlinking the last OIDC identity prevents this user from signing in via OIDC",
258
+ err=True,
259
+ )
260
+ url, port, token = _get_server_and_token()
261
+
262
+ request = SpecificRequest(
263
+ method=HTTPMethod.PATCH,
264
+ endpoint=f"admin/users/{user_id}",
265
+ json_body=user_data,
266
+ )
267
+ try:
268
+ request_api(
269
+ server=ServerParameters(server_url=url, server_port=port),
270
+ token=token,
271
+ specific_request=request,
272
+ )
273
+ except (AuthorizationError, AuthenticationError, APIError) as error:
274
+ handle_api_error(error)
275
+
276
+ typer.echo(f"User {user_id} updated successfully.")
277
+
278
+
279
+ @users_app.command("delete")
280
+ def delete_user(
281
+ user_id: str = typer.Option(
282
+ ...,
283
+ "--user",
284
+ help="Specify the ID of the user to delete.",
285
+ ),
286
+ ) -> None:
287
+ """Delete a user by ID.
288
+
289
+ :param user_id: The ID of the user to delete.
290
+ :type user_id: str
291
+
292
+ .. note::
293
+ This is a logical deletion; the user will be marked as deleted but not permanently
294
+ removed from the database. Until then, the user record will remain in the system.
295
+ """
296
+ url, port, token = _get_server_and_token()
297
+
298
+ request = SpecificRequest(
299
+ method=HTTPMethod.DELETE,
300
+ endpoint=f"admin/users/{user_id}",
301
+ )
302
+ try:
303
+ request_api(
304
+ server=ServerParameters(server_url=url, server_port=port),
305
+ token=token,
306
+ specific_request=request,
307
+ )
308
+ except (AuthorizationError, AuthenticationError, APIError) as error:
309
+ handle_api_error(error)
310
+
311
+ typer.echo(f"User {user_id} deleted successfully.")
312
+
313
+
314
+ @users_app.command("assign")
315
+ def assign_profile(
316
+ user_id: str = typer.Option(
317
+ ...,
318
+ "--user",
319
+ help="Specify the ID of the user to assign the profile to.",
320
+ ),
321
+ profile_id: int = typer.Option(
322
+ ...,
323
+ "--profile",
324
+ help="Specify the ID of the profile to assign.",
325
+ ),
326
+ ) -> None:
327
+ """Assign a profile to a user.
328
+
329
+ :param user_id: The ID of the user to assign the profile to.
330
+ :type user_id: str
331
+ :param profile_id: The ID of the profile to assign.
332
+ :type profile_id: int
333
+ """
334
+ url, port, token = _get_server_and_token()
335
+ request = SpecificRequest(
336
+ method=HTTPMethod.PUT,
337
+ endpoint=f"admin/users/{user_id}/profiles/{profile_id}",
338
+ )
339
+ try:
340
+ request_api(
341
+ server=ServerParameters(server_url=url, server_port=port),
342
+ token=token,
343
+ specific_request=request,
344
+ )
345
+ except (AuthorizationError, AuthenticationError, APIError) as error:
346
+ handle_api_error(error)
347
+
348
+ typer.echo(f"Profile {profile_id} assigned to user {user_id} successfully.")
349
+
350
+
351
+ @users_app.command("unassign")
352
+ def unassign_profile(
353
+ user_id: str = typer.Option(
354
+ ...,
355
+ "--user",
356
+ help="Specify the ID of the user to unassign the profile from.",
357
+ ),
358
+ profile_id: int = typer.Option(
359
+ ...,
360
+ "--profile",
361
+ help="Specify the ID of the profile to unassign.",
362
+ ),
363
+ ) -> None:
364
+ """Revoke a profile assignment from a user.
365
+
366
+ :param user_id: The ID of the user to unassign the profile from.
367
+ :type user_id: str
368
+ :param profile_id: The ID of the profile to unassign.
369
+ :type profile_id: int
370
+ """
371
+ url, port, token = _get_server_and_token()
372
+ request = SpecificRequest(
373
+ method=HTTPMethod.DELETE,
374
+ endpoint=f"admin/users/{user_id}/profiles/{profile_id}",
375
+ )
376
+ try:
377
+ request_api(
378
+ server=ServerParameters(server_url=url, server_port=port),
379
+ token=token,
380
+ specific_request=request,
381
+ )
382
+ except (AuthorizationError, AuthenticationError, APIError) as error:
383
+ handle_api_error(error)
384
+
385
+ typer.echo(f"Profile {profile_id} unassigned from user {user_id} successfully.")
386
+
387
+
388
+ @users_app.command("get")
389
+ def get_user(
390
+ user_id: str = typer.Argument(
391
+ ...,
392
+ help="Specify the ID of the user to retrieve."
393
+ ),
394
+ json_output: bool = typer.Option(
395
+ False,
396
+ "--json",
397
+ help="Output the user information in JSON format."
398
+ ),
399
+ yaml_output: bool = typer.Option(
400
+ False,
401
+ "--yaml",
402
+ help="Output the user information in YAML format."
403
+ ),
404
+ ) -> None:
405
+ """Get a specific user in the TTL-LAMa CLI.
406
+
407
+ :param user_id: The ID of the user to retrieve.
408
+ :type user_id: str
409
+ :param json_output: Whether to output the user information in JSON format.
410
+ :type json_output: bool
411
+ :param yaml_output: Whether to output the user information in YAML format.
412
+ :type yaml_output: bool
413
+ """
414
+ url, port, token = _get_server_and_token()
415
+
416
+ request = SpecificRequest(
417
+ method=HTTPMethod.GET,
418
+ endpoint=f"admin/users/{user_id}",
419
+ )
420
+ user = None
421
+ try:
422
+ result = request_api(
423
+ server=ServerParameters(server_url=url, server_port=port),
424
+ token=token,
425
+ specific_request=request
426
+ )
427
+ if not isinstance(result, dict):
428
+ typer.echo("The API response isn't a user")
429
+ raise typer.Exit(code=1)
430
+ user = result
431
+ if not user:
432
+ typer.echo(f"User with ID {user_id} not found.")
433
+ raise typer.Exit(code=1)
434
+ except (AuthorizationError, AuthenticationError, APIError) as e:
435
+ handle_api_error(e)
436
+
437
+ if user is None:
438
+ typer.echo(f"User with ID {user_id} could not be retrieved.")
439
+ raise typer.Exit(code=1)
440
+
441
+ editable_user = {
442
+ key: value
443
+ for key, value in user.items()
444
+ if key in EDITABLE_USER_FIELDS
445
+ }
446
+
447
+ if json_output:
448
+ typer.echo(json.dumps(editable_user, ensure_ascii=False, indent=4))
449
+ raise typer.Exit()
450
+ if yaml_output:
451
+ typer.echo(json_to_yaml(json.dumps(editable_user, ensure_ascii=False, indent=4)))
452
+ raise typer.Exit()
453
+ typer.echo()
454
+ table = Table(title=f"User {user.get('username', '')} Details", expand=True)
455
+ table.add_column("Field", style="cyan", no_wrap=True, overflow="ellipsis")
456
+ table.add_column("Value", style="green", overflow="ellipsis")
457
+ for key, value in user.items():
458
+ table.add_row(str(key), str(value))
459
+ console = Console()
460
+ console.print(table)