Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(vault): daemon protocol v2 contexts (#849)
Call Whiteb1eac72ecf37
diff --git a/storage/vault_service.py b/storage/vault_service.pyindex ad9433ba2..4959498fc 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -26,6 +26,7 @@ from typing import Anyfrom urllib.parse import urlsplitfrom sqlalchemy import func, or_, select+from sqlalchemy.dialects.sqlite import insert as sqlite_insertfrom sqlalchemy.engine import Connectionfrom sqlalchemy.exc import IntegrityError@@ -33,6 +34,7 @@ from storage import vault_crypto, vault_webauthnfrom storage.models import (agent_sessions,scopes,+ state_meta,vault_audit,vault_auth_factors,vault_grants,@@ -46,17 +48,17 @@ from storage.vault_crypto import Sealedlogger = logging.getLogger(__name__)SKILL_TAG_PREFIX = "skill:"-DEFAULT_ENV_GRANT_TTL_SECONDS = 300-DEFAULT_TAG_GRANT_TTL_SECONDS = 900+VAULT_SETTINGS_META_KEY = "vault_settings"+DEFAULT_UNLOCK_WINDOW_SECONDS = 600+UNLOCK_WINDOW_OPTIONS_SECONDS = (300, 600, 1800)+GRANT_DURATION_ONE_TIME = "one-time"+ONE_TIME_GRANT_TTL_SECONDS = 60+DEFAULT_GRANT_TTL_SECONDS = 300+GRANT_TTL_OPTIONS_SECONDS = (300, 900)+LAST_GRANT_TTL_OPTIONS = (GRANT_DURATION_ONE_TIME, *GRANT_TTL_OPTIONS_SECONDS)DEFAULT_AUTHZ_CHALLENGE_TTL_SECONDS = 120DEFAULT_REQUEST_TTL_SECONDS = 30 * 60AUTH_FACTOR_REGISTRATION_AUTHZ_OPERATION = "authorize_webauthn_factor_registration"-DEFAULT_GRANT_TTL_SECONDS = {- "env": DEFAULT_ENV_GRANT_TTL_SECONDS,- "tag": DEFAULT_TAG_GRANT_TTL_SECONDS,- "skill": DEFAULT_TAG_GRANT_TTL_SECONDS,-}-GRANT_TTL_OPTIONS_SECONDS = (300, 900, 3600)GRANT_PURPOSES = {"run", "fetch", "inject"}SUPPORTED_SIGNATURE_SCHEMES = {"ecdsa-secp256k1-recoverable",@@ -302,6 +304,118 @@ def _id(prefix: str) -> str:return f"{prefix}_{uuid.uuid4().hex[:12]}"+def _default_vault_settings() -> dict[str, Any]:+ return {+ "unlock_window_seconds": DEFAULT_UNLOCK_WINDOW_SECONDS,+ "strict_approvals": False,+ "last_grant_ttl": DEFAULT_GRANT_TTL_SECONDS,+ }+++def _normalize_unlock_window_seconds(value: Any) -> int:+ try:+ seconds = int(value)+ except (TypeError, ValueError) as exc:+ raise VaultServiceError("unlock_window_seconds must be one of 300, 600, or 1800") from exc+ if seconds not in UNLOCK_WINDOW_OPTIONS_SECONDS:+ raise VaultServiceError("unlock_window_seconds must be one of 300, 600, or 1800")+ return seconds+++def normalize_grant_duration(value: Any | None, *, default: Any | None = None) -> dict[str, Any]:+ raw = default if value is None else value+ if raw is None:+ raw = DEFAULT_GRANT_TTL_SECONDS+ if isinstance(raw, str):+ normalized = raw.strip().lower().replace("_", "-")+ if normalized == GRANT_DURATION_ONE_TIME:+ return {+ "last_grant_ttl": GRANT_DURATION_ONE_TIME,+ "ttl_seconds": ONE_TIME_GRANT_TTL_SECONDS,+ "one_shot": True,+ }+ try:+ raw = int(normalized)+ except ValueError as exc:+ raise InvalidGrantError("grant duration must be one-time, 300, or 900 seconds") from exc+ try:+ ttl = int(raw)+ except (TypeError, ValueError) as exc:+ raise InvalidGrantError("grant duration must be one-time, 300, or 900 seconds") from exc+ if ttl not in GRANT_TTL_OPTIONS_SECONDS:+ raise InvalidGrantError("grant duration must be one-time, 300, or 900 seconds")+ return {"last_grant_ttl": ttl, "ttl_seconds": ttl, "one_shot": False}+++def _normalize_last_grant_ttl(value: Any) -> str | int:+ return normalize_grant_duration(value)["last_grant_ttl"]+++def _normalize_strict_approvals(value: Any) -> bool:+ if type(value) is not bool:+ raise VaultServiceError("strict_approvals must be a boolean")+ return value+++def _normalize_vault_settings(raw: Any) -> dict[str, Any]:+ settings = _default_vault_settings()+ if isinstance(raw, dict):+ if "unlock_window_seconds" in raw:+ settings["unlock_window_seconds"] = _normalize_unlock_window_seconds(raw["unlock_window_seconds"])+ if "strict_approvals" in raw:+ settings["strict_approvals"] = _normalize_strict_approvals(raw["strict_approvals"])+ if "last_grant_ttl" in raw:+ settings["last_grant_ttl"] = _normalize_last_grant_ttl(raw["last_grant_ttl"])+ return settings+++def get_vault_settings(conn: Connection) -> dict[str, Any]:+ raw = conn.execute(+ select(state_meta.c.value_json).where(state_meta.c.key == VAULT_SETTINGS_META_KEY)+ ).scalar_one_or_none()+ return _normalize_vault_settings(_loads(raw))+++def save_vault_settings(conn: Connection, payload: dict[str, Any]) -> dict[str, Any]:+ if not isinstance(payload, dict):+ raise VaultServiceError("vault settings payload must be an object")+ current = get_vault_settings(conn)+ updates: dict[str, Any] = {}+ if "unlock_window_seconds" in payload:+ updates["unlock_window_seconds"] = _normalize_unlock_window_seconds(payload["unlock_window_seconds"])+ if "strict_approvals" in payload:+ updates["strict_approvals"] = _normalize_strict_approvals(payload["strict_approvals"])+ if "last_grant_ttl" in payload:+ updates["last_grant_ttl"] = _normalize_last_grant_ttl(payload["last_grant_ttl"])+ next_settings = _normalize_vault_settings({**current, **updates})+ value_json = json.dumps(next_settings, sort_keys=True)+ now = _now()+ stmt = sqlite_insert(state_meta).values(+ key=VAULT_SETTINGS_META_KEY,+ value_json=value_json,+ updated_at=now,+ )+ conn.execute(+ stmt.on_conflict_do_update(+ index_elements=[state_meta.c.key],+ set_={+ "value_json": value_json,+ "updated_at": now,+ },+ )+ )+ return next_settings+++def vault_session_policy(settings: dict[str, Any] | None = None) -> dict[str, Any]:+ normalized = _normalize_vault_settings(settings or {})+ return {+ "windowSeconds": normalized["unlock_window_seconds"],+ "strictApprovals": normalized["strict_approvals"],+ "parentValueSealAllowed": True,+ }++def _secret_name_case_key(name: str) -> str:# Secret names are ASCII shell identifiers, so SQL lower() and Python lower()# have the same case-folding behavior for the enforced domain.@@ -1394,11 +1508,7 @@ def _ttl_cap_from_grant_option(option: dict[str, Any], selector: dict[str, Any])ttl_options.append(value)if ttl_options:return max(ttl_options)- try:- default = int(option.get("default_ttl_seconds") or 0)- except (TypeError, ValueError):- default = 0- return max(1, default or _selector_ttl_seconds(selector))+ return max(GRANT_TTL_OPTIONS_SECONDS)def _request_grant_option(row: dict[str, Any]) -> RequestGrantOption:@@ -2384,6 +2494,14 @@ def get_protected_envelope(conn: Connection, name: str) -> Sealed:return _row_sealed(row)+def get_protected_record_envelope(conn: Connection, name: str) -> Sealed:+ row = _require_row(conn, name)+ if row.get("protection") != "protected":+ raise UnsupportedProtectionError(f"{name} is standard-tier")+ _reject_keypair_value_delivery(row, name)+ return _row_sealed(row)++def record_proxy_use(conn: Connection, name: str, *, requester: Any = None, delivery: Any = None) -> None:"""Bump usage + write a value-free ``proxied`` audit row after a brokered request."""row = _require_row(conn, name)@@ -2413,6 +2531,24 @@ def record_signing_use(audit(conn, "signed", secret_name=name, requester=requester, delivery=delivery, request_id=request_id)+def record_reveal_use(+ conn: Connection,+ name: str,+ *,+ requester: Any = None,+ delivery: Any = None,+ request_id: str | None = None,+) -> None:+ """Bump revealed secret usage + write a value-free ``revealed`` audit row."""+ _require_row(conn, name)+ conn.execute(+ vault_secrets.update()+ .where(vault_secrets.c.name == name)+ .values(last_used_at=_now(), use_count=vault_secrets.c.use_count + 1)+ )+ audit(conn, "revealed", secret_name=name, requester=requester, delivery=delivery, request_id=request_id)++def get_envelopes(conn: Connection, names: list[str]) -> dict[str, Sealed]:"""Return the stored envelopes for the requested secrets (standard tier; no decrypt).@@ -2597,15 +2733,6 @@ def _source_selector_payload(source_selector: dict[str, Any] | None = None) -> dreturn payload or {"env": [], "tags": []}-def _selector_ttl_seconds(source_selector: dict[str, Any]) -> int:- tags = source_selector.get("tags")- if isinstance(tags, list) and tags:- if any(isinstance(tag, str) and tag.startswith(SKILL_TAG_PREFIX) for tag in tags):- return DEFAULT_GRANT_TTL_SECONDS["skill"]- return DEFAULT_GRANT_TTL_SECONDS["tag"]- return DEFAULT_GRANT_TTL_SECONDS["env"]--def _parse_env_selector(spec: str) -> tuple[str, str]:raw = spec.strip()if not raw:@@ -2749,6 +2876,7 @@ def request_grantable_member_metas(conn: Connection, request_id: str) -> list[didef _grant_option(+ conn: Connection,rows: list[dict[str, Any]],*,source_selector: dict[str, Any],@@ -2756,13 +2884,17 @@ def _grant_option(one_shot: bool,) -> dict[str, Any]:members = [str(row["name"]) for row in rows]- default_ttl_seconds = _selector_ttl_seconds(source_selector)+ settings = get_vault_settings(conn)+ default_duration = GRANT_DURATION_ONE_TIME if one_shot else settings["last_grant_ttl"]+ normalized_default_duration = normalize_grant_duration(default_duration)option = {"grant_id": _id("vgr"),"source_selector": source_selector,"purpose": purpose,- "default_ttl_seconds": default_ttl_seconds,- "ttl_options_seconds": [seconds for seconds in GRANT_TTL_OPTIONS_SECONDS if seconds >= default_ttl_seconds],+ "default_grant_duration": normalized_default_duration["last_grant_ttl"],+ "grant_duration_options": list(LAST_GRANT_TTL_OPTIONS),+ "default_ttl_seconds": normalized_default_duration["ttl_seconds"],+ "ttl_options_seconds": list(GRANT_TTL_OPTIONS_SECONDS),"session_binding_default": True,"member_count": len(members),"member_snapshot": members,@@ -2792,7 +2924,7 @@ def approval_card(rows = member_rows if member_rows is not None else ([_require_row(conn, secret_name)] if secret_name else [])default_selector = {"env": [secret_name]} if secret_name else Noneselector = _source_selector_payload(source_selector or default_selector)- grant_options = [_grant_option(rows, source_selector=selector, purpose=purpose, one_shot=one_shot)] if grantable and rows else []+ grant_options = [_grant_option(conn, rows, source_selector=selector, purpose=purpose, one_shot=one_shot)] if grantable and rows else []protected_names = [str(row["name"]) for row in rows if row.get("protection") == "protected"]card = {"card_type": "approval",@@ -3031,6 +3163,101 @@ def get_request(conn: Connection, request_id: str, *, audience: str | None = REQreturn _request_row_payload(row_dict, conn=conn, audience=audience)+def set_request_operation_context(+ conn: Connection,+ request_id: str,+ operation_context: dict[str, Any],+ *,+ audience: str | None = REQUEST_AUDIENCE_UI,+) -> dict[str, Any]:+ row_dict = _load_request_row(conn, request_id)+ _, delivery = _request_json_payloads(row_dict)+ delivery_payload = dict(delivery) if isinstance(delivery, dict) else {}+ delivery_payload["operation_context"] = operation_context+ card = delivery_payload.get("card")+ if isinstance(card, dict):+ next_card = dict(card)+ next_card["operation_context"] = operation_context+ delivery_payload["card"] = next_card+ conn.execute(+ vault_requests.update()+ .where(vault_requests.c.id == request_id)+ .values(delivery=json.dumps(delivery_payload))+ )+ updated = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()+ return _request_row_payload(dict(updated), conn=conn, audience=audience)+++def _agent_binding_record_item_names(record: dict[str, Any]) -> set[str]:+ items = record.get("items")+ if not isinstance(items, list):+ return set()+ return {str(item.get("name") or "") for item in items if isinstance(item, dict) and item.get("name")}+++def _agent_binding_record_superseded(existing_record: dict[str, Any], new_record: dict[str, Any]) -> bool:+ existing_names = _agent_binding_record_item_names(existing_record)+ new_names = _agent_binding_record_item_names(new_record)+ if not existing_names or not new_names:+ return False+ existing_grant_id = str(existing_record.get("grant_id") or "")+ new_grant_id = str(new_record.get("grant_id") or "")+ if existing_grant_id and new_grant_id and existing_grant_id != new_grant_id:+ return False+ return existing_names.issubset(new_names)+++def _agent_binding_approval_record_cap(row_dict: dict[str, Any], new_record: dict[str, Any]) -> int:+ _, delivery = _request_json_payloads(row_dict)+ delivery_payload = delivery if isinstance(delivery, dict) else {}+ card = delivery_payload.get("card") if isinstance(delivery_payload.get("card"), dict) else {}+ grant_options = card.get("grant_options") if isinstance(card, dict) else []+ member_count = 0+ if isinstance(grant_options, list):+ for option in grant_options:+ if not isinstance(option, dict):+ continue+ members = option.get("member_snapshot")+ if isinstance(members, list):+ member_count = max(member_count, len([name for name in members if isinstance(name, str) and name]))+ return max(1, member_count, len(_agent_binding_record_item_names(new_record)))+++def record_request_agent_binding_approvals(+ conn: Connection,+ request_id: str,+ record: dict[str, Any],+ *,+ max_records: int | None = None,+) -> dict[str, Any]:+ if not isinstance(record, dict):+ raise InvalidRequestError("agent binding approval record must be an object")+ row_dict = _load_request_row(conn, request_id)+ _, delivery = _request_json_payloads(row_dict)+ delivery_payload = dict(delivery) if isinstance(delivery, dict) else {}+ records = delivery_payload.get("agent_binding_approvals")+ if not isinstance(records, list):+ records = []+ records = [+ existing+ for existing in records+ if isinstance(existing, dict) and not _agent_binding_record_superseded(existing, record)+ ]+ records.append(record)+ if max_records is not None:+ records = records[-max(1, max_records) :]+ else:+ records = records[-_agent_binding_approval_record_cap(row_dict, record) :]+ delivery_payload["agent_binding_approvals"] = records+ conn.execute(+ vault_requests.update()+ .where(vault_requests.c.id == request_id)+ .values(delivery=json.dumps(delivery_payload))+ )+ updated = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()+ return _request_row_payload(dict(updated), conn=conn, audience=REQUEST_AUDIENCE_AGENT)++def claim_sign_request(conn: Connection,request_id: str,@@ -3577,6 +3804,8 @@ def create_grant(purpose: str = "run",session_id: str | None = None,ttl_seconds: int | None = None,+ grant_duration: Any | None = None,+ expires_at: str | None = None,request_id: str | None = None,inherit_request_session: bool = True,expected_member_names: set[str] | list[str] | tuple[str, ...] | None = None,@@ -3608,8 +3837,33 @@ def create_grant(if expected_member_names is not None and set(members) != set(expected_member_names):raise InvalidGrantError("resident agent DEKs must match the approved grant members")live_rows_by_name = {row["name"]: row for row in live_rows}- one_shot_grant = approval.one_shot+ remember_duration = grant_duration is not None or ttl_seconds is not None+ default_duration = GRANT_DURATION_ONE_TIME if approval.one_shot else get_vault_settings(conn)["last_grant_ttl"]+ duration = normalize_grant_duration(grant_duration, default=default_duration)+ if ttl_seconds is not None:+ if grant_duration is not None:+ raise InvalidGrantError("use grant_duration or ttl_seconds, not both")+ duration = normalize_grant_duration(ttl_seconds)+ one_shot_grant = approval.one_shot or bool(duration["one_shot"])+ if one_shot_grant:+ requested_session_id = _request_session_id(_load_request_row(conn, request_id))+ if requested_session_id:+ if session_id and session_id != requested_session_id:+ raise InvalidRequestError("grant session does not match the approval request")+ session_id = requested_session_idresident_cache_ready = cache_ready and any(live_rows_by_name[name].get("protection") == "protected" for name in members)+ ttl = int(duration["ttl_seconds"])+ ttl = max(1, min(ttl, approval.ttl_cap_seconds))+ now_dt = datetime.now(timezone.utc)+ expires_at_dt = now_dt + timedelta(seconds=ttl)+ if expires_at is not None:+ issued_expires_at = _parse_iso_datetime(expires_at)+ if issued_expires_at is None:+ raise InvalidGrantError("grant binding expiry is invalid")+ if issued_expires_at <= now_dt:+ raise InvalidGrantError("grant binding has expired")+ expires_at_dt = min(expires_at_dt, issued_expires_at)+ expires_at = expires_at_dt.isoformat()decided_at = _now()claim = conn.execute(vault_requests.update()@@ -3622,10 +3876,6 @@ def create_grant()if claim.rowcount != 1:raise InvalidRequestError("grant approval request is not pending")- ttl = int(ttl_seconds or _selector_ttl_seconds(selector))- ttl = max(1, min(ttl, approval.ttl_cap_seconds))- now_dt = datetime.now(timezone.utc)- expires_at = (now_dt + timedelta(seconds=ttl)).isoformat()grant_id = approval.grant_idgrant_values = {"member_snapshot": json.dumps(members),@@ -3680,10 +3930,17 @@ def create_grant(conn,"granted",requester={"session_id": session_id} if session_id else None,- delivery={"source_selector": selector, "purpose": purpose, "member_count": len(members)},+ delivery={+ "source_selector": selector,+ "purpose": purpose,+ "member_count": len(members),+ "grant_duration": duration["last_grant_ttl"],+ },request_id=request_id,grant_id=grant_id,)+ if remember_duration:+ save_vault_settings(conn, {"last_grant_ttl": duration["last_grant_ttl"]})row = conn.execute(select(vault_grants).where(vault_grants.c.id == grant_id)).mappings().one()if not one_shot_grant:_approve_sibling_access_requests_for_grant(@@ -3778,6 +4035,7 @@ def mark_grant_agent_ready(grant_id: str,*,ttl_seconds: int | None = None,+ expires_at: str | None = None,cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,) -> dict[str, Any]:row = conn.execute(@@ -3795,7 +4053,14 @@ def mark_grant_agent_ready(ready_at_dt = datetime.now(timezone.utc)ready_at = ready_at_dt.isoformat()values: dict[str, Any] = {"agent_ready": 1, "agent_ready_at": ready_at}- if ttl_seconds is not None:+ if expires_at is not None:+ ready_expires_at = _parse_iso_datetime(expires_at)+ if ready_expires_at is None:+ raise InvalidGrantError("grant ready expiry is invalid")+ if ready_expires_at <= ready_at_dt:+ raise GrantNotActiveError(grant_id)+ values["expires_at"] = ready_expires_at.isoformat()+ elif ttl_seconds is not None:ttl = max(1, int(ttl_seconds))values["expires_at"] = (ready_at_dt + timedelta(seconds=ttl)).isoformat()result = conn.execute(diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex a95459bea..d2ff01c36 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -24,6 +24,8 @@ from storage.vault_crypto import Sealedfrom tests.vault_webauthn_helpers import WebAuthnTestCredentialfrom vibe import api+TEST_AGENT_PUBKEY = {"public_key": "pk", "fingerprint": "fp"}+def _sealed(suffix: str = "1") -> Sealed:return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")@@ -128,6 +130,60 @@ def _assert_no_unlock_material(payload: object) -> None:assert "wm-protected" not in encoded+def _payload_keys(payload: object) -> set[str]:+ if isinstance(payload, dict):+ keys = {str(key) for key in payload}+ for value in payload.values():+ keys.update(_payload_keys(value))+ return keys+ if isinstance(payload, list):+ keys: set[str] = set()+ for item in payload:+ keys.update(_payload_keys(item))+ return keys+ return set()+++def _verified_signed_context(context: dict) -> dict:+ from cryptography.hazmat.primitives.asymmetric import ed25519++ unsigned = dict(context)+ signature = unsigned.pop("signature")+ root_key = api.get_vault_sandbox_root_metadata()["root_metadata"]["daemon"]["verificationKeys"][0]+ public_key = ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(root_key["publicKey"]))+ public_key.verify(+ base64.b64decode(signature["value"]),+ json.dumps(unsigned, sort_keys=True, separators=(",", ":")).encode("utf-8"),+ )+ assert signature["alg"] == "ed25519"+ assert signature["keyId"] == root_key["keyId"]+ return unsigned+++def _agent_dek_blindbox(enc: str = "enc", ct: str = "ct") -> dict:+ return {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": enc, "ct": ct}+++def _issued_agent_dek_payload(+ request_id: str,+ *,+ grant_duration: str | int = 300,+ blindboxes: dict[str, dict] | None = None,+) -> dict:+ issued = api.create_vault_agent_bindings_batch({"request_id": request_id, "grant_duration": grant_duration})+ return {+ "agent_pubkey": issued["agent_pubkey"],+ "deks": [+ {+ "name": item["name"],+ "dek_blindbox": (blindboxes or {}).get(item["name"], _agent_dek_blindbox()),+ "approval": item["approval"],+ }+ for item in issued["items"]+ ],+ }++def _auth_factor_for_credential(credential: WebAuthnTestCredential) -> dict:with api._vault_engine().connect() as conn:row = conn.execute(@@ -161,6 +217,7 @@ def _establish_protected_secret_with_factor(@pytest.fixturedef avault_p2(monkeypatch):monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", lambda: dict(TEST_AGENT_PUBKEY))def test_create_list_delete_roundtrip(monkeypatch):@@ -471,20 +528,14 @@ def test_update_secret_metadata_does_not_stale_pending_protected_grant(monkeypathydrated = api.get_vault_request(request_id, audience=vault_service.REQUEST_AUDIENCE_UI)unlock_material = hydrated["request"]["card"]["grant_options"][0]["unlock_material"]assert unlock_material[0]["name"] == "PENDING_PROTECTED"+ issued = _issued_agent_dek_payload(request_id)fulfilled = api.fulfill_vault_access_request(request_id,{"grant_id": grant_id,"session_id": "ses_1",- "agent_pubkey": {"public_key": "pk", "fingerprint": "fp"},- "deks": [- {- "name": "PENDING_PROTECTED",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,},)@@ -1158,11 +1209,11 @@ def test_vault_sandbox_root_metadata_first_key_wins_under_concurrency(monkeypatcassert len(keys) == 1-def test_create_vault_agent_binding_signs_value_free_protected_grant(monkeypatch):- from cryptography.hazmat.primitives.asymmetric import ed25519-+def test_create_vault_agent_bindings_batch_signs_value_free_contexts(monkeypatch):monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)monkeypatch.setattr(api, "avault_agent_pubkey", Mock(return_value={"public_key": "agent-pk", "fingerprint": "agent-fp"}))+ with api._vault_engine().begin() as conn:+ _insert_workbench_session(conn, session_id="ses_binding", title="fix-ci-flake")api.create_vault_secret({"name": "PROTECTED_BINDING",@@ -1179,34 +1230,320 @@ def test_create_vault_agent_binding_signs_value_free_protected_grant(monkeypatch)grant_id = request["card"]["grant_options"][0]["grant_id"]- result = api.create_vault_agent_binding(- {"request_id": request["id"], "grant_id": grant_id, "name": "PROTECTED_BINDING", "ttl_seconds": 300}+ result = api.create_vault_agent_bindings_batch(+ {"request_id": request["id"], "grant_duration": 300})assert result["ok"] is Trueassert result["agent_pubkey"] == {"public_key": "agent-pk", "fingerprint": "agent-fp"}- assert set(result["approval"]) == {"nonce", "expires_at_unix"}- binding = dict(result["binding"])- signature = binding.pop("signature")- root_key = api.get_vault_sandbox_root_metadata()["root_metadata"]["daemon"]["verificationKeys"][0]- public_key = ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(root_key["publicKey"]))- public_key.verify(- base64.b64decode(signature["value"]),- json.dumps(binding, sort_keys=True, separators=(",", ":")).encode("utf-8"),- )- assert signature["alg"] == "ed25519"- assert signature["keyId"] == root_key["keyId"]- assert binding["requestId"] == request["id"]- assert binding["grantId"] == grant_id- assert binding["agent"]["fingerprint"] == "agent-fp"- context = binding["context"]+ assert result["grant_duration"] == 300+ assert result["ttl_seconds"] == 300+ assert len(result["items"]) == 1+ item = result["items"][0]+ assert item["name"] == "PROTECTED_BINDING"+ assert set(item["approval"]) == {"nonce", "expires_at_unix"}+ context = _verified_signed_context(item["context"])+ assert context["v"] == 2assert context["purpose"] == "agent-deliver"- assert context["name"] == "PROTECTED_BINDING"+ assert context["requestId"].startswith("vab_")assert context["grantId"] == grant_id- assert context["ttlSecs"] == 300- assert isinstance(context["approvalNonce"], list)- assert len(context["approvalNonce"]) == 16- assert context["operationHash"] == api._agent_deliver_operation_hash("PROTECTED_BINDING", 300)+ assert context["agent"]["fingerprint"] == "agent-fp"+ assert context["display"]["secrets"] == [{"name": "PROTECTED_BINDING", "kind": "static"}]+ assert context["display"]["sessionLabel"] == "fix-ci-flake"+ assert context["display"]["grantTtlSeconds"] == 300+ assert context["release"] == {+ "name": "PROTECTED_BINDING",+ "ttlSecs": 300,+ "approvalNonce": list(base64.b64decode(item["approval"]["nonce"])),+ "approvalExpiresAtUnix": item["approval"]["expires_at_unix"],+ "operationHash": api._agent_deliver_operation_hash("PROTECTED_BINDING", 300),+ }+++def test_agent_bindings_batch_covers_all_protected_selector_members_one_time(monkeypatch):+ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", Mock(return_value={"public_key": "agent-pk", "fingerprint": "agent-fp"}))+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("standard")))+ for name in ("PROTECTED_A", "PROTECTED_B"):+ api.create_vault_secret(+ {+ "name": name,+ "protection": "protected",+ "tags": ["deploy"],+ "sealed": {"ciphertext": f"ct-{name}", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ api.create_vault_secret(+ {+ "name": "STANDARD_ASK",+ "tags": ["deploy"],+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},+ "policy": {"always_ask": True},+ }+ )+ request = api.request_vault_access(+ {+ "source_selector": {"tags": ["deploy"]},+ "session_id": "ses_batch",+ "command": "deploy\nprod",+ "egress": "api.github.com",+ }+ )["request"]++ result = api.create_vault_agent_bindings_batch(+ {+ "request_id": request["id"],+ "grant_duration": "one-time",+ }+ )++ assert result["grant_duration"] == "one-time"+ assert result["ttl_seconds"] == 60+ assert [item["name"] for item in result["items"]] == ["PROTECTED_A", "PROTECTED_B"]+ assert request["card"]["grant_options"][0]["member_snapshot"] == ["PROTECTED_A", "PROTECTED_B", "STANDARD_ASK"]+ contexts = [_verified_signed_context(item["context"]) for item in result["items"]]+ assert len({context["requestId"] for context in contexts}) == 2+ assert all(context["requestId"].startswith("vab_") for context in contexts)+ for context in contexts:+ assert context["display"]["secrets"] == [+ {"name": "PROTECTED_A", "kind": "static"},+ {"name": "PROTECTED_B", "kind": "static"},+ {"name": "STANDARD_ASK", "kind": "static"},+ ]+ assert context["display"]["command"] == "deploy prod"+ assert context["display"]["egress"] == "api.github.com"+ assert context["display"]["source"] == {"tags": ["deploy"]}+ assert context["display"]["grantTtlSeconds"] == 60+ assert context["release"]["ttlSecs"] == 60+ assert context["release"]["operationHash"] == api._agent_deliver_operation_hash(+ context["release"]["name"],+ 60,+ )+ assert api.get_vault_settings()["settings"]["last_grant_ttl"] == "one-time"+++def test_agent_bindings_batch_rejects_mixed_duration_fields(monkeypatch):+ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", Mock(return_value={"public_key": "agent-pk", "fingerprint": "agent-fp"}))+ api.create_vault_secret(+ {+ "name": "PROTECTED_MIXED_TTL",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ with api._vault_engine().begin() as conn:+ request = vault_service.create_access_request(conn, "PROTECTED_MIXED_TTL")++ with pytest.raises(api.VaultApiError) as exc:+ api.create_vault_agent_bindings_batch(+ {+ "request_id": request["id"],+ "grant_duration": 300,+ "ttl_seconds": 900,+ }+ )++ assert exc.value.code == "invalid_request"+++def test_agent_bindings_batch_retries_replace_stale_approval_records(monkeypatch):+ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", Mock(return_value={"public_key": "agent-pk", "fingerprint": "agent-fp"}))+ for name in ("PROTECTED_BATCH_RETRY_A", "PROTECTED_BATCH_RETRY_B"):+ api.create_vault_secret(+ {+ "name": name,+ "protection": "protected",+ "tags": ["batch-retry"],+ "sealed": {"ciphertext": f"ct-{name}", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ request = api.request_vault_access(+ {"source_selector": {"tags": ["batch-retry"]}, "session_id": "ses_batch_retry"}+ )["request"]++ for _index in range(5):+ api.create_vault_agent_bindings_batch({"request_id": request["id"], "grant_duration": 300})++ with api._vault_engine().connect() as conn:+ stored = vault_service.get_request(conn, request["id"], audience=vault_service.REQUEST_AUDIENCE_AGENT)+ records = stored["delivery"]["agent_binding_approvals"]+ assert len(records) == 1+ assert [item["name"] for item in records[0]["items"]] == ["PROTECTED_BATCH_RETRY_A", "PROTECTED_BATCH_RETRY_B"]+++def test_legacy_agent_binding_records_all_protected_members(monkeypatch, avault_p2):+ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", Mock(return_value={"public_key": "agent-pk", "fingerprint": "agent-fp"}))+ agent_grant = Mock(return_value={"granted": 25, "ttl_secs": 300})+ monkeypatch.setattr(api, "avault_agent_grant", agent_grant)+ names = [f"PROTECTED_BULK_{index:02d}" for index in range(25)]+ for name in names:+ api.create_vault_secret(+ {+ "name": name,+ "protection": "protected",+ "tags": ["bulk"],+ "sealed": {"ciphertext": f"ct-{name}", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ requested = api.request_vault_access({"source_selector": {"tags": ["bulk"]}, "session_id": "ses_bulk"})+ option = requested["request"]["card"]["grant_options"][0]++ deks = []+ agent_pubkey = None+ for name in option["member_snapshot"]:+ binding = api.create_vault_agent_binding(+ {+ "request_id": requested["request"]["id"],+ "grant_id": option["grant_id"],+ "name": name,+ "grant_duration": 300,+ }+ )+ agent_pubkey = binding["agent_pubkey"]+ deks.append({"name": name, "dek_blindbox": _agent_dek_blindbox(enc=f"enc-{name}"), "approval": binding["approval"]})++ created = api.create_vault_grant(+ {+ "session_id": "ses_bulk",+ "request_id": requested["request"]["id"],+ "agent_pubkey": agent_pubkey,+ "deks": deks,+ }+ )++ assert created["grant"]["member_snapshot"] == names+ assert agent_grant.call_count == 1+ with api._vault_engine().connect() as conn:+ request = vault_service.get_request(conn, requested["request"]["id"], audience=vault_service.REQUEST_AUDIENCE_AGENT)+ assert len(request["delivery"]["agent_binding_approvals"]) == 25+++def test_legacy_agent_binding_retries_replace_stale_approval_records(monkeypatch, avault_p2):+ names = [f"PROTECTED_RETRY_{index}" for index in range(3)]+ for name in names:+ api.create_vault_secret(+ {+ "name": name,+ "protection": "protected",+ "tags": ["retry"],+ "sealed": {"ciphertext": f"ct-{name}", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ requested = api.request_vault_access({"source_selector": {"tags": ["retry"]}, "session_id": "ses_retry"})+ option = requested["request"]["card"]["grant_options"][0]++ for name in names:+ api.create_vault_agent_binding(+ {"request_id": requested["request"]["id"], "grant_id": option["grant_id"], "name": name, "grant_duration": 300}+ )+ for _index in range(5):+ api.create_vault_agent_binding(+ {+ "request_id": requested["request"]["id"],+ "grant_id": option["grant_id"],+ "name": names[0],+ "grant_duration": 300,+ }+ )++ with api._vault_engine().connect() as conn:+ request = vault_service.get_request(conn, requested["request"]["id"], audience=vault_service.REQUEST_AUDIENCE_AGENT)+ records = request["delivery"]["agent_binding_approvals"]+ record_names = [record["items"][0]["name"] for record in records]+ assert len(records) == len(names)+ assert record_names.count(names[0]) == 1+ assert set(record_names) == set(names)+++def test_vault_settings_roundtrip_and_policy():+ defaults = api.get_vault_settings()+ assert defaults["settings"] == {+ "unlock_window_seconds": 600,+ "strict_approvals": False,+ "last_grant_ttl": 300,+ }+ assert defaults["policy"] == {+ "windowSeconds": 600,+ "strictApprovals": False,+ "parentValueSealAllowed": True,+ }++ saved = api.save_vault_settings(+ {+ "unlock_window_seconds": 1800,+ "strict_approvals": True,+ "last_grant_ttl": "one-time",+ }+ )++ assert saved["settings"]["last_grant_ttl"] == "one-time"+ assert saved["policy"]["windowSeconds"] == 1800+ assert saved["policy"]["strictApprovals"] is True+ assert api.get_vault_settings()["settings"] == saved["settings"]+ with pytest.raises(api.VaultApiError) as exc:+ api.save_vault_settings({"strict_approvals": "false"})+ assert exc.value.code == "invalid_request"+++def test_create_vault_reveal_context_signs_named_protected_secret(monkeypatch):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ api.create_vault_secret(+ {+ "name": "PROTECTED_REVEAL",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )++ result = api.create_vault_reveal_context("PROTECTED_REVEAL", {"session_label": "Workbench - vaults"})++ assert result["ok"] is True+ context = _verified_signed_context(result["context"])+ assert context["v"] == 2+ assert context["purpose"] == "reveal"+ assert context["requestId"].startswith("vrl_")+ assert context["display"]["secrets"] == [{"name": "PROTECTED_REVEAL", "kind": "static"}]+ assert context["display"]["sessionLabel"] == "Workbench - vaults"+ assert result["envelope"] == {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}+ assert context["release"] == {+ "name": "PROTECTED_REVEAL",+ "envelopeHash": api._envelope_hash(result["envelope"]),+ }+ assert not ({"plaintext", "plain_text", "dek", "deks", "secret_unlock_material", "unlock_material"} & _payload_keys(result))+ with api._vault_engine().connect() as conn:+ meta = vault_service.get_secret_meta(conn, "PROTECTED_REVEAL")+ audit_rows = conn.execute(+ select(vault_audit.c.request_id, vault_audit.c.delivery).where(+ vault_audit.c.secret_name == "PROTECTED_REVEAL",+ vault_audit.c.event == "revealed",+ )+ ).mappings().all()+ assert meta["use_count"] == 0+ assert meta["last_used_at"] is None+ assert audit_rows == []+++def test_create_vault_reveal_context_rejects_protected_keypair(monkeypatch):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ public_meta, _signature = _browser_ecdsa_signature_for_digest("00" * 32)+ api.create_vault_secret(+ {+ "name": "PROTECTED_REVEAL_KEY",+ "protection": "protected",+ "kind": "keypair",+ "signer_kind": "local",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ "public_meta": public_meta,+ }+ )++ with pytest.raises(api.VaultApiError) as exc:+ api.create_vault_reveal_context("PROTECTED_REVEAL_KEY")++ assert exc.value.code == "keypair_not_value_deliverable"def test_protected_create_establishing_vmk_rejects_second_init(monkeypatch):@@ -1665,6 +2002,7 @@ def test_request_vault_access_reports_missing_selector_member_name():def test_agent_access_sibling_request_result_returns_covering_grant(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("api")))monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", lambda: dict(TEST_AGENT_PUBKEY))monkeypatch.setattr(api, "avault_agent_grant", Mock(return_value={"granted": 1, "ttl_secs": 300}))api.create_vault_secret({@@ -1675,17 +2013,12 @@ def test_agent_access_sibling_request_result_returns_covering_grant(monkeypatch))req_a = api.request_vault_access({"name": "A_KEY", "session_id": "ses_1"})req_b = api.request_vault_access({"name": "A_KEY", "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(req_a["request"]["id"])created = api.create_vault_grant({"request_id": req_a["request"]["id"],"session_id": "ses_1",- "deks": [- {- "name": "A_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,})@@ -1699,6 +2032,7 @@ def test_agent_access_sibling_request_result_returns_covering_grant(monkeypatch)def test_agent_access_selector_sibling_request_result_returns_covering_grant(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("api")))monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", lambda: dict(TEST_AGENT_PUBKEY))monkeypatch.setattr(api, "avault_agent_grant", Mock(return_value={"granted": 2, "ttl_secs": 300}))for name in ("A_KEY", "B_KEY"):api.create_vault_secret(@@ -1715,22 +2049,18 @@ def test_agent_access_selector_sibling_request_result_returns_covering_grant(mon)req_a = api.request_vault_access({"source_selector": {"tags": ["deploy"]}, "session_id": "ses_1"})req_b = api.request_vault_access({"source_selector": {"tags": ["deploy"]}, "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(+ req_a["request"]["id"],+ blindboxes={+ "A_KEY": _agent_dek_blindbox("enc-a", "ct-a"),+ "B_KEY": _agent_dek_blindbox("enc-b", "ct-b"),+ },+ )created = api.create_vault_grant({"request_id": req_a["request"]["id"],"session_id": "ses_1",- "deks": [- {- "name": "A_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc-a", "ct": "ct-a"},- "approval": {"nonce": "bm9uY2UtYQ==", "expires_at_unix": 4102444800},- },- {- "name": "B_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc-b", "ct": "ct-b"},- "approval": {"nonce": "bm9uY2UtYg==", "expires_at_unix": 4102444800},- },- ],+ **issued,})@@ -2037,7 +2367,13 @@ def test_agent_sign_request_accepts_protected_browser_signature(monkeypatch):assert requested["ok"] is Trueassert requested["request"]["card"]["protection"] == "protected"+ assert requested["request"]["card"]["secret_unlock_material"] == {+ "name": "PROTECTED_ETH_KEY",+ "kind": "keypair",+ "envelope": {"ciphertext": "ct-key", "nonce": "n-key", "wrap_meta": "wm-key"},+ }assert requested["request"]["delivery"]["signing_context"] == _signing_context(digest)+ assert requested["request"]["delivery"]["operation_context"] == requested["request"]["card"]["operation_context"]assert completed["ok"] is Trueassert completed["signature"] == signatureassert api.get_vault_request(requested["request"]["id"])["result"] == {"type": "signature", "signature": signature}@@ -2135,28 +2471,23 @@ def test_create_and_revoke_grant_api(monkeypatch, avault_p2):requester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])created = api.create_vault_grant({"session_id": "ses_1","ttl_seconds": 300,"request_id": req["id"],- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,})assert created["grant"]["runtime_member_count"] == 1assert created["grant"]["delivery_ready"] is True- assert agent_grant.call_args.kwargs["ttl_secs"] == 300+ assert 1 <= agent_grant.call_args.kwargs["ttl_secs"] <= 300assert agent_grant.call_args.kwargs["deks"] == [{"name": "GRANT_KEY","dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},+ "approval": issued["deks"][0]["approval"],}]grants = api.get_vault_grants()["grants"]@@ -2181,6 +2512,7 @@ def test_fulfill_access_request_relays_only_browser_dek_blindbox(monkeypatch, av)requested = api.request_vault_access({"name": "PROTECTED_KEY", "session_id": "ses_1"})grant_id = requested["request"]["card"]["grant_options"][0]["grant_id"]+ issued = _issued_agent_dek_payload(requested["request"]["id"])fulfilled = api.fulfill_vault_access_request(requested["request"]["id"],@@ -2188,14 +2520,7 @@ def test_fulfill_access_request_relays_only_browser_dek_blindbox(monkeypatch, av"grant_id": grant_id,"session_id": "ses_1","ttl_seconds": 300,- "agent_pubkey": {"public_key": "pk", "fingerprint": "fp"},- "deks": [- {- "name": "PROTECTED_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,},)@@ -2208,13 +2533,13 @@ def test_fulfill_access_request_relays_only_browser_dek_blindbox(monkeypatch, av{"name": "PROTECTED_KEY","dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},+ "approval": issued["deks"][0]["approval"],}]with api._vault_engine().connect() as conn:resolved = vault_service.resolve_secret_access(conn, "PROTECTED_KEY", session_id="ses_1", create_request=False)assert resolved["status"] == "agent_delivery_ready"- validate_pubkey.assert_called_once_with({"public_key": "pk", "fingerprint": "fp"})+ validate_pubkey.assert_called_once_with(TEST_AGENT_PUBKEY)encoded = json.dumps({"fulfilled": fulfilled, "agent_deks": agent_grant.call_args.kwargs["deks"]})assert "raw-dek-must-not-cross-python-agent-boundary" not in encodedassert "plaintext-must-not-cross-python-agent-boundary" not in encoded@@ -2235,19 +2560,13 @@ def test_fulfill_protected_always_ask_access_uses_one_shot_resident_agent_grant(})requested = api.request_vault_access({"name": "PROTECTED_ASK", "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(requested["request"]["id"], grant_duration="one-time")fulfilled = api.fulfill_vault_access_request(requested["request"]["id"],{"session_id": "ses_1",- "agent_pubkey": {"public_key": "pk", "fingerprint": "fp"},- "deks": [- {- "name": "PROTECTED_ASK",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,},)@@ -2256,12 +2575,12 @@ def test_fulfill_protected_always_ask_access_uses_one_shot_resident_agent_grant(assert fulfilled["grant"]["one_shot"] is Trueassert fulfilled["grant"]["source_selector"] == {"env": ["PROTECTED_ASK"]}assert fulfilled["grant"]["delivery_ready"] is True- validate_pubkey.assert_called_once_with({"public_key": "pk", "fingerprint": "fp"})+ validate_pubkey.assert_called_once_with(TEST_AGENT_PUBKEY)assert agent_grant.call_args.kwargs["deks"] == [{"name": "PROTECTED_ASK","dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},+ "approval": issued["deks"][0]["approval"],}]@@ -2928,6 +3247,145 @@ def test_create_grant_api_rejects_mismatched_deks_before_claiming_request(monkeyassert grants == []+def test_create_grant_api_rejects_unissued_agent_dek_approval(monkeypatch, avault_p2):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ agent_grant = Mock(return_value={"granted": 1, "ttl_secs": 300})+ monkeypatch.setattr(api, "avault_agent_grant", agent_grant)+ api.create_vault_secret({"name": "GRANT_KEY", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}})+ requested = api.request_vault_access({"name": "GRANT_KEY", "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(requested["request"]["id"])+ tampered_deks = [dict(issued["deks"][0])]+ tampered_deks[0]["approval"] = {**tampered_deks[0]["approval"], "nonce": "tampered"}++ with pytest.raises(api.VaultApiError) as exc:+ api.create_vault_grant(+ {+ "session_id": "ses_1",+ "request_id": requested["request"]["id"],+ "agent_pubkey": issued["agent_pubkey"],+ "deks": tampered_deks,+ }+ )++ assert exc.value.code == "invalid_grant"+ agent_grant.assert_not_called()+ with api._vault_engine().connect() as conn:+ status = conn.execute(select(vault_service.vault_requests.c.status).where(vault_service.vault_requests.c.id == requested["request"]["id"])).scalar_one()+ assert status == "pending"+++def test_create_grant_api_rejects_binding_duration_mismatch(monkeypatch, avault_p2):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ agent_grant = Mock(return_value={"granted": 1, "ttl_secs": 300})+ monkeypatch.setattr(api, "avault_agent_grant", agent_grant)+ api.create_vault_secret({"name": "GRANT_KEY", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}})+ requested = api.request_vault_access({"name": "GRANT_KEY", "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(requested["request"]["id"], grant_duration="one-time")++ with pytest.raises(api.VaultApiError) as exc:+ api.create_vault_grant(+ {+ "session_id": "ses_1",+ "request_id": requested["request"]["id"],+ "grant_duration": 300,+ **issued,+ }+ )++ assert exc.value.code == "invalid_grant"+ agent_grant.assert_not_called()+++def test_create_grant_api_accepts_fingerprint_only_agent_pubkey(monkeypatch, avault_p2):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ agent_grant = Mock(return_value={"granted": 1, "ttl_secs": 300})+ monkeypatch.setattr(api, "avault_agent_grant", agent_grant)+ api.create_vault_secret({"name": "GRANT_KEY", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}})+ requested = api.request_vault_access({"name": "GRANT_KEY", "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(requested["request"]["id"])++ created = api.create_vault_grant(+ {+ "session_id": "ses_1",+ "request_id": requested["request"]["id"],+ "agent_pubkey": {"fingerprint": issued["agent_pubkey"]["fingerprint"]},+ "deks": issued["deks"],+ }+ )++ assert created["grant"]["status"] == "active"+ agent_grant.assert_called_once()+ assert agent_grant.call_args.kwargs["expected_pubkey"] == {"fingerprint": issued["agent_pubkey"]["fingerprint"]}+++def test_create_grant_api_caps_grant_and_relay_by_binding_expiry(monkeypatch, avault_p2):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ agent_grant = Mock(return_value={"granted": 1, "ttl_secs": 60})+ monkeypatch.setattr(api, "avault_agent_grant", agent_grant)+ api.create_vault_secret({"name": "GRANT_KEY", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}})+ requested = api.request_vault_access({"name": "GRANT_KEY", "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(requested["request"]["id"])+ binding_expires_at = datetime.now(timezone.utc) + timedelta(seconds=60)+ with api._vault_engine().begin() as conn:+ row = conn.execute(select(vault_requests).where(vault_requests.c.id == requested["request"]["id"])).mappings().one()+ delivery = json.loads(row["delivery"])+ delivery["agent_binding_approvals"][0]["expires_at"] = api._isoformat_z(binding_expires_at)+ conn.execute(+ vault_requests.update()+ .where(vault_requests.c.id == requested["request"]["id"])+ .values(delivery=json.dumps(delivery))+ )++ created = api.create_vault_grant(+ {+ "session_id": "ses_1",+ "request_id": requested["request"]["id"],+ **issued,+ }+ )++ grant_expires_at = datetime.fromisoformat(created["grant"]["expires_at"]).astimezone(timezone.utc)+ assert grant_expires_at <= binding_expires_at+ assert 1 <= agent_grant.call_args.kwargs["ttl_secs"] <= 60+ assert agent_grant.call_args.kwargs["ttl_secs"] < 300+++def test_create_grant_api_rejects_expired_binding_before_claiming_request(monkeypatch, avault_p2):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ agent_grant = Mock(return_value={"granted": 1, "ttl_secs": 300})+ monkeypatch.setattr(api, "avault_agent_grant", agent_grant)+ api.create_vault_secret({"name": "GRANT_KEY", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}})+ requested = api.request_vault_access({"name": "GRANT_KEY", "session_id": "ses_1"})+ issued = _issued_agent_dek_payload(requested["request"]["id"])+ binding_expires_at = datetime.now(timezone.utc) - timedelta(seconds=1)+ with api._vault_engine().begin() as conn:+ row = conn.execute(select(vault_requests).where(vault_requests.c.id == requested["request"]["id"])).mappings().one()+ delivery = json.loads(row["delivery"])+ delivery["agent_binding_approvals"][0]["expires_at"] = api._isoformat_z(binding_expires_at)+ conn.execute(+ vault_requests.update()+ .where(vault_requests.c.id == requested["request"]["id"])+ .values(delivery=json.dumps(delivery))+ )++ with pytest.raises(api.VaultApiError) as exc:+ api.create_vault_grant(+ {+ "session_id": "ses_1",+ "request_id": requested["request"]["id"],+ **issued,+ }+ )++ assert exc.value.code == "invalid_grant"+ agent_grant.assert_not_called()+ with api._vault_engine().connect() as conn:+ status = conn.execute(select(vault_service.vault_requests.c.status).where(vault_service.vault_requests.c.id == requested["request"]["id"])).scalar_one()+ grants = vault_service.list_grants(conn, status=None)+ assert status == "pending"+ assert grants == []++def test_create_grant_api_relay_runs_after_grant_commit(monkeypatch, avault_p2):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))api.create_vault_secret({"name": "GRANT_KEY", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}})@@ -2950,18 +3408,13 @@ def test_create_grant_api_relay_runs_after_grant_commit(monkeypatch, avault_p2):return {"granted": 1, "ttl_secs": kwargs["ttl_secs"]}monkeypatch.setattr(api, "avault_agent_grant", relay)+ issued = _issued_agent_dek_payload(req["id"])created = api.create_vault_grant({"session_id": "ses_1","request_id": req["id"],- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,})@@ -3022,19 +3475,14 @@ def test_create_grant_api_expires_grant_when_agent_grant_fails(monkeypatch, avaurequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({"session_id": "ses_1","request_id": req["id"],- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,})@@ -3062,19 +3510,14 @@ def test_create_grant_api_rejects_partial_agent_cache(monkeypatch, avault_p2):requester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({"session_id": "ses_1","request_id": req["id"],- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,})@@ -3090,7 +3533,7 @@ def test_create_grant_api_rejects_partial_agent_cache(monkeypatch, avault_p2):agent_release.assert_called_once_with(grant_id=grants[0]["id"])-def test_grant_ttl_uses_approved_lifetime():+def test_grant_ttl_uses_remaining_lifetime():now = datetime.now(timezone.utc)ttl = api._grant_ttl_seconds({@@ -3099,7 +3542,7 @@ def test_grant_ttl_uses_approved_lifetime():})- assert ttl == 1020+ assert 1 <= ttl <= 120def test_create_grant_api_releases_scope_when_mark_ready_fails(monkeypatch, avault_p2):@@ -3116,21 +3559,16 @@ def test_create_grant_api_releases_scope_when_mark_ready_fails(monkeypatch, avaurequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({"session_id": "ses_1","request_id": req["id"],- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,}- )+ )assert exc.value.code == "invalid_grant"with api._vault_engine().connect() as conn:@@ -3156,16 +3594,11 @@ def test_create_grant_retry_reuses_expired_failed_grant_id(monkeypatch, avault_prequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])payload = {"session_id": "ses_1","request_id": req["id"],- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,}with pytest.raises(api.VaultApiError) as exc:@@ -3205,19 +3638,14 @@ def test_create_grant_api_releases_failed_grant_id_without_touching_existing_grarequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({"session_id": "ses_1","request_id": req["id"],- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,})@@ -3244,18 +3672,13 @@ def test_create_grant_api_preserves_unbound_session_choice(monkeypatch, avault_prequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])created = api.create_vault_grant({"request_id": req["id"],"this_session_only": False,- "deks": [- {- "name": "GRANT_KEY",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,})@@ -3319,7 +3742,58 @@ def test_protected_sign_requires_browser_signature(monkeypatch):assert result["code"] == "browser_signature_required"assert result["request"]["card"]["request_type"] == "sign"assert result["request"]["card"]["grant_options"] == []+ assert result["request"]["card"]["secret_unlock_material"] == {+ "name": "ETH_KEY",+ "kind": "keypair",+ "envelope": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }assert result["request"]["delivery"]["signing_context"] == _signing_context(digest)+ signed_context = result["request"]["delivery"]["operation_context"]+ assert result["request"]["card"]["operation_context"] == signed_context+ context = _verified_signed_context(signed_context)+ assert context["v"] == 2+ assert context["purpose"] == "sign"+ assert context["requestId"] == result["request"]["id"]+ assert context["display"]["secrets"] == [{"name": "ETH_KEY", "kind": "keypair"}]+++def test_protected_sign_agent_audience_keeps_unlock_material_omitted(monkeypatch):+ from unittest.mock import Mock++ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ public_meta, _signature = _browser_ecdsa_signature_for_digest("00" * 32)+ api.create_vault_secret(+ {+ "name": "ETH_AGENT_KEY",+ "protection": "protected",+ "kind": "keypair",+ "signer_kind": "local",+ "sealed": {"ciphertext": "ct-agent", "nonce": "n-agent", "wrap_meta": "wm-agent"},+ "public_meta": public_meta,+ }+ )+ digest = "00" * 32++ result = api.vault_sign(+ {+ "name": "ETH_AGENT_KEY",+ "digest": digest,+ "scheme": "ecdsa-secp256k1-recoverable",+ "signing_context": _signing_context(digest),+ "requester": {"source": "agent-cli", "session_id": "ses_agent"},+ "delivery": {"session_id": "ses_agent"},+ }+ )++ assert result["ok"] is False+ assert result["code"] == "browser_signature_required"+ assert "secret_unlock_material" not in json.dumps(result["request"])+ assert "unlock_material" not in json.dumps(result["request"])+ signed_context = result["request"]["delivery"]["operation_context"]+ assert result["request"]["card"]["operation_context"] == signed_context+ context = _verified_signed_context(signed_context)+ assert context["purpose"] == "sign"+ assert context["display"]["secrets"] == [{"name": "ETH_AGENT_KEY", "kind": "keypair"}]def test_protected_sign_request_requires_pinned_signing_public_key(monkeypatch):diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.pyindex 2bdf8bb0a..c23b9b098 100644--- a/tests/test_vault_cli.py+++ b/tests/test_vault_cli.py@@ -75,6 +75,15 @@ def _signing_context_json(digest: str) -> str:)+def _assert_cli_sign_operation_context(request: dict, *, name: str) -> None:+ signed_context = request["delivery"]["operation_context"]+ assert request["card"]["operation_context"] == signed_context+ assert signed_context["purpose"] == "sign"+ assert signed_context["requestId"] == request["id"]+ assert signed_context["display"]["secrets"] == [{"name": name, "kind": "keypair"}]+ assert signed_context["signature"]["alg"] == "ed25519"++def _create_standard_secret(name: str, *, sealed: Sealed | None = None, **kwargs):with cli._open_vault_engine().begin() as conn:return vault_service.create_secret(conn, name=name, sealed=sealed or _sealed(), **kwargs)@@ -577,6 +586,7 @@ def test_sign_request_and_await_cli_reads_approved_signature_for_always_ask_stanrequest_payload = json.loads(capfd.readouterr().out)assert request_payload["kind"] == "vault_sign_request"assert "signature" not in request_payload+ _assert_cli_sign_operation_context(request_payload["request"], name="ETH_KEY")request_id = request_payload["request_id"]with cli._open_vault_engine().connect() as conn:row = conn.execute(vault_requests.select().where(vault_requests.c.id == request_id)).mappings().one()@@ -634,6 +644,7 @@ def test_sign_request_cli_requires_context_for_protected_keypair(capfd):assert payload["request"]["card"]["protection"] == "protected"assert payload["request"]["card"]["grant_options"] == []assert payload["request"]["delivery"]["signing_context"] == json.loads(_signing_context_json("00" * 32))+ _assert_cli_sign_operation_context(payload["request"], name="PROTECTED_ETH_KEY")def test_vault_await_wait_treats_failed_request_as_terminal(capfd):diff --git a/tests/test_vault_rest.py b/tests/test_vault_rest.pyindex 149675c12..85c41086f 100644--- a/tests/test_vault_rest.py+++ b/tests/test_vault_rest.py@@ -20,6 +20,22 @@ def _sealed(suffix: str = "1") -> Sealed:def _mock_avault_p2(monkeypatch):monkeypatch.setattr(api, "_require_avault_p2_surface", lambda _feature: None)monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_pubkey", lambda: {"public_key": "pk", "fingerprint": "fp"})+++def _issued_agent_dek_payload(request_id: str) -> dict:+ issued = api.create_vault_agent_bindings_batch({"request_id": request_id, "grant_duration": 300})+ return {+ "agent_pubkey": issued["agent_pubkey"],+ "deks": [+ {+ "name": item["name"],+ "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},+ "approval": item["approval"],+ }+ for item in issued["items"]+ ],+ }def test_rest_create_rejects_protected_plaintext_value(monkeypatch):@@ -182,6 +198,119 @@ def test_rest_agent_pubkey_route(monkeypatch):assert response.get_json() == {"ok": True, "public_key": "pk", "fingerprint": "fp"}+def test_rest_vault_settings_roundtrip():+ client = app.test_client()++ defaults = client.get("/api/vault/settings")+ saved = client.patch(+ "/api/vault/settings",+ json={"unlock_window_seconds": 300, "strict_approvals": True, "last_grant_ttl": 900},+ headers=csrf_headers(client),+ )++ assert defaults.status_code == 200+ assert defaults.get_json()["settings"]["unlock_window_seconds"] == 600+ assert saved.status_code == 200+ assert saved.get_json()["settings"] == {+ "unlock_window_seconds": 300,+ "strict_approvals": True,+ "last_grant_ttl": 900,+ }+ assert saved.get_json()["policy"]["windowSeconds"] == 300+ rejected = client.patch(+ "/api/vault/settings",+ json={"strict_approvals": "false"},+ headers=csrf_headers(client),+ )+ assert rejected.status_code == 409+ assert rejected.get_json()["code"] == "invalid_request"+++def test_rest_reveal_context_route(monkeypatch):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ api.create_vault_secret(+ {+ "name": "PROTECTED_REST_REVEAL",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ client = app.test_client()++ response = client.post(+ "/api/vault/secrets/PROTECTED_REST_REVEAL/reveal-context",+ json={},+ headers=csrf_headers(client),+ )++ assert response.status_code == 200+ body = response.get_json()+ assert body["context"]["purpose"] == "reveal"+ assert body["envelope"] == {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}+ assert body["context"]["release"] == {+ "name": "PROTECTED_REST_REVEAL",+ "envelopeHash": api._envelope_hash(body["envelope"]),+ }+++def test_rest_agent_bindings_batch_route(monkeypatch):+ _mock_avault_p2(monkeypatch)+ monkeypatch.setattr(api, "avault_agent_pubkey", Mock(return_value={"public_key": "pk", "fingerprint": "fp"}))+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ api.create_vault_secret(+ {+ "name": "PROTECTED_REST_BINDING",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ requested = api.request_vault_access({"name": "PROTECTED_REST_BINDING", "session_id": "ses_1"})["request"]+ client = app.test_client()++ response = client.post(+ "/api/vault/agent-bindings:batch",+ json={"request_id": requested["id"], "grant_duration": 300},+ headers=csrf_headers(client),+ )++ assert response.status_code == 200+ body = response.get_json()+ assert body["grant_id"] == requested["card"]["grant_options"][0]["grant_id"]+ assert [item["name"] for item in body["items"]] == ["PROTECTED_REST_BINDING"]+++def test_rest_agent_binding_legacy_route_bridge(monkeypatch):+ _mock_avault_p2(monkeypatch)+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ api.create_vault_secret(+ {+ "name": "PROTECTED_REST_LEGACY_BINDING",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ requested = api.request_vault_access({"name": "PROTECTED_REST_LEGACY_BINDING", "session_id": "ses_1"})["request"]+ client = app.test_client()++ response = client.post(+ "/api/vault/agent-binding",+ json={+ "request_id": requested["id"],+ "grant_id": requested["card"]["grant_options"][0]["grant_id"],+ "name": "PROTECTED_REST_LEGACY_BINDING",+ "ttl_seconds": 300,+ },+ headers=csrf_headers(client),+ )++ assert response.status_code == 200+ body = response.get_json()+ assert body["grant_id"] == requested["card"]["grant_options"][0]["grant_id"]+ assert body["binding"]["context"]["purpose"] == "agent-deliver"+ assert body["binding"]["context"]["name"] == "PROTECTED_REST_LEGACY_BINDING"+ assert set(body["approval"]) == {"nonce", "expires_at_unix"}++def test_rest_security_headers_delegate_webauthn_to_self_and_sandbox():client = app.test_client()@@ -254,19 +383,14 @@ def test_rest_requests_and_grants_routes(monkeypatch):requester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)+ issued = _issued_agent_dek_payload(req["id"])grant_response = client.post("/api/vault/grants",json={"session_id": "ses_1","request_id": req["id"],- "deks": [- {- "name": "PROTECTED_REST",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,},headers=csrf_headers(client),)@@ -369,18 +493,13 @@ def test_rest_fulfill_access_request_route(monkeypatch):)requested = api.request_vault_access({"name": "PROTECTED_REST", "session_id": "ses_1"})client = app.test_client()+ issued = _issued_agent_dek_payload(requested["request"]["id"])response = client.post(f"/api/vault/requests/{requested['request']['id']}/fulfill-access",json={"session_id": "ses_1",- "deks": [- {- "name": "PROTECTED_REST",- "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},- "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},- }- ],+ **issued,},headers=csrf_headers(client),)diff --git a/tests/test_vault_service.py b/tests/test_vault_service.pyindex 46ba06f53..c3da58894 100644--- a/tests/test_vault_service.py+++ b/tests/test_vault_service.py@@ -2,7 +2,9 @@from __future__ import annotations+import concurrent.futuresimport json+import threadingfrom datetime import datetime, timedelta, timezoneimport pytest@@ -11,7 +13,7 @@ from sqlalchemy.exc import IntegrityErrorfrom storage import vault_service as vs, vault_webauthnfrom storage.db import create_sqlite_engine-from storage.models import metadata, vault_auth_factors, vault_grants, vault_requests, vault_secrets+from storage.models import metadata, state_meta, vault_auth_factors, vault_grants, vault_requests, vault_secretsfrom storage.vault_crypto import Sealedfrom tests.vault_webauthn_helpers import WebAuthnTestCredential@@ -58,7 +60,14 @@ def _establish_protected_secret(conn, name: str, credential: WebAuthnTestCredentreturn credential, dict(factor)-def _grant_from_request(conn, request: dict, *, cache_ready: bool = True, ttl_seconds: int | None = None) -> dict:+def _grant_from_request(+ conn,+ request: dict,+ *,+ cache_ready: bool = True,+ ttl_seconds: int | None = None,+ expires_at: str | None = None,+) -> dict:option = request["card"]["grant_options"][0]return vs.create_grant(conn,@@ -67,6 +76,7 @@ def _grant_from_request(conn, request: dict, *, cache_ready: bool = True, ttl_sepurpose=option["purpose"],request_id=request["id"],ttl_seconds=ttl_seconds,+ expires_at=expires_at,cache_ready=cache_ready,)@@ -321,16 +331,56 @@ def test_create_grant_stores_final_fields_and_readiness_by_grant_id(vault):assert release_refs == [{"grant_id": grant["id"]}]-def test_create_grant_caps_ttl_to_approval_options(vault):+def test_create_grant_rejects_removed_ttl_options(vault):_create(vault, name="A_KEY", protection="protected", tags=["deploy"])with vault.begin() as conn:req = vs.create_access_request(conn, source_selector={"tags": ["deploy"]})- grant = _grant_from_request(conn, req, ttl_seconds=86_400)++ with pytest.raises(vs.InvalidGrantError):+ _grant_from_request(conn, req, ttl_seconds=86_400)+++def test_create_grant_one_time_uses_short_one_shot_window(vault):+ _create(vault, name="A_KEY", protection="protected", tags=["deploy"])++ with vault.begin() as conn:+ req = vs.create_access_request(conn, source_selector={"tags": ["deploy"]}, requester={"session_id": "ses_1"})+ option = req["card"]["grant_options"][0]+ grant = vs.create_grant(+ conn,+ member_names=option["member_snapshot"],+ source_selector=option["source_selector"],+ purpose=option["purpose"],+ request_id=req["id"],+ grant_duration="one-time",+ )+ settings = vs.get_vault_settings(conn)created = datetime.fromisoformat(grant["created_at"])expires = datetime.fromisoformat(grant["expires_at"])- assert expires - created == timedelta(seconds=3600)+ assert expires - created == timedelta(seconds=60)+ assert grant["one_shot"] is True+ assert grant["session_id"] == "ses_1"+ assert settings["last_grant_ttl"] == "one-time"+++def test_save_vault_settings_first_write_is_atomic_under_concurrency(vault):+ barrier = threading.Barrier(6)++ def save_settings(index: int) -> dict:+ with vault.begin() as conn:+ barrier.wait(timeout=5)+ return vs.save_vault_settings(conn, {"last_grant_ttl": 300 if index % 2 else 900})++ with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:+ results = list(executor.map(save_settings, range(6)))++ with vault.connect() as conn:+ rows = list(conn.execute(select(state_meta).where(state_meta.c.key == vs.VAULT_SETTINGS_META_KEY)).mappings())++ assert len(rows) == 1+ assert {result["last_grant_ttl"] for result in results}.issubset({300, 900})def test_sibling_approval_requires_matching_purpose(vault):@@ -617,6 +667,23 @@ def test_multi_member_one_shot_grant_is_consumed_once(vault):assert releases == [{"grant_id": grant["id"]}]+def test_create_grant_rejects_expired_binding_without_claiming_request(vault):+ _create(vault, name="PROTECTED_KEY", protection="protected")+ expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()++ with vault.begin() as conn:+ req = vs.create_access_request(conn, "PROTECTED_KEY", requester={"session_id": "ses_1"})++ with pytest.raises(vs.InvalidGrantError, match="grant binding has expired"):+ _grant_from_request(conn, req, expires_at=expired_at)++ row = conn.execute(select(vault_requests).where(vault_requests.c.id == req["id"])).mappings().one()+ grants = conn.execute(select(vault_grants).where(vault_grants.c.request_id == req["id"])).mappings().all()++ assert row["status"] == "pending"+ assert grants == []++def test_selector_request_expires_when_member_rotates(vault):_create(vault, name="A_KEY", protection="protected", tags=["deploy"])_create(vault, name="B_KEY", protection="protected", tags=["deploy"])diff --git a/vibe/api.py b/vibe/api.pyindex ea8b4a059..00ec1fc78 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1628,6 +1628,14 @@ def _agent_deliver_operation_hash(name: str, ttl_seconds: int) -> str:).hexdigest()+def _envelope_hash(envelope_payload: dict[str, Any]) -> dict[str, str]:+ canonical = json.dumps(envelope_payload, sort_keys=True, separators=(",", ":"))+ return {+ "alg": "sha256",+ "digest": hashlib.sha256(canonical.encode("utf-8")).hexdigest(),+ }++def _signed_agent_binding(binding: dict[str, Any], key: dict[str, str]) -> dict[str, Any]:from cryptography.hazmat.primitives.asymmetric import ed25519@@ -1644,6 +1652,288 @@ def _signed_agent_binding(binding: dict[str, Any], key: dict[str, str]) -> dict[}+def _isoformat_z(value: datetime) -> str:+ return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")+++def _display_text(value: Any, *, max_len: int) -> str | None:+ if value is None:+ return None+ text = re.sub(r"[\x00-\x1f\x7f]+", " ", str(value))+ text = re.sub(r"\s+", " ", text).strip()+ if not text:+ return None+ if len(text) > max_len:+ return f"{text[: max_len - 3].rstrip()}..."+ return text+++def _display_list(values: Any, *, max_items: int = 20, max_len: int = 80) -> list[str]:+ if not isinstance(values, list):+ return []+ out: list[str] = []+ for item in values:+ cleaned = _display_text(item, max_len=max_len)+ if cleaned:+ out.append(cleaned)+ if len(out) >= max_items:+ break+ return out+++def _display_source(selector: Any) -> dict[str, list[str]]:+ from storage import vault_service++ if not isinstance(selector, dict):+ return {}+ source: dict[str, list[str]] = {}+ env = _display_list(selector.get("env"))+ if env:+ source["env"] = env+ raw_tags = selector.get("tags")+ plain_tags: list[str] = []+ skills: list[str] = []+ if isinstance(raw_tags, list):+ for tag in raw_tags:+ cleaned = _display_text(tag, max_len=80)+ if not cleaned:+ continue+ if cleaned.startswith(vault_service.SKILL_TAG_PREFIX):+ skill = _display_text(cleaned[len(vault_service.SKILL_TAG_PREFIX) :], max_len=80)+ if skill:+ skills.append(skill)+ else:+ plain_tags.append(cleaned)+ raw_skills = selector.get("skills")+ if isinstance(raw_skills, list):+ skills.extend(_display_list(raw_skills))+ if plain_tags:+ source["tags"] = list(dict.fromkeys(plain_tags))[:20]+ if skills:+ source["skills"] = list(dict.fromkeys(skills))[:20]+ return source+++def _operation_context_display(+ request_payload: dict[str, Any] | None,+ secret_metas: list[dict[str, Any]],+ *,+ grant_ttl_seconds: int | None = None,+) -> dict[str, Any]:+ request_payload = request_payload if isinstance(request_payload, dict) else {}+ card = request_payload.get("card") if isinstance(request_payload.get("card"), dict) else {}+ display: dict[str, Any] = {+ "secrets": [+ {+ "name": str(meta["name"]),+ "kind": str(meta.get("kind") or "static") if meta.get("kind") in {"static", "keypair"} else "static",+ }+ for meta in secret_metas+ ]+ }+ session = request_payload.get("session") if isinstance(request_payload.get("session"), dict) else {}+ session_label = _display_text(session.get("label") or card.get("session_id"), max_len=120)+ if session_label:+ display["sessionLabel"] = session_label+ command = _display_text(card.get("command"), max_len=240)+ if command:+ display["command"] = command+ egress = _display_text(card.get("egress"), max_len=160)+ if egress:+ display["egress"] = egress+ delivery = request_payload.get("delivery") if isinstance(request_payload.get("delivery"), dict) else {}+ source = _display_source(card.get("source_selector") or delivery.get("source_selector"))+ if source:+ display["source"] = source+ if grant_ttl_seconds is not None:+ display["grantTtlSeconds"] = int(grant_ttl_seconds)+ return display+++def _grant_duration_value_from_payload(payload: dict[str, Any]) -> Any | None:+ from storage import vault_service++ grant_duration_keys = ("grant_duration", "grantDuration", "last_grant_ttl", "lastGrantTtl")+ ttl_keys = ("ttl_seconds", "ttlSecs")+ has_grant_duration = any(key in payload for key in grant_duration_keys)+ has_one_shot = payload.get("one_shot") is True or payload.get("oneShot") is True+ has_legacy_ttl = any(key in payload for key in ttl_keys)+ if (has_grant_duration or has_one_shot) and has_legacy_ttl:+ raise VaultApiError("use grant_duration or ttl_seconds, not both", code="invalid_request", status=409)++ for key in grant_duration_keys:+ if key in payload:+ return payload[key]+ if has_one_shot:+ return vault_service.GRANT_DURATION_ONE_TIME+ for key in ttl_keys:+ if key in payload:+ value = payload[key]+ try:+ if int(value) == vault_service.ONE_TIME_GRANT_TTL_SECONDS:+ return vault_service.GRANT_DURATION_ONE_TIME+ except (TypeError, ValueError):+ pass+ return value+ return None+++def _signed_operation_context(context: dict[str, Any], key: dict[str, str]) -> dict[str, Any]:+ return _signed_agent_binding(context, key)+++def create_vault_agent_bindings_batch(payload: dict) -> dict:+ from storage import vault_crypto, vault_service++ if not isinstance(payload, dict):+ raise VaultApiError("payload must be an object", code="invalid_payload")+ request_id = str(payload.get("request_id") or payload.get("requestId") or "").strip()+ if not request_id:+ raise VaultApiError("request_id is required", code="missing_request_id")++ engine = _vault_engine()+ try:+ with engine.begin() as conn:+ request_payload = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_UI)+ option = _grant_option_from_request(conn, request_id)+ grant_duration_value = _grant_duration_value_from_payload(payload)+ remember_duration = grant_duration_value is not None+ duration = vault_service.normalize_grant_duration(+ grant_duration_value,+ default=option.get("default_grant_duration") or vault_service.get_vault_settings(conn)["last_grant_ttl"],+ )+ grantable_members = vault_service.request_grantable_member_metas(conn, request_id)+ protected_metas = [member for member in grantable_members if member.get("protection") == "protected"]+ member_order = {name: index for index, name in enumerate(option["member_names"])}+ grantable_members.sort(key=lambda item: member_order.get(str(item.get("name")), 10_000))+ protected_metas.sort(key=lambda item: member_order.get(str(item.get("name")), 10_000))+ if remember_duration:+ vault_service.save_vault_settings(conn, {"last_grant_ttl": duration["last_grant_ttl"]})+ except vault_service.RequestNotFoundError as exc:+ raise VaultApiError(f"request '{request_id}' not found", code="request_not_found", status=404) from exc+ except vault_service.InvalidRequestError as exc:+ raise VaultApiError(str(exc), code="invalid_request", status=409) from exc+ except vault_service.InvalidGrantError as exc:+ raise VaultApiError(str(exc), code="invalid_grant") from exc+ except vault_service.VaultServiceError as exc:+ raise VaultApiError(str(exc), code="vault_error") from exc++ if not protected_metas:+ return {+ "ok": True,+ "request_id": request_id,+ "grant_id": option["grant_id"],+ "grant_duration": duration["last_grant_ttl"],+ "ttl_seconds": duration["ttl_seconds"],+ "items": [],+ }++ with engine.begin() as conn:+ key = _load_or_create_vault_daemon_binding_key(conn)++ for meta in protected_metas:+ name = str(meta.get("name") or "")+ try:+ valid_name = vault_crypto.is_valid_secret_name(name)+ except Exception:+ valid_name = False+ if not valid_name:+ raise VaultApiError("invalid secret name (use ^[A-Za-z_][A-Za-z0-9_]*$)", code="invalid_name")+ if meta.get("protection") != "protected":+ raise VaultApiError("agent binding is only valid for protected secrets", code="not_protected", status=409)++ try:+ _require_avault_grant_delivery_surface("resident agent grant")+ agent_pubkey = avault_agent_pubkey()+ except AvaultError as exc:+ raise _vault_api_error_from_avault(exc, prefix="avault agent binding failed") from exc++ now = datetime.now(timezone.utc)+ ttl_seconds = int(duration["ttl_seconds"])+ expires_at = now + timedelta(seconds=ttl_seconds)+ expires_at_unix = int(expires_at.timestamp())+ display = _operation_context_display(request_payload, grantable_members, grant_ttl_seconds=ttl_seconds)+ agent = {+ "publicKey": {+ "public_key": str(agent_pubkey["public_key"]),+ "fingerprint": str(agent_pubkey["fingerprint"]),+ },+ "fingerprint": str(agent_pubkey["fingerprint"]),+ }+ items: list[dict[str, Any]] = []+ issued_items: list[dict[str, Any]] = []+ for meta in protected_metas:+ name = str(meta["name"])+ approval_nonce = os.urandom(16)+ context_request_id = f"vab_{uuid.uuid4().hex}"+ release = {+ "name": name,+ "ttlSecs": ttl_seconds,+ "approvalNonce": list(approval_nonce),+ "approvalExpiresAtUnix": expires_at_unix,+ "operationHash": _agent_deliver_operation_hash(name, ttl_seconds),+ }+ context = {+ "v": 2,+ "purpose": "agent-deliver",+ "requestId": context_request_id,+ "grantId": option["grant_id"],+ "display": display,+ "release": release,+ "agent": agent,+ "expiresAt": _isoformat_z(expires_at),+ }+ signed_context = _signed_operation_context(context, key)+ approval = {+ "nonce": _b64(approval_nonce),+ "expires_at_unix": expires_at_unix,+ }+ items.append(+ {+ "name": name,+ "context": signed_context,+ "approval": approval,+ }+ )+ issued_items.append(+ {+ "name": name,+ "request_id": context_request_id,+ "approval": approval,+ }+ )+ with engine.begin() as conn:+ vault_service.record_request_agent_binding_approvals(+ conn,+ request_id,+ {+ "grant_id": option["grant_id"],+ "grant_duration": duration["last_grant_ttl"],+ "ttl_seconds": ttl_seconds,+ "agent": agent,+ "issued_at": _isoformat_z(now),+ "expires_at": _isoformat_z(expires_at),+ "items": issued_items,+ },+ )+ return {+ "ok": True,+ "request_id": request_id,+ "grant_id": option["grant_id"],+ "grant_duration": duration["last_grant_ttl"],+ "ttl_seconds": ttl_seconds,+ "agent": {+ "publicKey": agent["publicKey"],+ "fingerprint": str(agent_pubkey["fingerprint"]),+ },+ "agent_pubkey": {+ "public_key": str(agent_pubkey["public_key"]),+ "fingerprint": str(agent_pubkey["fingerprint"]),+ },+ "items": items,+ }++def create_vault_agent_binding(payload: dict) -> dict:from storage import vault_crypto, vault_service@@ -1652,31 +1942,41 @@ def create_vault_agent_binding(payload: dict) -> dict:request_id = str(payload.get("request_id") or payload.get("requestId") or "").strip()grant_id = str(payload.get("grant_id") or payload.get("grantId") or "").strip()name = str(payload.get("name") or "").strip()- try:- ttl_seconds = int(payload.get("ttl_seconds") or payload.get("ttlSecs") or 300)- except (TypeError, ValueError) as exc:- raise VaultApiError("ttl_seconds must be an integer", code="invalid_grant") from excif not request_id or not grant_id:raise VaultApiError("request_id and grant_id are required", code="invalid_request", status=409)- if ttl_seconds < 1 or ttl_seconds > 24 * 60 * 60:- raise VaultApiError("ttl_seconds out of bounds", code="invalid_grant")if not vault_crypto.is_valid_secret_name(name):raise VaultApiError("invalid secret name (use ^[A-Za-z_][A-Za-z0-9_]*$)", code="invalid_name")engine = _vault_engine()- with engine.begin() as conn:- option = _grant_option_from_request(conn, request_id)- if grant_id != option["grant_id"]:- raise VaultApiError("grant id does not match the approval request", code="invalid_request", status=409)- if name not in set(option["member_names"]):- raise VaultApiError("secret is not part of the approval request", code="invalid_request", status=409)- try:+ try:+ with engine.begin() as conn:+ option = _grant_option_from_request(conn, request_id)+ if grant_id != option["grant_id"]:+ raise vault_service.InvalidRequestError("grant id does not match the approval request")+ if name not in set(option["member_names"]):+ raise vault_service.InvalidRequestError("secret is not part of the approval request")+ grant_duration_value = _grant_duration_value_from_payload(payload)+ remember_duration = grant_duration_value is not None+ duration = vault_service.normalize_grant_duration(+ grant_duration_value,+ default=option.get("default_grant_duration") or vault_service.get_vault_settings(conn)["last_grant_ttl"],+ )meta = vault_service.get_secret_meta(conn, name)- except vault_service.SecretNotFoundError as exc:- raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc- if meta.get("protection") != "protected":- raise VaultApiError("agent binding is only valid for protected secrets", code="not_protected", status=409)- key = _load_or_create_vault_daemon_binding_key(conn)+ if meta.get("protection") != "protected":+ raise VaultApiError("agent binding is only valid for protected secrets", code="not_protected", status=409)+ key = _load_or_create_vault_daemon_binding_key(conn)+ if remember_duration:+ vault_service.save_vault_settings(conn, {"last_grant_ttl": duration["last_grant_ttl"]})+ except vault_service.SecretNotFoundError as exc:+ raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc+ except vault_service.RequestNotFoundError as exc:+ raise VaultApiError(f"request '{request_id}' not found", code="request_not_found", status=404) from exc+ except vault_service.InvalidRequestError as exc:+ raise VaultApiError(str(exc), code="invalid_request", status=409) from exc+ except vault_service.InvalidGrantError as exc:+ raise VaultApiError(str(exc), code="invalid_grant") from exc+ except vault_service.VaultServiceError as exc:+ raise VaultApiError(str(exc), code="vault_error") from exctry:_require_avault_grant_delivery_surface("resident agent grant")@@ -1684,47 +1984,200 @@ def create_vault_agent_binding(payload: dict) -> dict:except AvaultError as exc:raise _vault_api_error_from_avault(exc, prefix="avault agent binding failed") from exc+ ttl_seconds = int(duration["ttl_seconds"])now = datetime.now(timezone.utc)expires_at = now + timedelta(seconds=ttl_seconds)expires_at_unix = int(expires_at.timestamp())- approval_nonce = list(os.urandom(16))- context = {- "purpose": "agent-deliver",- "name": name,- "grantId": grant_id,- "ttlSecs": ttl_seconds,- "approvalNonce": approval_nonce,- "approvalExpiresAtUnix": expires_at_unix,- "operationHash": _agent_deliver_operation_hash(name, ttl_seconds),+ approval_nonce = os.urandom(16)+ approval = {"nonce": _b64(approval_nonce), "expires_at_unix": expires_at_unix}+ agent = {+ "publicKey": {+ "public_key": str(agent_pubkey["public_key"]),+ "fingerprint": str(agent_pubkey["fingerprint"]),+ },+ "fingerprint": str(agent_pubkey["fingerprint"]),}binding = {"challengeId": f"vab_{uuid.uuid4().hex}","requestId": request_id,"grantId": grant_id,- "agent": {- "publicKey": {- "public_key": str(agent_pubkey["public_key"]),- "fingerprint": str(agent_pubkey["fingerprint"]),- },- "fingerprint": str(agent_pubkey["fingerprint"]),+ "agent": agent,+ "context": {+ "purpose": "agent-deliver",+ "name": name,+ "grantId": grant_id,+ "ttlSecs": ttl_seconds,+ "approvalNonce": list(approval_nonce),+ "approvalExpiresAtUnix": expires_at_unix,+ "operationHash": _agent_deliver_operation_hash(name, ttl_seconds),},- "context": context,- "expiresAt": expires_at.isoformat().replace("+00:00", "Z"),+ "expiresAt": _isoformat_z(expires_at),}+ signed_binding = _signed_agent_binding(binding, key)+ with engine.begin() as conn:+ vault_service.record_request_agent_binding_approvals(+ conn,+ request_id,+ {+ "grant_id": grant_id,+ "grant_duration": duration["last_grant_ttl"],+ "ttl_seconds": ttl_seconds,+ "agent": agent,+ "issued_at": _isoformat_z(now),+ "expires_at": _isoformat_z(expires_at),+ "items": [{"name": name, "request_id": binding["challengeId"], "approval": approval}],+ },+ )return {"ok": True,+ "request_id": request_id,+ "grant_id": grant_id,+ "grant_duration": duration["last_grant_ttl"],+ "ttl_seconds": ttl_seconds,"agent_pubkey": {"public_key": str(agent_pubkey["public_key"]),"fingerprint": str(agent_pubkey["fingerprint"]),},- "binding": _signed_agent_binding(binding, key),- "approval": {- "nonce": _b64(bytes(approval_nonce)),- "expires_at_unix": expires_at_unix,- },+ "binding": signed_binding,+ "approval": approval,}+def create_vault_reveal_context(name: str, payload: dict | None = None) -> dict:+ from storage import vault_crypto, vault_service++ secret_name = str(name or "").strip()+ if not vault_crypto.is_valid_secret_name(secret_name):+ raise VaultApiError("invalid secret name (use ^[A-Za-z_][A-Za-z0-9_]*$)", code="invalid_name")+ body = payload if isinstance(payload, dict) else {}+ try:+ ttl_seconds = int(body.get("ttl_seconds") or body.get("ttlSecs") or 120)+ except (TypeError, ValueError) as exc:+ raise VaultApiError("ttl_seconds must be an integer", code="invalid_request") from exc+ ttl_seconds = max(1, min(ttl_seconds, 10 * 60))+ engine = _vault_engine()+ context_request_id = f"vrl_{uuid.uuid4().hex}"+ expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)+ try:+ with engine.begin() as conn:+ meta = vault_service.get_secret_meta(conn, secret_name)+ if meta.get("protection") != "protected":+ raise VaultApiError("reveal context is only valid for protected secrets", code="not_protected", status=409)+ envelope = vault_service.get_protected_record_envelope(conn, secret_name)+ key = _load_or_create_vault_daemon_binding_key(conn)+ envelope_payload = _envelope_payload(envelope)+ context = {+ "v": 2,+ "purpose": "reveal",+ "requestId": context_request_id,+ "display": _operation_context_display(+ {+ "card": {+ "command": body.get("command"),+ "egress": body.get("egress"),+ "session_id": body.get("session_label") or body.get("sessionLabel"),+ "source_selector": body.get("source") if isinstance(body.get("source"), dict) else {},+ }+ },+ [meta],+ ),+ "release": {+ "name": secret_name,+ "envelopeHash": _envelope_hash(envelope_payload),+ },+ "expiresAt": _isoformat_z(expires_at),+ }+ signed_context = _signed_operation_context(context, key)+ except vault_service.SecretNotFoundError as exc:+ raise VaultApiError(f"secret '{secret_name}' not found", code="secret_not_found", status=404) from exc+ except vault_service.KeypairNotValueDeliverableError as exc:+ raise VaultApiError(str(exc), code="keypair_not_value_deliverable", status=409) from exc+ return {"ok": True, "context": signed_context, "envelope": envelope_payload}+++def get_vault_settings() -> dict:+ from storage import vault_service++ engine = _vault_engine()+ with engine.begin() as conn:+ settings = vault_service.get_vault_settings(conn)+ return {"ok": True, "settings": settings, "policy": vault_service.vault_session_policy(settings)}+++def save_vault_settings(payload: dict) -> dict:+ from storage import vault_service++ if not isinstance(payload, dict):+ raise VaultApiError("payload must be an object", code="invalid_payload")+ allowed = {"unlock_window_seconds", "strict_approvals", "last_grant_ttl"}+ extra = set(payload) - allowed+ if extra:+ raise VaultApiError(f"unsupported vault settings fields: {', '.join(sorted(extra))}", code="invalid_request", status=409)+ engine = _vault_engine()+ try:+ with engine.begin() as conn:+ settings = vault_service.save_vault_settings(conn, payload)+ except vault_service.InvalidGrantError as exc:+ raise VaultApiError(str(exc), code="invalid_grant") from exc+ except vault_service.VaultServiceError as exc:+ raise VaultApiError(str(exc), code="invalid_request", status=409) from exc+ return {"ok": True, "settings": settings, "policy": vault_service.vault_session_policy(settings)}+++def _request_context_expires_at(request_payload: dict[str, Any]) -> str:+ expires_at = _parse_iso_utc(request_payload.get("expires_at"))+ if expires_at is None:+ expires_at = datetime.now(timezone.utc) + timedelta(seconds=30 * 60)+ return _isoformat_z(expires_at)+++def _attach_signed_sign_operation_context(+ request_id: str,+ *,+ audience: str | None = None,+) -> dict:+ from storage import vault_service++ response_audience = audience or vault_service.REQUEST_AUDIENCE_AGENT+ engine = _vault_engine()+ try:+ with engine.begin() as conn:+ request_payload = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_UI)+ if request_payload.get("request_type") != "sign":+ raise vault_service.InvalidRequestError("operation context can only be attached to sign requests")+ meta = vault_service.get_secret_meta(conn, str(request_payload.get("secret_name") or ""))+ key = _load_or_create_vault_daemon_binding_key(conn)+ context = {+ "v": 2,+ "purpose": "sign",+ "requestId": request_id,+ "display": _operation_context_display(request_payload, [meta]),+ "expiresAt": _request_context_expires_at(request_payload),+ }+ signed = _signed_operation_context(context, key)+ return vault_service.set_request_operation_context(+ conn,+ request_id,+ signed,+ audience=response_audience,+ )+ except vault_service.SecretNotFoundError as exc:+ raise VaultApiError(f"secret '{exc}' not found", code="secret_not_found", status=404) from exc+ except vault_service.RequestNotFoundError as exc:+ raise VaultApiError(f"request '{request_id}' not found", code="request_not_found", status=404) from exc+ except vault_service.InvalidRequestError as exc:+ raise VaultApiError(str(exc), code="invalid_request", status=409) from exc+++def _sign_request_response_audience(request: dict[str, Any]) -> str:+ from storage import vault_service++ card = request.get("card") if isinstance(request.get("card"), dict) else {}+ if "secret_unlock_material" in card or "unlock_material" in card:+ return vault_service.REQUEST_AUDIENCE_UI+ return vault_service.REQUEST_AUDIENCE_AGENT++def _vault_webauthn_context(origin: str | None):from storage import vault_webauthn@@ -2141,6 +2594,19 @@ def _vault_requester_payload(payload: dict) -> dict:return out+def _vault_ui_requester_payload(payload: dict) -> dict:+ requester = payload.get("requester") if isinstance(payload.get("requester"), dict) else {}+ session_id = str(payload.get("session_id") or requester.get("session_id") or "").strip()+ out = dict(requester)+ if session_id:+ out["session_id"] = session_id+ if payload.get("run_id"):+ out["run_id"] = str(payload["run_id"])+ if payload.get("skill"):+ out["skill"] = str(payload["skill"])+ return out++def _vault_delivery_payload(payload: dict) -> dict:delivery = dict(payload.get("delivery") if isinstance(payload.get("delivery"), dict) else {})for key in ("session_id", "skill", "command", "egress", "mode"):@@ -2246,7 +2712,7 @@ def request_vault_sign(payload: dict) -> dict:digest=digest,scheme=scheme,signing_context=signing_context,- requester=_vault_requester_payload(payload),+ requester=_vault_ui_requester_payload(payload),delivery=_vault_delivery_payload(payload),expires_at=_expires_at_from_ttl(payload),)@@ -2256,6 +2722,10 @@ def request_vault_sign(payload: dict) -> dict:raise VaultApiError(str(exc), code="invalid_request", status=409) from excexcept vault_service.VaultServiceError as exc:raise VaultApiError(str(exc), code="vault_error") from exc+ request = _attach_signed_sign_operation_context(+ str(request["id"]),+ audience=_sign_request_response_audience(request),+ )_publish_vaults_updated(scope="request",request_id=request.get("id"),@@ -2313,15 +2783,24 @@ def _parse_iso_utc(value: object) -> datetime | None:return parsed.astimezone(timezone.utc)+def _remaining_ttl_seconds(expires_at: datetime) -> int:+ remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()+ return max(1, int(round(remaining)))+++def _binding_relay_ttl_seconds(expires_at: datetime, requested_ttl_seconds: int) -> int:+ remaining = (expires_at - datetime.now(timezone.utc)).total_seconds()+ if remaining <= 0:+ raise VaultApiError("resident agent DEK binding context has expired", code="invalid_grant")+ remaining_seconds = max(1, int(remaining))+ return min(requested_ttl_seconds, remaining_seconds)++def _grant_ttl_seconds(grant: dict) -> int:- created_at = _parse_iso_utc(grant.get("created_at"))expires_at = _parse_iso_utc(grant.get("expires_at"))if expires_at is None:return 1- if created_at is None:- return 1- approved_lifetime = (expires_at - created_at).total_seconds()- return max(1, int(round(approved_lifetime)))+ return _remaining_ttl_seconds(expires_at)def _release_one_shot_agent_grant(grant: dict | None, *, reason: str) -> None:@@ -2456,6 +2935,102 @@ def _resident_agent_deks_from_payload(payload: dict, *, needs_agent_deks: bool)return agent_deks+def _agent_binding_record_items(record: dict[str, Any]) -> list[dict[str, Any]]:+ items = record.get("items")+ return items if isinstance(items, list) else []+++def _agent_binding_record_matches_agent(record: dict[str, Any], expected_pubkey: dict[str, Any] | None) -> bool:+ if expected_pubkey is None:+ return False+ agent = record.get("agent") if isinstance(record.get("agent"), dict) else {}+ public_key = agent.get("publicKey") if isinstance(agent.get("publicKey"), dict) else {}+ expected_public_key = str(expected_pubkey.get("public_key") or "")+ expected_fingerprint = str(expected_pubkey.get("fingerprint") or "")+ if not expected_public_key and not expected_fingerprint:+ return False+ record_public_key = str(public_key.get("public_key") or "")+ record_fingerprint = str(public_key.get("fingerprint") or agent.get("fingerprint") or "")+ if expected_public_key and record_public_key != expected_public_key:+ return False+ if expected_fingerprint and record_fingerprint != expected_fingerprint:+ return False+ return True+++def _request_agent_binding_records(request: dict[str, Any]) -> list[dict[str, Any]]:+ delivery = request.get("delivery") if isinstance(request.get("delivery"), dict) else {}+ records = delivery.get("agent_binding_approvals")+ return [record for record in records if isinstance(record, dict)] if isinstance(records, list) else []+++def _validate_agent_binding_approvals(+ request: dict[str, Any],+ *,+ grant_id: str,+ agent_deks: list[dict[str, Any]],+ expected_pubkey: dict[str, Any] | None,+ grant_duration: Any | None,+) -> Any | None:+ from storage import vault_service++ records = _request_agent_binding_records(request)+ if not records:+ raise VaultApiError("resident agent DEKs do not match an issued binding context", code="invalid_grant")+ expected_duration = (+ vault_service.normalize_grant_duration(grant_duration)["last_grant_ttl"] if grant_duration is not None else None+ )+ now = datetime.now(timezone.utc)+ matched_durations: set[Any] = set()+ matched_ttl_seconds: set[int] = set()+ matched_expires_at: list[datetime] = []+ for dek in agent_deks:+ dek_name = str(dek.get("name") or "")+ dek_approval = dek.get("approval")+ matched_record: dict[str, Any] | None = None+ for record in records:+ if str(record.get("grant_id") or "") != grant_id:+ continue+ if not _agent_binding_record_matches_agent(record, expected_pubkey):+ continue+ record_expires_at = _parse_iso_utc(record.get("expires_at"))+ if record_expires_at is None or record_expires_at <= now:+ continue+ duration = record.get("grant_duration")+ if expected_duration is not None and vault_service.normalize_grant_duration(duration)["last_grant_ttl"] != expected_duration:+ continue+ for item in _agent_binding_record_items(record):+ if item.get("name") == dek_name and item.get("approval") == dek_approval:+ matched_record = record+ break+ if matched_record is not None:+ break+ if matched_record is None:+ raise VaultApiError("resident agent DEKs do not match issued binding contexts", code="invalid_grant")+ normalized_duration = vault_service.normalize_grant_duration(matched_record.get("grant_duration"))+ matched_durations.add(normalized_duration["last_grant_ttl"])+ try:+ issued_ttl_seconds = int(matched_record.get("ttl_seconds", normalized_duration["ttl_seconds"]))+ except (TypeError, ValueError) as exc:+ raise VaultApiError("resident agent DEK binding context has invalid TTL", code="invalid_grant") from exc+ if issued_ttl_seconds < 1:+ raise VaultApiError("resident agent DEK binding context has invalid TTL", code="invalid_grant")+ matched_ttl_seconds.add(issued_ttl_seconds)+ record_expires_at = _parse_iso_utc(matched_record.get("expires_at"))+ if record_expires_at is None:+ raise VaultApiError("resident agent DEK binding context has invalid expiry", code="invalid_grant")+ matched_expires_at.append(record_expires_at)+ if len(matched_durations) != 1:+ raise VaultApiError("resident agent DEK binding contexts disagree on grant duration", code="invalid_grant")+ if len(matched_ttl_seconds) != 1:+ raise VaultApiError("resident agent DEK binding contexts disagree on grant TTL", code="invalid_grant")+ return {+ "grant_duration": next(iter(matched_durations)),+ "ttl_seconds": next(iter(matched_ttl_seconds)),+ "expires_at": _isoformat_z(min(matched_expires_at)),+ }++def _access_request_secret_name(request_id: str) -> str:from storage import vault_service@@ -2507,6 +3082,7 @@ def _grant_option_from_request(conn, request_id: str) -> dict[str, Any]:"source_selector": source_selector,"purpose": purpose,"one_shot": bool(option.get("one_shot")),+ "default_grant_duration": option.get("default_grant_duration"),}@@ -2570,20 +3146,23 @@ def create_vault_grant(payload: dict) -> dict:if not isinstance(payload, dict):raise VaultApiError("payload must be an object", code="invalid_payload")- ttl = payload.get("ttl_seconds")- try:- ttl_seconds = int(ttl) if ttl is not None else None- except (TypeError, ValueError) as exc:- raise VaultApiError("ttl_seconds must be an integer", code="invalid_grant") from exc+ grant_duration = _grant_duration_value_from_payload(payload)+ if grant_duration is not None:+ try:+ vault_service.normalize_grant_duration(grant_duration)+ except vault_service.InvalidGrantError as exc:+ raise VaultApiError(str(exc), code="invalid_grant") from excrequest_id = payload.get("request_id")if not request_id:raise VaultApiError("request_id is required to create a grant", code="missing_request_id")request_id = str(request_id)engine = _vault_engine()preflight_error: Exception | None = None+ request_for_grant: dict[str, Any] | None = Nonewith engine.begin() as conn:try:option = _grant_option_from_request(conn, request_id)+ request_for_grant = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)member_names = payload.get("member_names") if isinstance(payload.get("member_names"), list) else option["member_names"]member_names = [str(name) for name in member_names if isinstance(name, str) and name]source_selector = payload.get("source_selector") if isinstance(payload.get("source_selector"), dict) else option["source_selector"]@@ -2618,6 +3197,8 @@ def create_vault_grant(payload: dict) -> dict:raise VaultApiError("grant has no grantable static secrets", code="not_grantable", status=409)protected_member_names = {str(member["name"]) for member in grantable_members if member.get("protection") == "protected"}needs_agent_deks = bool(protected_member_names)+ binding_grant_expires_at: str | None = None+ binding_relay_ttl_seconds: int | None = Noneagent_deks = _resident_agent_deks_from_payload(payload, needs_agent_deks=needs_agent_deks)provided_names = {item["name"] for item in agent_deks}@@ -2631,6 +3212,26 @@ def create_vault_grant(payload: dict) -> dict:validate_avault_agent_pubkey(expected_pubkey)except AvaultError as exc:raise _vault_api_error_from_avault(exc, prefix="avault agent grant failed") from exc+ binding = _validate_agent_binding_approvals(+ request_for_grant or {},+ grant_id=option["grant_id"],+ agent_deks=agent_deks,+ expected_pubkey=expected_pubkey,+ grant_duration=grant_duration,+ )+ if grant_duration is None:+ grant_duration = binding["grant_duration"]+ binding_grant_expires_at = binding["expires_at"]+ try:+ binding_requested_ttl_seconds = int(binding["ttl_seconds"])+ except (KeyError, TypeError, ValueError) as exc:+ raise VaultApiError("resident agent DEK binding context has invalid ttl", code="invalid_grant") from exc+ if binding_requested_ttl_seconds < 1:+ raise VaultApiError("resident agent DEK binding context has invalid ttl", code="invalid_grant")+ binding_expires_at = _parse_iso_utc(binding_grant_expires_at)+ if binding_expires_at is None:+ raise VaultApiError("resident agent DEK binding context has invalid expiry", code="invalid_grant")+ binding_relay_ttl_seconds = _binding_relay_ttl_seconds(binding_expires_at, binding_requested_ttl_seconds)session_id = payload.get("session_id")inherit_request_session = payload.get("this_session_only") is not Falseif not inherit_request_session:@@ -2643,7 +3244,8 @@ def create_vault_grant(payload: dict) -> dict:source_selector=source_selector,purpose=purpose,session_id=str(session_id) if session_id else None,- ttl_seconds=ttl_seconds,+ grant_duration=grant_duration,+ expires_at=binding_grant_expires_at,request_id=request_id,inherit_request_session=inherit_request_session,expected_member_names=expected_member_names,@@ -2670,7 +3272,7 @@ def create_vault_grant(payload: dict) -> dict:return {"ok": True, "grant": grant}agent_relayed = Falsetry:- relay_ttl = _grant_ttl_seconds(grant)+ relay_ttl = binding_relay_ttl_seconds if binding_relay_ttl_seconds is not None else _grant_ttl_seconds(grant)agent_result = avault_agent_grant(grant_id=str(grant["id"]),purpose=str(grant.get("purpose") or purpose),@@ -2682,7 +3284,7 @@ def create_vault_grant(payload: dict) -> dict:raise AvaultError("avault agent grant cached fewer DEKs than requested")agent_relayed = Truewith engine.begin() as conn:- grant = vault_service.mark_grant_agent_ready(conn, str(grant["id"]), ttl_seconds=relay_ttl)+ grant = vault_service.mark_grant_agent_ready(conn, str(grant["id"]), expires_at=str(grant.get("expires_at") or ""))except (vault_service.InvalidGrantError, vault_service.GrantNotActiveError) as exc:if agent_relayed:_cleanup_failed_agent_grant(@@ -3217,6 +3819,17 @@ def vault_sign(payload: dict) -> dict:except vault_service.VaultServiceError as exc:raise VaultApiError(str(exc), code="vault_error") from exc+ if protected_response is not None and isinstance(protected_response.get("request"), dict):+ request_id_for_context = str(protected_response["request"].get("id") or "")+ if request_id_for_context and protected_response.get("code") in {"browser_signature_required", "approval_required"}:+ request_with_context = _attach_signed_sign_operation_context(+ request_id_for_context,+ audience=_sign_request_response_audience(protected_response["request"]),+ )+ protected_response["request"] = request_with_context+ if approval_required_request is not None and approval_required_request.get("id") == request_id_for_context:+ approval_required_request = request_with_context+if protected_response is not None:if protected_event is not None:_publish_vaults_updated(**protected_event)diff --git a/vibe/cli.py b/vibe/cli.pyindex fa6876502..1289c0a0e 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -6704,6 +6704,7 @@ def cmd_vault_sign(args):signature=result.get("signature"),)return 0+ request = api._attach_signed_sign_operation_context(str(request["id"]))_publish_cli_vaults_updated(scope="request", request=request)_print_cli_payload("vault_sign_request",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 9480683a3..94caf0f2b 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3214,6 +3214,16 @@ def vault_sandbox_root_metadata_get():return _vault_error_response(exc)[email protected]("/api/vault/agent-bindings:batch", methods=["POST"])+def vault_agent_bindings_batch_post():+ from vibe import api++ try:+ return jsonify(api.create_vault_agent_bindings_batch(request.json or {}))+ except ValueError as exc:+ return _vault_error_response(exc)++@app.route("/api/vault/agent-binding", methods=["POST"])def vault_agent_binding_post():from vibe import api@@ -3224,6 +3234,26 @@ def vault_agent_binding_post():return _vault_error_response(exc)[email protected]("/api/vault/settings", methods=["GET"])+def vault_settings_get():+ from vibe import api++ try:+ return jsonify(api.get_vault_settings())+ except ValueError as exc:+ return _vault_error_response(exc)++[email protected]("/api/vault/settings", methods=["PATCH"])+def vault_settings_patch():+ from vibe import api++ try:+ return jsonify(api.save_vault_settings(request.json or {}))+ except ValueError as exc:+ return _vault_error_response(exc)++@app.route("/api/vault/vmk", methods=["GET"])def vault_vmk_get():from vibe import api@@ -3291,6 +3321,16 @@ def vault_secret_delete(name):return _vault_error_response(exc)[email protected]("/api/vault/secrets/<name>/reveal-context", methods=["POST"])+def vault_secret_reveal_context_post(name):+ from vibe import api++ try:+ return jsonify(api.create_vault_reveal_context(name, request.json or {}))+ except ValueError as exc:+ return _vault_error_response(exc)++@app.route("/api/vault/requests", methods=["GET"])def vault_requests_get():from vibe import api