fix(gateway): live allowlist refresh reads only its own source, publishes all-or-nothing
Two ways a refresh could authorize from a policy the operator did not set: - An adapter built from `gateway --config <file>` (or any unstamped config) got the home config.yaml's version as its live-gate baseline, so an unrelated home-config save replaced the custom file's allowlist with the home one. mark_live_gate_baseline() now records an empty (unknown-source) baseline for a config load_gateway_config() did not stamp; refresh_live_gate_extra() already keeps the loaded gates for that. - The YAML env bridge transaction ended inside load_yaml_layer(), before GatewayConfig.from_dict / env overrides / validation. A document whose Telegram list bridged fine but whose other blocks failed typed construction raised, the adapter kept its last good list, and the runner's env-reading authorization already saw the new grant. load_gateway_config() now holds the transaction across the whole load (a raise restores every bridged write); the non-strict fallback path aborts the bridge's writes before continuing on the env/gateway.json config.
This commit is contained in:
@@ -856,16 +856,29 @@ 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
|
||||
from gateway.platforms._shared import gate_config_version, yaml_env_refresh
|
||||
|
||||
_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():
|
||||
config = _load_gateway_config_layers(_home, gw_data, strict)
|
||||
for platform_config in config.platforms.values():
|
||||
platform_config.loaded_version = version
|
||||
return config
|
||||
|
||||
|
||||
def _load_gateway_config_layers(_home: Path, gw_data: dict, strict: bool) -> GatewayConfig:
|
||||
from gateway import config_loader
|
||||
from gateway.platforms._shared import abort_yaml_env_refresh
|
||||
try:
|
||||
config_loader.load_yaml_layer(_home, gw_data)
|
||||
except Exception as e:
|
||||
if strict:
|
||||
raise
|
||||
abort_yaml_env_refresh()
|
||||
logger.warning(
|
||||
# DingTalk settings → env vars: migrated to the dingtalk plugin's apply_yaml_config_fn hook
|
||||
# (plugins/platforms/dingtalk/adapter.py). #41112 / #3823.
|
||||
@@ -883,8 +896,6 @@ def load_gateway_config(*, strict: bool = False) -> GatewayConfig:
|
||||
config = GatewayConfig.from_dict(gw_data)
|
||||
_apply_env_overrides(config)
|
||||
_validate_gateway_config(config)
|
||||
for platform_config in config.platforms.values():
|
||||
platform_config.loaded_version = version
|
||||
return config
|
||||
|
||||
|
||||
|
||||
@@ -237,6 +237,18 @@ def cancel_yaml_env_refresh() -> None:
|
||||
load.failed = True
|
||||
|
||||
|
||||
def abort_yaml_env_refresh() -> None:
|
||||
"""Undo this load's bridged writes now: its caller caught a failure and continues on a fallback
|
||||
config, so neither the writes nor a retraction of missing settings may be published."""
|
||||
with _YAML_ENV_LOCK:
|
||||
load = getattr(_YAML_ENV_LOAD, "current", None)
|
||||
if load is not None:
|
||||
load.restore()
|
||||
load.prior.clear()
|
||||
load.undo.clear()
|
||||
load.failed = True
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def yaml_env_refresh():
|
||||
"""Retract only unchanged bridge-owned leftovers after one complete, successful YAML load."""
|
||||
@@ -364,10 +376,14 @@ def gate_config_version(home: Any = None) -> tuple:
|
||||
def mark_live_gate_baseline(adapter: Any) -> None:
|
||||
"""Record, on the adapter's first connect, which config the connect-time gate copy came from.
|
||||
A reconnect keeps the first baseline so an edit made before it is still picked up. The
|
||||
baseline's home is the adapter's OWNING profile: every later refresh reads that home."""
|
||||
baseline's home is the adapter's OWNING profile: every later refresh reads that home.
|
||||
|
||||
Only a config ``load_gateway_config()`` stamped has a known source. Any other (``gateway
|
||||
--config <file>``, a programmatic config) keeps its loaded gates: refreshing it from a home
|
||||
config.yaml would replace the operator's chosen policy with a file it never came from."""
|
||||
if getattr(adapter, "_live_gate_version", None) is None:
|
||||
loaded = getattr(getattr(adapter, "config", None), "loaded_version", None)
|
||||
adapter._live_gate_version = loaded if loaded is not None else gate_config_version()
|
||||
adapter._live_gate_version = loaded if loaded is not None else ()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
|
||||
68
tests/agent/test_env_loader_source_bridge_handback.py
Normal file
68
tests/agent/test_env_loader_source_bridge_handback.py
Normal file
@@ -0,0 +1,68 @@
|
||||
"""A secret source that took over a YAML-bridged value hands it back to the bridge when removed.
|
||||
|
||||
Otherwise the restored value reads as the operator's, and a later config.yaml tightening of the same
|
||||
allowlist is ignored: the runner's authorization keeps admitting the removed user.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from gateway.config_loader import load_yaml_layer
|
||||
from hermes_cli import env_loader
|
||||
from tests.agent.test_env_loader_reload_restore import _register_fake_source
|
||||
|
||||
KEY = "TELEGRAM_ALLOWED_USERS"
|
||||
MARKER = "HERMES_BRIDGED_" + KEY
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolated(tmp_path, monkeypatch):
|
||||
from agent.secret_sources import registry
|
||||
|
||||
registry._reset_registry_for_tests()
|
||||
env_loader.reset_secret_source_cache()
|
||||
for name in ("_LOADED_DOTENV_KEYS", "_MANAGED_DOTENV_KEYS"):
|
||||
monkeypatch.setattr(env_loader, name, set())
|
||||
monkeypatch.setattr(env_loader, "_DOTENV_PUBLISHED", {})
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
for key in (KEY, MARKER): # setenv first so teardown also removes what the loaders write
|
||||
monkeypatch.setenv(key, "")
|
||||
monkeypatch.delenv(key)
|
||||
yield
|
||||
registry._reset_registry_for_tests()
|
||||
env_loader.reset_secret_source_cache()
|
||||
|
||||
|
||||
def _config(home, users, source=False):
|
||||
text = "telegram:\n allow_from: " + json.dumps(users) + "\n"
|
||||
if source:
|
||||
text += "secrets:\n fakebulk:\n enabled: true\n"
|
||||
(home / "config.yaml").write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source_value, override", [("333", True), ("111,222", False)],
|
||||
ids=["source_overrode", "source_skipped_equal"])
|
||||
def test_removed_source_returns_the_list_to_yaml(tmp_path, source_value, override):
|
||||
from gateway.authz_mixin import GatewayAuthorizationMixin
|
||||
from gateway.config import GatewayConfig, Platform
|
||||
from gateway.session import SessionSource
|
||||
|
||||
_config(tmp_path, ["111", "222"])
|
||||
load_yaml_layer(tmp_path, {})
|
||||
_register_fake_source({KEY: source_value}, override_existing=override)
|
||||
_config(tmp_path, ["111", "222"], source=True)
|
||||
env_loader.load_hermes_dotenv(hermes_home=tmp_path)
|
||||
assert os.environ[KEY] == source_value and MARKER not in os.environ
|
||||
|
||||
_config(tmp_path, ["111"]) # source removed, list tightened in the same edit
|
||||
env_loader.reset_secret_source_cache(tmp_path)
|
||||
env_loader.load_hermes_dotenv(hermes_home=tmp_path)
|
||||
load_yaml_layer(tmp_path, {})
|
||||
|
||||
runner = GatewayAuthorizationMixin()
|
||||
runner.config, runner.adapters, runner.pairing_store = GatewayConfig(), {}, None
|
||||
removed = SessionSource(platform=Platform.TELEGRAM, user_id="222", chat_id="222", chat_type="dm")
|
||||
assert os.environ[KEY] == "111"
|
||||
assert runner._is_user_authorized(removed) is False
|
||||
77
tests/plugins/platforms/test_live_allowlist_sources.py
Normal file
77
tests/plugins/platforms/test_live_allowlist_sources.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""A live allowlist refresh reads only the config the gate came from, and publishes all-or-nothing.
|
||||
|
||||
An adapter built from ``gateway --config custom.yaml`` keeps that file's policy when the home
|
||||
config.yaml changes; a config.yaml edit whose typed construction fails leaves the adapter AND the
|
||||
runner's env-reading authorization on the last good lists.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
import os
|
||||
import time
|
||||
|
||||
import hermes_yaml as yaml
|
||||
import pytest
|
||||
|
||||
from gateway.config import Platform, load_gateway_config
|
||||
|
||||
_WRITES = itertools.count()
|
||||
|
||||
|
||||
def _write(home, doc):
|
||||
path = home / "config.yaml"
|
||||
path.write_text(yaml.safe_dump(doc), encoding="utf-8")
|
||||
stamp = time.time_ns() - 10_000_000_000 + next(_WRITES) * 1_000_000
|
||||
os.utime(path, ns=(stamp, stamp))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def home(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
for name in list(os.environ):
|
||||
if name.startswith(("DISCORD_", "TELEGRAM_", "HERMES_BRIDGED_", "GATEWAY_ALLOW")):
|
||||
monkeypatch.delenv(name)
|
||||
for var in ("DISCORD_ALLOWED_USERS", "TELEGRAM_ALLOWED_USERS"): # teardown removes bridged writes
|
||||
monkeypatch.setenv(var, "")
|
||||
monkeypatch.delenv(var)
|
||||
monkeypatch.setenv(f"HERMES_BRIDGED_{var}", "")
|
||||
monkeypatch.delenv(f"HERMES_BRIDGED_{var}")
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_custom_config_adapter_ignores_home_config_edits(home):
|
||||
from gateway.config_loader import load_gateway_config_file
|
||||
from plugins.platforms.discord.adapter import DiscordAdapter
|
||||
|
||||
_write(home, {"discord": {"allow_from": ["222"]}})
|
||||
custom = home / "custom.yaml"
|
||||
custom.write_text(yaml.safe_dump({"platforms": {"discord": {"enabled": True, "extra": {"allow_from": ["111"]}}}}))
|
||||
adapter = DiscordAdapter(load_gateway_config_file(str(custom)).platforms[Platform.DISCORD])
|
||||
adapter._snapshot_gate_env()
|
||||
adapter._allowed_user_ids = adapter._get_allowed_users()
|
||||
adapter._allowed_role_ids = adapter._get_allowed_roles()
|
||||
adapter._mark_live_gate_baseline()
|
||||
assert (adapter._is_allowed_user("111"), adapter._is_allowed_user("222")) == (True, False)
|
||||
_write(home, {"discord": {"allow_from": ["222"]}, "display": {"tool_preview_length": 123}})
|
||||
assert (adapter._is_allowed_user("111"), adapter._is_allowed_user("222")) == (True, False)
|
||||
|
||||
|
||||
def test_failed_typed_construction_publishes_no_env_grant(home):
|
||||
from gateway.platforms._shared import mark_live_gate_baseline
|
||||
from plugins.platforms.telegram.adapter import TelegramAdapter
|
||||
from tests.gateway.test_multiplex_interactive_auth import _runner
|
||||
|
||||
_write(home, {"telegram": {"allow_from": ["111"]}})
|
||||
adapter = TelegramAdapter(load_gateway_config().platforms[Platform.TELEGRAM])
|
||||
mark_live_gate_baseline(adapter)
|
||||
runner = _runner(home)
|
||||
runner.config.multiplex_profiles = False
|
||||
runner.config.profile_routes = []
|
||||
runner.adapters = {Platform.TELEGRAM: adapter}
|
||||
runner.config.platforms = {Platform.TELEGRAM: adapter.config}
|
||||
adapter.set_authorization_check(runner._make_adapter_auth_check(Platform.TELEGRAM))
|
||||
assert adapter._is_callback_user_authorized("222", chat_id="222", chat_type="private") is False
|
||||
# The Telegram list bridges fine; another platform's block then fails typed construction.
|
||||
_write(home, {"telegram": {"allow_from": ["222"]}, "platforms": {"discord": {"home_channel": {"name": "x"}}}})
|
||||
assert adapter._is_callback_user_authorized("222", chat_id="222", chat_type="private") is False
|
||||
assert os.environ.get("TELEGRAM_ALLOWED_USERS") == "111"
|
||||
assert adapter.config.extra.get("allow_from") == ["111"]
|
||||
Reference in New Issue
Block a user