plugin.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """Core-owned wrapper around a plugin-registered login backend.
  2. Every plugin backend reaches the browser vault only through ``PluginLoginBackend``, so the isolation
  3. rules hold however the plugin implements ``LoginBackend``:
  4. - Its namespace is ``<registered name>:``, taken from the registry key, never from attributes the plugin
  5. can change later. Ownership is decided here, so a plugin's own ``owns()`` is never consulted and it
  6. is never handed a handle outside its namespace (built-in ``vault_``/``op:``/``bw:`` or another plugin's).
  7. - It is handed the handle and nothing else: no page, CDP session, task id, other entries or master
  8. password. ``needs_unlock`` is always False, so Hermes' master-password prompt never runs for it.
  9. - Its exceptions are replaced by a fixed-text ``PluginBackendError`` raised outside the ``except``, so a
  10. secret in a plugin's error text reaches no tool result, log line or exception chain. Returned values
  11. are validated and copied into core-owned objects inside the same guard: reading a field of a
  12. plugin-owned object (a property, ``__getattribute__``, a ``str`` subclass) can run plugin code too.
  13. """
  14. from __future__ import annotations
  15. from contextlib import contextmanager
  16. from typing import Any, Callable, Optional
  17. from agent.vault_backends.base import LoginBackend
  18. from agent.vault_store import VAULT_KINDS, VaultItemMeta
  19. _FAILED = object()
  20. _INVALID = object()
  21. _TEXT_FIELDS = ("id", "kind", "label", "created_at")
  22. _OPTIONAL_TEXT_FIELDS = ("origin", "identifier", "identifier_type")
  23. def _text(value: Any) -> Any:
  24. """An exact ``str`` copy (a subclass's methods never run outside the guard), or ``_INVALID``."""
  25. return str.__str__(value) if isinstance(value, str) else _INVALID
  26. def _materialize(meta: Any) -> Any:
  27. """A core-owned ``VaultItemMeta`` copied from the plugin's, or ``_INVALID`` when a field has the wrong type."""
  28. if not isinstance(meta, VaultItemMeta):
  29. return _INVALID
  30. fields = {f: _text(getattr(meta, f)) for f in _TEXT_FIELDS}
  31. for f in _OPTIONAL_TEXT_FIELDS:
  32. value = getattr(meta, f)
  33. fields[f] = None if value is None else _text(value)
  34. has_otp, origins = meta.has_otp, meta.allowed_origins
  35. if not isinstance(origins, tuple) or type(has_otp) is not bool:
  36. return _INVALID
  37. fields["allowed_origins"] = tuple(_text(o) for o in origins)
  38. if _INVALID in fields.values() or _INVALID in fields["allowed_origins"] or fields["kind"] not in VAULT_KINDS:
  39. return _INVALID
  40. return VaultItemMeta(has_otp=has_otp, **fields)
  41. class PluginBackendError(RuntimeError):
  42. """A plugin login backend failed or broke its contract (fixed text: never the plugin's own message)."""
  43. class PluginLoginBackend(LoginBackend):
  44. needs_unlock = False
  45. def __init__(self, name: str, plugin: LoginBackend):
  46. self.name, self.prefix, self._plugin = name, f"{name}:", plugin
  47. self.display_name = f"{name} (plugin)" # core-composed: a plugin cannot present itself as a built-in manager
  48. def owns(self, handle: str) -> bool:
  49. return isinstance(handle, str) and handle.startswith(self.prefix)
  50. def _call(self, fn: Callable[[], Any]) -> Any:
  51. try:
  52. result = fn()
  53. except Exception: # health: allow BLE001 -- the plugin's error text may hold a credential; replaced below
  54. result = _FAILED
  55. if result is _FAILED:
  56. raise PluginBackendError(f"The {self.name} login backend failed.")
  57. return result
  58. def _require_own(self, handle: str) -> None:
  59. if not self.owns(handle):
  60. raise PluginBackendError(f"Handle is outside the {self.name} login backend's namespace.")
  61. def _require(self, ok: bool) -> None:
  62. if not ok:
  63. raise PluginBackendError(f"The {self.name} login backend returned an invalid value.")
  64. def list_items(self) -> list[VaultItemMeta]:
  65. items = self._call(lambda: [_materialize(m) for m in self._plugin.list_items()])
  66. self._require(all(m is not _INVALID for m in items))
  67. return [m for m in items if self.owns(m.id)]
  68. def get_meta(self, handle: str) -> Optional[VaultItemMeta]:
  69. if not self.owns(handle):
  70. return None
  71. def fetch() -> Any:
  72. meta = self._plugin.get_meta(handle)
  73. return None if meta is None else _materialize(meta)
  74. meta = self._call(fetch)
  75. self._require(meta is not _INVALID)
  76. return meta if meta is not None and meta.id == handle else None
  77. def resolve_password(self, handle: str) -> str:
  78. self._require_own(handle)
  79. value = self._call(lambda: _text(self._plugin.resolve_password(handle)))
  80. self._require(value is not _INVALID)
  81. return value
  82. def resolve_otp(self, handle: str) -> Optional[str]:
  83. self._require_own(handle)
  84. def fetch() -> Any:
  85. value = self._plugin.resolve_otp(handle)
  86. return None if value is None else _text(value)
  87. value = self._call(fetch)
  88. self._require(value is not _INVALID)
  89. return value
  90. def resolve_secret(self, handle: str) -> dict[str, str]:
  91. self._require_own(handle)
  92. def fetch() -> Any:
  93. value = self._plugin.resolve_secret(handle)
  94. if not isinstance(value, dict):
  95. return _INVALID
  96. copied = {_text(k): _text(v) for k, v in value.items()}
  97. return _INVALID if _INVALID in copied or _INVALID in copied.values() else copied
  98. value = self._call(fetch)
  99. self._require(value is not _INVALID)
  100. return value
  101. @contextmanager
  102. def fill_context(self):
  103. """The plugin's own context around one of ITS fills; it never sees the core's exception."""
  104. context = self._call(lambda: self._plugin.fill_context())
  105. self._call(lambda: context.__enter__())
  106. try:
  107. yield
  108. finally:
  109. self._call(lambda: context.__exit__(None, None, None))