Skip to content

The agent that grows with you

fix(vault): resolve 1Password vault from fresh item metadata

Willb45971380c6a
diff --git a/agent/vault_backends/onepassword.py b/agent/vault_backends/onepassword.py
index 1aa15592d79..400abf5e3ea 100644
--- a/agent/vault_backends/onepassword.py
+++ b/agent/vault_backends/onepassword.py
@@ -4,7 +4,8 @@ Unlock: ``op signin --raw`` with the master password on stdin (desktop-app
integration 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> --fields label=password --reveal``.
+username. Resolve: ``op item get <id> --vault <vault-id> ...``, selecting the
+item's vault from fresh listing metadata (required for service accounts).
"""
from __future__ import annotations
@@ -119,14 +120,38 @@ 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 resolve_password(self, handle: str) -> str:
+ 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")
item_id = handle[len(self.prefix):]
- return self._run("item", "get", item_id, "--fields", "label=password", "--reveal").rstrip("\r\n")
+ 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]
+
+ def resolve_password(self, handle: str) -> str:
+ return self._run("item", "get", *self._item_selector(handle),
+ "--fields", "label=password", "--reveal").rstrip("\r\n")
def resolve_otp(self, handle: str) -> Optional[str]:
# `--otp` mints the current TOTP from the item's one-time-password field; items without one error out.
try:
- code = self._run("item", "get", handle[len(self.prefix):], "--otp").strip()
+ code = self._run("item", "get", *self._item_selector(handle), "--otp").strip()
except Exception:
return None
return code if code.isdigit() else None
diff --git a/tests/agent/test_vault_onepassword_selector.py b/tests/agent/test_vault_onepassword_selector.py
new file mode 100644
index 00000000000..686af755dcc
--- /dev/null
+++ b/tests/agent/test_vault_onepassword_selector.py
@@ -0,0 +1,92 @@
+"""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")