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
ttlama_cli/__init__.py ADDED
File without changes
ttlama_cli/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Entrypoint for TTL-LAMa CLI."""
2
+
3
+ from ttlama_cli import cli
4
+
5
+ if __name__ == "__main__":
6
+ cli.main()
@@ -0,0 +1,221 @@
1
+ """API client for TTL-LAMa CLI.
2
+
3
+ This module provides functions to interact with the TTL-LAMa server API.
4
+
5
+ .. functions::
6
+ - `authenticate_internal`: Authenticate with the TTL-LAMa server and return an authentication
7
+ token.
8
+
9
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
10
+ .. version:: 1.0.0
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from typing import TypeAlias, cast
15
+
16
+ from requests import Session, request
17
+ from requests.exceptions import RequestException
18
+
19
+ from .exc import APIError, AuthenticationError, AuthorizationError
20
+ from .objects import ServerParameters, SpecificRequest
21
+
22
+ JSONValue: TypeAlias = (
23
+ None
24
+ | bool
25
+ | int
26
+ | float
27
+ | str
28
+ | list["JSONValue"]
29
+ | dict[str, "JSONValue"]
30
+ )
31
+
32
+
33
+ def _oidc_public_post(
34
+ server: ServerParameters,
35
+ endpoint: str,
36
+ payload: dict[str, JSONValue],
37
+ ) -> dict[str, object]:
38
+ """Send an unauthenticated OIDC CLI request and validate its JSON response."""
39
+ url = f"{server.server_url}:{server.server_port}/api/v1/{endpoint}"
40
+ try:
41
+ response = request("POST", url, json=payload, timeout=15)
42
+ except RequestException as error:
43
+ raise APIError("Unable to reach the TTL-LAMa API.") from error
44
+
45
+ if response.status_code == 401:
46
+ raise AuthenticationError("The OIDC login ticket or device code is invalid.")
47
+ if response.status_code == 403:
48
+ raise AuthorizationError("The OIDC login request was rejected.")
49
+ try:
50
+ response.raise_for_status()
51
+ except RequestException as error:
52
+ raise APIError(
53
+ f"TTL-LAMa API responded with HTTP status {response.status_code}."
54
+ ) from error
55
+
56
+ try:
57
+ response_data = response.json()
58
+ except ValueError as error:
59
+ raise APIError("OIDC API response is invalid.") from error
60
+ if not isinstance(response_data, dict):
61
+ raise APIError("OIDC API response is invalid.")
62
+ return cast(dict[str, object], response_data)
63
+
64
+
65
+ def _access_token_from_response(response: dict[str, object]) -> str:
66
+ """Extract a non-empty Bearer token from an OIDC API response."""
67
+ token = response.get("access_token")
68
+ if not isinstance(token, str) or not token:
69
+ raise APIError("OIDC API response does not contain a valid access token.")
70
+ return token
71
+
72
+
73
+ def exchange_oidc_cli_ticket(server: ServerParameters, ticket: str) -> str:
74
+ """Exchange a loopback login ticket for a TTL-LAMa Bearer token."""
75
+ response = _oidc_public_post(
76
+ server,
77
+ "auth/oidc/exchange",
78
+ {"ticket": ticket},
79
+ )
80
+ return _access_token_from_response(response)
81
+
82
+
83
+ def begin_oidc_device_authorization(server: ServerParameters) -> dict[str, object]:
84
+ """Start OIDC Device Authorization on the TTL-LAMa server."""
85
+ return _oidc_public_post(server, "auth/oidc/device", {})
86
+
87
+
88
+ def poll_oidc_device_authorization(
89
+ server: ServerParameters,
90
+ device_code: str,
91
+ ) -> dict[str, object]:
92
+ """Poll OIDC Device Authorization through the TTL-LAMa server."""
93
+ response = _oidc_public_post(
94
+ server,
95
+ "auth/oidc/device/poll",
96
+ {"device_code": device_code},
97
+ )
98
+ if response.get("status") == "complete":
99
+ response["access_token"] = _access_token_from_response(response)
100
+ return response
101
+
102
+
103
+ def authenticate_internal(server_url: str, server_port: int, username: str, password: str) -> str:
104
+ """Authenticate with the TTL-LAMa server and return an authentication token.
105
+
106
+ :param server_url: URL of the TTL-LAMa server.
107
+ :type server_url: str
108
+ :param server_port: Port of the TTL-LAMa server.
109
+ :type server_port: int
110
+ :param username: Username for authentication.
111
+ :type username: str
112
+ :param password: Password for authentication.
113
+ :type password: str
114
+ :return: Authentication token.
115
+ :rtype: str
116
+ :raises APIError: If there is an API error.
117
+ :raises AuthenticationError: If authentication fails.
118
+ :raises AuthorizationError: If the user does not have admin privileges.
119
+ """
120
+ session = Session()
121
+
122
+ try:
123
+ csrf_response = session.get(
124
+ f"{server_url}:{server_port}/api/v1/csrf",
125
+ timeout=5,
126
+ )
127
+ csrf_response.raise_for_status()
128
+ csrf_data = csrf_response.json()
129
+ if not isinstance(csrf_data, dict):
130
+ raise APIError("La réponse CSRF de l’API est invalide.")
131
+
132
+ csrf_payload = cast(dict[str, object], csrf_data)
133
+ csrf = csrf_payload.get("csrf_token")
134
+ if not isinstance(csrf, str) or not csrf:
135
+ raise APIError("La réponse CSRF de l’API ne contient pas de jeton.")
136
+
137
+ response = session.post(
138
+ f"{server_url}:{server_port}/api/v1/auth",
139
+ json={"username": username, "password": password},
140
+ headers={"X-CSRFToken": csrf},
141
+ timeout=5,
142
+ )
143
+ except RequestException as error:
144
+ raise APIError("Impossible de joindre l’API TTL-LAMa.") from error
145
+
146
+ if response.status_code == 401:
147
+ raise AuthenticationError("Nom d’utilisateur ou mot de passe incorrect.")
148
+ if response.status_code == 501:
149
+ raise APIError("L’authentification interne n’est pas disponible sur ce serveur.")
150
+
151
+ try:
152
+ response.raise_for_status()
153
+ except RequestException as error:
154
+ raise APIError(
155
+ f"L’API TTL-LAMa a répondu avec le statut HTTP {response.status_code}."
156
+ ) from error
157
+
158
+ try:
159
+ response_data = response.json()
160
+ except ValueError as error:
161
+ raise APIError("La réponse d’authentification de l’API est invalide.") from error
162
+
163
+ if not isinstance(response_data, dict):
164
+ raise APIError("La réponse d’authentification de l’API est invalide.")
165
+
166
+ payload = cast(dict[str, object], response_data)
167
+ token = payload.get("access_token")
168
+
169
+ if not isinstance(token, str) or not token:
170
+ raise APIError("La réponse d’authentification ne contient pas de jeton valide.")
171
+ return token
172
+
173
+ def request_api(
174
+ server: ServerParameters,
175
+ token: str,
176
+ specific_request: SpecificRequest,
177
+ ) -> dict[str, object] | list[dict[str, object]] | None:
178
+ """Request the API.
179
+
180
+ :param server: Server parameters.
181
+ :type server: ServerParameters
182
+ :param token: Authentication token.
183
+ :type token: str
184
+ :param specific_request: Specific HTTP request details.
185
+ :type specific_request: SpecificRequest
186
+ :return: An object, a list of objects, or None if the API returned no data.
187
+ :rtype: dict[str, object] | list[dict[str, object]] | None
188
+ :raises APIError: If there is an API error.
189
+ """
190
+ url = f"{server.server_url}:{server.server_port}/api/v1/{specific_request.endpoint}"
191
+ try:
192
+ response = request(
193
+ specific_request.method,
194
+ url,
195
+ headers={"Authorization": f"Bearer {token}"},
196
+ params=specific_request.params,
197
+ json=specific_request.json_body,
198
+ timeout=specific_request.timeout,
199
+ )
200
+ except RequestException as error:
201
+ raise APIError("Impossible de joindre l’API TTL-LAMa.") from error
202
+
203
+ if response.status_code == 401:
204
+ raise AuthenticationError("Bearer token is invalid.")
205
+ if response.status_code == 403:
206
+ raise AuthorizationError("You haven't admin privileges.")
207
+
208
+ try:
209
+ response.raise_for_status()
210
+ except RequestException as error:
211
+ raise APIError(
212
+ f"TTL-LAMa API responded with HTTP status {response.status_code}."
213
+ ) from error
214
+
215
+ if response.status_code == 204:
216
+ return None
217
+
218
+ try:
219
+ return response.json()
220
+ except ValueError as error:
221
+ raise APIError("API response is invalid.") from error
ttlama_cli/cli.py ADDED
@@ -0,0 +1,71 @@
1
+ """CLI to administrate TTL-LAMa.
2
+
3
+ .. functions::
4
+ - `main`: Entrypoint for the TTL-LAMa CLI.
5
+
6
+ .. cli::
7
+ - `callback`: Callback for the TTL-LAMa CLI.
8
+
9
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
10
+ .. version:: 0.1.0
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from importlib.metadata import version, metadata
16
+
17
+ import typer
18
+
19
+ from .commands.auth import app as auth_app
20
+ from .commands.config import app as config_app, global_config_app
21
+ from .commands.admin import app as admin_app
22
+ from .commands.user import app as user_app
23
+ from .commands.backend import app as backend_app
24
+
25
+ app = typer.Typer(
26
+ no_args_is_help=True,
27
+ help="CLI to administrate TTL-LAMa.",
28
+ )
29
+ app.add_typer(auth_app, name="auth")
30
+ app.add_typer(config_app, name="config")
31
+ app.add_typer(global_config_app, name="global-config")
32
+ app.add_typer(admin_app, name="admin")
33
+ app.add_typer(user_app, name="user")
34
+ app.add_typer(backend_app, name="backend")
35
+
36
+ def show_version(value: bool) -> bool:
37
+ """Show the version of the TTL-LAMa CLI if the flag is set."""
38
+ if value:
39
+ name_mail = metadata('ttlama_cli')['Author-email'].split('|')
40
+ name = name_mail[0].replace("\"", "").strip()
41
+ mail = name_mail[1]
42
+ version_str = version('ttlama_cli')
43
+ url = metadata('ttlama_cli')['Project-URL']
44
+ print(f"TTL-LAMa-CLI {' ' * 20}{version_str}")
45
+ print(f"Developped and maintained by {' ' * 20}{name}")
46
+ print(f"Read more in {' ' * 20}{url}")
47
+ print(f"Contact for more at {' ' * 20}{mail}")
48
+ raise typer.Exit()
49
+ return value
50
+
51
+ def main() -> None:
52
+ """Entrypoint for the TTL-LAMa CLI.
53
+
54
+ .. note:: This is the main entrypoint for the TTL-LAMa CLI. Use the `ttlama` command
55
+ to invoke it.
56
+ """
57
+ app()
58
+
59
+ @app.callback()
60
+ def callback(
61
+ version_flag: bool = typer.Option( # pylint: disable=W0613
62
+ False,
63
+ "--version",
64
+ "-v",
65
+ is_eager=True,
66
+ callback=show_version,
67
+ help="Show the version of the TTL-LAMa CLI.",
68
+ )
69
+ ) -> None:
70
+ """Callback for the TTL-LAMa CLI."""
71
+ pass # pylint: disable=W0107
@@ -0,0 +1,256 @@
1
+ """Shared helpers for CLI command groups."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import cast
8
+
9
+ import typer
10
+ from rich.console import Console
11
+ from rich.table import Table
12
+ from yaml import YAMLError
13
+
14
+ from ..api_client import request_api
15
+ from ..config_store import load_server_config
16
+ from ..exc import APIError, TokenStorageError
17
+ from ..objects import HTTPMethod, ServerParameters, SpecificRequest
18
+ from ..objects.requests import JSONValue
19
+ from ..token_store import get_access_token
20
+ from ..utils import json_to_yaml, yaml_to_json
21
+
22
+
23
+ def get_server_and_token() -> tuple[str, int, str]:
24
+ """Retrieve the configured server and its access token."""
25
+ try:
26
+ server_url, server_port = load_server_config()
27
+ token = get_access_token(server_url, server_port)
28
+ if not token:
29
+ raise TokenStorageError("No access token is stored for this server.")
30
+ except (FileNotFoundError, ValueError, TokenStorageError) as error:
31
+ typer.echo(f"Error retrieving server credentials: {error}", err=True)
32
+ raise typer.Exit(code=1) from error
33
+ return server_url, server_port, token
34
+
35
+
36
+ def validate_output_options(json_output: bool, yaml_output: bool) -> None:
37
+ """Reject simultaneous JSON and YAML output options."""
38
+ if json_output and yaml_output:
39
+ typer.echo("Choose only one output option: --json or --yaml.", err=True)
40
+ raise typer.Exit(code=1)
41
+
42
+
43
+ def display_structured_output(
44
+ data: dict[str, object] | list[dict[str, object]] | None,
45
+ *,
46
+ json_output: bool,
47
+ yaml_output: bool,
48
+ yaml_root: str | None = None,
49
+ ) -> bool:
50
+ """Display JSON or YAML data and report whether a format was selected."""
51
+ if json_output:
52
+ typer.echo(json.dumps(data, ensure_ascii=False, indent=4))
53
+ return True
54
+ if yaml_output:
55
+ yaml_data: object = {yaml_root: data} if yaml_root is not None else data
56
+ typer.echo(json_to_yaml(json.dumps(yaml_data, ensure_ascii=False)))
57
+ return True
58
+ return False
59
+
60
+
61
+ def request_configured_api(
62
+ specific_request: SpecificRequest,
63
+ ) -> dict[str, object] | list[dict[str, object]] | None:
64
+ """Send a request with the configured server and stored access token.
65
+
66
+ :param specific_request: The specific API request to send.
67
+ :type specific_request: SpecificRequest
68
+ :returns: The API response as a dictionary or a list of dictionaries.
69
+ :rtype: dict[str, object] | list[dict[str, object]] | None
70
+ """
71
+ server_url, server_port, token = get_server_and_token()
72
+ return request_api(
73
+ server=ServerParameters(server_url=server_url, server_port=server_port),
74
+ token=token,
75
+ specific_request=specific_request,
76
+ )
77
+
78
+
79
+ def load_data_file(file_path: Path, resource_name: str) -> dict[str, JSONValue]:
80
+ """Load a JSON or YAML object from a file or standard input.
81
+
82
+ :param file_path: The request file path, or ``-`` to read standard input.
83
+ :type file_path: Path
84
+ :param resource_name: The name of the resource being loaded (for error messages).
85
+ :type resource_name: str
86
+ :returns: The parsed JSON or YAML object as a dictionary.
87
+ :rtype: dict[str, JSONValue]
88
+ """
89
+ source = "standard input" if file_path == Path("-") else f"'{file_path}'"
90
+ try:
91
+ contents = (
92
+ sys.stdin.read()
93
+ if file_path == Path("-")
94
+ else file_path.read_text(encoding="utf-8")
95
+ )
96
+ except (OSError, UnicodeError) as error:
97
+ typer.echo(
98
+ f"Error reading {resource_name} data from {source}: {error}",
99
+ err=True,
100
+ )
101
+ raise typer.Exit(code=1) from error
102
+
103
+ try:
104
+ data = json.loads(yaml_to_json(contents))
105
+ except (TypeError, ValueError, YAMLError) as error:
106
+ typer.echo(
107
+ f"Error parsing {resource_name} data file: expected valid JSON or YAML.",
108
+ err=True,
109
+ )
110
+ raise typer.Exit(code=1) from error
111
+
112
+ if not isinstance(data, dict):
113
+ typer.echo(
114
+ f"{resource_name.capitalize()} data must contain an object "
115
+ "at the top level.",
116
+ err=True,
117
+ )
118
+ raise typer.Exit(code=1)
119
+ return cast(dict[str, JSONValue], data)
120
+
121
+
122
+ def request_user_overview(
123
+ server_url: str,
124
+ server_port: int,
125
+ token: str,
126
+ ) -> dict[str, object]:
127
+ """Fetch and validate the authenticated user's overview response.
128
+
129
+ :param server_url: The URL of the server.
130
+ :type server_url: str
131
+ :param server_port: The port of the server.
132
+ :type server_port: int
133
+ :param token: The authentication token.
134
+ :type token: str
135
+ :returns: The user's overview as a dictionary.
136
+ :rtype: dict[str, object]
137
+ """
138
+ response = request_api(
139
+ server=ServerParameters(server_url=server_url, server_port=server_port),
140
+ token=token,
141
+ specific_request=SpecificRequest(
142
+ method=HTTPMethod.GET,
143
+ endpoint="users/me/overview",
144
+ ),
145
+ )
146
+ if not isinstance(response, dict):
147
+ raise APIError("The API response isn't a user overview.")
148
+ overview = response
149
+ if not isinstance(overview.get("user"), dict):
150
+ raise APIError("The API response has no valid user identity.")
151
+ for key in ("devices", "leases", "profiles"):
152
+ rows = overview.get(key)
153
+ if not isinstance(rows, list) or any(
154
+ not isinstance(row, dict) for row in cast(list[object], rows)
155
+ ):
156
+ raise APIError(f"The API response has no valid {key} list.")
157
+ return overview
158
+
159
+
160
+ def profile_rows(response: object) -> list[dict[str, object]]:
161
+ """Validate the list response returned by a profile endpoint.
162
+
163
+ :param response: The API response to validate.
164
+ :type response: object
165
+ :returns: A list of profile objects.
166
+ :rtype: list[dict[str, object]]
167
+ """
168
+ return resource_rows(response, "profile")
169
+
170
+
171
+ def resource_rows(response: object, resource_name: str) -> list[dict[str, object]]:
172
+ """Validate an API list response containing object rows.
173
+
174
+ :param response: The API response to validate.
175
+ :type response: object
176
+ :param resource_name: The name of the resource being validated.
177
+ :type resource_name: str
178
+ :returns: A list of resource objects.
179
+ :rtype: list[dict[str, object]]
180
+ """
181
+ if not isinstance(response, list):
182
+ raise APIError(f"The API response isn't a {resource_name} list.")
183
+ rows = cast(list[object], response)
184
+ if any(not isinstance(row, dict) for row in rows):
185
+ raise APIError(f"The API response isn't a {resource_name} list.")
186
+ return cast(list[dict[str, object]], rows)
187
+
188
+
189
+ def resource_object(response: object, resource_name: str) -> dict[str, object]:
190
+ """Validate an API response containing one object.
191
+
192
+ :param response: The API response to validate.
193
+ :type response: object
194
+ :param resource_name: The name of the resource being validated.
195
+ :type resource_name: str
196
+ :returns: The resource object.
197
+ :rtype: dict[str, object]
198
+ """
199
+ if not isinstance(response, dict):
200
+ raise APIError(f"The API response isn't a {resource_name}.")
201
+ return cast(dict[str, object], response)
202
+
203
+
204
+ def display_profiles(
205
+ profiles: list[dict[str, object]],
206
+ *,
207
+ json_output: bool,
208
+ yaml_output: bool,
209
+ ) -> None:
210
+ """Display profiles as JSON, YAML, or a Rich table.
211
+
212
+ :param profiles: The list of profiles to display.
213
+ :type profiles: list[dict[str, object]]
214
+ :param json_output: Whether to output as JSON.
215
+ :type json_output: bool
216
+ :param yaml_output: Whether to output as YAML.
217
+ :type yaml_output: bool
218
+ """
219
+ if display_structured_output(
220
+ profiles,
221
+ json_output=json_output,
222
+ yaml_output=yaml_output,
223
+ yaml_root="profiles",
224
+ ):
225
+ return
226
+
227
+ table = Table(title="Profiles", expand=True)
228
+ table.add_column("Profile ID", style="cyan", no_wrap=True)
229
+ table.add_column("Name", style="green", overflow="ellipsis")
230
+ table.add_column("Default duration")
231
+ table.add_column("Maximum duration")
232
+ table.add_column("Networks")
233
+ table.add_column("Status")
234
+ for profile in profiles:
235
+ policy_value = profile.get("policy")
236
+ policy = (
237
+ cast(dict[str, object], policy_value)
238
+ if isinstance(policy_value, dict)
239
+ else {}
240
+ )
241
+ networks_value = policy.get("networks")
242
+ network_count = (
243
+ len(cast(list[object], networks_value))
244
+ if isinstance(networks_value, list)
245
+ else 0
246
+ )
247
+ status = "revoked" if profile.get("revoked_at") is not None else "active"
248
+ table.add_row(
249
+ str(profile.get("id", "")),
250
+ str(profile.get("name", "")),
251
+ str(policy.get("default_duration", "-")),
252
+ str(policy.get("maximum_duration", "-")),
253
+ str(network_count),
254
+ status,
255
+ )
256
+ Console().print(table)
@@ -0,0 +1,22 @@
1
+ """Admin commands for the TTL-LAMa CLI.
2
+
3
+ .. module_author:: Rémi Verschuur <rverschuur@audit-io.fr>
4
+ .. version:: 0.1.0
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import typer
9
+
10
+ from .devices import devices_app
11
+ from .leases import leases_app
12
+ from .profiles import profiles_app
13
+ from .users import users_app
14
+
15
+ app = typer.Typer(
16
+ no_args_is_help=True,
17
+ help="Admin commands for the TTL-LAMa CLI.",
18
+ )
19
+ app.add_typer(users_app, name="users")
20
+ app.add_typer(devices_app, name="devices")
21
+ app.add_typer(leases_app, name="leases")
22
+ app.add_typer(profiles_app, name="profiles")