feat: support ${VAR} env var interpolation in config secrets
Allow config.json to reference environment variables via ${VAR_NAME}
syntax. Variables are resolved at runtime by resolve_config_env_vars(),
keeping the raw templates in the Pydantic model so save_config()
preserves them. This lets secrets live in a separate env file
(e.g. loaded by systemd EnvironmentFile=) instead of plain text
in config.json.
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
"""Configuration loading utilities."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pydantic
|
||||
@@ -76,6 +78,38 @@ def save_config(config: Config, config_path: Path | None = None) -> None:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
def resolve_config_env_vars(config: Config) -> Config:
|
||||
"""Return a copy of *config* with ``${VAR}`` env-var references resolved.
|
||||
|
||||
Only string values are affected; other types pass through unchanged.
|
||||
Raises :class:`ValueError` if a referenced variable is not set.
|
||||
"""
|
||||
data = config.model_dump(mode="json", by_alias=True)
|
||||
data = _resolve_env_vars(data)
|
||||
return Config.model_validate(data)
|
||||
|
||||
|
||||
def _resolve_env_vars(obj: object) -> object:
|
||||
"""Recursively resolve ``${VAR}`` patterns in string values."""
|
||||
if isinstance(obj, str):
|
||||
return re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}", _env_replace, obj)
|
||||
if isinstance(obj, dict):
|
||||
return {k: _resolve_env_vars(v) for k, v in obj.items()}
|
||||
if isinstance(obj, list):
|
||||
return [_resolve_env_vars(v) for v in obj]
|
||||
return obj
|
||||
|
||||
|
||||
def _env_replace(match: re.Match[str]) -> str:
|
||||
name = match.group(1)
|
||||
value = os.environ.get(name)
|
||||
if value is None:
|
||||
raise ValueError(
|
||||
f"Environment variable '{name}' referenced in config is not set"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _migrate_config(data: dict) -> dict:
|
||||
"""Migrate old config formats to current."""
|
||||
# Move tools.exec.restrictToWorkspace → tools.restrictToWorkspace
|
||||
|
||||
Reference in New Issue
Block a user