entitybind 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.
entitybind/context.py ADDED
@@ -0,0 +1,100 @@
1
+ """Per-invocation context shared by every command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections.abc import Mapping
7
+
8
+ from entitybind.credentials import (
9
+ CredentialStore,
10
+ ResolvedCredential,
11
+ parse_iso,
12
+ resolve_credential,
13
+ )
14
+ from entitybind.device import refresh_credential
15
+ from entitybind.errors import AuthError
16
+ from entitybind.http import DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, ApiClient
17
+ from entitybind.products import CORE, Product, product_named, resolve_base_url
18
+ from entitybind.runtime import Output, Runtime
19
+
20
+ # Refresh a stored OAuth access token this long before it expires.
21
+ REFRESH_MARGIN_SECONDS = 60.0
22
+
23
+
24
+ class Context:
25
+ def __init__(self, runtime: Runtime, args: argparse.Namespace) -> None:
26
+ self.runtime = runtime
27
+ self.args = args
28
+ self.output = Output(runtime, json_mode=bool(getattr(args, "json", False)))
29
+ self._store: CredentialStore | None = None
30
+
31
+ @property
32
+ def env(self) -> Mapping[str, str]:
33
+ return self.runtime.env
34
+
35
+ def product(self) -> Product:
36
+ return product_named(getattr(self.args, "product", None) or CORE.name)
37
+
38
+ def base_url(self, product: Product) -> str:
39
+ return resolve_base_url(product, getattr(self.args, "base_url", None), self.env)
40
+
41
+ def store(self) -> CredentialStore:
42
+ if self._store is None:
43
+ self._store = CredentialStore(self.env, self.runtime.keyring(), warn=self.output.info)
44
+ return self._store
45
+
46
+ def http_timeout(self, minimum: float | None = None) -> float:
47
+ explicit = getattr(self.args, "http_timeout", None)
48
+ if explicit is not None:
49
+ return float(explicit)
50
+ return max(DEFAULT_TIMEOUT, minimum or 0.0)
51
+
52
+ def client(
53
+ self, base_url: str, *, token: str | None = None, timeout: float | None = None
54
+ ) -> ApiClient:
55
+ retries = getattr(self.args, "max_retries", None)
56
+ return ApiClient(
57
+ base_url,
58
+ token=token,
59
+ transport=self.runtime.transport,
60
+ timeout=timeout if timeout is not None else self.http_timeout(),
61
+ max_retries=DEFAULT_MAX_RETRIES if retries is None else int(retries),
62
+ sleep=self.runtime.sleep,
63
+ now=self.runtime.now,
64
+ notify=self.output.info,
65
+ )
66
+
67
+ def resolve(
68
+ self, product: Product, base_url: str, *, override_env: str | None = None
69
+ ) -> ResolvedCredential:
70
+ resolved = resolve_credential(
71
+ product, base_url, self.env, self.store(), override_env=override_env
72
+ )
73
+ if resolved is None:
74
+ raise AuthError(
75
+ f"not logged in to {product.label} at {base_url}",
76
+ hint=f"run `entitybind login{'' if product is CORE else ' --product aml'}` "
77
+ f"or set {product.key_env}",
78
+ )
79
+ credential = resolved.credential
80
+ if credential is not None and credential.refresh_token:
81
+ expires = parse_iso(credential.expires_at)
82
+ if expires is not None and expires - self.runtime.now() < REFRESH_MARGIN_SECONDS:
83
+ with self.client(base_url) as anonymous:
84
+ refreshed = refresh_credential(
85
+ anonymous, product, credential, now=self.runtime.now()
86
+ )
87
+ self.store().update_metadata(refreshed)
88
+ resolved.token = refreshed.api_key
89
+ return resolved
90
+
91
+ def authenticated(
92
+ self,
93
+ product: Product,
94
+ *,
95
+ override_env: str | None = None,
96
+ timeout: float | None = None,
97
+ ) -> tuple[ApiClient, ResolvedCredential, str]:
98
+ base_url = self.base_url(product)
99
+ resolved = self.resolve(product, base_url, override_env=override_env)
100
+ return self.client(base_url, token=resolved.token, timeout=timeout), resolved, base_url
@@ -0,0 +1,349 @@
1
+ """Where a logged-in credential lives, per product and base URL.
2
+
3
+ Secrets go to the OS keyring when the optional `keyring` extra is installed
4
+ and a working backend exists. Otherwise they go to
5
+ `$XDG_CONFIG_HOME/entitybind/credentials.json` (default `~/.config`), written
6
+ atomically with mode 0600 in a 0700 directory. The npm client reads and writes
7
+ the same file in the same format.
8
+
9
+ `ENTITYBIND_API_KEY` (Core) and `ENTITYBIND_AML_KEY` (AML) override anything
10
+ stored, which is how CI and other non-interactive callers authenticate.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import json
17
+ from collections.abc import Callable, Mapping
18
+ from dataclasses import dataclass, fields
19
+ from datetime import datetime, timezone
20
+ from pathlib import Path
21
+ from typing import Any, Protocol
22
+
23
+ from entitybind.errors import AuthError, ConflictError
24
+ from entitybind.files import POSIX, atomic_write, config_dir, ensure_private_dir, existing_mode
25
+ from entitybind.products import CLIENT_ID, Product
26
+
27
+ SERVICE = "entitybind"
28
+ CREDENTIALS_FILE = "credentials.json"
29
+ FORMAT_VERSION = 1
30
+ NO_KEYRING_ENV = "ENTITYBIND_NO_KEYRING"
31
+ _SECRET_FIELDS = ("api_key", "refresh_token")
32
+
33
+
34
+ class KeyringLike(Protocol):
35
+ def get_password(self, service_name: str, username: str) -> str | None: ...
36
+
37
+ def set_password(self, service_name: str, username: str, password: str) -> None: ...
38
+
39
+ def delete_password(self, service_name: str, username: str) -> None: ...
40
+
41
+
42
+ class _ModuleKeyring:
43
+ """Adapter over the `keyring` module so its signatures stay its own concern."""
44
+
45
+ def __init__(self, module: Any) -> None:
46
+ self._module = module
47
+
48
+ def get_password(self, service_name: str, username: str) -> str | None:
49
+ value = self._module.get_password(service_name, username)
50
+ return value if isinstance(value, str) else None
51
+
52
+ def set_password(self, service_name: str, username: str, password: str) -> None:
53
+ self._module.set_password(service_name, username, password)
54
+
55
+ def delete_password(self, service_name: str, username: str) -> None:
56
+ self._module.delete_password(service_name, username)
57
+
58
+
59
+ def load_system_keyring(env: Mapping[str, str]) -> KeyringLike | None:
60
+ """The OS keyring, or None when the extra is absent or no backend works."""
61
+ if env.get(NO_KEYRING_ENV):
62
+ return None
63
+ try:
64
+ import keyring
65
+ except ImportError:
66
+ return None
67
+ try:
68
+ backend = keyring.get_keyring()
69
+ priority = float(getattr(backend, "priority", 1))
70
+ except Exception:
71
+ return None
72
+ if priority <= 0: # keyring's "fail" and "null" backends
73
+ return None
74
+ return _ModuleKeyring(keyring)
75
+
76
+
77
+ def utc_now_iso(now: float) -> str:
78
+ return datetime.fromtimestamp(now, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
79
+
80
+
81
+ def parse_iso(value: str | None) -> float | None:
82
+ if not value:
83
+ return None
84
+ try:
85
+ moment = datetime.fromisoformat(value.replace("Z", "+00:00"))
86
+ except ValueError:
87
+ return None
88
+ if moment.tzinfo is None:
89
+ moment = moment.replace(tzinfo=timezone.utc)
90
+ return moment.timestamp()
91
+
92
+
93
+ @dataclass
94
+ class Credential:
95
+ product: str
96
+ base_url: str
97
+ api_key: str
98
+ storage: str = "file"
99
+ token_type: str = "Bearer" # noqa: S105 - RFC 6749 token type name, not a secret
100
+ scope: str | None = None
101
+ key_id: str | None = None
102
+ tenant_id: str | None = None
103
+ expires_at: str | None = None
104
+ refresh_token: str | None = None
105
+ obtained_at: str | None = None
106
+ client_id: str = CLIENT_ID
107
+
108
+ @property
109
+ def account(self) -> str:
110
+ return f"{self.product}:{self.base_url}"
111
+
112
+ def public(self) -> dict[str, Any]:
113
+ """Everything except the secrets."""
114
+ record: dict[str, Any] = {}
115
+ for item in fields(self):
116
+ if item.name in _SECRET_FIELDS:
117
+ continue
118
+ value = getattr(self, item.name)
119
+ if value is not None:
120
+ record[item.name] = value
121
+ return record
122
+
123
+ def to_file_record(self) -> dict[str, Any]:
124
+ record = self.public()
125
+ if self.storage == "file":
126
+ record["api_key"] = self.api_key
127
+ if self.refresh_token:
128
+ record["refresh_token"] = self.refresh_token
129
+ return record
130
+
131
+
132
+ def _credential_from(record: Mapping[str, Any], secrets: Mapping[str, Any]) -> Credential:
133
+ known = {item.name for item in fields(Credential)}
134
+ values = {key: value for key, value in record.items() if key in known}
135
+ values.update({key: value for key, value in secrets.items() if key in _SECRET_FIELDS})
136
+ api_key = values.get("api_key")
137
+ if not isinstance(api_key, str) or not api_key:
138
+ raise AuthError("the stored credential has no key; run `entitybind login` again")
139
+ return Credential(**values)
140
+
141
+
142
+ class CredentialStore:
143
+ def __init__(
144
+ self,
145
+ env: Mapping[str, str],
146
+ keyring: KeyringLike | None,
147
+ *,
148
+ warn: Callable[[str], None] | None = None,
149
+ ) -> None:
150
+ self.directory = config_dir(env)
151
+ self.path = self.directory / CREDENTIALS_FILE
152
+ self.keyring = keyring
153
+ self._warn = warn
154
+ self._warned_mode = False
155
+
156
+ def _say(self, message: str) -> None:
157
+ if self._warn is not None:
158
+ self._warn(message)
159
+
160
+ def read(self) -> dict[str, Any]:
161
+ if not self.path.exists():
162
+ return {"version": FORMAT_VERSION, "credentials": {}}
163
+ mode = existing_mode(self.path)
164
+ if POSIX and mode is not None and mode & 0o077 and not self._warned_mode:
165
+ self._warned_mode = True
166
+ self._say(
167
+ f"warning: {self.path} is readable by other users (mode {mode:o}); "
168
+ "it will be rewritten with mode 600 on the next change"
169
+ )
170
+ try:
171
+ data = json.loads(self.path.read_text(encoding="utf-8"))
172
+ except ValueError:
173
+ raise ConflictError(
174
+ f"{self.path} is not valid JSON; fix it or delete it and log in again",
175
+ code="credentials_unreadable",
176
+ ) from None
177
+ if not isinstance(data, dict) or not isinstance(data.get("credentials", {}), dict):
178
+ raise ConflictError(
179
+ f"{self.path} does not hold EntityBind credentials", code="credentials_unreadable"
180
+ )
181
+ version = data.get("version", FORMAT_VERSION)
182
+ if not isinstance(version, int) or version > FORMAT_VERSION:
183
+ raise ConflictError(
184
+ f"{self.path} was written by a newer entitybind; upgrade this client",
185
+ code="credentials_format",
186
+ )
187
+ data.setdefault("credentials", {})
188
+ return data
189
+
190
+ def _write(self, data: dict[str, Any]) -> None:
191
+ ensure_private_dir(self.directory)
192
+ data["version"] = FORMAT_VERSION
193
+ atomic_write(self.path, json.dumps(data, indent=2, sort_keys=True) + "\n", mode=0o600)
194
+
195
+ def _records(self, data: dict[str, Any], product: str) -> dict[str, Any]:
196
+ bucket = data["credentials"].get(product)
197
+ if not isinstance(bucket, dict):
198
+ bucket = {}
199
+ data["credentials"][product] = bucket
200
+ return bucket
201
+
202
+ def metadata(self, product: Product, base_url: str) -> dict[str, Any]:
203
+ """A stored record's non-secret fields, read without the keyring."""
204
+ try:
205
+ data = self.read()
206
+ except ConflictError:
207
+ return {}
208
+ bucket = data["credentials"].get(product.name)
209
+ record = bucket.get(base_url) if isinstance(bucket, dict) else None
210
+ if not isinstance(record, dict):
211
+ return {}
212
+ return {key: value for key, value in record.items() if key not in _SECRET_FIELDS}
213
+
214
+ def get(self, product: Product, base_url: str) -> Credential | None:
215
+ data = self.read()
216
+ bucket = data["credentials"].get(product.name)
217
+ record = bucket.get(base_url) if isinstance(bucket, dict) else None
218
+ if not isinstance(record, dict):
219
+ return None
220
+ if record.get("storage") == "keyring":
221
+ return _credential_from(record, self._keyring_secret(product, base_url))
222
+ return _credential_from(record, record)
223
+
224
+ def _keyring_secret(self, product: Product, base_url: str) -> dict[str, Any]:
225
+ if self.keyring is None:
226
+ raise AuthError(
227
+ "the credential for this product is stored in the OS keyring, but keyring "
228
+ "support is not available",
229
+ hint="install entitybind[keyring], set "
230
+ f"{product.key_env}, or run `entitybind login` again",
231
+ )
232
+ try:
233
+ raw = self.keyring.get_password(SERVICE, f"{product.name}:{base_url}")
234
+ except Exception as exc:
235
+ raise AuthError(
236
+ f"could not read the OS keyring ({type(exc).__name__})",
237
+ hint=f"unlock the keyring, set {product.key_env}, or run `entitybind login` again",
238
+ ) from None
239
+ if not raw:
240
+ raise AuthError(
241
+ "the OS keyring has no entry for this credential",
242
+ hint="run `entitybind login` again",
243
+ )
244
+ try:
245
+ secret = json.loads(raw)
246
+ except ValueError:
247
+ secret = {"api_key": raw}
248
+ return secret if isinstance(secret, dict) else {"api_key": raw}
249
+
250
+ def save(self, credential: Credential, *, prefer_keyring: bool = True) -> Credential:
251
+ data = self.read()
252
+ bucket = self._records(data, credential.product)
253
+ previous = bucket.get(credential.base_url)
254
+ credential.storage = "file"
255
+ if prefer_keyring and self.keyring is not None:
256
+ secret = {"api_key": credential.api_key}
257
+ if credential.refresh_token:
258
+ secret["refresh_token"] = credential.refresh_token
259
+ try:
260
+ self.keyring.set_password(SERVICE, credential.account, json.dumps(secret))
261
+ credential.storage = "keyring"
262
+ except Exception as exc:
263
+ self._say(
264
+ f"warning: the OS keyring refused the credential ({type(exc).__name__}); "
265
+ f"storing it in {self.path} with mode 600 instead"
266
+ )
267
+ if (
268
+ credential.storage == "file"
269
+ and isinstance(previous, dict)
270
+ and previous.get("storage") == "keyring"
271
+ ):
272
+ self._forget_keyring(credential.account)
273
+ bucket[credential.base_url] = credential.to_file_record()
274
+ self._write(data)
275
+ return credential
276
+
277
+ def _forget_keyring(self, account: str) -> None:
278
+ if self.keyring is None:
279
+ return
280
+ with contextlib.suppress(Exception):
281
+ self.keyring.delete_password(SERVICE, account)
282
+
283
+ def delete(self, product: Product, base_url: str) -> bool:
284
+ if not self.path.exists():
285
+ return False
286
+ data = self.read()
287
+ bucket = data["credentials"].get(product.name)
288
+ if not isinstance(bucket, dict) or base_url not in bucket:
289
+ return False
290
+ record = bucket.pop(base_url)
291
+ if isinstance(record, dict) and record.get("storage") == "keyring":
292
+ self._forget_keyring(f"{product.name}:{base_url}")
293
+ if not bucket:
294
+ data["credentials"].pop(product.name, None)
295
+ self._write(data)
296
+ return True
297
+
298
+ def delete_all(self) -> int:
299
+ if not self.path.exists():
300
+ return 0
301
+ data = self.read()
302
+ removed = 0
303
+ for product_name, bucket in list(data["credentials"].items()):
304
+ if not isinstance(bucket, dict):
305
+ continue
306
+ for base_url, record in bucket.items():
307
+ removed += 1
308
+ if isinstance(record, dict) and record.get("storage") == "keyring":
309
+ self._forget_keyring(f"{product_name}:{base_url}")
310
+ data["credentials"] = {}
311
+ self._write(data)
312
+ return removed
313
+
314
+ def update_metadata(self, credential: Credential) -> None:
315
+ """Persist non-secret fields (and a refreshed secret) for a stored credential."""
316
+ self.save(credential, prefer_keyring=credential.storage == "keyring")
317
+
318
+
319
+ @dataclass
320
+ class ResolvedCredential:
321
+ token: str
322
+ source: str
323
+ env_var: str | None = None
324
+ credential: Credential | None = None
325
+
326
+
327
+ def resolve_credential(
328
+ product: Product,
329
+ base_url: str,
330
+ env: Mapping[str, str],
331
+ store: CredentialStore,
332
+ *,
333
+ override_env: str | None = None,
334
+ ) -> ResolvedCredential | None:
335
+ """An environment key wins over anything stored."""
336
+ for name in (override_env, product.key_env):
337
+ if not name:
338
+ continue
339
+ value = env.get(name, "").strip()
340
+ if value:
341
+ return ResolvedCredential(token=value, source="environment", env_var=name)
342
+ stored = store.get(product, base_url)
343
+ if stored is None:
344
+ return None
345
+ return ResolvedCredential(token=stored.api_key, source=stored.storage, credential=stored)
346
+
347
+
348
+ def credentials_path(env: Mapping[str, str]) -> Path:
349
+ return config_dir(env) / CREDENTIALS_FILE