diff --git a/gateway/config.py b/gateway/config.py index da5dbaafd4..41608f5089 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -856,14 +856,14 @@ def load_gateway_config(*, strict: bool = False) -> GatewayConfig: ``strict=True`` raises a config.yaml failure instead of falling back to env + gateway.json: a live allowlist refresh keeps its last good lists rather than apply an env-only config.""" from gateway import config_loader - from gateway.platforms._shared import gate_config_version, yaml_env_refresh + from gateway.platforms._shared import gate_config_version, yaml_env_transaction _home = get_hermes_home() version = gate_config_version() gw_data = config_loader.load_legacy_gateway_json(_home) # One transaction through typed construction, overrides and validation: the runner's authorization # reads the bridged env, so a load that fails after the YAML overlay must not leave its writes. - with yaml_env_refresh(): + with yaml_env_transaction(): config = _load_gateway_config_layers(_home, gw_data, strict) for platform_config in config.platforms.values(): platform_config.loaded_version = version diff --git a/gateway/platforms/_shared.py b/gateway/platforms/_shared.py index b4d0b5aa32..8040fa2bbd 100644 --- a/gateway/platforms/_shared.py +++ b/gateway/platforms/_shared.py @@ -213,6 +213,23 @@ class _YamlEnvLoad: # adapter (last good lists) and the runner (process env) never check different policies. prior: dict[str, tuple[Optional[str], Optional[str]]] = field(default_factory=dict) undo: list[Callable[[], None]] = field(default_factory=list) # ownership state kept outside the env + before: dict[str, str] = field(default_factory=dict) # bridge markers present when the load began + in_layer: bool = False + committed: bool = False + + def retract_leftovers(self) -> None: + """Drop unchanged bridge-owned values this load's YAML no longer sets. Their priors are + recorded first, so a later failure in the same load restores them with its writes.""" + self.committed = True + if self.failed: + return + for name, digest in self.before.items(): + marker = bridged_env_marker(name) + if (name not in self.seen and os.getenv(marker) == digest + and _is_bridge_leftover(name, digest) and not _supplied_by_operator(name)): + self.prior.setdefault(name, (os.getenv(name), digest)) + os.environ.pop(name, None) + os.environ.pop(marker, None) def restore(self) -> None: for name, values in self.prior.items(): @@ -250,8 +267,12 @@ def abort_yaml_env_refresh() -> None: @contextlib.contextmanager -def yaml_env_refresh(): - """Retract only unchanged bridge-owned leftovers after one complete, successful YAML load.""" +def yaml_env_transaction(): + """One load's rollback scope: everything bridged or retracted inside it is restored if it raises. + + ``load_gateway_config`` holds it across typed construction and env overrides, so a load that fails + after the YAML layer publishes nothing; the retraction itself happens at the YAML layer's end + (:func:`yaml_env_refresh`), before anything reads the env it cleans.""" if bridge_env_skipped(): yield return @@ -259,9 +280,9 @@ def yaml_env_refresh(): if getattr(_YAML_ENV_LOAD, "current", None) is not None: yield # A nested load participates in the outer load, never clears its partial writes. return - before = {key[len(BRIDGED_ENV_MARKER_PREFIX):]: value for key, value in os.environ.items() - if key.startswith(BRIDGED_ENV_MARKER_PREFIX) and key != BRIDGED_ENV_MARKER_PREFIX} - load = _YamlEnvLoad() + load = _YamlEnvLoad(before={ + key[len(BRIDGED_ENV_MARKER_PREFIX):]: value for key, value in os.environ.items() + if key.startswith(BRIDGED_ENV_MARKER_PREFIX) and key != BRIDGED_ENV_MARKER_PREFIX}) _YAML_ENV_LOAD.current = load try: try: @@ -269,17 +290,32 @@ def yaml_env_refresh(): except BaseException: load.restore() raise - if not load.failed: - for name, digest in before.items(): - marker = bridged_env_marker(name) - if (name not in load.seen and os.getenv(marker) == digest - and _is_bridge_leftover(name, digest) and not _supplied_by_operator(name)): - os.environ.pop(name, None) - os.environ.pop(marker, None) + if not load.committed: + load.retract_leftovers() finally: del _YAML_ENV_LOAD.current +@contextlib.contextmanager +def yaml_env_refresh(): + """The YAML layer: retract only unchanged bridge-owned leftovers after one complete, successful + overlay, before the caller builds a config from the env (env overrides read the same names).""" + if bridge_env_skipped(): + yield + return + with yaml_env_transaction(), _YAML_ENV_LOCK: + load = _YAML_ENV_LOAD.current + if load.in_layer or load.committed: + yield # a nested or later layer: only the transaction's first layer decides retraction + return + load.in_layer = True + try: + yield + load.retract_leftovers() + finally: + load.in_layer = False + + def record_yaml_env_prior(name: str, undo: Callable[[], None]) -> None: """Record *name* before a bridge writes it outside :func:`yaml_env_setter` (the allow-all grant), so a load that raises restores it and runs *undo* to roll back that writer's ownership flag.""" diff --git a/tests/plugins/platforms/test_live_allowlist_sources.py b/tests/plugins/platforms/test_live_allowlist_sources.py index 3dda29e0a2..bcc8b5bd8a 100644 --- a/tests/plugins/platforms/test_live_allowlist_sources.py +++ b/tests/plugins/platforms/test_live_allowlist_sources.py @@ -94,3 +94,22 @@ def test_a_non_strict_load_that_fails_mid_bridge_restores_the_last_good_env(home _write(home, {"discord": {"allow_from": ["222"]}, "require_mention": True, "telegram": True}) load_gateway_config() assert {name: (os.environ.get(name), os.environ.get(bridged_env_marker(name))) for name in good} == good + + +@pytest.mark.parametrize("platform,var", [(Platform.TELEGRAM, "TELEGRAM_REPLY_TO_MODE"), + (Platform.DISCORD, "DISCORD_REPLY_TO_MODE")]) +def test_a_removed_setting_leftover_never_shapes_the_load_that_retracts_it(home, monkeypatch, platform, var): + """A restart child inherits a bridged value whose YAML key was since removed: the env-override pass + of the same load must not read it, and a load that then fails restores it with the last good env.""" + from gateway.platforms._shared import bridged_env_digest, bridged_env_marker + + monkeypatch.setenv(var, "all") + monkeypatch.setenv(bridged_env_marker(var), bridged_env_digest("all")) + broken = {"enabled": True, "home_channel": {"name": "x"}} # fails typed construction after the YAML layer + _write(home, {"platforms": {platform.value: broken}}) + with pytest.raises(Exception): + load_gateway_config() + assert (os.environ.get(var), os.environ.get(bridged_env_marker(var))) == ("all", bridged_env_digest("all")) + _write(home, {"platforms": {platform.value: {"enabled": True}}}) + assert load_gateway_config().platforms[platform].reply_to_mode != "all" + assert var not in os.environ and bridged_env_marker(var) not in os.environ