media_policy.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. """Shared config→env bridge for media-delivery policy.
  2. ``validate_media_delivery_path`` reads ``HERMES_MEDIA_DELIVERY_STRICT`` (gateway.strict),
  3. ``HERMES_MEDIA_ALLOW_DIRS`` (gateway.media_delivery_allow_dirs) and
  4. ``HERMES_MEDIA_TRUST_RECENT_FILES`` (gateway.trust_recent_files). Every delivery
  5. entrypoint (gateway startup, ``hermes cron run``, ``hermes send``) calls
  6. :func:`apply_media_policy_env` first so standalone paths filter under the gateway's
  7. policy instead of silently dropping attachments in strict/allowlisted deployments.
  8. An explicitly-set env var WINS over config.yaml, so shell overrides survive. Under a HERMES_HOME
  9. override (a served profile's turn or cron fire) nothing is bridged: readers load that profile's config.
  10. """
  11. from __future__ import annotations
  12. import logging
  13. import os
  14. from typing import Any, Dict, Optional
  15. logger = logging.getLogger(__name__)
  16. _FLAG_ENVS = (("strict", "HERMES_MEDIA_DELIVERY_STRICT"), ("trust_recent_files", "HERMES_MEDIA_TRUST_RECENT_FILES"))
  17. _ALLOW_DIRS_ENV = "HERMES_MEDIA_ALLOW_DIRS"
  18. _TRUST_RECENT_SECONDS_ENV = "HERMES_MEDIA_TRUST_RECENT_SECONDS"
  19. _TRUTHY = frozenset({"1", "true", "yes", "on"})
  20. def _routed_gateway_cfg() -> Optional[dict[str, Any]]:
  21. """``gateway`` section of the ROUTED profile's config when a HERMES_HOME override is active
  22. (multiplexed turn), else None. The env bridge is one process-wide copy of the launch profile's
  23. policy, so a secondary's deliveries must read their own config instead of ``os.environ``."""
  24. from hermes_constants import get_hermes_home_override
  25. if not get_hermes_home_override():
  26. return None
  27. try:
  28. from hermes_cli.config import load_config_readonly
  29. gateway_cfg = load_config_readonly().get("gateway")
  30. except Exception:
  31. return {}
  32. return gateway_cfg if isinstance(gateway_cfg, dict) else {}
  33. def media_delivery_strict() -> bool:
  34. cfg = _routed_gateway_cfg()
  35. if cfg is not None:
  36. return bool(cfg.get("strict", False))
  37. return os.environ.get(_FLAG_ENVS[0][1], "0").strip().lower() in _TRUTHY
  38. def media_delivery_allow_dirs() -> str:
  39. """Operator allowlist as the ``os.pathsep``-joined string the validator splits."""
  40. cfg = _routed_gateway_cfg()
  41. if cfg is not None:
  42. return _allow_dirs_str(cfg.get("media_delivery_allow_dirs"))
  43. return os.environ.get(_ALLOW_DIRS_ENV, "")
  44. def media_delivery_trust_recent() -> bool:
  45. cfg = _routed_gateway_cfg()
  46. if cfg is not None:
  47. return bool(cfg.get("trust_recent_files", True))
  48. return os.environ.get(_FLAG_ENVS[1][1], "1").strip().lower() not in ("0", "false", "no", "off", "")
  49. def media_delivery_trust_recent_seconds() -> str:
  50. """Raw recency window (``""`` = validator default); the caller parses/floors it."""
  51. cfg = _routed_gateway_cfg()
  52. if cfg is not None:
  53. raw = cfg.get("trust_recent_files_seconds")
  54. return "" if raw is None else str(raw)
  55. return os.environ.get(_TRUST_RECENT_SECONDS_ENV, "")
  56. def _load_gateway_cfg(config: Optional[dict[str, Any]] = None) -> dict[str, Any]:
  57. if config is None:
  58. try:
  59. from hermes_cli.config import load_config
  60. config = load_config() or {}
  61. except Exception:
  62. return {}
  63. gateway_cfg = config.get("gateway", {})
  64. return gateway_cfg if isinstance(gateway_cfg, dict) else {}
  65. def _set_env_default(env: str, value: str) -> None:
  66. """Set ``env`` only when unset/empty and ``value`` is non-empty (env wins)."""
  67. if value and not os.environ.get(env):
  68. os.environ[env] = value
  69. def _allow_dirs_str(allow_dirs: Any) -> str:
  70. if isinstance(allow_dirs, (list, tuple)):
  71. return os.pathsep.join(str(p) for p in allow_dirs if p)
  72. return allow_dirs if isinstance(allow_dirs, str) else ""
  73. def apply_media_policy_env(config: Optional[dict[str, Any]] = None) -> None:
  74. """Bridge gateway media-policy settings from config.yaml into the env. Idempotent,
  75. env-wins, never raises — a bridge failure must not break delivery (validator defaults apply).
  76. No-op under a HERMES_HOME override, the same gate the readers use: there they take the
  77. profile's own config (``_routed_gateway_cfg``), and ``os.environ`` is shared — a routed cron
  78. fire would hand its allowlist and strictness to the launch profile and its children."""
  79. try:
  80. from hermes_constants import get_hermes_home_override
  81. if get_hermes_home_override():
  82. return
  83. gateway_cfg = _load_gateway_cfg(config)
  84. if not gateway_cfg:
  85. return
  86. for key, env in _FLAG_ENVS:
  87. flag = gateway_cfg.get(key)
  88. if flag is not None:
  89. _set_env_default(env, "1" if flag else "0")
  90. allow_dirs = gateway_cfg.get("media_delivery_allow_dirs")
  91. if allow_dirs:
  92. _set_env_default(_ALLOW_DIRS_ENV, _allow_dirs_str(allow_dirs))
  93. except Exception:
  94. logger.debug("apply_media_policy_env failed", exc_info=True)