knuckles-cli 0.2.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.
@@ -0,0 +1,3 @@
1
+ """Operator CLI for the Knuckles identity service."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,7 @@
1
+ """Allow ``python -m knuckles_cli``."""
2
+
3
+ import sys
4
+
5
+ from knuckles_cli.cli import main
6
+
7
+ sys.exit(main())
knuckles_cli/api.py ADDED
@@ -0,0 +1,252 @@
1
+ """Thin HTTP client for the Knuckles public and admin endpoints.
2
+
3
+ Deliberately independent of the ``knuckles-client`` SDK (Decision
4
+ #025): the operator has an admin token, not app-client credentials,
5
+ and ``doctor`` needs raw status codes from the discovery endpoints.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ import requests
13
+
14
+ from knuckles_cli import __version__
15
+ from knuckles_cli.errors import (
16
+ ADMIN_API_DISABLED,
17
+ HTTP_ERROR,
18
+ NETWORK_ERROR,
19
+ NOT_LOGGED_IN,
20
+ CliError,
21
+ )
22
+
23
+ _ADMIN_BASE = "/v1/admin/app-clients"
24
+
25
+
26
+ class KnucklesAPI:
27
+ """Calls one Knuckles deployment.
28
+
29
+ Attributes:
30
+ base_url: Knuckles base URL, no trailing slash.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ base_url: str,
36
+ *,
37
+ admin_token: str | None = None,
38
+ timeout: float = 10.0,
39
+ session: requests.Session | None = None,
40
+ ) -> None:
41
+ """Initialize the client.
42
+
43
+ Args:
44
+ base_url: Knuckles base URL.
45
+ admin_token: Operator admin token for ``/v1/admin/*``.
46
+ timeout: Per-request timeout in seconds.
47
+ session: Optional pre-built session.
48
+ """
49
+ self.base_url = base_url.rstrip("/")
50
+ self._admin_token = admin_token
51
+ self._timeout = timeout
52
+ self._session = session or requests.Session()
53
+ self._session.headers["User-Agent"] = f"knuckles-cli/{__version__}"
54
+
55
+ @property
56
+ def has_admin_token(self) -> bool:
57
+ """Whether admin calls can be made.
58
+
59
+ Returns:
60
+ ``True`` when an admin token is configured.
61
+ """
62
+ return self._admin_token is not None
63
+
64
+ def _send(
65
+ self,
66
+ method: str,
67
+ path: str,
68
+ *,
69
+ json: dict[str, Any] | None = None,
70
+ headers: dict[str, str] | None = None,
71
+ ) -> requests.Response:
72
+ """Send one request, converting transport failures.
73
+
74
+ Args:
75
+ method: HTTP verb.
76
+ path: Path under the base URL, leading slash included.
77
+ json: Optional JSON body.
78
+ headers: Optional extra headers.
79
+
80
+ Returns:
81
+ The raw response.
82
+
83
+ Raises:
84
+ CliError: ``NETWORK_ERROR`` if the server is unreachable.
85
+ """
86
+ try:
87
+ return self._session.request(
88
+ method,
89
+ f"{self.base_url}{path}",
90
+ json=json,
91
+ headers=headers,
92
+ timeout=self._timeout,
93
+ )
94
+ except requests.RequestException as exc:
95
+ raise CliError(
96
+ NETWORK_ERROR, f"Could not reach {self.base_url}: {exc}"
97
+ ) from exc
98
+
99
+ def get_public(self, path: str) -> tuple[int, Any]:
100
+ """GET an unauthenticated endpoint, returning status and body.
101
+
102
+ Args:
103
+ path: Path under the base URL.
104
+
105
+ Returns:
106
+ Tuple of HTTP status and parsed JSON (``None`` when the body
107
+ is not JSON).
108
+
109
+ Raises:
110
+ CliError: ``NETWORK_ERROR`` if the server is unreachable.
111
+ """
112
+ response = self._send("GET", path)
113
+ try:
114
+ return response.status_code, response.json()
115
+ except ValueError:
116
+ return response.status_code, None
117
+
118
+ def admin(
119
+ self, method: str, path: str = "", *, json: dict[str, Any] | None = None
120
+ ) -> Any:
121
+ """Call an admin route and return its ``data`` payload.
122
+
123
+ Args:
124
+ method: HTTP verb.
125
+ path: Path under ``/v1/admin/app-clients``.
126
+ json: Optional JSON body.
127
+
128
+ Returns:
129
+ The response's ``data`` value.
130
+
131
+ Raises:
132
+ CliError: ``NOT_LOGGED_IN`` without a token,
133
+ ``ADMIN_API_DISABLED`` when the server's admin surface
134
+ is off, or the server's own error code otherwise.
135
+ """
136
+ if self._admin_token is None:
137
+ raise CliError(
138
+ NOT_LOGGED_IN,
139
+ "No admin token. Run `knuckles login` or set KNUCKLES_ADMIN_TOKEN.",
140
+ )
141
+ response = self._send(
142
+ method,
143
+ f"{_ADMIN_BASE}{path}",
144
+ json=json,
145
+ headers={"X-Admin-Token": self._admin_token},
146
+ )
147
+ try:
148
+ body = response.json()
149
+ except ValueError:
150
+ body = None
151
+ if response.ok and isinstance(body, dict) and "data" in body:
152
+ return body["data"]
153
+
154
+ error = body.get("error") if isinstance(body, dict) else None
155
+ if isinstance(error, dict) and isinstance(error.get("code"), str):
156
+ code = error["code"]
157
+ message = str(error.get("message", ""))
158
+ else:
159
+ code = HTTP_ERROR
160
+ message = f"Unexpected HTTP {response.status_code} from {self.base_url}."
161
+ # Every admin route exists when the surface is on, so a bare
162
+ # NOT_FOUND (not APP_CLIENT_NOT_FOUND) means it is switched off.
163
+ if response.status_code == 404 and code == "NOT_FOUND":
164
+ code = ADMIN_API_DISABLED
165
+ message = (
166
+ "The admin API is disabled on this server. Set "
167
+ "KNUCKLES_ADMIN_TOKEN in the Knuckles environment and redeploy."
168
+ )
169
+ raise CliError(code, message, status_code=response.status_code)
170
+
171
+ def list_apps(self) -> list[dict[str, Any]]:
172
+ """List every tenant.
173
+
174
+ Returns:
175
+ Redacted app-client rows.
176
+ """
177
+ data = self.admin("GET")
178
+ return list(data)
179
+
180
+ def get_app(self, client_id: str) -> dict[str, Any]:
181
+ """Fetch one tenant.
182
+
183
+ Args:
184
+ client_id: The tenant's ``client_id``.
185
+
186
+ Returns:
187
+ The redacted app-client row.
188
+ """
189
+ return dict(self.admin("GET", f"/{client_id}"))
190
+
191
+ def create_app(
192
+ self, *, client_id: str, app_name: str, allowed_origins: list[str]
193
+ ) -> dict[str, Any]:
194
+ """Register a tenant.
195
+
196
+ Args:
197
+ client_id: New ``client_id`` slug.
198
+ app_name: Human-facing name.
199
+ allowed_origins: Origins permitted in redirect URLs.
200
+
201
+ Returns:
202
+ The row plus the one-time ``client_secret``.
203
+ """
204
+ return dict(
205
+ self.admin(
206
+ "POST",
207
+ json={
208
+ "client_id": client_id,
209
+ "app_name": app_name,
210
+ "allowed_origins": allowed_origins,
211
+ },
212
+ )
213
+ )
214
+
215
+ def update_app(self, client_id: str, fields: dict[str, Any]) -> dict[str, Any]:
216
+ """Patch tenant-config columns.
217
+
218
+ Args:
219
+ client_id: The tenant's ``client_id``.
220
+ fields: Column values; ``None`` clears to env fallback.
221
+
222
+ Returns:
223
+ The updated redacted row.
224
+ """
225
+ return dict(self.admin("PATCH", f"/{client_id}", json=fields))
226
+
227
+ def rotate_secret(self, client_id: str) -> dict[str, Any]:
228
+ """Mint a new client secret.
229
+
230
+ Args:
231
+ client_id: The tenant's ``client_id``.
232
+
233
+ Returns:
234
+ ``{"client_id", "client_secret"}``.
235
+ """
236
+ return dict(self.admin("POST", f"/{client_id}/rotate-secret"))
237
+
238
+ def set_origins(self, client_id: str, origins: list[str]) -> dict[str, Any]:
239
+ """Replace a tenant's allowed origins.
240
+
241
+ Args:
242
+ client_id: The tenant's ``client_id``.
243
+ origins: The full new origin list.
244
+
245
+ Returns:
246
+ The updated redacted row.
247
+ """
248
+ return dict(
249
+ self.admin(
250
+ "PUT", f"/{client_id}/origins", json={"allowed_origins": origins}
251
+ )
252
+ )