The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(vault): check the page origin before entering a backend's fill_context
Teknium850efff14f0d
diff --git a/agent/vault_backends/base.py b/agent/vault_backends/base.pyindex 7dc813b8d4d..a6480bc7439 100644--- a/agent/vault_backends/base.py+++ b/agent/vault_backends/base.py@@ -39,7 +39,8 @@ class LoginBackend(ABC):return Truedef fill_context(self) -> AbstractContextManager:- """Optional profile-exclusive context covering origin check through CDP fill."""+ """Optional profile-exclusive context, entered after the origin pre-check: covers the in-context+ metadata re-check, secret resolution and the CDP write."""return nullcontext()@abstractmethoddiff --git a/tests/tools/test_browser_vault.py b/tests/tools/test_browser_vault.pyindex 09319d84cf0..99e94298889 100644--- a/tests/tools/test_browser_vault.py+++ b/tests/tools/test_browser_vault.py@@ -18,6 +18,7 @@ import reimport osimport statimport sys+from contextlib import nullcontextfrom pathlib import Pathfrom unittest.mock import patch@@ -323,6 +324,9 @@ class TestBrowserVaultTools:def get_meta(self, handle):return meta if handle == meta.id else None+ def fill_context(self):+ return nullcontext()+def resolve_password(self, handle):return "s3cret-pw"diff --git a/tests/tools/test_browser_vault_plugin_isolation.py b/tests/tools/test_browser_vault_plugin_isolation.pyindex a736a075d99..8404f9c12d4 100644--- a/tests/tools/test_browser_vault_plugin_isolation.py+++ b/tests/tools/test_browser_vault_plugin_isolation.py@@ -8,7 +8,8 @@ browser's CDP boundary (page origin, input inspection, the secret eval) is faked1. a plugin backend only ever sees handles in its own ``<name>:`` namespace;2. it receives the handle and nothing else: no fill-context arguments, no master password;3. built-in names and handle prefixes are reserved, and a backend name cannot be taken over;-4. it is off until ``vault.<name>.enabled: true``, refused in the plugin host, and origin-checked;+4. it is off until ``vault.<name>.enabled: true``, refused in the plugin host, and origin-checked before+ its ``fill_context`` is entered (fill and one-time code alike), then again inside it;5. its secret values never reach a tool result (the transcript) or the logs, and are redacted."""@@ -238,9 +239,10 @@ def test_plugin_backend_gets_only_its_handle_never_unlock_material(vault_home, palpha.calls.clear()out = json.loads(_vault({"action": "fill", "handle": "alpha:1"}))assert out["success"] is True and out["backend"] == "alpha"- assert [c[0] for c in alpha.calls] == ["fill_context", "get_meta", "resolve_password"]- assert alpha.calls[0] == ("fill_context", (), {})- assert all(c[1:] == ("alpha:1", (), {}) for c in alpha.calls[1:])+ # metadata + origin guard, then the context, the in-context re-read, and only then the secret+ assert [c[0] for c in alpha.calls] == ["get_meta", "fill_context", "get_meta", "resolve_password"]+ assert alpha.calls[1] == ("fill_context", (), {})+ assert all(c[1:] == ("alpha:1", (), {}) for c in alpha.calls if c[0] != "fill_context")# A plugin may not drive Hermes' master-password prompt: the user would be typing a password# into a dialog the plugin labelled (here "1Password").@@ -323,7 +325,7 @@ def test_plugin_backend_is_off_until_enabled_refused_in_host_and_origin_checked(page.origin = "https://evil.example"out = json.loads(_vault({"action": "fill", "handle": "alpha:1"}))assert out["error_type"] == "origin_mismatch"- assert "resolve_password" not in [c[0] for c in alpha.calls]+ assert [c[0] for c in alpha.calls] == ["get_meta"] # refused before fill_context, before any secretpage.origin = ORIGINassert json.loads(_vault({"action": "fill", "handle": "alpha:1"}))["success"] is Trueassert len(page.secret_evals) == 1 and json.dumps(ORIGIN) in page.secret_evals[0]@@ -376,7 +378,7 @@ class Backend(LoginBackend):name, prefix, display_name = "ctxvault", "ctxvault:", "Ctx"def __init__(self):- self.calls, self.active = [], False+ self.calls, self.active, self.moved = [], False, False@contextlib.contextmanagerdef fill_context(self):@@ -392,10 +394,13 @@ class Backend(LoginBackend):return [self.get_meta("ctxvault:1")]def get_meta(self, handle):- return VaultItemMeta(id=handle, kind="login", label="Ctx", origin="https://example.com",+ # ``moved``: the manager's entry was re-bound to another site; the frozen snapshot shows it.+ origin = "https://moved.example" if self.active and self.moved else "https://example.com"+ return VaultItemMeta(id=handle, kind="login", label="Ctx", origin=origin,created_at="2026-01-01T00:00:00Z", has_otp=True)def resolve_password(self, handle):+ self.calls.append("resolve_password")return "unused"def resolve_otp(self, handle):@@ -430,6 +435,44 @@ def test_plugin_otp_is_minted_and_written_inside_the_backends_fill_context(vaultassert code in page.secret_evals[0] and code not in json.dumps(out)+def _ctx_backend(vault_home, page, monkeypatch, code="739251"):+ from tools import browser_vault_tool++ home, _local, load = vault_home+ _write_plugin(home, "ctx_vault", _CONTEXT_BACKEND.format(code=code), " ctx.register_login_backend(Backend())\n")+ load(["ctx_vault"], {"ctxvault": "true"})+ otp_field = {"autocomplete": "one-time-code", "formIndex": 0, "index": 0, "label": "", "name": "otp", "type": "text"}+ monkeypatch.setattr(browser_vault_tool, "_eval_js",+ lambda task_id, expr: {"success": True, "result": json.dumps(_CONTROLS + [otp_field])})+ return _backend("ctxvault")+++def test_plugin_otp_on_a_foreign_origin_is_refused_before_fill_context(vault_home, page, monkeypatch):+ from agent.vault_backends import unlock as unlock_mod++ backend = _ctx_backend(vault_home, page, monkeypatch)+ page.origin = "https://evil.example"+ asked = []+ unlock_mod.set_code_prompt_callback(lambda site, hint: asked.append(site) or "000000")+ try:+ out = json.loads(_vault({"action": "enter_code", "handle": "ctxvault:1"}))+ finally:+ unlock_mod.set_code_prompt_callback(None)+ assert out["error_type"] == "origin_mismatch", out+ assert backend.calls == [] and page.secret_evals == [] and asked == []+++def test_an_item_rebound_inside_fill_context_is_refused_before_its_secret(vault_home, page, monkeypatch):+ backend = _ctx_backend(vault_home, page, monkeypatch)+ backend.moved = True+ for args in ({"action": "fill", "handle": "ctxvault:1"}, {"action": "enter_code", "handle": "ctxvault:1"}):+ backend.calls.clear()+ out = json.loads(_vault(args))+ assert out["error_type"] == "origin_mismatch", (args, out)+ assert backend.calls == ["enter", "exit"], (args, backend.calls)+ assert page.secret_evals == []++_LAZY_META_BACKEND = '''from agent.vault_backends.base import LoginBackendfrom agent.vault_store import VaultItemMetadiff --git a/tools/browser_vault_context.py b/tools/browser_vault_context.pyindex 095c7698e75..c676a1e3cf4 100644--- a/tools/browser_vault_context.py+++ b/tools/browser_vault_context.py@@ -1,38 +1,65 @@"""Run a vault fill, or an automatic one-time-code entry, inside the selected backend's ``fill_context``(a plugin backend's lock/snapshot/manager session).+Order, for every backend: the item's metadata is read and the page origin checked against it+(``_bound_page_origin``) BEFORE the context is entered, so a page on the wrong origin never opens a+backend's manager session or lock. Inside the context a backend with its own ``fill_context`` has the+item re-read, so the origins checked and the secret resolved come from one snapshot.+A plugin backend's failure arrives as ``PluginBackendError`` (fixed text, see``agent/vault_backends/plugin.py``) and becomes a typed refusal; built-in backends behave as before."""import json-from contextlib import nullcontextfrom functools import wraps-def with_backend_fill_context(fill):- @wraps(fill)- def wrapped(handle, task_id=None):- from agent.vault_backends import backend_for_handle+def plugin_errors_as_refusal(fn):+ """A ``PluginBackendError`` raised anywhere in ``fn`` (metadata read, context enter/exit, resolve)+ becomes the ``backend_unavailable`` refusal."""+ @wraps(fn)+ def wrapped(*args, **kwargs):from agent.vault_backends.plugin import PluginBackendError- backend = backend_for_handle(handle)- context = backend.fill_context() if backend is not None and hasattr(backend, "fill_context") else nullcontext()try:- with context:- return fill(handle, task_id, _backend=backend)+ return fn(*args, **kwargs)except PluginBackendError as exc:return json.dumps({"success": False, "error_type": "backend_unavailable", "error": str(exc)})return wrapped-def write_backend_code(backend, handle, write):+def saved_origins(meta) -> list[str]:+ """The exact origins a vault item may be filled on (several for manager items)."""+ return list(meta.allowed_origins) or ([str(meta.origin)] if meta.origin else [])+++def snapshot_refusal(backend, handle, meta, page_origin):+ """Inside ``fill_context``: ``None`` when the item still binds ``page_origin``, else the refusal.+ Only a backend with its own context is re-read (the built-in managers' metadata read is a full+ listing, and their default context freezes nothing)."""+ from agent.vault_backends.base import LoginBackend++ if type(backend).fill_context is LoginBackend.fill_context:+ return None+ fresh = backend.get_meta(handle)+ if fresh is not None and fresh.kind == meta.kind and page_origin in saved_origins(fresh):+ return None+ return {"success": False, "error_type": "origin_mismatch",+ "error": (f"Refused: the saved item changed before the fill and no longer binds {page_origin}. "+ "Nothing was resolved or written.")}+++def write_backend_code(backend, handle, meta, origin, write):"""Mint the backend's one-time code for ``handle`` and ``write`` it, both inside ``fill_context``, as a- password fill is. ``None`` when the backend has no code (or failed to give one): the caller asks the user."""+ password fill is. The caller has already checked ``origin`` against ``meta``. ``None`` when the backend+ has no code (or failed to give one): the caller asks the user."""from agent.vault_backends.plugin import PluginBackendErrorwritten = Nonetry:with backend.fill_context():+ refusal = snapshot_refusal(backend, handle, meta, origin)+ if refusal is not None:+ return json.dumps(refusal)try:code = backend.resolve_otp(handle)except Exception: # health: allow BLE001 -- no automatic code; the user is asked insteaddiff --git a/tools/browser_vault_tool.py b/tools/browser_vault_tool.pyindex c2ab5f0685d..547abbcb2b5 100644--- a/tools/browser_vault_tool.py+++ b/tools/browser_vault_tool.py@@ -33,6 +33,8 @@ import secretsimport loggingfrom typing import Any, Dict, Optional+from tools.browser_vault_context import plugin_errors_as_refusal, saved_origins, snapshot_refusal, write_backend_code+logger = logging.getLogger(__name__)@@ -191,7 +193,7 @@ def _bound_page_origin(task_id: str, meta: Any, probe_kind: str) -> str | dict[selse the refusal to return. Manager items may bind several websites; matching is exact andnothing wildcard or parent-domain is inferred. The caller hands the returned origin to ``build_fill_js``,which re-asserts it inside the page immediately before the write (navigation between check and fill)."""- allowed = list(meta.allowed_origins) or ([str(meta.origin)] if meta.origin else [])+ allowed = saved_origins(meta)if not allowed:return {"success": False, "error_type": "no_origin","error": f"Vault item {meta.id!r} has no bound origin; {meta.kind} items are filled only on "@@ -342,6 +344,7 @@ def _saved_login(handle: str) -> tuple[Any, Any]:return backend, None+@plugin_errors_as_refusaldef browser_vault_enter_code(handle: str = "", task_id: Optional[str] = None) -> str:"""Second factor: fill the one-time code the CURRENT page asks for. If the saved login (``handle``) has anauthenticator seed, the code is minted server-side and nobody is asked; otherwise the user is prompted on@@ -396,7 +399,7 @@ def browser_vault_enter_code(handle: str = "", task_id: Optional[str] = None) ->"next": "Submit the form (many sites auto-submit when the last digit lands)."})if meta is not None: # a saved login on its bound origin: mint + write inside the backend's fill_context- written = write_backend_code(backend, handle, lambda code: write(code, backend.name))+ written = write_backend_code(backend, handle, meta, origin, lambda code: write(code, backend.name))if written is not None:return writtenprompt = get_code_prompt_callback()@@ -411,11 +414,8 @@ def browser_vault_enter_code(handle: str = "", task_id: Optional[str] = None) ->return write(code, "user")-from tools.browser_vault_context import with_backend_fill_context, write_backend_code---@with_backend_fill_context-def browser_vault_fill(handle: str, task_id: Optional[str] = None, *, _backend=None) -> str:+@plugin_errors_as_refusal+def browser_vault_fill(handle: str, task_id: Optional[str] = None) -> str:"""Fill the current page's password field from a vault handle.Password-only: the identifier is agent-visible metadata (see@@ -423,22 +423,10 @@ def browser_vault_fill(handle: str, task_id: Optional[str] = None, *, _backend=NThe password is resolved server-side and injected via in-page JS overthe supervisor CDP WebSocket; the result reports only counts/metadata."""- from agent.redact import register_vault_redaction_value- from agent.vault_login_classifier import (- ClassifiedLoginControl,- LoginControl,- build_fill_js,- build_inspection_js,- classify_checkout_control,- classify_login_control,- select_checkout_fills,- select_password_fill,- )from agent.vault_backends import UnlockRequired, backend_for_handle- from agent.vault_store import ADDRESS_FIELDS, PAYMENT_FIELDS, scrub_secret_from_texteffective_task_id = task_id or "default"- backend = _backend+ backend = backend_for_handle(handle)if backend is not None and backend.needs_unlock and not backend.is_unlocked():unlocked = json.loads(browser_vault_unlock(backend.name))if not unlocked.get("success"):@@ -461,7 +449,7 @@ def browser_vault_fill(handle: str, task_id: Optional[str] = None, *, _backend=N})# Origin binding pre-check (the authoritative re-check runs inside the fill script), before the user is- # asked to confirm a card and before any value is resolved.+ # asked to confirm a card, before the backend's fill_context is entered and before any value is resolved.page_origin = _bound_page_origin(effective_task_id, meta, meta.kind)if isinstance(page_origin, dict):return json.dumps(page_origin)@@ -469,6 +457,30 @@ def browser_vault_fill(handle: str, task_id: Optional[str] = None, *, _backend=Nreturn json.dumps({"success": False, "error_type": "payment_declined","error": "The user did not confirm filling this payment card. Do not retry; ask them instead."})+ with backend.fill_context():+ refusal = snapshot_refusal(backend, handle, meta, page_origin)+ if refusal is not None:+ return json.dumps(refusal)+ return _fill_bound_page(backend, handle, meta, page_origin, effective_task_id)+++def _fill_bound_page(backend: Any, handle: str, meta: Any, page_origin: str, effective_task_id: str) -> str:+ """Inspect the page, resolve the item's secret and write it; runs inside the backend's fill_context+ after the origin guard passed."""+ from agent.redact import register_vault_redaction_value+ from agent.vault_login_classifier import (+ ClassifiedLoginControl,+ LoginControl,+ build_fill_js,+ build_inspection_js,+ classify_checkout_control,+ classify_login_control,+ select_checkout_fills,+ select_password_fill,+ )+ from agent.vault_backends import UnlockRequired+ from agent.vault_store import ADDRESS_FIELDS, PAYMENT_FIELDS, scrub_secret_from_text+# ── Inspect + classify page controls ────────────────────────────────────nonce = secrets.token_hex(8) # binds this fill to THIS inspection's stampsinspect = _eval_js(effective_task_id, build_inspection_js(nonce))@@ -520,8 +532,7 @@ def browser_vault_fill(handle: str, task_id: Optional[str] = None, *, _backend=Nfill_result = _eval_js_secret(effective_task_id, build_fill_js(fills, expected_origin=page_origin, nonce=nonce))- except Exception as exc:- # Strip any secret material from exception text before surfacing.+ except Exception as exc: # health: allow BLE001 -- any CDP failure becomes a typed result; its text is scrubbed of the secretreturn json.dumps({"success": False, "error": scrub_secret_from_text(str(exc), secret)})diff --git a/website/docs/developer-guide/browser-vault-plugin.md b/website/docs/developer-guide/browser-vault-plugin.mdindex eea47c78a8a..b538b352e12 100644--- a/website/docs/developer-guide/browser-vault-plugin.md+++ b/website/docs/developer-guide/browser-vault-plugin.md@@ -86,7 +86,7 @@ hold however the plugin implements its class:| **Reserved namespaces** | The names `local`, `onepassword`, `bitwarden`, `vault`, `op` and `bw`, and any prefix inside a built-in prefix (`vault_x:`), are refused. So is a name another plugin already holds in the profile: no backend, built-in or plugin, can be replaced or shadowed. `name` and `prefix` must be plain string attributes, not properties, and the class may not override `__getattribute__` or `__class__`: Hermes judges the registration without running your code. || **Off by default** | Only `vault.<name>.enabled: true` turns a backend on. || **In-process only** | `ctx.register_login_backend` is refused under `plugins.isolation: host`, because `fill_context()` is a server-local context manager. |-| **Same fill path** | Plugin items go through the same exact-origin pre-check, in-page origin re-assertion, supervisor CDP secret evaluation (never argv) and payment confirmation as built-in items. |+| **Same fill path** | Plugin items (passwords and automatic one-time codes) go through the same exact-origin pre-check, in-page origin re-assertion, supervisor CDP secret evaluation (never argv) and payment confirmation as built-in items. || **Secrets stay out of the conversation** | Values you return are registered with the browser-result redaction boundary before they reach the page. Any exception your backend raises is replaced by a fixed message (`The <name> login backend failed.`) before it can reach a tool result, a log line or an exception chain, so a secret in your error text cannot reach the model. A value of the wrong type is refused the same way. Hermes copies what you return (metadata fields, passwords, codes) into its own plain objects inside that same guard, so an error raised while a field is read gets the fixed message too. |An in-process plugin is ordinary Python running inside Hermes, so these rules are an API contract,@@ -100,9 +100,12 @@ plugins Hermes offers this seam to; it is not a sandbox either.freeze credential-reference/origin configuration for the whole operation, so a reload cannot pair oldmetadata with a newly configured secret. Hermes enters it only for fills of your own handles (apassword fill, and an automatic one-time code for `browser_vault action=enter_code`, both through the-in-page write), calls it-with no arguments, and exits it with `(None, None, None)`, so you never see the core's exception. Release-on exit even when the fill failed. A fill lock does not serialize unrelated browser navigation.+in-page write), and only after the page origin matched your item's `get_meta()`: a page on another+origin never opens your context. Inside the context Hermes calls `get_meta()` again and refuses the+fill unless the frozen item still binds that page origin, so the origins checked and the secret+resolved come from one snapshot. It calls `fill_context()` with no arguments and exits it with+`(None, None, None)`, so you never see the core's exception. Release on exit even when the fill+failed. A fill lock does not serialize unrelated browser navigation.## Writing errors