platform_env.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """Declarative env-credential bridge a platform plugin attaches to its ``PlatformEntry``.
  2. A platform declares ``env_overrides`` (ordered ``step(config)`` callables, usually :class:`EnvCred`,
  3. :func:`home_step`, :func:`reply_mode_step`) and ``env_enable_credentials`` (the env names its
  4. explicit-disable WARNING cites). ``gateway.config_env._apply_env_overrides`` runs the steps of every
  5. platform with activation evidence, so the data lives with the adapter instead of in a core table.
  6. Import-light on purpose (only ``gateway.config``): adapters import it at module load.
  7. """
  8. import contextlib
  9. import functools
  10. import importlib.util
  11. import json
  12. import logging
  13. from dataclasses import dataclass
  14. from functools import partial
  15. from pathlib import Path
  16. from typing import Any, Callable, Optional
  17. from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfig, _getenv_str
  18. # Logger name parity with the origin module: records stay under "gateway.config".
  19. logger = logging.getLogger("gateway.config")
  20. getenv = _getenv_str
  21. # --- small value parsers -----------------------------------------------------
  22. def csv_list(value: str) -> list:
  23. return [part.strip() for part in value.split(",") if part.strip()]
  24. def int_or(default: int) -> Callable[[str], int]:
  25. """``int(raw.strip(), 10)`` with *default* on malformed/blank input."""
  26. def parse(raw: str) -> int:
  27. try:
  28. return int(str(raw).strip(), 10)
  29. except (TypeError, ValueError):
  30. return default
  31. return parse
  32. def strip_slash(value: str) -> str:
  33. return value.rstrip("/")
  34. def strip_lower(value: str) -> str:
  35. return value.strip().lower()
  36. def truthy_token(value: str) -> bool:
  37. return value.lower() in {"true", "1", "yes", "on"}
  38. def mention_patterns(value: str) -> Any:
  39. """JSON list, else comma/newline separated."""
  40. try:
  41. return json.loads(value)
  42. except ValueError: # json.JSONDecodeError
  43. return csv_list(value.replace("\n", ","))
  44. def csv_extras(extra: dict[str, Any], spec) -> None:
  45. """``extra[key] = csv_list(raw)`` for each ``(key, raw)`` whose list is non-empty."""
  46. for key, raw in spec:
  47. items = csv_list(raw)
  48. if items:
  49. extra[key] = items
  50. def env_first(envs) -> str:
  51. """First truthy value among *envs* (a single name or a tuple of alternatives)."""
  52. if isinstance(envs, str):
  53. return getenv(envs)
  54. return next((v for v in map(getenv, envs) if v), "")
  55. # --- reusable steps -----------------------------------------------------------
  56. INT = object() # spec marker: ``int(value)``, silently skipped when malformed
  57. def env_extras(extra: dict[str, Any], spec, *, strip: bool = False) -> None:
  58. """``extra[key] = fn(value)`` for each ``(key, env[, fn])`` whose env value is truthy.
  59. ``strip=True`` strips BEFORE the truthiness check. ``fn=INT`` parses an int
  60. and silently ignores a non-integer value.
  61. """
  62. for key, env, *fn in spec:
  63. value = getenv(env)
  64. if strip:
  65. value = value.strip()
  66. if not value:
  67. continue
  68. if fn and fn[0] is INT:
  69. with contextlib.suppress(ValueError):
  70. extra[key] = int(value)
  71. else:
  72. extra[key] = fn[0](value) if fn else value
  73. def env_home_channel(config: GatewayConfig, platform: Platform, env_base: str, *, strip: bool = False) -> None:
  74. """Set ``home_channel`` from ``<env_base>`` (+``_NAME``/``_THREAD_ID``) when the platform is configured."""
  75. chat_id = getenv(env_base)
  76. if strip:
  77. chat_id = chat_id.strip()
  78. if chat_id and platform in config.platforms:
  79. config.platforms[platform].home_channel = HomeChannel(
  80. platform=platform, chat_id=chat_id,
  81. name=getenv(f"{env_base}_NAME", "Home"), thread_id=getenv(f"{env_base}_THREAD_ID") or None,
  82. )
  83. def env_reply_mode(config: GatewayConfig, platform: Platform, env: str) -> None:
  84. mode = getenv(env).lower()
  85. if mode in {"off", "first", "all"}:
  86. config.platforms.setdefault(platform, PlatformConfig()).reply_to_mode = mode
  87. # ``partial`` (not a closure) so ``hermes_cli.profile_channels`` can read the env names a step owns
  88. # from ``step.keywords`` (``env`` / ``env_base``).
  89. def home_step(platform: Platform, env_base: str, *, strip: bool = False):
  90. return partial(env_home_channel, platform=platform, env_base=env_base, strip=strip)
  91. def reply_mode_step(platform: Platform, env: str):
  92. return partial(env_reply_mode, platform=platform, env=env)
  93. def enable_from_env(config: GatewayConfig, platform: Platform) -> PlatformConfig:
  94. """Enable *platform* on env credentials unless config.yaml explicitly disabled it (warns once).
  95. Delegates to the core gate, which owns the explicit-disable marker and the one-time WARNING."""
  96. from gateway.config_env import _enable_from_env # lazy: config_env imports this module
  97. return _enable_from_env(config, platform)
  98. @dataclass(frozen=True)
  99. class EnvCred:
  100. """Credential-gated platform enable, applied as ``step(config)``.
  101. ``creds``: env names that must ALL be truthy (inner tuple = ANY of). ``token``: env stored as
  102. ``PlatformConfig.token`` even when yaml disables the adapter (sending skills use it). ``fixed``:
  103. ``(extra_key, env[, default[, fn]])`` always written once enabled. ``optional*``: ``env_extras``
  104. specs. ``warn_missing``: ``(env, msg)`` logged BEFORE enabling when blank. ``then``: tail
  105. ``fn(config, platform_config)``. ``home``: ``env_home_channel`` env base applied only when the gate passed.
  106. """
  107. platform: Platform
  108. creds: tuple
  109. token: Optional[str] = None
  110. fixed: tuple = ()
  111. optional: tuple = ()
  112. optional_stripped: tuple = ()
  113. warn_missing: Optional[tuple] = None
  114. then: Optional[Callable[[GatewayConfig, PlatformConfig], None]] = None
  115. home: Optional[str] = None
  116. home_strip: bool = False
  117. def __call__(self, config: GatewayConfig) -> None:
  118. if not all(env_first(group) for group in self.creds):
  119. return
  120. if self.warn_missing and not getenv(self.warn_missing[0]):
  121. logger.warning(self.warn_missing[1])
  122. platform_config = enable_from_env(config, self.platform)
  123. if self.token and (token := getenv(self.token)):
  124. platform_config.token = token
  125. extra = platform_config.extra
  126. for key, env, *rest in self.fixed:
  127. default = rest[0] if rest else ""
  128. value = env_first(env) or default if isinstance(env, tuple) else getenv(env, default)
  129. extra[key] = rest[1](value) if len(rest) > 1 else value
  130. env_extras(extra, self.optional)
  131. env_extras(extra, self.optional_stripped, strip=True)
  132. if self.then is not None:
  133. self.then(config, platform_config)
  134. if self.home:
  135. env_home_channel(config, self.platform, self.home, strip=self.home_strip)
  136. # --- bundled rows without the plugin -------------------------------------------
  137. # Entries a bundled plugin registers under a name other than its directory, with the export prefix.
  138. _BUNDLED_ENV_SIBLINGS = {"wecom_callback": ("wecom", "CALLBACK_")}
  139. @functools.cache
  140. def bundled_sibling(directory: str, stem: str = "gateway_env") -> Any:
  141. """``plugins/platforms/<directory>/<stem>.py`` (a light declaration module importing only core)
  142. executed from its file under a private name: the plugin package (``__init__``, adapter,
  143. ``register()``) is never imported. None when absent or *directory* is not a bundled plugin."""
  144. from gateway.config import Platform
  145. if directory not in Platform._scan_bundled_plugin_platforms()[0]:
  146. return None
  147. path = Path(__file__).resolve().parent.parent / "plugins" / "platforms" / directory / f"{stem}.py"
  148. if not path.is_file():
  149. return None
  150. spec = importlib.util.spec_from_file_location(f"_hermes_bundled_{stem}_{directory}", path)
  151. module = importlib.util.module_from_spec(spec)
  152. spec.loader.exec_module(module)
  153. return module
  154. def bundled_env_rows(name: str) -> Optional[tuple]:
  155. """``(env_overrides, env_enable_credentials)`` a BUNDLED platform plugin declares, read without
  156. the plugin. For when its registry entry is absent: discovery suppressed (a parked profile's
  157. config read, ``HERMES_SAFE_MODE``) or the plugin disabled. These rows were core's own table, and
  158. the duplicate-credential guard and the explicit-disable warning still need them then."""
  159. directory, prefix = _BUNDLED_ENV_SIBLINGS.get(name, (name, ""))
  160. module = bundled_sibling(directory)
  161. if module is None:
  162. return None
  163. return (tuple(getattr(module, f"{prefix}ENV_OVERRIDES", ()) or ()),
  164. tuple(getattr(module, f"{prefix}ENV_ENABLE_CREDENTIALS", ()) or ()))
  165. def bundled_authz(name: str) -> dict:
  166. """``AUTHZ`` (allowlist / allow-all / allow-bots / own-policy env names) a bundled platform
  167. plugin declares in its ``gateway_env.py``, read without the plugin; {} for other names."""
  168. directory, prefix = _BUNDLED_ENV_SIBLINGS.get(name, (name, ""))
  169. module = bundled_sibling(directory)
  170. return dict(getattr(module, f"{prefix}AUTHZ", None) or {}) if module is not None else {}
  171. def authz_field(name: str, field: str, entry: Any = None) -> Any:
  172. """*entry*'s authorization env field, else the bundled plugin's declaration. A user plugin
  173. overriding a bundled platform, safe mode or a disabled plugin then still gate on the names core
  174. always enforced for it; never looser than the bundled adapter."""
  175. value = getattr(entry, field, None) if entry is not None else None
  176. return value or bundled_authz(str(name or "").strip().lower()).get(field)