hermes-agent/tests/gateway/test_adapter_authz_secret_scope.py
John Paul Soliva b5a300fe34 fix(email): pairing, decline and gateway grants reach the gateway instead of dying in the adapter pre-gate
EmailAdapter._sender_accepted runs before any MessageEvent exists and
read only EMAIL_ALLOWED_USERS. Unset, it dropped every sender unless
allow-all was on; set, it dropped everyone not listed. The gateway's
own handling therefore never ran for email:
platforms.email.unauthorized_dm_behavior "pair" (the setup wizard's
"Use DM pairing") and "decline" sent nothing, and a sender admitted by
GATEWAY_ALLOWED_USERS or an approved pairing was dropped. bb304b4914
turned the empty-allowlist branch into drop-all after #50568 had made
"pair" email's explicit opt-in.

The gate now keeps a sender listed by address in EMAIL_ALLOWED_USERS
or GATEWAY_ALLOWED_USERS, a sender the registered gateway
authorization check admits (that is the only reader of the pairing
store), and, under an explicit pair or decline, an unknown sender the
gateway will answer. The default "ignore" still drops unknown senders
before a MessageEvent exists, so the mail-loop guard from fd9c32c0f2
holds.

Three guards keep the wider gate from widening access, and close two
forged-From: paths main already had:
- A sender admitted only so the gateway can answer it (pair or
  decline) must authenticate its From:, open access or not: the
  pairing code or refusal is mailed back to that address. A granted
  sender still needs it short of open access, since a pairing grant
  keys on From: just as the allowlist does. Open access follows the
  gateway's own order: EMAIL_ALLOW_ALL_USERS wins over a list, while
  GATEWAY_ALLOW_ALL_USERS beside a list admits nobody extra, so it no
  longer exempts a listed address from From: authentication either
  (on main a forged From: of a listed address got through there).
- Open access comes from the gateway's own verdict when a check is
  registered. GATEWAY_ALLOW_ALL_USERS beside a GATEWAY_ALLOWED_USERS
  list grants a stranger nothing there, so the env flag alone no
  longer exempts one from From: authentication (that path mailed a
  pairing code to a forged From: on main too).
- A sender whose local part alone matches an allowlist entry is
  dropped. The gateway's check also matches an address by its bare
  local part (#119446), so without this, GATEWAY_ALLOWED_USERS=alice
  (a chat username) would admit or pair alice@<any domain>. The lists
  are parsed as the gateway parses them, JSON list literals included,
  or '["alice"]' would slip past this guard.

_allowlist_in_effect only served the old condition and is removed.
The scope tests now assert the same scoped reads through
_sender_accepted, with GATEWAY_ALLOWED_USERS covered as well.

Measured end to end with the real GatewayRunner callback wired
(adapter -> gateway ingress):
- pair, decline, GATEWAY_ALLOWED_USERS and an approved pairing each
  went from 0 events reaching the gateway to 1. pair mails a pairing
  code, decline mails one refusal.
- An unauthenticated From: in pair mode, for a paired address or for a
  GATEWAY_ALLOWED_USERS address still reaches nothing.
- A bare GATEWAY_ALLOWED_USERS=stranger entry lets nothing from
  stranger@<domain> through, under ignore or pair. Without the
  local-part guard that mail reached the gateway in both.
- The same holds for a JSON-literal list, and a pair-mode stranger
  with a forged From: under allow-all beside an EMAIL_ or
  GATEWAY_ALLOWED_USERS list reaches nothing.
- The default still drops.
2026-09-23 07:48:32 -07:00

142 lines
6.5 KiB
Python

"""Adapter authz gates must read GATEWAY_/PLATFORM_ allow-all + allowlists through the profile
secret scope (#77548 cluster; #72348 / #86905 precedent).
Under ``gateway.multiplex_profiles`` ``os.environ`` holds the DEFAULT profile's values. A raw
``os.getenv`` in an adapter's own gate let the default's ``GATEWAY_ALLOW_ALL_USERS=true`` open every
secondary email/QQ/WhatsApp/Matrix/Teams/Slack/LINE/DingTalk bot, and the default's allowlist decide
who may approve on a secondary bot. Two invariants per adapter: the default env never answers a
scoped gate; the scope's own opt-in/allowlist does.
"""
import contextlib
from types import SimpleNamespace
import pytest
from agent import secret_scope as ss
from gateway.config import PlatformConfig
_DEFAULT_ENV = {
"GATEWAY_ALLOW_ALL_USERS": "true", "GATEWAY_ALLOWED_USERS": "default-admin",
"TEAMS_ALLOW_ALL_USERS": "true", "TEAMS_ALLOWED_USERS": "default-admin",
"MATRIX_ALLOWED_USERS": "@default-admin:example.org", "MATRIX_IGNORE_USER_PATTERNS": r"^@spam:.*",
"WHATSAPP_ALLOWED_USERS": "+15550001111", "SLACK_ALLOW_BOTS": "all", "SLACK_API_HUMAN_USERS": "U0DEFAULT",
"LINE_ALLOW_ALL_USERS": "true", "LINE_ALLOWED_USERS": "Udefault", "DINGTALK_ALLOWED_USERS": "default-admin",
"EMAIL_ALLOWED_USERS": "[email protected]",
}
@pytest.fixture
def default_env(monkeypatch):
"""Multiplex on; os.environ carries the DEFAULT profile's permissive authz."""
for name, value in _DEFAULT_ENV.items():
monkeypatch.setenv(name, value)
monkeypatch.setattr(ss, "_MULTIPLEX_ACTIVE", True)
@contextlib.contextmanager
def _scope(secrets):
token = ss.set_secret_scope(secrets)
try:
yield
finally:
ss.reset_secret_scope(token)
def _matrix(extra=None):
from plugins.platforms.matrix.adapter import MatrixAdapter
return MatrixAdapter(PlatformConfig(enabled=True, token="t", extra={"homeserver": "https://m.example",
"user_id": "@bot:m.example", **(extra or {})}))
def _whatsapp():
from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin
host = WhatsAppBehaviorMixin()
host._dm_allowlist_source, host._allow_from = "WHATSAPP_ALLOWED_USERS", set()
return host
def _slack():
from plugins.platforms.slack.adapter import SlackAdapter
adapter = SlackAdapter.__new__(SlackAdapter)
adapter.config = PlatformConfig(enabled=True, extra={})
return adapter
def _dingtalk():
from plugins.platforms.dingtalk.adapter import DingTalkAdapter
adapter = DingTalkAdapter.__new__(DingTalkAdapter)
adapter.config = PlatformConfig(enabled=True, extra={})
return adapter
def _email():
from plugins.platforms.email.adapter import EmailAdapter
return EmailAdapter(PlatformConfig(enabled=True, extra={"address": "[email protected]"}))
def _line():
from plugins.platforms.line.adapter import LineAdapter
return LineAdapter(PlatformConfig(enabled=True, extra={"channel_access_token": "t", "channel_secret": "s"}))
# (label, opt-in the SECONDARY scope grants, gate(scope) -> observed value, closed value, open value)
_GATES = [
("email.allow_all", {"GATEWAY_ALLOW_ALL_USERS": "true"},
lambda: __import__("plugins.platforms.email.adapter", fromlist=["EmailAdapter"]).EmailAdapter._allow_all_senders(),
False, True),
("email.allowlist", {"EMAIL_ALLOWED_USERS": "[email protected]"},
lambda: _email()._sender_accepted("[email protected]", {"sender_authenticated": True}),
False, True),
("email.gateway_allowlist", {"GATEWAY_ALLOWED_USERS": "[email protected]"},
lambda: _email()._sender_accepted("[email protected]", {"sender_authenticated": True}),
False, True),
("qqbot.open_dm", {"QQ_ALLOW_ALL_USERS": "true"},
lambda: __import__("gateway.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter._open_dm_opted_in(object.__new__(__import__("gateway.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter)),
False, True),
("whatsapp.open_dm", {"GATEWAY_ALLOW_ALL_USERS": "true"},
lambda: __import__("gateway.platforms.whatsapp_common", fromlist=["WhatsAppBehaviorMixin"]).WhatsAppBehaviorMixin._open_dm_opted_in(_whatsapp()),
False, True),
("whatsapp.live_allow_from", {"WHATSAPP_ALLOWED_USERS": "+15559998888"},
lambda: __import__("gateway.platforms.whatsapp_common", fromlist=["WhatsAppBehaviorMixin"]).WhatsAppBehaviorMixin._live_dm_allow_from(_whatsapp()),
set(), {"+15559998888"}),
("teams.card_action", {"TEAMS_ALLOWED_USERS": "clicker"},
lambda: __import__("plugins.platforms.teams.adapter", fromlist=["TeamsAdapter"]).TeamsAdapter._card_action_denied(
SimpleNamespace(aad_object_id="clicker")) is None,
False, True),
("matrix.authorized_user", {"MATRIX_ALLOWED_USERS": "@bot2-admin:example.org"},
lambda: _matrix()._is_authorized_user("@bot2-admin:example.org"),
False, True),
("matrix.ignored_patterns", {"MATRIX_IGNORE_USER_PATTERNS": r"^@bot2-spam:.*"},
lambda: [p.pattern for p in _matrix()._ignored_user_patterns],
[], [r"^@bot2-spam:.*"]),
("slack.allow_bots", {"SLACK_ALLOW_BOTS": "mentions"}, lambda: _slack()._slack_allow_bots(), "none", "mentions"),
("slack.api_human_users", {"SLACK_API_HUMAN_USERS": "U0BOT2"},
lambda: set(_slack()._slack_api_human_users()), set(), {"U0BOT2"}),
("line.allow_all", {"LINE_ALLOW_ALL_USERS": "true"}, lambda: _line().allow_all, False, True),
("line.allowed_users", {"LINE_ALLOWED_USERS": "Ubot2"}, lambda: _line().allowed_users, set(), {"Ubot2"}),
("dingtalk.allowed_users", {"DINGTALK_ALLOWED_USERS": "Bot2Admin"},
lambda: {u.lower() for u in _dingtalk()._csv_setting("allowed_users", "DINGTALK_ALLOWED_USERS")}, set(), {"bot2admin"}),
]
@pytest.mark.parametrize("label,scope_opt_in,gate,closed,opened", _GATES, ids=[g[0] for g in _GATES])
def test_default_env_never_answers_a_scoped_gate(default_env, label, scope_opt_in, gate, closed, opened):
"""Secondary scope with NO opt-in: the default profile's permissive os.environ must not open it."""
with _scope({}):
assert gate() == closed
@pytest.mark.parametrize("label,scope_opt_in,gate,closed,opened", _GATES, ids=[g[0] for g in _GATES])
def test_scope_opt_in_opens_the_gate(default_env, monkeypatch, label, scope_opt_in, gate, closed, opened):
"""The secondary's own .env decides — even when the default profile's env is silent."""
for name in _DEFAULT_ENV:
monkeypatch.delenv(name, raising=False)
with _scope(scope_opt_in):
assert gate() == opened