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.
- benchling_toolkit/__init__.py +6 -0
- benchling_toolkit/api.py +219 -0
- benchling_toolkit/auth.py +133 -0
- benchling_toolkit/change_spec.py +436 -0
- benchling_toolkit/cli.py +840 -0
- benchling_toolkit/config.py +57 -0
- benchling_toolkit/credentials.py +257 -0
- benchling_toolkit/environment.py +188 -0
- benchling_toolkit/errors.py +104 -0
- benchling_toolkit/export.py +662 -0
- benchling_toolkit/keychain.py +323 -0
- benchling_toolkit/listing.py +487 -0
- benchling_toolkit/mcp_server.py +847 -0
- benchling_toolkit/models.py +290 -0
- benchling_toolkit/plans/__init__.py +13 -0
- benchling_toolkit/plans/base.py +60 -0
- benchling_toolkit/plans/document.py +298 -0
- benchling_toolkit/plans/fields.py +300 -0
- benchling_toolkit/plans/planner.py +318 -0
- benchling_toolkit/plans/repository.py +105 -0
- benchling_toolkit/plans/result_update.py +845 -0
- benchling_toolkit/plans/results.py +184 -0
- benchling_toolkit/plans/table.py +241 -0
- benchling_toolkit/py.typed +0 -0
- benchling_toolkit/redact.py +67 -0
- benchling_toolkit/runtime.py +82 -0
- benchling_toolkit/services.py +1206 -0
- benchling_toolkit/tls.py +10 -0
- benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/list-parameters.json +32 -0
- benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/openapi-manifest.json +48 -0
- benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/change-spec.schema.json +173 -0
- benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/envelope.schema.json +30 -0
- benchling_toolkit-0.4.0.dist-info/METADATA +576 -0
- benchling_toolkit-0.4.0.dist-info/RECORD +38 -0
- benchling_toolkit-0.4.0.dist-info/WHEEL +5 -0
- benchling_toolkit-0.4.0.dist-info/entry_points.txt +2 -0
- benchling_toolkit-0.4.0.dist-info/licenses/LICENSE +22 -0
- benchling_toolkit-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Local application directories for plans, journals and locks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def application_home() -> Path:
|
|
11
|
+
"""Return the per-user config root; BENCHLING_TOOLKIT_HOME overrides the platform default."""
|
|
12
|
+
override = os.getenv("BENCHLING_TOOLKIT_HOME")
|
|
13
|
+
if override:
|
|
14
|
+
return Path(override).expanduser().resolve()
|
|
15
|
+
if os.name == "nt":
|
|
16
|
+
root = Path(os.getenv("APPDATA", Path.home() / "AppData" / "Roaming"))
|
|
17
|
+
elif sys.platform == "darwin":
|
|
18
|
+
root = Path.home() / "Library" / "Application Support"
|
|
19
|
+
else:
|
|
20
|
+
root = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config"))
|
|
21
|
+
return root / "benchling-toolkit"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ConfigStore:
|
|
25
|
+
"""Locates the on-disk state directories under a single root."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, root: Path | None = None) -> None:
|
|
28
|
+
self.root = root or application_home()
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def plans_dir(self) -> Path:
|
|
32
|
+
"""Directory holding saved change plans."""
|
|
33
|
+
return self.root / "plans"
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def journals_dir(self) -> Path:
|
|
37
|
+
"""Directory holding write-execution journals."""
|
|
38
|
+
return self.root / "journals"
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def locks_dir(self) -> Path:
|
|
42
|
+
"""Directory holding lock files."""
|
|
43
|
+
return self.root / "locks"
|
|
44
|
+
|
|
45
|
+
def ensure(self) -> None:
|
|
46
|
+
"""Create all directories owner-only (0700); chmod failures are ignored."""
|
|
47
|
+
for directory in (
|
|
48
|
+
self.root,
|
|
49
|
+
self.plans_dir,
|
|
50
|
+
self.journals_dir,
|
|
51
|
+
self.locks_dir,
|
|
52
|
+
):
|
|
53
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
54
|
+
try:
|
|
55
|
+
directory.chmod(0o700)
|
|
56
|
+
except OSError:
|
|
57
|
+
pass
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Login, logout, and status for one or more named environments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from pydantic import ValidationError as ModelValidationError
|
|
10
|
+
|
|
11
|
+
from .auth import AuthManager
|
|
12
|
+
from .environment import ENV_NAME, EnvironmentConfigStore, invalid_environment_name, write_private
|
|
13
|
+
from .errors import AuthenticationError, BenchlingAgentError, ValidationError
|
|
14
|
+
from .keychain import Keychain, bind_login_fix
|
|
15
|
+
from .models import AuthMethod, Environment, explain_environment_error
|
|
16
|
+
from .redact import redact_text, register_secret
|
|
17
|
+
from .tls import verified_context
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def open_token_client() -> httpx.Client:
|
|
21
|
+
"""HTTP client used only for the OAuth token endpoint."""
|
|
22
|
+
return httpx.Client(timeout=30.0, verify=verified_context())
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def build_environment(name: str, tenant_url: str, client_id: str) -> Environment:
|
|
26
|
+
"""Validate a tenant URL and client ID separately, without echoing either value."""
|
|
27
|
+
if not ENV_NAME.match(name):
|
|
28
|
+
raise invalid_environment_name(name)
|
|
29
|
+
client_id = client_id.strip()
|
|
30
|
+
if not client_id:
|
|
31
|
+
raise ValidationError("Client ID is required", details={"env": name, "field": "client_id"})
|
|
32
|
+
if any(character in client_id for character in "\r\n\x00"):
|
|
33
|
+
raise ValidationError("Invalid client ID", details={"env": name, "field": "client_id"})
|
|
34
|
+
try:
|
|
35
|
+
environment = Environment.model_validate(
|
|
36
|
+
{
|
|
37
|
+
"name": name,
|
|
38
|
+
"tenant_url": tenant_url.strip(),
|
|
39
|
+
"client_id": client_id,
|
|
40
|
+
"auth_method": AuthMethod.CLIENT_CREDENTIALS,
|
|
41
|
+
}
|
|
42
|
+
)
|
|
43
|
+
except ModelValidationError as exc:
|
|
44
|
+
raise explain_environment_error(exc, env=name) from exc
|
|
45
|
+
return environment
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def login_fix_values(
|
|
49
|
+
store: EnvironmentConfigStore,
|
|
50
|
+
name: str,
|
|
51
|
+
tenant_url: str | None,
|
|
52
|
+
client_id: str | None,
|
|
53
|
+
) -> tuple[str | None, str | None]:
|
|
54
|
+
"""Tenant URL and client ID to print in a keychain fix command.
|
|
55
|
+
|
|
56
|
+
A supplied tenant URL is normalized. A supplied client ID is trimmed.
|
|
57
|
+
Either one that was omitted comes from environments.json when ``name`` is
|
|
58
|
+
already configured. A value that cannot be used is left unset.
|
|
59
|
+
"""
|
|
60
|
+
saved_url, saved_client = _saved_login_fields(store, name)
|
|
61
|
+
supplied_url = _command_tenant_url(tenant_url) if tenant_url and tenant_url.strip() else None
|
|
62
|
+
supplied_client = client_id.strip() if client_id and client_id.strip() else None
|
|
63
|
+
return supplied_url or saved_url, supplied_client or saved_client
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _command_tenant_url(value: str) -> str | None:
|
|
67
|
+
try:
|
|
68
|
+
return build_environment("dev", value, "client").base_url
|
|
69
|
+
except BenchlingAgentError:
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _saved_login_fields(store: EnvironmentConfigStore, name: str) -> tuple[str | None, str | None]:
|
|
74
|
+
if not store.environments_path.exists():
|
|
75
|
+
return None, None
|
|
76
|
+
try:
|
|
77
|
+
environment = store.resolve(name)
|
|
78
|
+
except BenchlingAgentError:
|
|
79
|
+
return None, None
|
|
80
|
+
return environment.base_url, environment.client_id
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def login(
|
|
84
|
+
store: EnvironmentConfigStore,
|
|
85
|
+
keychain: Keychain,
|
|
86
|
+
*,
|
|
87
|
+
name: str,
|
|
88
|
+
tenant_url: str,
|
|
89
|
+
client_id: str,
|
|
90
|
+
secret: str,
|
|
91
|
+
http: httpx.Client | None = None,
|
|
92
|
+
) -> Environment:
|
|
93
|
+
"""Verify client credentials, then save the environment and its secret.
|
|
94
|
+
|
|
95
|
+
Nothing is written if the token request fails. A failure while saving rolls
|
|
96
|
+
the keychain and environments.json back to their previous contents.
|
|
97
|
+
"""
|
|
98
|
+
if secret == "" or secret.strip() == "":
|
|
99
|
+
raise ValidationError("Client secret is required", details={"env": name})
|
|
100
|
+
register_secret(secret)
|
|
101
|
+
environment = build_environment(name, tenant_url, client_id)
|
|
102
|
+
with bind_login_fix(
|
|
103
|
+
env=environment.name,
|
|
104
|
+
tenant_url=environment.base_url,
|
|
105
|
+
client_id=environment.client_id,
|
|
106
|
+
):
|
|
107
|
+
keychain.require()
|
|
108
|
+
if store.environments_path.exists():
|
|
109
|
+
store.configured_names()
|
|
110
|
+
_verify_token(environment, secret, http)
|
|
111
|
+
previous_secret = keychain.get(name)
|
|
112
|
+
previous_file = _read_file(store)
|
|
113
|
+
try:
|
|
114
|
+
keychain.set(name, secret)
|
|
115
|
+
store.upsert(environment)
|
|
116
|
+
except BenchlingAgentError:
|
|
117
|
+
_rollback(store, keychain, name, previous_secret, previous_file)
|
|
118
|
+
raise
|
|
119
|
+
except Exception as exc:
|
|
120
|
+
_rollback(store, keychain, name, previous_secret, previous_file)
|
|
121
|
+
raise AuthenticationError(
|
|
122
|
+
"Could not save the environment after authentication succeeded",
|
|
123
|
+
details={"env": name, "reason": type(exc).__name__},
|
|
124
|
+
) from exc
|
|
125
|
+
return environment
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def logout(store: EnvironmentConfigStore, keychain: Keychain, name: str) -> None:
|
|
129
|
+
"""Remove the environment record and its keychain secret."""
|
|
130
|
+
names = store.configured_names() if store.environments_path.exists() else []
|
|
131
|
+
if not ENV_NAME.match(name):
|
|
132
|
+
raise invalid_environment_name(name, available=names)
|
|
133
|
+
keychain.require()
|
|
134
|
+
present = name in names
|
|
135
|
+
secret = keychain.get(name)
|
|
136
|
+
if not present and secret is None:
|
|
137
|
+
raise ValidationError(
|
|
138
|
+
f"Environment {name!r} is not configured.",
|
|
139
|
+
details={"env": name, "available_envs": names},
|
|
140
|
+
)
|
|
141
|
+
keychain.delete(name)
|
|
142
|
+
if not present:
|
|
143
|
+
return
|
|
144
|
+
try:
|
|
145
|
+
store.remove(name)
|
|
146
|
+
except Exception:
|
|
147
|
+
if secret is not None:
|
|
148
|
+
keychain.set(name, secret)
|
|
149
|
+
raise
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@dataclass
|
|
153
|
+
class StatusReport:
|
|
154
|
+
"""Local configuration for each environment, plus optional token checks."""
|
|
155
|
+
|
|
156
|
+
environments: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
157
|
+
failed_envs: list[str] = field(default_factory=list)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def collect_status(
|
|
161
|
+
store: EnvironmentConfigStore,
|
|
162
|
+
keychain: Keychain,
|
|
163
|
+
*,
|
|
164
|
+
name: str | None,
|
|
165
|
+
check: bool,
|
|
166
|
+
http: httpx.Client | None = None,
|
|
167
|
+
) -> StatusReport:
|
|
168
|
+
"""Describe saved environments without including secrets or tokens."""
|
|
169
|
+
names = [name] if name else store.configured_names()
|
|
170
|
+
if name:
|
|
171
|
+
store.resolve(name)
|
|
172
|
+
if not names:
|
|
173
|
+
return StatusReport()
|
|
174
|
+
keychain.require()
|
|
175
|
+
secrets = {item: secret for item in names if (secret := keychain.get(item))}
|
|
176
|
+
owns_http = http is None
|
|
177
|
+
client = http or open_token_client()
|
|
178
|
+
auth = AuthManager(secrets, http=client)
|
|
179
|
+
try:
|
|
180
|
+
report = StatusReport()
|
|
181
|
+
for item in names:
|
|
182
|
+
environment = store.resolve(item)
|
|
183
|
+
row = auth.status(environment)
|
|
184
|
+
if check:
|
|
185
|
+
row["token_check"] = _token_check(auth, environment, bool(secrets.get(item)))
|
|
186
|
+
row["access_token_cached"] = auth.status(environment)["access_token_cached"]
|
|
187
|
+
if row["token_check"]["ok"] is False:
|
|
188
|
+
report.failed_envs.append(item)
|
|
189
|
+
report.environments[item] = row
|
|
190
|
+
return report
|
|
191
|
+
finally:
|
|
192
|
+
auth.close()
|
|
193
|
+
if owns_http:
|
|
194
|
+
client.close()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _verify_token(environment: Environment, secret: str, http: httpx.Client | None) -> None:
|
|
198
|
+
owns_http = http is None
|
|
199
|
+
client = http or open_token_client()
|
|
200
|
+
auth = AuthManager({environment.name: secret}, http=client)
|
|
201
|
+
try:
|
|
202
|
+
auth.headers(environment)
|
|
203
|
+
finally:
|
|
204
|
+
auth.close()
|
|
205
|
+
if owns_http:
|
|
206
|
+
client.close()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _token_check(
|
|
210
|
+
auth: AuthManager, environment: Environment, secret_present: bool
|
|
211
|
+
) -> dict[str, Any]:
|
|
212
|
+
if not secret_present:
|
|
213
|
+
return {
|
|
214
|
+
"ok": False,
|
|
215
|
+
"message": (
|
|
216
|
+
"Client secret is not in the keychain; "
|
|
217
|
+
f"run benchling auth login --env {environment.name}"
|
|
218
|
+
),
|
|
219
|
+
}
|
|
220
|
+
try:
|
|
221
|
+
auth.headers(environment)
|
|
222
|
+
except BenchlingAgentError as exc:
|
|
223
|
+
return {"ok": False, "message": redact_text(exc.message)}
|
|
224
|
+
return {"ok": True}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _read_file(store: EnvironmentConfigStore) -> str | None:
|
|
228
|
+
path = store.environments_path
|
|
229
|
+
if not path.exists():
|
|
230
|
+
return None
|
|
231
|
+
return path.read_text(encoding="utf-8")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _rollback(
|
|
235
|
+
store: EnvironmentConfigStore,
|
|
236
|
+
keychain: Keychain,
|
|
237
|
+
name: str,
|
|
238
|
+
previous_secret: str | None,
|
|
239
|
+
previous_file: str | None,
|
|
240
|
+
) -> None:
|
|
241
|
+
try:
|
|
242
|
+
if previous_secret is None:
|
|
243
|
+
keychain.delete(name)
|
|
244
|
+
else:
|
|
245
|
+
keychain.set(name, previous_secret)
|
|
246
|
+
path = store.environments_path
|
|
247
|
+
if previous_file is None:
|
|
248
|
+
if path.exists():
|
|
249
|
+
path.unlink()
|
|
250
|
+
else:
|
|
251
|
+
write_private(path, previous_file)
|
|
252
|
+
except Exception as exc:
|
|
253
|
+
raise AuthenticationError(
|
|
254
|
+
"Saving the environment failed, and the previous credentials could not be restored. "
|
|
255
|
+
"Run `benchling auth login --env NAME` again.",
|
|
256
|
+
details={"env": name, "reason": type(exc).__name__},
|
|
257
|
+
) from exc
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Named environments stored in environments.json.
|
|
2
|
+
|
|
3
|
+
The file holds the tenant URL and client ID only. Client secrets live in the
|
|
4
|
+
OS keychain. ``BENCHLING_<ENV>_*`` variables are not read.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from pydantic import ValidationError as ModelValidationError
|
|
16
|
+
|
|
17
|
+
from .config import ConfigStore
|
|
18
|
+
from .errors import ValidationError
|
|
19
|
+
from .models import AuthMethod, Environment, explain_environment_error
|
|
20
|
+
|
|
21
|
+
ENV_NAME = re.compile(r"^[a-z][a-z0-9]{0,31}$")
|
|
22
|
+
ENV_NAME_RULE = "use lowercase letters and digits, starting with a letter, at most 32 characters"
|
|
23
|
+
FILE_VERSION = 1
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def invalid_environment_name(name: str, *, available: list[str] | None = None) -> ValidationError:
|
|
27
|
+
"""Explain the environment-name rule. The submitted name is not treated as a secret."""
|
|
28
|
+
shown = f" {name!r}" if name and len(name) <= 64 and name.isprintable() else ""
|
|
29
|
+
return ValidationError(
|
|
30
|
+
f"Invalid environment name{shown}: {ENV_NAME_RULE}.",
|
|
31
|
+
details={"env": None, "available_envs": list(available or [])},
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def write_private(path: Path, text: str) -> None:
|
|
36
|
+
"""Atomically replace a file and force mode 0600, ignoring chmod failures."""
|
|
37
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
38
|
+
temporary = path.parent / f".{path.name}.tmp"
|
|
39
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
40
|
+
try:
|
|
41
|
+
try:
|
|
42
|
+
handle = os.fdopen(fd, "w", encoding="utf-8")
|
|
43
|
+
except Exception:
|
|
44
|
+
os.close(fd)
|
|
45
|
+
raise
|
|
46
|
+
with handle:
|
|
47
|
+
handle.write(text)
|
|
48
|
+
try:
|
|
49
|
+
os.chmod(temporary, 0o600)
|
|
50
|
+
except OSError:
|
|
51
|
+
pass
|
|
52
|
+
os.replace(temporary, path)
|
|
53
|
+
except Exception:
|
|
54
|
+
if temporary.exists():
|
|
55
|
+
temporary.unlink()
|
|
56
|
+
raise
|
|
57
|
+
try:
|
|
58
|
+
os.chmod(path, 0o600)
|
|
59
|
+
except OSError:
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class EnvironmentConfigStore(ConfigStore):
|
|
64
|
+
"""Resolve environments from environments.json under the state directory.
|
|
65
|
+
|
|
66
|
+
The inherited directories hold write plans and journals, not secrets.
|
|
67
|
+
Files saved by previous versions are never read.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def environments_path(self) -> Path:
|
|
72
|
+
"""Path of the non-secret environment file."""
|
|
73
|
+
return self.root / "environments.json"
|
|
74
|
+
|
|
75
|
+
def configured_names(self) -> list[str]:
|
|
76
|
+
"""Sorted environment names saved in environments.json."""
|
|
77
|
+
return sorted(self._records())
|
|
78
|
+
|
|
79
|
+
def resolve(self, name: str | None) -> Environment:
|
|
80
|
+
"""Build the Environment for a name.
|
|
81
|
+
|
|
82
|
+
Raises ValidationError if the name is missing, unknown, or the saved
|
|
83
|
+
record is invalid. The client secret is not loaded here.
|
|
84
|
+
"""
|
|
85
|
+
names = self.configured_names()
|
|
86
|
+
if not name:
|
|
87
|
+
raise ValidationError(
|
|
88
|
+
"An environment is required; pass --env NAME",
|
|
89
|
+
details={"available_envs": names},
|
|
90
|
+
)
|
|
91
|
+
if not ENV_NAME.match(name):
|
|
92
|
+
raise invalid_environment_name(name, available=names)
|
|
93
|
+
records = self._records()
|
|
94
|
+
if name not in records:
|
|
95
|
+
raise ValidationError(
|
|
96
|
+
f"Unknown environment {name!r}; run `benchling auth login --env {name}`",
|
|
97
|
+
details={"env": name, "available_envs": names},
|
|
98
|
+
)
|
|
99
|
+
return self._environment(name, records[name])
|
|
100
|
+
|
|
101
|
+
def metadata(self) -> dict[str, Any]:
|
|
102
|
+
"""Non-secret JSON description of every configured environment, keyed by name."""
|
|
103
|
+
return {
|
|
104
|
+
env: self.resolve(env).model_dump(mode="json", exclude_none=True)
|
|
105
|
+
for env in self.configured_names()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
def upsert(self, environment: Environment) -> None:
|
|
109
|
+
"""Insert or replace one environment's non-secret record."""
|
|
110
|
+
if not environment.client_id:
|
|
111
|
+
raise ValidationError("Client ID is required", details={"env": environment.name})
|
|
112
|
+
records = self._records() if self.environments_path.exists() else {}
|
|
113
|
+
records[environment.name] = {
|
|
114
|
+
"tenant_url": environment.base_url,
|
|
115
|
+
"client_id": environment.client_id,
|
|
116
|
+
}
|
|
117
|
+
self._write(records)
|
|
118
|
+
|
|
119
|
+
def remove(self, name: str) -> bool:
|
|
120
|
+
"""Remove one environment. Returns True when a record was deleted."""
|
|
121
|
+
if not self.environments_path.exists():
|
|
122
|
+
return False
|
|
123
|
+
records = self._records()
|
|
124
|
+
if name not in records:
|
|
125
|
+
return False
|
|
126
|
+
del records[name]
|
|
127
|
+
self._write(records)
|
|
128
|
+
return True
|
|
129
|
+
|
|
130
|
+
def _records(self) -> dict[str, Any]:
|
|
131
|
+
path = self.environments_path
|
|
132
|
+
if not path.exists():
|
|
133
|
+
return {}
|
|
134
|
+
try:
|
|
135
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
136
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
137
|
+
raise ValidationError(
|
|
138
|
+
"Could not read environments.json",
|
|
139
|
+
details={"path": str(path)},
|
|
140
|
+
) from exc
|
|
141
|
+
if not isinstance(raw, dict) or raw.get("version") != FILE_VERSION:
|
|
142
|
+
raise ValidationError("environments.json has an unsupported version")
|
|
143
|
+
environments = raw.get("environments")
|
|
144
|
+
if not isinstance(environments, dict):
|
|
145
|
+
raise ValidationError("environments.json is invalid")
|
|
146
|
+
for name in environments:
|
|
147
|
+
if not isinstance(name, str) or not ENV_NAME.match(name):
|
|
148
|
+
raise ValidationError("environments.json contains an invalid environment name")
|
|
149
|
+
if not isinstance(environments[name], dict):
|
|
150
|
+
raise ValidationError(
|
|
151
|
+
"environments.json is invalid",
|
|
152
|
+
details={"env": name},
|
|
153
|
+
)
|
|
154
|
+
return environments
|
|
155
|
+
|
|
156
|
+
def _environment(self, name: str, record: dict[str, Any]) -> Environment:
|
|
157
|
+
client_id = record.get("client_id")
|
|
158
|
+
if (
|
|
159
|
+
not isinstance(client_id, str)
|
|
160
|
+
or not client_id.strip()
|
|
161
|
+
or any(character in client_id for character in "\r\n\x00")
|
|
162
|
+
):
|
|
163
|
+
raise ValidationError("Invalid client ID", details={"env": name, "field": "client_id"})
|
|
164
|
+
tenant_url = record.get("tenant_url")
|
|
165
|
+
if not isinstance(tenant_url, str) or not tenant_url.strip():
|
|
166
|
+
raise ValidationError(
|
|
167
|
+
"Invalid tenant URL. Expected https://host, a bare host, or a host ending in "
|
|
168
|
+
"/api/v2 or /api/v3.",
|
|
169
|
+
details={"env": name, "field": "tenant_url"},
|
|
170
|
+
)
|
|
171
|
+
try:
|
|
172
|
+
environment = Environment.model_validate(
|
|
173
|
+
{
|
|
174
|
+
"name": name,
|
|
175
|
+
"tenant_url": tenant_url,
|
|
176
|
+
"client_id": client_id,
|
|
177
|
+
"auth_method": AuthMethod.CLIENT_CREDENTIALS,
|
|
178
|
+
}
|
|
179
|
+
)
|
|
180
|
+
except ModelValidationError as exc:
|
|
181
|
+
# Pydantic errors include input values; never expose them.
|
|
182
|
+
raise explain_environment_error(exc, env=name) from exc
|
|
183
|
+
return environment
|
|
184
|
+
|
|
185
|
+
def _write(self, records: dict[str, Any]) -> None:
|
|
186
|
+
self.ensure()
|
|
187
|
+
payload = {"version": FILE_VERSION, "environments": records}
|
|
188
|
+
write_private(self.environments_path, json.dumps(payload, indent=2) + "\n")
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Error taxonomy: each error carries a stable code and the CLI exit code it maps to."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import IntEnum
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ExitCode(IntEnum):
|
|
10
|
+
"""Process exit codes; 0 is success and each failure class has a distinct value."""
|
|
11
|
+
|
|
12
|
+
SUCCESS = 0
|
|
13
|
+
VALIDATION = 2
|
|
14
|
+
AUTHENTICATION = 3
|
|
15
|
+
ACCESS_OR_NOT_FOUND = 4
|
|
16
|
+
CONFLICT = 5
|
|
17
|
+
UNSUPPORTED = 6
|
|
18
|
+
UPSTREAM = 7
|
|
19
|
+
PARTIAL_OR_UNKNOWN = 8
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BenchlingAgentError(Exception):
|
|
23
|
+
"""Base for all expected failures; subclasses set code and exit_code.
|
|
24
|
+
|
|
25
|
+
details must be JSON-safe and free of secrets since it is emitted in the envelope.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
code = "benchling_error"
|
|
29
|
+
exit_code = ExitCode.UPSTREAM
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
message: str,
|
|
34
|
+
*,
|
|
35
|
+
details: dict[str, Any] | None = None,
|
|
36
|
+
retryable: bool = False,
|
|
37
|
+
) -> None:
|
|
38
|
+
super().__init__(message)
|
|
39
|
+
self.message = message
|
|
40
|
+
self.details = details or {}
|
|
41
|
+
self.retryable = retryable
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ValidationError(BenchlingAgentError):
|
|
45
|
+
"""Caller input or a change specification is invalid."""
|
|
46
|
+
|
|
47
|
+
code = "validation_error"
|
|
48
|
+
exit_code = ExitCode.VALIDATION
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class AuthenticationError(BenchlingAgentError):
|
|
52
|
+
"""Credentials are missing, rejected or could not be exchanged for a token."""
|
|
53
|
+
|
|
54
|
+
code = "authentication_error"
|
|
55
|
+
exit_code = ExitCode.AUTHENTICATION
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class AccessError(BenchlingAgentError):
|
|
59
|
+
"""Authenticated but not permitted to access the resource."""
|
|
60
|
+
|
|
61
|
+
code = "access_denied"
|
|
62
|
+
exit_code = ExitCode.ACCESS_OR_NOT_FOUND
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class NotFoundError(BenchlingAgentError):
|
|
66
|
+
"""The requested resource does not exist; shares an exit code with AccessError."""
|
|
67
|
+
|
|
68
|
+
code = "not_found"
|
|
69
|
+
exit_code = ExitCode.ACCESS_OR_NOT_FOUND
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ConflictError(BenchlingAgentError):
|
|
73
|
+
"""A plan precondition failed, e.g. the entry changed since the plan was made."""
|
|
74
|
+
|
|
75
|
+
code = "conflict"
|
|
76
|
+
exit_code = ExitCode.CONFLICT
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class UnsupportedError(BenchlingAgentError):
|
|
80
|
+
"""The operation or content type is not supported, or is unavailable on this tenant."""
|
|
81
|
+
|
|
82
|
+
code = "unsupported_capability"
|
|
83
|
+
exit_code = ExitCode.UNSUPPORTED
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class UpstreamError(BenchlingAgentError):
|
|
87
|
+
"""The remote API failed or returned an unexpected response; may be retryable."""
|
|
88
|
+
|
|
89
|
+
code = "upstream_error"
|
|
90
|
+
exit_code = ExitCode.UPSTREAM
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ApiDriftError(UpstreamError):
|
|
94
|
+
"""Benchling rejected a method this client still sends. The published API has moved."""
|
|
95
|
+
|
|
96
|
+
code = "api_drift"
|
|
97
|
+
exit_code = ExitCode.UPSTREAM
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class PartialCompletionError(BenchlingAgentError):
|
|
101
|
+
"""An apply finished only in part, or its outcome cannot be confirmed; inspect the journal."""
|
|
102
|
+
|
|
103
|
+
code = "partial_or_unknown_completion"
|
|
104
|
+
exit_code = ExitCode.PARTIAL_OR_UNKNOWN
|