vault_backend_registry.py 4.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """Profile-scoped browser-vault login backends registered by trusted in-process plugins.
  2. Registration (``ctx.register_login_backend``) is refused for: a name that is not a lowercase
  3. identifier, a handle prefix other than ``<name>:``, a name or prefix in a built-in backend's namespace,
  4. a name another plugin already holds in this profile, a backend that wants Hermes' master-password
  5. prompt (``needs_unlock``), and ``name``/``prefix`` computed by a descriptor or an attribute-access hook
  6. (they could change after validation, and reading them would run plugin code; :func:`static_name` judges
  7. them before anything reads them). ``enabled_plugin_backends`` re-checks every stored key and wraps each backend in
  8. :class:`agent.vault_backends.plugin.PluginLoginBackend`, the only form the vault tool ever sees.
  9. """
  10. import inspect
  11. import logging
  12. import re
  13. from agent.provider_registry import ProviderRegistry
  14. from agent.vault_backends.base import LoginBackend
  15. _registry = ProviderRegistry(label="Login backend", provider_cls=LoginBackend,
  16. logger=logging.getLogger(__name__))
  17. _registry.export(globals())
  18. _NAME = re.compile(r"[a-z][a-z0-9_]*")
  19. def _builtin_namespaces() -> tuple[set[str], tuple[str, ...]]:
  20. from agent.vault_backends.base import external_backend_classes
  21. from agent.vault_backends.local import LocalLoginBackend
  22. classes = (LocalLoginBackend, *external_backend_classes())
  23. names = {cls.name for cls in classes} | {cls.prefix.rstrip(":_") for cls in classes}
  24. return names, tuple(cls.prefix for cls in classes)
  25. def _namespace_error(name) -> str:
  26. """Why ``name`` cannot be a plugin backend's namespace, or "" when it can."""
  27. if not isinstance(name, str) or not _NAME.fullmatch(name):
  28. return "login backend name must be a lowercase identifier"
  29. names, prefixes = _builtin_namespaces()
  30. if name in names or f"{name}:".startswith(prefixes):
  31. return "builtin login backend namespace is reserved"
  32. return ""
  33. def static_name(provider) -> str:
  34. """The backend's name, judged without running plugin code (``ValueError`` with a fixed message when refused).
  35. Registration reads ``provider.name``; a property, a ``__getattribute__`` hook or a ``__class__`` override
  36. would run the plugin's code there, outside any guard, and its exception text would reach the loader log.
  37. """
  38. cls = type(provider)
  39. if not issubclass(cls, LoginBackend):
  40. raise ValueError("login backend must subclass LoginBackend")
  41. if cls.__getattribute__ is not object.__getattribute__ or any("__class__" in vars(k) for k in cls.__mro__[:-1]):
  42. raise ValueError("login backend must not override attribute access")
  43. name, prefix = inspect.getattr_static(provider, "name", None), inspect.getattr_static(provider, "prefix", None)
  44. if type(name) is not str or type(prefix) is not str:
  45. raise ValueError("login backend name and prefix must be plain string attributes")
  46. error = _namespace_error(name) or ("" if prefix == f"{name}:" else "login backend prefix must be '<name>:'")
  47. if error:
  48. raise ValueError(error)
  49. if inspect.getattr_static(provider, "needs_unlock", False) is not False:
  50. raise ValueError("plugin login backends cannot use the Hermes master-password prompt (needs_unlock)")
  51. return name
  52. def register_provider(provider, *, scope=None):
  53. name = static_name(provider)
  54. if name in _registry.merged(scope):
  55. raise ValueError(f"login backend name {name!r} is already registered")
  56. _registry.register(provider, scope=scope)
  57. def enabled_plugin_backends(cfg: dict) -> list[LoginBackend]:
  58. """Registered backends the profile turned on with ``vault.<name>.enabled: true``, wrapped."""
  59. from agent.vault_backends.plugin import PluginLoginBackend
  60. out: list[LoginBackend] = []
  61. for name, provider in sorted(_registry.merged().items()):
  62. section = cfg.get(name)
  63. if not _namespace_error(name) and isinstance(section, dict) and section.get("enabled") is True:
  64. out.append(PluginLoginBackend(name, provider))
  65. return out