ttlama-sdk 0.1.0__tar.gz

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.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: ttlama-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client for the TTL-LAMa API
5
+ Author-email: "Rémi Verschuur|rverschuur@audit-io.fr|" <rverschuur@audit-io.fr>
6
+ Maintainer-email: Rémi Verschuur <rverschuur@audit-io.fr>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Repository, https://github.com/remiv1/TTL-LAMa-SDK
9
+ Keywords: TTL-LAMa,API,SDK
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Developers
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: requests<3,>=2
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest<10,>=9; extra == "test"
19
+ Provides-Extra: release
20
+ Requires-Dist: build<2,>=1; extra == "release"
21
+ Requires-Dist: twine<8,>=7; extra == "release"
22
+
23
+ # TTL-LAMa Python SDK
24
+
25
+ This synchronous client supports TTL-LAMa API v1 authentication, users, devices, profiles and leases. It does not depend on the CLI. Global configuration and web routes are outside its scope.
26
+
27
+ See [README.fr.md](README.fr.md) for the French guide.
28
+
29
+ ## Install
30
+
31
+ Use Python 3.12 or newer in a virtual environment:
32
+
33
+ ```sh
34
+ python -m pip install ./sdk/python
35
+ ```
36
+
37
+ From the SDK repository root, install the development dependencies with `python -m pip install -e './python[test]'` and run `python -m pytest python/tests`.
38
+
39
+ ## Usage
40
+
41
+ ```python
42
+ from getpass import getpass
43
+ from ttlama_sdk import TTLLama
44
+
45
+ with TTLLama("https://ttl-lama.example") as ttl:
46
+ ttl.login("admin", getpass("Password: "))
47
+ user = ttl.user.get("USER_UUID")
48
+ ttl.user.assign_profile(user["id"], 1)
49
+ ttl.auth.logout()
50
+ ```
51
+
52
+ Alternatively, pass an existing token with `TTLLama(url, token=token)`. Internal login handles the CSRF token and associated cookie, then uses a Bearer token. The token remains in memory and is available as `ttl.token`; callers must keep it secret. Closing the client does not revoke the session. Logout revokes the current session; changing the password revokes all of the user's sessions.
53
+
54
+ Administrator operations are available on `ttl.user`, `ttl.device`, `ttl.lease`, and `ttl.profile`. The current user's account and resources are available on `ttl.me`, `ttl.me.devices`, and `ttl.me.leases`. List methods accept API filters as keyword arguments. Create and update methods accept API fields as keyword arguments. Results are JSON dictionaries or lists, and `204` responses return `None`. User creation without a supplied password in internal mode returns `user` and `generated_password`; an explicitly supplied password is not returned.
55
+
56
+ For OIDC device authorization, use `ttl.auth.oidc_device()` and poll with `ttl.auth.oidc_poll(device_code)` at the provider's interval. Increase the interval for `slow_down`; `denied` and `expired` end the flow. A completed poll stores the token automatically. `ttl.auth.oidc_exchange(ticket)` exchanges a one-time CLI ticket. The application is responsible for displaying the user code and verification URL, opening a browser if needed, and polling.
57
+
58
+ Register only the client's WireGuard public key. Keep the private key local and fill the returned configuration template locally. Destination filtering by profile requires appropriate external network configuration.
59
+
60
+ Errors inherit from `TTLamaError`. `APIError` exposes `status_code` and an optional `lease_id`; HTTP 400, 401, 403, 404, 409 and 503 map to `ValidationError`, `AuthenticationError`, `AuthorizationError`, `NotFoundError`, `ConflictError` and `ProvisioningError`. Default timeouts are 5 seconds for ordinary requests and 60 seconds for lease provisioning; configure them using `timeout` and `lease_timeout`. Mutations are never retried automatically: after a timeout or `503`, inspect the lease state before retrying.
@@ -0,0 +1,38 @@
1
+ # TTL-LAMa Python SDK
2
+
3
+ This synchronous client supports TTL-LAMa API v1 authentication, users, devices, profiles and leases. It does not depend on the CLI. Global configuration and web routes are outside its scope.
4
+
5
+ See [README.fr.md](README.fr.md) for the French guide.
6
+
7
+ ## Install
8
+
9
+ Use Python 3.12 or newer in a virtual environment:
10
+
11
+ ```sh
12
+ python -m pip install ./sdk/python
13
+ ```
14
+
15
+ From the SDK repository root, install the development dependencies with `python -m pip install -e './python[test]'` and run `python -m pytest python/tests`.
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ from getpass import getpass
21
+ from ttlama_sdk import TTLLama
22
+
23
+ with TTLLama("https://ttl-lama.example") as ttl:
24
+ ttl.login("admin", getpass("Password: "))
25
+ user = ttl.user.get("USER_UUID")
26
+ ttl.user.assign_profile(user["id"], 1)
27
+ ttl.auth.logout()
28
+ ```
29
+
30
+ Alternatively, pass an existing token with `TTLLama(url, token=token)`. Internal login handles the CSRF token and associated cookie, then uses a Bearer token. The token remains in memory and is available as `ttl.token`; callers must keep it secret. Closing the client does not revoke the session. Logout revokes the current session; changing the password revokes all of the user's sessions.
31
+
32
+ Administrator operations are available on `ttl.user`, `ttl.device`, `ttl.lease`, and `ttl.profile`. The current user's account and resources are available on `ttl.me`, `ttl.me.devices`, and `ttl.me.leases`. List methods accept API filters as keyword arguments. Create and update methods accept API fields as keyword arguments. Results are JSON dictionaries or lists, and `204` responses return `None`. User creation without a supplied password in internal mode returns `user` and `generated_password`; an explicitly supplied password is not returned.
33
+
34
+ For OIDC device authorization, use `ttl.auth.oidc_device()` and poll with `ttl.auth.oidc_poll(device_code)` at the provider's interval. Increase the interval for `slow_down`; `denied` and `expired` end the flow. A completed poll stores the token automatically. `ttl.auth.oidc_exchange(ticket)` exchanges a one-time CLI ticket. The application is responsible for displaying the user code and verification URL, opening a browser if needed, and polling.
35
+
36
+ Register only the client's WireGuard public key. Keep the private key local and fill the returned configuration template locally. Destination filtering by profile requires appropriate external network configuration.
37
+
38
+ Errors inherit from `TTLamaError`. `APIError` exposes `status_code` and an optional `lease_id`; HTTP 400, 401, 403, 404, 409 and 503 map to `ValidationError`, `AuthenticationError`, `AuthorizationError`, `NotFoundError`, `ConflictError` and `ProvisioningError`. Default timeouts are 5 seconds for ordinary requests and 60 seconds for lease provisioning; configure them using `timeout` and `lease_timeout`. Mutations are never retried automatically: after a timeout or `503`, inspect the lease state before retrying.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ttlama-sdk"
7
+ authors = [
8
+ { name = "Rémi Verschuur|rverschuur@audit-io.fr|", email = "rverschuur@audit-io.fr" },
9
+ ]
10
+ keywords = ["TTL-LAMa", "API", "SDK"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Programming Language :: Python :: 3",
14
+ "Operating System :: OS Independent",
15
+ "Intended Audience :: Developers"
16
+ ]
17
+ version = "0.1.0"
18
+ urls = { "Repository" = "https://github.com/remiv1/TTL-LAMa-SDK" }
19
+ description = "Python client for the TTL-LAMa API"
20
+ readme = "README.md"
21
+ requires-python = ">=3.12"
22
+ dependencies = [
23
+ "requests>=2,<3",
24
+ ]
25
+ license = "Apache-2.0"
26
+ license-files = ["LICENSE"]
27
+ maintainers = [
28
+ { name = "Rémi Verschuur", email = "rverschuur@audit-io.fr" },
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ test = ["pytest>=9,<10"]
33
+ release = ["build>=1,<2", "twine>=7,<8"]
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
40
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,19 @@
1
+ """Python SDK for the TTL-LAMa API."""
2
+
3
+ from .client import TTLLama
4
+ from .errors import (
5
+ APIError, AuthenticationError, AuthorizationError, ConflictError,
6
+ NotFoundError, ProvisioningError, TTLamaError, ValidationError,
7
+ )
8
+
9
+ __all__ = [
10
+ "TTLLama",
11
+ "TTLamaError",
12
+ "APIError",
13
+ "AuthenticationError",
14
+ "AuthorizationError",
15
+ "ValidationError",
16
+ "NotFoundError",
17
+ "ConflictError",
18
+ "ProvisioningError",
19
+ ]
@@ -0,0 +1,150 @@
1
+ """HTTP transport and authentication for the TTL-LAMa API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, cast
6
+ from urllib.parse import urlsplit
7
+
8
+ import requests
9
+
10
+ from .errors import (
11
+ APIError, AuthenticationError, AuthorizationError, ConflictError,
12
+ NotFoundError, ProvisioningError, ValidationError,
13
+ )
14
+ from .resources import AdminDevices, AdminLeases, Auth, CurrentUser, Profiles, Users
15
+
16
+
17
+ class TTLLama:
18
+ """A synchronous client for one TTL-LAMa server.
19
+
20
+ :param base_url: Server origin, including its scheme and optional port.
21
+ :param token: Optional existing TTL-LAMa Bearer token.
22
+ :param timeout: Default HTTP timeout in seconds.
23
+ :param lease_timeout: HTTP timeout for VPN provisioning operations.
24
+ """
25
+
26
+ def __init__(self, base_url: str, *, token: str | None = None,
27
+ timeout: float = 5.0, lease_timeout: float = 60.0) -> None:
28
+ parts = urlsplit(base_url)
29
+ if (parts.scheme not in {"http", "https"} or not parts.netloc
30
+ or parts.username is not None or parts.password is not None
31
+ or parts.path not in {"", "/"} or parts.query or parts.fragment):
32
+ raise ValueError("base_url must be an HTTP(S) server origin")
33
+ if timeout <= 0 or lease_timeout <= 0:
34
+ raise ValueError("Timeouts must be positive")
35
+ if token is not None and not token.strip():
36
+ raise ValueError("Token must not be empty")
37
+ self._api_url = base_url.rstrip("/") + "/api/v1"
38
+ self._token: str | None = token
39
+ self.timeout = timeout
40
+ self.lease_timeout = lease_timeout
41
+ self.session = requests.Session()
42
+ self.auth = Auth(self)
43
+ self.user = Users(self)
44
+ self.device = AdminDevices(self)
45
+ self.lease = AdminLeases(self)
46
+ self.profile = Profiles(self)
47
+ self.me = CurrentUser(self)
48
+
49
+ @property
50
+ def token(self) -> str | None:
51
+ """Return the current Bearer token, if authenticated."""
52
+ return self._token
53
+
54
+ @token.setter
55
+ def token(self, value: str | None) -> None:
56
+ if value is not None and not value.strip():
57
+ raise ValueError("Token must not be empty")
58
+ self._token = value
59
+
60
+ def close(self) -> None:
61
+ """Close the HTTP session."""
62
+ self.session.close()
63
+
64
+ def __enter__(self) -> TTLLama:
65
+ return self
66
+
67
+ def __exit__(self, *args: object) -> None:
68
+ self.close()
69
+
70
+ def request(self, method: str, path: str, *, json: object = None,
71
+ params: object = None, timeout: float | None = None,
72
+ authenticated: bool = True, headers: dict[str, str] | None = None) -> Any:
73
+ """Send an API request and return its decoded JSON or ``None``.
74
+
75
+ :param method: HTTP method.
76
+ :param path: Path relative to ``/api/v1``, beginning with ``/``.
77
+ :param json: Optional JSON request body.
78
+ :param params: Optional query parameters.
79
+ :param timeout: Override for the request timeout in seconds.
80
+ :param authenticated: Whether to send the current Bearer token.
81
+ :param headers: Optional additional HTTP headers.
82
+ :returns: The decoded response or ``None`` for HTTP 204.
83
+ :raises APIError: If the request fails or its response is invalid.
84
+ """
85
+ request_headers = dict(headers or {})
86
+ if authenticated and self._token is not None:
87
+ request_headers["Authorization"] = f"Bearer {self._token}"
88
+ try:
89
+ response = self.session.request(
90
+ method, self._api_url + path, json=cast(Any, json), params=cast(Any, params),
91
+ headers=request_headers, timeout=timeout if timeout is not None else self.timeout,
92
+ )
93
+ except requests.RequestException as error:
94
+ raise APIError("Unable to reach the TTL-LAMa API") from error
95
+ if not response.ok:
96
+ lease_id: int | None = None
97
+ try:
98
+ payload: object = response.json()
99
+ if isinstance(payload, dict):
100
+ error_data = cast(dict[str, object], payload)
101
+ error_lease_id = error_data.get("lease_id")
102
+ if isinstance(error_lease_id, int):
103
+ lease_id = error_lease_id
104
+ except ValueError:
105
+ pass
106
+ error_type = {
107
+ 400: ValidationError,
108
+ 401: AuthenticationError,
109
+ 403: AuthorizationError,
110
+ 404: NotFoundError,
111
+ 409: ConflictError,
112
+ 503: ProvisioningError,
113
+ }.get(response.status_code, APIError)
114
+ raise error_type(f"TTL-LAMa API returned HTTP {response.status_code}",
115
+ status_code=response.status_code, lease_id=lease_id)
116
+ if response.status_code == 204:
117
+ return None
118
+ try:
119
+ return response.json()
120
+ except ValueError as error:
121
+ raise APIError("TTL-LAMa API returned invalid JSON",
122
+ status_code=response.status_code) from error
123
+
124
+ def login(self, username: str, password: str) -> str:
125
+ """Authenticate internally and store the returned Bearer token.
126
+
127
+ :param username: Internal username.
128
+ :param password: Internal password.
129
+ :returns: The session token.
130
+ :raises APIError: If authentication or the API response fails.
131
+ """
132
+ csrf: object = self.request("GET", "/csrf", authenticated=False)
133
+ csrf_token = cast(
134
+ dict[str, object],
135
+ csrf
136
+ ).get("csrf_token") if isinstance(csrf, dict) else None
137
+ if not isinstance(csrf_token, str) or not csrf_token:
138
+ raise APIError("TTL-LAMa API returned an invalid CSRF token")
139
+ payload: object = self.request(
140
+ "POST", "/auth", json={"username": username, "password": password},
141
+ authenticated=False, headers={"X-CSRFToken": csrf_token},
142
+ )
143
+ access_token = cast(
144
+ dict[str, object],
145
+ payload
146
+ ).get("access_token") if isinstance(payload, dict) else None
147
+ if not isinstance(access_token, str) or not access_token:
148
+ raise APIError("TTL-LAMa API returned an invalid access token")
149
+ self._token = access_token
150
+ return access_token
@@ -0,0 +1,52 @@
1
+ """Exceptions raised by the TTL-LAMa Python SDK."""
2
+
3
+
4
+ class TTLamaError(Exception):
5
+ """Base exception for SDK errors."""
6
+
7
+
8
+ class APIError(TTLamaError):
9
+ """An HTTP or transport error returned while accessing the API.
10
+
11
+ :param message: Error message.
12
+ :type message: str
13
+ :param status_code: HTTP status code, if available.
14
+ :type status_code: int | None
15
+ :param lease_id: Lease ID related to the error, if available.
16
+ :type lease_id: int | None
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ message: str,
22
+ *,
23
+ status_code: int | None = None,
24
+ lease_id: int | None = None
25
+ ) -> None:
26
+ super().__init__(message)
27
+ self.status_code = status_code
28
+ self.lease_id = lease_id
29
+
30
+
31
+ class AuthenticationError(APIError):
32
+ """Authentication failed or the session expired."""
33
+
34
+
35
+ class AuthorizationError(APIError):
36
+ """The authenticated user lacks the required permissions."""
37
+
38
+
39
+ class ValidationError(APIError):
40
+ """The request or its CSRF token is invalid."""
41
+
42
+
43
+ class NotFoundError(APIError):
44
+ """The requested resource was not found."""
45
+
46
+
47
+ class ConflictError(APIError):
48
+ """The request conflicts with the current resource state."""
49
+
50
+
51
+ class ProvisioningError(APIError):
52
+ """VPN provisioning could not be confirmed."""
@@ -0,0 +1,258 @@
1
+ """Resource operations for the TTL-LAMa API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, cast
6
+ from urllib.parse import quote
7
+ from uuid import UUID
8
+
9
+ from .errors import APIError
10
+
11
+ if TYPE_CHECKING:
12
+ from .client import TTLLama
13
+
14
+ JSONObject = dict[str, Any]
15
+ UserID = str | UUID
16
+
17
+
18
+ def _id(value: str | int | UUID) -> str:
19
+ return quote(str(value), safe="")
20
+
21
+
22
+ class _Resource:
23
+ def __init__(self, client: TTLLama) -> None:
24
+ self._client = client
25
+
26
+ def _object(self, method: str, path: str, **kwargs: Any) -> JSONObject:
27
+ result = self._client.request(method, path, **kwargs)
28
+ if not isinstance(result, dict):
29
+ raise APIError("TTL-LAMa API returned an invalid object")
30
+ return cast(JSONObject, result)
31
+
32
+ def _list(self, path: str, **params: Any) -> list[JSONObject]:
33
+ result = self._client.request("GET", path, params=params)
34
+ if not isinstance(result, list):
35
+ raise APIError("TTL-LAMa API returned an invalid list")
36
+ items = cast(list[object], result)
37
+ if any(not isinstance(item, dict) for item in items):
38
+ raise APIError("TTL-LAMa API returned an invalid list")
39
+ return cast(list[JSONObject], items)
40
+
41
+
42
+ class Auth(_Resource):
43
+ """Authentication and OIDC operations."""
44
+
45
+ def csrf(self) -> JSONObject:
46
+ """Get a CSRF token and retain its associated session cookie."""
47
+ return self._object("GET", "/csrf", authenticated=False)
48
+
49
+ def logout(self) -> None:
50
+ """Revoke the current session and forget its token on success."""
51
+ self._client.request("POST", "/auth/logout")
52
+ self._client.token = None
53
+
54
+ def oidc_exchange(self, ticket: str) -> JSONObject:
55
+ """Exchange a single-use OIDC ticket and store the returned token."""
56
+ result = self._object("POST", "/auth/oidc/exchange", json={"ticket": ticket},
57
+ authenticated=False)
58
+ self._save_token(result)
59
+ return result
60
+
61
+ def oidc_device(self) -> JSONObject:
62
+ """Start OIDC device authorization."""
63
+ return self._object("POST", "/auth/oidc/device", json={}, authenticated=False)
64
+
65
+ def oidc_poll(self, device_code: str) -> JSONObject:
66
+ """Poll device authorization and store the token upon completion."""
67
+ result = self._object("POST", "/auth/oidc/device/poll",
68
+ json={"device_code": device_code}, authenticated=False)
69
+ if result.get("status") == "complete":
70
+ self._save_token(result)
71
+ return result
72
+
73
+ def _save_token(self, result: JSONObject) -> None:
74
+ token = result.get("access_token")
75
+ if not isinstance(token, str) or not token:
76
+ raise APIError("TTL-LAMa API returned an invalid access token")
77
+ self._client.token = token
78
+
79
+
80
+ class Users(_Resource):
81
+ """Administrative user operations."""
82
+
83
+ def list(self, **filters: Any) -> list[JSONObject]:
84
+ """List users using optional relationship filters."""
85
+ return self._list("/admin/users", **filters)
86
+
87
+ def get(self, user_id: UserID) -> JSONObject:
88
+ """Get a user by UUID."""
89
+ return self._object("GET", f"/admin/users/{_id(user_id)}")
90
+
91
+ def create(self, username: str, **fields: Any) -> JSONObject:
92
+ """Create a user; preserve any generated password in the response."""
93
+ return self._object("POST", "/admin/users", json={"username": username, **fields})
94
+
95
+ def update(self, user_id: UserID, **fields: Any) -> JSONObject:
96
+ """Update the supplied user fields."""
97
+ return self._object("PATCH", f"/admin/users/{_id(user_id)}", json=fields)
98
+
99
+ def delete(self, user_id: UserID) -> None:
100
+ """Disable a user and revoke dependent access."""
101
+ self._client.request("DELETE", f"/admin/users/{_id(user_id)}")
102
+
103
+ def profiles(self, user_id: UserID) -> list[JSONObject]:
104
+ """List profiles assigned to the user."""
105
+ return self._list(f"/admin/users/{_id(user_id)}/profiles")
106
+
107
+ def assign_profile(self, user_id: UserID, profile_id: int) -> JSONObject:
108
+ """Assign a profile to a user."""
109
+ return self._object("PUT", f"/admin/users/{_id(user_id)}/profiles/{_id(profile_id)}")
110
+
111
+ def unassign_profile(self, user_id: UserID, profile_id: int) -> None:
112
+ """Remove an assignment and revoke its leases."""
113
+ self._client.request("DELETE", f"/admin/users/{_id(user_id)}/profiles/{_id(profile_id)}")
114
+
115
+
116
+ class AdminDevices(_Resource):
117
+ """Administrative device operations."""
118
+
119
+ def list(self, **filters: Any) -> list[JSONObject]:
120
+ """List devices using optional relationship filters."""
121
+ return self._list("/admin/devices", **filters)
122
+
123
+ def get(self, device_id: int) -> JSONObject:
124
+ """Get a device."""
125
+ return self._object("GET", f"/admin/devices/{_id(device_id)}")
126
+
127
+ def update(self, device_id: int, **fields: Any) -> JSONObject:
128
+ """Update a device name or public key."""
129
+ return self._object("PATCH", f"/admin/devices/{_id(device_id)}", json=fields)
130
+
131
+ def block(self, device_id: int) -> JSONObject:
132
+ """Block a device and revoke its leases."""
133
+ return self._object("POST", f"/admin/devices/{_id(device_id)}/block")
134
+
135
+ def delete(self, device_id: int) -> None:
136
+ """Revoke a device."""
137
+ self._client.request("DELETE", f"/admin/devices/{_id(device_id)}")
138
+
139
+
140
+ class AdminLeases(_Resource):
141
+ """Administrative lease operations."""
142
+
143
+ def list(self, **filters: Any) -> list[JSONObject]:
144
+ """List leases using optional filters."""
145
+ return self._list("/admin/leases", **filters)
146
+
147
+ def get(self, lease_id: int) -> JSONObject:
148
+ """Get a lease."""
149
+ return self._object("GET", f"/admin/leases/{_id(lease_id)}")
150
+
151
+ def revoke(self, lease_id: int) -> JSONObject:
152
+ """Revoke a lease and wait for VPN confirmation."""
153
+ return self._object("POST", f"/admin/leases/{_id(lease_id)}/revoke",
154
+ timeout=self._client.lease_timeout)
155
+
156
+
157
+ class Profiles(_Resource):
158
+ """Administrative access profile operations."""
159
+
160
+ def list(self, **filters: Any) -> list[JSONObject]:
161
+ """List profiles using optional relationship filters."""
162
+ return self._list("/admin/profiles", **filters)
163
+
164
+ def get(self, profile_id: int) -> JSONObject:
165
+ """Get a profile and its policy."""
166
+ return self._object("GET", f"/admin/profiles/{_id(profile_id)}")
167
+
168
+ def create(self, name: str, **policy: Any) -> JSONObject:
169
+ """Create a profile with its complete policy."""
170
+ return self._object("POST", "/admin/profiles", json={"name": name, **policy})
171
+
172
+ def update(self, profile_id: int, **fields: Any) -> JSONObject:
173
+ """Update a profile or its policy."""
174
+ return self._object("PATCH", f"/admin/profiles/{_id(profile_id)}", json=fields)
175
+
176
+ def delete(self, profile_id: int) -> None:
177
+ """Revoke a profile and dependent access."""
178
+ self._client.request("DELETE", f"/admin/profiles/{_id(profile_id)}")
179
+
180
+
181
+ class OwnedDevices(_Resource):
182
+ """Devices belonging to the authenticated user."""
183
+
184
+ def list(self) -> list[JSONObject]:
185
+ """List owned devices."""
186
+ return self._list("/users/me/devices")
187
+
188
+ def get(self, device_id: int) -> JSONObject:
189
+ """Get an owned device."""
190
+ return self._object("GET", f"/users/me/devices/{_id(device_id)}")
191
+
192
+ def create(self, name: str, public_key: str) -> JSONObject:
193
+ """Register a device using its public key only."""
194
+ return self._object(
195
+ "POST",
196
+ "/users/me/devices",
197
+ json={
198
+ "name": name,
199
+ "public_key": public_key,
200
+ },
201
+ )
202
+
203
+ def delete(self, device_id: int) -> None:
204
+ """Revoke an owned device and its leases."""
205
+ self._client.request("DELETE", f"/users/me/devices/{_id(device_id)}")
206
+
207
+
208
+ class OwnedLeases(_Resource):
209
+ """Leases belonging to the authenticated user."""
210
+
211
+ def list(self) -> list[JSONObject]:
212
+ """List owned leases."""
213
+ return self._list("/users/me/leases")
214
+
215
+ def get(self, lease_id: int) -> JSONObject:
216
+ """Get an owned lease."""
217
+ return self._object("GET", f"/users/me/leases/{_id(lease_id)}")
218
+
219
+ def create(self, device_id: int, profile_id: int, *, duration: str | None = None) -> JSONObject:
220
+ """Create a lease and wait for VPN confirmation."""
221
+ payload: JSONObject = {"device_id": device_id, "profile_id": profile_id}
222
+ if duration is not None:
223
+ payload["duration"] = duration
224
+ return self._object("POST", "/users/me/leases", json=payload,
225
+ timeout=self._client.lease_timeout)
226
+
227
+ def configuration(self, lease_id: int) -> JSONObject:
228
+ """Get public WireGuard parameters for an active lease."""
229
+ return self._object("GET", f"/users/me/leases/{_id(lease_id)}/configuration")
230
+
231
+ def revoke(self, lease_id: int) -> JSONObject:
232
+ """Revoke an owned lease and wait for VPN confirmation."""
233
+ return self._object("POST", f"/users/me/leases/{_id(lease_id)}/revoke",
234
+ timeout=self._client.lease_timeout)
235
+
236
+
237
+ class CurrentUser(_Resource):
238
+ """Account and resources of the authenticated user."""
239
+
240
+ def __init__(self, client: TTLLama) -> None:
241
+ super().__init__(client)
242
+ self.devices = OwnedDevices(client)
243
+ self.leases = OwnedLeases(client)
244
+
245
+ def get(self) -> JSONObject:
246
+ """Get the authenticated identity and session expirations."""
247
+ return self._object("GET", "/users/me")
248
+
249
+ def overview(self) -> JSONObject:
250
+ """Get the authenticated identity and its resources."""
251
+ return self._object("GET", "/users/me/overview")
252
+
253
+ def change_password(self, current_password: str, new_password: str) -> None:
254
+ """Change the internal password and forget the revoked session token."""
255
+ self._client.request("PATCH", "/users/me/password", json={
256
+ "current_password": current_password, "new_password": new_password,
257
+ })
258
+ self._client.token = None
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: ttlama-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client for the TTL-LAMa API
5
+ Author-email: "Rémi Verschuur|rverschuur@audit-io.fr|" <rverschuur@audit-io.fr>
6
+ Maintainer-email: Rémi Verschuur <rverschuur@audit-io.fr>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Repository, https://github.com/remiv1/TTL-LAMa-SDK
9
+ Keywords: TTL-LAMa,API,SDK
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Developers
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: requests<3,>=2
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest<10,>=9; extra == "test"
19
+ Provides-Extra: release
20
+ Requires-Dist: build<2,>=1; extra == "release"
21
+ Requires-Dist: twine<8,>=7; extra == "release"
22
+
23
+ # TTL-LAMa Python SDK
24
+
25
+ This synchronous client supports TTL-LAMa API v1 authentication, users, devices, profiles and leases. It does not depend on the CLI. Global configuration and web routes are outside its scope.
26
+
27
+ See [README.fr.md](README.fr.md) for the French guide.
28
+
29
+ ## Install
30
+
31
+ Use Python 3.12 or newer in a virtual environment:
32
+
33
+ ```sh
34
+ python -m pip install ./sdk/python
35
+ ```
36
+
37
+ From the SDK repository root, install the development dependencies with `python -m pip install -e './python[test]'` and run `python -m pytest python/tests`.
38
+
39
+ ## Usage
40
+
41
+ ```python
42
+ from getpass import getpass
43
+ from ttlama_sdk import TTLLama
44
+
45
+ with TTLLama("https://ttl-lama.example") as ttl:
46
+ ttl.login("admin", getpass("Password: "))
47
+ user = ttl.user.get("USER_UUID")
48
+ ttl.user.assign_profile(user["id"], 1)
49
+ ttl.auth.logout()
50
+ ```
51
+
52
+ Alternatively, pass an existing token with `TTLLama(url, token=token)`. Internal login handles the CSRF token and associated cookie, then uses a Bearer token. The token remains in memory and is available as `ttl.token`; callers must keep it secret. Closing the client does not revoke the session. Logout revokes the current session; changing the password revokes all of the user's sessions.
53
+
54
+ Administrator operations are available on `ttl.user`, `ttl.device`, `ttl.lease`, and `ttl.profile`. The current user's account and resources are available on `ttl.me`, `ttl.me.devices`, and `ttl.me.leases`. List methods accept API filters as keyword arguments. Create and update methods accept API fields as keyword arguments. Results are JSON dictionaries or lists, and `204` responses return `None`. User creation without a supplied password in internal mode returns `user` and `generated_password`; an explicitly supplied password is not returned.
55
+
56
+ For OIDC device authorization, use `ttl.auth.oidc_device()` and poll with `ttl.auth.oidc_poll(device_code)` at the provider's interval. Increase the interval for `slow_down`; `denied` and `expired` end the flow. A completed poll stores the token automatically. `ttl.auth.oidc_exchange(ticket)` exchanges a one-time CLI ticket. The application is responsible for displaying the user code and verification URL, opening a browser if needed, and polling.
57
+
58
+ Register only the client's WireGuard public key. Keep the private key local and fill the returned configuration template locally. Destination filtering by profile requires appropriate external network configuration.
59
+
60
+ Errors inherit from `TTLamaError`. `APIError` exposes `status_code` and an optional `lease_id`; HTTP 400, 401, 403, 404, 409 and 503 map to `ValidationError`, `AuthenticationError`, `AuthorizationError`, `NotFoundError`, `ConflictError` and `ProvisioningError`. Default timeouts are 5 seconds for ordinary requests and 60 seconds for lease provisioning; configure them using `timeout` and `lease_timeout`. Mutations are never retried automatically: after a timeout or `503`, inspect the lease state before retrying.
@@ -0,0 +1,14 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/ttlama_sdk/__init__.py
4
+ src/ttlama_sdk/client.py
5
+ src/ttlama_sdk/errors.py
6
+ src/ttlama_sdk/resources.py
7
+ src/ttlama_sdk.egg-info/PKG-INFO
8
+ src/ttlama_sdk.egg-info/SOURCES.txt
9
+ src/ttlama_sdk.egg-info/dependency_links.txt
10
+ src/ttlama_sdk.egg-info/requires.txt
11
+ src/ttlama_sdk.egg-info/top_level.txt
12
+ tests/test_client.py
13
+ tests/test_resources.py
14
+ tests/test_server_integration.py
@@ -0,0 +1,8 @@
1
+ requests<3,>=2
2
+
3
+ [release]
4
+ build<2,>=1
5
+ twine<8,>=7
6
+
7
+ [test]
8
+ pytest<10,>=9
@@ -0,0 +1 @@
1
+ ttlama_sdk
@@ -0,0 +1,216 @@
1
+ """Tests for the SDK transport and authentication."""
2
+
3
+ import json
4
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
5
+ from threading import Thread
6
+ from unittest.mock import Mock
7
+
8
+ import pytest
9
+ from requests.exceptions import ConnectionError as RequestsConnectionError
10
+
11
+ from ttlama_sdk import (
12
+ APIError, AuthenticationError, AuthorizationError, ConflictError, NotFoundError,
13
+ ProvisioningError, TTLLama, ValidationError,
14
+ )
15
+
16
+
17
+ def test_login_preserves_csrf_session_and_uses_bearer() -> None:
18
+ """Test that login preserves CSRF token, session, and uses bearer token."""
19
+ client = TTLLama("https://example.test")
20
+ session = Mock()
21
+ session.request.side_effect = [
22
+ Mock(ok=True, status_code=200, json=Mock(return_value={"csrf_token": "csrf"})),
23
+ Mock(ok=True, status_code=200, json=Mock(return_value={"access_token": "token"})),
24
+ Mock(ok=True, status_code=200, json=Mock(return_value={"id": "user"})),
25
+ ]
26
+ client.session = session
27
+
28
+ assert client.login("alice", "secret") == "token"
29
+ assert client.request("GET", "/users/me") == {"id": "user"}
30
+ assert session.request.call_args_list[0].args[:2] == ("GET", "https://example.test/api/v1/csrf")
31
+ assert session.request.call_args_list[1].kwargs["headers"] == {"X-CSRFToken": "csrf"}
32
+ assert session.request.call_args_list[2].kwargs["headers"] == {"Authorization": "Bearer token"}
33
+
34
+
35
+ def response(payload: object = None, status: int = 200) -> Mock:
36
+ """Create a mock response with the given payload and status code."""
37
+ return Mock(ok=status < 400, status_code=status, json=Mock(return_value=payload))
38
+
39
+
40
+ def test_missing_csrf_stops_login() -> None:
41
+ """Test that missing CSRF token stops the login process."""
42
+ client = TTLLama("https://example.test")
43
+ client.session = Mock()
44
+ client.session.request.return_value = response({"csrf_token": ""})
45
+ with pytest.raises(APIError):
46
+ client.login("alice", "secret")
47
+ assert client.session.request.call_count == 1
48
+ assert client.token is None
49
+
50
+
51
+ @pytest.mark.parametrize("status,error_type", [
52
+ (400, ValidationError), (401, AuthenticationError), (403, AuthorizationError),
53
+ (404, NotFoundError), (409, ConflictError), (503, ProvisioningError), (500, APIError),
54
+ ])
55
+ def test_http_errors_are_typed_and_do_not_leak_response(
56
+ status: int,
57
+ error_type: type[APIError],
58
+ ) -> None:
59
+ """Test that HTTP errors are correctly typed and do not leak sensitive response information."""
60
+ client = TTLLama("https://example.test", token="token")
61
+ client.session = Mock()
62
+ client.session.request.return_value = response({"error": "secret", "lease_id": 9}, status)
63
+ with pytest.raises(error_type) as caught:
64
+ client.me.leases.create(1, 2)
65
+ assert caught.value.status_code == status
66
+ assert caught.value.lease_id == 9
67
+ assert "secret" not in str(caught.value)
68
+ assert client.session.request.call_count == 1
69
+ assert client.session.request.call_args.kwargs["timeout"] == 60.0
70
+
71
+
72
+ def test_network_and_non_json_errors() -> None:
73
+ """Test that network errors and non-JSON responses are handled correctly."""
74
+ client = TTLLama("https://example.test")
75
+ client.session = Mock()
76
+ client.session.request.side_effect = RequestsConnectionError("failure")
77
+ with pytest.raises(APIError, match="Unable to reach"):
78
+ client.me.get()
79
+ client.session.request.side_effect = None
80
+ invalid = response()
81
+ invalid.json.side_effect = ValueError("bad JSON")
82
+ client.session.request.return_value = invalid
83
+ with pytest.raises(APIError, match="invalid JSON"):
84
+ client.me.get()
85
+
86
+
87
+ def test_generated_password_and_explicit_password_are_preserved() -> None:
88
+ """Test that generated passwords and explicitly provided passwords are preserved correctly."""
89
+ client = TTLLama("https://example.test", token="token")
90
+ client.session = Mock()
91
+ client.session.request.side_effect = [
92
+ response({"user": {"id": "uuid"}, "generated_password": "generated"}, 201),
93
+ response({"id": "uuid"}, 201),
94
+ ]
95
+ assert client.user.create("alice")["generated_password"] == "generated"
96
+ assert client.user.create("bob", password="password") == {"id": "uuid"}
97
+ assert client.session.request.call_args.kwargs["json"] == {
98
+ "username": "bob", "password": "password",
99
+ }
100
+
101
+
102
+ def test_assignment_and_removal() -> None:
103
+ """Test that profile assignment and removal work correctly."""
104
+ client = TTLLama("https://example.test", token="token")
105
+ client.session = Mock()
106
+ client.session.request.side_effect = [response({"id": 4}), response(status=204)]
107
+ assert client.user.assign_profile("uuid", 3) == {"id": 4}
108
+ assert client.user.unassign_profile("uuid", 3) is None
109
+ assert client.session.request.call_args.args == (
110
+ "DELETE", "https://example.test/api/v1/admin/users/uuid/profiles/3",
111
+ )
112
+
113
+
114
+ def test_oidc_stores_token_only_on_success() -> None:
115
+ """Test that OIDC authentication only stores the token on successful responses."""
116
+ client = TTLLama("https://example.test")
117
+ client.session = Mock()
118
+ client.session.request.side_effect = [
119
+ response({"device_code": "device", "interval": 5}),
120
+ response({"status": "pending"}),
121
+ response({"status": "complete", "access_token": "token", "token_type": "Bearer"}),
122
+ response({"access_token": "ticket-token", "token_type": "Bearer"}),
123
+ ]
124
+ assert client.auth.oidc_device()["device_code"] == "device"
125
+ assert client.auth.oidc_poll("device")["status"] == "pending"
126
+ assert client.token is None
127
+ assert client.auth.oidc_poll("device")["status"] == "complete"
128
+ assert client.token == "token"
129
+ client.auth.oidc_exchange("ticket")
130
+ assert client.token == "ticket-token"
131
+ assert all(not call.kwargs["headers"] for call in client.session.request.call_args_list)
132
+
133
+
134
+ @pytest.mark.parametrize("action", ["logout", "change_password"])
135
+ def test_revoking_current_session_forgets_token(action: str) -> None:
136
+ """Test that revoking the current session forgets the token."""
137
+ client = TTLLama("https://example.test", token="token")
138
+ client.session = Mock()
139
+ client.session.request.return_value = response(status=204)
140
+ if action == "logout":
141
+ client.auth.logout()
142
+ else:
143
+ client.me.change_password("old", "new")
144
+ assert client.token is None
145
+
146
+
147
+ @pytest.mark.parametrize(
148
+ "url",
149
+ [
150
+ "example.test",
151
+ "https://user:secret@example.test",
152
+ "https://example.test/path",
153
+ ]
154
+ )
155
+ def test_rejects_invalid_server_origins(url: str) -> None:
156
+ """Test that invalid server origins are rejected."""
157
+ with pytest.raises(ValueError):
158
+ TTLLama(url)
159
+
160
+
161
+ def test_real_http_session_sends_csrf_cookie_and_bearer() -> None:
162
+ """Test that the real HTTP session sends the CSRF cookie and bearer token correctly."""
163
+ class Handler(BaseHTTPRequestHandler):
164
+ """HTTP request handler for testing CSRF and bearer token behavior."""
165
+ def send_json(
166
+ self,
167
+ status: int,
168
+ payload: dict[str, object],
169
+ *,
170
+ cookie: bool = False,
171
+ ) -> None:
172
+ """Send a JSON response with the given status, payload, and optional cookie."""
173
+ encoded = json.dumps(payload).encode()
174
+ self.send_response(status)
175
+ self.send_header("Content-Type", "application/json")
176
+ self.send_header("Content-Length", str(len(encoded)))
177
+ if cookie:
178
+ self.send_header("Set-Cookie", "session=csrf-session; Path=/; HttpOnly")
179
+ self.end_headers()
180
+ self.wfile.write(encoded)
181
+
182
+ def do_GET(self) -> None: # pylint: disable=C0103
183
+ """Handle GET requests for CSRF token and user info."""
184
+ if self.path == "/api/v1/csrf":
185
+ self.send_json(200, {"csrf_token": "csrf"}, cookie=True)
186
+ elif (
187
+ self.path == "/api/v1/users/me"
188
+ and self.headers.get("Authorization") == "Bearer token"
189
+ ):
190
+ self.send_json(200, {"user": {"username": "alice"}})
191
+ else:
192
+ self.send_json(401, {"error": "unauthorized"})
193
+
194
+ def do_POST(self) -> None: # pylint: disable=C0103
195
+ """Handle POST requests for authentication."""
196
+ size = int(self.headers.get("Content-Length", "0"))
197
+ body = json.loads(self.rfile.read(size))
198
+ if (self.path == "/api/v1/auth"
199
+ and self.headers.get("Cookie") == "session=csrf-session"
200
+ and self.headers.get("X-CSRFToken") == "csrf"
201
+ and body == {"username": "alice", "password": "password"}):
202
+ self.send_json(200, {"access_token": "token"})
203
+ else:
204
+ self.send_json(400, {"error": "invalid request"})
205
+
206
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
207
+ thread = Thread(target=server.serve_forever, daemon=True)
208
+ thread.start()
209
+ try:
210
+ with TTLLama(f"http://127.0.0.1:{server.server_port}") as client:
211
+ assert client.login("alice", "password") == "token"
212
+ assert client.me.get()["user"]["username"] == "alice"
213
+ finally:
214
+ server.shutdown()
215
+ thread.join()
216
+ server.server_close()
@@ -0,0 +1,88 @@
1
+ """Tests for the SDK resource methods and their HTTP contracts."""
2
+
3
+ from collections.abc import Callable
4
+ from unittest.mock import Mock
5
+
6
+ import pytest
7
+
8
+ from ttlama_sdk import APIError, TTLLama
9
+
10
+
11
+ RESOURCE_CASES: list[tuple[Callable[[TTLLama], object], str, str, object]] = [
12
+ (lambda c: c.auth.csrf(), "GET", "/csrf", {}),
13
+ (lambda c: c.me.get(), "GET", "/users/me", {}),
14
+ (lambda c: c.me.overview(), "GET", "/users/me/overview", {}),
15
+ (lambda c: c.me.devices.list(), "GET", "/users/me/devices", []),
16
+ (lambda c: c.me.devices.get(2), "GET", "/users/me/devices/2", {}),
17
+ (lambda c: c.me.devices.create("name", "key"), "POST", "/users/me/devices", {}),
18
+ (lambda c: c.me.devices.delete(2), "DELETE", "/users/me/devices/2", None),
19
+ (lambda c: c.me.leases.list(), "GET", "/users/me/leases", []),
20
+ (lambda c: c.me.leases.get(2), "GET", "/users/me/leases/2", {}),
21
+ (lambda c: c.me.leases.create(2, 3), "POST", "/users/me/leases", {}),
22
+ (lambda c: c.me.leases.configuration(2), "GET", "/users/me/leases/2/configuration", {}),
23
+ (lambda c: c.me.leases.revoke(2), "POST", "/users/me/leases/2/revoke", {}),
24
+ (lambda c: c.user.list(device=2), "GET", "/admin/users", []),
25
+ (lambda c: c.user.get("uuid"), "GET", "/admin/users/uuid", {}),
26
+ (lambda c: c.user.create("alice"), "POST", "/admin/users", {}),
27
+ (lambda c: c.user.update("uuid", enabled=False), "PATCH", "/admin/users/uuid", {}),
28
+ (lambda c: c.user.delete("uuid"), "DELETE", "/admin/users/uuid", None),
29
+ (lambda c: c.user.profiles("uuid"), "GET", "/admin/users/uuid/profiles", []),
30
+ (lambda c: c.user.assign_profile("uuid", 2), "PUT", "/admin/users/uuid/profiles/2", {}),
31
+ (lambda c: c.user.unassign_profile("uuid", 2), "DELETE", "/admin/users/uuid/profiles/2", None),
32
+ (lambda c: c.device.list(), "GET", "/admin/devices", []),
33
+ (lambda c: c.device.get(2), "GET", "/admin/devices/2", {}),
34
+ (lambda c: c.device.update(2, name="new"), "PATCH", "/admin/devices/2", {}),
35
+ (lambda c: c.device.block(2), "POST", "/admin/devices/2/block", {}),
36
+ (lambda c: c.device.delete(2), "DELETE", "/admin/devices/2", None),
37
+ (lambda c: c.lease.list(), "GET", "/admin/leases", []),
38
+ (lambda c: c.lease.get(2), "GET", "/admin/leases/2", {}),
39
+ (lambda c: c.lease.revoke(2), "POST", "/admin/leases/2/revoke", {}),
40
+ (lambda c: c.profile.list(), "GET", "/admin/profiles", []),
41
+ (lambda c: c.profile.get(2), "GET", "/admin/profiles/2", {}),
42
+ (lambda c: c.profile.create("name", lease_target="wg0"), "POST", "/admin/profiles", {}),
43
+ (lambda c: c.profile.update(2, name="new"), "PATCH", "/admin/profiles/2", {}),
44
+ (lambda c: c.profile.delete(2), "DELETE", "/admin/profiles/2", None),
45
+ ]
46
+
47
+
48
+ @pytest.mark.parametrize("operation,method,path,result", RESOURCE_CASES)
49
+ def test_resource_routes(
50
+ operation: Callable[[TTLLama], object],
51
+ method: str,
52
+ path: str,
53
+ result: object,
54
+ ) -> None:
55
+ """Test that the resource routes generate the correct HTTP requests."""
56
+ client = TTLLama("https://example.test", token="token")
57
+ request_mock = Mock(return_value=result)
58
+ client.request = request_mock
59
+ assert operation(client) == result
60
+ assert request_mock.call_args.args == (method, path)
61
+
62
+
63
+ def test_list_filters_and_lease_payloads() -> None:
64
+ """Test that list filters and lease payloads are correctly handled."""
65
+ client = TTLLama("https://example.test", lease_timeout=75)
66
+ request_mock = Mock(return_value=[])
67
+ client.request = request_mock
68
+ client.lease.list(status="active", user="uuid")
69
+ assert request_mock.call_args.kwargs["params"] == {"status": "active", "user": "uuid"}
70
+ request_mock.return_value = {"id": 3}
71
+ client.me.leases.create(1, 2, duration="1h")
72
+ assert request_mock.call_args.kwargs == {
73
+ "json": {"device_id": 1, "profile_id": 2, "duration": "1h"}, "timeout": 75,
74
+ }
75
+ client.me.leases.create(1, 2)
76
+ assert "duration" not in request_mock.call_args.kwargs["json"]
77
+ client.lease.revoke(3)
78
+ assert request_mock.call_args.kwargs["timeout"] == 75
79
+
80
+
81
+ def test_invalid_resource_shape() -> None:
82
+ """Test that invalid resource shapes raise APIError."""
83
+ client = TTLLama("https://example.test")
84
+ client.request = Mock(return_value=["not an object"])
85
+ with pytest.raises(APIError, match="invalid list"):
86
+ client.user.list()
87
+ with pytest.raises(APIError, match="invalid object"):
88
+ client.user.get("uuid")
@@ -0,0 +1,56 @@
1
+ """Optional SDK integration test against the local TTL-LAMa application."""
2
+
3
+ from pathlib import Path
4
+ from threading import Thread
5
+
6
+ import pytest
7
+ from werkzeug.serving import make_server
8
+ from ttlama_sdk import TTLLama
9
+
10
+ from api.config import DatabaseSettings, FlaskSettings
11
+
12
+ pytest.importorskip("api.bootstrap", reason="TTL-LAMa server sources are not installed")
13
+
14
+ from api.bootstrap import create_app # pylint: disable=C0413
15
+
16
+
17
+
18
+ def test_internal_login_user_and_profile_workflow(tmp_path: Path) -> None:
19
+ """Test the internal login, user creation, profile assignment, and user workflow."""
20
+ settings = FlaskSettings.model_validate({
21
+ "AUTH_MODE": "internal",
22
+ "FLASK_ENV": "testing",
23
+ "SECRET_KEY": "test-secret-key-with-more-than-thirty-two-characters",
24
+ "ADMIN_USERNAME": "sdk-admin",
25
+ "ADMIN_PASSWORD": "test-password",
26
+ "ENFORCE_SECURE_CONNECTION": False,
27
+ "SESSION_COOKIE_SECURE": False,
28
+ })
29
+ application = create_app(settings, DatabaseSettings(DB_PATH=str(tmp_path / "sdk.db")))
30
+ application.config["BACKEND_LEASE_TARGETS"] = {"wg0"}
31
+ server = make_server("127.0.0.1", 0, application)
32
+ thread = Thread(target=server.serve_forever, daemon=True)
33
+ thread.start()
34
+ try:
35
+ url = f"http://127.0.0.1:{server.server_port}"
36
+ with TTLLama(url) as admin:
37
+ admin.login("sdk-admin", "test-password")
38
+ created = admin.user.create("sdk-user")
39
+ profile = admin.profile.create(
40
+ "sdk-profile", default_duration="1h", maximum_duration="8h",
41
+ lease_target="wg0", networks=["10.0.0.0/24"],
42
+ address_pools=["10.250.0.0/24"], endpoint="vpn.example.test:51820",
43
+ public_key="server-key",
44
+ )
45
+ assignment = admin.user.assign_profile(created["user"]["id"], profile["id"])
46
+ assert assignment["profile_id"] == profile["id"]
47
+ assert admin.user.get(created["user"]["id"])["username"] == "sdk-user"
48
+ with TTLLama(url) as user:
49
+ user.login("sdk-user", created["generated_password"])
50
+ assert user.me.overview()["profiles"][0]["id"] == profile["id"]
51
+ user.auth.logout()
52
+ finally:
53
+ server.shutdown()
54
+ thread.join()
55
+ server.server_close()
56
+ application.extensions["database_config"].close()