benchling-toolkit 0.4.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.
Files changed (38) hide show
  1. benchling_toolkit/__init__.py +6 -0
  2. benchling_toolkit/api.py +219 -0
  3. benchling_toolkit/auth.py +133 -0
  4. benchling_toolkit/change_spec.py +436 -0
  5. benchling_toolkit/cli.py +840 -0
  6. benchling_toolkit/config.py +57 -0
  7. benchling_toolkit/credentials.py +257 -0
  8. benchling_toolkit/environment.py +188 -0
  9. benchling_toolkit/errors.py +104 -0
  10. benchling_toolkit/export.py +662 -0
  11. benchling_toolkit/keychain.py +323 -0
  12. benchling_toolkit/listing.py +487 -0
  13. benchling_toolkit/mcp_server.py +847 -0
  14. benchling_toolkit/models.py +290 -0
  15. benchling_toolkit/plans/__init__.py +13 -0
  16. benchling_toolkit/plans/base.py +60 -0
  17. benchling_toolkit/plans/document.py +298 -0
  18. benchling_toolkit/plans/fields.py +300 -0
  19. benchling_toolkit/plans/planner.py +318 -0
  20. benchling_toolkit/plans/repository.py +105 -0
  21. benchling_toolkit/plans/result_update.py +845 -0
  22. benchling_toolkit/plans/results.py +184 -0
  23. benchling_toolkit/plans/table.py +241 -0
  24. benchling_toolkit/py.typed +0 -0
  25. benchling_toolkit/redact.py +67 -0
  26. benchling_toolkit/runtime.py +82 -0
  27. benchling_toolkit/services.py +1206 -0
  28. benchling_toolkit/tls.py +10 -0
  29. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/list-parameters.json +32 -0
  30. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/openapi-manifest.json +48 -0
  31. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/change-spec.schema.json +173 -0
  32. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/envelope.schema.json +30 -0
  33. benchling_toolkit-0.4.0.dist-info/METADATA +576 -0
  34. benchling_toolkit-0.4.0.dist-info/RECORD +38 -0
  35. benchling_toolkit-0.4.0.dist-info/WHEEL +5 -0
  36. benchling_toolkit-0.4.0.dist-info/entry_points.txt +2 -0
  37. benchling_toolkit-0.4.0.dist-info/licenses/LICENSE +22 -0
  38. benchling_toolkit-0.4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,323 @@
1
+ """OS keychain storage for client secrets.
2
+
3
+ The service name is ``benchling-toolkit`` and the username is the environment
4
+ name. There is no plaintext file fallback.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import shlex
11
+ import shutil
12
+ import sys
13
+ from collections.abc import Iterator
14
+ from contextlib import contextmanager
15
+ from contextvars import ContextVar
16
+ from dataclasses import dataclass
17
+ from typing import Any, Protocol
18
+
19
+ import keyring
20
+ from keyring.errors import KeyringError, KeyringLocked, PasswordDeleteError
21
+
22
+ from .errors import AuthenticationError
23
+ from .redact import register_secret
24
+
25
+ SERVICE_NAME = "benchling-toolkit"
26
+ _SECRET_SERVICE_NAME = "org.freedesktop.secrets"
27
+ _UNLOCK = "gnome-keyring-daemon --unlock --components=secrets"
28
+ _PLACEHOLDER_ENV = "dev"
29
+ _PLACEHOLDER_URL = "https://your-tenant.benchling.com"
30
+ _PLACEHOLDER_CLIENT = "CLIENT"
31
+ _INSTALL = "sudo apt-get install -y gnome-keyring dbus"
32
+ _README = "See the README section Headless Linux."
33
+ # Shown only for `benchling mcp serve`. CLI login already has a terminal session.
34
+ _MCP_ENV = (
35
+ "The standard MCP SDK launches stdio servers with only HOME, LOGNAME, PATH, "
36
+ "SHELL, TERM and USER, so DBUS_SESSION_BUS_ADDRESS is missing. "
37
+ "Set it in the MCP client config env block. Cron needs that same long-lived bus exported."
38
+ )
39
+ # Set for the lifetime of run_mcp_server, including its keychain check.
40
+ _in_mcp_serve: ContextVar[bool] = ContextVar("benchling_in_mcp_serve", default=False)
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class _LoginFix:
45
+ """Values already known when a keychain error interrupts login."""
46
+
47
+ env: str | None = None
48
+ tenant_url: str | None = None
49
+ client_id: str | None = None
50
+
51
+
52
+ # Set only around `benchling auth login`. Other commands keep the placeholders.
53
+ _login_fix: ContextVar[_LoginFix | None] = ContextVar("benchling_login_fix", default=None)
54
+ NO_KEYRING_MESSAGE = (
55
+ "No usable OS keychain is available because no Secret Service backend is installed.\n"
56
+ f"{_INSTALL}\n"
57
+ f"{_README}"
58
+ )
59
+
60
+
61
+ class _Backend(Protocol):
62
+ priority: float
63
+
64
+ def get_password(self, service: str, username: str) -> str | None: ...
65
+
66
+ def set_password(self, service: str, username: str, password: str) -> None: ...
67
+
68
+ def delete_password(self, service: str, username: str) -> None: ...
69
+
70
+
71
+ def _backend_name(backend: object) -> str:
72
+ kind = type(backend)
73
+ return f"{kind.__module__}.{kind.__qualname__}"
74
+
75
+
76
+ def _usable(backend: Any) -> bool:
77
+ """True when the backend is a real OS keychain, not fail/null/plaintext."""
78
+ kind = type(backend)
79
+ module = kind.__module__.lower()
80
+ name = kind.__name__.lower()
81
+ if module.endswith(".fail") or module.endswith(".null"):
82
+ return False
83
+ if "plaintext" in module or "plaintext" in name:
84
+ return False
85
+ try:
86
+ priority = float(backend.priority)
87
+ except (AttributeError, TypeError, ValueError, RuntimeError):
88
+ return False
89
+ return priority >= 1
90
+
91
+
92
+ def provider_installed() -> bool:
93
+ """True when a Linux Secret Service provider binary is on PATH."""
94
+ return any(
95
+ shutil.which(name)
96
+ for name in ("gnome-keyring-daemon", "kwalletd6", "kwalletd5", "kwalletd")
97
+ )
98
+
99
+
100
+ def secret_service_reachable() -> bool:
101
+ """True when this session bus owns org.freedesktop.secrets."""
102
+ if not os.environ.get("DBUS_SESSION_BUS_ADDRESS"):
103
+ return False
104
+ try:
105
+ connection = _open_session_bus()
106
+ except Exception:
107
+ return False
108
+ try:
109
+ return _secret_service_owned(connection)
110
+ except Exception:
111
+ return False
112
+ finally:
113
+ _close_bus(connection)
114
+
115
+
116
+ def _open_session_bus() -> Any:
117
+ from jeepney.io.blocking import open_dbus_connection # type: ignore[import-untyped]
118
+
119
+ return open_dbus_connection(bus="SESSION", auth_timeout=1.0)
120
+
121
+
122
+ def _secret_service_owned(connection: Any) -> bool:
123
+ from jeepney.bus_messages import message_bus # type: ignore[import-untyped]
124
+ from jeepney.io.blocking import Proxy
125
+
126
+ owned: Any = Proxy(message_bus, connection).NameHasOwner(_SECRET_SERVICE_NAME)
127
+ value = owned[0] if isinstance(owned, tuple) else owned
128
+ return bool(value)
129
+
130
+
131
+ def _close_bus(connection: Any) -> None:
132
+ close = getattr(connection, "close", None)
133
+ if not callable(close):
134
+ return
135
+ try:
136
+ close()
137
+ except Exception:
138
+ return
139
+
140
+
141
+ def _is_locked(exc: BaseException | None) -> bool:
142
+ if exc is None:
143
+ return False
144
+ if isinstance(exc, KeyringLocked):
145
+ return True
146
+ return "lock" in type(exc).__name__.lower()
147
+
148
+
149
+ def classify_keychain_failure(backend: object | None, exc: BaseException | None = None) -> str:
150
+ """Return no_backend, dbus_unreachable, or locked."""
151
+ if _is_locked(exc):
152
+ return "locked"
153
+ if sys.platform.startswith("linux"):
154
+ if not provider_installed():
155
+ return "no_backend"
156
+ if not secret_service_reachable():
157
+ return "dbus_unreachable"
158
+ if exc is not None:
159
+ return "locked"
160
+ return "no_backend"
161
+
162
+
163
+ def _dbus_bus_line() -> str:
164
+ """Describe the session bus that failed. Do not call an unset bus 'set', or the reverse."""
165
+ if os.environ.get("DBUS_SESSION_BUS_ADDRESS"):
166
+ return f"DBUS_SESSION_BUS_ADDRESS is set, but this bus has no {_SECRET_SERVICE_NAME} name."
167
+ return "DBUS_SESSION_BUS_ADDRESS is unset."
168
+
169
+
170
+ def _lines(*parts: str) -> str:
171
+ return "\n".join(part for part in parts if part)
172
+
173
+
174
+ def _cause(cause: str) -> str:
175
+ if cause == "locked":
176
+ return "No usable OS keychain is available because the Secret Service collection is locked."
177
+ if cause == "dbus_unreachable":
178
+ return (
179
+ "No usable OS keychain is available because Secret Service is not reachable on D-Bus. "
180
+ + _dbus_bus_line()
181
+ )
182
+ return "No usable OS keychain is available because no Secret Service backend is installed."
183
+
184
+
185
+ def _shell_value(value: str | None, placeholder: str) -> str:
186
+ """Quote a supplied flag value. An omitted value stays a shell-safe placeholder."""
187
+ if value is None or not value.strip():
188
+ return placeholder
189
+ return shlex.quote(value.strip())
190
+
191
+
192
+ def dbus_login_command(
193
+ *,
194
+ env: str | None = None,
195
+ tenant_url: str | None = None,
196
+ client_id: str | None = None,
197
+ ) -> str:
198
+ """Unlock the keyring and log in inside one ``dbus-run-session``.
199
+
200
+ ``env``, ``tenant_url``, and ``client_id`` are shell-quoted. Omitted values
201
+ stay placeholders. ``$KEYRING_PASSWORD`` and ``$BENCHLING_CLIENT_SECRET``
202
+ stay variable references; this command never contains a secret value.
203
+ """
204
+ login = (
205
+ 'printf "%s" "$BENCHLING_CLIENT_SECRET" | benchling auth login '
206
+ f"--env {_shell_value(env, _PLACEHOLDER_ENV)} "
207
+ f"--tenant-url {_shell_value(tenant_url, _PLACEHOLDER_URL)} "
208
+ f"--client-id {_shell_value(client_id, _PLACEHOLDER_CLIENT)} "
209
+ "--secret-stdin"
210
+ )
211
+ # The session exits with its shell, and the bus exits with it. Login has to
212
+ # be in that same shell or the secret is stored on a bus that is already gone.
213
+ script = f'printf "%s\\n" "$KEYRING_PASSWORD" | {_UNLOCK}; {login}'
214
+ return f"dbus-run-session -- sh -c {shlex.quote(script)}"
215
+
216
+
217
+ @contextmanager
218
+ def bind_login_fix(
219
+ *,
220
+ env: str | None,
221
+ tenant_url: str | None,
222
+ client_id: str | None,
223
+ ) -> Iterator[None]:
224
+ """Use these login values in a keychain error raised inside the block."""
225
+ token = _login_fix.set(_LoginFix(env=env, tenant_url=tenant_url, client_id=client_id))
226
+ try:
227
+ yield
228
+ finally:
229
+ _login_fix.reset(token)
230
+
231
+
232
+ def _fix_command(cause: str) -> str:
233
+ """One command. The README has the rest, including a long-lived bus."""
234
+ if cause == "no_backend":
235
+ return _INSTALL
236
+ current = _login_fix.get()
237
+ if current is None:
238
+ return dbus_login_command()
239
+ return dbus_login_command(
240
+ env=current.env,
241
+ tenant_url=current.tenant_url,
242
+ client_id=current.client_id,
243
+ )
244
+
245
+
246
+ def keychain_message(cause: str) -> str:
247
+ """Cause, one fix command, and a README pointer. MCP adds the env-block line.
248
+
249
+ Never includes secret values. The MCP line is only present while `mcp serve` is running.
250
+ """
251
+ parts = [_cause(cause), _fix_command(cause), _README]
252
+ if _in_mcp_serve.get():
253
+ parts.append(_MCP_ENV)
254
+ return _lines(*parts)
255
+
256
+
257
+ def _keychain_error(backend: object | None, exc: BaseException | None) -> AuthenticationError:
258
+ cause = classify_keychain_failure(backend, exc)
259
+ if backend is not None:
260
+ backend_name: str = _backend_name(backend)
261
+ elif exc is not None:
262
+ backend_name = type(exc).__name__
263
+ else:
264
+ backend_name = "unknown"
265
+ return AuthenticationError(
266
+ keychain_message(cause),
267
+ details={"backend": backend_name, "cause": cause},
268
+ )
269
+
270
+
271
+ class Keychain:
272
+ """Read and write one environment's client secret."""
273
+
274
+ def __init__(self, backend: _Backend | None = None) -> None:
275
+ self._backend = backend
276
+
277
+ def backend(self) -> Any:
278
+ """Return the injected backend, or the process-wide keyring backend."""
279
+ if self._backend is not None:
280
+ return self._backend
281
+ return keyring.get_keyring()
282
+
283
+ def require(self) -> None:
284
+ """Raise AuthenticationError when no OS keychain can store a secret."""
285
+ backend = self.backend()
286
+ if _usable(backend):
287
+ return
288
+ raise _keychain_error(backend, None)
289
+
290
+ def get(self, env: str) -> str | None:
291
+ """Return the stored secret, or None when this environment has none."""
292
+ self.require()
293
+ try:
294
+ value = self.backend().get_password(SERVICE_NAME, env)
295
+ except KeyringError as exc:
296
+ raise _unavailable(exc) from exc
297
+ if isinstance(value, str) and value:
298
+ register_secret(value)
299
+ return value
300
+ return None
301
+
302
+ def set(self, env: str, secret: str) -> None:
303
+ """Store a client secret. The value is not logged."""
304
+ self.require()
305
+ register_secret(secret)
306
+ try:
307
+ self.backend().set_password(SERVICE_NAME, env, secret)
308
+ except KeyringError as exc:
309
+ raise _unavailable(exc) from exc
310
+
311
+ def delete(self, env: str) -> None:
312
+ """Remove a client secret. Missing entries are not an error."""
313
+ self.require()
314
+ try:
315
+ self.backend().delete_password(SERVICE_NAME, env)
316
+ except PasswordDeleteError:
317
+ return
318
+ except KeyringError as exc:
319
+ raise _unavailable(exc) from exc
320
+
321
+
322
+ def _unavailable(exc: KeyringError) -> AuthenticationError:
323
+ return _keychain_error(None, exc)