commypanel 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.
commypanel/__init__.py ADDED
@@ -0,0 +1,78 @@
1
+ """A small client for the HTTP API of a CommyPanel server.
2
+
3
+ List apps, start and follow deployments, start, stop and restart an app, read its logs and manage its
4
+ environment variables. Standard library only, and built to be hard to misuse:
5
+
6
+ * the panel address must be https (plain http only for localhost, and only when asked for);
7
+ * redirects are never followed, so the token cannot be sent to another host;
8
+ * the token is kept out of errors, ``repr`` and formatting;
9
+ * calls have a timeout, bounded retries and a limit on the size of an answer;
10
+ * environment variable values can only be written, because the API never returns them.
11
+
12
+ Create a token in the panel under Settings > API tokens, give it only the abilities it needs, limit it to one
13
+ app and let it expire::
14
+
15
+ import os
16
+ from commypanel import Client
17
+
18
+ client = Client("https://panel.example.com", os.environ["COMMY_TOKEN"])
19
+ deployment = client.start_deployment("shop")
20
+ deployment = client.wait_for_deployment("shop", deployment.number)
21
+ """
22
+
23
+ from ._client import Client, __version__
24
+ from ._errors import (
25
+ ApiError,
26
+ CommyPanelError,
27
+ InsecureURLError,
28
+ InvalidInputError,
29
+ InvalidTokenError,
30
+ InvalidURLError,
31
+ RedirectError,
32
+ ResponseTooLargeError,
33
+ TransportError,
34
+ WaitTimeoutError,
35
+ is_conflict,
36
+ is_forbidden,
37
+ is_not_found,
38
+ is_rate_limited,
39
+ is_unauthorized,
40
+ )
41
+ from ._types import (
42
+ Ability,
43
+ App,
44
+ Deployment,
45
+ DeployStrategy,
46
+ EnvChange,
47
+ EnvKeys,
48
+ Logs,
49
+ Token,
50
+ )
51
+
52
+ __all__ = [
53
+ "Ability",
54
+ "ApiError",
55
+ "App",
56
+ "Client",
57
+ "CommyPanelError",
58
+ "DeployStrategy",
59
+ "Deployment",
60
+ "EnvChange",
61
+ "EnvKeys",
62
+ "InsecureURLError",
63
+ "InvalidInputError",
64
+ "InvalidTokenError",
65
+ "InvalidURLError",
66
+ "Logs",
67
+ "RedirectError",
68
+ "ResponseTooLargeError",
69
+ "Token",
70
+ "TransportError",
71
+ "WaitTimeoutError",
72
+ "__version__",
73
+ "is_conflict",
74
+ "is_forbidden",
75
+ "is_not_found",
76
+ "is_rate_limited",
77
+ "is_unauthorized",
78
+ ]
commypanel/_client.py ADDED
@@ -0,0 +1,546 @@
1
+ """The client: one panel, one token."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http
6
+ import http.client
7
+ import ipaddress
8
+ import json
9
+ import socket
10
+ import ssl
11
+ import time
12
+ import urllib.parse
13
+ from typing import Any, Callable, Dict, List, Optional, Tuple
14
+
15
+ from ._errors import (
16
+ ApiError,
17
+ CommyPanelError,
18
+ InsecureURLError,
19
+ InvalidInputError,
20
+ InvalidTokenError,
21
+ InvalidURLError,
22
+ RedirectError,
23
+ ResponseTooLargeError,
24
+ TransportError,
25
+ WaitTimeoutError,
26
+ )
27
+ from ._types import App, Deployment, EnvChange, EnvKeys, Logs, Token
28
+ from ._validate import check_env_key, check_number, check_slug
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ _BASE_PATH = "/api/v1"
33
+ _DEFAULT_TIMEOUT = 30.0
34
+ _DEFAULT_MAX_BODY = 16 << 20 # 16 MiB: far more than 5000 log lines
35
+ _MAX_ERROR_BODY = 1 << 20
36
+ _DEFAULT_RETRIES = 2
37
+ _MAX_RETRIES = 5
38
+ _MAX_RETRY_WAIT = 30.0
39
+
40
+
41
+ class Client:
42
+ """A client for one CommyPanel server with one token. It keeps no per-call state, so it can be shared between threads.
43
+
44
+ Args:
45
+ base_url: The panel address, ``https://panel.example.com``.
46
+ token: An API token (Settings > API tokens in the panel).
47
+ allow_http_loopback: Allow plain http, but only for localhost, 127.0.0.1 or ::1 (development).
48
+ ca_cert_pem: One more certificate authority to trust, in PEM, besides the system's, for a panel with a
49
+ private CA. There is deliberately no option to skip verification.
50
+ timeout: Seconds one network operation may take (default 30).
51
+ retries: How many times a failed request may be tried again (default 2, at most 5). Only requests that
52
+ are safe to repeat are retried: any request the panel refused with 429, and reading calls that met
53
+ a 502, 503 or 504.
54
+ max_response_bytes: The largest answer the client will read (default 16 MiB).
55
+ user_agent: A name (your tool) to put in front of the library's User-Agent.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ base_url: str,
61
+ token: str,
62
+ *,
63
+ allow_http_loopback: bool = False,
64
+ ca_cert_pem: Optional[str] = None,
65
+ timeout: float = _DEFAULT_TIMEOUT,
66
+ retries: int = _DEFAULT_RETRIES,
67
+ max_response_bytes: int = _DEFAULT_MAX_BODY,
68
+ user_agent: Optional[str] = None,
69
+ ) -> None:
70
+ if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0:
71
+ raise ValueError("commypanel: the timeout must be positive")
72
+
73
+ if not isinstance(retries, int) or isinstance(retries, bool) or not 0 <= retries <= _MAX_RETRIES:
74
+ raise ValueError("commypanel: retries must be between 0 and 5")
75
+
76
+ if not isinstance(max_response_bytes, int) or isinstance(max_response_bytes, bool) or max_response_bytes <= 0:
77
+ raise ValueError("commypanel: the limit must be positive")
78
+
79
+ scheme, netloc, host, port = _check_base_url(base_url, allow_http_loopback)
80
+ _check_token(token)
81
+
82
+ self._scheme = scheme
83
+ self._netloc = netloc
84
+ self._host = host
85
+ self._port = port
86
+ self._token = token
87
+ self._timeout = float(timeout)
88
+ self._retries = retries
89
+ self._max_body = max_response_bytes
90
+ self._agent = "commypanel-python/" + __version__
91
+ self._ssl = _tls_context(ca_cert_pem) if scheme == "https" else None
92
+
93
+ if user_agent and user_agent.strip():
94
+ self._agent = user_agent.strip() + " " + self._agent
95
+
96
+ #: Replaced in tests, so they do not really wait.
97
+ self._sleep: Callable[[float], None] = time.sleep
98
+
99
+ # -- the token never shows ------------------------------------------------------------
100
+
101
+ def __repr__(self) -> str:
102
+ return "Client(base_url=%r, token=<redacted>)" % self.base_url
103
+
104
+ __str__ = __repr__
105
+
106
+ def __getstate__(self) -> Any:
107
+ raise TypeError("commypanel.Client holds a token and cannot be pickled or copied by value")
108
+
109
+ @property
110
+ def base_url(self) -> str:
111
+ """The panel address the client uses."""
112
+ return "%s://%s" % (self._scheme, self._netloc)
113
+
114
+ # -- the API --------------------------------------------------------------------------
115
+
116
+ def token(self) -> Token:
117
+ """The token this client uses: its name, abilities, the apps it is limited to and when it expires.
118
+
119
+ Any valid token may ask. It is a good way to check a token when it is saved.
120
+ """
121
+ _, data = self._request("GET", "/token")
122
+
123
+ return Token.from_dict(_as_dict(data))
124
+
125
+ def list_apps(self) -> List[App]:
126
+ """The apps the token may see (ability ``apps:read``)."""
127
+ _, data = self._request("GET", "/apps")
128
+
129
+ return [App.from_dict(_as_dict(item)) for item in _as_list(data)]
130
+
131
+ def get_app(self, slug: str) -> App:
132
+ """One app (ability ``apps:read``)."""
133
+ _, data = self._request("GET", _app_path(slug))
134
+
135
+ return App.from_dict(_as_dict(data))
136
+
137
+ def list_deployments(self, slug: str, limit: Optional[int] = None) -> List[Deployment]:
138
+ """The newest deployments of an app, newest first (ability ``apps:read``).
139
+
140
+ ``limit`` None uses the panel's default (20); the panel allows at most 50.
141
+ """
142
+ query = {"limit": str(limit)} if limit else None
143
+ _, data = self._request("GET", _app_path(slug, "deployments"), query)
144
+
145
+ return [Deployment.from_dict(_as_dict(item)) for item in _as_list(data)]
146
+
147
+ def get_deployment(self, slug: str, number: int, with_log: bool = False) -> Deployment:
148
+ """One deployment (ability ``apps:read``), with the build log when ``with_log`` is true."""
149
+ check_number(number)
150
+ query = {"log": "1"} if with_log else None
151
+ _, data = self._request("GET", _app_path(slug, "deployments", str(number)), query)
152
+
153
+ return Deployment.from_dict(_as_dict(data))
154
+
155
+ def start_deployment(self, slug: str) -> Deployment:
156
+ """Queue a deployment (ability ``apps:deploy``) and return it at once; follow it with ``wait_for_deployment``.
157
+
158
+ If one is already running the error is a conflict (``is_conflict``) whose ``ApiError.deployment`` is the running one.
159
+ """
160
+ _, data = self._request("POST", _app_path(slug, "deployments"))
161
+
162
+ return Deployment.from_dict(_as_dict(data))
163
+
164
+ def apply_changes(self, slug: str) -> Deployment:
165
+ """Make changed variables, volumes and links take effect from the running version, with no build (ability ``apps:deploy``)."""
166
+ _, data = self._request("POST", _app_path(slug, "apply"))
167
+
168
+ return Deployment.from_dict(_as_dict(data))
169
+
170
+ def start_app(self, slug: str) -> App:
171
+ """Start a stopped app (ability ``apps:control``)."""
172
+ return self._control(slug, "start")
173
+
174
+ def stop_app(self, slug: str) -> App:
175
+ """Stop a running app; visitors see an error until it is started again (ability ``apps:control``)."""
176
+ return self._control(slug, "stop")
177
+
178
+ def restart_app(self, slug: str) -> App:
179
+ """Restart a running app (ability ``apps:control``)."""
180
+ return self._control(slug, "restart")
181
+
182
+ def logs(self, slug: str, tail: Optional[int] = None) -> Logs:
183
+ """The last lines of the running container's output (ability ``apps:logs``).
184
+
185
+ ``tail`` is clamped by the panel to 10..5000 (default 200). Logs often hold secrets, and every read is
186
+ recorded in the panel's audit log.
187
+ """
188
+ query = {"tail": str(tail)} if tail else None
189
+ _, data = self._request("GET", _app_path(slug, "logs"), query)
190
+
191
+ return Logs.from_dict(_as_dict(data))
192
+
193
+ def list_env(self, slug: str) -> EnvKeys:
194
+ """The names of an app's environment variables (ability ``apps:env``). The API never returns values."""
195
+ _, data = self._request("GET", _app_path(slug, "env"))
196
+
197
+ return EnvKeys.from_dict(_as_dict(data))
198
+
199
+ def set_env(self, slug: str, key: str, value: str) -> Tuple[EnvChange, bool]:
200
+ """Set an environment variable (ability ``apps:env``). Returns ``(change, created)``.
201
+
202
+ The change takes effect with ``apply_changes`` or the next deployment. The value is sent, never read back.
203
+ """
204
+ check_env_key(key)
205
+ path = _app_path(slug, "env", key)
206
+
207
+ if not isinstance(value, str):
208
+ raise InvalidInputError("commypanel: a variable's value must be a string")
209
+
210
+ status, data = self._request("PUT", path, None, {"value": value})
211
+
212
+ return EnvChange.from_dict(_as_dict(data)), status == 201
213
+
214
+ def unset_env(self, slug: str, key: str) -> EnvChange:
215
+ """Remove an environment variable (ability ``apps:env``). A variable that is not there is a 404 (``is_not_found``)."""
216
+ check_env_key(key)
217
+ _, data = self._request("DELETE", _app_path(slug, "env", key))
218
+
219
+ return EnvChange.from_dict(_as_dict(data))
220
+
221
+ def wait_for_deployment(
222
+ self,
223
+ slug: str,
224
+ number: int,
225
+ poll: float = 3.0,
226
+ on_update: Optional[Callable[[Deployment], None]] = None,
227
+ timeout: Optional[float] = None,
228
+ ) -> Deployment:
229
+ """Poll a deployment until it is finished and return the final state.
230
+
231
+ Args:
232
+ poll: Seconds between looks (default 3, at least 1).
233
+ on_update: Called with every look.
234
+ timeout: Give up after this many seconds (raises ``WaitTimeoutError``; the deployment carries on in the panel).
235
+
236
+ Check ``succeeded`` (and ``status``) on the result: a deployment can finish as failed or rolled back.
237
+ """
238
+ if not isinstance(poll, (int, float)) or poll < 1:
239
+ poll = 3.0
240
+
241
+ deadline = None if timeout is None else time.monotonic() + timeout
242
+
243
+ while True:
244
+ deployment = self.get_deployment(slug, number)
245
+
246
+ if on_update is not None:
247
+ on_update(deployment)
248
+
249
+ if deployment.finished:
250
+ return deployment
251
+
252
+ wait = float(poll)
253
+
254
+ if deadline is not None:
255
+ remaining = deadline - time.monotonic()
256
+
257
+ if remaining <= 0:
258
+ raise WaitTimeoutError("commypanel: still waiting for deployment #%d" % number)
259
+
260
+ wait = min(wait, remaining)
261
+
262
+ self._sleep(wait)
263
+
264
+ # -- plumbing -------------------------------------------------------------------------
265
+
266
+ def _control(self, slug: str, action: str) -> App:
267
+ _, data = self._request("POST", _app_path(slug, action))
268
+
269
+ return App.from_dict(_as_dict(data))
270
+
271
+ def _request(
272
+ self,
273
+ method: str,
274
+ path: str,
275
+ query: Optional[Dict[str, str]] = None,
276
+ body: Optional[Dict[str, Any]] = None,
277
+ ) -> Tuple[int, Any]:
278
+ payload = None if body is None else json.dumps(body, separators=(",", ":")).encode("utf-8")
279
+ target = _BASE_PATH + path
280
+
281
+ if query:
282
+ target += "?" + urllib.parse.urlencode(query)
283
+
284
+ attempt = 0
285
+
286
+ while True:
287
+ try:
288
+ return self._once(method, target, payload)
289
+ except ApiError as err:
290
+ if attempt >= self._retries or not _retryable(method, err.status):
291
+ raise
292
+
293
+ wait = float(err.retry_after_seconds) if err.retry_after_seconds > 0 else 0.5 * (2**attempt)
294
+ self._sleep(min(wait, _MAX_RETRY_WAIT))
295
+ attempt += 1
296
+
297
+ def _once(self, method: str, target: str, payload: Optional[bytes]) -> Tuple[int, Any]:
298
+ headers = {
299
+ "Authorization": "Bearer " + self._token,
300
+ "Accept": "application/json",
301
+ "User-Agent": self._agent,
302
+ "Connection": "close",
303
+ }
304
+
305
+ if payload is not None:
306
+ headers["Content-Type"] = "application/json"
307
+
308
+ # One connection per call: nothing is shared between calls or threads.
309
+ if self._scheme == "https":
310
+ conn: http.client.HTTPConnection = http.client.HTTPSConnection(
311
+ self._host, self._port, timeout=self._timeout, context=self._ssl
312
+ )
313
+ else:
314
+ conn = http.client.HTTPConnection(self._host, self._port, timeout=self._timeout)
315
+
316
+ try:
317
+ try:
318
+ conn.request(method, target, body=payload, headers=headers)
319
+ resp = conn.getresponse()
320
+ status = resp.status
321
+ retry_after = _retry_after(resp.getheader("Retry-After"))
322
+
323
+ if 300 <= status < 400:
324
+ raise RedirectError(
325
+ "commypanel: the panel answered with a redirect, which is not followed "
326
+ "(check the address, https and www)"
327
+ )
328
+
329
+ limit = min(self._max_body, _MAX_ERROR_BODY) if status >= 400 else self._max_body
330
+ raw = resp.read(limit + 1)
331
+ except CommyPanelError:
332
+ raise
333
+ except (OSError, http.client.HTTPException) as err:
334
+ # The address has no secret in it, but keep the token out of anything quoted.
335
+ message = _scrub(_describe(err), self._token)
336
+ raise TransportError("commypanel: %s %s: %s" % (method, target.split("?")[0], message)) from None
337
+ finally:
338
+ conn.close()
339
+
340
+ if len(raw) > limit:
341
+ raise ResponseTooLargeError("commypanel: the answer is too large")
342
+
343
+ if status >= 400:
344
+ raise _api_error(status, raw, retry_after, self._token)
345
+
346
+ try:
347
+ envelope = json.loads(raw.decode("utf-8"))
348
+ except (ValueError, UnicodeDecodeError):
349
+ envelope = None
350
+
351
+ if not isinstance(envelope, dict) or "data" not in envelope:
352
+ raise CommyPanelError(
353
+ "commypanel: the answer is not the JSON the API gives (is %s a CommyPanel?)" % self.base_url
354
+ )
355
+
356
+ return status, envelope["data"]
357
+
358
+
359
+ # -- helpers ---------------------------------------------------------------------------------
360
+
361
+
362
+ def _check_base_url(raw: str, allow_http_loopback: bool) -> Tuple[str, str, str, int]:
363
+ if not isinstance(raw, str):
364
+ raise InvalidURLError("commypanel: the panel address must look like https://panel.example.com")
365
+
366
+ invalid = InvalidURLError("commypanel: the panel address must look like https://panel.example.com")
367
+
368
+ try:
369
+ parts = urllib.parse.urlsplit(raw.strip())
370
+ host = parts.hostname
371
+ port = parts.port
372
+ except ValueError:
373
+ raise invalid from None
374
+
375
+ if not parts.netloc or not host:
376
+ raise invalid
377
+
378
+ if "@" in parts.netloc or parts.query or parts.fragment or "?" in raw or "#" in raw:
379
+ raise invalid
380
+
381
+ if parts.path not in ("", "/") and parts.path.rstrip("/") != _BASE_PATH:
382
+ raise invalid
383
+
384
+ if parts.scheme == "https":
385
+ pass
386
+ elif parts.scheme == "http":
387
+ if not allow_http_loopback or not _is_loopback(host):
388
+ raise InsecureURLError("commypanel: the panel address must be https")
389
+ else:
390
+ raise InsecureURLError("commypanel: the panel address must be https")
391
+
392
+ return parts.scheme, parts.netloc, host, port if port is not None else (443 if parts.scheme == "https" else 80)
393
+
394
+
395
+ def _is_loopback(host: str) -> bool:
396
+ if host.lower() == "localhost":
397
+ return True
398
+
399
+ try:
400
+ return ipaddress.ip_address(host).is_loopback
401
+ except ValueError:
402
+ return False
403
+
404
+
405
+ def _check_token(token: object) -> None:
406
+ if not isinstance(token, str) or token == "" or len(token) > 512:
407
+ raise InvalidTokenError("commypanel: the token is empty or has characters a token cannot have")
408
+
409
+ for ch in token:
410
+ if ch <= " " or ch == "\x7f":
411
+ raise InvalidTokenError("commypanel: the token is empty or has characters a token cannot have")
412
+
413
+
414
+ def _tls_context(ca_cert_pem: Optional[str]) -> ssl.SSLContext:
415
+ context = ssl.create_default_context() # verifies the certificate and the host name
416
+ context.minimum_version = ssl.TLSVersion.TLSv1_2
417
+
418
+ if ca_cert_pem:
419
+ pem = ca_cert_pem.decode("ascii", "replace") if isinstance(ca_cert_pem, bytes) else ca_cert_pem
420
+
421
+ try:
422
+ context.load_verify_locations(cadata=pem)
423
+ except ssl.SSLError:
424
+ raise ValueError("commypanel: the CA certificate is not valid PEM") from None
425
+
426
+ if "BEGIN CERTIFICATE" not in pem:
427
+ raise ValueError("commypanel: the CA certificate is not valid PEM")
428
+
429
+ return context
430
+
431
+
432
+ def _app_path(slug: str, *rest: str) -> str:
433
+ path = "/apps/" + check_slug(slug)
434
+
435
+ for part in rest:
436
+ path += "/" + part
437
+
438
+ return path
439
+
440
+
441
+ def _retryable(method: str, status: int) -> bool:
442
+ # A 429 means the panel did not do the work, so any call may be repeated; a gateway error is only
443
+ # repeated for calls that read (a write may have happened).
444
+ if status == 429:
445
+ return True
446
+
447
+ if status in (502, 503, 504):
448
+ return method == "GET"
449
+
450
+ return False
451
+
452
+
453
+ def _retry_after(value: Optional[str]) -> int:
454
+ try:
455
+ seconds = int((value or "").strip())
456
+ except ValueError:
457
+ return 0
458
+
459
+ return seconds if seconds > 0 else 0
460
+
461
+
462
+ def _api_error(status: int, raw: bytes, retry_after: int, token: str) -> ApiError:
463
+ try:
464
+ body = json.loads(raw.decode("utf-8"))
465
+ except (ValueError, UnicodeDecodeError):
466
+ body = None
467
+
468
+ # A misbehaving server could echo the Authorization header into its error text, and that text ends up in
469
+ # the caller's logs: nothing the panel says is allowed to carry the token.
470
+ body = _redact(body, token)
471
+
472
+ if isinstance(body, dict):
473
+ error = body.get("error")
474
+ message = body.get("message")
475
+ text = error if isinstance(error, str) and error else (message if isinstance(message, str) and message else "")
476
+
477
+ if text:
478
+ fields: Dict[str, List[str]] = {}
479
+ raw_fields = body.get("errors")
480
+
481
+ if isinstance(raw_fields, dict):
482
+ for name, problems in raw_fields.items():
483
+ if isinstance(problems, list):
484
+ fields[str(name)] = [str(p) for p in problems]
485
+
486
+ deployment = body.get("deployment")
487
+
488
+ return ApiError(
489
+ status,
490
+ text,
491
+ fields,
492
+ Deployment.from_dict(deployment) if isinstance(deployment, dict) else None,
493
+ retry_after,
494
+ )
495
+
496
+ # A proxy or a crash answered with something that is not the API's JSON: say what it was, not what it said.
497
+ try:
498
+ phrase = http.HTTPStatus(status).phrase
499
+ except ValueError:
500
+ phrase = "Error"
501
+
502
+ return ApiError(status, phrase + " (not an answer from the CommyPanel API)", None, None, retry_after)
503
+
504
+
505
+ def _describe(err: BaseException) -> str:
506
+ if isinstance(err, (socket.timeout, TimeoutError)):
507
+ return "timed out"
508
+
509
+ if isinstance(err, ssl.SSLError):
510
+ return str(err) # "certificate verify failed: IP address mismatch ..." says why
511
+
512
+ reason = getattr(err, "reason", None)
513
+
514
+ return str(reason or err) or err.__class__.__name__
515
+
516
+
517
+ def _redact(value: Any, token: str) -> Any:
518
+ """Replaces the token with "[redacted]" in every string of a decoded JSON value (keys too)."""
519
+ if isinstance(value, str):
520
+ return _scrub(value, token)
521
+
522
+ if isinstance(value, list):
523
+ return [_redact(item, token) for item in value]
524
+
525
+ if isinstance(value, dict):
526
+ return {_scrub(str(key), token): _redact(item, token) for key, item in value.items()}
527
+
528
+ return value
529
+
530
+
531
+ def _scrub(text: str, token: str) -> str:
532
+ return text.replace(token, "[redacted]") if token and token in text else text
533
+
534
+
535
+ def _as_dict(data: Any) -> Dict[str, Any]:
536
+ if not isinstance(data, dict):
537
+ raise CommyPanelError("commypanel: reading the answer: an object was expected")
538
+
539
+ return data
540
+
541
+
542
+ def _as_list(data: Any) -> List[Any]:
543
+ if not isinstance(data, list):
544
+ raise CommyPanelError("commypanel: reading the answer: a list was expected")
545
+
546
+ return data
commypanel/_errors.py ADDED
@@ -0,0 +1,104 @@
1
+ """Errors raised by the client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Dict, List, Optional
6
+
7
+ if TYPE_CHECKING: # pragma: no cover
8
+ from ._types import Deployment
9
+
10
+
11
+ class CommyPanelError(Exception):
12
+ """Base class of everything this library raises on purpose."""
13
+
14
+
15
+ class InsecureURLError(CommyPanelError):
16
+ """The panel address is not https (or loopback http, when allowed)."""
17
+
18
+
19
+ class InvalidURLError(CommyPanelError):
20
+ """The panel address is not a plain scheme://host[:port]."""
21
+
22
+
23
+ class InvalidTokenError(CommyPanelError):
24
+ """The token is empty, too long, or has spaces or control characters."""
25
+
26
+
27
+ class InvalidInputError(CommyPanelError):
28
+ """An app name or variable name that cannot be valid; no request was made."""
29
+
30
+
31
+ class ResponseTooLargeError(CommyPanelError):
32
+ """An answer is bigger than the client accepts."""
33
+
34
+
35
+ class RedirectError(CommyPanelError):
36
+ """The panel answered with a redirect. Redirects are never followed, so a token cannot be handed to another address."""
37
+
38
+
39
+ class TransportError(CommyPanelError):
40
+ """The request could not be made or answered (connection, TLS, timeout)."""
41
+
42
+
43
+ class WaitTimeoutError(CommyPanelError):
44
+ """wait_for_deployment gave up waiting; the deployment itself carries on in the panel."""
45
+
46
+
47
+ class ApiError(CommyPanelError):
48
+ """An error answer from the panel."""
49
+
50
+ def __init__(
51
+ self,
52
+ status: int,
53
+ message: str,
54
+ fields: Optional[Dict[str, List[str]]] = None,
55
+ deployment: "Optional[Deployment]" = None,
56
+ retry_after_seconds: int = 0,
57
+ ) -> None:
58
+ super().__init__(status, message)
59
+ self.status = status
60
+ #: The panel's own sentence (its ``error`` key).
61
+ self.message = message
62
+ #: The problems of a 422, by field name.
63
+ self.fields: Dict[str, List[str]] = dict(fields or {})
64
+ #: The deployment that is already running, on a 409 that says so.
65
+ self.deployment = deployment
66
+ #: How long the panel asked to wait, when it did (429), in seconds.
67
+ self.retry_after_seconds = retry_after_seconds
68
+
69
+ def __str__(self) -> str:
70
+ text = "commypanel: %d %s" % (self.status, self.message)
71
+
72
+ for name in sorted(self.fields):
73
+ text += " (%s: %s)" % (name, " ".join(self.fields[name]))
74
+
75
+ return text
76
+
77
+
78
+ def _has_status(err: BaseException, status: int) -> bool:
79
+ return isinstance(err, ApiError) and err.status == status
80
+
81
+
82
+ def is_not_found(err: BaseException) -> bool:
83
+ """A 404: no such app, deployment or variable, or an app the token may not use."""
84
+ return _has_status(err, 404)
85
+
86
+
87
+ def is_unauthorized(err: BaseException) -> bool:
88
+ """A 401: no token, or an invalid, revoked or expired one."""
89
+ return _has_status(err, 401)
90
+
91
+
92
+ def is_forbidden(err: BaseException) -> bool:
93
+ """A 403: the token lacks the ability, or its owner lacks the permission."""
94
+ return _has_status(err, 403)
95
+
96
+
97
+ def is_conflict(err: BaseException) -> bool:
98
+ """A 409: the state does not allow it, for example a deployment is already running (see ``ApiError.deployment``)."""
99
+ return _has_status(err, 409)
100
+
101
+
102
+ def is_rate_limited(err: BaseException) -> bool:
103
+ """A 429."""
104
+ return _has_status(err, 429)
commypanel/_types.py ADDED
@@ -0,0 +1,182 @@
1
+ """The objects the API returns. They never hold secrets, and environment variable values are not among them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any, Dict, List, Optional
8
+
9
+
10
+ class Ability:
11
+ """What a token may do (the strings the API uses)."""
12
+
13
+ READ = "apps:read"
14
+ DEPLOY = "apps:deploy"
15
+ CONTROL = "apps:control"
16
+ LOGS = "apps:logs"
17
+ ENV = "apps:env"
18
+
19
+
20
+ class DeployStrategy:
21
+ """How a new release replaces the running one."""
22
+
23
+ #: The new version starts beside the old one (no downtime).
24
+ ROLLING = "rolling"
25
+ #: The old version stops first, for software that cannot run twice on the same data.
26
+ STOP_FIRST = "stop_first"
27
+
28
+
29
+ def _time(value: Any) -> Optional[datetime]:
30
+ if not isinstance(value, str) or not value:
31
+ return None
32
+
33
+ text = value[:-1] + "+00:00" if value.endswith("Z") else value
34
+
35
+ try:
36
+ return datetime.fromisoformat(text)
37
+ except ValueError:
38
+ return None
39
+
40
+
41
+ def _opt_str(value: Any) -> Optional[str]:
42
+ return value if isinstance(value, str) else None
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Token:
47
+ """The token the client is using."""
48
+
49
+ name: str
50
+ abilities: List[str]
51
+ #: The apps the token is limited to; None means every app its owner may use.
52
+ apps: Optional[List[str]]
53
+ expires_at: Optional[datetime]
54
+ last_used_at: Optional[datetime]
55
+ #: The owner's name.
56
+ owner: str
57
+
58
+ @classmethod
59
+ def from_dict(cls, d: Dict[str, Any]) -> "Token":
60
+ apps = d.get("apps")
61
+
62
+ return cls(
63
+ name=str(d.get("name", "")),
64
+ abilities=[str(a) for a in d.get("abilities") or []],
65
+ apps=None if apps is None else [str(a) for a in apps],
66
+ expires_at=_time(d.get("expires_at")),
67
+ last_used_at=_time(d.get("last_used_at")),
68
+ owner=str(d.get("owner", "")),
69
+ )
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Deployment:
74
+ """One deployment, rollback or "apply changes"."""
75
+
76
+ number: int
77
+ status: str
78
+ stage: Optional[str]
79
+ #: True once it is over, whatever the result. Poll until it is.
80
+ finished: bool
81
+ #: Only meaningful once finished. A watched release can still be rolled back later (status "rolled_back").
82
+ succeeded: bool
83
+ commit: Optional[str]
84
+ commit_message: Optional[str]
85
+ strategy: str
86
+ is_rollback: bool
87
+ error: Optional[str]
88
+ created_at: Optional[datetime]
89
+ finished_at: Optional[datetime]
90
+ url: str
91
+ #: The build log, only when asked for.
92
+ log: str = ""
93
+
94
+ @classmethod
95
+ def from_dict(cls, d: Dict[str, Any]) -> "Deployment":
96
+ return cls(
97
+ number=int(d.get("number", 0)),
98
+ status=str(d.get("status", "")),
99
+ stage=_opt_str(d.get("stage")),
100
+ finished=bool(d.get("finished", False)),
101
+ succeeded=bool(d.get("succeeded", False)),
102
+ commit=_opt_str(d.get("commit")),
103
+ commit_message=_opt_str(d.get("commit_message")),
104
+ strategy=str(d.get("strategy", "")),
105
+ is_rollback=bool(d.get("is_rollback", False)),
106
+ error=_opt_str(d.get("error")),
107
+ created_at=_time(d.get("created_at")),
108
+ finished_at=_time(d.get("finished_at")),
109
+ url=str(d.get("url", "")),
110
+ log=str(d.get("log", "") or ""),
111
+ )
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class App:
116
+ """One app. It never holds secrets."""
117
+
118
+ slug: str
119
+ name: str
120
+ status: str
121
+ stack: Optional[str]
122
+ deploy_strategy: str
123
+ domains: List[str]
124
+ live_deployment: Optional[int]
125
+ latest_deployment: Optional[Deployment]
126
+ created_at: Optional[datetime]
127
+
128
+ @classmethod
129
+ def from_dict(cls, d: Dict[str, Any]) -> "App":
130
+ live = d.get("live_deployment")
131
+ latest = d.get("latest_deployment")
132
+
133
+ return cls(
134
+ slug=str(d.get("slug", "")),
135
+ name=str(d.get("name", "")),
136
+ status=str(d.get("status", "")),
137
+ stack=_opt_str(d.get("stack")),
138
+ deploy_strategy=str(d.get("deploy_strategy", "")),
139
+ domains=[str(x) for x in d.get("domains") or []],
140
+ live_deployment=int(live) if isinstance(live, int) else None,
141
+ latest_deployment=Deployment.from_dict(latest) if isinstance(latest, dict) else None,
142
+ created_at=_time(d.get("created_at")),
143
+ )
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class Logs:
148
+ """The output of an app's running container."""
149
+
150
+ #: False when the app has no running container.
151
+ live: bool
152
+ lines: int
153
+ logs: str
154
+
155
+ @classmethod
156
+ def from_dict(cls, d: Dict[str, Any]) -> "Logs":
157
+ return cls(live=bool(d.get("live", False)), lines=int(d.get("lines", 0)), logs=str(d.get("logs", "") or ""))
158
+
159
+
160
+ @dataclass(frozen=True)
161
+ class EnvKeys:
162
+ """The names of an app's environment variables. Values are never returned by the API."""
163
+
164
+ keys: List[str] = field(default_factory=list)
165
+ #: True when variables, volumes or links changed after the running container was made: call apply_changes.
166
+ pending_changes: bool = False
167
+
168
+ @classmethod
169
+ def from_dict(cls, d: Dict[str, Any]) -> "EnvKeys":
170
+ return cls(keys=[str(k) for k in d.get("keys") or []], pending_changes=bool(d.get("pending_changes", False)))
171
+
172
+
173
+ @dataclass(frozen=True)
174
+ class EnvChange:
175
+ """The answer to setting or removing a variable. The value is not part of it."""
176
+
177
+ key: str
178
+ pending_changes: bool
179
+
180
+ @classmethod
181
+ def from_dict(cls, d: Dict[str, Any]) -> "EnvChange":
182
+ return cls(key=str(d.get("key", "")), pending_changes=bool(d.get("pending_changes", False)))
@@ -0,0 +1,32 @@
1
+ """Names are checked before any request, so an app or variable name cannot change the path."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from ._errors import InvalidInputError
8
+
9
+ # fullmatch, not match with $: "$" would let a trailing newline through.
10
+ _SLUG = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
11
+ _ENV_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}")
12
+
13
+
14
+ def check_slug(slug: object) -> str:
15
+ if not isinstance(slug, str) or _SLUG.fullmatch(slug) is None:
16
+ raise InvalidInputError("commypanel: invalid app or variable name")
17
+
18
+ return slug
19
+
20
+
21
+ def check_env_key(key: object) -> str:
22
+ if not isinstance(key, str) or _ENV_KEY.fullmatch(key) is None:
23
+ raise InvalidInputError("commypanel: invalid app or variable name")
24
+
25
+ return key
26
+
27
+
28
+ def check_number(number: object) -> int:
29
+ if not isinstance(number, int) or isinstance(number, bool) or number < 1:
30
+ raise InvalidInputError("commypanel: invalid app or variable name")
31
+
32
+ return number
commypanel/py.typed ADDED
File without changes
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: commypanel
3
+ Version: 0.1.0
4
+ Summary: A small, dependency-free client for the CommyPanel HTTP API.
5
+ Author: CommyPanel contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/CommyPanel/commypanel-python
8
+ Project-URL: Source, https://github.com/CommyPanel/commypanel-python
9
+ Project-URL: Issues, https://github.com/CommyPanel/commypanel-python/issues
10
+ Project-URL: Panel, https://github.com/CommyPanel/panel
11
+ Keywords: commypanel,deploy,api-client,self-hosted
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # commypanel-python
28
+
29
+ A small Python client for the HTTP API of a [CommyPanel](https://github.com/CommyPanel/panel) server: list
30
+ apps, start and follow deployments, start, stop and restart an app, read its logs and manage its
31
+ environment variables.
32
+
33
+ - **No dependencies.** Python standard library only, Python 3.9 or newer. Fully typed (`py.typed`).
34
+ - **Hard to misuse.** https only, no redirects, bounded retries and answers, and the token kept out of
35
+ errors and `repr`. See [Security](#security).
36
+ - **Matches the API.** `testdata/openapi.yaml` is a copy of the panel's API description, and a test fails
37
+ when the API gains a call this library does not have.
38
+
39
+ ```bash
40
+ pip install commypanel
41
+ ```
42
+
43
+ (Until the first release is on PyPI, install from a checkout: `pip install .`.)
44
+
45
+ ## Use
46
+
47
+ Create a token in the panel under **Settings > API tokens**. Give it only what it needs (for a deploy job:
48
+ `apps:deploy` and `apps:read`), limit it to one app, and let it expire.
49
+
50
+ ```python
51
+ import os
52
+ from commypanel import Client, is_conflict
53
+
54
+ client = Client("https://panel.example.com", os.environ["COMMY_TOKEN"])
55
+
56
+ try:
57
+ deployment = client.start_deployment("shop")
58
+ except Exception as err:
59
+ if is_conflict(err): # one is already running: err.deployment is that one
60
+ raise SystemExit("a deployment is already running: #%d" % err.deployment.number)
61
+ raise
62
+
63
+ deployment = client.wait_for_deployment(
64
+ "shop", deployment.number, poll=3, on_update=lambda d: print(d.status), timeout=600
65
+ )
66
+
67
+ if not deployment.succeeded:
68
+ raise SystemExit("the deployment ended as %s: %s" % (deployment.status, deployment.error))
69
+ ```
70
+
71
+ Errors from the panel are `commypanel.ApiError` (with `status`, `message`, `fields`, `deployment` and
72
+ `retry_after_seconds`); test them with `is_not_found`, `is_forbidden`, `is_conflict`, `is_unauthorized` and
73
+ `is_rate_limited`. Everything this library raises on purpose derives from `commypanel.CommyPanelError`.
74
+
75
+ | Method | API call | Ability |
76
+ |---|---|---|
77
+ | `token()` | `GET /token` | none |
78
+ | `list_apps()`, `get_app(slug)` | `GET /apps`, `GET /apps/{slug}` | `apps:read` |
79
+ | `list_deployments(slug, limit=None)`, `get_deployment(slug, number, with_log=False)` | `GET /apps/{slug}/deployments[/{n}]` | `apps:read` |
80
+ | `start_deployment(slug)`, `apply_changes(slug)` | `POST /apps/{slug}/deployments`, `/apply` | `apps:deploy` |
81
+ | `start_app(slug)`, `stop_app(slug)`, `restart_app(slug)` | `POST /apps/{slug}/start`, `/stop`, `/restart` | `apps:control` |
82
+ | `logs(slug, tail=None)` | `GET /apps/{slug}/logs` | `apps:logs` |
83
+ | `list_env(slug)`, `set_env(slug, key, value)`, `unset_env(slug, key)` | `GET`, `PUT`, `DELETE /apps/{slug}/env[/{key}]` | `apps:env` |
84
+ | `wait_for_deployment(slug, number, poll=3, on_update=None, timeout=None)` | polls `GET .../deployments/{n}` | `apps:read` |
85
+
86
+ Environment variable **values are write-only**: the API never returns them, so `list_env` gives names, and
87
+ `set_env` returns `(change, created)`.
88
+
89
+ ## Security
90
+
91
+ - **https only.** `Client` refuses any other address. `allow_http_loopback=True` allows plain http for
92
+ `localhost`, `127.0.0.1` and `::1` only, for development.
93
+ - **TLS is always verified**, including the host name. There is no option to skip it. For a panel with a
94
+ private CA pass `ca_cert_pem=` (a PEM string).
95
+ - **Redirects are never followed**, so the token cannot be handed to another address; a redirect raises
96
+ `RedirectError`.
97
+ - **The token stays out of sight.** It is only ever in the `Authorization` header: not in URLs, error
98
+ messages, `repr()`, `str()` or formatting, and a `Client` cannot be pickled.
99
+ - **Bounded.** A timeout (30 s per network operation), at most 2 retries (never for a write that may have
100
+ happened: only a 429, and gateway errors for reads), `Retry-After` capped at 30 s, answers capped at
101
+ 16 MiB.
102
+ - **Names are checked before any request**, so an app or variable name cannot change the path.
103
+ - **No dependencies and no install-time code**: nothing runs when you install it.
104
+
105
+ Report a security problem privately, as described in [SECURITY.md](SECURITY.md).
106
+
107
+ ## Compatibility
108
+
109
+ This library speaks API `v1` (`/api/v1`) of CommyPanel 0.10 and later. It needs Python 3.9 or newer. A
110
+ `Client` keeps no state between calls, so one can be shared between threads.
111
+
112
+ ## Development
113
+
114
+ ```bash
115
+ scripts/sync-spec.sh ../../commypanel # copy the API description from the panel repository
116
+ python3 -m unittest discover -s tests -v # no test dependencies
117
+ ```
118
+
119
+ `tests/fixtures/tls` holds throwaway test-only certificates (see the README there).
120
+
121
+ ## Publishing
122
+
123
+ Not yet published to PyPI. When it is, it will be from CI with PyPI trusted publishing (no long-lived
124
+ token) and signed attestations, set up as a deliberate step of its own.
125
+
126
+ MIT licensed.
@@ -0,0 +1,11 @@
1
+ commypanel/__init__.py,sha256=mczQ2jtXwbjxCAdJJNiHLIFgmiuxVVHJPzlkNaqq8ZY,2033
2
+ commypanel/_client.py,sha256=-OnxDTEjYBLDg1kSayIOWuu5Lt7bT2ZUQAz3FEK2ET8,19976
3
+ commypanel/_errors.py,sha256=Ww-roa3p9TSjLOlUA3B73B37evmcAh2wZjNOkAK8IVc,3259
4
+ commypanel/_types.py,sha256=vfx56EflOrWA14NZ2uuzzfR6yh3IXBJqNj5Y3-vlk_o,5625
5
+ commypanel/_validate.py,sha256=fvqbnSprjXusXzJVIdAWAHaHYc4w0RMVsHfjhcEPO8w,974
6
+ commypanel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ commypanel-0.1.0.dist-info/licenses/LICENSE,sha256=fokeHD8SuNfh4j7f80ZZqcgQjnN2pISV3Z2i6lKz5sY,1080
8
+ commypanel-0.1.0.dist-info/METADATA,sha256=dIPjZCsZj-uzyyOlDs-R1035tDxx5Jyg3B_tNdZ57Qk,5863
9
+ commypanel-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ commypanel-0.1.0.dist-info/top_level.txt,sha256=TRGbXltbXa7EhVzs4aHYdUuVa0r9nplsYSiUvvjBCpE,11
11
+ commypanel-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CommyPanel contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ commypanel