codemie-cdk-python 0.1.0rc0__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.
- codemie_cdk_python-0.1.0rc0.dist-info/METADATA +840 -0
- codemie_cdk_python-0.1.0rc0.dist-info/RECORD +39 -0
- codemie_cdk_python-0.1.0rc0.dist-info/WHEEL +4 -0
- codemie_cdk_python-0.1.0rc0.dist-info/entry_points.txt +3 -0
- codemie_iac/__init__.py +49 -0
- codemie_iac/cli/__init__.py +17 -0
- codemie_iac/cli/__main__.py +24 -0
- codemie_iac/cli/commands/__init__.py +17 -0
- codemie_iac/cli/commands/apply.py +119 -0
- codemie_iac/cli/commands/plan.py +72 -0
- codemie_iac/cli/documents.py +59 -0
- codemie_iac/cli/env_file.py +62 -0
- codemie_iac/cli/exit_status.py +80 -0
- codemie_iac/cli/main.py +118 -0
- codemie_iac/cli/render.py +206 -0
- codemie_iac/cli/target_config.py +230 -0
- codemie_iac/cli/token_client.py +42 -0
- codemie_iac/credentials.py +99 -0
- codemie_iac/envelope.py +188 -0
- codemie_iac/plan_apply/__init__.py +70 -0
- codemie_iac/plan_apply/bulk_create.py +561 -0
- codemie_iac/plan_apply/credentials.py +306 -0
- codemie_iac/plan_apply/errors.py +223 -0
- codemie_iac/plan_apply/field_policy.py +185 -0
- codemie_iac/plan_apply/guards.py +221 -0
- codemie_iac/plan_apply/kinds.py +815 -0
- codemie_iac/plan_apply/lookup.py +313 -0
- codemie_iac/plan_apply/ordering.py +177 -0
- codemie_iac/plan_apply/single_apply.py +751 -0
- codemie_iac/resolver.py +61 -0
- codemie_iac/schema.py +106 -0
- codemie_iac/serializer.py +64 -0
- codemie_iac/specs/__init__.py +13 -0
- codemie_iac/specs/assistant.py +509 -0
- codemie_iac/specs/category.py +36 -0
- codemie_iac/specs/datasource.py +595 -0
- codemie_iac/specs/integration.py +103 -0
- codemie_iac/specs/skill.py +51 -0
- codemie_iac/specs/workflow.py +154 -0
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
# Copyright 2026 EPAM Systems, Inc. ("EPAM")
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Credential resolution that never leaks secret values."""
|
|
16
|
+
|
|
17
|
+
import copy
|
|
18
|
+
import os
|
|
19
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from pydantic import BaseModel
|
|
23
|
+
from pydantic_core import core_schema
|
|
24
|
+
|
|
25
|
+
from ..credentials import CredentialRef
|
|
26
|
+
from .errors import UnresolvableCredentialError
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"MCP_REF_FIELDS",
|
|
30
|
+
"SECRET_FIELDS",
|
|
31
|
+
"EnvCredentialResolver",
|
|
32
|
+
"ProviderSecretLookup",
|
|
33
|
+
"SecretValue",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
_MASK = "***"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SecretValue:
|
|
40
|
+
"""Holds a secret; repr/str/format are masked, ``reveal()`` returns it."""
|
|
41
|
+
|
|
42
|
+
__slots__ = ("_value",)
|
|
43
|
+
|
|
44
|
+
def __init__(self, value: str):
|
|
45
|
+
self._value = value
|
|
46
|
+
|
|
47
|
+
def reveal(self) -> str:
|
|
48
|
+
return self._value
|
|
49
|
+
|
|
50
|
+
def __repr__(self) -> str:
|
|
51
|
+
return f"SecretValue({_MASK})"
|
|
52
|
+
|
|
53
|
+
def __str__(self) -> str:
|
|
54
|
+
return _MASK
|
|
55
|
+
|
|
56
|
+
def __format__(self, format_spec: str) -> str:
|
|
57
|
+
return _MASK
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def __get_pydantic_core_schema__(cls, source: Any, handler: Any) -> Any:
|
|
61
|
+
return core_schema.is_instance_schema(
|
|
62
|
+
cls,
|
|
63
|
+
serialization=core_schema.plain_serializer_function_ser_schema(
|
|
64
|
+
lambda _v: _MASK
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def __reduce__(self) -> Any:
|
|
69
|
+
raise TypeError("SecretValue cannot be pickled")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _as_ref(value: Any) -> CredentialRef | None:
|
|
73
|
+
if isinstance(value, CredentialRef):
|
|
74
|
+
return value
|
|
75
|
+
if isinstance(value, str):
|
|
76
|
+
try:
|
|
77
|
+
return CredentialRef(value)
|
|
78
|
+
except ValueError:
|
|
79
|
+
return None
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
#: MCP server fields that can carry credential refs. The same list drives
|
|
84
|
+
#: collection (preflight, redaction) and revealing (request bodies), so a ref
|
|
85
|
+
#: is never revealed without having been collected, or the other way round.
|
|
86
|
+
MCP_REF_FIELDS = ("config", "mcp_connect_url", "arguments", "command")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _walk(value: Any) -> Iterator[Any]:
|
|
90
|
+
"""Every leaf (string or ``CredentialRef``) of a nested value."""
|
|
91
|
+
if isinstance(value, BaseModel) and not isinstance(value, CredentialRef):
|
|
92
|
+
for name in type(value).model_fields:
|
|
93
|
+
yield from _walk(getattr(value, name, None))
|
|
94
|
+
elif isinstance(value, Mapping):
|
|
95
|
+
for item in value.values():
|
|
96
|
+
yield from _walk(item)
|
|
97
|
+
elif isinstance(value, (list, tuple)):
|
|
98
|
+
for item in value:
|
|
99
|
+
yield from _walk(item)
|
|
100
|
+
else:
|
|
101
|
+
yield value
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _iter_config_values(server: Any) -> Iterator[Any]:
|
|
105
|
+
for field in MCP_REF_FIELDS:
|
|
106
|
+
yield from _walk(getattr(server, field, None))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _iter_servers(spec: Any) -> Iterator[Any]:
|
|
110
|
+
yield from getattr(spec, "mcp_servers", None) or []
|
|
111
|
+
workflow = getattr(spec, "workflow", None)
|
|
112
|
+
assistants = getattr(workflow, "assistants", None) or {}
|
|
113
|
+
for assistant in assistants.values():
|
|
114
|
+
yield from getattr(assistant, "mcp_servers", None) or []
|
|
115
|
+
for tool in getattr(workflow, "tools", None) or []:
|
|
116
|
+
if getattr(tool, "mcp_server", None) is not None:
|
|
117
|
+
yield tool.mcp_server
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# --- datasource secret fields ----------------------------------------------
|
|
121
|
+
|
|
122
|
+
# (provider_name, toolkit_id) -> names of settings the platform provider schema
|
|
123
|
+
# marks secret (parameter_type == SECRET). Injected by the caller that can reach
|
|
124
|
+
# the platform. While it is unset or failing, provider settings fail closed:
|
|
125
|
+
# every non-empty string setting must be an env: reference.
|
|
126
|
+
ProviderSecretLookup = Callable[[str, str], Iterable[str]]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _schema_secret_keys(
|
|
130
|
+
spec: Any, lookup: ProviderSecretLookup | None
|
|
131
|
+
) -> tuple[frozenset[str] | None, str]:
|
|
132
|
+
"""Secret setting names per the platform provider schema and, when the
|
|
133
|
+
schema is unavailable, ``None`` plus the reason (never the error text,
|
|
134
|
+
which could echo a value).
|
|
135
|
+
|
|
136
|
+
The result must be a collection of names. A bare string would split into
|
|
137
|
+
characters, so it counts as "schema unavailable", like any non-string
|
|
138
|
+
member. An empty collection is a valid answer: the schema marks no
|
|
139
|
+
setting secret."""
|
|
140
|
+
if lookup is None:
|
|
141
|
+
return None, "no lookup configured"
|
|
142
|
+
try:
|
|
143
|
+
keys = lookup(spec.provider_name, spec.toolkit_id)
|
|
144
|
+
if isinstance(keys, (str, bytes)):
|
|
145
|
+
return None, f"lookup returned {type(keys).__name__}, not a collection"
|
|
146
|
+
names = frozenset(keys)
|
|
147
|
+
except Exception as exc: # noqa: BLE001 - any lookup failure means "schema unknown"
|
|
148
|
+
return None, f"lookup raised {type(exc).__name__}"
|
|
149
|
+
if not all(isinstance(name, str) for name in names):
|
|
150
|
+
return None, "lookup returned a non-string name"
|
|
151
|
+
return names, ""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _string_leaves(value: Any) -> Iterator[Any]:
|
|
155
|
+
"""The leaves of ``value`` that could be a secret or an ``env:`` reference."""
|
|
156
|
+
return (
|
|
157
|
+
leaf
|
|
158
|
+
for leaf in _walk(value)
|
|
159
|
+
if isinstance(leaf, (str, CredentialRef)) and leaf != ""
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _provider_secret_settings(
|
|
164
|
+
spec: Any, lookup: ProviderSecretLookup | None
|
|
165
|
+
) -> Iterator[tuple[str, Any, str]]:
|
|
166
|
+
"""Schema-secret settings as ``(name, value, note)``. With the schema
|
|
167
|
+
unavailable every setting is in doubt, so must be an ``env:`` reference,
|
|
168
|
+
except values that hold no string (int, bool, float, None, containers of
|
|
169
|
+
those): those can be neither a secret string nor a reference. A dict or
|
|
170
|
+
list is in doubt per string leaf it contains."""
|
|
171
|
+
schema_keys, why = _schema_secret_keys(spec, lookup)
|
|
172
|
+
settings = getattr(spec, "settings", None) or {}
|
|
173
|
+
if schema_keys is not None:
|
|
174
|
+
for name, value in settings.items():
|
|
175
|
+
if name in schema_keys:
|
|
176
|
+
yield name, value, ""
|
|
177
|
+
return
|
|
178
|
+
note = f"; the provider schema lookup was unavailable ({why})"
|
|
179
|
+
for name, value in settings.items():
|
|
180
|
+
for leaf in _string_leaves(value):
|
|
181
|
+
yield name, leaf, note
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _sharepoint_secrets(
|
|
185
|
+
spec: Any, lookup: ProviderSecretLookup | None
|
|
186
|
+
) -> Iterator[tuple[str, Any, str]]:
|
|
187
|
+
yield "access_token", getattr(spec, "access_token", None), ""
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _no_secret_settings(
|
|
191
|
+
spec: Any, lookup: ProviderSecretLookup | None
|
|
192
|
+
) -> Iterator[tuple[str, Any, str]]:
|
|
193
|
+
return iter(())
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# Keyed by datasource ``type``; svn and xray have no secret fields. SharePoint
|
|
197
|
+
# carries its transient OAuth ``access_token`` as an ``env:`` reference.
|
|
198
|
+
SECRET_FIELDS: dict[
|
|
199
|
+
str,
|
|
200
|
+
Callable[[Any, ProviderSecretLookup | None], Iterable[tuple[str, Any, str]]],
|
|
201
|
+
] = {
|
|
202
|
+
"provider": _provider_secret_settings,
|
|
203
|
+
"svn": _no_secret_settings,
|
|
204
|
+
"knowledge_base_sharepoint": _sharepoint_secrets,
|
|
205
|
+
"knowledge_base_xray": _no_secret_settings,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _require_ref(spec: Any, setting: str, value: Any, note: str = "") -> Any:
|
|
210
|
+
"""``value`` when it is an ``env:`` reference; otherwise reject, naming the
|
|
211
|
+
setting but never echoing the value."""
|
|
212
|
+
if _as_ref(value) is None:
|
|
213
|
+
raise UnresolvableCredentialError(
|
|
214
|
+
"literal_secret",
|
|
215
|
+
"datasource",
|
|
216
|
+
str(getattr(spec, "name", "")),
|
|
217
|
+
f"secret setting {setting!r} must be an env: reference, "
|
|
218
|
+
f"not a literal value{note}",
|
|
219
|
+
)
|
|
220
|
+
return value
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _iter_datasource_secrets(
|
|
224
|
+
spec: Any, lookup: ProviderSecretLookup | None
|
|
225
|
+
) -> Iterator[Any]:
|
|
226
|
+
extract = SECRET_FIELDS.get(getattr(spec, "type", None), _no_secret_settings)
|
|
227
|
+
for setting, value, note in extract(spec, lookup):
|
|
228
|
+
if value not in (None, ""):
|
|
229
|
+
yield _require_ref(spec, setting, value, note)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _iter_provider_setting_refs(spec: Any) -> Iterator[Any]:
|
|
233
|
+
"""Every string leaf of the provider settings: the request body reveals
|
|
234
|
+
all ``env:`` references, so preflight must check all of them, not only the
|
|
235
|
+
ones the schema calls secret."""
|
|
236
|
+
if getattr(spec, "type", None) == "provider":
|
|
237
|
+
yield from _string_leaves(getattr(spec, "settings", None) or {})
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _iter_candidates(spec: Any, lookup: ProviderSecretLookup | None) -> Iterator[Any]:
|
|
241
|
+
for entry in getattr(spec, "credential_values", None) or []:
|
|
242
|
+
yield getattr(entry, "ref", None)
|
|
243
|
+
yield from _iter_datasource_secrets(spec, lookup)
|
|
244
|
+
yield from _iter_provider_setting_refs(spec)
|
|
245
|
+
for server in _iter_servers(spec):
|
|
246
|
+
yield from _iter_config_values(server)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class EnvCredentialResolver:
|
|
250
|
+
"""Resolves ``env:NAME`` references from an environment mapping."""
|
|
251
|
+
|
|
252
|
+
def __init__(
|
|
253
|
+
self,
|
|
254
|
+
environ: Mapping[str, str] | None = None,
|
|
255
|
+
provider_secret_lookup: ProviderSecretLookup | None = None,
|
|
256
|
+
):
|
|
257
|
+
self._environ = os.environ if environ is None else environ
|
|
258
|
+
self._revealed: set[str] = set()
|
|
259
|
+
self._provider_secret_lookup = provider_secret_lookup
|
|
260
|
+
|
|
261
|
+
def with_provider_secret_lookup(
|
|
262
|
+
self, lookup: ProviderSecretLookup | None
|
|
263
|
+
) -> "EnvCredentialResolver":
|
|
264
|
+
"""A resolver with ``lookup``; the original is not modified. The copy
|
|
265
|
+
shares the environment and the revealed-values set, so error scrubbing
|
|
266
|
+
still sees every value handed out."""
|
|
267
|
+
other = copy.copy(self)
|
|
268
|
+
other._provider_secret_lookup = lookup
|
|
269
|
+
return other
|
|
270
|
+
|
|
271
|
+
def revealed_values(self) -> frozenset[str]:
|
|
272
|
+
"""Secret values handed out so far, for scrubbing error text."""
|
|
273
|
+
return frozenset(self._revealed)
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def _var_name(ref: CredentialRef) -> str:
|
|
277
|
+
return ref.root.split(":", 1)[1]
|
|
278
|
+
|
|
279
|
+
def is_resolvable(self, ref: CredentialRef) -> bool:
|
|
280
|
+
return bool(self._environ.get(self._var_name(ref)))
|
|
281
|
+
|
|
282
|
+
def resolve(self, ref: CredentialRef) -> SecretValue:
|
|
283
|
+
value = self._environ.get(self._var_name(ref))
|
|
284
|
+
if not value:
|
|
285
|
+
raise UnresolvableCredentialError(
|
|
286
|
+
"unresolvable_credential",
|
|
287
|
+
"credential",
|
|
288
|
+
ref.root,
|
|
289
|
+
f"credential reference {ref.root!r} is unset or empty",
|
|
290
|
+
)
|
|
291
|
+
self._revealed.add(value)
|
|
292
|
+
return SecretValue(value)
|
|
293
|
+
|
|
294
|
+
def provider_secret_keys(self, spec: Any) -> frozenset[str] | None:
|
|
295
|
+
"""Secret setting names of a provider spec per the platform schema, or
|
|
296
|
+
``None`` when the schema is unavailable (no lookup, or it failed)."""
|
|
297
|
+
return _schema_secret_keys(spec, self._provider_secret_lookup)[0]
|
|
298
|
+
|
|
299
|
+
def collect_refs(self, spec: Any) -> list[CredentialRef]:
|
|
300
|
+
"""All distinct credential refs in a spec, in first-seen order."""
|
|
301
|
+
seen: dict[str, CredentialRef] = {}
|
|
302
|
+
for candidate in _iter_candidates(spec, self._provider_secret_lookup):
|
|
303
|
+
ref = _as_ref(candidate)
|
|
304
|
+
if ref is not None:
|
|
305
|
+
seen.setdefault(ref.root, ref)
|
|
306
|
+
return list(seen.values())
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# Copyright 2026 EPAM Systems, Inc. ("EPAM")
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Structured errors raised by the plan/apply layer."""
|
|
16
|
+
|
|
17
|
+
import base64
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
from collections.abc import Iterable
|
|
21
|
+
from typing import Any
|
|
22
|
+
from urllib.parse import quote, quote_plus, urlsplit
|
|
23
|
+
|
|
24
|
+
import requests
|
|
25
|
+
from codemie_sdk.exceptions import ApiError, CodeMieError
|
|
26
|
+
from pydantic import BaseModel, ConfigDict
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"PLATFORM_ERRORS",
|
|
30
|
+
"ApplyError",
|
|
31
|
+
"FieldError",
|
|
32
|
+
"PlatformRejectionError",
|
|
33
|
+
"UnresolvableCredentialError",
|
|
34
|
+
"UnresolvedReferenceError",
|
|
35
|
+
"scrub",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
_REDACTED = "[redacted]"
|
|
39
|
+
|
|
40
|
+
#: What a rejected platform call raises. The SDK calls ``raise_for_status()``,
|
|
41
|
+
#: so in practice it is ``requests.HTTPError``; ``ApiError`` is kept for
|
|
42
|
+
#: callers (and fakes) that raise the SDK's own error type.
|
|
43
|
+
PLATFORM_ERRORS = (ApiError, requests.HTTPError)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _forms(secret: str) -> set[str]:
|
|
47
|
+
"""The secret as it may appear in a response: raw, JSON-escaped,
|
|
48
|
+
URL-encoded, single-quoted for YAML, and base64 (standard and URL-safe)
|
|
49
|
+
of the bare value.
|
|
50
|
+
|
|
51
|
+
A composite encoding (``base64("user:secret")`` for basic auth) is not
|
|
52
|
+
covered: the other half is unknown here.
|
|
53
|
+
"""
|
|
54
|
+
raw = secret.encode()
|
|
55
|
+
return {
|
|
56
|
+
secret,
|
|
57
|
+
json.dumps(secret)[1:-1],
|
|
58
|
+
secret.replace("'", "''"),
|
|
59
|
+
quote(secret, safe=""),
|
|
60
|
+
quote_plus(secret),
|
|
61
|
+
base64.b64encode(raw).decode(),
|
|
62
|
+
base64.urlsafe_b64encode(raw).decode(),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def scrub(text: str, secrets: Iterable[str] = ()) -> str:
|
|
67
|
+
"""``text`` with every known secret value (in its common encodings)
|
|
68
|
+
replaced by a placeholder."""
|
|
69
|
+
forms = {f for s in secrets if s for f in _forms(s) if f}
|
|
70
|
+
for form in sorted(forms, key=len, reverse=True):
|
|
71
|
+
# A YAML dump folds a long value at its spaces (newline and indent),
|
|
72
|
+
# so a space matches any run of whitespace.
|
|
73
|
+
pattern = r"\s+".join(re.escape(part) for part in form.split(" "))
|
|
74
|
+
text = re.sub(pattern, _REDACTED, text)
|
|
75
|
+
return text
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class FieldError(BaseModel):
|
|
79
|
+
"""A single field-level problem reported by the platform."""
|
|
80
|
+
|
|
81
|
+
model_config = ConfigDict(extra="forbid")
|
|
82
|
+
|
|
83
|
+
field: str
|
|
84
|
+
message: str
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ApplyError(CodeMieError):
|
|
88
|
+
"""Base error for a failure while planning or applying one entity."""
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self, error_type: str, entity_kind: str, entity_name: str, reason: str
|
|
92
|
+
):
|
|
93
|
+
self.error_type = error_type
|
|
94
|
+
self.entity_kind = entity_kind
|
|
95
|
+
self.entity_name = entity_name
|
|
96
|
+
self.reason = reason
|
|
97
|
+
super().__init__(f"{entity_kind}/{entity_name}: {reason}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class UnresolvedReferenceError(ApplyError):
|
|
101
|
+
"""A reference to another entity could not be resolved."""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class UnresolvableCredentialError(ApplyError):
|
|
105
|
+
"""A credential value could not be resolved."""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
_GENERAL = "(request)"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _loc_field(loc: Any) -> str:
|
|
112
|
+
parts = [str(p) for p in loc if p != "body"] if isinstance(loc, list) else []
|
|
113
|
+
return ".".join(parts) or _GENERAL
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _fastapi_errors(detail: Any, secrets: Iterable[str]) -> list[FieldError]:
|
|
117
|
+
"""FastAPI validation errors: ``detail: [{loc, msg}]`` (or a plain string)."""
|
|
118
|
+
if isinstance(detail, str):
|
|
119
|
+
return [FieldError(field=_GENERAL, message=scrub(detail, secrets))]
|
|
120
|
+
found = []
|
|
121
|
+
for item in detail if isinstance(detail, list) else []:
|
|
122
|
+
if isinstance(item, dict) and isinstance(item.get("msg"), str):
|
|
123
|
+
found.append(
|
|
124
|
+
FieldError(
|
|
125
|
+
field=scrub(_loc_field(item.get("loc")), secrets),
|
|
126
|
+
message=scrub(item["msg"], secrets),
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
return found
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _backend_errors(error: Any, secrets: Iterable[str]) -> list[FieldError]:
|
|
133
|
+
"""The backend envelope: ``{"error": {"message", "details", "help"}}``."""
|
|
134
|
+
if not isinstance(error, dict) or not isinstance(error.get("message"), str):
|
|
135
|
+
return []
|
|
136
|
+
message = error["message"]
|
|
137
|
+
details = error.get("details")
|
|
138
|
+
if isinstance(details, str) and details:
|
|
139
|
+
message = f"{message}: {details}"
|
|
140
|
+
return [FieldError(field=_GENERAL, message=scrub(message, secrets))]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _parse_field_errors(
|
|
144
|
+
body: Any, secrets: Iterable[str] = ()
|
|
145
|
+
) -> list[FieldError] | None:
|
|
146
|
+
"""Field errors as the backend sends them (secrets scrubbed); None when none."""
|
|
147
|
+
if not isinstance(body, dict):
|
|
148
|
+
return None
|
|
149
|
+
parsed = _fastapi_errors(body.get("detail"), secrets) or _backend_errors(
|
|
150
|
+
body.get("error"), secrets
|
|
151
|
+
)
|
|
152
|
+
return parsed or None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _status_and_body(cause: Exception) -> tuple[int | None, Any]:
|
|
156
|
+
if isinstance(cause, requests.HTTPError):
|
|
157
|
+
response = cause.response
|
|
158
|
+
if response is None:
|
|
159
|
+
return None, None
|
|
160
|
+
try:
|
|
161
|
+
return response.status_code, response.json()
|
|
162
|
+
except ValueError:
|
|
163
|
+
return response.status_code, None
|
|
164
|
+
return getattr(cause, "status_code", None), getattr(cause, "response", None)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class PlatformRejectionError(ApplyError):
|
|
168
|
+
"""The platform rejected a create/update call.
|
|
169
|
+
|
|
170
|
+
Keeps only the scrubbed message, the HTTP status and the parsed field
|
|
171
|
+
errors; the original exception (whose request body holds the resolved
|
|
172
|
+
credentials) is deliberately not kept, so a printed traceback cannot
|
|
173
|
+
show it.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
def __init__(
|
|
177
|
+
self,
|
|
178
|
+
error_type: str,
|
|
179
|
+
entity_kind: str,
|
|
180
|
+
entity_name: str,
|
|
181
|
+
cause: ApiError | requests.HTTPError,
|
|
182
|
+
secrets: Iterable[str] = (),
|
|
183
|
+
):
|
|
184
|
+
secrets = tuple(secrets)
|
|
185
|
+
self.status_code, body = _status_and_body(cause)
|
|
186
|
+
self.structured_errors: list[FieldError] | None = _parse_field_errors(
|
|
187
|
+
body, secrets
|
|
188
|
+
)
|
|
189
|
+
super().__init__(
|
|
190
|
+
error_type, entity_kind, entity_name, scrub(str(cause), secrets)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
_DETAIL_LIMIT = 500
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _request_path(exc: BaseException) -> str:
|
|
198
|
+
response = getattr(exc, "response", None)
|
|
199
|
+
url = getattr(response, "url", None)
|
|
200
|
+
return urlsplit(url).path if isinstance(url, str) else ""
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def platform_detail(exc: BaseException) -> str | None:
|
|
204
|
+
"""``"<status>: <message>"`` of a platform HTTP error, else ``None``.
|
|
205
|
+
|
|
206
|
+
Without a parsable message the status (and the request path, when known)
|
|
207
|
+
is still returned, so an expired token and a wrong id stay distinguishable.
|
|
208
|
+
|
|
209
|
+
For errors that do not pass through ``PlatformRejectionError`` (a failing
|
|
210
|
+
read while planning): ``requests.HTTPError`` keeps the platform's
|
|
211
|
+
explanation only in its response, not in ``str(exc)``. Not scrubbed:
|
|
212
|
+
callers scrub with the secrets they know. Capped.
|
|
213
|
+
"""
|
|
214
|
+
if not isinstance(exc, PLATFORM_ERRORS):
|
|
215
|
+
return None
|
|
216
|
+
status, body = _status_and_body(exc)
|
|
217
|
+
if status is None:
|
|
218
|
+
return None
|
|
219
|
+
errors = _parse_field_errors(body)
|
|
220
|
+
if not errors:
|
|
221
|
+
return f"{status} {_request_path(exc)}".strip()
|
|
222
|
+
message = "; ".join(e.message for e in errors)
|
|
223
|
+
return f"{status}: {message[:_DETAIL_LIMIT]}"
|