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.
Files changed (39) hide show
  1. codemie_cdk_python-0.1.0rc0.dist-info/METADATA +840 -0
  2. codemie_cdk_python-0.1.0rc0.dist-info/RECORD +39 -0
  3. codemie_cdk_python-0.1.0rc0.dist-info/WHEEL +4 -0
  4. codemie_cdk_python-0.1.0rc0.dist-info/entry_points.txt +3 -0
  5. codemie_iac/__init__.py +49 -0
  6. codemie_iac/cli/__init__.py +17 -0
  7. codemie_iac/cli/__main__.py +24 -0
  8. codemie_iac/cli/commands/__init__.py +17 -0
  9. codemie_iac/cli/commands/apply.py +119 -0
  10. codemie_iac/cli/commands/plan.py +72 -0
  11. codemie_iac/cli/documents.py +59 -0
  12. codemie_iac/cli/env_file.py +62 -0
  13. codemie_iac/cli/exit_status.py +80 -0
  14. codemie_iac/cli/main.py +118 -0
  15. codemie_iac/cli/render.py +206 -0
  16. codemie_iac/cli/target_config.py +230 -0
  17. codemie_iac/cli/token_client.py +42 -0
  18. codemie_iac/credentials.py +99 -0
  19. codemie_iac/envelope.py +188 -0
  20. codemie_iac/plan_apply/__init__.py +70 -0
  21. codemie_iac/plan_apply/bulk_create.py +561 -0
  22. codemie_iac/plan_apply/credentials.py +306 -0
  23. codemie_iac/plan_apply/errors.py +223 -0
  24. codemie_iac/plan_apply/field_policy.py +185 -0
  25. codemie_iac/plan_apply/guards.py +221 -0
  26. codemie_iac/plan_apply/kinds.py +815 -0
  27. codemie_iac/plan_apply/lookup.py +313 -0
  28. codemie_iac/plan_apply/ordering.py +177 -0
  29. codemie_iac/plan_apply/single_apply.py +751 -0
  30. codemie_iac/resolver.py +61 -0
  31. codemie_iac/schema.py +106 -0
  32. codemie_iac/serializer.py +64 -0
  33. codemie_iac/specs/__init__.py +13 -0
  34. codemie_iac/specs/assistant.py +509 -0
  35. codemie_iac/specs/category.py +36 -0
  36. codemie_iac/specs/datasource.py +595 -0
  37. codemie_iac/specs/integration.py +103 -0
  38. codemie_iac/specs/skill.py +51 -0
  39. codemie_iac/specs/workflow.py +154 -0
@@ -0,0 +1,206 @@
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
+ """Text and JSON rendering of plan/apply results and errors.
16
+
17
+ Every renderer returns a ``str``. Only engine-scrubbed fields (``reason``,
18
+ ``structured_errors``) are used for errors, never ``str(exc)``; the final
19
+ output is additionally passed through ``scrub()`` with any extra ``secrets``.
20
+ """
21
+
22
+ import json
23
+ from collections.abc import Iterable
24
+ from typing import Any
25
+
26
+ from pydantic import ValidationError
27
+
28
+ from ..plan_apply import (
29
+ ApplyError,
30
+ ApplyResult,
31
+ BulkCreateReport,
32
+ Plan,
33
+ )
34
+ from ..plan_apply.errors import platform_detail, scrub
35
+ from .documents import InvalidDocumentError
36
+ from .exit_status import ExitStatus
37
+ from .target_config import ConfigError
38
+
39
+ __all__ = [
40
+ "render_apply_result",
41
+ "render_bulk_report",
42
+ "render_error",
43
+ "render_plan",
44
+ ]
45
+
46
+
47
+ def _scrub_value(value: Any, secrets: tuple[str, ...]) -> Any:
48
+ if isinstance(value, str):
49
+ return scrub(value, secrets)
50
+ if isinstance(value, dict):
51
+ return {
52
+ _scrub_value(k, secrets): _scrub_value(v, secrets) for k, v in value.items()
53
+ }
54
+ if isinstance(value, list):
55
+ return [_scrub_value(v, secrets) for v in value]
56
+ return value
57
+
58
+
59
+ def _emit_json(payload: dict, status: ExitStatus, secrets: Iterable[str]) -> str:
60
+ payload = {
61
+ **payload,
62
+ "status": ExitStatus(status).name.lower(),
63
+ "exit_code": int(status),
64
+ }
65
+ return (
66
+ json.dumps(_scrub_value(payload, tuple(secrets)), indent=2, default=str) + "\n"
67
+ )
68
+
69
+
70
+ def _emit_text(lines: list[str], secrets: Iterable[str]) -> str:
71
+ return scrub("\n".join(lines), tuple(secrets)) + "\n"
72
+
73
+
74
+ def _val(value: Any) -> str:
75
+ return json.dumps(value, default=str, sort_keys=True)
76
+
77
+
78
+ def _field_error_lines(errors: Any, indent: str = " ") -> list[str]:
79
+ return [f"{indent}- {e.field}: {e.message}" for e in errors or []]
80
+
81
+
82
+ def render_plan(
83
+ plan: Plan,
84
+ *,
85
+ json_output: bool,
86
+ status: ExitStatus,
87
+ secrets: Iterable[str] = (),
88
+ ) -> str:
89
+ """Render a plan: differences, and ``cannot_compare`` as warnings."""
90
+ if json_output:
91
+ return _emit_json(plan.model_dump(mode="json"), status, secrets)
92
+ lines = ["No differences." if plan.is_empty else "Differences:"]
93
+ for d in plan.differences:
94
+ lines.append(f" {d.field}")
95
+ lines.append(f" document: {_val(d.document_value)}")
96
+ lines.append(f" live: {_val(d.live_value)}")
97
+ lines += [
98
+ f"warning: cannot compare {c.field}: {c.reason}" for c in plan.cannot_compare
99
+ ]
100
+ return _emit_text(lines, secrets)
101
+
102
+
103
+ def _id_suffix(entity_id: str | None) -> str:
104
+ # The platform does not return an id for every kind (e.g. integrations).
105
+ return f" (id: {entity_id})" if entity_id else ""
106
+
107
+
108
+ def _apply_headline(result: ApplyResult) -> str:
109
+ if result.created:
110
+ return f"created{_id_suffix(result.id)}"
111
+ if not result.changed:
112
+ return f"no change made{_id_suffix(result.id)}"
113
+ return f"updated{_id_suffix(result.id)}"
114
+
115
+
116
+ def render_apply_result(
117
+ result: ApplyResult,
118
+ *,
119
+ json_output: bool,
120
+ status: ExitStatus,
121
+ secrets: Iterable[str] = (),
122
+ ) -> str:
123
+ """Render a single-entity apply outcome."""
124
+ if json_output:
125
+ return _emit_json(result.model_dump(mode="json"), status, secrets)
126
+ lines = [_apply_headline(result)]
127
+ lines += [f"warning: could not compare {f}" for f in result.uncomparable]
128
+ return _emit_text(lines, secrets)
129
+
130
+
131
+ def render_bulk_report(
132
+ report: BulkCreateReport,
133
+ *,
134
+ json_output: bool,
135
+ status: ExitStatus,
136
+ secrets: Iterable[str] = (),
137
+ ) -> str:
138
+ """Render a bulk create report: created entities and the first failure."""
139
+ if json_output:
140
+ return _emit_json(report.model_dump(mode="json"), status, secrets)
141
+ lines = [f"created {len(report.created)}:"]
142
+ lines += [f" {c.kind.value}/{c.name}{_id_suffix(c.id)}" for c in report.created]
143
+ failed = report.failed
144
+ if failed is not None:
145
+ lines.append(f"failed: {failed.kind.value}/{failed.name} [{failed.error_type}]")
146
+ lines.append(f" reason: {failed.reason}")
147
+ lines += _field_error_lines(failed.structured_errors)
148
+ return _emit_text(lines, secrets)
149
+
150
+
151
+ def _validation_reason(exc: ValidationError) -> str:
152
+ """``loc: message`` per problem; never the offending input value."""
153
+ return "; ".join(
154
+ f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}" for e in exc.errors()
155
+ )
156
+
157
+
158
+ def _error_payload(exc: BaseException) -> dict:
159
+ if isinstance(exc, ApplyError):
160
+ errors = getattr(exc, "structured_errors", None)
161
+ return {
162
+ "error_type": exc.error_type,
163
+ "kind": exc.entity_kind,
164
+ "name": exc.entity_name,
165
+ "reason": exc.reason,
166
+ "structured_errors": (
167
+ [e.model_dump(mode="json") for e in errors] if errors else None
168
+ ),
169
+ }
170
+ if isinstance(exc, (ConfigError, InvalidDocumentError)):
171
+ reason = str(exc)
172
+ elif isinstance(exc, ValidationError):
173
+ reason = _validation_reason(exc)
174
+ else:
175
+ reason = platform_detail(exc) # the HTTP response body, scrubbed on emit
176
+ return {"error_type": type(exc).__name__, "reason": reason}
177
+
178
+
179
+ def _error_lines(exc: BaseException, payload: dict) -> list[str]:
180
+ if isinstance(exc, ApplyError):
181
+ lines = [
182
+ f"error: {payload['kind']}/{payload['name']} [{payload['error_type']}]",
183
+ f" reason: {payload['reason']}",
184
+ ]
185
+ return lines + _field_error_lines(getattr(exc, "structured_errors", None))
186
+ if payload["reason"]:
187
+ return [f"error: {payload['error_type']}: {payload['reason']}"]
188
+ return [f"error: {payload['error_type']}"]
189
+
190
+
191
+ def render_error(
192
+ exc: BaseException,
193
+ *,
194
+ json_output: bool,
195
+ status: ExitStatus,
196
+ secrets: Iterable[str] = (),
197
+ ) -> str:
198
+ """Render an error from its scrubbed fields; never ``str(exc)``.
199
+
200
+ Only ``ConfigError`` and ``InvalidDocumentError`` (documented secret-free)
201
+ expose their message.
202
+ """
203
+ payload = _error_payload(exc)
204
+ if json_output:
205
+ return _emit_json(payload, status, secrets)
206
+ return _emit_text(_error_lines(exc, payload), secrets)
@@ -0,0 +1,230 @@
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
+ """Target project and platform connection settings for the plan/apply CLI.
16
+
17
+ Precedence per key: command-line flag > environment variable (the real
18
+ environment, then a ``.env`` file that only fills in unset names) > the
19
+ ``environment:`` mapping of ``codemie.yaml`` > the legacy ``api:`` mapping.
20
+ String values in the file may reference ``${NAME}`` / ``${NAME:-default}``.
21
+ """
22
+
23
+ import os
24
+ import re
25
+ from dataclasses import dataclass, field
26
+ from typing import Any, Mapping, Optional, Union
27
+
28
+ import yaml
29
+ from codemie_sdk import CodeMieClient
30
+
31
+ from .env_file import read_env_file
32
+ from .token_client import TokenClient
33
+
34
+ __all__ = ["ConfigError", "TargetConfig", "DEFAULT_CONFIG_PATH"]
35
+
36
+ DEFAULT_CONFIG_PATH = "./codemie.yaml"
37
+ DEFAULT_ENV_FILE = "./.env"
38
+
39
+ #: client argument -> (env var, ``environment:`` key, legacy ``api:`` key)
40
+ _API_URL = ("codemie_api_domain", "CODEMIE_API_URL", "codemie_api_url", "url")
41
+ _KEYCLOAK = {
42
+ "auth_server_url": ("CODEMIE_AUTH_URL", "auth_server_url", "auth_url"),
43
+ "auth_realm_name": ("CODEMIE_REALM", "auth_realm_name", "realm"),
44
+ }
45
+ _OPTIONAL = {
46
+ "auth_client_id": ("CODEMIE_CLIENT_ID", "client_id", None),
47
+ "auth_client_secret": ("CODEMIE_CLIENT_SECRET", "client_secret", None),
48
+ "username": ("CODEMIE_USERNAME", "username", None),
49
+ "password": ("CODEMIE_PASSWORD", "password", None),
50
+ }
51
+ _JWT = ("CODEMIE_JWT_TOKEN", "jwt_token", None)
52
+ _VAR = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}")
53
+
54
+
55
+ class ConfigError(Exception):
56
+ """Missing or invalid target configuration; the message never holds secrets."""
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class TargetConfig:
61
+ """Resolved target project and client connection settings."""
62
+
63
+ project: str
64
+ _client_args: Mapping[str, Optional[str]] = field(repr=False)
65
+ _jwt_token: Optional[str] = field(default=None, repr=False)
66
+ _verify_ssl: bool = True
67
+ _environ: Mapping[str, str] = field(default_factory=dict, repr=False)
68
+
69
+ @classmethod
70
+ def resolve(
71
+ cls,
72
+ project_flag: Optional[str],
73
+ config_path: Optional[str],
74
+ environ: Optional[Mapping[str, str]] = None,
75
+ env_file: Optional[str] = None,
76
+ ) -> "TargetConfig":
77
+ """Merge flag, environment, ``.env`` and ``codemie.yaml`` values."""
78
+ real = os.environ if environ is None else environ
79
+ env = {**_load_env_file(env_file), **real}
80
+ document = _expand(_load_document(config_path), env)
81
+ project = project_flag or env.get("CODEMIE_PROJECT") or _file_project(document)
82
+ if not project:
83
+ raise ConfigError(
84
+ "Missing project: use --project, CODEMIE_PROJECT or project.name "
85
+ "in codemie.yaml"
86
+ )
87
+ jwt = _lookup(env, document, _JWT)
88
+ return cls(
89
+ project=project,
90
+ _client_args=_client_args(env, document, bool(jwt)),
91
+ _jwt_token=jwt,
92
+ _verify_ssl=_verify_ssl(env),
93
+ _environ=env,
94
+ )
95
+
96
+ @property
97
+ def environment(self) -> Mapping[str, str]:
98
+ """Real environment merged over ``.env``; what ``env:NAME`` credentials read."""
99
+ return self._environ
100
+
101
+ def build_client(self) -> Union[CodeMieClient, TokenClient]:
102
+ """Construct the platform client (token client when a JWT is set)."""
103
+ if self._jwt_token:
104
+ return TokenClient(
105
+ str(self._client_args["codemie_api_domain"]),
106
+ self._jwt_token,
107
+ verify_ssl=self._verify_ssl,
108
+ )
109
+ return CodeMieClient(**self._client_args, verify_ssl=self._verify_ssl)
110
+
111
+
112
+ def _load_document(config_path: Optional[str]) -> dict[str, Any]:
113
+ """Parse the config file; only a missing *default* file is tolerated."""
114
+ explicit = config_path is not None
115
+ path = config_path if explicit else DEFAULT_CONFIG_PATH
116
+ try:
117
+ with open(path, encoding="utf-8") as handle:
118
+ data = yaml.safe_load(handle)
119
+ except FileNotFoundError:
120
+ if explicit:
121
+ raise ConfigError(f"Config file {path} cannot be read") from None
122
+ return {}
123
+ except (OSError, UnicodeDecodeError):
124
+ raise ConfigError(f"Config file {path} cannot be read") from None
125
+ except yaml.YAMLError:
126
+ raise ConfigError(f"Config file {path} is not valid YAML") from None
127
+ if data is None:
128
+ return {}
129
+ if not isinstance(data, dict):
130
+ raise ConfigError(f"Config file {path} must contain a YAML mapping")
131
+ return data
132
+
133
+
134
+ def _load_env_file(env_file: Optional[str]) -> dict[str, str]:
135
+ """Read ``.env``; only a missing *default* file is tolerated."""
136
+ explicit = env_file is not None
137
+ path = env_file if explicit else DEFAULT_ENV_FILE
138
+ try:
139
+ return read_env_file(path)
140
+ except FileNotFoundError:
141
+ if explicit:
142
+ raise ConfigError(f"Env file {path} cannot be read") from None
143
+ return {}
144
+ except (OSError, UnicodeDecodeError):
145
+ raise ConfigError(f"Env file {path} cannot be read") from None
146
+
147
+
148
+ def _mapping(document: Mapping[str, Any], key: str) -> Mapping[str, Any]:
149
+ value = document.get(key)
150
+ return value if isinstance(value, dict) else {}
151
+
152
+
153
+ def _file_project(document: Mapping[str, Any]) -> Optional[str]:
154
+ name = _mapping(document, "project").get("name")
155
+ return str(name) if name else None
156
+
157
+
158
+ def _substitute(match: "re.Match[str]", env: Mapping[str, str]) -> str:
159
+ name, default = match.group(1), match.group(2)
160
+ found = env.get(name)
161
+ if found:
162
+ return found
163
+ if default is None:
164
+ raise ConfigError(
165
+ f"codemie.yaml references ${{{name}}}, which is not set "
166
+ f"(use ${{{name}:-}} to allow an empty value)"
167
+ )
168
+ return default
169
+
170
+
171
+ def _expand(value: Any, env: Mapping[str, str]) -> Any:
172
+ """Expand ``${NAME}`` / ``${NAME:-default}`` in every string, recursively.
173
+
174
+ A ``${NAME}`` that is unset or empty is a config error; ``${NAME:-}`` is how
175
+ a value is allowed to be empty.
176
+ """
177
+ if isinstance(value, str):
178
+ return _VAR.sub(lambda m: _substitute(m, env), value)
179
+ if isinstance(value, dict):
180
+ return {key: _expand(item, env) for key, item in value.items()}
181
+ if isinstance(value, list):
182
+ return [_expand(item, env) for item in value]
183
+ return value
184
+
185
+
186
+ def _verify_ssl(env: Mapping[str, str]) -> bool:
187
+ return (env.get("CODEMIE_VERIFY_SSL") or "true").strip().lower() != "false"
188
+
189
+
190
+ def _lookup(
191
+ env: Mapping[str, str],
192
+ document: Mapping[str, Any],
193
+ spec: tuple[str, str, Optional[str]],
194
+ ) -> Optional[str]:
195
+ """Environment variable > ``environment:`` value > legacy ``api:`` value."""
196
+ env_name, env_key, api_key = spec
197
+ value = env.get(env_name) or _mapping(document, "environment").get(env_key)
198
+ if not value and api_key:
199
+ value = _mapping(document, "api").get(api_key)
200
+ return str(value) if value else None
201
+
202
+
203
+ def _require(
204
+ env: Mapping[str, str],
205
+ document: Mapping[str, Any],
206
+ spec: tuple[str, str, Optional[str]],
207
+ ) -> str:
208
+ value = _lookup(env, document, spec)
209
+ if not value:
210
+ env_name, env_key, _ = spec
211
+ raise ConfigError(
212
+ f"Missing {env_name} (or environment.{env_key} in codemie.yaml)"
213
+ )
214
+ return value
215
+
216
+
217
+ def _client_args(
218
+ env: Mapping[str, str], document: Mapping[str, Any], jwt_mode: bool
219
+ ) -> dict[str, Optional[str]]:
220
+ arg, env_name, env_key, api_key = _API_URL
221
+ args: dict[str, Optional[str]] = {
222
+ arg: _require(env, document, (env_name, env_key, api_key))
223
+ }
224
+ if jwt_mode:
225
+ return args
226
+ for arg, spec in _KEYCLOAK.items():
227
+ args[arg] = _require(env, document, spec)
228
+ for arg, spec in _OPTIONAL.items():
229
+ args[arg] = _lookup(env, document, spec)
230
+ return args
@@ -0,0 +1,42 @@
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
+ """Bearer-token client for JWT mode.
16
+
17
+ ``CodeMieClient`` cannot take a plain JWT (its ``external_token`` goes through a
18
+ Keycloak exchange), but the SDK services accept a static token. This client
19
+ exposes every service the plan/apply engine uses, built as ``CodeMieClient`` does.
20
+ """
21
+
22
+ from codemie_sdk.services.assistant import AssistantService
23
+ from codemie_sdk.services.categories import CategoryService
24
+ from codemie_sdk.services.datasource import DatasourceService
25
+ from codemie_sdk.services.integration import IntegrationService
26
+ from codemie_sdk.services.skill import SkillService
27
+ from codemie_sdk.services.workflow import WorkflowService
28
+
29
+ __all__ = ["TokenClient"]
30
+
31
+
32
+ class TokenClient:
33
+ """Minimal ``CodeMieClient`` stand-in authenticated with a static bearer token."""
34
+
35
+ def __init__(self, api_domain: str, token: str, verify_ssl: bool = True):
36
+ domain = api_domain.rstrip("/")
37
+ self.assistants = AssistantService(domain, token, verify_ssl=verify_ssl)
38
+ self.categories = CategoryService(domain, token, verify_ssl=verify_ssl)
39
+ self.datasources = DatasourceService(domain, token, verify_ssl=verify_ssl)
40
+ self.integrations = IntegrationService(domain, token, verify_ssl=verify_ssl)
41
+ self.skills = SkillService(domain, token, verify_ssl=verify_ssl)
42
+ self.workflows = WorkflowService(domain, token, verify_ssl=verify_ssl)
@@ -0,0 +1,99 @@
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
+ import re
16
+ import threading
17
+ from pydantic import RootModel, model_validator
18
+
19
+ # CR-001: the shape check alone (`<alnum>+:<alnum/underscore>+`) accepts any
20
+ # colon-delimited literal with a lowercase-alnum prefix -- including a secret
21
+ # string that happens to be formatted that way. Restricting the prefix to a
22
+ # known, closed set of reference sources means an arbitrary literal cannot
23
+ # coincidentally satisfy the reference shape; "env" is the only source this
24
+ # module currently produces (via `from_entity`).
25
+ _REF_PATTERN = re.compile(r"^(?P<source>[a-z0-9]+):(?P<identifier>[A-Za-z0-9_]+)$")
26
+ _KNOWN_SOURCES = frozenset({"env"})
27
+
28
+ # CR-002: `from_entity`'s sanitization is intentionally lossy (distinct
29
+ # identifiers that differ only in punctuation collapse to the same output --
30
+ # see test_from_entity_sanitizes_non_alphanumeric), so two genuinely distinct
31
+ # (identifier, credential_key) pairs can collide onto the same CredentialRef
32
+ # string. The information needed to detect that (the original, pre-sanitized
33
+ # pair) only exists at the moment `from_entity` is called -- once a Bundle
34
+ # holds the final ref string, that provenance is gone. This process-lifetime
35
+ # registry remembers which pair produced which ref string, and raises if a
36
+ # *different* pair ever produces one already claimed by another pair. Calling
37
+ # `from_entity` again with the exact same pair (determinism, AC8) is not a
38
+ # collision and never raises.
39
+ _SEEN_REFS_LOCK = threading.Lock()
40
+ _SEEN_REFS: dict[str, tuple[str, str]] = {}
41
+
42
+
43
+ class CredentialRef(RootModel[str]):
44
+ @model_validator(mode="after")
45
+ def _check_format(self) -> "CredentialRef":
46
+ match = _REF_PATTERN.fullmatch(self.root)
47
+ if not match or match.group("source") not in _KNOWN_SOURCES:
48
+ raise ValueError(
49
+ "CredentialRef must match '<source>:<identifier>' with a "
50
+ f"known source {sorted(_KNOWN_SOURCES)!r}, got {self.root!r}"
51
+ )
52
+ return self
53
+
54
+ @classmethod
55
+ def from_entity(cls, identifier: str, credential_key: str) -> "CredentialRef":
56
+ def sanitize(value: str) -> str:
57
+ return re.sub(r"[^A-Za-z0-9]+", "_", value)
58
+
59
+ sanitized_id = sanitize(identifier).upper()
60
+ sanitized_key = sanitize(credential_key).upper()
61
+ if not any(c.isalnum() for c in sanitized_id) or not any(
62
+ c.isalnum() for c in sanitized_key
63
+ ):
64
+ raise ValueError(
65
+ "CredentialRef.from_entity requires identifier and "
66
+ "credential_key to each contain at least one alphanumeric "
67
+ f"character, got identifier={identifier!r}, "
68
+ f"credential_key={credential_key!r}"
69
+ )
70
+
71
+ ref_string = f"env:{sanitized_id}_{sanitized_key}"
72
+ pair = (identifier, credential_key)
73
+ with _SEEN_REFS_LOCK:
74
+ existing = _SEEN_REFS.get(ref_string)
75
+ if existing is not None and existing != pair:
76
+ raise ValueError(
77
+ f"CredentialRef collision: identifier/credential_key "
78
+ f"pairs {existing!r} and {pair!r} both sanitize to "
79
+ f"{ref_string!r}; use more distinguishable identifiers "
80
+ "or credential keys."
81
+ )
82
+ _SEEN_REFS[ref_string] = pair
83
+ return cls(ref_string)
84
+
85
+
86
+ def reset_registry() -> None:
87
+ """Clear the process-lifetime collision registry (CR-001).
88
+
89
+ ``_SEEN_REFS`` otherwise accumulates for the lifetime of the process,
90
+ with no bound and no scoping to any particular ``Bundle``. A long-running
91
+ host that builds many logically unrelated ``Bundle``s over its lifetime
92
+ should call this between them: without it, memory grows without bound,
93
+ and two unrelated batches that happen to reuse the same
94
+ ``(identifier, credential_key)`` pair for genuinely different secrets
95
+ would spuriously collide -- or silently share a ref -- across batches
96
+ that have nothing to do with each other.
97
+ """
98
+ with _SEEN_REFS_LOCK:
99
+ _SEEN_REFS.clear()