The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(vault): take the vault from the fill's own listing; surface service-account auth errors
Tekniumd7c4d49db996
diff --git a/agent/vault_backends/onepassword.py b/agent/vault_backends/onepassword.pyindex 400abf5e3ea..9e926eb0594 100644--- a/agent/vault_backends/onepassword.py+++ b/agent/vault_backends/onepassword.py@@ -4,8 +4,8 @@ Unlock: ``op signin --raw`` with the master password on stdin (desktop-appintegration or account-level auth) mints an ``OP_SESSION_<account>`` token.A configured service-account token skips the prompt entirely (headless).List: ``op item list --categories Login --format json`` → title, urls,-username. Resolve: ``op item get <id> --vault <vault-id> ...``, selecting the-item's vault from fresh listing metadata (required for service accounts).+username, vault. Resolve: ``op item get <id> --vault <vault-id> ...`` (service+accounts reject an item read without a vault query)."""from __future__ import annotations@@ -39,6 +39,7 @@ class OnePasswordLoginBackend(LoginBackend):from agent.secret_scope import get_secretenv_name = str(self.cfg.get("service_account_token_env") or "OP_SERVICE_ACCOUNT_TOKEN")self._service_token = get_secret(env_name, "") or ""+ self._item_vaults: dict[str, str] = {} # item id -> vault id from the latest ``item list``# ── auth ────────────────────────────────────────────────────────────────@@ -92,7 +93,9 @@ class OnePasswordLoginBackend(LoginBackend):timeout_message="op timed out", stdin=subprocess.DEVNULL)if proc.returncode != 0:err = _scrub(proc.stderr or "")- if "session" in err.lower() or "sign in" in err.lower() or "not signed in" in err.lower():+ # A service account never holds a session, so an auth failure there is not a lock to undo:+ # surface op's own error instead of an unlock prompt that reports "already unlocked".+ if not self._service_token and any(w in err.lower() for w in ("session", "sign in", "not signed in")):_unlock.lock(self.name)raise UnlockRequired(self)raise RuntimeError(f"op failed: {err[:200]}")@@ -104,7 +107,11 @@ class OnePasswordLoginBackend(LoginBackend):return []raw = json.loads(self._run("item", "list", "--categories", "Login", "--format", "json") or "[]")out: list[VaultItemMeta] = []+ self._item_vaults = {}for item in raw if isinstance(raw, list) else []:+ vault = item.get("vault") or {}+ if item.get("id"):+ self._item_vaults[str(item["id"])] = str(vault.get("id") or "") if isinstance(vault, dict) else ""urls = [str(u["href"]) for u in item.get("urls") or [] if isinstance(u, dict) and u.get("href")]origins = _all_origins(urls)if not origins:@@ -120,29 +127,17 @@ class OnePasswordLoginBackend(LoginBackend):def get_meta(self, handle: str) -> Optional[VaultItemMeta]:return next((m for m in self.list_items() if m.id == handle), None)- def _item_selector(self, handle: str) -> List[str]:- # Keep existing op:<item-id> handles valid, including across backend instances.- # Resolve from fresh metadata rather than caching a vault or guessing the first one.- if not handle.startswith(self.prefix):- raise ValueError("Invalid 1Password login handle")+ def _item_selector(self, handle: str) -> list[str]:+ """``op item get`` target for a listed login. A service account must name the item's vault+ (``--vault``) and ``item list`` reports it, so the vault comes from the same listing that+ proved the handle is a Login item; a handle nothing listed is refused before any secret read."""item_id = handle[len(self.prefix):]- if not item_id or not item_id[0].isalnum() or not all(- c.isascii() and (c.isalnum() or c == "-") for c in item_id- ):- raise ValueError("Invalid 1Password login handle")- raw = json.loads(self._run("item", "list", "--categories", "Login", "--format", "json") or "[]")- if not isinstance(raw, list):- raise RuntimeError("Invalid 1Password login metadata")- matches = [item for item in raw if isinstance(item, dict) and item.get("id") == item_id]- if len(matches) != 1:- raise RuntimeError("1Password login is missing or ambiguous; list logins again")- vault = matches[0].get("vault")- vault_id = vault.get("id") if isinstance(vault, dict) else None- if isinstance(vault_id, str) and vault_id:- return [item_id, "--vault", vault_id]- if self._service_token:- raise RuntimeError("1Password login metadata is missing its vault ID; list logins again")- return [item_id]+ if item_id not in self._item_vaults:+ self.list_items()+ if item_id not in self._item_vaults:+ raise RuntimeError("1Password login not found; list logins again")+ vault_id = self._item_vaults[item_id]+ return [item_id, "--vault", vault_id] if vault_id else [item_id]def resolve_password(self, handle: str) -> str:return self._run("item", "get", *self._item_selector(handle),diff --git a/tests/agent/test_vault_backends.py b/tests/agent/test_vault_backends.pyindex 844e3fd2aaf..213dc7269da 100644--- a/tests/agent/test_vault_backends.py+++ b/tests/agent/test_vault_backends.py@@ -129,7 +129,7 @@ def test_unlock_uses_vendor_passwordenv_contract_then_fill_routes_by_prefix(fakefinally:unlock_mod.set_unlock_prompt_callback(None)- calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]+ calls = [json.loads(line) for line in log.read_text(encoding="utf-8-sig").splitlines()]unlock_calls = [c for c in calls if c["argv"][:2] == ["unlock", "--raw"]]assert len(unlock_calls) == 1 and unlock_calls[0]["pw"] == "correct horse" and unlock_calls[0]["stdin"] == ""assert all("correct horse" not in " ".join(c["argv"]) for c in calls), "master password must never be argv"@@ -231,3 +231,58 @@ def test_onepassword_backend_env_forwards_config_directory(monkeypatch):backend = OnePasswordLoginBackend({"enabled": True})assert backend._env(None)["OP_CONFIG_DIR"] == "/tmp/op-config"+++# A stand-in `op` holding the real CLI's service-account rule: `item get` without a vault query exits 1+# with op's own message (op 2.32 checks this client-side, before it even decodes the token).+_FAKE_OP = r'''#!/usr/bin/env python3+import json, os, sys+argv = sys.argv[1:]+with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "op.log"), "a") as log:+ log.write(json.dumps(argv) + "\n")+if argv[:2] == ["item", "list"]:+ print(json.dumps([{"id": i, "title": i, "vault": {"id": "vault-" + i[-1]},+ "urls": [{"href": "https://example.com/login"}]} for i in ("item-a", "item-b", "item-c")])); sys.exit(0)+if argv[:2] == ["item", "get"]:+ if os.environ.get("OP_SERVICE_ACCOUNT_TOKEN") and "--vault" not in argv:+ sys.stderr.write("a vault query must be provided when this command is called by a service account\n"); sys.exit(1)+ if "item-c" in argv: # a revoked/garbled token: op's own wording mentions a session+ sys.stderr.write("error initializing client: Validation: (failed to session.DecodeSACredentials)\n"); sys.exit(1)+ print("123456" if "--otp" in argv else "dummy-password"); sys.exit(0)+sys.exit(2)+'''+++def fake_op_service_account(tmp_path):+ from agent.vault_backends.onepassword import OnePasswordLoginBackend++ exe = tmp_path / "op"+ exe.write_text(_FAKE_OP, encoding="utf-8")+ exe.chmod(exe.stat().st_mode | stat.S_IXUSR)+ token = lambda name, default="": "dummy-sa-token" if name == "OP_SERVICE_ACCOUNT_TOKEN" else default+ with patch("agent.secret_scope.get_secret", side_effect=token):+ # a fresh backend per tool call, exactly as backend_for_handle builds one: nothing listed yet+ yield (lambda: OnePasswordLoginBackend({"binary_path": str(exe)})), tmp_path / "op.log"+++def test_onepassword_service_account_reads_name_the_items_own_vault(fake_op_service_account):+ """#108335: a service account can list logins but every fill/OTP read failed because+ `op item get` never named a vault. Each read now carries the vault its listing reported."""+ new_backend, log = fake_op_service_account+ assert new_backend().resolve_password("op:item-b") == "dummy-password"+ assert new_backend().resolve_otp("op:item-a") == "123456"+ gets = [a for a in map(json.loads, log.read_text(encoding="utf-8-sig").splitlines()) if a[:2] == ["item", "get"]]+ assert [a[a.index("--vault") + 1] for a in gets] == ["vault-b", "vault-a"]+++def test_onepassword_service_account_refusals_name_the_real_cause(fake_op_service_account):+ """A handle no listing returned is refused before any secret read, and a token op rejects+ surfaces op's error rather than an unlock prompt a service account can never satisfy."""+ new_backend, log = fake_op_service_account+ with pytest.raises(RuntimeError, match="not found"):+ new_backend().resolve_password("op:--help")+ assert new_backend().resolve_otp("op:ghost") is None+ assert all(json.loads(a)[:2] != ["item", "get"] for a in log.read_text(encoding="utf-8-sig").splitlines())+ with pytest.raises(RuntimeError, match="DecodeSACredentials"):+ new_backend().resolve_password("op:item-c")diff --git a/tests/agent/test_vault_onepassword_selector.py b/tests/agent/test_vault_onepassword_selector.pydeleted file mode 100644index 686af755dcc..00000000000--- a/tests/agent/test_vault_onepassword_selector.py+++ /dev/null@@ -1,92 +0,0 @@-"""Metadata-only selector regressions; no real password manager is invoked."""-import json-from unittest.mock import Mock, patch--import pytest--from agent.vault_backends.onepassword import OnePasswordLoginBackend---def item(item_id="item-a", vault: object = "vault-a"):- return {"id": item_id, "title": "Example", "vault": {"id": vault},- "urls": [{"href": "https://example.com/login"}]}---def backend():- with patch("agent.secret_scope.get_secret", return_value="dummy-service-token"):- backend = OnePasswordLoginBackend()- backend._run = Mock()- return backend--[email protected]("method,flags,value", [- ("resolve_password", ("--fields", "label=password", "--reveal"), "dummy-password"),- ("resolve_otp", ("--otp",), "123456"),-])-def test_legacy_handles_resolve_each_items_vault(backend, method, flags, value):- records = [item(), item("item-b", "vault-b")]- backend._run.return_value = json.dumps(records)- assert [m.id for m in backend.list_items()] == ["op:item-a", "op:item-b"]- assert backend.get_meta("op:item-b").origin == "https://example.com"- for item_id, vault_id in [("item-a", "vault-a"), ("item-b", "vault-b")]:- backend._run.reset_mock()- backend._run.side_effect = [json.dumps(records), value + "\r\n"]- assert getattr(backend, method)("op:" + item_id) == value- assert backend._run.call_args_list[0].args == (- "item", "list", "--categories", "Login", "--format", "json")- assert backend._run.call_args_list[1].args == (- "item", "get", item_id, "--vault", vault_id, *flags)--[email protected]("records", [- [], [item("other")], [item(vault="")], [item(vault=None)],- [dict(item(), vault=None)], [dict(item(), vault="not-a-record")],- [item(), item(vault="vault-b")], {"error": "not-a-list"},-])[email protected]("method", ["resolve_password", "resolve_otp"])-def test_missing_or_ambiguous_metadata_never_reads_secret(backend, records, method):- backend._run.return_value = json.dumps(records)- if method == "resolve_password":- with pytest.raises(RuntimeError):- backend.resolve_password("op:item-a")- else:- assert backend.resolve_otp("op:item-a") is None- assert all(c.args[:2] != ("item", "get") for c in backend._run.call_args_list)--[email protected]("method", ["resolve_password", "resolve_otp"])[email protected]("failure", [RuntimeError("metadata unavailable"), "not-json", "[]"])-def test_refresh_failure_does_not_reuse_old_vault(backend, method, failure):- backend._run.return_value = json.dumps([item()])- backend.list_items()- backend._run.reset_mock()- backend._run.side_effect = [failure]- if method == "resolve_password":- with pytest.raises((RuntimeError, ValueError)):- backend.resolve_password("op:item-a")- else:- assert backend.resolve_otp("op:item-a") is None- assert all(c.args[:2] != ("item", "get") for c in backend._run.call_args_list)--[email protected]("handle", ["bw:item-a", "op:", "op:--help", "op:vault-a:item-a"])-def test_invalid_handles_fail_before_cli(backend, handle):- with pytest.raises(ValueError):- backend.resolve_password(handle)- assert backend.resolve_otp(handle) is None- backend._run.assert_not_called()---def test_personal_session_without_vault_keeps_unscoped_read(backend):- backend._service_token = ""- backend._run.side_effect = [json.dumps([item(vault="")]), "dummy-password\n"]- assert backend.resolve_password("op:item-a") == "dummy-password"- assert backend._run.call_args.args == (- "item", "get", "item-a", "--fields", "label=password", "--reveal")---def test_fresh_backend_does_not_depend_on_listing_cache(backend):- backend._run.side_effect = [json.dumps([item(vault="vault-new")]), "dummy-password\n"]- assert backend.resolve_password("op:item-a") == "dummy-password"- assert backend._run.call_args.args[3:5] == ("--vault", "vault-new")