unstract-cli 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.
unstract_cli/config.py ADDED
@@ -0,0 +1,747 @@
1
+ """Profile-based configuration.
2
+
3
+ Two products with different hosts, different keys, and `org_id` as a URL *path
4
+ segment* rather than a flag. Named profiles (kubectl/aws style) hold per-product
5
+ host, key and org, plus a key per deployment for the ones that need their own.
6
+
7
+ The resolution chain -- **flag > env > profile > built-in default** -- is
8
+ implemented once here and used by every parameter. It is never re-implemented
9
+ per command.
10
+
11
+ The CLI is fully usable with **no config file at all**, driven entirely by
12
+ environment variables; that is the expected mode in CI and agent sandboxes.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import stat
19
+ import sys
20
+ import tempfile
21
+ import tomllib
22
+ from collections.abc import Callable, Iterator
23
+ from copy import deepcopy
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import tomli_w
29
+
30
+ from unstract_cli.core.errors import remember_secret, warn
31
+
32
+ LLMWHISPERER = "llmwhisperer"
33
+ DOCSTUDIO = "docstudio"
34
+ PRODUCTS: tuple[str, ...] = (LLMWHISPERER, DOCSTUDIO)
35
+
36
+ #: Settings whose values are credentials: registered for scrubbing when
37
+ #: resolved, withheld from a discovered project file, never echoed.
38
+ SECRET_SETTINGS = frozenset({"api_key", "platform_key"})
39
+
40
+ DEFAULT_BASE_URLS: dict[str, str] = {
41
+ LLMWHISPERER: "https://llmwhisperer-api.us-central.unstract.com/api/v2",
42
+ DOCSTUDIO: "https://us-central.unstract.com",
43
+ }
44
+
45
+ #: Environment variables per (product, setting), checked before the config file
46
+ #: and in the order given. The trailing names are the published clients' own,
47
+ #: so an environment set up for a client does not leave the CLI on its default.
48
+ #:
49
+ #: The platform key sits on the docstudio block beside the deployment key: one
50
+ #: deployment serves both the platform API and the deployments it manages, so
51
+ #: the two keys share a host and an organisation.
52
+ ENV_VARS: dict[tuple[str, str], tuple[str, ...]] = {
53
+ (LLMWHISPERER, "api_key"): ("LLMWHISPERER_API_KEY",),
54
+ (LLMWHISPERER, "base_url"): ("LLMWHISPERER_BASE_URL", "LLMWHISPERER_BASE_URL_V2"),
55
+ (DOCSTUDIO, "api_key"): ("UNSTRACT_DEPLOYMENT_KEY", "UNSTRACT_API_DEPLOYMENT_KEY"),
56
+ (DOCSTUDIO, "base_url"): ("UNSTRACT_BASE_URL",),
57
+ (DOCSTUDIO, "org_id"): ("UNSTRACT_ORG_ID",),
58
+ (DOCSTUDIO, "platform_key"): ("UNSTRACT_PLATFORM_KEY",),
59
+ }
60
+
61
+
62
+ #: Where the credentials are minted: knowing a key is unset is no help without
63
+ #: knowing where one is made.
64
+ KEY_SOURCES = (
65
+ "Get an LLMWhisperer key from the LLMWhisperer console; a deployment key is "
66
+ "shown on the API deployment's own page in the Unstract UI, and an "
67
+ "organisation admin mints a key covering every deployment in the "
68
+ "organisation under Settings -> Global API Deployment Keys. A platform key, "
69
+ "which identifies the organisation and lists what is in it but cannot run a "
70
+ "deployment, is minted by an organisation admin under "
71
+ "Settings -> Platform API Keys."
72
+ )
73
+
74
+
75
+ def settings_for(product: str) -> tuple[str, ...]:
76
+ """The settings a product actually has.
77
+
78
+ Products differ: `org_id` and `platform_key` are settings only for
79
+ `docstudio` -- llmwhisperer has no organisation -- and reporting a setting a
80
+ user has no way to supply reads as a misconfiguration they cannot fix.
81
+ """
82
+ return tuple(sorted(key for prod, key in ENV_VARS if prod == product))
83
+
84
+
85
+ #: Filename a project can commit to point the CLI at its own settings.
86
+ PROJECT_CONFIG_NAME = ".unstract.toml"
87
+
88
+ #: Where the config lives when nothing else selects one.
89
+ HOME_CONFIG = Path("~/.unstract/config.toml")
90
+
91
+
92
+ class ConfigError(Exception):
93
+ """Configuration could not be loaded or resolved."""
94
+
95
+
96
+ #: Set by the root `--config` flag, and highest precedence like every flag.
97
+ _config_override: Path | None = None
98
+
99
+
100
+ def set_config_path(path: str | Path | None) -> None:
101
+ """Point this process at a specific config file (the `--config` flag)."""
102
+ global _config_override
103
+ _config_override = Path(path).expanduser() if path else None
104
+
105
+
106
+ def find_project_config(start: Path | None = None) -> Path | None:
107
+ """Search upward from the working directory for ``.unstract.toml``.
108
+
109
+ Mirrors how git and ruff resolve project settings: running the CLI inside a
110
+ project picks up that project's config with no flag. The search stops at the
111
+ filesystem root, and at ``$HOME`` so a stray file in a parent directory
112
+ cannot silently capture every invocation.
113
+
114
+ A symlinked candidate is skipped rather than followed: the file it points at
115
+ is chosen by whoever wrote the link, and this path is written to as well as
116
+ read from -- `config set` and `config init --force` would rewrite the target.
117
+ """
118
+ current = (start or Path.cwd()).resolve()
119
+ home = Path.home().resolve()
120
+ for directory in (current, *current.parents):
121
+ candidate = directory / PROJECT_CONFIG_NAME
122
+ if candidate.is_file() and not candidate.is_symlink():
123
+ return candidate
124
+ if directory == home:
125
+ break
126
+ return None
127
+
128
+
129
+ def config_path() -> Path:
130
+ """Location of the config file.
131
+
132
+ Resolution: ``--config``, then ``$UNSTRACT_CONFIG``, then a project-local
133
+ ``.unstract.toml`` found by upward search, then ``~/.unstract/config.toml``.
134
+
135
+ Several config files coexisting is expected, not exceptional: a per-project
136
+ file checked into a repo, a throwaway one in CI, and a personal default, each
137
+ selected per invocation.
138
+ """
139
+ return _resolve_config_path()[0]
140
+
141
+
142
+ def init_path() -> Path:
143
+ """Where `config init` writes when no config file was named.
144
+
145
+ Discovery is for reading. A file found by walking up from the working
146
+ directory is not trusted with credentials or hosts, so a starter config
147
+ written there is one the next command refuses to honour -- and writing to a
148
+ checked-in file the user never named is a surprise in its own right.
149
+ """
150
+ path, discovered = _resolve_config_path()
151
+ return HOME_CONFIG.expanduser() if discovered else path
152
+
153
+
154
+ def _resolve_config_path() -> tuple[Path, bool]:
155
+ """The config path, and whether it was *discovered* rather than named.
156
+
157
+ The boolean is the trust signal: a path the user named (``--config`` or
158
+ ``$UNSTRACT_CONFIG``) is trusted, one found by walking up from the working
159
+ directory is not. See ``UNTRUSTED_PROJECT_KEYS``.
160
+ """
161
+ if _config_override is not None:
162
+ return _config_override, False
163
+ if override := os.environ.get("UNSTRACT_CONFIG"):
164
+ return Path(override).expanduser(), False
165
+ if local := find_project_config():
166
+ return local, True
167
+ return HOME_CONFIG.expanduser(), False
168
+
169
+
170
+ def _deref(value: Any, *, allow_env: bool) -> Any:
171
+ """Resolve ``env:VAR_NAME`` indirection so config files hold no secrets.
172
+
173
+ An unset variable resolves to ``None`` rather than the literal string, so a
174
+ missing credential surfaces as "not configured" instead of being sent as the
175
+ nonsense value ``"env:FOO"``.
176
+
177
+ An empty string resolves the same way: the placeholders a generated config
178
+ carries must not satisfy `require`.
179
+
180
+ ``allow_env`` is the trust boundary, and has no default: the permissive
181
+ branch is the one that splices an attacker-chosen variable into a request
182
+ URL, so a caller has to ask for it. A discovered project-local file may not
183
+ name the variable to read, because whatever it names is then spliced into a
184
+ request URL and echoed back in any error about it.
185
+ """
186
+ if isinstance(value, str):
187
+ if value.startswith("env:"):
188
+ return os.environ.get(value[4:].strip()) or None if allow_env else None
189
+ return value or None
190
+ return value
191
+
192
+
193
+ #: Settings a *discovered* project-local file may not supply as literals: a
194
+ #: checkout the user did not write must not choose the host their key is sent
195
+ #: to. Such a file may not name an environment variable to read either --
196
+ #: see `ResolvedConfig._env_refused`.
197
+ UNTRUSTED_PROJECT_KEYS = SECRET_SETTINGS | {"base_url"}
198
+
199
+
200
+ @dataclass
201
+ class ConfigFile:
202
+ """Parsed contents of the config file."""
203
+
204
+ default_profile: str | None = None
205
+ profiles: dict[str, dict[str, Any]] = field(default_factory=dict)
206
+ path: Path | None = None
207
+ exists: bool = False
208
+ #: Non-fatal diagnostics (e.g. loose file permissions), surfaced on stderr.
209
+ warnings: tuple[str, ...] = ()
210
+ #: True when `path` was found by walking up from the working directory rather
211
+ #: than named. Such a file is not trusted with credentials or hosts.
212
+ is_project_local: bool = False
213
+ #: Keys withheld from an untrusted file, as ``{(profile, *blocks, key): value}``.
214
+ #: Excluded from resolution, but kept so a write-back does not drop them.
215
+ withheld: dict[tuple[str, ...], Any] = field(default_factory=dict)
216
+ #: The file as it was parsed. A write rebuilds only the tables this CLI owns,
217
+ #: so anything else in the file survives being written through.
218
+ raw: dict[str, Any] = field(default_factory=dict)
219
+
220
+
221
+ def _strip_untrusted(profiles: dict[str, Any]) -> dict[tuple[str, ...], Any]:
222
+ """Remove the untrusted keys from a profile tree, in place, reporting what went."""
223
+ withheld: dict[tuple[str, ...], Any] = {}
224
+
225
+ def walk(node: Any, trail: tuple[str, ...]) -> None:
226
+ if not isinstance(node, dict):
227
+ return
228
+ for key in list(node):
229
+ if key in UNTRUSTED_PROJECT_KEYS:
230
+ withheld[(*trail, key)] = node.pop(key)
231
+ else:
232
+ walk(node[key], (*trail, key))
233
+
234
+ walk(profiles, ())
235
+ return withheld
236
+
237
+
238
+ def _is_discovered(path: Path) -> bool:
239
+ """Whether this path is the file an upward search would have found.
240
+
241
+ Trust follows the file, not the call: naming the project-local file that
242
+ discovery would have picked anyway does not make its contents any more the
243
+ user's own. ``--config`` and ``$UNSTRACT_CONFIG`` are a deliberate choice and
244
+ are resolved before this, so they stay trusted.
245
+ """
246
+ candidate = find_project_config()
247
+ return candidate is not None and candidate.resolve() == path.resolve()
248
+
249
+
250
+ def load_config(path: Path | None = None) -> ConfigFile:
251
+ """Load the config file. A missing file is normal, not an error."""
252
+ if path is not None:
253
+ target, project_local = path, _is_discovered(path)
254
+ else:
255
+ target, project_local = _resolve_config_path()
256
+ if not target.exists():
257
+ return ConfigFile(path=target, exists=False, is_project_local=project_local)
258
+
259
+ try:
260
+ with target.open("rb") as fh:
261
+ raw = tomllib.load(fh)
262
+ except (OSError, tomllib.TOMLDecodeError) as exc:
263
+ raise ConfigError(f"Could not read config at {target}: {exc}") from exc
264
+
265
+ warnings: list[str] = []
266
+ try:
267
+ mode = target.stat().st_mode
268
+ if mode & (stat.S_IRWXG | stat.S_IRWXO):
269
+ warnings.append(
270
+ f"Config file {target} is readable by other users "
271
+ f"(mode {stat.filemode(mode)}); consider `chmod 600`."
272
+ )
273
+ except OSError: # pragma: no cover - stat failure is not worth failing on
274
+ pass
275
+
276
+ profiles = raw.get("profiles", {})
277
+ if not isinstance(profiles, dict):
278
+ raise ConfigError(f"`profiles` in {target} must be a table.")
279
+
280
+ # Withheld keys are reported rather than dropped in silence; the rest of
281
+ # the file still applies.
282
+ withheld: dict[tuple[str, ...], Any] = {}
283
+ if project_local:
284
+ withheld = _strip_untrusted(profiles)
285
+ if withheld:
286
+ names = ", ".join(sorted(".".join(trail) for trail in withheld))
287
+ warnings.append(
288
+ f"Ignoring {names} from project config {target}: a discovered "
289
+ f"{PROJECT_CONFIG_NAME} may not supply credentials or base URLs. "
290
+ "Pass --config explicitly, or set the environment variable instead."
291
+ )
292
+
293
+ return ConfigFile(
294
+ default_profile=raw.get("default_profile"),
295
+ profiles=profiles,
296
+ path=target,
297
+ exists=True,
298
+ warnings=tuple(warnings),
299
+ is_project_local=project_local,
300
+ withheld=withheld,
301
+ raw=raw,
302
+ )
303
+
304
+
305
+ def _restored_profiles(cfg: ConfigFile, target: Path) -> dict[str, Any]:
306
+ """The profiles to write, with anything withheld put back.
307
+
308
+ Withholding a key from resolution is the security property; deleting it from
309
+ the user's file is not, and `config set` loads, mutates and saves the whole
310
+ document. Restored **only** when writing back to the file they came from --
311
+ into any other path this would copy untrusted values somewhere they are
312
+ trusted.
313
+ """
314
+ if not cfg.withheld or cfg.path is None or target.resolve() != cfg.path.resolve():
315
+ return cfg.profiles
316
+
317
+ profiles = deepcopy(cfg.profiles)
318
+ for (*parents, leaf), value in cfg.withheld.items():
319
+ node: dict[str, Any] = profiles
320
+ for segment in parents:
321
+ child = node.get(segment)
322
+ if not isinstance(child, dict):
323
+ child = node[segment] = {}
324
+ node = child
325
+ node.setdefault(leaf, value)
326
+ return profiles
327
+
328
+
329
+ def save_config(
330
+ cfg: ConfigFile,
331
+ path: Path | None = None,
332
+ *,
333
+ on_unconfirmed: Callable[[], None] | None = None,
334
+ ) -> Path:
335
+ """Write the config file with owner-only permissions.
336
+
337
+ The file is in place when this returns. ``on_unconfirmed`` is called when
338
+ the directory entry could not be synced as well, so the write may not
339
+ survive a crash; the warning alone reaches only stderr.
340
+ """
341
+ target = path or cfg.path or config_path()
342
+ target.parent.mkdir(parents=True, exist_ok=True)
343
+
344
+ # Started from the file as it was read: a table this CLI does not know
345
+ # about is not a table it may delete.
346
+ doc: dict[str, Any] = {k: v for k, v in cfg.raw.items() if k != "profiles"}
347
+ doc.pop("default_profile", None)
348
+ if cfg.default_profile:
349
+ doc["default_profile"] = cfg.default_profile
350
+ doc["profiles"] = _restored_profiles(cfg, target)
351
+
352
+ # The path is not always one the user chose, and replacing a symlink would
353
+ # silently turn a deliberate one into a regular file.
354
+ if target.is_symlink():
355
+ raise ConfigError(
356
+ f"Refusing to write config through the symlink at {target}: it would "
357
+ f"overwrite {os.readlink(target)} instead. Pass --config with the path "
358
+ "of the real file."
359
+ )
360
+
361
+ # Written to a temporary file and renamed into place, so a failed write
362
+ # cannot destroy a working config. `mkstemp` names the temporary
363
+ # unpredictably -- a guessable sibling is a symlink waiting to be planted --
364
+ # and creates it 0600, the mode the rename then gives the config.
365
+ try:
366
+ handle_fd, name = tempfile.mkstemp(dir=target.parent, suffix=".tmp")
367
+ except OSError as exc:
368
+ # The atomic rename needs a writable directory, not just a writable
369
+ # file.
370
+ raise ConfigError(
371
+ f"Cannot write {target}: its directory {target.parent} is not "
372
+ f"writable, and the config is replaced rather than overwritten so a "
373
+ f"failed write cannot destroy it ({exc.strerror})."
374
+ ) from exc
375
+ tmp = Path(name)
376
+ try:
377
+ with os.fdopen(handle_fd, "wb") as fh:
378
+ tomli_w.dump(doc, fh)
379
+ # The rename replaces one whole config with another only if the
380
+ # new bytes reached the disk before it.
381
+ fh.flush()
382
+ os.fsync(fh.fileno())
383
+ os.replace(tmp, target)
384
+ # Syncing the file does not cover the directory entry now pointing at
385
+ # it. Windows cannot open a directory to sync it; elsewhere the config
386
+ # has already landed, so a failure is reported rather than raised.
387
+ if sys.platform != "win32":
388
+ try:
389
+ dir_fd = os.open(target.parent, os.O_RDONLY)
390
+ try:
391
+ os.fsync(dir_fd)
392
+ finally:
393
+ os.close(dir_fd)
394
+ except OSError as exc:
395
+ warn(
396
+ f"warning: config written to {target}, but its directory "
397
+ f"could not be synced ({exc.strerror}); the write may not "
398
+ "survive a crash."
399
+ )
400
+ if on_unconfirmed is not None:
401
+ on_unconfirmed()
402
+ except BaseException:
403
+ tmp.unlink(missing_ok=True)
404
+ raise
405
+ return target
406
+
407
+
408
+ @dataclass
409
+ class ResolvedConfig:
410
+ """Effective settings for one invocation.
411
+
412
+ ``overrides`` holds command-line flags, which outrank everything else.
413
+ """
414
+
415
+ file: ConfigFile
416
+ profile_name: str | None = None
417
+ overrides: dict[str, Any] = field(default_factory=dict)
418
+ #: `env:` references already refused, so one is reported once per run.
419
+ _reported: set[str] = field(default_factory=set, repr=False, init=False)
420
+
421
+ @property
422
+ def active_profile(self) -> str | None:
423
+ """Profile selected by flag, ``UNSTRACT_PROFILE``, or the file default."""
424
+ return (
425
+ self.profile_name
426
+ or os.environ.get("UNSTRACT_PROFILE")
427
+ or self.file.default_profile
428
+ )
429
+
430
+ def _profile(self) -> dict[str, Any]:
431
+ name = self.active_profile
432
+ if not name:
433
+ return {}
434
+ profile = self.file.profiles.get(name)
435
+ if profile is None:
436
+ if self.file.exists and self.file.profiles:
437
+ known = ", ".join(sorted(self.file.profiles)) or "none"
438
+ raise ConfigError(
439
+ f"Profile {name!r} not found in {self.file.path}. "
440
+ f"Known profiles: {known}"
441
+ )
442
+ return {}
443
+ return profile if isinstance(profile, dict) else {}
444
+
445
+ def _product_block(self, product: str) -> dict[str, Any]:
446
+ # Settings nested under the product name and nowhere else: a config
447
+ # that looks applied but is not fails later with no obvious cause.
448
+ block = self._profile().get(product)
449
+ return block if isinstance(block, dict) else {}
450
+
451
+ def unknown_settings(self, product: str) -> tuple[str, ...]:
452
+ """Keys written under a product that nothing will ever read back."""
453
+ try:
454
+ written = set(self._product_block(product))
455
+ except ConfigError:
456
+ return ()
457
+ return tuple(sorted(written - set(settings_for(product))))
458
+
459
+ def get(self, product: str, key: str, default: Any = None) -> Any:
460
+ """Resolve one setting: **flag > env > profile > built-in default**."""
461
+ value = self._resolve(product, key, default)
462
+ if key in SECRET_SETTINGS:
463
+ remember_secret(value)
464
+ return value
465
+
466
+ def _tiers(self, product: str, key: str) -> Iterator[Any]:
467
+ """What each tier says, in order -- flag, env, profile -- unset as `None`.
468
+
469
+ Lazy on purpose: reading the profile block resolves the profile name,
470
+ which raises for one that does not exist. A caller answered by an
471
+ earlier tier must not be failed by a later one it never consulted.
472
+ """
473
+ yield self.overrides.get(f"{product}.{key}")
474
+ yield next(
475
+ (v for e in ENV_VARS.get((product, key), ()) if (v := os.environ.get(e))),
476
+ None,
477
+ )
478
+ raw = self._product_block(product).get(key)
479
+ yield _deref(raw, allow_env=self._env_allowed(raw))
480
+
481
+ def _explicit(self, product: str, key: str) -> Any:
482
+ """The tiers a human supplied: flag, then environment, then profile."""
483
+ return next((v for v in self._tiers(product, key) if v is not None), None)
484
+
485
+ def _resolve(self, product: str, key: str, default: Any = None) -> Any:
486
+ if (value := self._explicit(product, key)) is not None:
487
+ return value
488
+
489
+ if default is not None:
490
+ return default
491
+ if key == "base_url":
492
+ return DEFAULT_BASE_URLS.get(product)
493
+ return None
494
+
495
+ def _env_refused(self, raw: Any) -> bool:
496
+ """Whether this value names an environment variable this file may not read.
497
+
498
+ Pure, so a report can ask the same question `_resolve` does without the
499
+ side effect of warning about a value it is only describing.
500
+ """
501
+ return self.file.is_project_local and (
502
+ isinstance(raw, str) and raw.startswith("env:")
503
+ )
504
+
505
+ def _env_allowed(self, raw: Any) -> bool:
506
+ """Whether this value may name an environment variable to read."""
507
+ if not self._env_refused(raw):
508
+ return True
509
+ # Straight to stderr rather than onto `file.warnings`: those are
510
+ # reported when the file is loaded, and this is found while resolving.
511
+ if raw not in self._reported:
512
+ self._reported.add(raw)
513
+ warn(
514
+ f"warning: ignoring {raw!r} in the project-local "
515
+ f"{self.file.path}: a config file found by searching upwards "
516
+ "may not choose which environment variable is read."
517
+ )
518
+ return False
519
+
520
+ def _env_refusal_detail(self, raw: Any) -> str:
521
+ """Why an `env:` reference was not followed."""
522
+ return (
523
+ f"{self.file.path} is a discovered {PROJECT_CONFIG_NAME}, which may "
524
+ f"not choose which environment variable is read, so {raw!r} is ignored"
525
+ )
526
+
527
+ def require(self, product: str, key: str) -> Any:
528
+ """Resolve a setting, or raise a message naming exactly how to supply it."""
529
+ if (value := self.get(product, key)) is not None:
530
+ return value
531
+
532
+ hints: list[str] = []
533
+ if env_vars := ENV_VARS.get((product, key)):
534
+ hints.append(f"set ${env_vars[0]}")
535
+ hints.append(f"or add `{key}` to the [profiles.<name>.{product}] block")
536
+ # `--api-key` exists but is not suggested: a secret on the command line
537
+ # lands in shell history and in the process list.
538
+ if key not in SECRET_SETTINGS:
539
+ hints.append(f"or pass --{key.replace('_', '-')}")
540
+ if not self.file.exists:
541
+ hints.append("or run `unstract auth login` to set up interactively")
542
+ raise ConfigError(
543
+ f"Missing required setting {product}.{key}. To fix: {'; '.join(hints)}."
544
+ )
545
+
546
+ def deployment_names(self) -> tuple[str, ...]:
547
+ """The deployments the active profile holds a key of its own for."""
548
+ table = self._profile().get("deployments")
549
+ return tuple(sorted(table)) if isinstance(table, dict) else ()
550
+
551
+ def deployment_key(self, api_name: str) -> Any:
552
+ """The key to run one deployment with, or ``None`` if nothing names one.
553
+
554
+ **flag > env > per-deployment entry > profile key**. The entry is the
555
+ most specific value *within* the profile tier, not a tier of its own: a
556
+ file value that outranked the environment would let a stale entry hijack
557
+ a run the caller set up with ``$UNSTRACT_DEPLOYMENT_KEY``.
558
+ """
559
+ value, _source = self._deployment_key(api_name)
560
+ remember_secret(value)
561
+ return value
562
+
563
+ def deployment_key_source(self, api_name: str) -> str | None:
564
+ """Which tier the key for this deployment came from, or ``None``.
565
+
566
+ One of ``"flag"``, ``"env"``, ``"entry"``, ``"profile"``. A message
567
+ about a rejected key names the place it was actually read from, rather
568
+ than the place it could have been stored.
569
+ """
570
+ return self._deployment_key(api_name)[1]
571
+
572
+ def _deployment_key(self, api_name: str) -> tuple[Any, str | None]:
573
+ """The key and the tier it came from, resolved once for both callers."""
574
+ tiers = self._tiers(DOCSTUDIO, "api_key")
575
+ flag, env = next(tiers), next(tiers)
576
+ if flag is not None:
577
+ return flag, "flag"
578
+ if env is not None:
579
+ return env, "env"
580
+ if (entry := self._entry_key(api_name)) is not None:
581
+ return entry, "entry"
582
+ if (profile := next(tiers)) is not None:
583
+ return profile, "profile"
584
+ return None, None
585
+
586
+ def _entry_key(self, api_name: str) -> Any:
587
+ """The key the deployment's own entry names, if it names one.
588
+
589
+ An ``env:`` reference that does not resolve is not silence. Falling back
590
+ there runs the deployment with the profile's key and reports success.
591
+ """
592
+ table = self._profile().get("deployments")
593
+ entry = table.get(api_name) if isinstance(table, dict) else None
594
+ raw = entry.get("api_key") if isinstance(entry, dict) else None
595
+ # A discovered project file never gets this far: its keys are withheld
596
+ # at load time, so an `env:` reference seen here is always trusted.
597
+ if isinstance(raw, str) and raw.startswith("env:"):
598
+ if value := _deref(raw, allow_env=True):
599
+ return value
600
+ raise ConfigError(
601
+ f"Deployment {api_name!r} sets api_key to {raw!r}, and "
602
+ f"${raw[4:].strip()} is not set in this process's environment."
603
+ )
604
+ return raw or None
605
+
606
+ def deployment_key_sources(self, api_name: str) -> tuple[str, ...]:
607
+ """Every place a key for this deployment could have come from, in order.
608
+
609
+ Quoted when none of them did: a caller told only that a key is missing
610
+ has to guess which of four places the CLI looked in.
611
+ """
612
+ profile = self.active_profile or "<name>"
613
+ return (
614
+ "--api-key",
615
+ f"${ENV_VARS[(DOCSTUDIO, 'api_key')][0]}",
616
+ f'[profiles.{profile}.deployments."{api_name}"] api_key',
617
+ f"[profiles.{profile}.docstudio] api_key",
618
+ )
619
+
620
+ def resolution_source(self, product: str, key: str) -> dict[str, Any]:
621
+ """Report where a setting resolves from, without echoing a secret.
622
+
623
+ `config doctor` uses this to answer the question that costs the most
624
+ time: "the CLI says the key is not configured, but I set it -- where is
625
+ it looking?"
626
+ """
627
+ if self.overrides.get(f"{product}.{key}") is not None:
628
+ return {"resolved": True, "source": "flag/override"}
629
+
630
+ for env_var in ENV_VARS.get((product, key), ()):
631
+ if os.environ.get(env_var):
632
+ return {"resolved": True, "source": f"env:{env_var}"}
633
+
634
+ raw = self._product_block(product).get(key)
635
+ if isinstance(raw, str) and raw.startswith("env:"):
636
+ var = raw[4:].strip()
637
+ if self._env_refused(raw):
638
+ return {
639
+ "resolved": False,
640
+ "source": f"profile -> env:{var} (refused)",
641
+ "detail": self._env_refusal_detail(raw),
642
+ }
643
+ present = bool(os.environ.get(var))
644
+ return {
645
+ "resolved": present,
646
+ "source": f"profile -> env:{var}",
647
+ "detail": None
648
+ if present
649
+ else f"${var} is not set in this process's environment",
650
+ }
651
+ if raw not in (None, ""):
652
+ return {"resolved": True, "source": "profile (literal)"}
653
+
654
+ report: dict[str, Any] = (
655
+ {"resolved": True, "source": "built-in default"}
656
+ if key == "base_url" and DEFAULT_BASE_URLS.get(product)
657
+ else {"resolved": False, "source": "unset"}
658
+ )
659
+ if detail := self.withheld_detail(product, key):
660
+ report["detail"] = detail
661
+ return report
662
+
663
+ def withheld_detail(self, *trail: str) -> str | None:
664
+ """Why a setting the config file plainly holds did not arrive, if that is why.
665
+
666
+ Reporting only where a value came *from* would leave the user staring at
667
+ a setting they can see in the file. Takes a trail rather than a
668
+ product/key pair so a deployment entry's own key -- nested a level deeper
669
+ -- is answerable too.
670
+ """
671
+ if (self.active_profile, *trail) not in self.file.withheld:
672
+ return None
673
+ return (
674
+ f"{self.file.path} sets {trail[-1]}, and a discovered "
675
+ f"{PROJECT_CONFIG_NAME} is not trusted with it."
676
+ )
677
+
678
+
679
+ def starter_profiles() -> dict[str, dict[str, Any]]:
680
+ """Profile stubs written by `config init`.
681
+
682
+ Every credential uses ``env:`` indirection: the generated file is a map of
683
+ where secrets live, never a copy of them.
684
+
685
+ No ``platform_key`` and no ``deployments`` table on purpose: a platform key
686
+ is optional and an ``env:`` reference to an unset variable is a `config
687
+ doctor` problem, and one deployment key normally covers the organisation,
688
+ so a per-deployment key is the exception rather than the shape to start
689
+ from.
690
+ """
691
+ return {
692
+ "cloud-us": {
693
+ LLMWHISPERER: {
694
+ "base_url": DEFAULT_BASE_URLS[LLMWHISPERER],
695
+ "api_key": "env:LLMWHISPERER_API_KEY",
696
+ },
697
+ DOCSTUDIO: {
698
+ "base_url": DEFAULT_BASE_URLS[DOCSTUDIO],
699
+ "org_id": "",
700
+ "api_key": "env:UNSTRACT_DEPLOYMENT_KEY",
701
+ },
702
+ },
703
+ "cloud-eu": {
704
+ LLMWHISPERER: {
705
+ "base_url": "https://llmwhisperer-api.eu-west.unstract.com/api/v2",
706
+ "api_key": "env:LLMWHISPERER_API_KEY",
707
+ },
708
+ },
709
+ # A shape to copy for a self-hosted install, not a profile to select:
710
+ # its host is a placeholder and only the active profile is resolved.
711
+ "onprem-example": {
712
+ LLMWHISPERER: {
713
+ "base_url": "https://llmwhisperer.unstract.internal.example/api/v2",
714
+ "api_key": "env:LLMWHISPERER_API_KEY",
715
+ },
716
+ DOCSTUDIO: {
717
+ "base_url": "https://unstract.internal.example",
718
+ "org_id": "",
719
+ "api_key": "env:UNSTRACT_DEPLOYMENT_KEY",
720
+ },
721
+ },
722
+ }
723
+
724
+
725
+ __all__ = [
726
+ "DEFAULT_BASE_URLS",
727
+ "DOCSTUDIO",
728
+ "ENV_VARS",
729
+ "HOME_CONFIG",
730
+ "KEY_SOURCES",
731
+ "LLMWHISPERER",
732
+ "PRODUCTS",
733
+ "PROJECT_CONFIG_NAME",
734
+ "SECRET_SETTINGS",
735
+ "UNTRUSTED_PROJECT_KEYS",
736
+ "ConfigError",
737
+ "ConfigFile",
738
+ "ResolvedConfig",
739
+ "config_path",
740
+ "find_project_config",
741
+ "init_path",
742
+ "load_config",
743
+ "save_config",
744
+ "set_config_path",
745
+ "settings_for",
746
+ "starter_profiles",
747
+ ]