env_passthrough.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """Environment variable passthrough registry: the session-scoped allowlist of vars a
  2. skill's ``required_environment_variables`` (registered by ``skill_view``) or
  3. ``terminal.env_passthrough`` in config.yaml may forward into sandboxed children
  4. (execute_code, terminal), which strip secrets by default. Under profile multiplexing,
  5. forwarded values resolve through the profile's secret scope, not the process env."""
  6. from __future__ import annotations
  7. import logging
  8. from typing import Iterable
  9. from hermes_cli.config import cfg_get, read_raw_config
  10. logger = logging.getLogger(__name__)
  11. # Process-wide set of env var names registered by skills for sandbox
  12. # passthrough. Deliberately NOT a ContextVar: tool dispatch fans each tool
  13. # call onto a worker whose context is a copy_context() snapshot taken at
  14. # submit time (tools.thread_context.propagate_context_to_thread), so a
  15. # registration made inside one tool's worker (skill_view calling
  16. # register_env_passthrough) never reaches the submitting thread's context —
  17. # every subsequent tool (execute_code, terminal) re-snapshots the original
  18. # context and sees an empty allowlist, and the skill's declared env vars
  19. # never pass through (#90004). The config-based allowlist below is already
  20. # a module-level global with exactly the process-wide visibility the skill
  21. # path needs to match.
  22. #
  23. # Cross-session exposure is limited to the NAMES: the values still resolve
  24. # per profile through resolve_passthrough_value's secret_scope, so a name
  25. # registered by one session cannot read another profile's secret. The
  26. # previous ContextVar also never actually isolated anything within one
  27. # process running a single profile (the common deployment).
  28. _allowed_env_vars: set[str] = set()
  29. def _get_allowed() -> set[str]:
  30. """Get the process-wide skill passthrough allowlist."""
  31. return _allowed_env_vars
  32. # Config-based allowlist, keyed by Hermes home: under gateway.multiplex_profiles one process serves
  33. # many profiles, and a single slot would let the first profile's operator allowlist decide which env
  34. # vars tunnel into every other profile's sandbox children.
  35. _config_passthrough: dict[str, frozenset[str]] = {}
  36. def _is_hermes_provider_credential(name: str) -> bool:
  37. """True if ``name`` is a Hermes-managed provider credential per
  38. ``_HERMES_PROVIDER_ENV_BLOCKLIST`` or a dynamic Hermes-internal secret
  39. (AUXILIARY_*_API_KEY / _BASE_URL, GATEWAY_RELAY_*). Skill-declared
  40. ``required_environment_variables`` must not override this — that was the
  41. GHSA-rhgp-j443-p4rf bypass (a skill registered ``OPENAI_API_KEY`` and received it
  42. in the ``execute_code`` child); non-Hermes keys (TENOR_API_KEY, …) stay
  43. registerable. Fails closed when the blocklist cannot be imported."""
  44. try:
  45. from tools.environments.local_env_policy import (
  46. _is_hermes_internal_secret, _is_provider_env_blocklisted)
  47. except Exception as e:
  48. logger.warning(
  49. "env passthrough: provider credential blocklist import failed; "
  50. "failing closed and refusing passthrough registration for %r: %s", name, e)
  51. return True
  52. # Case-folded membership too: the remote-exec env builder resolves each
  53. # registered name via os.getenv(), which is case-insensitive on Windows, so
  54. # ``openai_api_key`` would tunnel the real OPENAI_API_KEY into children.
  55. return _is_hermes_internal_secret(name) or _is_provider_env_blocklisted(name)
  56. def register_env_passthrough(var_names: Iterable[str]) -> None:
  57. """Register env var names as allowed in sandboxed environments (typically a
  58. skill's ``required_environment_variables``). Hermes-managed provider credentials
  59. are rejected (GHSA-rhgp-j443-p4rf) — such skills should use the main-process tools
  60. (web_search, web_extract, …); third-party keys pass normally."""
  61. for name in _accepted((n.strip() for n in var_names), (
  62. "env passthrough: refusing to register Hermes provider "
  63. "credential %r (blocked by _HERMES_PROVIDER_ENV_BLOCKLIST). "
  64. "Skills must not override the execute_code sandbox's "
  65. "credential scrubbing; see GHSA-rhgp-j443-p4rf."
  66. )):
  67. _get_allowed().add(name)
  68. logger.debug("env passthrough: registered %s", name)
  69. def _accepted(names, refusal_msg: str):
  70. """Yield non-empty *names* that are not Hermes provider credentials; refused
  71. names are logged with *refusal_msg* (``%r`` = name)."""
  72. for name in names:
  73. if not name:
  74. continue
  75. if _is_hermes_provider_credential(name):
  76. logger.warning(refusal_msg, name)
  77. continue
  78. yield name
  79. def _load_config_passthrough() -> frozenset[str]:
  80. """Load ``tools.env_passthrough`` from config.yaml (cached). Same credential
  81. filter as register_env_passthrough: operator config must not tunnel provider
  82. credentials into sandbox children either (GHSA-rhgp-j443-p4rf)."""
  83. from hermes_constants import hermes_home_key
  84. try:
  85. home_key = hermes_home_key()
  86. except (RuntimeError, OSError):
  87. # No resolvable home (stripped environ in a sandbox child): nothing to scope by.
  88. home_key = ""
  89. cached = _config_passthrough.get(home_key)
  90. if cached is not None:
  91. return cached
  92. result: set[str] = set()
  93. try:
  94. passthrough = cfg_get(read_raw_config(), "terminal", "env_passthrough")
  95. items = passthrough if isinstance(passthrough, list) else ()
  96. result.update(_accepted((i.strip() for i in items if isinstance(i, str)), (
  97. "env passthrough: refusing to register Hermes "
  98. "provider credential %r from config.yaml (blocked "
  99. "by _HERMES_PROVIDER_ENV_BLOCKLIST). Operator "
  100. "configuration must not override the execute_code "
  101. "sandbox's credential scrubbing; see "
  102. "GHSA-rhgp-j443-p4rf."
  103. )))
  104. except Exception as e:
  105. logger.debug("Could not read tools.env_passthrough from config: %s", e)
  106. _config_passthrough[home_key] = frozenset(result)
  107. return _config_passthrough[home_key]
  108. def is_env_passthrough(var_name: str) -> bool:
  109. """True if *var_name* was registered by a skill or listed in config and is not a
  110. Hermes-managed credential NOW. Ownership changes after acceptance (a platform plugin
  111. registered later declares the name in its ``required_env`` or manifest), so the refusal applied at registration
  112. is re-applied here, where every child builder consumes the allowlist."""
  113. return ((var_name in _get_allowed() or var_name in _load_config_passthrough())
  114. and not _is_hermes_provider_credential(var_name))
  115. def get_all_passthrough() -> frozenset[str]:
  116. """Return the union of skill-registered and config-based passthrough vars, minus names
  117. that have become Hermes-managed credentials since they were accepted."""
  118. return frozenset(name for name in frozenset(_get_allowed()) | _load_config_passthrough()
  119. if not _is_hermes_provider_credential(name))
  120. def resolve_passthrough_value(name: str, fallback: str | None = None) -> str | None:
  121. """Resolve an allowlisted variable without crossing profile boundaries. ``fallback``
  122. is what the caller would have forwarded before secret scopes existed (a snapshot of
  123. ``os.environ`` / the profile ``.env``). An active multiplex scope is authoritative:
  124. a missing key returns ``None``, never the process-global env, and an unscoped read
  125. raises the fail-closed ``UnscopedSecretError``. Outside multiplexing an installed
  126. scope keeps overlay semantics and an unscoped caller keeps its fallback."""
  127. from agent.secret_scope import (
  128. _is_global_env, current_secret_scope, get_secret, is_multiplex_active)
  129. # Global terminal/runtime settings are not profile secrets; ``fallback`` is
  130. # already the caller's effective value (incl. an explicit per-call override).
  131. if _is_global_env(name) and fallback is not None:
  132. return fallback
  133. multiplex_active = is_multiplex_active()
  134. if current_secret_scope() is None:
  135. return get_secret(name) if multiplex_active else fallback
  136. return get_secret(name, None if multiplex_active else fallback)
  137. def scoped_passthrough_additions(present: Iterable[str]) -> dict[str, str]:
  138. """Declared passthrough names the bound profile secret scope supplies but the env being
  139. filtered (*present*) lacks. A routed profile's ``.env`` and hydrated sources never enter
  140. ``os.environ`` (``load_hermes_dotenv`` skips the process-global load for a routed home), so a
  141. name-by-name filter over the process env can only forward a declared name the LAUNCH profile
  142. also happens to define — the served profile's own value has no way in (#114209). Reads the
  143. bound scope alone: never ``os.environ``, never another profile. Empty without a scope, so
  144. single-profile spawns are byte-identical."""
  145. from agent.secret_scope import _is_global_env, current_secret_scope
  146. scope = current_secret_scope()
  147. if not scope:
  148. return {}
  149. present = set(present)
  150. additions: dict[str, str] = {}
  151. for name in get_all_passthrough():
  152. if name in present or _is_global_env(name):
  153. continue
  154. value = scope.get(name)
  155. if value is not None:
  156. additions[name] = value
  157. return additions
  158. def clear_env_passthrough() -> None:
  159. """Reset the skill-registered allowlist (e.g. on session reset).
  160. Clears the process-wide set; a later ``skill_view`` re-registers its
  161. vars on demand, so recovery is a single skill load."""
  162. _get_allowed().clear()