plugin_capabilities.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """Plugin capability declarations + consent state.
  2. Every capability id maps 1:1 to a trust gate that already exists on the enforcing surface; ids
  3. without an enforcing gate are deliberately never minted.
  4. """
  5. from __future__ import annotations
  6. import hashlib
  7. import logging
  8. from dataclasses import dataclass
  9. from datetime import datetime, timezone, UTC
  10. from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
  11. logger = logging.getLogger(__name__)
  12. @dataclass(frozen=True)
  13. class CapabilitySpec:
  14. """One declarable capability and the legacy gate it maps to."""
  15. id: str
  16. # Deprecated boolean under plugins.entries.<id>, e.g. ("llm", "allow_model_override"); empty for a
  17. # capability born after the consent flow, whose only gate is declare + consent.
  18. legacy_path: tuple[str, ...]
  19. description: str # one-line risk description shown on the consent screen
  20. # (id, legacy_path, description) — ONLY capabilities with an existing enforcing surface.
  21. _CAPABILITY_ROWS = (
  22. ("tools.override", ("allow_tool_override",),
  23. "Replace built-in tools (e.g. shell_exec, write_file) — an "
  24. "override can intercept everything routed through that tool"),
  25. ("llm.provider_override", ("llm", "allow_provider_override"),
  26. "Run host-owned LLM calls against a provider other than your "
  27. "active one (uses your credentials)"),
  28. ("llm.model_override", ("llm", "allow_model_override"),
  29. "Choose which model host-owned LLM calls use (spend follows "
  30. "the chosen model)"),
  31. ("llm.agent_id_override", ("llm", "allow_agent_id_override"),
  32. "Attribute its LLM calls to a different agent id"),
  33. ("llm.profile_override", ("llm", "allow_profile_override"),
  34. "Run LLM calls under a different auth profile"),
  35. ("llm.task_override", ("llm", "allow_task_override"),
  36. "Route its LLM calls through the host's built-in auxiliary "
  37. "task lanes"),
  38. ("llm.side_question", (),
  39. "Ask your agent a short question after each turn. It sees the "
  40. "whole session, including memory, and spends your main model's tokens."),
  41. ("gateway.platform_actions", ("allow_platform_actions",),
  42. "Act on connected chat platforms as the gateway bot "
  43. "(add reactions, rename threads) via ctx.platform_actions"))
  44. CAPABILITY_REGISTRY: dict[str, CapabilitySpec] = {
  45. cid: CapabilitySpec(cid, path, desc) for cid, path, desc in _CAPABILITY_ROWS
  46. }
  47. VALID_CAPABILITY_IDS = frozenset(CAPABILITY_REGISTRY)
  48. # Config keys under ``plugins.entries.<plugin_id>``.
  49. GRANTED_KEY = "granted_capabilities"
  50. CONSENT_KEY = "capabilities_consent"
  51. def parse_declared_capabilities(raw: Any, plugin_name: str = "?") -> list[str]:
  52. """Normalize a manifest ``capabilities:`` value into known capability ids.
  53. Unknown ids are dropped with a warning: they can never be granted by this build, so hiding
  54. them from the consent screen is the fail-closed choice (the plugin must degrade gracefully).
  55. """
  56. if not raw:
  57. return []
  58. if not isinstance(raw, (list, tuple)):
  59. logger.warning(
  60. "Plugin %s: manifest 'capabilities' must be a list, got %s — ignoring",
  61. plugin_name, type(raw).__name__)
  62. return []
  63. out: list[str] = []
  64. for item in raw:
  65. if not isinstance(item, str):
  66. logger.warning("Plugin %s: ignoring non-string capability entry %r", plugin_name, item)
  67. continue
  68. cap = item.strip()
  69. if cap not in VALID_CAPABILITY_IDS:
  70. logger.warning(
  71. "Plugin %s: unknown capability %r (known: %s) — ignoring",
  72. plugin_name, cap, ", ".join(sorted(VALID_CAPABILITY_IDS)))
  73. elif cap not in out:
  74. out.append(cap)
  75. return out
  76. def _known(capabilities: Iterable[str]) -> list[str]:
  77. """Deduplicated (order-preserving) subset of *capabilities* with a registry entry."""
  78. return [c for c in dict.fromkeys(capabilities) if c in VALID_CAPABILITY_IDS]
  79. def capability_set_hash(capabilities: Iterable[str]) -> str:
  80. """Deterministic sha256 over a capability set (order-insensitive)."""
  81. canon = "\n".join(sorted(set(capabilities)))
  82. return hashlib.sha256(canon.encode("utf-8")).hexdigest()
  83. # ── Consent state (read side — fail closed on ANY error) ────────────────────────────────────
  84. def _plugin_entry(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> dict:
  85. """``plugins.entries.<plugin_id>`` or ``{}`` — never raises (unreadable state = not granted)."""
  86. try:
  87. cfg: Any = config
  88. if cfg is None:
  89. from hermes_cli.config import load_config
  90. cfg = load_config() or {}
  91. entry = ((cfg.get("plugins") or {}).get("entries") or {}).get(plugin_id) or {}
  92. return entry if isinstance(entry, dict) else {}
  93. except Exception:
  94. return {}
  95. def granted_capabilities(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> frozenset:
  96. """The set of capabilities the user has granted this plugin."""
  97. raw = _plugin_entry(plugin_id, config).get(GRANTED_KEY)
  98. if not isinstance(raw, list):
  99. return frozenset()
  100. return frozenset(_known(c.strip() for c in raw if isinstance(c, str)))
  101. def _legacy_gate_set(entry: Mapping[str, Any], spec: CapabilitySpec) -> bool:
  102. """True when the deprecated ``allow_*`` key for *spec* is truthy (never for a consent-only one)."""
  103. if not spec.legacy_path:
  104. return False
  105. node: Any = entry
  106. for part in spec.legacy_path:
  107. if not isinstance(node, Mapping):
  108. return False
  109. node = node.get(part)
  110. return bool(node)
  111. def plugin_capability_granted(plugin_id: str, capability: str, config: Optional[Mapping[str, Any]] = None) -> bool:
  112. """Canonical check: is *capability* live for *plugin_id*? True via ``granted_capabilities`` OR
  113. the deprecated-but-honored legacy ``allow_*`` key. Unknown ids / unreadable state -> False."""
  114. spec = CAPABILITY_REGISTRY.get(capability)
  115. if spec is None:
  116. logger.debug("capability check for unknown id %r (plugin %s) — denied", capability, plugin_id)
  117. return False
  118. entry = _plugin_entry(plugin_id, config)
  119. if capability in granted_capabilities(plugin_id, config={"plugins": {"entries": {plugin_id: entry}}}):
  120. allowed, evidence = True, "granted_capabilities"
  121. elif _legacy_gate_set(entry, spec):
  122. allowed, evidence = True, f"legacy key plugins.entries.{plugin_id}.{'.'.join(spec.legacy_path)} (deprecated)"
  123. else:
  124. allowed, evidence = False, "not granted"
  125. logger.info( # audit trail for capability gate decisions
  126. "capability_check plugin=%s capability=%s decision=%s checked_by=plugin_capability_granted evidence=%s",
  127. plugin_id, capability, "allow" if allowed else "deny", evidence)
  128. return allowed
  129. # ── Consent state (write side) ──────────────────────────────────────────────────────────────
  130. def _child_dict(parent: dict, key: str) -> dict:
  131. """``parent[key]`` as a dict, replacing any non-dict value in place."""
  132. child = parent.setdefault(key, {})
  133. if not isinstance(child, dict):
  134. child = {}
  135. parent[key] = child
  136. return child
  137. def record_consent(plugin_id: str, granted: Iterable[str], declared: Iterable[str]) -> None:
  138. """Persist a consent decision: ``granted_capabilities`` (union with prior grants), the consent
  139. record (hash of the declared set the user saw + UTC timestamp), and the legacy ``allow_*`` key
  140. for each grant so existing enforcement sites keep working unchanged."""
  141. from hermes_cli.config import load_config, save_config
  142. config = load_config()
  143. entry = _child_dict(_child_dict(_child_dict(config, "plugins"), "entries"), plugin_id)
  144. previous = entry.get(GRANTED_KEY)
  145. merged = (list(previous) if isinstance(previous, list) else []) + _known(granted)
  146. entry[GRANTED_KEY] = sorted(_known(c for c in merged if isinstance(c, str)))
  147. entry[CONSENT_KEY] = {
  148. "hash": capability_set_hash(_known(declared)),
  149. "granted_at": datetime.now(UTC).isoformat(timespec="seconds"),
  150. }
  151. # Bridge: mirror each grant into its legacy gate (enforcement sites still read allow_*).
  152. for cap in entry[GRANTED_KEY]:
  153. if not CAPABILITY_REGISTRY[cap].legacy_path:
  154. continue
  155. *parents, leaf = CAPABILITY_REGISTRY[cap].legacy_path
  156. node = entry
  157. for part in parents:
  158. node = _child_dict(node, part)
  159. node[leaf] = True
  160. save_config(config)
  161. logger.info(
  162. "capability_consent plugin=%s granted=%s declared_hash=%s", plugin_id,
  163. ",".join(entry[GRANTED_KEY]) or "(none)", entry[CONSENT_KEY]["hash"][:12])
  164. def consent_hash(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> Optional[str]:
  165. """Return the stored consent hash, or None when absent/corrupt."""
  166. consent = _plugin_entry(plugin_id, config).get(CONSENT_KEY)
  167. h = consent.get("hash") if isinstance(consent, dict) else None
  168. return h if isinstance(h, str) and h else None
  169. def pending_capabilities(
  170. plugin_id: str, declared: Iterable[str], config: Optional[Mapping[str, Any]] = None
  171. ) -> list[str]:
  172. """Declared-but-ungranted capabilities: everything at first consent, only the additions on an
  173. update re-consent (they must be re-consented before going live)."""
  174. granted = granted_capabilities(plugin_id, config)
  175. return [c for c in _known(declared) if c not in granted]
  176. def declared_set_changed(
  177. plugin_id: str, declared: Iterable[str], config: Optional[Mapping[str, Any]] = None
  178. ) -> bool:
  179. """True when the declared set differs from what the user consented to (or never consented)."""
  180. stored = consent_hash(plugin_id, config)
  181. return stored is None or stored != capability_set_hash(_known(declared))