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,300 @@
1
+ """Device management commands for the TTL-LAMa CLI.
2
+
3
+ .. CLI:: ``ttlama admin devices``
4
+ - ``list``: list devices with optional lease and profile filters.
5
+ - ``get``: retrieve a device.
6
+ - ``update``: update device metadata from a JSON or YAML file.
7
+ - ``block``: block a device and revoke its active leases.
8
+ - ``delete``: logically delete a device and revoke its active leases.
9
+
10
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
11
+ .. version:: 1.0.0
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+
17
+ import typer
18
+ from rich.console import Console
19
+ from rich.table import Table
20
+
21
+ from .. import (
22
+ display_structured_output,
23
+ get_server_and_token as _get_server_and_token,
24
+ load_data_file as _load_data_file,
25
+ resource_object,
26
+ resource_rows,
27
+ validate_output_options,
28
+ )
29
+ from ...api_client import request_api
30
+ from ...exc import (
31
+ APIError,
32
+ AuthenticationError,
33
+ AuthorizationError,
34
+ handle_api_error,
35
+ )
36
+ from ...objects import HTTPMethod, ServerParameters, SpecificRequest
37
+ from ...objects.requests import JSONValue
38
+
39
+ devices_app = typer.Typer(
40
+ no_args_is_help=True,
41
+ help="Device management commands for the TTL-LAMa CLI.",
42
+ )
43
+
44
+
45
+ def _load_device_file(file_path: Path) -> dict[str, JSONValue]:
46
+ """Load a device update body from a JSON or YAML file.
47
+
48
+ :param file_path: The path to the device data file.
49
+ :type file_path: Path
50
+ :returns: The parsed device update body.
51
+ :rtype: dict[str, JSONValue]
52
+ """
53
+ return _load_data_file(file_path, "device")
54
+
55
+
56
+ def _create_filters(
57
+ lease: int | None = None,
58
+ profile: int | None = None,
59
+ ) -> dict[str, int] | None:
60
+ """Create combined device relationship filters.
61
+
62
+ :param lease: The lease ID to filter by.
63
+ :type lease: int | None
64
+ :param profile: The profile ID to filter by.
65
+ :type profile: int | None
66
+ :returns: The query parameters, or None when no filters are set.
67
+ :rtype: dict[str, int] | None
68
+ """
69
+ filters = {
70
+ key: value
71
+ for key, value in {"lease": lease, "profile": profile}.items()
72
+ if value is not None
73
+ }
74
+ return filters or None
75
+
76
+
77
+ def _device_update_data(response: object) -> dict[str, object]:
78
+ """Extract the fields accepted by the device update endpoint.
79
+
80
+ :param response: The device object returned by the API.
81
+ :type response: object
82
+ :returns: The name and public key accepted by the update API.
83
+ :rtype: dict[str, object]
84
+ """
85
+ device = resource_object(response, "device")
86
+ name = device.get("name")
87
+ public_key = device.get("public_key")
88
+ if not isinstance(name, str) or not isinstance(public_key, str):
89
+ raise APIError("The API device response has invalid update fields.")
90
+ return {"name": name, "public_key": public_key}
91
+
92
+
93
+ @devices_app.command("ls")
94
+ def list_devices(
95
+ lease: int | None = typer.Option(None, "--lease", help="Filter by lease ID."),
96
+ profile: int | None = typer.Option(None, "--profile", help="Filter by profile ID."),
97
+ json_output: bool = typer.Option(False, "--json", help="Output devices as JSON."),
98
+ yaml_output: bool = typer.Option(False, "--yaml", help="Output devices as YAML."),
99
+ ) -> None:
100
+ """List devices, optionally filtered by lease or profile.
101
+
102
+ :param lease: Filter by lease ID.
103
+ :type lease: int | None
104
+ :param profile: Filter by profile ID.
105
+ :type profile: int | None
106
+ :param json_output: Whether to output devices as JSON.
107
+ :type json_output: bool
108
+ :param yaml_output: Whether to output devices as YAML.
109
+ :type yaml_output: bool
110
+ """
111
+ validate_output_options(json_output, yaml_output)
112
+ server_url, server_port, token = _get_server_and_token()
113
+ try:
114
+ response = request_api(
115
+ server=ServerParameters(server_url=server_url, server_port=server_port),
116
+ token=token,
117
+ specific_request=SpecificRequest(
118
+ method=HTTPMethod.GET,
119
+ endpoint="admin/devices",
120
+ params=_create_filters(lease=lease, profile=profile),
121
+ ),
122
+ )
123
+ devices = resource_rows(response, "device")
124
+ except (AuthorizationError, AuthenticationError, APIError) as error:
125
+ handle_api_error(error)
126
+ return
127
+
128
+ if not devices:
129
+ typer.echo("No devices found.")
130
+ raise typer.Exit(code=1)
131
+ if display_structured_output(
132
+ devices,
133
+ json_output=json_output,
134
+ yaml_output=yaml_output,
135
+ yaml_root="devices",
136
+ ):
137
+ return
138
+
139
+ table = Table(title="Devices", expand=True)
140
+ table.add_column("Device ID", style="cyan", no_wrap=True)
141
+ table.add_column("User ID", overflow="ellipsis")
142
+ table.add_column("Name", style="green", overflow="ellipsis")
143
+ table.add_column("Created", overflow="ellipsis")
144
+ table.add_column("Status", justify="center")
145
+ for device in devices:
146
+ status = "blocked" if device.get("revoked_at") is not None else "active"
147
+ table.add_row(
148
+ str(device.get("id", "")),
149
+ str(device.get("user_id", "")),
150
+ str(device.get("name", "")),
151
+ str(device.get("created_at", "")),
152
+ status,
153
+ )
154
+ Console().print(table)
155
+
156
+
157
+ @devices_app.command("get")
158
+ def get_device(
159
+ device_id: int = typer.Option(..., "--device", help="Device ID to retrieve."),
160
+ json_output: bool = typer.Option(False, "--json", help="Output editable fields as JSON."),
161
+ yaml_output: bool = typer.Option(False, "--yaml", help="Output editable fields as YAML."),
162
+ ) -> None:
163
+ """Retrieve a device and display its details.
164
+
165
+ :param device_id: The ID of the device to retrieve.
166
+ :type device_id: int
167
+ :param json_output: Whether to output editable fields as JSON.
168
+ :type json_output: bool
169
+ :param yaml_output: Whether to output editable fields as YAML.
170
+ :type yaml_output: bool
171
+ """
172
+ validate_output_options(json_output, yaml_output)
173
+ server_url, server_port, token = _get_server_and_token()
174
+ try:
175
+ response = request_api(
176
+ server=ServerParameters(server_url=server_url, server_port=server_port),
177
+ token=token,
178
+ specific_request=SpecificRequest(
179
+ method=HTTPMethod.GET,
180
+ endpoint=f"admin/devices/{device_id}",
181
+ ),
182
+ )
183
+ device = resource_object(response, "device")
184
+ update_data = _device_update_data(device)
185
+ except (AuthorizationError, AuthenticationError, APIError) as error:
186
+ handle_api_error(error)
187
+ return
188
+
189
+ if display_structured_output(
190
+ update_data,
191
+ json_output=json_output,
192
+ yaml_output=yaml_output,
193
+ ):
194
+ return
195
+
196
+ table = Table(title=f"Device {device_id}", expand=True)
197
+ table.add_column("Field", style="cyan", overflow="ellipsis")
198
+ table.add_column("Value", style="green", overflow="ellipsis")
199
+ for key in ("id", "user_id", "name", "public_key", "created_at", "revoked_at"):
200
+ value = device.get(key)
201
+ table.add_row(key, "-" if value is None else str(value))
202
+ Console().print(table)
203
+
204
+
205
+ @devices_app.command("update")
206
+ def update_device(
207
+ device_id: int = typer.Option(..., "--device", help="Device ID to update."),
208
+ file_path: Path = typer.Option(..., "--file", help="JSON or YAML device update file."),
209
+ ) -> None:
210
+ """Update a device from a JSON or YAML file.
211
+
212
+ :param device_id: The ID of the device to update.
213
+ :type device_id: int
214
+ :param file_path: The path to the device update file.
215
+ :type file_path: Path
216
+ """
217
+ device_data = _load_device_file(file_path)
218
+ server_url, server_port, token = _get_server_and_token()
219
+ try:
220
+ request_api(
221
+ server=ServerParameters(server_url=server_url, server_port=server_port),
222
+ token=token,
223
+ specific_request=SpecificRequest(
224
+ method=HTTPMethod.PATCH,
225
+ endpoint=f"admin/devices/{device_id}",
226
+ json_body=device_data,
227
+ ),
228
+ )
229
+ except (AuthorizationError, AuthenticationError, APIError) as error:
230
+ handle_api_error(error)
231
+ return
232
+ typer.echo(f"Device {device_id} updated successfully.")
233
+
234
+
235
+ @devices_app.command("block")
236
+ def block_device(
237
+ device_id: int = typer.Option(..., "--device", help="Device ID to block."),
238
+ ) -> None:
239
+ """Block a device after confirmation and revoke its active leases.
240
+
241
+ :param device_id: The ID of the device to block.
242
+ :type device_id: int
243
+ """
244
+ if not typer.confirm(
245
+ f"Block device {device_id} and revoke its active leases?",
246
+ default=False,
247
+ ):
248
+ typer.echo("Device was not blocked.", err=True)
249
+ raise typer.Exit(code=1)
250
+
251
+ server_url, server_port, token = _get_server_and_token()
252
+ try:
253
+ request_api(
254
+ server=ServerParameters(server_url=server_url, server_port=server_port),
255
+ token=token,
256
+ specific_request=SpecificRequest(
257
+ method=HTTPMethod.POST,
258
+ endpoint=f"admin/devices/{device_id}/block",
259
+ ),
260
+ )
261
+ except (AuthorizationError, AuthenticationError, APIError) as error:
262
+ handle_api_error(error)
263
+ return
264
+ typer.echo(f"Device {device_id} blocked; active leases were revoked.")
265
+
266
+
267
+ @devices_app.command("delete")
268
+ def delete_device(
269
+ device_id: int = typer.Option(..., "--device", help="Device ID to delete."),
270
+ ) -> None:
271
+ """Logically delete a device after confirmation.
272
+
273
+ Deletion revokes the device and its active leases but retains its history.
274
+
275
+ :param device_id: The ID of the device to delete.
276
+ :type device_id: int
277
+ """
278
+ if not typer.confirm(
279
+ f"Delete device {device_id}, revoke its active leases, and retain its history?",
280
+ default=False,
281
+ ):
282
+ typer.echo("Device was not deleted.", err=True)
283
+ raise typer.Exit(code=1)
284
+
285
+ server_url, server_port, token = _get_server_and_token()
286
+ try:
287
+ request_api(
288
+ server=ServerParameters(server_url=server_url, server_port=server_port),
289
+ token=token,
290
+ specific_request=SpecificRequest(
291
+ method=HTTPMethod.DELETE,
292
+ endpoint=f"admin/devices/{device_id}",
293
+ ),
294
+ )
295
+ except (AuthorizationError, AuthenticationError, APIError) as error:
296
+ handle_api_error(error)
297
+ return
298
+ typer.echo(
299
+ f"Device {device_id} deleted (revoked); active leases were revoked and history retained."
300
+ )
@@ -0,0 +1,244 @@
1
+ """Lease management commands for the TTL-LAMa CLI.
2
+
3
+ .. CLI:: ``ttlama admin leases``
4
+ - ``list``: list leases with optional user, device, profile, and status filters.
5
+ - ``get``: retrieve a lease.
6
+ - ``revoke``: revoke a lease while retaining its history.
7
+
8
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
9
+ .. version:: 1.0.0
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from enum import Enum
14
+
15
+ import typer
16
+ from rich.console import Console
17
+ from rich.table import Table
18
+
19
+ from .. import (
20
+ display_structured_output,
21
+ get_server_and_token as _get_server_and_token,
22
+ resource_object,
23
+ resource_rows,
24
+ validate_output_options,
25
+ )
26
+ from ...api_client import request_api
27
+ from ...exc import (
28
+ APIError,
29
+ AuthenticationError,
30
+ AuthorizationError,
31
+ handle_api_error,
32
+ )
33
+ from ...objects import HTTPMethod, ServerParameters, SpecificRequest
34
+
35
+ leases_app = typer.Typer(
36
+ no_args_is_help=True,
37
+ help="Lease management commands for the TTL-LAMa CLI.",
38
+ )
39
+
40
+
41
+ class LeaseStatus(str, Enum):
42
+ """Statuses accepted by the lease list endpoint."""
43
+
44
+ ACTIVE = "active"
45
+ EXPIRED = "expired"
46
+ REVOKED = "revoked"
47
+
48
+
49
+ def _create_filters(
50
+ user: str | None = None,
51
+ device: int | None = None,
52
+ profile: int | None = None,
53
+ status: LeaseStatus | None = None,
54
+ ) -> dict[str, str | int] | None:
55
+ """Create combined lease filters for the API request.
56
+
57
+ :param user: Filter by user UUID.
58
+ :type user: str | None
59
+ :param device: Filter by device ID.
60
+ :type device: int | None
61
+ :param profile: Filter by profile ID.
62
+ :type profile: int | None
63
+ :param status: Filter by lease lifecycle status.
64
+ :type status: LeaseStatus | None
65
+ :returns: The query parameters, or None when no filters are set.
66
+ :rtype: dict[str, str | int] | None
67
+ """
68
+ filters: dict[str, str | int] = {
69
+ key: value
70
+ for key, value in {
71
+ "user": user,
72
+ "device": device,
73
+ "profile": profile,
74
+ "status": status.value if status is not None else None,
75
+ }.items()
76
+ if value is not None
77
+ }
78
+ return filters or None
79
+
80
+
81
+ @leases_app.command(
82
+ "ls",
83
+ help="List leases, optionally filtered by user, device, profile, or status.",
84
+ )
85
+ def list_leases( # pylint: disable=R0913, R0917
86
+ user: str | None = typer.Option(None, "--user", help="Filter by user UUID."),
87
+ device: int | None = typer.Option(None, "--device", help="Filter by device ID."),
88
+ profile: int | None = typer.Option(None, "--profile", help="Filter by profile ID."),
89
+ status: LeaseStatus | None = typer.Option(
90
+ None,
91
+ "--status",
92
+ help="Filter by status: active, expired, or revoked.",
93
+ ),
94
+ json_output: bool = typer.Option(False, "--json", help="Output leases as JSON."),
95
+ yaml_output: bool = typer.Option(False, "--yaml", help="Output leases as YAML."),
96
+ ) -> None:
97
+ """List leases, optionally filtered by user, device, profile, or status.
98
+
99
+ :param user: Filter by user UUID.
100
+ :type user: str | None
101
+ :param device: Filter by device ID.
102
+ :type device: int | None
103
+ :param profile: Filter by profile ID.
104
+ :type profile: int | None
105
+ :param status: Filter by lease lifecycle status.
106
+ :type status: LeaseStatus | None
107
+ :param json_output: Whether to output leases as JSON.
108
+ :type json_output: bool
109
+ :param yaml_output: Whether to output leases as YAML.
110
+ :type yaml_output: bool
111
+ """
112
+ validate_output_options(json_output, yaml_output)
113
+ server_url, server_port, token = _get_server_and_token()
114
+ try:
115
+ response = request_api(
116
+ server=ServerParameters(server_url=server_url, server_port=server_port),
117
+ token=token,
118
+ specific_request=SpecificRequest(
119
+ method=HTTPMethod.GET,
120
+ endpoint="admin/leases",
121
+ params=_create_filters(
122
+ user=user,
123
+ device=device,
124
+ profile=profile,
125
+ status=status,
126
+ ),
127
+ ),
128
+ )
129
+ leases = resource_rows(response, "lease")
130
+ except (AuthorizationError, AuthenticationError, APIError) as error:
131
+ handle_api_error(error)
132
+ return
133
+
134
+ if not leases:
135
+ typer.echo("No leases found.")
136
+ raise typer.Exit(code=1)
137
+ if display_structured_output(
138
+ leases,
139
+ json_output=json_output,
140
+ yaml_output=yaml_output,
141
+ yaml_root="leases",
142
+ ):
143
+ return
144
+
145
+ table = Table(title="Leases", expand=True)
146
+ table.add_column("Lease ID", style="cyan", no_wrap=True)
147
+ table.add_column("User ID", overflow="ellipsis")
148
+ table.add_column("Device ID", justify="right")
149
+ table.add_column("Profile ID", justify="right")
150
+ table.add_column("Created", overflow="ellipsis")
151
+ table.add_column("Ends", overflow="ellipsis")
152
+ table.add_column("Status", justify="center")
153
+ for lease in leases:
154
+ table.add_row(
155
+ str(lease.get("id", "")),
156
+ str(lease.get("user_id", "")),
157
+ str(lease.get("device_id", "")),
158
+ str(lease.get("profile_id", "")),
159
+ str(lease.get("created_at", "")),
160
+ str(lease.get("ended_at", "")),
161
+ str(lease.get("status", "")),
162
+ )
163
+ Console().print(table)
164
+
165
+
166
+ @leases_app.command("get", help="Retrieve a lease and display all of its fields.")
167
+ def get_lease(
168
+ lease_id: int = typer.Option(..., "--lease", help="Lease ID to retrieve."),
169
+ json_output: bool = typer.Option(False, "--json", help="Output the lease as JSON."),
170
+ yaml_output: bool = typer.Option(False, "--yaml", help="Output the lease as YAML."),
171
+ ) -> None:
172
+ """Retrieve a lease and display all of its fields.
173
+
174
+ :param lease_id: The ID of the lease to retrieve.
175
+ :type lease_id: int
176
+ :param json_output: Whether to output the lease as JSON.
177
+ :type json_output: bool
178
+ :param yaml_output: Whether to output the lease as YAML.
179
+ :type yaml_output: bool
180
+ """
181
+ validate_output_options(json_output, yaml_output)
182
+ server_url, server_port, token = _get_server_and_token()
183
+ try:
184
+ response = request_api(
185
+ server=ServerParameters(server_url=server_url, server_port=server_port),
186
+ token=token,
187
+ specific_request=SpecificRequest(
188
+ method=HTTPMethod.GET,
189
+ endpoint=f"admin/leases/{lease_id}",
190
+ ),
191
+ )
192
+ lease = resource_object(response, "lease")
193
+ except (AuthorizationError, AuthenticationError, APIError) as error:
194
+ handle_api_error(error)
195
+ return
196
+
197
+ if display_structured_output(
198
+ lease,
199
+ json_output=json_output,
200
+ yaml_output=yaml_output,
201
+ ):
202
+ return
203
+
204
+ table = Table(title=f"Lease {lease_id}", expand=True)
205
+ table.add_column("Field", style="cyan", overflow="ellipsis")
206
+ table.add_column("Value", style="green", overflow="ellipsis")
207
+ for key, value in lease.items():
208
+ table.add_row(key, "-" if value is None else str(value))
209
+ Console().print(table)
210
+
211
+
212
+ @leases_app.command(
213
+ "revoke",
214
+ help="Revoke a lease after confirmation while retaining its history.",
215
+ )
216
+ def revoke_lease(
217
+ lease_id: int = typer.Option(..., "--lease", help="Lease ID to revoke."),
218
+ ) -> None:
219
+ """Revoke a lease after confirmation while retaining its history.
220
+
221
+ :param lease_id: The ID of the lease to revoke.
222
+ :type lease_id: int
223
+ """
224
+ if not typer.confirm(
225
+ f"Revoke lease {lease_id} and retain its history?",
226
+ default=False,
227
+ ):
228
+ typer.echo("Lease was not revoked.", err=True)
229
+ raise typer.Exit(code=1)
230
+
231
+ server_url, server_port, token = _get_server_and_token()
232
+ try:
233
+ request_api(
234
+ server=ServerParameters(server_url=server_url, server_port=server_port),
235
+ token=token,
236
+ specific_request=SpecificRequest(
237
+ method=HTTPMethod.POST,
238
+ endpoint=f"admin/leases/{lease_id}/revoke",
239
+ ),
240
+ )
241
+ except (AuthorizationError, AuthenticationError, APIError) as error:
242
+ handle_api_error(error)
243
+ return
244
+ typer.echo(f"Lease {lease_id} revoked; history retained.")