access_policy_mixin.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """Config-driven DM / group intake policy shared by the adapters that gate access themselves
  2. (Weixin, WeCom, QQBot, WhatsApp, Yuanbao's ``AccessPolicy``).
  3. Host contract — the adapter sets these on ``self`` before any predicate runs: ``_dm_policy`` /
  4. ``_group_policy`` (``open`` | ``allowlist`` | ``disabled`` | ``pairing``), ``_allow_from`` /
  5. ``_group_allow_from`` (iterable of allowlist entries), and ``ALLOW_ALL_ENV_PREFIX`` (class
  6. attribute, e.g. ``"WEIXIN"``). Platform-specific allowlist matching goes through
  7. ``_entry_matches``; env-seeded allowlists that must be re-read live go through
  8. ``_live_dm_allow_from``.
  9. Every env read is profile-scoped and fails closed: under multiplexing ``os.environ`` holds the
  10. DEFAULT profile's opt-in, which must never open a secondary bot's DMs (#93522).
  11. """
  12. from __future__ import annotations
  13. from typing import Iterable
  14. from gateway.platforms._shared import get_scoped_secret
  15. OPTIN_TRUTHY = frozenset({"true", "1", "yes"})
  16. class OwnAccessPolicyMixin:
  17. ALLOW_ALL_ENV_PREFIX: str = ""
  18. def __init_subclass__(cls, **kwargs):
  19. super().__init_subclass__(**kwargs)
  20. # A host that forgets its prefix would silently read ``_ALLOW_ALL_USERS`` and deny every
  21. # open-DM deployment whose setup wrote ``<PLATFORM>_ALLOW_ALL_USERS`` — refuse at class creation.
  22. if not str(cls.ALLOW_ALL_ENV_PREFIX or "").strip():
  23. raise TypeError(f"{cls.__qualname__} mixes in OwnAccessPolicyMixin but sets no ALLOW_ALL_ENV_PREFIX")
  24. @property
  25. def enforces_own_access_policy(self) -> bool:
  26. return True
  27. def _allow_all_env_names(self) -> tuple[str, ...]:
  28. return ("GATEWAY_ALLOW_ALL_USERS", f"{self.ALLOW_ALL_ENV_PREFIX}_ALLOW_ALL_USERS")
  29. def _open_dm_opted_in(self) -> bool:
  30. return any(str(get_scoped_secret(name, "") or "").strip().lower() in OPTIN_TRUTHY
  31. for name in self._allow_all_env_names())
  32. def _entry_matches(self, entries: Iterable[str], target: str) -> bool:
  33. return target in entries
  34. def _live_dm_allow_from(self) -> Iterable[str]:
  35. return self._allow_from
  36. def _is_dm_allowed(self, sender_id: str) -> bool:
  37. """Strict DM authorization — pairing does not imply access."""
  38. if self._dm_policy == "allowlist":
  39. return self._entry_matches(self._live_dm_allow_from(), sender_id)
  40. return self._dm_policy == "open" and self._open_dm_opted_in()
  41. def _is_dm_intake_allowed(self, sender_id: str) -> bool:
  42. """Whether a DM may reach gateway intake; ``pairing`` admits everyone with a principal so the
  43. handshake can run (the pairing gate itself runs later). A blank principal is never admitted."""
  44. principal = str(sender_id or "").strip()
  45. if not principal:
  46. return False
  47. return self._dm_policy == "pairing" or self._is_dm_allowed(principal)
  48. def _is_group_allowed(self, chat_id: str, sender_id: str = "") -> bool:
  49. """``disabled``/``pairing``/unknown policies never forward group traffic at intake."""
  50. if self._group_policy == "allowlist":
  51. return self._entry_matches(self._group_allow_from, chat_id)
  52. return self._group_policy == "open"