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,328 @@
1
+ """Profile management commands for the TTL-LAMa CLI.
2
+
3
+ .. CLI:: ``ttlama admin profiles``
4
+ - ``list``: list profiles with optional relationship filters.
5
+ - ``get``: retrieve a profile.
6
+ - ``create``: create a profile from a JSON or YAML file.
7
+ - ``update``: update a profile from a JSON or YAML file.
8
+ - ``delete``: revoke a profile.
9
+
10
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
11
+ .. version:: 1.0.0
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from pathlib import Path
17
+ from typing import cast
18
+
19
+ import typer
20
+ from rich.console import Console
21
+ from rich.table import Table
22
+
23
+ from .. import (
24
+ display_profiles as _display_profiles,
25
+ get_server_and_token as _get_server_and_token,
26
+ load_data_file as _load_data_file,
27
+ profile_rows as _profile_rows,
28
+ validate_output_options,
29
+ )
30
+ from ...api_client import request_api
31
+ from ...exc import (
32
+ APIError,
33
+ AuthenticationError,
34
+ AuthorizationError,
35
+ handle_api_error,
36
+ )
37
+ from ...objects import HTTPMethod, ServerParameters, SpecificRequest
38
+ from ...objects.requests import JSONValue
39
+ from ...utils import json_to_yaml
40
+
41
+ profiles_app = typer.Typer(
42
+ no_args_is_help=True,
43
+ help="Profile management commands for the TTL-LAMa CLI.",
44
+ )
45
+
46
+
47
+ def _load_profile_file(file_path: Path) -> dict[str, JSONValue]:
48
+ """Load a profile request body from a JSON or YAML file.
49
+
50
+ :param file_path: The path to the JSON or YAML file containing the profile data.
51
+ :type file_path: Path
52
+ :returns: The loaded profile data as a dictionary.
53
+ :rtype: dict[str, JSONValue]
54
+ """
55
+ return _load_data_file(file_path, "profile")
56
+
57
+
58
+ def _create_filters(
59
+ user: str | None = None,
60
+ device: int | None = None,
61
+ lease: int | None = None,
62
+ ) -> dict[str, str | int] | None:
63
+ """Create combined profile relationship filters.
64
+
65
+ :param user: Filter by assigned user UUID.
66
+ :type user: str | None
67
+ :param device: Filter by device ID.
68
+ :type device: int | None
69
+ :param lease: Filter by lease ID.
70
+ :type lease: int | None
71
+ :returns: A dictionary of filters or None if no filters are set.
72
+ :rtype: dict[str, str | int] | None
73
+ """
74
+ filters = {
75
+ key: value
76
+ for key, value in {"user": user, "device": device, "lease": lease}.items()
77
+ if value is not None
78
+ }
79
+ return filters or None
80
+
81
+
82
+ def _profile_update_data(response: object) -> dict[str, JSONValue]:
83
+ """Flatten a profile response into fields accepted by the update API.
84
+
85
+ :param response: The profile response object from the API.
86
+ :type response: object
87
+ :returns: A dictionary of fields suitable for the update API.
88
+ :rtype: dict[str, JSONValue]
89
+ """
90
+ if not isinstance(response, dict):
91
+ raise APIError("The API response isn't a profile.")
92
+ profile = cast(dict[str, object], response)
93
+ name = profile.get("name")
94
+ if not isinstance(name, str):
95
+ raise APIError("The API profile response has no valid name.")
96
+
97
+ update_data: dict[str, JSONValue] = {"name": name}
98
+ raw_policy = profile.get("policy")
99
+ if raw_policy is None:
100
+ return update_data
101
+ if not isinstance(raw_policy, dict):
102
+ raise APIError("The API profile policy is invalid.")
103
+
104
+ policy = cast(dict[str, object], raw_policy)
105
+ default_duration = policy.get("default_duration")
106
+ maximum_duration = policy.get("maximum_duration")
107
+ networks = policy.get("networks")
108
+ if (
109
+ not isinstance(default_duration, str)
110
+ or not isinstance(maximum_duration, str)
111
+ or not isinstance(networks, list)
112
+ or any(
113
+ not isinstance(network, str)
114
+ for network in cast(list[object], networks)
115
+ )
116
+ ):
117
+ raise APIError("The API profile policy is incomplete or invalid.")
118
+
119
+ update_data.update(
120
+ default_duration=default_duration,
121
+ maximum_duration=maximum_duration,
122
+ networks=cast(JSONValue, cast(list[str], networks)),
123
+ )
124
+ return update_data
125
+
126
+
127
+ @profiles_app.command("ls")
128
+ def list_profiles(
129
+ user: str | None = typer.Option(None, "--user", help="Filter by assigned user UUID."),
130
+ device: int | None = typer.Option(None, "--device", help="Filter by device ID."),
131
+ lease: int | None = typer.Option(None, "--lease", help="Filter by lease ID."),
132
+ json_output: bool = typer.Option(False, "--json", help="Output profiles as JSON."),
133
+ yaml_output: bool = typer.Option(False, "--yaml", help="Output profiles as YAML."),
134
+ ) -> None:
135
+ """List profiles, optionally filtered by user, device, or lease.
136
+
137
+ :param user: Filter by assigned user UUID.
138
+ :type user: str | None
139
+ :param device: Filter by device ID.
140
+ :type device: int | None
141
+ :param lease: Filter by lease ID.
142
+ :type lease: int | None
143
+ :param json_output: Whether to output the profiles as JSON.
144
+ :type json_output: bool
145
+ :param yaml_output: Whether to output the profiles as YAML.
146
+ :type yaml_output: bool
147
+ """
148
+ validate_output_options(json_output, yaml_output)
149
+
150
+ server_url, server_port, token = _get_server_and_token()
151
+ try:
152
+ response = request_api(
153
+ server=ServerParameters(server_url=server_url, server_port=server_port),
154
+ token=token,
155
+ specific_request=SpecificRequest(
156
+ method=HTTPMethod.GET,
157
+ endpoint="admin/profiles",
158
+ params=_create_filters(user=user, device=device, lease=lease),
159
+ ),
160
+ )
161
+ profiles = _profile_rows(response)
162
+ except (AuthorizationError, AuthenticationError, APIError) as error:
163
+ handle_api_error(error)
164
+ return
165
+
166
+ if not profiles:
167
+ typer.echo("No profiles found.")
168
+ raise typer.Exit(code=1)
169
+ _display_profiles(profiles, json_output=json_output, yaml_output=yaml_output)
170
+
171
+
172
+ @profiles_app.command("get")
173
+ def get_profile(
174
+ profile_id: int = typer.Option(..., "--profile", help="Profile ID to retrieve."),
175
+ json_output: bool = typer.Option(False, "--json", help="Output the profile as JSON."),
176
+ yaml_output: bool = typer.Option(False, "--yaml", help="Output the profile as YAML."),
177
+ ) -> None:
178
+ """Retrieve a profile and display its updateable fields.
179
+
180
+ :param profile_id: The ID of the profile to retrieve.
181
+ :type profile_id: int
182
+ :param json_output: Whether to output the profile as JSON.
183
+ :type json_output: bool
184
+ :param yaml_output: Whether to output the profile as YAML.
185
+ :type yaml_output: bool
186
+ """
187
+ validate_output_options(json_output, yaml_output)
188
+
189
+ server_url, server_port, token = _get_server_and_token()
190
+ try:
191
+ response = request_api(
192
+ server=ServerParameters(server_url=server_url, server_port=server_port),
193
+ token=token,
194
+ specific_request=SpecificRequest(
195
+ method=HTTPMethod.GET,
196
+ endpoint=f"admin/profiles/{profile_id}",
197
+ ),
198
+ )
199
+ update_data = _profile_update_data(response)
200
+ except (AuthorizationError, AuthenticationError, APIError) as error:
201
+ handle_api_error(error)
202
+ return
203
+
204
+ if json_output:
205
+ typer.echo(json.dumps(update_data, ensure_ascii=False, indent=4))
206
+ return
207
+ if yaml_output:
208
+ typer.echo(json_to_yaml(json.dumps(update_data, ensure_ascii=False, indent=4)))
209
+ return
210
+
211
+ table = Table(title=f"Profile {profile_id}", expand=True)
212
+ table.add_column("Field", style="cyan", overflow="ellipsis")
213
+ table.add_column("Value", style="green", overflow="ellipsis")
214
+ for key, value in update_data.items():
215
+ table.add_row(
216
+ key,
217
+ json.dumps(value, ensure_ascii=False)
218
+ if isinstance(value, list)
219
+ else str(value),
220
+ )
221
+ Console().print(table)
222
+
223
+
224
+ @profiles_app.command("create")
225
+ def create_profile(
226
+ file_path: Path = typer.Option(..., "--file", help="JSON or YAML profile data file."),
227
+ ) -> None:
228
+ """Create a profile from a JSON or YAML file.
229
+
230
+ :param file_path: Path to the JSON or YAML profile data file.
231
+ :type file_path: Path
232
+ """
233
+ profile_data = _load_profile_file(file_path)
234
+ server_url, server_port, token = _get_server_and_token()
235
+ try:
236
+ request_api(
237
+ server=ServerParameters(server_url=server_url, server_port=server_port),
238
+ token=token,
239
+ specific_request=SpecificRequest(
240
+ method=HTTPMethod.POST,
241
+ endpoint="admin/profiles",
242
+ json_body=profile_data,
243
+ ),
244
+ )
245
+ except (AuthorizationError, AuthenticationError, APIError) as error:
246
+ handle_api_error(error)
247
+ return
248
+ typer.echo("Profile created successfully.")
249
+
250
+
251
+ @profiles_app.command("update")
252
+ def update_profile(
253
+ profile_id: int = typer.Option(..., "--profile", help="Profile ID to update."),
254
+ file_path: Path = typer.Option(..., "--file", help="JSON or YAML fields to update."),
255
+ ) -> None:
256
+ """Update a profile from a JSON or YAML file.
257
+
258
+ :param profile_id: The ID of the profile to update.
259
+ :type profile_id: int
260
+ :param file_path: Path to the JSON or YAML fields to update.
261
+ :type file_path: Path
262
+ """
263
+ profile_data = _load_profile_file(file_path)
264
+ server_url, server_port, token = _get_server_and_token()
265
+ try:
266
+ request_api(
267
+ server=ServerParameters(server_url=server_url, server_port=server_port),
268
+ token=token,
269
+ specific_request=SpecificRequest(
270
+ method=HTTPMethod.PATCH,
271
+ endpoint=f"admin/profiles/{profile_id}",
272
+ json_body=profile_data,
273
+ ),
274
+ )
275
+ except (AuthorizationError, AuthenticationError, APIError) as error:
276
+ handle_api_error(error)
277
+ return
278
+ typer.echo(f"Profile {profile_id} updated successfully.")
279
+
280
+
281
+ @profiles_app.command("delete")
282
+ def delete_profile(
283
+ profile_id: int = typer.Option(..., "--profile", help="Profile ID to revoke."),
284
+ ) -> None:
285
+ """Revoke a profile and its dependent access.
286
+
287
+ :param profile_id: The ID of the profile to revoke.
288
+ :type profile_id: int
289
+ """
290
+ server_url, server_port, token = _get_server_and_token()
291
+ try:
292
+ profile = request_api(
293
+ server=ServerParameters(server_url=server_url, server_port=server_port),
294
+ token=token,
295
+ specific_request=SpecificRequest(
296
+ method=HTTPMethod.GET,
297
+ endpoint=f"admin/profiles/{profile_id}",
298
+ ),
299
+ )
300
+ if not isinstance(profile, dict):
301
+ raise APIError("The API response isn't a profile.")
302
+ profile_name = profile.get("name")
303
+ if not isinstance(profile_name, str):
304
+ raise APIError("The API profile response has no valid name.")
305
+ except (AuthorizationError, AuthenticationError, APIError) as error:
306
+ handle_api_error(error)
307
+ return
308
+
309
+ confirmation = typer.prompt(
310
+ f"Type the full profile name to confirm revocation of '{profile_name}'"
311
+ )
312
+ if confirmation != profile_name:
313
+ typer.echo("Profile name did not match; profile was not revoked.", err=True)
314
+ raise typer.Exit(code=1)
315
+
316
+ try:
317
+ request_api(
318
+ server=ServerParameters(server_url=server_url, server_port=server_port),
319
+ token=token,
320
+ specific_request=SpecificRequest(
321
+ method=HTTPMethod.DELETE,
322
+ endpoint=f"admin/profiles/{profile_id}",
323
+ ),
324
+ )
325
+ except (AuthorizationError, AuthenticationError, APIError) as error:
326
+ handle_api_error(error)
327
+ return
328
+ typer.echo(f"Profile {profile_id} revoked successfully.")