Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Read Bitwarden credentials with fewer CLI processes and keep the session key out of errors (SKY-17721) (#8794)
Shuchang Zheng253f0e44ecaa
diff --git a/skyvern/config.py b/skyvern/config.pyindex ddbf6602a..3d4713bde 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -457,10 +457,12 @@ class Settings(BaseSettings):# How long a cached vault may go without a `bw sync`. A miss forces a sync and one retry,# so this is the staleness ceiling for an *edit*, not for a newly created item.BITWARDEN_SESSION_SYNC_INTERVAL_SECONDS: float = 60.0- # How long an unused session may keep an unlocked vault in memory and on disk before it is- # logged out. Long enough that a batch stays warm throughout, short enough that an idle pod is- # not sitting on someone's open vault. Set to 0 to keep sessions for the pod's lifetime.+ # How long an unused session may keep an unlocked vault in memory and on disk before it is logged+ # out (0 disables): long enough to keep a batch warm, short enough that an idle pod holds no open vault.BITWARDEN_SESSION_MAX_IDLE_SECONDS: float = 900.0+ # Retires even a busy session after this long, ±15% per session (0 disables); each retirement costs a+ # cold login. The periodic sync catches a revoked login sooner, so this only bounds an open vault's age.+ BITWARDEN_SESSION_MAX_LIFETIME_SECONDS: float = 14400.0# Each `bw` invocation is a Node process costing real CPU and ~hundreds of MB. Bound how many# run at once so a burst of runs cannot starve the browsers sharing the pod.BITWARDEN_MAX_CONCURRENT_CLI_COMMANDS: int = 4diff --git a/skyvern/forge/sdk/services/bitwarden.py b/skyvern/forge/sdk/services/bitwarden.pyindex d7e8e72ed..e256a6403 100644--- a/skyvern/forge/sdk/services/bitwarden.py+++ b/skyvern/forge/sdk/services/bitwarden.py@@ -12,7 +12,8 @@ import tempfileimport timeimport uuidfrom collections import OrderedDict-from collections.abc import AsyncIterator, Awaitable, Callable+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator+from contextvars import ContextVarfrom dataclasses import dataclassfrom enum import IntEnum, StrEnumfrom functools import cached_property@@ -75,7 +76,12 @@ _EXPIRED_SESSION_MARKERS = ("session key is invalid","invalid session","mac failed",+ # The interactive unlock prompt a locked read prints if `BW_NOINTERACTION` ever stops reaching it.+ "master password:",)+# How `bw sync` reports the server rejecting the login behind a cached session. The CLI logs itself+# out when it sees one, so that session's vault copy can never be refreshed again.+_REJECTED_LOGIN_PATTERN = re.compile(r'invalid_grant|"statuscode"\s*:\s*401\b|cannot refresh access token')# A vault copy that predates the item looks exactly like an item that does not exist, so both are# worth one forced sync before believing the miss._STALE_VAULT_MARKERS = ("not found", "no items found", "no item found")@@ -105,6 +111,8 @@ def _contains_decryption_failure(value: Any) -> bool:_IDENTITY_FINGERPRINT_SALT = secrets.token_bytes(32)_IDENTITY_FINGERPRINT_ITERATIONS = 120_000+_SESSION_LIFETIME_JITTER = 0.15+class _SessionRepair(StrEnum):"""What to do to a cached session that just failed a read."""@@ -114,9 +122,11 @@ class _SessionRepair(StrEnum):RELOGIN = "relogin"-def _repair_for_failure(message: str) -> _SessionRepair:- lowered = message.lower()- if any(marker in lowered for marker in _EXPIRED_SESSION_MARKERS):+def _repair_for_failure(error: BaseException) -> _SessionRepair:+ lowered = str(error).lower()+ if any(marker in lowered for marker in _EXPIRED_SESSION_MARKERS) or (+ isinstance(error, BitwardenSyncError) and _REJECTED_LOGIN_PATTERN.search(lowered)+ ):return _SessionRepair.RELOGINif any(marker in lowered for marker in _STALE_VAULT_MARKERS):return _SessionRepair.RESYNC@@ -183,7 +193,14 @@ class _CliSession:self.synced_at: float = 0.0self.in_flight = 0self.retired = False- self.last_used_at = time.monotonic()+ self.created_at = time.monotonic()+ self.last_used_at = self.created_at+ # Sessions one burst logged in would otherwise all expire, and all log in again, together.+ self.lifetime_scale = random.uniform(1 - _SESSION_LIFETIME_JITTER, 1 + _SESSION_LIFETIME_JITTER)++ def outlived(self, now: float) -> bool:+ max_lifetime = settings.BITWARDEN_SESSION_MAX_LIFETIME_SECONDS * self.lifetime_scale+ return max_lifetime > 0 and now - self.created_at >= max_lifetime@propertydef env(self) -> dict[str, str]:@@ -200,21 +217,17 @@ class _CliSession:self.in_flight -= 1self.last_used_at = time.monotonic()if self.retired and self.in_flight == 0:- self._remove_data_dir()+ self._log_out()def retire(self) -> None:- """Log this identity out for good.-- Removing the directory is what logs it out: the directory holds the tokens and the vault- copy. A retired session is never handed out again, so it is safe to wait for the readers- still inside `in_use` rather than deleting the directory out from under them.- """+ """Never hand this session out again, and log it out once its last reader has finished."""self.retired = True- self.session_key = Noneif self.in_flight == 0:- self._remove_data_dir()+ self._log_out()- def _remove_data_dir(self) -> None:+ def _log_out(self) -> None:+ # Removing the directory is what logs the identity out: it holds the tokens and the vault copy.+ self.session_key = Noneshutil.rmtree(self.appdata_dir, ignore_errors=True)@@ -236,6 +249,13 @@ class _CliSessionCache:async def checkout(self, identity: _VaultIdentity) -> _CliSession:async with self._lock:session = self._sessions.get(identity.fingerprint)+ outlived: list[tuple[_CliSession, str]] = []+ if session is not None and session.outlived(time.monotonic()):+ # A session in constant use never goes idle, so only its age can retire it. Readers+ # already inside finish on it; this checkout gets a fresh login.+ del self._sessions[identity.fingerprint]+ outlived.append((session, "lifetime"))+ session = Noneif session is None:# A directory per session object, not per identity: a session retired while another# request still held it must never be able to delete its own replacement's data.@@ -245,9 +265,9 @@ class _CliSessionCache:self._sessions[identity.fingerprint] = sessionos.makedirs(session.appdata_dir, mode=0o700, exist_ok=True)self._sessions.move_to_end(identity.fingerprint)- reclaimed = self._reclaim(keep=identity.fingerprint)+ reclaimed = outlived + self._reclaim(keep=identity.fingerprint)- await self._retire_all(reclaimed)+ self._retire_all(reclaimed)return sessionasync def release(self) -> None:@@ -260,20 +280,22 @@ class _CliSessionCache:"""async with self._lock:reclaimed = self._reclaim(keep=None)- await self._retire_all(reclaimed)+ self._retire_all(reclaimed)- async def _retire_all(self, reclaimed: list[tuple[_CliSession, str]]) -> None:+ @staticmethod+ def _retire_all(reclaimed: list[tuple[_CliSession, str]]) -> None:+ # Never waits on a session's lock: the reader that noticed a busy session expire would+ # otherwise queue behind every reader of the old session before starting its own login.for stale, reason in reclaimed:LOG.info("Retiring a cached Bitwarden CLI session",reason=reason,fingerprint=stale.identity.fingerprint[:12],)- async with stale.lock:- stale.retire()+ stale.retire()def _reclaim(self, keep: str | None) -> list[tuple[_CliSession, str]]:- """Retire sessions that have gone idle or pushed the cache past capacity.+ """Retire sessions that have gone idle, outlived their lifetime, or pushed the cache past capacity.The caller holds the cache lock. `keep` names the session this checkout is about to handout: it has no reader yet, so it looks idle, and retiring it would send the caller to a@@ -290,6 +312,8 @@ class _CliSessionCache:continueif max_idle > 0 and now - session.last_used_at >= max_idle:reason = "idle"+ elif session.outlived(now):+ reason = "lifetime"elif len(self._sessions) > capacity:reason = "capacity"else:@@ -302,20 +326,45 @@ class _CliSessionCache:async with self._lock:if self._sessions.get(session.identity.fingerprint) is session:del self._sessions[session.identity.fingerprint]- async with session.lock:- session.retire()+ session.retire()async def clear(self) -> None:async with self._lock:sessions = list(self._sessions.values())self._sessions.clear()for session in sessions:- async with session.lock:- session.retire()+ session.retire()_cli_sessions = _CliSessionCache()++@dataclass+class BitwardenSessionUsage:+ """How one credential read got its CLI session: a cached one, or a login of its own."""++ # Whether the first session the read checked out was already logged in when the read arrived,+ # so a read that waited out another read's login counts as cold. None when no read reached one.+ session_reused: bool | None = None+ # Wall time spent in `bw login`, summed across any repair logins. None when nothing logged in.+ login_seconds: float | None = None+ # Wall time spent queued for a session's lock, behind another read's login or sync.+ lock_wait_seconds: float | None = None+++_session_usage: ContextVar[BitwardenSessionUsage | None] = ContextVar("bitwarden_session_usage", default=None)+++def track_bitwarden_session_usage() -> Iterator[BitwardenSessionUsage]:+ usage = BitwardenSessionUsage()+ token = _session_usage.set(usage)+ try:+ yield usage+ finally:+ _session_usage.reset(token)++T = TypeVar("T")@@ -644,10 +693,15 @@ class BitwardenService:# CLEANEXIT/RESPONSE/QUIET/PRETTY/RAW/NOINTERACTION output modes). An inherited output-mode var# can suppress a failure, wrap the item payload, or — with BW_RAW — make `bw unlock` print the# raw vault session key on stdout. Scrub the whole BW_* prefix fail-closed and re-supply only- # what additional_env sets below; do not narrow this back to a fixed allowlist that can drift.+ # what is set below; do not narrow this back to a fixed allowlist that can drift.for key in [name for name in env if name.startswith("BW_")]:del env[key]env["NODE_NO_WARNINGS"] = "1"+ # Without it, a read of a locked vault prompts for the master password and exits 0 with no output+ # instead of failing with "Vault is locked.". Login stays interactive so a new-device challenge+ # still says "New device verification", which the global-credentials fallback keys on.+ if command[1:2] != ["login"]:+ env["BW_NOINTERACTION"] = "true"if additional_env:env.update(additional_env) # Update with any additional environment variables@@ -662,6 +716,8 @@ class BitwardenService:async with asyncio.timeout(timeout):shell_subprocess = await asyncio.create_subprocess_exec(*command,+ # An inherited open stdin turns any prompt into a hang until the timeout.+ stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,env=env,@@ -702,38 +758,46 @@ class BitwardenService:pass@staticmethod- def _extract_session_key(unlock_cmd_output: str) -> str | None:- # Split the text by lines- lines = unlock_cmd_output.split("\n")-- # Look for the line containing the BW_SESSION- for line in lines:- if 'BW_SESSION="' in line:- # Find the start and end positions of the session key- start = line.find('BW_SESSION="') + len('BW_SESSION="')- end = line.rfind('"', start)- return line[start:end]-- return None+ def _extract_session_key(cli_output: str) -> str | None:+ """The session key from `bw unlock` or an email `bw login` output, or None if it has none."""+ match = re.search(r'BW_SESSION="([^"\s]+)"', cli_output)+ return match.group(1) if match else None@staticmethod- async def _establish_cli_session(session: _CliSession, timeout: int) -> None:- """Log this identity in and unlock it. The caller holds `session.lock`."""+ async def _establish_cli_session(+ session: _CliSession,+ timeout: int,+ verify_sync: bool = False,+ trust_login_key: bool = True,+ ) -> None:+ """Log in (which already runs a full sync), then unlock unless an email login printed a key to trust.+ The caller holds `session.lock`."""identity = session.identity- await BitwardenService.login(- identity.client_id,- identity.client_secret,- email=identity.email,- master_password=identity.master_password,- timeout=timeout,- appdata_dir=session.appdata_dir,- )- session.session_key = await BitwardenService.unlock(- identity.master_password, timeout=timeout, appdata_dir=session.appdata_dir- )- # Sync after unlocking rather than before, so the one call works for both auth modes: an- # API-key login leaves the vault locked, and `bw sync` needs it open.- await BitwardenService.sync(timeout=timeout, session_key=session.session_key, appdata_dir=session.appdata_dir)+ usage = _session_usage.get()+ started = time.monotonic()+ try:+ login_key = await BitwardenService.login(+ identity.client_id,+ identity.client_secret,+ email=identity.email,+ master_password=identity.master_password,+ timeout=timeout,+ appdata_dir=session.appdata_dir,+ )+ finally:+ if usage is not None:+ usage.login_seconds = (usage.login_seconds or 0.0) + time.monotonic() - started+ if identity.uses_email_auth and trust_login_key and login_key:+ session.session_key = login_key+ else:+ session.session_key = await BitwardenService.unlock(+ identity.master_password, timeout=timeout, appdata_dir=session.appdata_dir+ )+ if verify_sync:+ # The sync inside `bw login` swallows its own failure; `bw sync` reports one.+ await BitwardenService.sync(+ timeout=timeout, session_key=session.session_key, appdata_dir=session.appdata_dir+ )session.synced_at = time.monotonic()@staticmethod@@ -741,11 +805,21 @@ class BitwardenService:session: _CliSession,timeout: int,force_sync: bool = False,+ verify_sync: bool = False,+ trust_login_key: bool = True,) -> None:"""Make `session` usable, logging in only if this process does not already hold a session."""+ usage = _session_usage.get()+ if usage is not None and usage.session_reused is None:+ usage.session_reused = session.session_key is not None+ queued_at = time.monotonic()async with session.lock:+ if usage is not None:+ usage.lock_wait_seconds = (usage.lock_wait_seconds or 0.0) + time.monotonic() - queued_atif session.session_key is None:- await BitwardenService._establish_cli_session(session, timeout=timeout)+ await BitwardenService._establish_cli_session(+ session, timeout=timeout, verify_sync=verify_sync, trust_login_key=trust_login_key+ )returnif (@@ -758,12 +832,16 @@ class BitwardenService:timeout=timeout, session_key=session.session_key, appdata_dir=session.appdata_dir)session.synced_at = time.monotonic()- except Exception:+ except Exception as error:if force_sync:# A caller that asked for a guaranteed-fresh vault has no way to tell a stale# answer from a correct one — a listing that is missing an item someone just# added looks exactly like a listing that is right. Say the refresh failed.raise+ if _repair_for_failure(error) is _SessionRepair.RELOGIN:+ # The login behind this session is gone, so the cached copy can only get staler.+ # The caller drops the session and logs in again rather than read from it.+ raise# An opportunistic refresh is different: the read that follows can still detect a# miss and force another sync, so a failure here is not worth failing the run over.LOG.warning("Could not refresh the cached Bitwarden vault; reading the cached copy", exc_info=True)@@ -775,19 +853,29 @@ class BitwardenService:run: Callable[[_CliSession], Awaitable[T]],force_sync: bool = False,) -> T:- """Run `run` against a live CLI session, repairing a stale session once before giving up."""+ """Run `run` against a live CLI session, repairing a stale session once before giving up.+ `force_sync` demands a `bw sync` that reports failure even after a fresh login; a repair only resyncs."""+ resync = force_syncfor attempt in range(2):session = await _cli_sessions.checkout(identity)try:# Claim the session before the first await after checkout, so eviction cannot pull# the data directory out from under a command that is about to run against it.async with session.in_use():- await BitwardenService._prepare_cli_session(session, timeout=timeout, force_sync=force_sync)+ await BitwardenService._prepare_cli_session(+ session,+ timeout=timeout,+ force_sync=resync,+ verify_sync=force_sync,+ # A login key that unlocks nothing makes the read fail with "Vault is locked.";+ # the repair login then unlocks explicitly, so that costs one retry, not every read.+ trust_login_key=attempt == 0,+ )return await run(session)except BitwardenAccessDeniedError:raiseexcept BaseException as error:- repair = _repair_for_failure(str(error)) if attempt == 0 else _SessionRepair.NONE+ repair = _repair_for_failure(error) if attempt == 0 else _SessionRepair.NONE# A session that never finished logging in is not a session; drop it rather than# hand the next run a half-built data directory.if session.session_key is None or repair is _SessionRepair.RELOGIN:@@ -800,7 +888,7 @@ class BitwardenService:fingerprint=identity.fingerprint[:12],error=str(error),)- force_sync = True+ resync = Truefinally:# This request is done holding its session, which may be what makes another one# reclaimable. Runs on the way out of a return, a raise and a retry alike.@@ -835,14 +923,14 @@ class BitwardenService:if items_result.returncode != 0:raise BitwardenListItemsError(f"Failed to list Bitwarden items. Error: {items_result.stderr}")+ # Never quote stdout in an error: it is the decrypted vault, passwords included. `from None` keeps+ # the parse error, whose `doc` is that stdout, out of the chain.try:items = json.loads(items_result.stdout)except json.JSONDecodeError:- raise BitwardenListItemsError(- f"Failed to parse items JSON. Error: {items_result.stderr} Output: {items_result.stdout}"- )+ raise BitwardenListItemsError(f"Failed to parse items JSON. Error: {items_result.stderr}") from Noneif not isinstance(items, list):- raise BitwardenListItemsError(f"Failed to parse items JSON. Output: {items_result.stdout}")+ raise BitwardenListItemsError(f"Items output is a JSON {type(items).__name__}, not a list")return items@staticmethod@@ -865,7 +953,7 @@ class BitwardenService:try:item = json.loads(item_result.stdout)except json.JSONDecodeError:- raise BitwardenGetItemError(f"Failed to parse Bitwarden item JSON. Error: {item_result.stderr}")+ raise BitwardenGetItemError(f"Failed to parse Bitwarden item JSON. Error: {item_result.stderr}") from Noneif not isinstance(item, dict) or item.get("object") != "item":raise BitwardenGetItemError("Invalid Bitwarden item envelope")returned_id = item.get("id")@@ -1352,13 +1440,13 @@ class BitwardenService:master_password: str | None = None,timeout: int = settings.BITWARDEN_TIMEOUT_SECONDS,appdata_dir: str | None = None,- ) -> None:+ ) -> str | None:"""- Log in to the Bitwarden CLI.+ Log in to the Bitwarden CLI, returning the session key the login printed, if any.Supports two auth modes:- 1. Email + master_password (preferred when available)- 2. API key (client_id + client_secret) via --apikey flag+ 1. Email + master_password (preferred when available), which also unlocks the vault+ 2. API key (client_id + client_secret) via --apikey flag, which leaves it locked"""bw_email = email or settings.BITWARDEN_EMAILbw_master_password = master_password or settings.BITWARDEN_MASTER_PASSWORD@@ -1375,14 +1463,16 @@ class BitwardenService:login_command = ["bw", "login", "--apikey"]login_result = await BitwardenService.run_command(login_command, env, timeout=timeout)- # Validate the login result+ # Never quote stdout in an error: a successful email login prints the vault session key there,+ # even when stderr carries something unexpected.if login_result.stdout and "You are logged in!" not in login_result.stdout:- raise BitwardenLoginError(f"Failed to log in. stdout: {login_result.stdout} stderr: {login_result.stderr}")+ raise BitwardenLoginError(f"Failed to log in. stderr: {login_result.stderr}")if login_result.stderr and not BitwardenService._is_ignorable_login_stderr(login_result.stderr):- raise BitwardenLoginError(f"Failed to log in. stdout: {login_result.stdout} stderr: {login_result.stderr}")+ raise BitwardenLoginError(f"Failed to log in. stderr: {login_result.stderr}")LOG.info("Bitwarden login successful")+ return BitwardenService._extract_session_key(login_result.stdout)@staticmethodasync def unlock(diff --git a/skyvern/forge/sdk/workflow/credential_fetch_outcome.py b/skyvern/forge/sdk/workflow/credential_fetch_outcome.pyindex 496182595..2fdbcf97f 100644--- a/skyvern/forge/sdk/workflow/credential_fetch_outcome.py+++ b/skyvern/forge/sdk/workflow/credential_fetch_outcome.py@@ -29,6 +29,7 @@ from skyvern.exceptions import (RuntimeSequentialCredentialUnsupported,)from skyvern.forge.sdk.schemas.credentials import CredentialVaultType+from skyvern.forge.sdk.services.bitwarden import BitwardenSessionUsage, track_bitwarden_session_usagefrom skyvern.forge.sdk.services.credential.custom_credential_vault_service import CustomCredentialConfigurationErrorfrom skyvern.forge.sdk.workflow.models.parameter import (Parameter,@@ -141,6 +142,7 @@ def _log_outcome(outcome: CredentialFetchOutcome,failure_type: str | None,started: float,+ session: BitwardenSessionUsage,) -> None:log = LOG.info if outcome == "succeeded" else LOG.warninglog(@@ -150,6 +152,9 @@ def _log_outcome(outcome=outcome,failure_type=failure_type,duration_seconds=round(time.monotonic() - started, 3),+ session_reused=session.session_reused,+ login_seconds=None if session.login_seconds is None else round(session.login_seconds, 3),+ lock_wait_seconds=None if session.lock_wait_seconds is None else round(session.lock_wait_seconds, 3),)@@ -167,10 +172,11 @@ async def record_credential_fetch()fetch = CredentialFetch(provider=provider, parameter_type=parameter_type)started = time.monotonic()- try:- yield fetch- except Exception as error:- outcome, failure_type = classify_credential_fetch_failure(error, customer_owned=fetch.customer_owned)- _log_outcome(fetch, outcome, failure_type, started)- raise- _log_outcome(fetch, "succeeded", None, started)+ with track_bitwarden_session_usage() as session:+ try:+ yield fetch+ except Exception as error:+ outcome, failure_type = classify_credential_fetch_failure(error, customer_owned=fetch.customer_owned)+ _log_outcome(fetch, outcome, failure_type, started, session)+ raise+ _log_outcome(fetch, "succeeded", None, started, session)diff --git a/tests/unit/test_bitwarden_login.py b/tests/unit/test_bitwarden_login.pyindex 6699b13d6..92d7905e7 100644--- a/tests/unit/test_bitwarden_login.py+++ b/tests/unit/test_bitwarden_login.py@@ -454,6 +454,25 @@ async def test_run_command_scrubs_inherited_cli_output_modes(assert all(os.environ[flag] == "true" for flag in flags)[email protected](("subcommand", "noninteractive"), [("get", "true"), ("login", None)])+async def test_run_command_never_lets_a_read_prompt(tmp_path, subcommand: str, noninteractive: str | None) -> None:+ # A locked read that may prompt exits 0 with no output on a closed stdin and hangs on an open one;+ # with BW_NOINTERACTION it fails with "Vault is locked.". Login stays interactive for its device prompt.+ fake_cli = tmp_path / "bw"+ fake_cli.write_text(+ f"#!{sys.executable}\n"+ "import json, os\n"+ "print(json.dumps({'noninteractive': os.environ.get('BW_NOINTERACTION'),"+ " 'stdin_is_devnull': os.path.samestat(os.fstat(0), os.stat(os.devnull))}))\n"+ )+ fake_cli.chmod(0o755)++ result = await BitwardenService.run_command([str(fake_cli), subcommand])++ assert json.loads(result.stdout) == {"noninteractive": noninteractive, "stdin_is_devnull": True}++@pytest.mark.asyncioasync def test_unlock_never_echoes_raw_session_key_in_error(monkeypatch: pytest.MonkeyPatch) -> None:# With an inherited BW_RAW, `bw unlock` prints the bare session key (the vault decryption key) on@@ -580,11 +599,11 @@ async def test_every_cli_step_receives_the_attempt_budget(monkeypatch: pytest.Mo)# Establishing the session and reading the item all run on the attempt's budget. No `bw logout`:- # the session is kept for the next run rather than torn down (SKY-14751).+ # the session is kept for the next run rather than torn down (SKY-14751), and no `bw sync`: the+ # login already ran a full one.assert budgets == {"bw login": 37,"bw unlock": 37,- "bw sync": 37,"bw get": 37,}diff --git a/tests/unit/test_bitwarden_session_cache.py b/tests/unit/test_bitwarden_session_cache.pyindex 485cf64c2..e081a2c9c 100644--- a/tests/unit/test_bitwarden_session_cache.py+++ b/tests/unit/test_bitwarden_session_cache.py@@ -15,19 +15,33 @@ before an item miss is believed.import asyncioimport jsonimport os-from collections.abc import Iterator+import random+from collections.abc import Awaitable, Callable, Iterator+from datetime import UTC, datetime+from unittest.mock import AsyncMockimport pytest+from structlog.testing import capture_logsfrom skyvern.exceptions import BitwardenGetItemError+from skyvern.forge.sdk.schemas.credentials import CredentialVaultTypefrom skyvern.forge.sdk.services import bitwarden as bitwarden_modulefrom skyvern.forge.sdk.services.bitwarden import (BitwardenConstants,BitwardenService,RunCommandResult,)+from skyvern.forge.sdk.workflow.credential_fetch_outcome import (+ RUN_CREDENTIAL_FETCH_FINISHED_MESSAGE,+ record_credential_fetch,+)+from skyvern.forge.sdk.workflow.models.parameter import BitwardenLoginCredentialParameter+from tests.unit.scoped_asyncio import ScopedAsyncioAPPDATA_ENV = bitwarden_module._BITWARDEN_APPDATA_ENV_VAR+# Synthetic stand-ins for the base64 session keys the CLI prints.+LOGIN_SESSION_KEY = "c3ludGhldGljLWxvZ2luLWtleQ=="+UNLOCK_SESSION_KEY = "c3ludGhldGljLXVubG9jay1rZXk="ITEM_ID = "11111111-1111-1111-1111-111111111111"OTHER_ITEM_ID = "22222222-2222-2222-2222-222222222222"CARD_ITEM = {@@ -58,11 +72,34 @@ def _isolated_session_cache(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:yield+def _session_key_banner(title: str, session_key: str) -> str:+ """What bw 2025.9.0 prints after an email `bw login` or a `bw unlock`."""+ return (+ f"{title}\n\n"+ "To unlock your vault, set your session key to the `BW_SESSION` environment variable. ex:\n"+ f'$ export BW_SESSION="{session_key}"\n'+ f'> $env:BW_SESSION="{session_key}"\n\n'+ "You can also pass the session key to any command with the `--session` option. ex:\n"+ f"$ bw list items --session {session_key}"+ )+++# What bw 2025.9.0 prints after `bw login --apikey`: the vault stays locked and no key is issued.+API_KEY_LOGIN_OUTPUT = "You are logged in!\n\nTo unlock your vault, use the `unlock` command. ex:\n$ bw unlock"+# What bw 2025.9.0 answers a read of a logged-in but locked vault with, captured from the real binary.+VAULT_IS_LOCKED = RunCommandResult(stdout="", stderr="Vault is locked.", returncode=1)+# The same read when it is allowed to prompt and its stdin is closed: exit 0, nothing read.+MASTER_PASSWORD_PROMPT = RunCommandResult(+ stdout="\n", stderr="? Master password: [input is hidden] \x1b[37D\x1b[37C", returncode=0+)++class FakeVaultCli:"""Stands in for the `bw` binary, recording every step and the data directory it ran against."""def __init__(self) -> None:self.calls: list[tuple[str, str | None]] = []+ self.session_args: list[tuple[str, str | None]] = []self.item: dict = {"object": "item","id": ITEM_ID,@@ -70,10 +107,15 @@ class FakeVaultCli:"login": {"username": "[email protected]", "password": "hunter2", "totp": ""},"fields": [{"name": "first_name", "value": "Alice"}],}- # stderr to answer the next `bw get` / `bw list` calls with, one per entry, before succeeding.- self.get_failures: list[str] = []- self.list_failures: list[str] = []+ # What to answer the next `bw get` / `bw list` / `bw sync` calls with, one per entry, before+ # succeeding: a bare string is a failure's stderr.+ self.get_failures: list[str | RunCommandResult] = []+ self.list_failures: list[str | RunCommandResult] = []+ self.sync_failures: list[str] = []self.get_stderr = ""+ self.login_stdout: str | None = None+ self.login_stderr = ""+ self.on_login: Callable[[], Awaitable[None]] | None = None@propertydef steps(self) -> list[str]:@@ -86,24 +128,52 @@ class FakeVaultCli:self, command: list[str], additional_env: dict[str, str] | None = None, timeout: float = 60) -> RunCommandResult:self.calls.append((command[1], (additional_env or {}).get(APPDATA_ENV)))+ if "--session" in command:+ self.session_args.append((command[1], command[command.index("--session") + 1]))if command[1] == "login":- return RunCommandResult(stdout="You are logged in!", stderr="", returncode=0)+ if self.on_login is not None:+ await self.on_login()+ if self.login_stdout is not None:+ stdout = self.login_stdout+ elif "--apikey" in command:+ stdout = API_KEY_LOGIN_OUTPUT+ else:+ stdout = _session_key_banner("You are logged in!", LOGIN_SESSION_KEY)+ return RunCommandResult(stdout=stdout, stderr=self.login_stderr, returncode=0)if command[1] == "unlock":return RunCommandResult(- stdout='Your vault is now unlocked!\n$ export BW_SESSION="session-key"', stderr="", returncode=0+ stdout=_session_key_banner("Your vault is now unlocked!", UNLOCK_SESSION_KEY), stderr="", returncode=0)+ if command[1] == "sync" and self.sync_failures:+ return RunCommandResult(stdout="", stderr=self.sync_failures.pop(0), returncode=1)if command[1] == "get":if self.get_failures:- return RunCommandResult(stdout="", stderr=self.get_failures.pop(0), returncode=1)+ return _as_failure(self.get_failures.pop(0))return RunCommandResult(stdout=json.dumps(self.item), stderr=self.get_stderr, returncode=0)if command[1] == "list":if self.list_failures:- # How the CLI reports a dead session: non-zero, nothing on stdout, reason on stderr.- return RunCommandResult(stdout="", stderr=self.list_failures.pop(0), returncode=1)+ return _as_failure(self.list_failures.pop(0))return RunCommandResult(stdout=json.dumps([self.item]), stderr="", returncode=0)return RunCommandResult(stdout="", stderr="", returncode=0)+def _as_failure(failure: str | RunCommandResult) -> RunCommandResult:+ if isinstance(failure, RunCommandResult):+ return failure+ # How the CLI reports a dead session: non-zero, nothing on stdout, reason on stderr.+ return RunCommandResult(stdout="", stderr=failure, returncode=1)+++def _rendered_chain(error: BaseException) -> list[BaseException]:+ """The exceptions a traceback shows for `error`: causes, and contexts not suppressed by `from None`."""+ chain: list[BaseException] = []+ link: BaseException | None = error+ while link is not None:+ chain.append(link)+ link = link.__cause__ or (None if link.__suppress_context__ else link.__context__)+ return chain++@pytest.fixturedef cli(monkeypatch: pytest.MonkeyPatch) -> FakeVaultCli:fake = FakeVaultCli()@@ -118,7 +188,12 @@ def _identity_of(master_password: str = "master-password") -> "bitwarden_module.)-async def _fetch(item_id: str = ITEM_ID, master_password: str = "master-password") -> dict[str, str]:+async def _fetch(+ item_id: str = ITEM_ID,+ master_password: str = "master-password",+ email: str | None = None,+ max_retries: int = bitwarden_module.settings.BITWARDEN_MAX_RETRIES,+) -> dict[str, str]:return await BitwardenService.get_secret_value_from_url(client_id="client-id",client_secret="client-secret",@@ -126,9 +201,32 @@ async def _fetch(item_id: str = ITEM_ID, master_password: str = "master-passwordbw_organization_id="org-id",bw_collection_ids=None,item_id=item_id,+ email=email,+ max_retries=max_retries,+ )+++def _login_parameter() -> BitwardenLoginCredentialParameter:+ now = datetime.now(UTC)+ return BitwardenLoginCredentialParameter(+ key="portal_login",+ bitwarden_login_credential_parameter_id="blc_1",+ workflow_id="wf_test",+ bitwarden_client_id_aws_secret_key="unused",+ bitwarden_client_secret_aws_secret_key="unused",+ bitwarden_master_password_aws_secret_key="unused",+ url_parameter_key="target_url",+ created_at=now,+ modified_at=now,)+async def _recorded_fetch(email: str | None = None) -> None:+ """A read wrapped the way a run wraps it, so it logs "Run credential fetch finished"."""+ async with record_credential_fetch(_login_parameter(), CredentialVaultType.BITWARDEN):+ await _fetch(email=email)++@pytest.mark.asyncioasync def test_a_batch_of_runs_for_one_organization_pays_a_single_login(cli: FakeVaultCli) -> None:"""AC: 100 runs against one organization inside three minutes make <=1 identity call per run."""@@ -137,12 +235,265 @@ async def test_a_batch_of_runs_for_one_organization_pays_a_single_login(cli: Fakassert all(result[BitwardenConstants.PASSWORD] == "hunter2" for result in results)assert cli.steps.count("login") == 1assert cli.steps.count("unlock") == 1- assert cli.steps.count("sync") == 1+ # `bw login` already ran a forced full sync, so a fresh session does not pay for another.+ assert cli.steps.count("sync") == 0# Only the per-item decrypt is paid per run, and nothing logs the batch back out mid-flight.assert cli.steps.count("get") == 100assert "logout" not in cli.steps+async def test_a_cold_email_read_logs_in_and_reads_with_the_key_the_login_printed(cli: FakeVaultCli) -> None:+ """An email login unlocks the vault and prints its session key, so unlock and sync are both redundant."""+ result = await _fetch(email="[email protected]")++ assert result[BitwardenConstants.PASSWORD] == "hunter2"+ assert cli.steps == ["login", "get"]+ assert cli.session_args == [("get", LOGIN_SESSION_KEY)]+++ "login_stdout",+ [API_KEY_LOGIN_OUTPUT, _session_key_banner("You are logged in!", LOGIN_SESSION_KEY)],+ ids=["no-key", "noninteractive-key"],+)+async def test_a_cold_api_key_read_still_unlocks(cli: FakeVaultCli, login_stdout: str) -> None:+ """An API-key login leaves the vault locked; non-interactively it still prints a key, which unlocks nothing."""+ cli.login_stdout = login_stdout++ result = await _fetch()++ assert result[BitwardenConstants.PASSWORD] == "hunter2"+ assert cli.steps == ["login", "unlock", "get"]+ assert cli.session_args == [("get", UNLOCK_SESSION_KEY)]++[email protected]("locked_read", [VAULT_IS_LOCKED, MASTER_PASSWORD_PROMPT], ids=["noninteractive", "prompt"])[email protected]("path", ["get", "list"])+async def test_a_login_key_that_unlocks_nothing_costs_one_relogin_that_unlocks(+ cli: FakeVaultCli, locked_read: RunCommandResult, path: str+) -> None:+ """Left unrepaired, every read for this identity on this pod fails until the session expires."""+ if path == "get":+ cli.get_failures = [locked_read]+ result = await _fetch(email="[email protected]")+ else:+ cli.list_failures = [locked_read]+ result = await _fetch_by_url(email="[email protected]")++ assert result[BitwardenConstants.PASSWORD] == "hunter2"+ assert cli.steps == ["login", path, "login", "unlock", path]+ assert cli.session_args == [(path, LOGIN_SESSION_KEY), (path, UNLOCK_SESSION_KEY)]+++async def test_an_email_login_that_prints_no_session_key_falls_back_to_unlock(cli: FakeVaultCli) -> None:+ """A CLI version whose login output changes shape must cost an unlock, not the read."""+ cli.login_stdout = "You are logged in!"++ result = await _fetch(email="[email protected]")++ assert result[BitwardenConstants.PASSWORD] == "hunter2"+ assert cli.steps == ["login", "unlock", "get"]+ assert cli.session_args == [("get", UNLOCK_SESSION_KEY)]+++async def test_a_login_with_unexpected_stderr_never_reveals_the_session_key(+ cli: FakeVaultCli, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The login succeeded and printed its key on stdout; only stderr is fit for the error and the logs."""+ monkeypatch.setattr(bitwarden_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))+ cli.login_stderr = "Something the CLI has never said before.\n"++ with capture_logs() as logs, pytest.raises(bitwarden_module.BitwardenListItemsError) as excinfo:+ await _fetch(email="[email protected]", max_retries=2)++ assert "Something the CLI has never said before." in str(excinfo.value)+ assert all(LOGIN_SESSION_KEY not in str(link) for link in _rendered_chain(excinfo.value))+ assert LOGIN_SESSION_KEY not in json.dumps(logs, default=str)+++async def test_a_login_whose_output_is_unrecognized_never_reveals_it(+ cli: FakeVaultCli, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Output that does not say "You are logged in!" can still carry the session key."""+ monkeypatch.setattr(bitwarden_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))+ cli.login_stdout = _session_key_banner("A login banner the CLI has never printed.", LOGIN_SESSION_KEY)++ with capture_logs() as logs, pytest.raises(bitwarden_module.BitwardenListItemsError) as excinfo:+ await _fetch(email="[email protected]", max_retries=2)++ assert "BitwardenLoginError" in str(excinfo.value)+ assert all(LOGIN_SESSION_KEY not in str(link) for link in _rendered_chain(excinfo.value))+ assert LOGIN_SESSION_KEY not in json.dumps(logs, default=str)+++ "stdout",+ ['[{"login": {"password": "hunter2"', '{"login": {"password": "hunter2"}}'],+ ids=["truncated", "not-a-list"],+)[email protected]("parser", ["list", "get"])+def test_output_that_is_not_the_expected_json_never_reaches_the_error(stdout: str, parser: str) -> None:+ """The stdout is the decrypted vault: neither the message nor a chained parse error may carry it."""+ result = RunCommandResult(stdout=stdout, stderr="", returncode=0)++ with pytest.raises((bitwarden_module.BitwardenListItemsError, BitwardenGetItemError)) as excinfo:+ if parser == "list":+ BitwardenService._parse_listed_items(result)+ else:+ BitwardenService._parse_fetched_item(result, ITEM_ID)++ for link in _rendered_chain(excinfo.value):+ assert "hunter2" not in str(link)+ assert "hunter2" not in str(getattr(link, "doc", ""))+++async def test_a_busy_session_past_its_lifetime_is_replaced_by_a_fresh_login(+ cli: FakeVaultCli, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A session that never sits idle long enough to be reclaimed is still retired once it is old."""+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_SESSION_MAX_LIFETIME_SECONDS", 3600)+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_SESSION_SYNC_INTERVAL_SECONDS", 3600)+ await _fetch()+ old = bitwarden_module._cli_sessions._sessions[_identity_of().fingerprint]+ old.created_at -= 3600 * (1 + bitwarden_module._SESSION_LIFETIME_JITTER) + 1+ cli.calls.clear()++ result = await _fetch()++ assert result[BitwardenConstants.PASSWORD] == "hunter2"+ assert cli.steps == ["login", "unlock", "get"]+ assert old.retired is True+ assert not os.path.isdir(old.appdata_dir)+++async def test_an_expiring_session_hands_over_without_waiting_for_its_readers(cli: FakeVaultCli) -> None:+ """The reader that notices the expiry logs in at once; readers still on the old session finish there."""+ await _fetch()+ old = bitwarden_module._cli_sessions._sessions[_identity_of().fingerprint]+ old.created_at -= bitwarden_module.settings.BITWARDEN_SESSION_MAX_LIFETIME_SECONDS * 2+ cli.calls.clear()++ async with old.in_use():+ # Another reader is mid-sync on the old session, holding its lock.+ async with old.lock:+ result = await asyncio.wait_for(_fetch(), timeout=5)+ assert old.session_key is not None+ assert os.path.isdir(old.appdata_dir)++ assert result[BitwardenConstants.PASSWORD] == "hunter2"+ assert cli.steps == ["login", "unlock", "get"]+ assert not os.path.isdir(old.appdata_dir)+++def test_sessions_logged_in_together_do_not_all_expire_together(monkeypatch: pytest.MonkeyPatch) -> None:+ """A burst's sessions would otherwise all pay a cold login at the same moment."""+ monkeypatch.setattr(bitwarden_module, "random", random.Random(0))+ lifetime = bitwarden_module.settings.BITWARDEN_SESSION_MAX_LIFETIME_SECONDS+ jitter = bitwarden_module._SESSION_LIFETIME_JITTER+ sessions = [bitwarden_module._CliSession(_identity_of(), f"/unused/{index}") for index in range(20)]++ expired_at_the_cap = [session.outlived(session.created_at + lifetime) for session in sessions]++ assert any(expired_at_the_cap) and not all(expired_at_the_cap)+ assert not any(session.outlived(session.created_at + lifetime * (1 - jitter) - 1) for session in sessions)+ assert all(session.outlived(session.created_at + lifetime * (1 + jitter) + 1) for session in sessions)+++ "rejection",+ [+ 'Syncing failed: {"response":{"error":"invalid_grant"},"statusCode":400}',+ 'Syncing failed: {"response":null,"statusCode":401}',+ 'Syncing failed: {"response": null, "statusCode": 401}',+ "You are not logged in.",+ ],+ ids=["refresh-token-rejected", "unauthorized", "unauthorized-spaced", "logged-out"],+)+async def test_a_refresh_rejected_for_auth_logs_in_again_exactly_once(+ cli: FakeVaultCli, monkeypatch: pytest.MonkeyPatch, rejection: str+) -> None:+ """The CLI logs itself out on a rejected login, so the cached copy must not be served as if fresh."""+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_SESSION_SYNC_INTERVAL_SECONDS", 0)+ await _fetch(email="[email protected]")+ cli.calls.clear()+ cli.sync_failures = [rejection]++ result = await _fetch(email="[email protected]")++ assert result[BitwardenConstants.PASSWORD] == "hunter2"+ assert cli.steps.count("login") == 1+ # The repair login unlocks explicitly rather than trust the login's key a second time.+ assert cli.steps == ["sync", "login", "unlock", "get"]+++async def test_the_run_fetch_line_says_whether_a_read_logged_in(cli: FakeVaultCli) -> None:+ with capture_logs() as logs:+ for _ in range(2):+ await _recorded_fetch(email="[email protected]")+ async with record_credential_fetch(_login_parameter(), CredentialVaultType.BITWARDEN):+ pass++ cold, warm, no_session = (log for log in logs if log["event"] == RUN_CREDENTIAL_FETCH_FINISHED_MESSAGE)+ assert cold["session_reused"] is False+ assert isinstance(cold["login_seconds"], float)+ assert (warm["session_reused"], warm["login_seconds"]) == (True, None)+ assert isinstance(warm["lock_wait_seconds"], float)+ assert (no_session["session_reused"], no_session["login_seconds"], no_session["lock_wait_seconds"]) == (+ None,+ None,+ None,+ )+++class _ManualClock:+ def __init__(self) -> None:+ self.now = 1_000.0++ def monotonic(self) -> float:+ return self.now+++async def test_reads_that_wait_out_another_reads_login_are_cold_and_say_how_long_they_queued(+ cli: FakeVaultCli, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A burst's first read logs in while the rest queue behind it; none of them found a warm session."""+ clock = _ManualClock()+ monkeypatch.setattr(bitwarden_module, "time", clock)++ async def a_thirty_second_login() -> None:+ for _ in range(10):+ # Lets every other read in the burst reach the session lock before the login finishes.+ await asyncio.sleep(0)+ clock.now += 30++ cli.on_login = a_thirty_second_login++ with capture_logs() as logs:+ await asyncio.gather(*(_recorded_fetch(email="[email protected]") for _ in range(5)))++ lines = [log for log in logs if log["event"] == RUN_CREDENTIAL_FETCH_FINISHED_MESSAGE]+ assert cli.steps.count("login") == 1+ assert [line["session_reused"] for line in lines] == [False] * 5+ assert sorted((line["lock_wait_seconds"], line["login_seconds"] or 0.0) for line in lines) == [+ (0.0, 30.0),+ (30.0, 0.0),+ (30.0, 0.0),+ (30.0, 0.0),+ (30.0, 0.0),+ ]++@pytest.mark.asyncioasync def test_a_warm_run_only_decrypts_the_one_item_it_names(cli: FakeVaultCli) -> None:await _fetch()@@ -202,7 +553,7 @@ async def test_an_expired_session_is_re_established_before_the_run_fails(cli: Faresult = await _fetch()assert result[BitwardenConstants.PASSWORD] == "hunter2"- assert cli.steps == ["get", "login", "unlock", "sync", "get"]+ assert cli.steps == ["get", "login", "unlock", "get"]@pytest.mark.asyncio@@ -446,6 +797,8 @@ async def test_browsing_a_vault_always_syncs_but_reuses_the_login(cli: FakeVault)await list_overviews()+ # The sync inside `bw login` swallows its own failure, so even a fresh login pays for one that reports it.+ assert cli.steps == ["login", "sync", "list"]cli.calls.clear()await list_overviews()@@ -496,7 +849,7 @@ async def test_concurrent_cli_commands_are_bounded(monkeypatch: pytest.MonkeyPatassert peak <= 2-async def _fetch_by_url(master_password: str = "master-password") -> dict[str, str]:+async def _fetch_by_url(master_password: str = "master-password", email: str | None = None) -> dict[str, str]:return await BitwardenService.get_secret_value_from_url(client_id="client-id",client_secret="client-secret",@@ -504,6 +857,7 @@ async def _fetch_by_url(master_password: str = "master-password") -> dict[str, sbw_organization_id="org-id",bw_collection_ids=None,url="https://example.com/login",+ email=email,)@@ -517,7 +871,7 @@ async def test_an_expired_session_is_re_established_on_the_url_search_path(cli:result = await _fetch_by_url()assert result[BitwardenConstants.PASSWORD] == "hunter2"- assert cli.steps == ["list", "login", "unlock", "sync", "list"]+ assert cli.steps == ["list", "login", "unlock", "list"]@pytest.mark.asyncio@@ -541,7 +895,7 @@ async def test_an_expired_session_is_re_established_on_the_identity_path(cli: Faresult = await fetch_identity()assert result == {"first_name": "Alice"}- assert cli.steps == ["list", "login", "unlock", "sync", "list"]+ assert cli.steps == ["list", "login", "unlock", "list"]@pytest.mark.asyncio@@ -661,7 +1015,7 @@ async def test_an_expired_session_is_re_established_on_the_credit_card_path(cli:result = await _fetch_card()assert result[BitwardenConstants.CREDIT_CARD_NUMBER] == "4111111111111111"- assert cli.steps == ["get", "login", "unlock", "sync", "get"]+ assert cli.steps == ["get", "login", "unlock", "get"]@pytest.mark.asynciodiff --git a/tests/unit/test_context_manager.py b/tests/unit/test_context_manager.pyindex 27eb07da0..602dc19b8 100644--- a/tests/unit/test_context_manager.py+++ b/tests/unit/test_context_manager.py@@ -265,6 +265,9 @@ _FETCH_LINE_FIELDS = {"outcome","failure_type","duration_seconds",+ "session_reused",+ "login_seconds",+ "lock_wait_seconds",}