slash_access.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. """Per-platform slash command access control.
  2. A second axis beside ``allow_from``: of the users allowed to talk to the gateway, which may run
  3. which slash commands. Two lists per scope (DM vs group, mirroring ``allow_from`` /
  4. ``group_allow_from``): ``allow_admin_from`` (user IDs that get every registered command, built-in
  5. and plugin) and ``user_allowed_commands`` (names non-admins may run; empty/unset -> only the
  6. ``_ALWAYS_ALLOWED_FOR_USERS`` floor). No ``allow_admin_from`` for a scope => gating disabled there,
  7. so existing installs are unaffected until an operator lists an admin. Applied at the dispatch
  8. site in ``gateway/run.py`` via the live registry; never affects plain chat.
  9. """
  10. from __future__ import annotations
  11. from dataclasses import dataclass
  12. from typing import Any, Callable, FrozenSet, Iterable, Optional
  13. # Read-only floor every allowed user keeps under gating, so a non-admin can still discover what
  14. # they can do. ``user_allowed_commands`` only adds to this set, never restricts it.
  15. _ALWAYS_ALLOWED_FOR_USERS: frozenset[str] = frozenset({"help", "whoami"})
  16. _DM_CHAT_TYPES = frozenset({"dm", "direct", "private", ""})
  17. # scope -> (admin list key, user command list key)
  18. _SCOPE_KEYS = {
  19. "dm": ("allow_admin_from", "user_allowed_commands"),
  20. "group": ("group_allow_admin_from", "group_user_allowed_commands"),
  21. }
  22. @dataclass(frozen=True)
  23. class SlashAccessPolicy:
  24. """Resolved access policy for one (platform, scope) pair; scope is ``"dm"`` or ``"group"``."""
  25. enabled: bool # gating active for this scope?
  26. admin_user_ids: frozenset[str]
  27. user_allowed_commands: frozenset[str]
  28. def is_admin(self, user_id: Optional[str]) -> bool:
  29. # Gating disabled -> everyone is admin so callers can use is_admin/can_run uniformly.
  30. if not self.enabled:
  31. return True
  32. return bool(user_id) and str(user_id) in self.admin_user_ids
  33. def can_run(self, user_id: Optional[str], canonical_cmd: str) -> bool:
  34. if self.is_admin(user_id):
  35. return True
  36. return bool(canonical_cmd) and (
  37. canonical_cmd in _ALWAYS_ALLOWED_FOR_USERS or canonical_cmd in self.user_allowed_commands
  38. )
  39. _DISABLED_POLICY = SlashAccessPolicy(
  40. enabled=False, admin_user_ids=frozenset(), user_allowed_commands=frozenset()
  41. )
  42. # Gated with nobody on the admin list: only the ``_ALWAYS_ALLOWED_FOR_USERS`` floor runs.
  43. _FAIL_CLOSED_POLICY = SlashAccessPolicy(
  44. enabled=True, admin_user_ids=frozenset(), user_allowed_commands=frozenset()
  45. )
  46. def _coerce_list(raw: Any, normalize: Callable[[str], str] = str) -> frozenset[str]:
  47. """Normalize a YAML-loaded value (None, list/tuple/set, comma string, or scalar) into a
  48. frozenset of stripped, non-empty strings, applying ``normalize`` to each."""
  49. if raw is None:
  50. return frozenset()
  51. if isinstance(raw, (list, tuple, set, frozenset)):
  52. items: Iterable[Any] = raw
  53. elif isinstance(raw, str):
  54. items = (s for s in raw.split(",") if s.strip())
  55. else:
  56. items = (raw,) # single scalar (int user id, etc.)
  57. return frozenset(s for s in (normalize(str(it).strip()) for it in items) if s)
  58. def _coerce_id_list(raw: Any) -> frozenset[str]:
  59. """Normalize an admin/user id list into a frozenset of strings."""
  60. return _coerce_list(raw)
  61. def _coerce_command_list(raw: Any) -> frozenset[str]:
  62. """Command allowlist: strip leading slashes (``/help`` or ``help``) and lowercase to match
  63. how ``resolve_command()`` stores names."""
  64. return _coerce_list(raw, lambda s: s.lstrip("/").lower())
  65. def policy_from_extra(extra: dict, scope: str) -> SlashAccessPolicy:
  66. """Build a policy from a platform's ``extra`` dict for one scope.
  67. DM scope falls back to ``group_user_allowed_commands`` ONLY for the command list, and only
  68. when DM didn't set its own. Admin lists are NOT cross-scope: a DM admin is not a group admin.
  69. """
  70. admin_key, cmd_key = _SCOPE_KEYS.get(scope, _SCOPE_KEYS["dm"])
  71. admin_ids = _coerce_id_list(extra.get(admin_key))
  72. cmds = _coerce_command_list(extra.get(cmd_key))
  73. if scope == "dm" and not cmds:
  74. cmds = _coerce_command_list(extra.get("group_user_allowed_commands"))
  75. return SlashAccessPolicy(enabled=bool(admin_ids), admin_user_ids=admin_ids, user_allowed_commands=cmds)
  76. def policy_for_source(gateway_config: Any, source: Any) -> SlashAccessPolicy:
  77. """Resolve the slash-gating policy for a SessionSource.
  78. Disabled (allow-everything) when gateway_config/source is None, the platform has no
  79. PlatformConfig, or no admin list is set for the scope. Gates slash commands only, never chat.
  80. """
  81. if gateway_config is None or source is None:
  82. return _DISABLED_POLICY
  83. platforms = getattr(gateway_config, "platforms", None)
  84. platform_config = None
  85. if platforms is not None:
  86. try:
  87. platform_config = platforms.get(source.platform)
  88. except Exception:
  89. platform_config = None
  90. # ``extra`` from a PlatformConfig-like object, or a bare dict as some test harnesses pass.
  91. extra = getattr(platform_config, "extra", None)
  92. if not isinstance(extra, dict):
  93. extra = platform_config if isinstance(platform_config, dict) else {}
  94. chat_type = getattr(source, "chat_type", None)
  95. normalized = str(chat_type).strip().lower() if chat_type is not None else ""
  96. if normalized:
  97. scope = "dm" if normalized in _DM_CHAT_TYPES else "group"
  98. return policy_from_extra(extra, scope)
  99. # Blank/None chat_type is ambiguous (relay frames may send "" / null; restored rows keep a
  100. # stored empty value verbatim). _DM_CHAT_TYPES lists "" but a truthiness guard made it
  101. # unreachable: resolve to whichever scope is gated so an ambiguous source never lands in an
  102. # ungated allow-everything scope; keep the historical group scope on a tie.
  103. dm_policy = policy_from_extra(extra, "dm")
  104. group_policy = policy_from_extra(extra, "group")
  105. return dm_policy if dm_policy.enabled and not group_policy.enabled else group_policy
  106. __all__ = ["SlashAccessPolicy", "policy_for_source", "policy_from_extra"]
  107. def policy_for_runner_source(runner: Any, source: Any) -> SlashAccessPolicy:
  108. """Slash-gating policy from the profile whose bot received ``source``.
  109. Under ``multiplex_profiles`` the runner's ``config`` is the launch profile's alone, so a platform
  110. configured only in a secondary profile had no PlatformConfig there and every caller came back
  111. unrestricted (#121705). Authorization follows the transport (bot-owning) profile, the owner
  112. ``RoutingIdentity.authorization_home`` already names; a served profile whose config is not cached
  113. fails closed instead of inheriting the launch profile's open policy.
  114. """
  115. config = getattr(runner, "config", None)
  116. if not getattr(config, "multiplex_profiles", False) or source is None:
  117. return policy_for_source(config, source)
  118. from gateway.session_identity import identity_of
  119. identity = identity_of(source)
  120. owner = identity.transport_profile if identity is not None else getattr(source, "profile", None)
  121. primary = getattr(runner, "_primary_profile_name", None) or "default"
  122. if owner and owner != primary:
  123. config = (getattr(runner, "_profile_configs", None) or {}).get(owner)
  124. if config is None:
  125. return _FAIL_CLOSED_POLICY
  126. return policy_for_source(config, source)