kasm-sdk 0.1.188__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.
kasm_sdk/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ """Kasm Workspaces API client for Python.
2
+
3
+ from kasm_sdk import Kasm
4
+
5
+ kasm = Kasm("https://kasm.example.com", api_key=key, api_secret=secret)
6
+ img = kasm.admin.catalog.images.get(image_id)
7
+
8
+ The groups and methods follow kcli's command tree (docs/sdk-design.md).
9
+ They, kasm_sdk.models (the Pydantic models of the spec's schemas),
10
+ kasm_sdk._schema and the problem types' error classes are generated from
11
+ the official OpenAPI spec and are never hand-edited.
12
+ """
13
+
14
+ from . import _problems, models
15
+ from ._client import AsyncKasm, Kasm
16
+ from ._problems import * # noqa: F403 (the problem types' error classes)
17
+ from ._profile import KasmProfileError
18
+ from ._transport import OMIT, FileInput, Omit, TokenSource
19
+ from .errors import (
20
+ BadRequestError,
21
+ ConflictError,
22
+ FieldError,
23
+ ForbiddenError,
24
+ KasmConnectionError,
25
+ KasmError,
26
+ KasmResponseError,
27
+ NotFoundError,
28
+ PayloadTooLargeError,
29
+ RateLimitedError,
30
+ ServerError,
31
+ UnauthenticatedError,
32
+ ValidationError,
33
+ )
34
+
35
+ from ._version import __version__
36
+
37
+ __all__ = [
38
+ "__version__",
39
+ "OMIT",
40
+ "AsyncKasm",
41
+ "BadRequestError",
42
+ "ConflictError",
43
+ "FieldError",
44
+ "FileInput",
45
+ "ForbiddenError",
46
+ "Kasm",
47
+ "KasmConnectionError",
48
+ "KasmError",
49
+ "KasmProfileError",
50
+ "KasmResponseError",
51
+ "NotFoundError",
52
+ "Omit",
53
+ "PayloadTooLargeError",
54
+ "RateLimitedError",
55
+ "ServerError",
56
+ "TokenSource",
57
+ "UnauthenticatedError",
58
+ "ValidationError",
59
+ "models",
60
+ ]
61
+ __all__ += _problems.__all__
kasm_sdk/_base.py ADDED
@@ -0,0 +1,47 @@
1
+ """The models' base class: Pydantic's BaseModel, with secret fields masked
2
+ when a model is printed (docs/sdk-design.md, decision 8). The fields are
3
+ the ones kcli keeps out of its tables, listed in _schema.SECRETS, and in a
4
+ dict a model holds, the keys the same rule names (_schema.SECRET_PATTERNS).
5
+ The values themselves, model_dump and the JSON sent are untouched."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any, Iterable
11
+
12
+ from pydantic import BaseModel
13
+
14
+ from ._schema import SECRET_PATTERNS, SECRETS
15
+
16
+ MASKED = "***"
17
+ _SECRET, _NOT_SECRET, _CREDENTIAL = (re.compile(p) for p in SECRET_PATTERNS)
18
+
19
+
20
+ def _secret_key(key: str, value: Any) -> bool:
21
+ if value is None:
22
+ return False
23
+ if _CREDENTIAL.search(key):
24
+ return True
25
+ return isinstance(value, str) and value != "" and bool(_SECRET.search(key)) and not _NOT_SECRET.search(key)
26
+
27
+
28
+ def masked(value: Any) -> Any:
29
+ """A copy of a dict or list with every secret key masked, at any depth;
30
+ any other value as it is."""
31
+ if isinstance(value, dict):
32
+ return {k: MASKED if isinstance(k, str) and _secret_key(k, v) else masked(v) for k, v in value.items()}
33
+ if isinstance(value, list):
34
+ return [masked(v) for v in value]
35
+ return value
36
+
37
+
38
+ class KasmModel(BaseModel):
39
+ """The base of every model in kasm_sdk.models."""
40
+
41
+ def __repr_args__(self) -> Iterable[tuple[str | None, Any]]:
42
+ secret = SECRETS.get(type(self).__name__, frozenset())
43
+ for name, value in super().__repr_args__():
44
+ if name in secret and value is not None and value != "":
45
+ yield name, MASKED
46
+ else:
47
+ yield name, masked(value)
kasm_sdk/_client.py ADDED
@@ -0,0 +1,284 @@
1
+ """Kasm and AsyncKasm: the clients, whose attributes are the API's groups."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from ._profile import AsyncProfileTokens, ProfileTokens, arun_kcli, from_env, options, run_kcli
10
+ from ._services import AsyncServices, Services
11
+ from ._transport import OMIT, AsyncTransport, Auth, Omit, Transport, TokenSource, finish, prepare
12
+ from .errors import UnauthenticatedError
13
+
14
+ _LOGIN = "auth.login.password"
15
+ _SECOND_FACTOR = ("totp_required", "webauthn_required")
16
+
17
+
18
+ class Kasm(Services):
19
+ """A Kasm Workspaces API client. Its attributes are the API's groups, as
20
+ in kcli::
21
+
22
+ kasm = Kasm("https://kasm.example.com", api_key=key, api_secret=secret)
23
+ img = kasm.admin.catalog.images.get(image_id)
24
+ for zone in kasm.admin.infrastructure.zones.iter():
25
+ ...
26
+
27
+ Give one of api_key and api_secret, token, or token_source. With no URL
28
+ and no credentials, the client is the environment's (KASM_URL,
29
+ KASM_API_KEY, KASM_API_KEY_SECRET) when it gives all three, otherwise
30
+ kcli's active profile (from_profile). timeout is per request, in seconds
31
+ (None for none; 30 by default, or the profile's); verify is httpx's
32
+ (False only for test boxes). An http_client given is used as is and not
33
+ closed.
34
+ retries (0, off, by default) is how many times a GET, PUT or DELETE
35
+ refused with 429 or 503 is sent again, after the server's Retry-After
36
+ (up to 60 s; a longer one is not waited for) or an exponential backoff.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ base_url: str | None = None,
42
+ *,
43
+ api_key: str | None = None,
44
+ api_secret: str | None = None,
45
+ token: str | None = None,
46
+ token_source: TokenSource | None = None,
47
+ timeout: float | None | Omit = OMIT,
48
+ verify: bool | str | Omit = OMIT,
49
+ user_agent: str | None = None,
50
+ http_client: httpx.Client | None = None,
51
+ retries: int = 0,
52
+ kcli: str = "kcli",
53
+ ) -> None:
54
+ if base_url is None and api_key is None and api_secret is None and token is None and token_source is None:
55
+ out = from_env() or run_kcli(kcli, None)
56
+ base_url, api_key, api_secret, token_source = _profile_auth(out, ProfileTokens, kcli)
57
+ timeout, verify = _profile_settings(out, timeout, verify)
58
+ elif base_url is None:
59
+ raise ValueError("base_url is required with credentials")
60
+ auth = Auth(api_key=api_key, api_secret=api_secret, token=token, token_source=token_source)
61
+ self._transport = Transport(
62
+ base_url,
63
+ auth,
64
+ timeout=30.0 if isinstance(timeout, Omit) else timeout,
65
+ verify=True if isinstance(verify, Omit) else verify,
66
+ user_agent=user_agent,
67
+ http_client=http_client,
68
+ retries=retries,
69
+ )
70
+ super().__init__(self._transport)
71
+
72
+ @classmethod
73
+ def from_profile(cls, name: str | None = None, *, kcli: str = "kcli", **opts: Any) -> Kasm:
74
+ """A client for a kcli profile: name, or kcli's choice (KCLI_PROFILE,
75
+ then the active profile), resolved as kcli does, environment
76
+ included. kcli supplies the URL, its timeout and TLS setting (opts
77
+ given here win), and the credential: an API key, or a password
78
+ profile's session token, which kcli renews when it expires or the
79
+ server refuses it. With no name, an environment that gives the URL
80
+ and API key in full (KASM_URL, KASM_API_KEY, KASM_API_KEY_SECRET) is
81
+ used without kcli. kcli is the executable to run; the SDK never
82
+ reads its secret store itself."""
83
+ out = (from_env() if name is None else None) or run_kcli(kcli, name)
84
+ base_url, api_key, api_secret, token_source = _profile_auth(out, ProfileTokens, kcli)
85
+ return cls(base_url, api_key=api_key, api_secret=api_secret, token_source=token_source, **options(out, opts))
86
+
87
+ @property
88
+ def base_url(self) -> str:
89
+ """The deployment this client talks to."""
90
+ return self._transport.base_url
91
+
92
+ def request(
93
+ self,
94
+ method: str,
95
+ path: str,
96
+ *,
97
+ params: dict[str, Any] | None = None,
98
+ query: dict[str, Any] | None = None,
99
+ json: Any = OMIT,
100
+ headers: dict[str, str] | None = None,
101
+ ) -> Any:
102
+ """Send any operation by method and path, for what the typed methods
103
+ do not cover, with the client's auth and error handling. It returns
104
+ the decoded JSON body, or None when there is none. headers are extra
105
+ request headers (Idempotency-Key, say); the client's own, auth
106
+ included, are set over them."""
107
+ op = f"{method.upper()} {path}"
108
+ req = prepare(self._transport.base_url, op, method.upper(), path, params=params, query=query, raw=json)
109
+ req.headers = headers or {}
110
+ response = self._transport.send(req)
111
+ body, err = self._transport._read(response)
112
+ empty = response.status_code == 204 or (response.is_success and not body and err is None)
113
+ return finish(op, response, body, err, "none" if empty else "json", None)
114
+
115
+ @classmethod
116
+ def login(cls, base_url: str, username: str, password: str, **options: Any) -> Kasm:
117
+ """Sign in with a username and password and return a client acting as
118
+ that user, which the self-service operations need. options are the
119
+ constructor's, without the credentials. A user who must also give a
120
+ second factor gets an UnauthenticatedError: password sign-in cannot
121
+ answer the challenge."""
122
+ t = Transport(
123
+ base_url,
124
+ Auth.none(),
125
+ **{k: options[k] for k in ("timeout", "verify", "user_agent", "http_client", "retries") if k in options},
126
+ )
127
+ try:
128
+ req = prepare(t.base_url, _LOGIN, "POST", "/api/auth/login", raw={"username": username, "password": password})
129
+ response = t.send(req)
130
+ out = finish(_LOGIN, response, *t._read(response), "json", None)
131
+ finally:
132
+ t.close()
133
+ return cls(base_url, token=_session_token(out, response), **options)
134
+
135
+ def close(self) -> None:
136
+ """Close the client's connections (not an http_client it was given)."""
137
+ self._transport.close()
138
+
139
+ def __enter__(self) -> Kasm:
140
+ return self
141
+
142
+ def __exit__(self, *exc: object) -> None:
143
+ self.close()
144
+
145
+ def __repr__(self) -> str:
146
+ return f"Kasm({self.base_url!r})"
147
+
148
+
149
+ class AsyncKasm(AsyncServices):
150
+ """The async Kasm client: Kasm's methods, awaited, and async iterators::
151
+
152
+ async with AsyncKasm("https://kasm.example.com", api_key=key, api_secret=secret) as kasm:
153
+ img = await kasm.admin.catalog.images.get(image_id)
154
+ async for zone in kasm.admin.infrastructure.zones.iter():
155
+ ...
156
+ """
157
+
158
+ def __init__(
159
+ self,
160
+ base_url: str | None = None,
161
+ *,
162
+ api_key: str | None = None,
163
+ api_secret: str | None = None,
164
+ token: str | None = None,
165
+ token_source: TokenSource | None = None,
166
+ timeout: float | None | Omit = OMIT,
167
+ verify: bool | str | Omit = OMIT,
168
+ user_agent: str | None = None,
169
+ http_client: httpx.AsyncClient | None = None,
170
+ retries: int = 0,
171
+ kcli: str = "kcli",
172
+ ) -> None:
173
+ if base_url is None and api_key is None and api_secret is None and token is None and token_source is None:
174
+ # Constructing cannot await: kcli runs here, blocking, once.
175
+ out = from_env() or run_kcli(kcli, None)
176
+ base_url, api_key, api_secret, token_source = _profile_auth(out, AsyncProfileTokens, kcli)
177
+ timeout, verify = _profile_settings(out, timeout, verify)
178
+ elif base_url is None:
179
+ raise ValueError("base_url is required with credentials")
180
+ auth = Auth(api_key=api_key, api_secret=api_secret, token=token, token_source=token_source)
181
+ self._transport = AsyncTransport(
182
+ base_url,
183
+ auth,
184
+ timeout=30.0 if isinstance(timeout, Omit) else timeout,
185
+ verify=True if isinstance(verify, Omit) else verify,
186
+ user_agent=user_agent,
187
+ http_client=http_client,
188
+ retries=retries,
189
+ )
190
+ super().__init__(self._transport)
191
+
192
+ @classmethod
193
+ async def from_profile(cls, name: str | None = None, *, kcli: str = "kcli", **opts: Any) -> AsyncKasm:
194
+ """Kasm.from_profile, awaited."""
195
+ out = (from_env() if name is None else None) or await arun_kcli(kcli, name)
196
+ base_url, api_key, api_secret, token_source = _profile_auth(out, AsyncProfileTokens, kcli)
197
+ return cls(base_url, api_key=api_key, api_secret=api_secret, token_source=token_source, **options(out, opts))
198
+
199
+ @property
200
+ def base_url(self) -> str:
201
+ """The deployment this client talks to."""
202
+ return self._transport.base_url
203
+
204
+ async def request(
205
+ self,
206
+ method: str,
207
+ path: str,
208
+ *,
209
+ params: dict[str, Any] | None = None,
210
+ query: dict[str, Any] | None = None,
211
+ json: Any = OMIT,
212
+ headers: dict[str, str] | None = None,
213
+ ) -> Any:
214
+ """Kasm.request, awaited."""
215
+ op = f"{method.upper()} {path}"
216
+ req = prepare(self._transport.base_url, op, method.upper(), path, params=params, query=query, raw=json)
217
+ req.headers = headers or {}
218
+ response = await self._transport.send(req)
219
+ body, err = await self._transport._read(response)
220
+ empty = response.status_code == 204 or (response.is_success and not body and err is None)
221
+ return finish(op, response, body, err, "none" if empty else "json", None)
222
+
223
+ @classmethod
224
+ async def login(cls, base_url: str, username: str, password: str, **options: Any) -> AsyncKasm:
225
+ """Kasm.login, awaited."""
226
+ t = AsyncTransport(
227
+ base_url,
228
+ Auth.none(),
229
+ **{k: options[k] for k in ("timeout", "verify", "user_agent", "http_client", "retries") if k in options},
230
+ )
231
+ try:
232
+ req = prepare(t.base_url, _LOGIN, "POST", "/api/auth/login", raw={"username": username, "password": password})
233
+ response = await t.send(req)
234
+ out = finish(_LOGIN, response, *(await t._read(response)), "json", None)
235
+ finally:
236
+ await t.aclose()
237
+ return cls(base_url, token=_session_token(out, response), **options)
238
+
239
+ async def aclose(self) -> None:
240
+ """Close the client's connections (not an http_client it was given)."""
241
+ await self._transport.aclose()
242
+
243
+ async def __aenter__(self) -> AsyncKasm:
244
+ return self
245
+
246
+ async def __aexit__(self, *exc: object) -> None:
247
+ await self.aclose()
248
+
249
+ def __repr__(self) -> str:
250
+ return f"AsyncKasm({self.base_url!r})"
251
+
252
+
253
+ def _session_token(out: Any, response: httpx.Response) -> str:
254
+ """The session token from a sign-in reply, or the error it amounts to."""
255
+ outcome = out.get("outcome") if isinstance(out, dict) else None
256
+ if outcome in _SECOND_FACTOR:
257
+ raise UnauthenticatedError(
258
+ _LOGIN,
259
+ 401,
260
+ response.headers,
261
+ title="Second factor required",
262
+ detail=f"this user must also give a second factor ({outcome.removesuffix('_required')}), "
263
+ "which password sign-in does not do; use an API key",
264
+ )
265
+ token = out.get("token") if isinstance(out, dict) else None
266
+ if not isinstance(token, str) or not token:
267
+ raise UnauthenticatedError(
268
+ _LOGIN, 401, response.headers, detail=f'the deployment answered without a session token (outcome "{outcome}")'
269
+ )
270
+ return token
271
+
272
+
273
+ def _profile_auth(out: dict[str, Any], tokens: Any, kcli: str) -> tuple[str, str | None, str | None, Any]:
274
+ """The URL and credential of kcli's answer (or the environment's): an
275
+ API key pair, or a token source that asks kcli again."""
276
+ if out["auth"] == "api_key":
277
+ return out["url"], out["api_key"], out["api_key_secret"], None
278
+ return out["url"], None, None, tokens(kcli, out["profile"], out)
279
+
280
+
281
+ def _profile_settings(out: dict[str, Any], timeout: Any, verify: Any) -> tuple[Any, Any]:
282
+ """timeout and verify, from kcli's answer where they were not given."""
283
+ opts = options(out, {k: v for k, v in (("timeout", timeout), ("verify", verify)) if not isinstance(v, Omit)})
284
+ return opts.get("timeout", OMIT), opts.get("verify", OMIT)
kasm_sdk/_problems.py ADDED
@@ -0,0 +1,129 @@
1
+ # Code generated by sdk-generator/internal/sdkgen from openapi/spec.json; DO NOT EDIT.
2
+ # Spec sha256 731723cbd5b1bd7ca6f73cb98eabdd70b9fcd82d12a8231dbe1e6c3d4ae34475.
3
+
4
+ """The error classes of the problem types whose schemas add fields."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ from .errors import BadRequestError, ConflictError, KasmError
11
+ from .models import (
12
+ CaptchaRequiredProblem,
13
+ EgressSelectionRequiredProblem,
14
+ ImageIncompatibleProblem,
15
+ LastEnabledConnectionProxyProblem,
16
+ LaunchConfigRequiredProblem,
17
+ NoResourcesProblem,
18
+ PersistentProfileModeProblem,
19
+ RdpClientRequiredProblem,
20
+ SessionStartingProblem,
21
+ )
22
+
23
+
24
+ class CaptchaRequiredError(ConflictError):
25
+ """409 captcha-required: A cast claim needs a solved CAPTCHA (missing, failed, or the link requires one the deployment has not configured). ``captcha_type`` and ``recaptcha_site_key`` are what the launcher needs to render the widget; both are ``null`` when no verifier is configured."""
26
+
27
+ @property
28
+ def problem(self) -> CaptchaRequiredProblem:
29
+ """The body, with the fields the problem type adds."""
30
+ return self._problem
31
+
32
+
33
+ class EgressSelectionRequiredError(ConflictError):
34
+ """409 egress-selection-required: The caller has egress gateways or providers to choose from and chose none."""
35
+
36
+ @property
37
+ def problem(self) -> EgressSelectionRequiredProblem:
38
+ """The body, with the fields the problem type adds."""
39
+ return self._problem
40
+
41
+
42
+ class ImageIncompatibleError(ConflictError):
43
+ """409 image-incompatible: Every host holding the image holds a build made for an older Kasm release than this backend supports."""
44
+
45
+ @property
46
+ def problem(self) -> ImageIncompatibleProblem:
47
+ """The body, with the fields the problem type adds."""
48
+ return self._problem
49
+
50
+
51
+ class LastEnabledConnectionProxyError(ConflictError):
52
+ """409 last-enabled-connection-proxy: Disabling this proxy would leave sessions without an enabled proxy of its type in its zone. Nothing was changed; resend with ``force`` (and optionally ``stop_sessions``) to proceed."""
53
+
54
+ @property
55
+ def problem(self) -> LastEnabledConnectionProxyProblem:
56
+ """The body, with the fields the problem type adds."""
57
+ return self._problem
58
+
59
+
60
+ class LaunchConfigRequiredError(ConflictError):
61
+ """409 launch-config-required: The image has a launch form and the request did not satisfy it."""
62
+
63
+ @property
64
+ def problem(self) -> LaunchConfigRequiredProblem:
65
+ """The body, with the fields the problem type adds."""
66
+ return self._problem
67
+
68
+
69
+ class NoResourcesError(ConflictError):
70
+ """409 no-resources: No server or agent can take the session right now. ``reason`` names the refusing server or the missing capacity and is included only for an administrator; ordinary users get the generic ``detail`` alone."""
71
+
72
+ @property
73
+ def problem(self) -> NoResourcesProblem:
74
+ """The body, with the fields the problem type adds."""
75
+ return self._problem
76
+
77
+
78
+ class PersistentProfileModeError(BadRequestError):
79
+ """400 persistent-profile-mode-unavailable: The requested ``persistent_profile_mode`` is not one the image offers; ``persistent_profile_modes`` lists the modes it does."""
80
+
81
+ @property
82
+ def problem(self) -> PersistentProfileModeProblem:
83
+ """The body, with the fields the problem type adds."""
84
+ return self._problem
85
+
86
+
87
+ class RdpClientRequiredError(ConflictError):
88
+ """409 rdp-client-required: The image leaves the RDP client to the caller and the request named none (or one that is not offered). ``rdp_client_types`` lists the accepted values."""
89
+
90
+ @property
91
+ def problem(self) -> RdpClientRequiredProblem:
92
+ """The body, with the fields the problem type adds."""
93
+ return self._problem
94
+
95
+
96
+ class SessionStartingError(ConflictError):
97
+ """409 session-starting: The session exists but is not running yet. Retrying the same request shortly is the expected response; it neither creates another session nor consumes another slot."""
98
+
99
+ @property
100
+ def problem(self) -> SessionStartingProblem:
101
+ """The body, with the fields the problem type adds."""
102
+ return self._problem
103
+
104
+
105
+ # The problem types by `type`: their class, the status it is raised for, and
106
+ # the model of the body.
107
+ PROBLEMS: dict[str, tuple[type[KasmError], int, Any]] = {
108
+ "captcha-required": (CaptchaRequiredError, 409, CaptchaRequiredProblem),
109
+ "egress-selection-required": (EgressSelectionRequiredError, 409, EgressSelectionRequiredProblem),
110
+ "image-incompatible": (ImageIncompatibleError, 409, ImageIncompatibleProblem),
111
+ "last-enabled-connection-proxy": (LastEnabledConnectionProxyError, 409, LastEnabledConnectionProxyProblem),
112
+ "launch-config-required": (LaunchConfigRequiredError, 409, LaunchConfigRequiredProblem),
113
+ "no-resources": (NoResourcesError, 409, NoResourcesProblem),
114
+ "persistent-profile-mode-unavailable": (PersistentProfileModeError, 400, PersistentProfileModeProblem),
115
+ "rdp-client-required": (RdpClientRequiredError, 409, RdpClientRequiredProblem),
116
+ "session-starting": (SessionStartingError, 409, SessionStartingProblem),
117
+ }
118
+
119
+ __all__ = [
120
+ "CaptchaRequiredError",
121
+ "EgressSelectionRequiredError",
122
+ "ImageIncompatibleError",
123
+ "LastEnabledConnectionProxyError",
124
+ "LaunchConfigRequiredError",
125
+ "NoResourcesError",
126
+ "PersistentProfileModeError",
127
+ "RdpClientRequiredError",
128
+ "SessionStartingError",
129
+ ]