feishu_comment_rules.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. """Feishu document comment access-control rules: exact doc > wildcard "*" > top-level > code defaults, each field
  2. (enabled/policy/allow_from) falling back independently. Config ~/.hermes/feishu_comment_rules.json (mtime-cached,
  3. hot-reload); pairing store ~/.hermes/feishu_comment_pairing.json."""
  4. from __future__ import annotations
  5. import json
  6. import logging
  7. import sys
  8. import time
  9. from dataclasses import dataclass, field
  10. from pathlib import Path
  11. from typing import Any, Callable, Dict, Optional
  12. from hermes_constants import get_hermes_home
  13. logger = logging.getLogger(__name__)
  14. RULES_FILE = get_hermes_home() / "feishu_comment_rules.json"
  15. PAIRING_FILE = get_hermes_home() / "feishu_comment_pairing.json"
  16. _RULES_FILE_AT_IMPORT, _PAIRING_FILE_AT_IMPORT = RULES_FILE, PAIRING_FILE
  17. def _rules_file() -> Path:
  18. """Active profile's rules file at call time: the patched ``RULES_FILE`` when a test changed
  19. it, else live profile-scoped HERMES_HOME — the multiplexed gateway serves every profile from
  20. one process, so the import-time constant would apply the launch profile's rules everywhere."""
  21. return RULES_FILE if RULES_FILE != _RULES_FILE_AT_IMPORT else get_hermes_home() / "feishu_comment_rules.json"
  22. def _pairing_file() -> Path:
  23. return PAIRING_FILE if PAIRING_FILE != _PAIRING_FILE_AT_IMPORT else get_hermes_home() / "feishu_comment_pairing.json"
  24. _VALID_POLICIES = ("allowlist", "pairing")
  25. @dataclass(frozen=True)
  26. class CommentDocumentRule:
  27. """Per-document rule. ``None`` means 'inherit from lower tier'."""
  28. enabled: Optional[bool] = None
  29. policy: Optional[str] = None
  30. allow_from: Optional[frozenset] = None
  31. @dataclass(frozen=True)
  32. class CommentsConfig:
  33. """Top-level comment access config."""
  34. enabled: bool = True
  35. policy: str = "pairing"
  36. allow_from: frozenset = field(default_factory=frozenset)
  37. documents: dict[str, CommentDocumentRule] = field(default_factory=dict)
  38. @dataclass(frozen=True)
  39. class ResolvedCommentRule:
  40. """Fully resolved rule after field-by-field fallback."""
  41. enabled: bool
  42. policy: str
  43. allow_from: frozenset
  44. match_source: str # e.g. "exact:docx:xxx" | "wildcard" | "top"
  45. class _MtimeCache:
  46. """JSON file cache: ``utils.file_cache_version`` per access, re-read only on change. ``path`` is a
  47. ``Path`` or a zero-arg callable resolving one; state is keyed per resolved path so profiles
  48. routed through one multiplexed process never share a slot."""
  49. def __init__(self, path: Path | Callable[[], Path]):
  50. self._resolve = path if callable(path) else (lambda: path)
  51. self._entries: dict[Path, tuple[tuple, dict]] = {}
  52. def invalidate(self) -> None:
  53. self._entries.pop(self._resolve(), None)
  54. def load(self) -> dict:
  55. from utils import file_cache_version
  56. path = self._resolve()
  57. try:
  58. version = file_cache_version(path)
  59. except FileNotFoundError:
  60. self._entries.pop(path, None)
  61. return {}
  62. except OSError:
  63. version = None # unreadable: the read below logs it and serves {}; never a cache hit
  64. cached = self._entries.get(path)
  65. if cached is not None and version is not None and cached[0] == version:
  66. return cached[1]
  67. try:
  68. with open(path, "r", encoding="utf-8-sig") as f:
  69. data = json.load(f)
  70. except (json.JSONDecodeError, OSError):
  71. logger.warning("[Feishu-Rules] Failed to read %s, using empty config", path)
  72. data = {}
  73. data = data if isinstance(data, dict) else {}
  74. self._entries[path] = (version, data)
  75. return data
  76. _rules_cache = _MtimeCache(_rules_file)
  77. _pairing_cache = _MtimeCache(_pairing_file)
  78. def _parse_frozenset(raw: Any) -> Optional[frozenset]:
  79. """Parse a list of strings into a frozenset; None if absent or not a list."""
  80. return frozenset(str(u).strip() for u in raw if str(u).strip()) if isinstance(raw, (list, tuple)) else None
  81. def _parse_policy(raw: Any, default: Optional[str]) -> Optional[str]:
  82. """Normalize a policy value; unknown/invalid values fall back to *default*."""
  83. policy = str(raw).strip().lower() if raw is not None else None
  84. return policy if policy in _VALID_POLICIES else default
  85. def _parse_document_rule(raw: dict) -> CommentDocumentRule:
  86. enabled = raw.get("enabled")
  87. return CommentDocumentRule(enabled=None if enabled is None else bool(enabled), policy=_parse_policy(raw.get("policy"), None), allow_from=_parse_frozenset(raw.get("allow_from")))
  88. def load_config() -> CommentsConfig:
  89. """Load comment rules from disk (mtime-cached)."""
  90. raw = _rules_cache.load()
  91. if not raw:
  92. return CommentsConfig()
  93. raw_docs = raw.get("documents", {})
  94. documents = {str(key): _parse_document_rule(rule_raw) for key, rule_raw in (raw_docs.items() if isinstance(raw_docs, dict) else ()) if isinstance(rule_raw, dict)}
  95. return CommentsConfig(
  96. enabled=raw.get("enabled", True), policy=_parse_policy(raw.get("policy", "pairing"), "pairing"),
  97. allow_from=_parse_frozenset(raw.get("allow_from")) or frozenset(), documents=documents,
  98. )
  99. def has_wiki_keys(cfg: CommentsConfig) -> bool:
  100. """Check if any document rule key starts with 'wiki:'."""
  101. return any(k.startswith("wiki:") for k in cfg.documents)
  102. def resolve_rule(cfg: CommentsConfig, file_type: str, file_token: str, wiki_token: str = "") -> ResolvedCommentRule:
  103. """Resolve effective rule: exact doc → wiki key → wildcard → top-level → defaults."""
  104. exact_key = f"{file_type}:{file_token}"
  105. exact = cfg.documents.get(exact_key)
  106. if exact is None and wiki_token:
  107. exact_key = f"wiki:{wiki_token}"
  108. exact = cfg.documents.get(exact_key)
  109. layers = [(exact, f"exact:{exact_key}"), (cfg.documents.get("*"), "wildcard")]
  110. def _pick(field_name: str): # first non-None document-layer value wins; otherwise the top-level value (even if None)
  111. return next(((getattr(layer, field_name), src) for layer, src in layers if layer is not None and getattr(layer, field_name) is not None), (getattr(cfg, field_name), "top"))
  112. enabled, en_src = _pick("enabled")
  113. policy, pol_src = _pick("policy")
  114. # match_source = highest-priority tier that contributed enabled or policy
  115. priority_order = {"exact": 0, "wildcard": 1, "top": 2}
  116. best_src = min([en_src, pol_src], key=lambda s: priority_order.get(s.split(":")[0], 3))
  117. return ResolvedCommentRule(enabled=enabled, policy=policy, allow_from=_pick("allow_from")[0], match_source=best_src)
  118. def _load_pairing_approved() -> set:
  119. """Return set of approved user open_ids (mtime-cached)."""
  120. approved = _pairing_cache.load().get("approved", {})
  121. return set(approved.keys()) if isinstance(approved, dict) else ({str(u) for u in approved if u} if isinstance(approved, list) else set())
  122. def _save_pairing(data: dict) -> None:
  123. pairing_file = _pairing_file()
  124. pairing_file.parent.mkdir(parents=True, exist_ok=True)
  125. with open(pairing_file.with_suffix(".tmp"), "w", encoding="utf-8") as f: # windows-footgun: ok (write/append mode, not a read)
  126. json.dump(data, f, indent=2, ensure_ascii=False)
  127. pairing_file.with_suffix(".tmp").replace(pairing_file)
  128. _pairing_cache.invalidate() # same-second rewrite can keep the mtime; force the next load to re-read
  129. def _mutate_pairing(user_open_id: str, add: bool) -> bool:
  130. """Add/remove *user_open_id* in the approved dict; True when the store actually changed."""
  131. data = _pairing_cache.load()
  132. approved = data.get("approved", {}) if isinstance(data.get("approved"), dict) else {}
  133. if (user_open_id in approved) == add:
  134. return False
  135. if add:
  136. approved[user_open_id] = {"approved_at": time.time()}
  137. else:
  138. del approved[user_open_id]
  139. data["approved"] = approved
  140. _save_pairing(data)
  141. return True
  142. def pairing_add(user_open_id: str) -> bool:
  143. """Add a user to the pairing-approved list. Returns True if newly added."""
  144. return _mutate_pairing(user_open_id, add=True)
  145. def pairing_remove(user_open_id: str) -> bool:
  146. """Remove a user from the pairing-approved list. Returns True if removed."""
  147. return _mutate_pairing(user_open_id, add=False)
  148. def pairing_list() -> dict[str, Any]:
  149. """Return the approved dict {user_open_id: {approved_at: ...}}."""
  150. approved = _pairing_cache.load().get("approved", {})
  151. return dict(approved) if isinstance(approved, dict) else {}
  152. def is_user_allowed(rule: ResolvedCommentRule, user_open_id: str) -> bool:
  153. """Check if user passes the resolved rule's policy gate."""
  154. return user_open_id in rule.allow_from or (rule.policy == "pairing" and user_open_id in _load_pairing_approved())
  155. def _fmt_allow(allow_from) -> str:
  156. return f"{sorted(allow_from) if allow_from else '[]'}"
  157. def _print_status() -> None:
  158. cfg = load_config()
  159. rules_file, pairing_file = _rules_file(), _pairing_file()
  160. print(f"Rules file: {rules_file}\n exists: {rules_file.exists()}\nPairing file: {pairing_file}\n exists: {pairing_file.exists()}\n")
  161. print(f"Top-level:\n enabled: {cfg.enabled}\n policy: {cfg.policy}\n allow_from: {_fmt_allow(cfg.allow_from)}\n")
  162. print(f"Document rules ({len(cfg.documents)}):" if cfg.documents else "Document rules: (none)")
  163. for key, rule in sorted(cfg.documents.items()):
  164. fields = (("enabled", rule.enabled), ("policy", rule.policy), ("allow_from", sorted(rule.allow_from) if rule.allow_from is not None else None))
  165. parts = [f"{name}={value}" for name, value in fields if value is not None]
  166. print(f" [{key}] {', '.join(parts) if parts else '(empty — inherits all)'}")
  167. print()
  168. approved = pairing_list()
  169. print(f"Pairing approved ({len(approved)}):")
  170. for uid, meta in sorted(approved.items()):
  171. print(f" {uid} (approved_at={meta.get('approved_at', 0)})")
  172. def _do_check(doc_key: str, user_open_id: str) -> None:
  173. parts = doc_key.split(":", 1)
  174. if len(parts) != 2:
  175. return print(f"Error: doc_key must be 'fileType:fileToken', got '{doc_key}'")
  176. rule = resolve_rule(load_config(), parts[0], parts[1])
  177. allowed = is_user_allowed(rule, user_open_id)
  178. print(f"Document: {doc_key}\nUser: {user_open_id}\nResolved rule:\n enabled: {rule.enabled}\n policy: {rule.policy}")
  179. print(f" allow_from: {_fmt_allow(rule.allow_from)}\n match_source: {rule.match_source}\nResult: {'ALLOWED' if allowed else 'DENIED'}")
  180. _PAIRING_OPS = {"add": (pairing_add, "Added: {}", "Already approved: {}"), "remove": (pairing_remove, "Removed: {}", "Not in approved list: {}")}
  181. def _pairing_cmd(args: list) -> int:
  182. """Handle ``pairing <add|remove|list> [user]``; returns the exit code."""
  183. sub = args[1] if len(args) > 1 else None
  184. if sub == "list":
  185. approved = pairing_list()
  186. print(*(f" {uid} approved_at={meta.get('approved_at', '?')}" for uid, meta in sorted(approved.items())) if approved else ("(no approved users)",), sep="\n")
  187. return 0
  188. if sub in _PAIRING_OPS and len(args) >= 3:
  189. fn, ok_msg, noop_msg = _PAIRING_OPS[sub]
  190. print((ok_msg if fn(args[2]) else noop_msg).format(args[2]))
  191. return 0
  192. print("Usage: pairing <add|remove|list> [args]" if sub is None else f"Usage: pairing {sub} <user_open_id>" if sub in _PAIRING_OPS else f"Unknown pairing subcommand: {sub}")
  193. return 1
  194. def _main() -> int:
  195. try:
  196. __import__("hermes_cli.env_loader", fromlist=["load_hermes_dotenv"]).load_hermes_dotenv()
  197. except Exception:
  198. pass
  199. usage = f"""Usage: python -m gateway.platforms.feishu_comment_rules <command> [args]
  200. Commands:
  201. status Show rules config and pairing state
  202. check <fileType:token> <user> Simulate access check
  203. pairing add <user_open_id> Add user to pairing-approved list
  204. pairing remove <user_open_id> Remove user from pairing-approved list
  205. pairing list List pairing-approved users
  206. Rules config file: {_rules_file()}
  207. Edit this JSON file directly to configure policies and document rules.
  208. Changes take effect on the next comment event (no restart needed).
  209. """
  210. args = sys.argv[1:]
  211. cmd = args[0] if args else ""
  212. if cmd == "status":
  213. _print_status()
  214. elif cmd == "check" and len(args) >= 3:
  215. _do_check(args[1], args[2])
  216. elif cmd == "check":
  217. print("Usage: check <fileType:fileToken> <user_open_id>")
  218. return 1
  219. elif cmd == "pairing":
  220. return _pairing_cmd(args)
  221. else:
  222. print(f"Unknown command: {cmd}\n{usage}" if cmd else usage)
  223. return 1
  224. return 0
  225. if __name__ == "__main__":
  226. sys.exit(_main())