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
Refactor Vault grants around grant ids (#756)
Call White44fdaa1d2530
diff --git a/storage/alembic/versions/20260621_0023_vault_tables.py b/storage/alembic/versions/20260621_0023_vault_tables.pyindex 32ecd96b9..3599c5135 100644--- a/storage/alembic/versions/20260621_0023_vault_tables.py+++ b/storage/alembic/versions/20260621_0023_vault_tables.py@@ -7,8 +7,6 @@ Create Date: 2026-06-21 (re-parented onto 20260622_0023 to linearize after mastefrom __future__ import annotations-from datetime import datetime, timezone-import sqlalchemy as safrom alembic import op@@ -26,22 +24,11 @@ def _tables() -> set[str]:def upgrade() -> None:existing = _tables()- if "vault_groups" not in existing:- op.create_table(- "vault_groups",- sa.Column("name", sa.String(), primary_key=True),- sa.Column("description", sa.Text(), nullable=True),- sa.Column("grantable", sa.Integer(), nullable=False, server_default="1"),- sa.Column("max_grant_ttl_seconds", sa.Integer(), nullable=False, server_default="900"),- sa.Column("created_at", sa.String(), nullable=False),- )-if "vault_secrets" not in existing:op.create_table("vault_secrets",sa.Column("id", sa.String(), primary_key=True),sa.Column("name", sa.String(), nullable=False),- sa.Column("group_name", sa.String(), sa.ForeignKey("vault_groups.name"), nullable=False, server_default="default"),sa.Column("tags", sa.Text(), nullable=True),sa.Column("kind", sa.String(), nullable=False, server_default="static"),sa.Column("protection", sa.String(), nullable=False, server_default="standard"),@@ -58,20 +45,7 @@ def upgrade() -> None:sa.Column("updated_at", sa.String(), nullable=False),sa.UniqueConstraint("name", name="uq_vault_secrets_name"),)- op.create_index("ix_vault_secrets_group", "vault_secrets", ["group_name"], if_not_exists=True)-- if "vault_links" not in existing:- op.create_table(- "vault_links",- sa.Column("id", sa.String(), primary_key=True),- sa.Column("secret_name", sa.String(), sa.ForeignKey("vault_secrets.name", ondelete="CASCADE"), nullable=False),- sa.Column("skill_name", sa.String(), nullable=False),- sa.Column("source", sa.String(), nullable=False),- sa.Column("required", sa.Integer(), nullable=False, server_default="1"),- sa.Column("created_at", sa.String(), nullable=False),- sa.UniqueConstraint("secret_name", "skill_name", name="uq_vault_links_secret_skill"),- )- op.create_index("ix_vault_links_skill", "vault_links", ["skill_name"], if_not_exists=True)+ op.create_index("ix_vault_secrets_name_kind", "vault_secrets", ["name", "kind"], if_not_exists=True)if "vault_requests" not in existing:op.create_table(@@ -93,17 +67,22 @@ def upgrade() -> None:op.create_table("vault_grants",sa.Column("id", sa.String(), primary_key=True),- sa.Column("scope_type", sa.String(), nullable=False),- sa.Column("scope_ref", sa.String(), nullable=False),- sa.Column("member_snapshot", sa.Text(), nullable=True),+ sa.Column("member_snapshot", sa.Text(), nullable=False),+ sa.Column("source_selector", sa.Text(), nullable=True),+ sa.Column("request_id", sa.String(), nullable=True),sa.Column("session_id", sa.String(), nullable=True),+ sa.Column("purpose", sa.String(), nullable=False, server_default="run"),sa.Column("status", sa.String(), nullable=False, server_default="active"),- sa.Column("created_by_request_id", sa.String(), nullable=True),+ sa.Column("one_shot", sa.Integer(), nullable=False, server_default="0"),sa.Column("created_at", sa.String(), nullable=False),sa.Column("expires_at", sa.String(), nullable=False),sa.Column("revoked_at", sa.String(), nullable=True),+ sa.Column("agent_ready", sa.Integer(), nullable=False, server_default="0"),+ sa.Column("agent_ready_at", sa.String(), nullable=True),)op.create_index("ix_vault_grants_status_expires", "vault_grants", ["status", "expires_at"], if_not_exists=True)+ op.create_index("ix_vault_grants_request", "vault_grants", ["request_id"], if_not_exists=True)+ op.create_index("ix_vault_grants_session_purpose", "vault_grants", ["session_id", "purpose"], if_not_exists=True)if "vault_audit" not in existing:op.create_table(@@ -120,24 +99,16 @@ def upgrade() -> None:op.create_index("ix_vault_audit_ts", "vault_audit", ["ts"], if_not_exists=True)op.create_index("ix_vault_audit_secret_ts", "vault_audit", ["secret_name", "ts"], if_not_exists=True)- # Seed the implicit ``default`` group (idempotent).- now = datetime.now(timezone.utc).isoformat()- op.get_bind().exec_driver_sql(- "insert or ignore into vault_groups (name, description, grantable, max_grant_ttl_seconds, created_at) "- f"values ('default', 'Default group', 1, 900, '{now}')"- )-def downgrade() -> None:op.drop_index("ix_vault_audit_secret_ts", table_name="vault_audit", if_exists=True)op.drop_index("ix_vault_audit_ts", table_name="vault_audit", if_exists=True)op.drop_table("vault_audit")+ op.drop_index("ix_vault_grants_session_purpose", table_name="vault_grants", if_exists=True)+ op.drop_index("ix_vault_grants_request", table_name="vault_grants", if_exists=True)op.drop_index("ix_vault_grants_status_expires", table_name="vault_grants", if_exists=True)op.drop_table("vault_grants")op.drop_index("ix_vault_requests_status_created", table_name="vault_requests", if_exists=True)op.drop_table("vault_requests")- op.drop_index("ix_vault_links_skill", table_name="vault_links", if_exists=True)- op.drop_table("vault_links")- op.drop_index("ix_vault_secrets_group", table_name="vault_secrets", if_exists=True)+ op.drop_index("ix_vault_secrets_name_kind", table_name="vault_secrets", if_exists=True)op.drop_table("vault_secrets")- op.drop_table("vault_groups")diff --git a/storage/alembic/versions/20260703_0026_vault_grant_id_tags_refactor.py b/storage/alembic/versions/20260703_0026_vault_grant_id_tags_refactor.pynew file mode 100644index 000000000..ddaa032a1--- /dev/null+++ b/storage/alembic/versions/20260703_0026_vault_grant_id_tags_refactor.py@@ -0,0 +1,206 @@+"""vault grant-id and tag selector refactor++Revision ID: 20260703_0026+Revises: 20260627_0025+Create Date: 2026-07-03+"""++from __future__ import annotations++import json+from datetime import datetime, timezone++import sqlalchemy as sa+from alembic import op++revision = "20260703_0026"+down_revision = "20260627_0025"+branch_labels = None+depends_on = None+++def _table_exists(name: str) -> bool:+ bind = op.get_bind()+ return bind.exec_driver_sql(+ "select 1 from sqlite_master where type = 'table' and name = ?",+ (name,),+ ).first() is not None+++def _columns(table_name: str) -> set[str]:+ bind = op.get_bind()+ return {row[1] for row in bind.exec_driver_sql(f'pragma table_info("{table_name}")')}+++def _create_vault_secrets(table_name: str = "vault_secrets") -> None:+ op.create_table(+ table_name,+ sa.Column("id", sa.String(), primary_key=True),+ sa.Column("name", sa.String(), nullable=False),+ sa.Column("tags", sa.Text(), nullable=True),+ sa.Column("kind", sa.String(), nullable=False, server_default="static"),+ sa.Column("protection", sa.String(), nullable=False, server_default="standard"),+ sa.Column("signer_kind", sa.String(), nullable=True),+ sa.Column("source", sa.String(), nullable=False, server_default="manual"),+ sa.Column("ciphertext", sa.Text(), nullable=True),+ sa.Column("nonce", sa.Text(), nullable=True),+ sa.Column("wrap_meta", sa.Text(), nullable=True),+ sa.Column("public_meta", sa.Text(), nullable=True),+ sa.Column("policy", sa.Text(), nullable=True),+ sa.Column("last_used_at", sa.String(), nullable=True),+ sa.Column("use_count", sa.Integer(), nullable=False, server_default="0"),+ sa.Column("created_at", sa.String(), nullable=False),+ sa.Column("updated_at", sa.String(), nullable=False),+ sa.UniqueConstraint("name", name=f"uq_{table_name}_name" if table_name != "vault_secrets" else "uq_vault_secrets_name"),+ )+++def _create_vault_grants() -> None:+ op.create_table(+ "vault_grants",+ sa.Column("id", sa.String(), primary_key=True),+ sa.Column("member_snapshot", sa.Text(), nullable=False),+ sa.Column("source_selector", sa.Text(), nullable=True),+ sa.Column("request_id", sa.String(), nullable=True),+ sa.Column("session_id", sa.String(), nullable=True),+ sa.Column("purpose", sa.String(), nullable=False, server_default="run"),+ sa.Column("status", sa.String(), nullable=False, server_default="active"),+ sa.Column("one_shot", sa.Integer(), nullable=False, server_default="0"),+ sa.Column("created_at", sa.String(), nullable=False),+ sa.Column("expires_at", sa.String(), nullable=False),+ sa.Column("revoked_at", sa.String(), nullable=True),+ sa.Column("agent_ready", sa.Integer(), nullable=False, server_default="0"),+ sa.Column("agent_ready_at", sa.String(), nullable=True),+ )+++def _merge_json_tags(raw: str | None, added_tags: set[str]) -> str:+ try:+ current = json.loads(raw) if raw else []+ except json.JSONDecodeError:+ current = []+ tags = [str(tag) for tag in current if isinstance(tag, str) and tag]+ seen = set(tags)+ for tag in sorted(added_tags):+ if tag not in seen:+ tags.append(tag)+ seen.add(tag)+ return json.dumps(tags)+++def _preserve_skill_links_as_tags() -> None:+ if not _table_exists("vault_links") or not _table_exists("vault_secrets") or "tags" not in _columns("vault_secrets"):+ return+ bind = op.get_bind()+ links: dict[str, set[str]] = {}+ for row in bind.exec_driver_sql("select secret_name, skill_name from vault_links").mappings():+ secret_name = str(row.get("secret_name") or "").strip()+ skill_name = str(row.get("skill_name") or "").strip()+ if not secret_name or not skill_name:+ continue+ tag = skill_name if skill_name.startswith("skill:") else f"skill:{skill_name}"+ links.setdefault(secret_name, set()).add(tag)+ for secret_name, added_tags in links.items():+ current = bind.exec_driver_sql("select tags from vault_secrets where name = ?", (secret_name,)).first()+ if current is None:+ continue+ bind.exec_driver_sql(+ "update vault_secrets set tags = ? where name = ?",+ (_merge_json_tags(current[0], added_tags), secret_name),+ )+++def _pending_access_card_is_legacy(delivery_raw: str | None) -> bool:+ try:+ delivery = json.loads(delivery_raw) if delivery_raw else {}+ except json.JSONDecodeError:+ return True+ if not isinstance(delivery, dict):+ return True+ card = delivery.get("card")+ if not isinstance(card, dict):+ return True+ if "scope_options" in card:+ return True+ options = card.get("grant_options")+ if not isinstance(options, list) or len(options) != 1 or not isinstance(options[0], dict):+ return True+ return not bool(str(options[0].get("grant_id") or "").strip())+++def _retire_legacy_pending_access_requests() -> None:+ if not _table_exists("vault_requests"):+ return+ bind = op.get_bind()+ now = datetime.now(timezone.utc).isoformat()+ legacy_ids = [+ str(row["id"])+ for row in bind.exec_driver_sql(+ """+ select id, delivery+ from vault_requests+ where request_type = 'access' and status = 'pending'+ """+ ).mappings()+ if _pending_access_card_is_legacy(row.get("delivery"))+ ]+ for request_id in legacy_ids:+ bind.exec_driver_sql(+ "update vault_requests set status = 'expired', decided_at = ? where id = ? and status = 'pending'",+ (now, request_id),+ )+++def upgrade() -> None:+ bind = op.get_bind()++ _retire_legacy_pending_access_requests()++ if _table_exists("vault_links"):+ _preserve_skill_links_as_tags()+ op.drop_index("ix_vault_links_skill", table_name="vault_links", if_exists=True)+ op.drop_table("vault_links")++ if _table_exists("vault_secrets") and "group_name" in _columns("vault_secrets"):+ op.drop_index("ix_vault_secrets_group", table_name="vault_secrets", if_exists=True)+ _create_vault_secrets("vault_secrets_new")+ bind.exec_driver_sql(+ """+ insert into vault_secrets_new (+ id, name, tags, kind, protection, signer_kind, source,+ ciphertext, nonce, wrap_meta, public_meta, policy,+ last_used_at, use_count, created_at, updated_at+ )+ select+ id, name, tags, kind, protection, signer_kind, source,+ ciphertext, nonce, wrap_meta, public_meta, policy,+ last_used_at, use_count, created_at, updated_at+ from vault_secrets+ """+ )+ op.drop_table("vault_secrets")+ op.rename_table("vault_secrets_new", "vault_secrets")++ if _table_exists("vault_secrets"):+ op.create_index("ix_vault_secrets_name_kind", "vault_secrets", ["name", "kind"], if_not_exists=True)++ if _table_exists("vault_groups"):+ op.drop_table("vault_groups")++ if _table_exists("vault_grants"):+ grant_cols = _columns("vault_grants")+ if {"scope_type", "scope_ref"} & grant_cols or "request_id" not in grant_cols:+ op.drop_index("ix_vault_grants_status_expires", table_name="vault_grants", if_exists=True)+ op.drop_table("vault_grants")+ _create_vault_grants()+ else:+ _create_vault_grants()++ op.create_index("ix_vault_grants_status_expires", "vault_grants", ["status", "expires_at"], if_not_exists=True)+ op.create_index("ix_vault_grants_request", "vault_grants", ["request_id"], if_not_exists=True)+ op.create_index("ix_vault_grants_session_purpose", "vault_grants", ["session_id", "purpose"], if_not_exists=True)+++def downgrade() -> None:+ # Vaults has not launched; keep the forward-only refactor simple.+ return Nonediff --git a/storage/models.py b/storage/models.pyindex 576f792d2..01f1aa353 100644--- a/storage/models.py+++ b/storage/models.py@@ -454,34 +454,20 @@ web_push_subscriptions = Table(Index("ix_web_push_subscriptions_user_device", "user_key", "device_id"),)-# Vaults — secret management for agents (design: docs/plans/vaults.md).-# A named secret is referenced by a globally-unique env-style ``name``; ``group_name``-# is a lightweight organizational + unlock-scope axis (NOT a separate keyspace, NOT a-# 1Password-style multi-vault container). Values are envelope-encrypted at rest-# (storage/vault_crypto.py): standard tier under a machine key, protected tier (P1)-# under a password/passkey-derived key. ``ciphertext``/``nonce`` are base64 text and-# ``wrap_meta`` is a JSON blob of the wrapped DEK + scheme — there is deliberately no-# plaintext column. The ``vault_secrets`` table is denylisted in ``vibe data query``.-vault_groups = Table(- "vault_groups",- metadata,- Column("name", String, primary_key=True),- Column("description", Text, nullable=True),- # Whether secrets in this group may be covered by a scope grant (P1). Stored as- # Integer (0/1) per the codebase boolean convention. Forced 0 if the group holds- # a keypair (signing is never grantable).- Column("grantable", Integer, nullable=False, server_default="1"),- Column("max_grant_ttl_seconds", Integer, nullable=False, server_default="900"),- Column("created_at", String, nullable=False),-)-+# Vaults — secret management for agents.+# A named secret is referenced by a globally-unique env-style ``name``. Tags are+# the only grouping selector; skill association is stored as reserved+# ``skill:<name>`` tags. Values are envelope-encrypted at rest (storage/vault_crypto.py):+# standard tier under a machine key, protected tier under a password/passkey-derived key.+# ``ciphertext``/``nonce`` are base64 text and ``wrap_meta`` is a JSON blob of the+# wrapped DEK + scheme — there is deliberately no plaintext column. The+# ``vault_secrets`` table is denylisted in ``vibe data query``.vault_secrets = Table("vault_secrets",metadata,Column("id", String, primary_key=True),# Globally-unique reference key, ENV-style ``^[A-Z][A-Z0-9_]*$``.Column("name", String, nullable=False),- Column("group_name", String, ForeignKey("vault_groups.name"), nullable=False, server_default="default"),Column("tags", Text, nullable=True), # JSON arrayColumn("kind", String, nullable=False, server_default="static"), # static | keypair (P2)Column("protection", String, nullable=False, server_default="standard"), # standard (P0) | protected (P1)@@ -499,24 +485,7 @@ vault_secrets = Table(Column("created_at", String, nullable=False),Column("updated_at", String, nullable=False),UniqueConstraint("name", name="uq_vault_secrets_name"),- Index("ix_vault_secrets_group", "group_name"),-)--# Skills <-> secrets is an M:N declared-dependency relation (a skill declares the-# secrets it needs), NOT ownership: one secret used by three skills is one row here-# plus three link rows, never duplicated. ``source`` distinguishes skill-meta-derived-# links from agent/user-made ones. (P1.)-vault_links = Table(- "vault_links",- metadata,- Column("id", String, primary_key=True),- Column("secret_name", String, ForeignKey("vault_secrets.name", ondelete="CASCADE"), nullable=False),- Column("skill_name", String, nullable=False),- Column("source", String, nullable=False), # skill_meta | agent | user- Column("required", Integer, nullable=False, server_default="1"),- Column("created_at", String, nullable=False),- UniqueConstraint("secret_name", "skill_name", name="uq_vault_links_secret_skill"),- Index("ix_vault_links_skill", "skill_name"),+ Index("ix_vault_secrets_name_kind", "name", "kind"),)# One queue for everything that needs a human: P0 uses ``provision`` (dynamic ask via@@ -537,26 +506,28 @@ vault_requests = Table(Index("ix_vault_requests_status_created", "status", "created_at"),)-# Metadata + audit of active scope-typed unlock grants. Key material is NEVER stored-# here; resident avault agent delivery material wires in later as process-local opaque-# state. This row records the scope + bounds for the UI and audit; the member set is-# frozen at grant time.+# Metadata + audit of active unlock grants. Key material is NEVER stored here;+# resident avault agent delivery material wires in later as process-local opaque+# state. The member set is frozen at grant time and keyed by the first-class grant id.vault_grants = Table("vault_grants",metadata,Column("id", String, primary_key=True),- Column("scope_type", String, nullable=False), # secret | skill | group- Column("scope_ref", String, nullable=False),- Column("member_snapshot", Text, nullable=True), # JSON: frozen secret-name set (audit)- Column("session_id", String, nullable=True), # null = any-session- Column("status", String, nullable=False, server_default="active"), # active | expired | revoked- Column("created_by_request_id", String, nullable=True),+ Column("member_snapshot", Text, nullable=False), # JSON: frozen protected secret-name set+ Column("source_selector", Text, nullable=True), # JSON: env/tag/skill source that produced the grant+ Column("request_id", String, nullable=True),+ Column("session_id", String, nullable=True),+ Column("purpose", String, nullable=False, server_default="run"), # run | fetch | inject+ Column("status", String, nullable=False, server_default="active"), # active | reserved | expired | revoked+ Column("one_shot", Integer, nullable=False, server_default=text("0")),Column("created_at", String, nullable=False),Column("expires_at", String, nullable=False),Column("revoked_at", String, nullable=True),Column("agent_ready", Integer, nullable=False, server_default=text("0")),Column("agent_ready_at", String, nullable=True),Index("ix_vault_grants_status_expires", "status", "expires_at"),+ Index("ix_vault_grants_request", "request_id"),+ Index("ix_vault_grants_session_purpose", "session_id", "purpose"),)# Append-only audit log. Secret VALUES never appear here — only names, requesters,diff --git a/storage/vault_service.py b/storage/vault_service.pyindex a29393b9e..b6afe928a 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -1,14 +1,14 @@-"""CRUD + resolve + grants + audit over the vault tables (design: docs/plans/vaults.md).+"""CRUD + resolve + grants + audit over the vault tables.Data layer for Vaults, sibling to ``storage/messages_service.py`` etc.: functions takea SQLAlchemy ``Connection`` and never open their own engine. This module owns the-metadata invariants around stored envelopes, approval requests, scope grants, and audit+metadata invariants around stored envelopes, approval requests, grants, and auditrows so future vault behavior lands here rather than in callers.Secret values and key material never live here. Standard-tier values are sealed by``avault`` before this layer stores them. Protected-tier values arrive alreadyencrypted by the browser; this layer only stores the opaque ciphertext + wrap-metadata. Scope grants persist metadata only; protected delivery material is owned by+metadata. Grants persist metadata only; protected delivery material is owned bythe resident avault agent, not by Python."""@@ -27,13 +27,19 @@ from sqlalchemy.engine import Connectionfrom sqlalchemy.exc import IntegrityErrorfrom storage import vault_crypto-from storage.models import vault_audit, vault_grants, vault_groups, vault_links, vault_requests, vault_secrets+from storage.models import vault_audit, vault_grants, vault_requests, vault_secretsfrom storage.vault_crypto import Sealed-DEFAULT_GROUP = "default"-GRANT_SCOPE_TYPES = {"secret", "skill", "group"}-DEFAULT_GRANT_TTL_SECONDS = {"secret": 300, "skill": 900, "group": 900}+SKILL_TAG_PREFIX = "skill:"+DEFAULT_ENV_GRANT_TTL_SECONDS = 300+DEFAULT_TAG_GRANT_TTL_SECONDS = 900+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","ecdsa-secp256k1-der",@@ -56,7 +62,6 @@ PROVISION_SPEC_FORBIDDEN_KEYS = {PROVISION_SPEC_ALLOWED_KEYS = {"kind","protection",- "group","description","tags","policy",@@ -68,8 +73,23 @@ PROVISION_SPEC_ALLOWED_AUTH_KEYS = {"type", "name"}@dataclass(frozen=True)class GrantApproval:+ grant_id: strmembers: list[str]session_id: str | None+ source_selector: dict[str, Any]+ purpose: str+ one_shot: bool+ ttl_cap_seconds: int+++@dataclass(frozen=True)+class RequestGrantOption:+ grant_id: str+ members: list[str]+ source_selector: dict[str, Any]+ purpose: str+ one_shot: bool+ ttl_cap_seconds: int@dataclass(frozen=True)@@ -273,6 +293,33 @@ def _string_list(value: Any, *, field: str) -> list[str]:return out+def _normalize_tag(value: str, *, field: str = "tag") -> str:+ tag = value.strip()+ if not tag:+ raise VaultServiceError(f"{field} must be a non-empty string")+ if any(ch.isspace() for ch in tag):+ raise VaultServiceError(f"{field} must not contain whitespace")+ return tag+++def skill_tag(skill: str) -> str:+ skill_name = _normalize_tag(skill, field="skill")+ if skill_name.startswith(SKILL_TAG_PREFIX):+ return skill_name+ return f"{SKILL_TAG_PREFIX}{skill_name}"+++def _normalize_tags(tags: list[str] | None) -> list[str]:+ return list(dict.fromkeys(_normalize_tag(tag) for tag in (tags or []) if isinstance(tag, str) and tag.strip()))+++def _row_tags(row: dict[str, Any]) -> list[str]:+ raw = _loads(row.get("tags")) or []+ if not isinstance(raw, list):+ return []+ return [str(tag) for tag in raw if isinstance(tag, str) and tag]++def _normalize_allowed_host(value: str, *, field: str) -> str:raw = value.strip().lower()if not raw:@@ -339,17 +386,12 @@ def normalize_provision_spec(spec: Any) -> dict[str, Any]:raise VaultServiceError("spec.protection must be 'standard' or 'protected'")normalized["protection"] = protection- group = _optional_string(spec.get("group"), field="spec.group") if "group" in spec else None- if group:- normalized["group"] = group-description = _optional_string(spec.get("description"), field="spec.description") if "description" in spec else Noneif description:normalized["description"] = descriptiontags = _string_list(spec.get("tags"), field="spec.tags") if "tags" in spec else []- if tags:- normalized["tags"] = tags+ tags = _normalize_tags(tags)policy = spec.get("policy")if policy is not None:@@ -396,7 +438,12 @@ def normalize_provision_spec(spec: Any) -> dict[str, Any]:raise VaultServiceError(f"unsupported spec.links fields: {', '.join(sorted(extra_link_keys))}")skills = _string_list(links.get("skills"), field="spec.links.skills") if "skills" in links else []if skills:- normalized["links"] = {"skills": skills}+ normalized_skills = list(dict.fromkeys(_normalize_tag(skill, field="spec.links.skills") for skill in skills))+ tags = list(dict.fromkeys([*tags, *(skill_tag(skill) for skill in normalized_skills)]))+ normalized["links"] = {"skills": normalized_skills}++ if tags:+ normalized["tags"] = tagsreturn normalized@@ -408,8 +455,7 @@ def _meta_payload(row: dict[str, Any]) -> dict[str, Any]:protection = row.get("protection")payload = {"name": row["name"],- "group": row.get("group_name"),- "tags": _loads(row.get("tags")) or [],+ "tags": _row_tags(row),"kind": kind,"protection": protection,"signer_kind": row.get("signer_kind"),@@ -570,17 +616,13 @@ def _grant_row_payload(readiness = _grant_readiness(conn, row, cache=cache, members=members)grant_id = row["id"]runtime_members = cache.covered_names(grant_id) if readiness.active else []- try:- always_ask = len(members) == 1 and _secret_always_ask(_require_row(conn, members[0]))- except SecretNotFoundError:- always_ask = Falsereturn {"id": grant_id,- "scope_type": row["scope_type"],- "scope_ref": row["scope_ref"],+ "source_selector": _loads(row.get("source_selector")) or {},"session_id": row.get("session_id"),+ "purpose": row.get("purpose"),"status": row.get("status"),- "created_by_request_id": row.get("created_by_request_id"),+ "request_id": row.get("request_id"),"created_at": row.get("created_at"),"expires_at": row.get("expires_at"),"revoked_at": row.get("revoked_at"),@@ -589,7 +631,7 @@ def _grant_row_payload("runtime_member_count": len(runtime_members),"delivery_ready": readiness.delivery_ready,"delivery_status": readiness.delivery_status,- "one_shot": always_ask,+ "one_shot": bool(int(row.get("one_shot") or 0)),}@@ -612,16 +654,18 @@ def _grant_payload(conn: Connection, row: dict[str, Any], *, cache: VaultGrantRureturn _grant_row_payload(conn, dict(row), cache=cache)-def _unique_grant_scopes(rows: list[dict[str, Any]]) -> list[dict[str, str]]:- seen: set[tuple[str, str]] = set()- scopes: list[dict[str, str]] = []+def _unique_grant_release_refs(rows: list[dict[str, Any]]) -> list[dict[str, str]]:+ seen: set[str] = set()+ refs: list[dict[str, str]] = []for row in rows:- key = (str(row["scope_type"]), str(row["scope_ref"]))+ key = str(row.get("id") or "")+ if not key:+ continueif key in seen:continueseen.add(key)- scopes.append({"scope_type": key[0], "scope_ref": key[1]})- return scopes+ refs.append({"grant_id": key})+ return refsdef _hydrate_card_unlock_material(conn: Connection, row: dict[str, Any], card: dict[str, Any]) -> dict[str, Any]:@@ -632,7 +676,7 @@ def _hydrate_card_unlock_material(conn: Connection, row: dict[str, Any], card: dif secret_row is not None and (material := _protected_unlock_material(dict(secret_row))) is not None:card["secret_unlock_material"] = materialhydrated_options: list[dict[str, Any]] = []- for option in card.get("scope_options") or []:+ for option in card.get("grant_options") or []:if not isinstance(option, dict):continueoption_payload = dict(option)@@ -657,7 +701,7 @@ def _hydrate_card_unlock_material(conn: Connection, row: dict[str, Any], card: doption_payload["unlock_material"] = materialshydrated_options.append(option_payload)if hydrated_options:- card["scope_options"] = hydrated_options+ card["grant_options"] = hydrated_optionsreturn card@@ -793,6 +837,80 @@ def _request_card(row: dict[str, Any]) -> dict[str, Any]:return card if isinstance(card, dict) else {}+def _request_member_names(row: dict[str, Any]) -> list[str]:+ card = _request_card(row)+ members: list[str] = []+ options = card.get("grant_options") if isinstance(card, dict) else None+ if isinstance(options, list):+ for option in options:+ if not isinstance(option, dict):+ continue+ snapshot = option.get("member_snapshot")+ if isinstance(snapshot, list):+ members.extend(str(name) for name in snapshot if isinstance(name, str) and name)+ if not members and row.get("secret_name"):+ members.append(str(row["secret_name"]))+ return sorted(set(members))+++def _request_covers_any_member(row: dict[str, Any], members: set[str]) -> bool:+ if not members:+ return False+ return bool(set(_request_member_names(row)) & members)+++def _request_members_are_subset(row: dict[str, Any], members: set[str]) -> bool:+ request_members = set(_request_member_names(row))+ return bool(request_members) and request_members.issubset(members)+++def _ttl_cap_from_grant_option(option: dict[str, Any], selector: dict[str, Any]) -> int:+ raw_options = option.get("ttl_options_seconds")+ ttl_options: list[int] = []+ if isinstance(raw_options, list):+ for raw in raw_options:+ try:+ value = int(raw)+ except (TypeError, ValueError):+ continue+ if value > 0:+ 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))+++def _request_grant_option(row: dict[str, Any]) -> RequestGrantOption:+ card = _request_card(row)+ options = card.get("grant_options") if isinstance(card, dict) else None+ if not isinstance(options, list) or len(options) != 1 or not isinstance(options[0], dict):+ raise InvalidRequestError("grant approval request is missing a grant option")+ option = options[0]+ grant_id = str(option.get("grant_id") or "").strip()+ if not grant_id:+ raise InvalidRequestError("grant approval request is missing a grant id")+ snapshot = option.get("member_snapshot")+ if not isinstance(snapshot, list):+ raise InvalidRequestError("grant approval request has an invalid member snapshot")+ members = [str(name) for name in snapshot if isinstance(name, str) and name]+ selector = _source_selector_payload(option.get("source_selector") if isinstance(option.get("source_selector"), dict) else {})+ purpose = str(option.get("purpose") or "run")+ if purpose not in GRANT_PURPOSES:+ raise InvalidRequestError("grant approval request has an invalid purpose")+ return RequestGrantOption(+ grant_id=grant_id,+ members=members,+ source_selector=selector,+ purpose=purpose,+ one_shot=bool(option.get("one_shot")),+ ttl_cap_seconds=_ttl_cap_from_grant_option(option, selector),+ )++def _secret_policy(row: dict[str, Any]) -> dict[str, Any]:return _loads(row.get("policy")) or {}@@ -866,47 +984,6 @@ def audit()-def ensure_default_group(conn: Connection) -> None:- """Insert the implicit ``default`` group if absent (the migration seeds it, but- keep this defensive for DBs built another way)."""- exists = conn.execute(select(vault_groups.c.name).where(vault_groups.c.name == DEFAULT_GROUP)).first()- if exists is None:- conn.execute(- vault_groups.insert().values(- name=DEFAULT_GROUP,- description="Default group",- grantable=1,- max_grant_ttl_seconds=900,- created_at=_now(),- )- )---def _ensure_group(conn: Connection, name: str) -> None:- """Create the group row if it's missing so a secret's ``group_name`` FK is satisfied.-- The Vaults UI / ``--group`` expose arbitrary group labels; without this an unseeded- group would trip the FK with a generic ``FOREIGN KEY constraint failed`` instead of- the group option just working.- """- if conn.execute(select(vault_groups.c.name).where(vault_groups.c.name == name)).first() is None:- try:- conn.execute(- vault_groups.insert().values(- name=name,- description="Default group" if name == DEFAULT_GROUP else None,- grantable=1,- max_grant_ttl_seconds=900,- created_at=_now(),- )- )- except IntegrityError:- # A concurrent create inserted this brand-new group between our check and insert.- # The row now exists (all the FK needs), so swallow the PK conflict and continue —- # otherwise the loser's otherwise-valid secret create would fail with a raw error.- pass--def _require_row(conn: Connection, name: str) -> dict[str, Any]:row = conn.execute(select(vault_secrets).where(vault_secrets.c.name == name)).mappings().first()if row is None:@@ -936,7 +1013,6 @@ def create_secret(*,name: str,sealed: Sealed,- group: str = DEFAULT_GROUP,tags: list[str] | None = None,protection: str = "standard",kind: str = "static",@@ -995,8 +1071,8 @@ def create_secret():raise VaultAlreadyInitializedError("a protected vault already exists; unlock it instead of re-initializing")- _ensure_group(conn, group)now = _now()+ normalized_tags = _normalize_tags(tags)public_meta = dict(public_meta or {})if description:public_meta["description"] = description@@ -1005,8 +1081,7 @@ def create_secret(vault_secrets.insert().values(id=_id("vlt"),name=name,- group_name=group,- tags=json.dumps(tags) if tags else None,+ tags=json.dumps(normalized_tags) if normalized_tags else None,kind=kind,protection=protection,signer_kind=signer_kind,@@ -1046,22 +1121,60 @@ def create_secret(def link_secret_to_skills(conn: Connection, secret_name: str, skills: list[str], *, source: str = "agent") -> None:if not skills:return- _require_row(conn, secret_name)- now = _now()- for skill in dict.fromkeys(item.strip() for item in skills if item and item.strip()):- try:- conn.execute(- vault_links.insert().values(- id=_id("vln"),- secret_name=secret_name,- skill_name=skill,- source=source,- required=1,- created_at=now,- )- )- except IntegrityError:- pass+ row = _require_row(conn, secret_name)+ current = _row_tags(row)+ updated = list(dict.fromkeys([*current, *(skill_tag(skill) for skill in skills if skill and skill.strip())]))+ if updated == current:+ return+ conn.execute(+ vault_secrets.update()+ .where(vault_secrets.c.name == secret_name)+ .values(tags=json.dumps(updated) if updated else None)+ )+ audit(conn, "tags-updated", secret_name=secret_name, delivery={"source": source, "tags": updated})+++def update_secret_tags(conn: Connection, secret_name: str, tags: list[str]) -> dict[str, Any]:+ row = _require_row(conn, secret_name)+ normalized = _normalize_tags(tags)+ conn.execute(+ vault_secrets.update()+ .where(vault_secrets.c.name == secret_name)+ .values(tags=json.dumps(normalized) if normalized else None)+ )+ audit(conn, "tags-updated", secret_name=secret_name, delivery={"tags": normalized})+ return _meta_payload(dict(row) | {"tags": json.dumps(normalized) if normalized else None})+++def update_secret_classification(+ conn: Connection,+ secret_name: str,+ *,+ kind: str | None = None,+ protection: str | None = None,+ cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,+) -> dict[str, Any]:+ row = _require_row(conn, secret_name)+ values: dict[str, Any] = {}+ if kind is not None:+ normalized_kind = kind.strip().lower()+ if normalized_kind not in {"static", "keypair"}:+ raise VaultServiceError(f"invalid vault secret kind: {kind!r}")+ values["kind"] = normalized_kind+ if protection is not None:+ normalized_protection = protection.strip().lower()+ if normalized_protection not in {"standard", "protected"}:+ raise VaultServiceError(f"invalid protection tier: {protection!r}")+ values["protection"] = normalized_protection+ if not values:+ return _meta_payload(row)+ if values.get("kind", row.get("kind")) != row.get("kind") or values.get("protection", row.get("protection")) != row.get("protection"):+ _expire_pending_requests_for_secret(conn, secret_name, reason="request-expired-classification-changed")+ _expire_active_grants_for_secret(conn, secret_name, cache=cache, reason="grant-expired-classification-changed")+ values["updated_at"] = _now()+ conn.execute(vault_secrets.update().where(vault_secrets.c.name == secret_name).values(**values))+ audit(conn, "updated", secret_name=secret_name, delivery={"fields": sorted(values)})+ return _meta_payload(_require_row(conn, secret_name))def get_secret_meta(conn: Connection, name: str) -> dict[str, Any]:@@ -1091,12 +1204,14 @@ def store_pubkey_pin(conn: Connection, name: str, pin: dict[str, Any]) -> dict[sreturn get_secret_meta(conn, name)-def list_secrets(conn: Connection, *, group: str | None = None) -> list[dict[str, Any]]:+def list_secrets(conn: Connection, *, tag: str | None = None) -> list[dict[str, Any]]:"""Masked, value-free list. Never decrypts."""query = select(vault_secrets).order_by(vault_secrets.c.name)- if group is not None:- query = query.where(vault_secrets.c.group_name == group)- return [_meta_payload(dict(row)) for row in conn.execute(query).mappings()]+ rows = [_meta_payload(dict(row)) for row in conn.execute(query).mappings()]+ if tag is not None:+ normalized = _normalize_tag(tag)+ rows = [row for row in rows if normalized in row.get("tags", [])]+ return rowsdef latest_protected_vmk_wrap_meta(conn: Connection) -> str | None:@@ -1314,7 +1429,6 @@ def fulfill_provision(request_id: str,sealed: Sealed,*,- group: str = DEFAULT_GROUP,description: str | None = None,) -> dict[str, Any]:"""Store the caller-sealed value for a pending provision request."""@@ -1325,7 +1439,6 @@ def fulfill_provision(conn,name=row["secret_name"],sealed=sealed,- group=group,description=description,provision_request_id=request_id,)@@ -1354,307 +1467,264 @@ def _secure_input_card(return card-def _grant_member_rows(conn: Connection, scope_type: str, scope_ref: str) -> list[dict[str, Any]]:- if scope_type == "secret":- return [_require_row(conn, scope_ref)]- if scope_type == "skill":- rows = (- conn.execute(- select(vault_secrets)- .select_from(vault_links.join(vault_secrets, vault_links.c.secret_name == vault_secrets.c.name))- .where(vault_links.c.skill_name == scope_ref)- .order_by(vault_secrets.c.name)- )- .mappings()- .all()- )- return [dict(row) for row in rows]- if scope_type == "group":- rows = (- conn.execute(- select(vault_secrets)- .where(vault_secrets.c.group_name == scope_ref)- .order_by(vault_secrets.c.name)- )- .mappings()- .all()- )- return [dict(row) for row in rows]- raise InvalidGrantError(f"invalid grant scope_type: {scope_type!r}")---def _grantable_member_rows(conn: Connection, scope_type: str, scope_ref: str) -> list[dict[str, Any]]:- rows = _grant_member_rows(conn, scope_type, scope_ref)- if not rows:- return []- group_names = {row.get("group_name") for row in rows if row.get("group_name")}- grantable_groups = {- row["name"]- for row in conn.execute(select(vault_groups).where(vault_groups.c.name.in_(group_names))).mappings()- if int(row.get("grantable") or 0) == 1- }- return [- row- for row in rows- if _secret_access_grantable(row) and (row.get("group_name") in grantable_groups)- ]---def _always_ask_request_member_rows(- conn: Connection,- scope_type: str,- scope_ref: str,- request_row: dict[str, Any],-) -> list[dict[str, Any]]:- requested_secret = request_row.get("secret_name")- if not requested_secret or scope_type != "secret" or scope_ref != requested_secret:- return []- row = _require_row(conn, str(requested_secret))- if not _secret_access_requestable(row) or not _secret_always_ask(row):- return []- if not _groups_grantable(conn, [str(row.get("group_name") or "")]):- return []- return [row]+def _source_selector_payload(source_selector: dict[str, Any] | None = None) -> dict[str, Any]:+ if source_selector is None:+ return {"env": [], "tags": []}+ if not isinstance(source_selector, dict):+ raise InvalidGrantError("source_selector must be an object")+ env = _string_list(source_selector.get("env"), field="source_selector.env") if "env" in source_selector else []+ tags = _string_list(source_selector.get("tags"), field="source_selector.tags") if "tags" in source_selector else []+ skills = _string_list(source_selector.get("skills"), field="source_selector.skills") if "skills" in source_selector else []+ normalized_tags = _normalize_tags(tags)+ normalized_tags = list(dict.fromkeys([*normalized_tags, *(skill_tag(skill) for skill in skills)]))+ payload: dict[str, Any] = {}+ if env:+ payload["env"] = env+ if normalized_tags:+ payload["tags"] = normalized_tags+ return 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:+ raise InvalidRequestError("env selector must be non-empty")+ if "=" in raw:+ env_name, secret_name = raw.split("=", 1)+ env_name = env_name.strip()+ secret_name = secret_name.strip()+ else:+ env_name = secret_name = raw+ if not vault_crypto.is_valid_secret_name(env_name) or not vault_crypto.is_valid_secret_name(secret_name):+ raise InvalidRequestError("env selector must use valid secret names")+ return env_name, secret_name-def _grantable_member_rows_for_request(+def expand_value_delivery_selector(conn: Connection,- scope_type: str,- scope_ref: str,- request_id: str | None,-) -> list[dict[str, Any]]:- rows = _grantable_member_rows(conn, scope_type, scope_ref)- if rows or not request_id:- return rows- try:- request_row = _load_request_for_transition(- conn,- str(request_id),- request_type="access",- allowed_statuses={"pending"},- wrong_type_message="grant approval must complete an access request",- wrong_status_message="grant approval request is not pending",- expired_message="grant approval request has expired",+ *,+ env: list[str] | None = None,+ tags: list[str] | None = None,+ skills: list[str] | None = None,+ source_selector: dict[str, Any] | None = None,+) -> dict[str, Any]:+ selector = _source_selector_payload(source_selector or {"env": env or [], "tags": tags or [], "skills": skills or []})+ selections: list[dict[str, Any]] = []+ env_by_secret: dict[str, str] = {}+ secret_by_env: dict[str, str] = {}++ def add_selection(row: dict[str, Any], env_name: str) -> None:+ secret_name = str(row["name"])+ _reject_keypair_value_delivery(row, secret_name)+ existing_env = env_by_secret.get(secret_name)+ if existing_env is not None:+ if existing_env != env_name:+ raise InvalidRequestError(f"{secret_name} was selected with conflicting env names")+ return+ existing_secret = secret_by_env.get(env_name)+ if existing_secret is not None and existing_secret != secret_name:+ raise InvalidRequestError(f"env {env_name} maps to multiple vault secrets")+ env_by_secret[secret_name] = env_name+ secret_by_env[env_name] = secret_name+ selections.append(+ {+ "name": secret_name,+ "env": env_name,+ "kind": row.get("kind"),+ "protection": row.get("protection"),+ })- except RequestNotFoundError:- raise- except InvalidRequestError:- raise- return _always_ask_request_member_rows(conn, scope_type, scope_ref, request_row)+ for env_spec in selector.get("env") or []:+ env_name, secret_name = _parse_env_selector(str(env_spec))+ add_selection(_require_row(conn, secret_name), env_name)-def grantable_member_metas(conn: Connection, scope_type: str, scope_ref: str) -> list[dict[str, Any]]:- return [_meta_payload(row) for row in _grantable_member_rows(conn, scope_type, scope_ref)]+ for tag in selector.get("tags") or []:+ normalized = _normalize_tag(str(tag))+ rows = [+ dict(row)+ for row in conn.execute(select(vault_secrets).order_by(vault_secrets.c.name)).mappings()+ if normalized in _row_tags(dict(row))+ ]+ for row in rows:+ add_selection(row, str(row["name"]))+ return {"source_selector": selector, "secrets": selections}-def request_grantable_member_metas(++def _request_member_rows_for_selector(conn: Connection,- scope_type: str,- scope_ref: str,- request_id: str,+ *,+ source_selector: dict[str, Any],) -> list[dict[str, Any]]:- return [- _meta_payload(row)- for row in _grantable_member_rows_for_request(- conn,- scope_type,- scope_ref,- request_id,- )- ]+ expanded = expand_value_delivery_selector(conn, source_selector=source_selector)+ rows: list[dict[str, Any]] = []+ for item in expanded["secrets"]:+ row = _require_row(conn, str(item["name"]))+ if row.get("protection") == "protected" or _secret_always_ask(row):+ rows.append(row)+ return rows-def _ttl_cap_for_members(conn: Connection, member_names: list[str]) -> int:- if not member_names:- return min(DEFAULT_GRANT_TTL_SECONDS.values())- rows = (- conn.execute(- select(vault_groups.c.max_grant_ttl_seconds)- .select_from(vault_secrets.join(vault_groups, vault_secrets.c.group_name == vault_groups.c.name))- .where(vault_secrets.c.name.in_(member_names))- )- .scalars()- .all()- )- caps = [int(row) for row in rows if row is not None]- return min(caps) if caps else 900+def _member_rows_for_names(conn: Connection, member_names: list[str]) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for name in member_names:+ row = _require_row(conn, str(name))+ _reject_keypair_value_delivery(row, str(name))+ rows.append(row)+ return rows-def _groups_grantable(conn: Connection, group_names: list[str]) -> bool:- names = {name for name in group_names if name}- if not names:- return False- grantable_groups = {- row["name"]- for row in conn.execute(select(vault_groups).where(vault_groups.c.name.in_(names))).mappings()- if int(row.get("grantable") or 0) == 1- }- return names.issubset(grantable_groups)+def grantable_member_metas(conn: Connection, member_names: list[str]) -> list[dict[str, Any]]:+ return [_meta_payload(row) for row in _member_rows_for_names(conn, member_names) if _secret_access_grantable(row)]-def _secret_scope_option(- conn: Connection,- row: dict[str, Any],- *,- default_ttl_seconds: int,- one_shot: bool = False,-) -> dict[str, Any] | None:- secret_name = str(row["name"])- if not _groups_grantable(conn, [str(row.get("group_name") or "")]):- return None- ttl_cap = _ttl_cap_for_members(conn, [secret_name])- capped_default = min(default_ttl_seconds, ttl_cap)- option = {- "scope_type": "secret",- "scope_ref": secret_name,- "default_ttl_seconds": capped_default,- "ttl_options_seconds": [seconds for seconds in GRANT_TTL_OPTIONS_SECONDS if seconds <= ttl_cap],- "session_binding_default": True,- "member_count": 1,- "member_snapshot": [secret_name],- "member_versions": [_member_version(row)],- }- if one_shot:- option["one_shot"] = True- return option+def request_grantable_member_metas(conn: Connection, request_id: str) -> list[dict[str, Any]]:+ row = _load_request_for_transition(+ conn,+ str(request_id),+ request_type="access",+ allowed_statuses={"pending"},+ wrong_type_message="grant approval must complete an access request",+ wrong_status_message="grant approval request is not pending",+ expired_message="grant approval request has expired",+ )+ option = _request_grant_option(row)+ return [_meta_payload(_require_row(conn, name)) for name in option.members]-def _scope_option(- conn: Connection,- scope_type: str,- scope_ref: str,+def _grant_option(+ rows: list[dict[str, Any]],*,- requested_secret: str,- default_ttl_seconds: int,-) -> dict[str, Any] | None:- rows = _grantable_member_rows(conn, scope_type, scope_ref)- members = [row["name"] for row in rows]- if not members or requested_secret not in members:- return None- ttl_cap = _ttl_cap_for_members(conn, members)- capped_default = min(default_ttl_seconds, ttl_cap)- return {- "scope_type": scope_type,- "scope_ref": scope_ref,- "default_ttl_seconds": capped_default,- "ttl_options_seconds": [seconds for seconds in GRANT_TTL_OPTIONS_SECONDS if seconds <= ttl_cap],+ source_selector: dict[str, Any],+ purpose: str,+ one_shot: bool,+) -> dict[str, Any]:+ members = [str(row["name"]) for row in rows]+ default_ttl_seconds = _selector_ttl_seconds(source_selector)+ 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],"session_binding_default": True,"member_count": len(members),"member_snapshot": members,"member_versions": [_member_version(row) for row in rows],}+ if one_shot:+ option["one_shot"] = True+ return optiondef approval_card(conn: Connection,- secret_name: str,+ secret_name: str | None,*,request_id: str,request_type: str = "access",+ member_rows: list[dict[str, Any]] | None = None,+ source_selector: dict[str, Any] | None = None,+ purpose: str = "run",command: str | None = None,egress: str | None = None,skill: str | None = None,session_id: str | None = None,+ one_shot: bool = False,grantable: bool = True,) -> dict[str, Any]:- row = _require_row(conn, secret_name)- group = row.get("group_name") or DEFAULT_GROUP- always_ask = _secret_always_ask(row)- one_shot_access = request_type == "access" and always_ask and _secret_access_requestable(row)- scope_options: list[dict[str, Any]] = []- if one_shot_access:- option = _secret_scope_option(- conn,- row,- default_ttl_seconds=DEFAULT_GRANT_TTL_SECONDS["secret"],- one_shot=True,- )- scope_options = [option] if option is not None else []- if grantable and not always_ask:- scope_options = [- option- for option in (- _scope_option(- conn,- "secret",- secret_name,- requested_secret=secret_name,- default_ttl_seconds=DEFAULT_GRANT_TTL_SECONDS["secret"],- ),- (- _scope_option(- conn,- "skill",- skill,- requested_secret=secret_name,- default_ttl_seconds=DEFAULT_GRANT_TTL_SECONDS["skill"],- )- if skill- else None- ),- _scope_option(- conn,- "group",- group,- requested_secret=secret_name,- default_ttl_seconds=DEFAULT_GRANT_TTL_SECONDS["group"],- ),- )- if option is not None- ]+ 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 None+ selector = _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 []+ protected_names = [str(row["name"]) for row in rows if row.get("protection") == "protected"]card = {"card_type": "approval","request_id": request_id,"request_type": request_type,"secret_name": secret_name,- "kind": row.get("kind"),- "protection": row.get("protection"),+ "secret_names": [str(row["name"]) for row in rows],+ "protected_secret_names": protected_names,+ "source_selector": selector,+ "purpose": purpose,"command": command,"egress": egress,+ "skill": skill,"session_id": session_id,"approve_once": True,- "one_shot": one_shot_access,- "scope_options": scope_options,+ "one_shot": one_shot,+ "grant_options": grant_options,"value": None,}+ if len(rows) == 1:+ card["kind"] = rows[0].get("kind")+ card["protection"] = rows[0].get("protection")return carddef create_access_request(conn: Connection,- name: str,+ name: str | None = None,*,+ source_selector: dict[str, Any] | None = None,+ purpose: str = "run",requester: Any = None,delivery: dict[str, Any] | None = None,message_id: str | None = None,expires_at: str | None = None,audience: str | None = None,) -> dict[str, Any]:- row = _require_row(conn, name)- if not _secret_access_requestable(row):- raise NotGrantableError(f"{name} is not access-requestable")+ if purpose not in GRANT_PURPOSES:+ raise InvalidRequestError(f"invalid grant purpose: {purpose!r}")payload_audience = audience or _request_audience_from_requester(requester)request_id = _id("vrq")delivery_payload = dict(delivery or {})requester_payload = requester if isinstance(requester, dict) else {}- always_ask = _secret_always_ask(row)+ default_selector = {"env": [name]} if name else None+ selector = _source_selector_payload(source_selector or default_selector)+ rows = _request_member_rows_for_selector(conn, source_selector=selector)+ if name:+ direct_row = _require_row(conn, name)+ if not _secret_access_requestable(direct_row):+ raise NotGrantableError(f"{name} is not access-requestable")+ if not rows:+ raise NotGrantableError("selector has no protected or approval-required static secrets")+ if len(rows) == 1 and _secret_always_ask(rows[0]) and rows[0].get("protection") == "standard":+ one_shot = True+ else:+ one_shot = any(_secret_always_ask(row) for row in rows)card = approval_card(conn,- name,+ str(rows[0]["name"]) if len(rows) == 1 else name,request_id=request_id,request_type="access",+ member_rows=rows,+ source_selector=selector,+ purpose=purpose,command=delivery_payload.get("command"),egress=delivery_payload.get("egress"),skill=delivery_payload.get("skill") or requester_payload.get("skill"),session_id=requester_payload.get("session_id") or delivery_payload.get("session_id"),- grantable=not always_ask,+ one_shot=one_shot,)delivery_payload["card"] = card+ delivery_payload["source_selector"] = selector+ delivery_payload["purpose"] = purposeconn.execute(vault_requests.insert().values(id=request_id,request_type="access",- secret_name=name,+ secret_name=str(rows[0]["name"]) if len(rows) == 1 else None,requester=json.dumps(requester) if requester is not None else None,delivery=json.dumps(delivery_payload),status="pending",@@ -2020,7 +2090,7 @@ def _expire_grant_rows(.values(status="expired", revoked_at=now, agent_ready=0, agent_ready_at=None))cache.drop(row["id"])- audit(conn, reason, grant_id=row["id"], delivery={"scope_type": row["scope_type"], "scope_ref": row["scope_ref"]})+ audit(conn, reason, grant_id=row["id"], delivery={"grant_id": row["id"]})expired += 1return expired@@ -2045,7 +2115,7 @@ def active_grant_rows_for_secret(conn: Connection, secret_name: str) -> list[dicdef active_grant_scopes_for_secret(conn: Connection, secret_name: str) -> list[dict[str, str]]:- return _unique_grant_scopes(active_grant_rows_for_secret(conn, secret_name))+ return _unique_grant_release_refs(active_grant_rows_for_secret(conn, secret_name))def active_grant_scopes_for_session(conn: Connection, session_id: str) -> list[dict[str, str]]:@@ -2055,7 +2125,7 @@ def active_grant_scopes_for_session(conn: Connection, session_id: str) -> list[dselect(vault_grants).where(vault_grants.c.status.in_(ACTIVE_GRANT_STATES), vault_grants.c.session_id == session_id)).mappings()]- return _unique_grant_scopes(rows)+ return _unique_grant_release_refs(rows)def agent_release_scopes_after_rows(@@ -2064,12 +2134,7 @@ def agent_release_scopes_after_rows(*,cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,) -> list[dict[str, str]]:- """Return resident-agent scopes that must be dropped after grant rows stop being active.-- The agent cache is keyed by scope, not grant id. Keeping a scope is valid only- when the remaining active grants for that scope still cover every member that- had been cached under the removed rows.- """+ """Return resident-agent grant ids that must be dropped after rows stop being active."""now = _now()expired_rows = [@@ -2084,48 +2149,15 @@ def agent_release_scopes_after_rows(rows = [dict(row) for row in rows if grant_row_has_resident_agent_ready(dict(row))]if not rows:return []- active_rows = [- dict(row)- for row in conn.execute(select(vault_grants).where(vault_grants.c.status.in_(ACTIVE_GRANT_STATES))).mappings()- if grant_row_has_resident_agent_ready(dict(row))- ]- active_by_scope: dict[tuple[str, str], set[str]] = {}- for row in active_rows:- key = (str(row["scope_type"]), str(row["scope_ref"]))- active_by_scope.setdefault(key, set()).update(_grant_member_names(row))-- removed_by_scope: dict[tuple[str, str], set[str]] = {}+ release_refs: list[dict[str, str]] = []for row in rows:- key = (str(row["scope_type"]), str(row["scope_ref"]))- removed_by_scope.setdefault(key, set()).update(_grant_member_names(row))-- release_scopes: list[dict[str, str]] = []- for (scope_type, scope_ref), removed_members in removed_by_scope.items():- if removed_members.issubset(active_by_scope.get((scope_type, scope_ref), set())):+ grant_id = str(row.get("id") or "")+ if not grant_id:continue- stale_scope_grants = [- dict(row)- for row in conn.execute(- select(vault_grants).where(- vault_grants.c.scope_type == scope_type,- vault_grants.c.scope_ref == scope_ref,- )- ).mappings()- ]- for stale_row in stale_scope_grants:- cache.drop(str(stale_row["id"]))- _clear_grant_agent_ready(conn, str(stale_row["id"]))- conn.execute(- vault_grants.update()- .where(- vault_grants.c.scope_type == scope_type,- vault_grants.c.scope_ref == scope_ref,- vault_grants.c.status.in_(ACTIVE_GRANT_STATES),- )- .values(agent_ready=0, agent_ready_at=None)- )- release_scopes.append({"scope_type": scope_type, "scope_ref": scope_ref})- return release_scopes+ cache.drop(grant_id)+ _clear_grant_agent_ready(conn, grant_id)+ release_refs.append({"grant_id": grant_id})+ return release_refsdef expire_grant(@@ -2151,19 +2183,20 @@ def _expire_pending_requests_for_secret(*,reason: str = "request-expired",) -> int:+ changed_members = {secret_name}rows = [dict(row)for row in conn.execute(select(vault_requests).where(- vault_requests.c.secret_name == secret_name,vault_requests.c.status == "pending",vault_requests.c.request_type.in_(("access", "sign")),)).mappings()+ if row.get("secret_name") == secret_name or _request_covers_any_member(dict(row), changed_members)]if not rows:return 0- return _expire_pending_request_rows(conn, rows, reason=reason)+ return _expire_pending_request_rows(conn, rows, reason=reason, delivery_extra={"changed_secret": secret_name})def expire_session_requests(conn: Connection, session_id: str, *, reason: str = "request-expired-session-archived") -> int:@@ -2197,11 +2230,11 @@ def _validate_access_request_for_grant(conn: Connection,request_id: str,*,- scope_type: str,- scope_ref: str,session_id: str | None,inherit_request_session: bool,live_members: list[str],+ source_selector: dict[str, Any],+ purpose: str,) -> GrantApproval:row_dict = _load_request_for_transition(conn,@@ -2212,93 +2245,89 @@ def _validate_access_request_for_grant(wrong_status_message="grant approval request is not pending",expired_message="grant approval request has expired",)- requested_secret = row_dict.get("secret_name")- if requested_secret not in live_members:- raise InvalidRequestError("grant scope does not cover the requested secret")- requested_row = _require_row(conn, str(requested_secret))- always_ask = _secret_always_ask(requested_row)- if always_ask and (- scope_type != "secret"- or scope_ref != requested_secret- or set(live_members) != {requested_secret}- ):- raise InvalidRequestError("always_ask secrets can only approve one-shot secret access")requested_session_id = _request_session_id(row_dict)effective_session_id = requested_session_id if session_id is None and inherit_request_session else session_id- if always_ask:- effective_session_id = requested_session_id or effective_session_id+ option = _request_grant_option(row_dict)+ if option.one_shot and requested_session_id:+ effective_session_id = requested_session_idif requested_session_id and effective_session_id and requested_session_id != effective_session_id:raise InvalidRequestError("grant session does not match the approval request")+ if option.purpose != purpose:+ raise InvalidRequestError("grant purpose does not match the approval request")+ if option.source_selector != _source_selector_payload(source_selector):+ raise InvalidRequestError("grant source selector does not match the approval request")+ if set(option.members) != set(live_members):+ raise InvalidRequestError("grant approval snapshot has stale members")card = _request_card(row_dict)- allowed_scopes = card.get("scope_options") if isinstance(card, dict) else None- if isinstance(allowed_scopes, list) and allowed_scopes:- for option in allowed_scopes:- if not (- isinstance(option, dict)- and option.get("scope_type") == scope_type- and option.get("scope_ref") == scope_ref- ):- continue- snapshot = option.get("member_snapshot") or []- if not isinstance(snapshot, list):- raise InvalidRequestError("grant scope has an invalid approval snapshot")- members = [str(name) for name in snapshot if isinstance(name, str) and name]- if always_ask and set(members) != {requested_secret}:- raise InvalidRequestError("always_ask secrets can only approve one-shot secret access")- if requested_secret not in members:- break- versions = option.get("member_versions")- if not isinstance(versions, list):- raise InvalidRequestError("grant scope approval snapshot is stale")- versions_by_name = {- item.get("name"): item- for item in versions- if isinstance(item, dict) and isinstance(item.get("name"), str)- }- if set(versions_by_name) != set(members):- raise InvalidRequestError("grant scope approval snapshot is stale")- current_rows = {- current["name"]: dict(current)- for current in conn.execute(select(vault_secrets).where(vault_secrets.c.name.in_(members))).mappings()- }- for member_name in members:- current = current_rows.get(member_name)- if current is None or member_name not in live_members:- raise InvalidRequestError("grant approval snapshot has stale members")- if not _member_version_matches(current, versions_by_name[member_name]):- raise InvalidRequestError("grant approval snapshot has stale members")- return GrantApproval(members=members, session_id=effective_session_id)- raise InvalidRequestError("grant scope was not offered by the approval request")- return GrantApproval(members=live_members, session_id=effective_session_id)+ raw_options = card.get("grant_options") if isinstance(card, dict) else None+ raw_option = raw_options[0] if isinstance(raw_options, list) and raw_options and isinstance(raw_options[0], dict) else {}+ versions = raw_option.get("member_versions")+ if not isinstance(versions, list):+ raise InvalidRequestError("grant approval snapshot is stale")+ versions_by_name = {+ item.get("name"): item+ for item in versions+ if isinstance(item, dict) and isinstance(item.get("name"), str)+ }+ if set(versions_by_name) != set(option.members):+ raise InvalidRequestError("grant approval snapshot is stale")+ current_rows = {+ current["name"]: dict(current)+ for current in conn.execute(select(vault_secrets).where(vault_secrets.c.name.in_(option.members))).mappings()+ }+ for member_name in option.members:+ current = current_rows.get(member_name)+ if current is None or member_name not in live_members:+ raise InvalidRequestError("grant approval snapshot has stale members")+ if not _member_version_matches(current, versions_by_name[member_name]):+ raise InvalidRequestError("grant approval snapshot has stale members")+ return GrantApproval(+ grant_id=option.grant_id,+ members=option.members,+ session_id=effective_session_id,+ source_selector=option.source_selector,+ purpose=option.purpose,+ one_shot=option.one_shot,+ ttl_cap_seconds=option.ttl_cap_seconds,+ )def _approve_sibling_access_requests_for_grant(conn: Connection,*,- created_by_request_id: str,+ request_id: str,members: list[str],session_id: str | None,+ purpose: str,decided_at: str,) -> int:if not members:return 0target_session_id = session_idif not target_session_id:- approval_row = conn.execute(select(vault_requests).where(vault_requests.c.id == created_by_request_id)).mappings().first()+ approval_row = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().first()target_session_id = _request_session_id(dict(approval_row)) if approval_row else Noneif not target_session_id:return 0+ member_set = {str(name) for name in members if str(name)}++ def _same_purpose_subset(row: dict[str, Any]) -> bool:+ try:+ option = _request_grant_option(row)+ except InvalidRequestError:+ return False+ return option.purpose == purpose and _request_members_are_subset(row, member_set)+rows = [dict(row)for row in conn.execute(select(vault_requests).where(- vault_requests.c.id != created_by_request_id,+ vault_requests.c.id != request_id,vault_requests.c.request_type == "access",vault_requests.c.status == "pending",- vault_requests.c.secret_name.in_(members),)).mappings()- if _request_session_id(dict(row)) == target_session_id+ if _request_session_id(dict(row)) == target_session_id and _same_purpose_subset(dict(row))]approved = 0now_dt = datetime.now(timezone.utc)@@ -2332,16 +2361,16 @@ def _approve_sibling_access_requests_for_grant(def restore_access_request_after_failed_grant(conn: Connection,*,- created_by_request_id: str,+ request_id: str,member_names: list[str] | set[str] | tuple[str, ...],session_id: str | None,) -> int:"""Make a protected grant approval retryable after resident-agent relay fails."""members = {str(name) for name in member_names if str(name)}- if not created_by_request_id or not members:+ if not request_id or not members:return 0- approval_row = conn.execute(select(vault_requests).where(vault_requests.c.id == created_by_request_id)).mappings().first()+ approval_row = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().first()if approval_row is None or approval_row.get("status") != "approved":return 0decided_at = approval_row.get("decided_at")@@ -2352,12 +2381,12 @@ def restore_access_request_after_failed_grant(select(vault_requests).where(vault_requests.c.request_type == "access",vault_requests.c.status == "approved",- vault_requests.c.secret_name.in_(members),)).mappings()- if row["id"] == created_by_request_id+ if row["id"] == request_idor (- target_session_id+ _request_members_are_subset(dict(row), members)+ and target_session_idand row.get("decided_at") == decided_atand _request_session_id(dict(row)) == target_session_id)@@ -2385,32 +2414,34 @@ def restore_access_request_after_failed_grant(def create_grant(conn: Connection,*,- scope_type: str,- scope_ref: str,+ member_names: list[str],+ source_selector: dict[str, Any],+ purpose: str = "run",session_id: str | None = None,ttl_seconds: int | None = None,- created_by_request_id: str | None = None,+ request_id: str | None = None,inherit_request_session: bool = True,expected_member_names: set[str] | list[str] | tuple[str, ...] | None = None,cache_ready: bool = True,cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,) -> dict[str, Any]:- if scope_type not in GRANT_SCOPE_TYPES:- raise InvalidGrantError(f"invalid grant scope_type: {scope_type!r}")- if not created_by_request_id:+ if purpose not in GRANT_PURPOSES:+ raise InvalidGrantError(f"invalid grant purpose: {purpose!r}")+ if not request_id:raise InvalidRequestError("grant creation requires an approval request")- live_rows = _grantable_member_rows_for_request(conn, scope_type, scope_ref, created_by_request_id)+ selector = _source_selector_payload(source_selector)+ live_rows = _member_rows_for_names(conn, member_names)live_members = [row["name"] for row in live_rows]if not live_members:- raise NotGrantableError(f"{scope_type}:{scope_ref} has no grantable static secrets")+ raise NotGrantableError("grant has no static secrets")approval = _validate_access_request_for_grant(conn,- created_by_request_id,- scope_type=scope_type,- scope_ref=scope_ref,+ request_id,session_id=session_id,inherit_request_session=inherit_request_session,live_members=live_members,+ source_selector=selector,+ purpose=purpose,)session_id = approval.session_idmembers = approval.members@@ -2419,15 +2450,13 @@ 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}- always_ask_grant = len(members) == 1 and _secret_always_ask(live_rows_by_name[members[0]])- resident_cache_ready = cache_ready and any(- live_rows_by_name[name].get("protection") != "standard" for name in members- )+ one_shot_grant = approval.one_shot+ resident_cache_ready = cache_ready and any(live_rows_by_name[name].get("protection") == "protected" for name in members)decided_at = _now()claim = conn.execute(vault_requests.update().where(- vault_requests.c.id == created_by_request_id,+ vault_requests.c.id == request_id,vault_requests.c.request_type == "access",vault_requests.c.status == "pending",)@@ -2435,21 +2464,22 @@ def create_grant()if claim.rowcount != 1:raise InvalidRequestError("grant approval request is not pending")- ttl = int(ttl_seconds or DEFAULT_GRANT_TTL_SECONDS[scope_type])- ttl = max(1, min(ttl, _ttl_cap_for_members(conn, members)))+ 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 = _id("vgr")+ grant_id = approval.grant_idtry:conn.execute(vault_grants.insert().values(id=grant_id,- scope_type=scope_type,- scope_ref=scope_ref,member_snapshot=json.dumps(members),+ source_selector=json.dumps(selector),session_id=session_id,+ purpose=purpose,status="active",- created_by_request_id=created_by_request_id,+ request_id=request_id,+ one_shot=1 if one_shot_grant else 0,created_at=now_dt.isoformat(),expires_at=expires_at,agent_ready=1 if resident_cache_ready else 0,@@ -2459,7 +2489,7 @@ def create_grant(except Exception:conn.execute(vault_requests.update()- .where(vault_requests.c.id == created_by_request_id)+ .where(vault_requests.c.id == request_id).values(status="pending", decided_at=None))raise@@ -2467,17 +2497,18 @@ def create_grant(conn,"granted",requester={"session_id": session_id} if session_id else None,- delivery={"scope_type": scope_type, "scope_ref": scope_ref, "member_count": len(members)},- request_id=created_by_request_id,+ delivery={"source_selector": selector, "purpose": purpose, "member_count": len(members)},+ request_id=request_id,grant_id=grant_id,)row = conn.execute(select(vault_grants).where(vault_grants.c.id == grant_id)).mappings().one()- if not always_ask_grant:+ if not one_shot_grant:_approve_sibling_access_requests_for_grant(conn,- created_by_request_id=created_by_request_id,+ request_id=request_id,members=members,session_id=session_id,+ purpose=purpose,decided_at=decided_at,)if resident_cache_ready:@@ -2512,7 +2543,7 @@ def get_grant_created_by_request(row = (conn.execute(select(vault_grants)- .where(vault_grants.c.created_by_request_id == request_id)+ .where(vault_grants.c.request_id == request_id).order_by(vault_grants.c.created_at.desc(), vault_grants.c.id.desc()).limit(1))@@ -2554,7 +2585,7 @@ def revoke_grant(.values(status="revoked", revoked_at=now, agent_ready=0, agent_ready_at=None))cache.drop(grant_id)- audit(conn, "grant-revoked", grant_id=grant_id, delivery={"scope_type": row_dict["scope_type"], "scope_ref": row_dict["scope_ref"]})+ audit(conn, "grant-revoked", grant_id=grant_id, delivery={"grant_id": grant_id})updated = conn.execute(select(vault_grants).where(vault_grants.c.id == grant_id)).mappings().one()return _grant_payload(conn, dict(updated), cache=cache)@@ -2623,7 +2654,7 @@ def revoke_session_grants(conn,"grant-revoked-session-archived",grant_id=row["id"],- delivery={"scope_type": row["scope_type"], "scope_ref": row["scope_ref"], "session_id": session_id},+ delivery={"grant_id": row["id"], "session_id": session_id},)revoked += 1return revoked@@ -2634,6 +2665,7 @@ def find_active_grant_for_secret(secret_name: str,*,session_id: str | None = None,+ purpose: str | None = None,cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,reserve_one_shot: bool = False,) -> dict[str, Any] | None:@@ -2641,6 +2673,7 @@ def find_active_grant_for_secret(conn,[secret_name],session_id=session_id,+ purpose=purpose,cache=cache,reserve_one_shot=reserve_one_shot,)@@ -2650,10 +2683,10 @@ def _grant_is_always_ask_for_members(conn: Connection,row: dict[str, Any],) -> bool:- members = _grant_member_names(row)- if len(members) != 1:+ try:+ return bool(int(row.get("one_shot") or 0))+ except (TypeError, ValueError):return False- return _secret_always_ask(_require_row(conn, members[0]))def consume_one_shot_grant(@@ -2700,7 +2733,7 @@ def release_one_shot_reservation()if result.rowcount != 1:raise GrantNotActiveError(grant_id)- audit(conn, "grant-reservation-released", grant_id=grant_id, delivery={"scope_type": row_dict["scope_type"], "scope_ref": row_dict["scope_ref"]})+ audit(conn, "grant-reservation-released", grant_id=grant_id, delivery={"grant_id": grant_id})row_dict = dict(conn.execute(select(vault_grants).where(vault_grants.c.id == grant_id)).mappings().one())members = _grant_member_names(row_dict)if grant_row_has_resident_agent_ready(row_dict) and members:@@ -2725,7 +2758,7 @@ def _reserve_one_shot_grant()if result.rowcount != 1:return None- audit(conn, "grant-reserved-one-shot", grant_id=row["id"], delivery={"scope_type": row["scope_type"], "scope_ref": row["scope_ref"]})+ audit(conn, "grant-reserved-one-shot", grant_id=row["id"], delivery={"grant_id": row["id"]})updated = dict(conn.execute(select(vault_grants).where(vault_grants.c.id == row["id"])).mappings().one())return _grant_payload(conn, updated, cache=cache)@@ -2735,6 +2768,7 @@ def find_active_grant_for_secrets(secret_names: list[str],*,session_id: str | None = None,+ purpose: str | None = None,cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,reserve_one_shot: bool = False,) -> dict[str, Any] | None:@@ -2742,15 +2776,13 @@ def find_active_grant_for_secrets(requested = {str(name) for name in secret_names if str(name)}if not requested:return None- rows = [- dict(row)- for row in conn.execute(- select(vault_grants).where(- vault_grants.c.status.in_(ACTIVE_GRANT_STATES),- or_(vault_grants.c.session_id.is_(None), vault_grants.c.session_id == session_id),- )- ).mappings()- ]+ query = select(vault_grants).where(+ vault_grants.c.status.in_(ACTIVE_GRANT_STATES),+ or_(vault_grants.c.session_id.is_(None), vault_grants.c.session_id == session_id),+ )+ if purpose is not None:+ query = query.where(vault_grants.c.purpose == purpose)+ rows = [dict(row) for row in conn.execute(query).mappings()]candidates: list[tuple[bool, int, str, str, dict[str, Any]]] = []for row in rows:members = _loads(row.get("member_snapshot")) or []@@ -2790,6 +2822,7 @@ def resolve_secret_access(name: str,*,session_id: str | None = None,+ purpose: str = "run",requester: Any = None,delivery: dict[str, Any] | None = None,create_request: bool = True,@@ -2804,6 +2837,8 @@ def resolve_secret_access(expire the grant and re-run this resolver to create a fresh approval request."""row = _require_row(conn, name)+ if purpose not in GRANT_PURPOSES:+ raise InvalidRequestError(f"invalid grant purpose: {purpose!r}")_reject_keypair_value_delivery(row, name)delivery_payload = dict(delivery or {})effective_session_id = (@@ -2818,6 +2853,7 @@ def resolve_secret_access(conn,name,session_id=effective_session_id,+ purpose=purpose,cache=cache,reserve_one_shot=reserve_one_shot,)@@ -2836,6 +2872,8 @@ def resolve_secret_access(request_payload = create_access_request(conn,name,+ source_selector={"env": [name]},+ purpose=purpose,requester=requester,delivery=delivery_payload,)diff --git a/tests/test_avault_agent.py b/tests/test_avault_agent.pyindex 3af45bc79..85ed8b824 100644--- a/tests/test_avault_agent.py+++ b/tests/test_avault_agent.py@@ -71,8 +71,8 @@ def test_agent_client_round_trips_pubkey_grant_deliver_and_release(tmp_path):assert client.pubkey() == {"public_key": "pk", "fingerprint": "fp"}assert client.grant(- scope_type="secret",- scope_ref="API_TOKEN",+ grant_id="vgr_api",+ purpose="run",ttl_secs=300,deks=[{@@ -83,8 +83,7 @@ def test_agent_client_round_trips_pubkey_grant_deliver_and_release(tmp_path):],) == {"granted": 1, "ttl_secs": 300}assert client.deliver_inject(- scope_type="secret",- scope_ref="API_TOKEN",+ grant_id="vgr_api",path=str(tmp_path / "out.env"),fmt="dotenv",secrets=[@@ -95,7 +94,7 @@ def test_agent_client_round_trips_pubkey_grant_deliver_and_release(tmp_path):}],) == {"ok": True}- assert client.release(scope_type="secret", scope_ref="API_TOKEN") == {"released": True}+ assert client.release(grant_id="vgr_api") == {"released": True}assert [request["type"] for request in server.requests] == ["pubkey", "grant", "deliver", "release"]assert server.requests[1]["ttl_secs"] == 300@@ -109,8 +108,7 @@ def test_agent_client_surfaces_agent_errors(tmp_path):with pytest.raises(AvaultAgentError, match="grant is missing or expired"):client.deliver_run(- scope_type="secret",- scope_ref="API_TOKEN",+ grant_id="vgr_api",command=["/bin/true"],secrets=[{@@ -258,8 +256,7 @@ def test_agent_client_does_not_retry_deliver_after_frame_write_timeout(tmp_path)client = AvaultAgentClient(socket_path, timeout=0.05, ensure_agent=_ensure)with pytest.raises(AvaultAgentError, match="request failed"):client.deliver_fetch(- scope_type="secret",- scope_ref="API_TOKEN",+ grant_id="vgr_api",name="API_TOKEN",envelope={"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},request={"headers": []},diff --git a/tests/test_session_archive.py b/tests/test_session_archive.pyindex 58b91d56e..bf6a6b050 100644--- a/tests/test_session_archive.py+++ b/tests/test_session_archive.py@@ -70,6 +70,19 @@ def _insert_run(conn, *, run_id: str, session_id: str, status: str) -> None:)+def _grant_from_request(conn, request: dict, *, session_id: str, cache) -> dict:+ option = request["card"]["grant_options"][0]+ return vs.create_grant(+ conn,+ member_names=option["member_snapshot"],+ source_selector=option["source_selector"],+ purpose=option["purpose"],+ session_id=session_id,+ request_id=request["id"],+ cache=cache,+ )++def test_archive_reclaims_bound_resources(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"service = SQLiteSessionsService(db_path)@@ -144,28 +157,14 @@ def test_archive_reclaims_bound_resources(tmp_path: Path) -> None:delivery={"session_id": "ses_other"},)cache = vs.GRANT_RUNTIME_CACHE- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ARCHIVE_KEY",- session_id=sid,- created_by_request_id=req["id"],- cache=cache,- )+ grant = _grant_from_request(conn, req, session_id=sid, cache=cache)reserved_req = vs.create_access_request(conn,"ARCHIVE_RESERVED_KEY",requester={"session_id": sid},delivery={"session_id": sid, "command": "python reserved.py"},)- reserved_grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ARCHIVE_RESERVED_KEY",- session_id=sid,- created_by_request_id=reserved_req["id"],- cache=cache,- )+ reserved_grant = _grant_from_request(conn, reserved_req, session_id=sid, cache=cache)reserved = vs.resolve_secret_access(conn,"ARCHIVE_RESERVED_KEY",@@ -183,10 +182,7 @@ def test_archive_reclaims_bound_resources(tmp_path: Path) -> None:assert result["status"] == "archived"assert result["agent_status"] == "idle"assert result["reclaimed"] == {"tasks": 1, "watches": 1, "runs": 2, "queued": 0}- assert {(scope["scope_type"], scope["scope_ref"]) for scope in result["revoked_vault_grant_scopes"]} == {- ("secret", "ARCHIVE_KEY"),- ("secret", "ARCHIVE_RESERVED_KEY"),- }+ assert {scope["grant_id"] for scope in result["revoked_vault_grant_scopes"]} == {grant["id"], reserved_grant["id"]}with engine.connect() as conn:live_defs = (@@ -252,13 +248,13 @@ def test_archive_release_vault_scopes_runs_in_threadpool(monkeypatch) -> None:asyncio.run(ui_server._archive_release_vault_scopes("ses_archive",- [{"scope_type": "secret", "scope_ref": "ARCHIVE_KEY"}],+ [{"grant_id": "vgr_archive"}],))assert callsrelease.assert_called_once_with(- [{"scope_type": "secret", "scope_ref": "ARCHIVE_KEY"}],+ [{"grant_id": "vgr_archive"}],reason="archive_session:ses_archive",)diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 308c10b82..7875ea786 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -17,7 +17,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260627_0025"+HEAD_REVISION = "20260703_0026"def _index_sql(conn: sqlite3.Connection, name: str) -> str:@@ -332,10 +332,10 @@ def test_run_migrations_strips_vault_secret_preview_metadata(tmp_path: Path) ->conn.executemany("""insert into vault_secrets (- id, name, group_name, tags, kind, protection, source,+ id, name, tags, kind, protection, source,ciphertext, nonce, wrap_meta, public_meta, policy,use_count, created_at, updated_at- ) values (?, ?, 'default', null, 'static', 'standard', 'manual',+ ) values (?, ?, null, 'static', 'standard', 'manual','ct', 'nonce', 'wrap', ?, null, 0, 'now', 'now')""",[@@ -368,17 +368,29 @@ def test_run_migrations_strips_vault_secret_preview_metadata(tmp_path: Path) ->assert "9999" not in json.dumps(rows)-def test_run_migrations_adds_vault_grant_agent_readiness_columns(tmp_path: Path) -> None:+def test_vault_snapshot_uses_final_grant_id_readiness_model(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"- run_migrations(db_path, revision="20260626_0024")+ run_migrations(db_path, revision="20260621_0023")with sqlite3.connect(db_path) as conn:version = conn.execute("select version_num from alembic_version").fetchone()- before_columns = {row[1] for row in conn.execute('pragma table_info("vault_grants")')}+ columns = {row[1] for row in conn.execute('pragma table_info("vault_grants")')}- assert version == ("20260626_0024",)- assert "agent_ready" not in before_columns- assert "agent_ready_at" not in before_columns+ assert version == ("20260621_0023",)+ assert {+ "id",+ "member_snapshot",+ "source_selector",+ "request_id",+ "session_id",+ "purpose",+ "one_shot",+ "expires_at",+ "agent_ready",+ "agent_ready_at",+ } <= columns+ assert "scope_type" not in columns+ assert "scope_ref" not in columnsrun_migrations(db_path)run_migrations(db_path)@@ -388,7 +400,124 @@ def test_run_migrations_adds_vault_grant_agent_readiness_columns(tmp_path: Path)columns = {row[1] for row in conn.execute('pragma table_info("vault_grants")')}assert version == (HEAD_REVISION,)- assert {"agent_ready", "agent_ready_at"} <= columns+ assert {"request_id", "session_id", "purpose", "agent_ready", "agent_ready_at"} <= columns+ assert "scope_type" not in columns+ assert "scope_ref" not in columns+++def test_vault_links_are_preserved_as_skill_tags_before_drop(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260627_0025")++ with sqlite3.connect(db_path) as conn:+ conn.executemany(+ """+ insert into vault_secrets (+ id, name, tags, kind, protection, source,+ ciphertext, nonce, wrap_meta, public_meta, policy,+ use_count, created_at, updated_at+ ) values (?, ?, ?, 'static', 'standard', 'manual',+ 'ct', 'nonce', 'wrap', null, null, 0, 'now', 'now')+ """,+ [+ ("vlt_a", "A_KEY", json.dumps(["existing"])),+ ("vlt_b", "B_KEY", None),+ ],+ )+ conn.execute(+ """+ create table vault_links (+ id text primary key,+ secret_name text not null,+ skill_name text not null,+ source text not null default 'agent',+ required integer not null default 0,+ created_at text not null,+ unique(secret_name, skill_name)+ )+ """+ )+ conn.execute("create index ix_vault_links_skill on vault_links(skill_name)")+ conn.executemany(+ """+ insert into vault_links (id, secret_name, skill_name, source, required, created_at)+ values (?, ?, ?, 'agent', 0, 'now')+ """,+ [+ ("lnk_1", "A_KEY", "deploy"),+ ("lnk_2", "A_KEY", "skill:release"),+ ("lnk_3", "B_KEY", "deploy"),+ ],+ )+ conn.commit()++ run_migrations(db_path)+ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ tables = {row[0] for row in conn.execute("select name from sqlite_master where type = 'table'")}+ rows = dict(conn.execute("select name, tags from vault_secrets order by name").fetchall())++ assert "vault_links" not in tables+ assert json.loads(rows["A_KEY"]) == ["existing", "skill:deploy", "skill:release"]+ assert json.loads(rows["B_KEY"]) == ["skill:deploy"]+++def test_run_migrations_expires_legacy_pending_access_cards(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260627_0025")++ now = "2026-07-03T00:00:00+00:00"+ legacy_delivery = json.dumps(+ {+ "card": {+ "card_type": "approval",+ "scope_options": [{"scope_type": "secret", "scope_ref": "A_KEY"}],+ }+ }+ )+ current_delivery = json.dumps(+ {+ "card": {+ "card_type": "approval",+ "grant_options": [+ {+ "grant_id": "vgr_ready",+ "member_snapshot": ["B_KEY"],+ "source_selector": {"env": ["B_KEY"]},+ }+ ],+ }+ }+ )+ with sqlite3.connect(db_path) as conn:+ conn.executemany(+ """+ insert into vault_requests (+ id, request_type, secret_name, requester, delivery, status,+ message_id, created_at, decided_at, expires_at+ ) values (?, ?, ?, null, ?, 'pending', null, ?, null, null)+ """,+ [+ ("req_legacy", "access", "A_KEY", legacy_delivery, now),+ ("req_current", "access", "B_KEY", current_delivery, now),+ ("req_sign", "sign", "SIGNING_KEY", legacy_delivery, now),+ ],+ )+ conn.commit()++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ rows = {+ row[0]: (row[1], row[2])+ for row in conn.execute("select id, status, decided_at from vault_requests order by id").fetchall()+ }++ assert rows["req_legacy"][0] == "expired"+ assert rows["req_legacy"][1] is not None+ assert rows["req_current"] == ("pending", None)+ assert rows["req_sign"] == ("pending", None)def test_scope_agent_backfill_migrates_explicit_agent_routes(tmp_path: Path) -> None:diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex 28697b8de..95dd9b90d 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -16,7 +16,7 @@ import pytestfrom sqlalchemy import selectfrom storage import vault_service-from storage.models import vault_links, vault_requests, vault_secrets+from storage.models import vault_requests, vault_secretsfrom storage.vault_crypto import Sealedfrom vibe import api@@ -25,6 +25,19 @@ def _sealed(suffix: str = "1") -> Sealed:return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")+def _grant_from_request(conn, request: dict, *, session_id: str | None = None, cache_ready: bool = True) -> dict:+ option = request["card"]["grant_options"][0]+ return vault_service.create_grant(+ conn,+ member_names=option["member_snapshot"],+ source_selector=option["source_selector"],+ purpose=option["purpose"],+ session_id=session_id,+ request_id=request["id"],+ cache_ready=cache_ready,+ )++def _browser_ecdsa_signature_for_digest(digest: str, *, key_value: int = 1) -> tuple[dict, dict]:from cryptography.hazmat.primitives import hashes, serializationfrom cryptography.hazmat.primitives.asymmetric import ec, utils@@ -202,9 +215,33 @@ def test_create_with_links_persists_skill_link(monkeypatch):"links": {"skills": ["github-pr-review"]},})- with api._vault_engine().connect() as conn:- rows = conn.execute(select(vault_links.c.skill_name).where(vault_links.c.secret_name == "GH_PAT")).scalars().all()- assert rows == ["github-pr-review"]+ assert api.get_vault_secrets()["secrets"][0]["tags"] == ["skill:github-pr-review"]+++def test_create_with_invalid_skill_link_returns_vault_api_error(monkeypatch):+ seal = Mock(return_value=_sealed())+ monkeypatch.setattr(api, "avault_seal_blind_box", seal)++ with pytest.raises(api.VaultApiError) as exc:+ api.create_vault_secret(+ {+ "name": "GH_PAT",+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},+ "links": {"skills": ["github review"]},+ }+ )++ assert exc.value.code == "invalid_request"+ assert exc.value.status == 409+ seal.assert_not_called()+++def test_get_vault_secrets_invalid_tag_filter_returns_vault_api_error():+ with pytest.raises(api.VaultApiError) as exc:+ api.get_vault_secrets(tag="bad tag")++ assert exc.value.code == "invalid_request"+ assert exc.value.status == 409def test_get_provision_request_by_name_returns_pending_spec():@@ -212,13 +249,13 @@ def test_get_provision_request_by_name_returns_pending_spec():req = vault_service.create_provision_request(conn,"GH_TOKEN",- spec={"group": "github", "links": {"skills": ["github-pr-review"]}},+ spec={"tags": ["github"], "links": {"skills": ["github-pr-review"]}},)result = api.get_vault_provision_request_by_name("GH_TOKEN")assert result["request"]["id"] == req["id"]- assert result["request"]["card"]["spec"]["group"] == "github"+ assert result["request"]["card"]["spec"]["tags"] == ["github", "skill:github-pr-review"]assert result["ambiguous"] is False@@ -227,24 +264,24 @@ def test_get_provision_request_returns_request_id_match():old_req = vault_service.create_provision_request(conn,"GH_TOKEN",- spec={"group": "old"},+ spec={"tags": ["old"]},)vault_service.create_provision_request(conn,"GH_TOKEN",- spec={"group": "new"},+ spec={"tags": ["new"]},)result = api.get_vault_provision_request(old_req["id"])assert result["request"]["id"] == old_req["id"]- assert result["request"]["card"]["spec"]["group"] == "old"+ assert result["request"]["card"]["spec"]["tags"] == ["old"]def test_get_provision_request_by_name_returns_none_when_ambiguous():with api._vault_engine().begin() as conn:- vault_service.create_provision_request(conn, "GH_TOKEN", spec={"group": "old"})- vault_service.create_provision_request(conn, "GH_TOKEN", spec={"group": "new"})+ vault_service.create_provision_request(conn, "GH_TOKEN", spec={"tags": ["old"]})+ vault_service.create_provision_request(conn, "GH_TOKEN", spec={"tags": ["new"]})result = api.get_vault_provision_request_by_name("GH_TOKEN")@@ -256,19 +293,19 @@ def test_create_secret_with_provision_request_id_fulfills_sibling_requests(monkeseal = Mock(return_value=_sealed("api"))monkeypatch.setattr(api, "avault_seal_blind_box", seal)with api._vault_engine().begin() as conn:- old_req = vault_service.create_provision_request(conn, "GH_TOKEN", spec={"group": "old"})- new_req = vault_service.create_provision_request(conn, "GH_TOKEN", spec={"group": "new"})+ old_req = vault_service.create_provision_request(conn, "GH_TOKEN", spec={"tags": ["old"]})+ new_req = vault_service.create_provision_request(conn, "GH_TOKEN", spec={"tags": ["new"]})created = api.create_vault_secret({"name": "GH_TOKEN",- "group": "new",+ "tags": ["new"],"blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},"provision_request_id": new_req["id"],})- assert created["secret"]["group"] == "new"+ assert created["secret"]["tags"] == ["new"]with api._vault_engine().connect() as conn:rows = {row["id"]: row["status"]@@ -616,11 +653,17 @@ def test_standard_keypair_sign_returns_signature_when_usage_audit_fails(monkeypasign.assert_called_once_with(_sealed("key"), "00" * 32, "ecdsa-secp256k1-recoverable", name="ETH_KEY")-def test_agent_access_request_and_standard_grant_api(monkeypatch):+def test_agent_access_request_and_standard_always_ask_grant_api(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("api")))agent_grant = Mock()monkeypatch.setattr(api, "avault_agent_grant", agent_grant)- api.create_vault_secret({"name": "STANDARD_KEY", "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"}})+ api.create_vault_secret(+ {+ "name": "STANDARD_KEY",+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},+ "policy": {"always_ask": True},+ }+ )requested = api.request_vault_access({@@ -633,11 +676,9 @@ def test_agent_access_request_and_standard_grant_api(monkeypatch):assert requested["ok"] is Trueassert requested["request"]["request_type"] == "access"- assert requested["request"]["card"]["scope_options"]+ assert requested["request"]["card"]["grant_options"]created = api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "STANDARD_KEY","session_id": "ses_1","request_id": requested["request"]["id"],}@@ -645,6 +686,7 @@ def test_agent_access_request_and_standard_grant_api(monkeypatch):assert created["grant"]["member_snapshot"] == ["STANDARD_KEY"]assert created["grant"]["delivery_ready"] is Trueassert created["grant"]["delivery_status"] == "standard_ready"+ assert created["grant"]["one_shot"] is Trueagent_grant.assert_not_called()with api._vault_engine().begin() as conn:grant_row = conn.execute(@@ -660,12 +702,12 @@ def test_agent_access_request_and_standard_grant_api(monkeypatch):assert fetched["result"]["grant"]["id"] == created["grant"]["id"]-def test_agent_access_request_does_not_return_protected_group_unlock_material(monkeypatch):+def test_agent_access_request_does_not_return_protected_tag_unlock_material(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("standard")))api.create_vault_secret({"name": "STANDARD_KEY",- "group": "crypto",+ "tags": ["crypto"],"blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},})@@ -673,16 +715,15 @@ def test_agent_access_request_does_not_return_protected_group_unlock_material(mo{"name": "PROTECTED_KEY","protection": "protected",- "group": "crypto",+ "tags": ["crypto"],"sealed": {"ciphertext": "ct-protected", "nonce": "n-protected", "wrap_meta": "wm-protected"},})- requested = api.request_vault_access({"name": "STANDARD_KEY", "session_id": "ses_1"})+ requested = api.request_vault_access({"source_selector": {"tags": ["crypto"]}, "session_id": "ses_1"})_assert_no_unlock_material(requested["request"]["card"])- group_option = next(option for option in requested["request"]["card"]["scope_options"] if option["scope_type"] == "group")- assert group_option["member_snapshot"] == ["PROTECTED_KEY", "STANDARD_KEY"]+ assert requested["request"]["card"]["grant_options"][0]["member_snapshot"] == ["PROTECTED_KEY"]def test_agent_access_request_ignores_client_source_for_hydration(monkeypatch):@@ -690,7 +731,7 @@ def test_agent_access_request_ignores_client_source_for_hydration(monkeypatch):api.create_vault_secret({"name": "STANDARD_KEY",- "group": "crypto",+ "tags": ["crypto"],"blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},})@@ -698,32 +739,58 @@ def test_agent_access_request_ignores_client_source_for_hydration(monkeypatch):{"name": "PROTECTED_KEY","protection": "protected",- "group": "crypto",+ "tags": ["crypto"],"sealed": {"ciphertext": "ct-protected", "nonce": "n-protected", "wrap_meta": "wm-protected"},})- requested = api.request_vault_access({"name": "STANDARD_KEY", "session_id": "ses_1", "source": "ui"})+ requested = api.request_vault_access({"source_selector": {"tags": ["crypto"]}, "session_id": "ses_1", "source": "ui"})assert requested["request"]["requester"]["source"] == "agent-cli"_assert_no_unlock_material(requested["request"]["card"])+def test_request_vault_access_malformed_selector_returns_vault_api_error():+ with pytest.raises(api.VaultApiError) as exc:+ api.request_vault_access({"source_selector": {"tags": "deploy"}, "session_id": "ses_1"})++ assert exc.value.code == "invalid_request"+ assert exc.value.status == 409+++def test_request_vault_access_reports_missing_selector_member_name():+ with pytest.raises(api.VaultApiError) as exc:+ api.request_vault_access({"source_selector": {"env": ["MISSING_KEY"]}, "session_id": "ses_1"})++ assert exc.value.code == "secret_not_found"+ assert exc.value.status == 404+ assert "MISSING_KEY" in str(exc.value)++def test_agent_access_sibling_request_result_returns_covering_grant(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("api")))- api.create_vault_secret({"name": "A_KEY", "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"}})- api.create_vault_secret({"name": "B_KEY", "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"}})- with api._vault_engine().begin() as conn:- conn.execute(vault_links.insert().values(id="ln_a", secret_name="A_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- conn.execute(vault_links.insert().values(id="ln_b", secret_name="B_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- req_a = api.request_vault_access({"name": "A_KEY", "session_id": "ses_1", "skill": "deploy"})- req_b = api.request_vault_access({"name": "B_KEY", "session_id": "ses_1", "skill": "deploy"})+ monkeypatch.setattr(api, "_require_avault_p2_surface", lambda _feature: None)+ monkeypatch.setattr(api, "avault_agent_grant", Mock(return_value={"granted": 1, "ttl_secs": 300}))+ api.create_vault_secret(+ {+ "name": "A_KEY",+ "protection": "protected",+ "sealed": {"ciphertext": "ct-a", "nonce": "n-a", "wrap_meta": "wm-a"},+ }+ )+ 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"})created = api.create_vault_grant({- "scope_type": "skill",- "scope_ref": "deploy","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},+ }+ ],})@@ -734,10 +801,62 @@ def test_agent_access_sibling_request_result_returns_covering_grant(monkeypatch)assert fetched["result"]["grant"]["id"] == created["grant"]["id"]+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_p2_surface", lambda _feature: None)+ 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(+ {+ "name": name,+ "protection": "protected",+ "tags": ["deploy"],+ "sealed": {+ "ciphertext": f"ct-{name.lower()}",+ "nonce": f"n-{name.lower()}",+ "wrap_meta": f"wm-{name.lower()}",+ },+ }+ )+ 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"})+ 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},+ },+ ],+ }+ )++ fetched = api.get_vault_request(req_b["request"]["id"])++ assert req_b["request"]["secret_name"] is None+ assert fetched["request"]["status"] == "approved"+ assert fetched["result"]["type"] == "grant"+ assert fetched["result"]["grant"]["id"] == created["grant"]["id"]++def test_get_vault_request_expires_timed_out_pending_request(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("api")))- api.create_vault_secret({"name": "STANDARD_KEY", "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"}})- requested = api.request_vault_access({"name": "STANDARD_KEY", "session_id": "ses_1", "request_ttl_seconds": 1})+ api.create_vault_secret(+ {+ "name": "PROTECTED_KEY",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ requested = api.request_vault_access({"name": "PROTECTED_KEY", "session_id": "ses_1", "request_ttl_seconds": 1})with api._vault_engine().begin() as conn:conn.execute(vault_service.vault_requests.update()@@ -758,8 +877,14 @@ def test_get_vault_request_expires_timed_out_pending_request(monkeypatch):def test_get_vault_requests_expires_and_commits_timed_out_pending_request(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("api")))- api.create_vault_secret({"name": "STANDARD_KEY", "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"}})- requested = api.request_vault_access({"name": "STANDARD_KEY", "session_id": "ses_1", "request_ttl_seconds": 1})+ api.create_vault_secret(+ {+ "name": "PROTECTED_KEY",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ requested = api.request_vault_access({"name": "PROTECTED_KEY", "session_id": "ses_1", "request_ttl_seconds": 1})with api._vault_engine().begin() as conn:conn.execute(vault_service.vault_requests.update()@@ -783,7 +908,6 @@ def test_get_vault_request_does_not_hydrate_protected_pending_unlock_material(mo{"name": "PROTECTED_KEY","protection": "protected",- "group": "crypto","sealed": {"ciphertext": "ct-protected", "nonce": "n-protected", "wrap_meta": "wm-protected"},})@@ -815,8 +939,14 @@ def test_agent_access_request_accepts_protected_static(monkeypatch):def test_deny_vault_request_api(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("api")))- api.create_vault_secret({"name": "STANDARD_KEY", "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"}})- requested = api.request_vault_access({"name": "STANDARD_KEY", "session_id": "ses_1"})+ api.create_vault_secret(+ {+ "name": "PROTECTED_KEY",+ "protection": "protected",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ }+ )+ requested = api.request_vault_access({"name": "PROTECTED_KEY", "session_id": "ses_1"})denied = api.deny_vault_request(requested["request"]["id"], {"reason": "not now", "requester": {"source": "test"}})@@ -1027,8 +1157,6 @@ def test_create_and_revoke_grant_api(monkeypatch, avault_p2):)created = api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","ttl_seconds": 300,"request_id": req["id"],@@ -1055,7 +1183,7 @@ def test_create_and_revoke_grant_api(monkeypatch, avault_p2):assert grants[0]["id"] == created["grant"]["id"]revoked = api.revoke_vault_grant(created["grant"]["id"])assert revoked["grant"]["status"] == "revoked"- agent_release.assert_called_once_with(scope_type="secret", scope_ref="GRANT_KEY")+ agent_release.assert_called_once_with(grant_id=created["grant"]["id"])def test_fulfill_access_request_relays_only_browser_dek_blindbox(monkeypatch, avault_p2):@@ -1072,10 +1200,12 @@ 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"]fulfilled = api.fulfill_vault_access_request(requested["request"]["id"],{+ "grant_id": grant_id,"session_id": "ses_1","ttl_seconds": 300,"agent_pubkey": {"public_key": "pk", "fingerprint": "fp"},@@ -1091,6 +1221,8 @@ def test_fulfill_access_request_relays_only_browser_dek_blindbox(monkeypatch, avassert fulfilled["ok"] is Trueassert fulfilled["result"]["type"] == "grant"+ assert fulfilled["grant"]["id"] == grant_id+ assert agent_grant.call_args.kwargs["grant_id"] == grant_idassert fulfilled["grant"]["delivery_ready"] is Trueassert agent_grant.call_args.kwargs["deks"] == [{@@ -1140,10 +1272,9 @@ def test_fulfill_protected_always_ask_access_uses_one_shot_resident_agent_grant()assert requested["request"]["card"]["one_shot"] is True- assert requested["request"]["card"]["scope_options"][0]["scope_ref"] == "PROTECTED_ASK"+ assert requested["request"]["card"]["grant_options"][0]["member_snapshot"] == ["PROTECTED_ASK"]assert fulfilled["grant"]["one_shot"] is True- assert fulfilled["grant"]["scope_type"] == "secret"- assert fulfilled["grant"]["scope_ref"] == "PROTECTED_ASK"+ assert fulfilled["grant"]["source_selector"] == {"env": ["PROTECTED_ASK"]}assert fulfilled["grant"]["delivery_ready"] is Truevalidate_pubkey.assert_called_once_with({"public_key": "pk", "fingerprint": "fp"})assert agent_grant.call_args.kwargs["deks"] == [@@ -1170,8 +1301,6 @@ def test_always_ask_grant_api_maps_stale_request_preflight_to_json_error(monkeypwith pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "ASK_KEY","session_id": "ses_1","request_id": requested["request"]["id"],}@@ -1201,8 +1330,6 @@ def test_always_ask_grant_api_commits_expired_preflight_request(monkeypatch):with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "ASK_KEY","session_id": "ses_1","request_id": requested["request"]["id"],}@@ -1362,11 +1489,11 @@ def test_fulfill_access_request_rejects_protected_keypair_value_delivery(monkeypwith pytest.raises(api.VaultApiError) as exc:api.request_vault_access({"name": "PROTECTED_ETH_KEY", "session_id": "ses_1"})- assert exc.value.code == "not_grantable"+ assert exc.value.code == "keypair_not_value_deliverable"agent_grant.assert_not_called()-def test_revoke_grant_keeps_agent_scope_when_other_active_grant_exists(monkeypatch):+def test_revoke_grant_releases_only_that_grant_id(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))agent_release = Mock(return_value={"released": True})monkeypatch.setattr(api, "avault_agent_release", agent_release)@@ -1378,34 +1505,24 @@ def test_revoke_grant_keeps_agent_scope_when_other_active_grant_exists(monkeypatrequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)- grant_1 = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="GRANT_KEY",- created_by_request_id=req_1["id"],- )+ grant_1 = _grant_from_request(conn, req_1)req_2 = vault_service.create_access_request(conn,"GRANT_KEY",requester={"session_id": "ses_2"},delivery={"session_id": "ses_2"},)- grant_2 = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="GRANT_KEY",- created_by_request_id=req_2["id"],- )+ grant_2 = _grant_from_request(conn, req_2)revoked = api.revoke_vault_grant(grant_1["id"])assert revoked["grant"]["status"] == "revoked"- agent_release.assert_not_called()+ agent_release.assert_called_once_with(grant_id=grant_1["id"])with api._vault_engine().connect() as conn:assert vault_service.find_active_grant_for_secret(conn, "GRANT_KEY", session_id="ses_2")["id"] == grant_2["id"]-def test_consume_one_shot_keeps_agent_scope_when_other_active_grant_exists(monkeypatch):+def test_consume_one_shot_releases_only_that_grant_id(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))agent_release = Mock(return_value={"released": True})monkeypatch.setattr(api, "avault_agent_release", agent_release)@@ -1424,28 +1541,18 @@ def test_consume_one_shot_keeps_agent_scope_when_other_active_grant_exists(monkerequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)- grant_1 = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- created_by_request_id=req_1["id"],- )+ grant_1 = _grant_from_request(conn, req_1)req_2 = vault_service.create_access_request(conn,"ASK_KEY",requester={"session_id": "ses_2"},delivery={"session_id": "ses_2"},)- grant_2 = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- created_by_request_id=req_2["id"],- )+ grant_2 = _grant_from_request(conn, req_2)api.consume_one_shot_grants([grant_1], reason="test")- agent_release.assert_not_called()+ agent_release.assert_called_once_with(grant_id=grant_1["id"])with api._vault_engine().connect() as conn:statuses = {row["id"]: row["status"]@@ -1481,25 +1588,14 @@ def test_forced_agent_grant_cleanup_treats_reserved_grant_as_live(monkeypatch):requester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)- grant_1 = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- created_by_request_id=req_1["id"],- )+ grant_1 = _grant_from_request(conn, req_1)req_2 = vault_service.create_access_request(conn,"ASK_KEY",requester={"session_id": "ses_2"},delivery={"session_id": "ses_2"},)- grant_2 = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_2",- created_by_request_id=req_2["id"],- )+ grant_2 = _grant_from_request(conn, req_2, session_id="ses_2")reserved = vault_service.resolve_secret_access(conn,"ASK_KEY",@@ -1519,7 +1615,7 @@ def test_forced_agent_grant_cleanup_treats_reserved_grant_as_live(monkeypatch):force_release_scope=True,)- agent_release.assert_not_called()+ agent_release.assert_called_once_with(grant_id=grant_1["id"])with api._vault_engine().connect() as conn:statuses = {row["id"]: row["status"]@@ -1532,11 +1628,18 @@ def test_forced_agent_grant_cleanup_treats_reserved_grant_as_live(monkeypatch):assert statuses == {grant_1["id"]: "expired", grant_2["id"]: "reserved"}-def test_revoke_grant_releases_scope_when_remaining_members_do_not_cover_cache(monkeypatch):+def test_revoke_tag_grant_releases_its_grant_id(monkeypatch):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))agent_release = Mock(return_value={"released": True})monkeypatch.setattr(api, "avault_agent_release", agent_release)- api.create_vault_secret({"name": "A_KEY", "protection": "protected", "group": "crypto", "sealed": {"ciphertext": "ct-a", "nonce": "n-a", "wrap_meta": "wm-a"}})+ api.create_vault_secret(+ {+ "name": "A_KEY",+ "protection": "protected",+ "tags": ["crypto"],+ "sealed": {"ciphertext": "ct-a", "nonce": "n-a", "wrap_meta": "wm-a"},+ }+ )with api._vault_engine().begin() as conn:req_narrow = vault_service.create_access_request(conn,@@ -1544,32 +1647,20 @@ def test_revoke_grant_releases_scope_when_remaining_members_do_not_cover_cache(mrequester={"session_id": "ses_narrow"},delivery={"session_id": "ses_narrow"},)- vault_service.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_narrow",- created_by_request_id=req_narrow["id"],- )- vault_service.create_secret(conn, name="B_KEY", protection="protected", group="crypto", sealed=_sealed("b"))- req_group = vault_service.create_access_request(- conn,- "A_KEY",- requester={"session_id": "ses_group"},- delivery={"session_id": "ses_group"},- )- group_grant = vault_service.create_grant(+ _grant_from_request(conn, req_narrow, session_id="ses_narrow")+ vault_service.create_secret(conn, name="B_KEY", protection="protected", tags=["crypto"], sealed=_sealed("b"))+ req_tag = vault_service.create_access_request(conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_group",- created_by_request_id=req_group["id"],+ source_selector={"tags": ["crypto"]},+ requester={"session_id": "ses_tag"},+ delivery={"session_id": "ses_tag"},)+ tag_grant = _grant_from_request(conn, req_tag, session_id="ses_tag")- revoked = api.revoke_vault_grant(group_grant["id"])+ revoked = api.revoke_vault_grant(tag_grant["id"])assert revoked["grant"]["status"] == "revoked"- agent_release.assert_called_once_with(scope_type="group", scope_ref="crypto")+ agent_release.assert_called_once_with(grant_id=tag_grant["id"])def test_delete_protected_secret_releases_agent_scope(monkeypatch):@@ -1586,18 +1677,12 @@ def test_delete_protected_secret_releases_agent_scope(monkeypatch):requester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)- vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="GRANT_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- )+ grant = _grant_from_request(conn, req, session_id="ses_1")removed = api.delete_vault_secret("GRANT_KEY")assert removed["removed"] is True- agent_release.assert_called_once_with(scope_type="secret", scope_ref="GRANT_KEY")+ agent_release.assert_called_once_with(grant_id=grant["id"])def test_release_agent_scope_fail_closed_resets_and_quarantines_socket(monkeypatch):@@ -1616,12 +1701,7 @@ def test_release_agent_scope_fail_closed_resets_and_quarantines_socket(monkeypatrequester={"session_id": "ses_1"},delivery={"session_id": "ses_1"},)- grant = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="GRANT_KEY",- created_by_request_id=req["id"],- )+ grant = _grant_from_request(conn, req)class Manager:def __init__(self) -> None:@@ -1632,7 +1712,7 @@ def test_release_agent_scope_fail_closed_resets_and_quarantines_socket(monkeypatmonkeypatch.setattr(api, "_avault_agent_manager", lambda: manager)monkeypatch.setattr(api, "avault_agent_release", Mock(side_effect=api.AvaultError("timed out waiting for release")))try:- api.release_vault_agent_scopes([{"scope_type": "secret", "scope_ref": "GRANT_KEY"}], reason="test")+ api.release_vault_agent_scopes([{"grant_id": grant["id"]}], reason="test")finally:listener.close()@@ -1653,7 +1733,7 @@ def test_release_agent_scope_ignores_absent_agent(monkeypatch):Mock(side_effect=api.AvaultError("failed to connect to avault agent: [Errno 2] No such file or directory")),)- api.release_vault_agent_scopes([{"scope_type": "secret", "scope_ref": "GRANT_KEY"}], reason="test")+ api.release_vault_agent_scopes([{"grant_id": "vgr_missing"}], reason="test")manager.reset.assert_not_called()@@ -1666,8 +1746,8 @@ def test_agent_grant_rejects_pubkey_mismatch(monkeypatch):with pytest.raises(api.AvaultError, match="fingerprint mismatch"):api.avault_agent_grant(- scope_type="secret",- scope_ref="GRANT_KEY",+ grant_id="vgr_grant",+ purpose="run",ttl_secs=300,deks=[{@@ -1698,8 +1778,7 @@ def test_agent_deliver_run_reuses_resident_agent_socket(monkeypatch):monkeypatch.setattr(api, "_avault_agent_manager", lambda: FakeManager())result = api.avault_agent_deliver_run(- scope_type="secret",- scope_ref="GRANT_KEY",+ grant_id="vgr_grant",secrets=[{"name": "GRANT_KEY", "env": "GRANT_KEY", "envelope": _sealed()}],command=["python3", "-c", "pass"],)@@ -1720,8 +1799,7 @@ def test_agent_deliver_run_treats_connect_failure_as_pre_handoff(monkeypatch):with pytest.raises(api.AvaultPreHandoffError):api.avault_agent_deliver_run(- scope_type="secret",- scope_ref="GRANT_KEY",+ grant_id="vgr_grant",secrets=[{"name": "GRANT_KEY", "env": "GRANT_KEY", "envelope": _sealed()}],command=["python3", "-c", "pass"],)@@ -1743,8 +1821,7 @@ def test_agent_deliver_fetch_uses_finite_timeout(monkeypatch):monkeypatch.setattr(api, "_avault_agent_manager", lambda: FakeManager())result = api.avault_agent_deliver_fetch(- scope_type="secret",- scope_ref="GRANT_KEY",+ grant_id="vgr_grant",name="GRANT_KEY",sealed=_sealed(),request={"method": "GET", "url": "https://example.com", "allowed_hosts": ["example.com"], "inject": {"type": "bearer"}},@@ -1770,8 +1847,6 @@ def test_create_grant_api_requires_resident_agent_deks(monkeypatch, avault_p2):with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],}@@ -1799,8 +1874,6 @@ def test_create_grant_api_rejects_mismatched_deks_before_claiming_request(monkeywith pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],"deks": [@@ -1847,8 +1920,6 @@ def test_create_grant_api_relay_runs_after_grant_commit(monkeypatch, avault_p2):created = api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],"deks": [@@ -1881,8 +1952,6 @@ def test_create_grant_api_rejects_stale_agent_pubkey_before_claiming_request(monwith pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],"agent_pubkey": {"public_key": "old-pk", "fingerprint": "old-fp"},@@ -1923,8 +1992,6 @@ def test_create_grant_api_expires_grant_when_agent_grant_fails(monkeypatch, avauwith pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],"deks": [@@ -1945,7 +2012,7 @@ def test_create_grant_api_expires_grant_when_agent_grant_fails(monkeypatch, avauassert len(grants) == 1assert grants[0]["status"] == "expired"assert grants[0]["delivery_ready"] is False- agent_release.assert_called_once_with(scope_type="secret", scope_ref="GRANT_KEY")+ agent_release.assert_called_once_with(grant_id=grants[0]["id"])def test_create_grant_api_rejects_partial_agent_cache(monkeypatch, avault_p2):@@ -1965,8 +2032,6 @@ def test_create_grant_api_rejects_partial_agent_cache(monkeypatch, avault_p2):with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],"deks": [@@ -1988,7 +2053,7 @@ def test_create_grant_api_rejects_partial_agent_cache(monkeypatch, avault_p2):assert len(grants) == 1assert grants[0]["status"] == "expired"assert grants[0]["delivery_ready"] is False- agent_release.assert_called_once_with(scope_type="secret", scope_ref="GRANT_KEY")+ agent_release.assert_called_once_with(grant_id=grants[0]["id"])def test_grant_ttl_uses_approved_lifetime():@@ -2021,8 +2086,6 @@ def test_create_grant_api_releases_scope_when_mark_ready_fails(monkeypatch, avauwith pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],"deks": [@@ -2033,10 +2096,9 @@ def test_create_grant_api_releases_scope_when_mark_ready_fails(monkeypatch, avau}],}- )+ )assert exc.value.code == "invalid_grant"- agent_release.assert_called_once_with(scope_type="secret", scope_ref="GRANT_KEY")with api._vault_engine().connect() as conn:status = conn.execute(select(vault_service.vault_requests.c.status).where(vault_service.vault_requests.c.id == req["id"])).scalar_one()grants = vault_service.list_grants(conn, status=None)@@ -2044,9 +2106,10 @@ def test_create_grant_api_releases_scope_when_mark_ready_fails(monkeypatch, avauassert len(grants) == 1assert grants[0]["status"] == "expired"assert grants[0]["delivery_ready"] is False+ agent_release.assert_called_once_with(grant_id=grants[0]["id"])-def test_create_grant_api_keeps_shared_agent_scope_when_relay_fails(monkeypatch, avault_p2):+def test_create_grant_api_releases_failed_grant_id_without_touching_existing_grant(monkeypatch, avault_p2):monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))monkeypatch.setattr(api, "avault_agent_grant", Mock(side_effect=api.AvaultError("grant is missing")))agent_release = Mock(return_value={"released": True})@@ -2059,13 +2122,7 @@ def test_create_grant_api_keeps_shared_agent_scope_when_relay_fails(monkeypatch,requester={"session_id": "ses_existing"},delivery={"session_id": "ses_existing"},)- existing_grant = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="GRANT_KEY",- session_id="ses_existing",- created_by_request_id=existing_req["id"],- )+ existing_grant = _grant_from_request(conn, existing_req, session_id="ses_existing")req = vault_service.create_access_request(conn,"GRANT_KEY",@@ -2076,8 +2133,6 @@ def test_create_grant_api_keeps_shared_agent_scope_when_relay_fails(monkeypatch,with pytest.raises(api.VaultApiError) as exc:api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","session_id": "ses_1","request_id": req["id"],"deks": [@@ -2091,13 +2146,13 @@ def test_create_grant_api_keeps_shared_agent_scope_when_relay_fails(monkeypatch,)assert exc.value.code == "avault_failed"- agent_release.assert_not_called()with api._vault_engine().connect() as conn:grants = {grant["id"]: grant for grant in vault_service.list_grants(conn, status=None)}assert grants[existing_grant["id"]]["status"] == "active"expired = [grant for grant in grants.values() if grant["id"] != existing_grant["id"]]assert len(expired) == 1assert expired[0]["status"] == "expired"+ agent_release.assert_called_once_with(grant_id=expired[0]["id"])def test_create_grant_api_preserves_unbound_session_choice(monkeypatch, avault_p2):@@ -2116,8 +2171,6 @@ def test_create_grant_api_preserves_unbound_session_choice(monkeypatch, avault_pcreated = api.create_vault_grant({- "scope_type": "secret",- "scope_ref": "GRANT_KEY","request_id": req["id"],"this_session_only": False,"deks": [@@ -2133,6 +2186,31 @@ def test_create_grant_api_preserves_unbound_session_choice(monkeypatch, avault_passert created["grant"]["session_id"] is None+def test_create_grant_api_binds_one_shot_to_request_session_when_unbound_requested(monkeypatch):+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("ask")))+ api.create_vault_secret(+ {+ "name": "ASK_KEY",+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},+ "policy": {"always_ask": True},+ }+ )+ requested = api.request_vault_access({"name": "ASK_KEY", "session_id": "ses_1"})++ created = api.create_vault_grant(+ {+ "request_id": requested["request"]["id"],+ "this_session_only": False,+ }+ )++ assert created["grant"]["one_shot"] is True+ assert created["grant"]["session_id"] == "ses_1"+ with api._vault_engine().begin() as conn:+ assert vault_service.find_active_grant_for_secret(conn, "ASK_KEY", session_id="other") is None+ assert vault_service.find_active_grant_for_secret(conn, "ASK_KEY", session_id="ses_1")["id"] == created["grant"]["id"]++def test_protected_sign_requires_browser_signature(monkeypatch):from unittest.mock import Mock@@ -2152,7 +2230,7 @@ def test_protected_sign_requires_browser_signature(monkeypatch):assert result["ok"] is Falseassert result["code"] == "browser_signature_required"assert result["request"]["card"]["request_type"] == "sign"- assert result["request"]["card"]["scope_options"] == []+ assert result["request"]["card"]["grant_options"] == []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 c6c427a06..486234d83 100644--- a/tests/test_vault_cli.py+++ b/tests/test_vault_cli.py@@ -26,7 +26,6 @@ def _ns(**kw):name=None,stdin=False,from_file=None,- group=None,tag=None,description=None,allow_host=None,@@ -65,25 +64,32 @@ def _create_standard_secret(name: str, *, sealed: Sealed | None = None, **kwargsreturn vault_service.create_secret(conn, name=name, sealed=sealed or _sealed(), **kwargs)-def _set_protected_grant(name: str, *, session_id: str | None = None) -> dict:+def _grant_from_request(conn, request: dict, *, session_id: str | None = None) -> dict:+ option = request["card"]["grant_options"][0]+ return vault_service.create_grant(+ conn,+ member_names=option["member_snapshot"],+ source_selector=option["source_selector"],+ purpose=option["purpose"],+ session_id=session_id,+ request_id=request["id"],+ )+++def _set_protected_grant(name: str, *, session_id: str | None = None, purpose: str = "run") -> dict:with cli._open_vault_engine().begin() as conn:vault_service.create_secret(conn, name=name, protection="protected", sealed=_sealed("protected"))req = vault_service.create_access_request(conn,name,+ purpose=purpose,requester={"source": "cli", "session_id": session_id} if session_id else {"source": "cli"},- delivery={"session_id": session_id, "mode": "run"} if session_id else {"mode": "run"},- )- return vault_service.create_grant(- conn,- scope_type="secret",- scope_ref=name,- session_id=session_id,- created_by_request_id=req["id"],+ delivery={"session_id": session_id, "mode": purpose} if session_id else {"mode": purpose},)+ return _grant_from_request(conn, req, session_id=session_id)-def _set_protected_always_ask_grant(name: str, *, session_id: str | None = None) -> dict:+def _set_protected_always_ask_grant(name: str, *, session_id: str | None = None, purpose: str = "run") -> dict:with cli._open_vault_engine().begin() as conn:vault_service.create_secret(conn,@@ -95,38 +101,27 @@ def _set_protected_always_ask_grant(name: str, *, session_id: str | None = None)req = vault_service.create_access_request(conn,name,+ purpose=purpose,requester={"source": "cli", "session_id": session_id} if session_id else {"source": "cli"},- delivery={"session_id": session_id, "mode": "run"} if session_id else {"mode": "run"},- )- return vault_service.create_grant(- conn,- scope_type="secret",- scope_ref=name,- session_id=session_id,- created_by_request_id=req["id"],+ delivery={"session_id": session_id, "mode": purpose} if session_id else {"mode": purpose},)+ return _grant_from_request(conn, req, session_id=session_id)-def _set_group_grant(names: list[str], *, group: str = "crypto", session_id: str | None = None) -> dict:+def _set_tag_grant(names: list[str], *, tag: str = "crypto", session_id: str | None = None) -> dict:with cli._open_vault_engine().begin() as conn:for name in names:- vault_service.create_secret(conn, name=name, protection="protected", group=group, sealed=_sealed(name.lower()))+ vault_service.create_secret(conn, name=name, protection="protected", tags=[tag], sealed=_sealed(name.lower()))req = vault_service.create_access_request(conn,- names[0],+ source_selector={"tags": [tag]},requester={"source": "cli", "session_id": session_id} if session_id else {"source": "cli"},delivery={"session_id": session_id, "mode": "run"} if session_id else {"mode": "run"},)- return vault_service.create_grant(- conn,- scope_type="group",- scope_ref=group,- session_id=session_id,- created_by_request_id=req["id"],- )+ return _grant_from_request(conn, req, session_id=session_id)-def _set_always_ask_standard_grant(name: str, *, session_id: str | None = None) -> dict:+def _set_always_ask_standard_grant(name: str, *, session_id: str | None = None, purpose: str = "run") -> dict:with cli._open_vault_engine().begin() as conn:vault_service.create_secret(conn,@@ -138,16 +133,38 @@ def _set_always_ask_standard_grant(name: str, *, session_id: str | None = None)req = vault_service.create_access_request(conn,name,+ purpose=purpose,requester={"source": "cli", "session_id": session_id} if session_id else {"source": "cli"},- delivery={"session_id": session_id, "mode": "run"} if session_id else {"mode": "run"},+ delivery={"session_id": session_id, "mode": purpose} if session_id else {"mode": purpose},)- return vault_service.create_grant(+ return _grant_from_request(conn, req, session_id=session_id)+++def _set_always_ask_standard_tag_grant(+ names: list[str],+ *,+ tag: str = "batch",+ session_id: str | None = None,+ purpose: str = "run",+) -> dict:+ with cli._open_vault_engine().begin() as conn:+ for name in names:+ vault_service.create_secret(+ conn,+ name=name,+ protection="standard",+ sealed=_sealed(name.lower()),+ tags=[tag],+ policy={"always_ask": True},+ )+ req = vault_service.create_access_request(conn,- scope_type="secret",- scope_ref=name,- session_id=session_id,- created_by_request_id=req["id"],+ source_selector={"tags": [tag]},+ purpose=purpose,+ requester={"source": "cli", "session_id": session_id} if session_id else {"source": "cli"},+ delivery={"session_id": session_id, "mode": purpose} if session_id else {"mode": purpose},)+ return _grant_from_request(conn, req, session_id=session_id)@pytest.mark.parametrize(@@ -222,15 +239,19 @@ def test_discover_reports_value_free_capabilities(tmp_path, capfd, monkeypatch):def test_access_request_cli_uses_caller_session(tmp_path, capfd, monkeypatch):- _create_standard_secret("STANDARD_KEY")+ with cli._open_vault_engine().begin() as conn:+ vault_service.create_secret(conn, name="PROTECTED_KEY", protection="protected", sealed=_sealed("protected"))monkeypatch.setenv("AVIBE_SESSION_ID", "ses_cli")- assert cli.cmd_vault_access(_ns(name="STANDARD_KEY", command="python sync.py")) == 0+ assert cli.cmd_vault_access(_ns(name="PROTECTED_KEY", command="python sync.py", skill="deploy")) == 0payload = json.loads(capfd.readouterr().out)assert payload["kind"] == "vault_access_request"assert payload["request"]["requester"]["session_id"] == "ses_cli"+ assert payload["request"]["requester"]["skill"] == "deploy"assert payload["request"]["delivery"]["command"] == "python sync.py"+ assert payload["request"]["delivery"]["skill"] == "deploy"+ assert payload["request"]["card"]["skill"] == "deploy"assert payload["request"]["status"] == "pending"@@ -296,7 +317,7 @@ def test_sign_request_cli_accepts_protected_keypair(capfd):assert payload["kind"] == "vault_sign_request"assert payload["request"]["secret_name"] == "PROTECTED_ETH_KEY"assert payload["request"]["card"]["protection"] == "protected"- assert payload["request"]["card"]["scope_options"] == []+ assert payload["request"]["card"]["grant_options"] == []def test_vault_await_wait_treats_failed_request_as_terminal(capfd):@@ -446,8 +467,7 @@ def test_run_delivers_protected_secret_under_agent_grant(tmp_path, capfd, monkeyassert "protected out\n" in captured.outassert "protected err\n" in captured.errdeliver.assert_called_once()- assert deliver.call_args.kwargs["scope_type"] == grant["scope_type"]- assert deliver.call_args.kwargs["scope_ref"] == grant["scope_ref"]+ assert deliver.call_args.kwargs["grant_id"] == grant["id"]assert deliver.call_args.kwargs["secrets"] == [{"name": "PROTECTED_KEY", "env": "LOCAL_NAME", "envelope": _sealed("protected")}]command = deliver.call_args.kwargs["command"]shell = shutil.which("sh") or "/bin/sh"@@ -507,6 +527,7 @@ def test_run_allows_tty_stdio_for_protected_delivery(tmp_path, monkeypatch):_set_protected_grant("PROTECTED_KEY")deliver = Mock(return_value={"exit_code": 0})monkeypatch.setattr(api, "avault_agent_deliver_run", deliver)+ monkeypatch.setattr(api, "avault_agent_release", Mock(return_value={"released": True}))monkeypatch.setattr(api, "avault_deliver_run", Mock())assert cli.cmd_vault_run(_ns(env=["PROTECTED_KEY"], command_argv=["python3", "-c", "pass"])) == 0@@ -563,7 +584,7 @@ def test_run_prefers_common_grant_for_protected_batch(tmp_path, capfd, monkeypatfrom vibe import apimonkeypatch.chdir(tmp_path)- group_grant = _set_group_grant(["A_KEY", "B_KEY"])+ tag_grant = _set_tag_grant(["A_KEY", "B_KEY"])with cli._open_vault_engine().begin() as conn:req = vault_service.create_access_request(conn,@@ -571,7 +592,7 @@ def test_run_prefers_common_grant_for_protected_batch(tmp_path, capfd, monkeypatrequester={"source": "cli"},delivery={"mode": "run"},)- vault_service.create_grant(conn, scope_type="secret", scope_ref="A_KEY", created_by_request_id=req["id"])+ _grant_from_request(conn, req)deliver = Mock(return_value={"exit_code": 0, "stdout": b"", "stderr": b""})monkeypatch.setattr(api, "avault_agent_deliver_run", deliver)monkeypatch.setattr(api, "avault_deliver_run", Mock())@@ -580,8 +601,7 @@ def test_run_prefers_common_grant_for_protected_batch(tmp_path, capfd, monkeypatassert code == 0deliver.assert_called_once()- assert deliver.call_args.kwargs["scope_type"] == group_grant["scope_type"]- assert deliver.call_args.kwargs["scope_ref"] == group_grant["scope_ref"]+ assert deliver.call_args.kwargs["grant_id"] == tag_grant["id"]assert [secret["name"] for secret in deliver.call_args.kwargs["secrets"]] == ["A_KEY", "B_KEY"]@@ -599,13 +619,13 @@ def test_run_uses_session_bound_protected_grant(tmp_path, capfd, monkeypatch):assert code == 0deliver.assert_called_once()assert deliver.call_args.kwargs["secrets"][0]["name"] == "PROTECTED_KEY"- assert deliver.call_args.kwargs["scope_ref"] == "PROTECTED_KEY"+ assert deliver.call_args.kwargs["grant_id"]def test_fetch_uses_session_bound_protected_grant(capfd, monkeypatch):from vibe import api- grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli")+ grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli", purpose="fetch")with cli._open_vault_engine().begin() as conn:row = conn.execute(vault_service.vault_secrets.select().where(vault_service.vault_secrets.c.name == "PROTECTED_KEY")).mappings().one()conn.execute(@@ -623,12 +643,12 @@ def test_fetch_uses_session_bound_protected_grant(capfd, monkeypatch):assert code == 0assert captured.out == "ok"deliver.assert_called_once()- assert deliver.call_args.kwargs["scope_ref"] == grant["scope_ref"]+ assert deliver.call_args.kwargs["grant_id"] == grant["id"]assert deliver.call_args.kwargs["sealed"] == _sealed("protected")def test_inject_resolver_uses_session_bound_protected_grant(tmp_path):- grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli")+ grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli", purpose="inject")engine = cli._open_vault_engine()resolved_grant, one_shot_grants, secrets = cli._resolve_vault_inject_delivery(@@ -679,15 +699,10 @@ def test_run_fast_path_does_not_reuse_reserved_protected_always_ask_grant(tmp_parequester={"source": "cli", "session_id": "ses_cli"},delivery={"session_id": "ses_cli", "mode": "run"},)- active_grant = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="PROTECTED_ASK",- session_id="ses_cli",- created_by_request_id=req["id"],- )+ active_grant = _grant_from_request(conn, req, session_id="ses_cli")deliver = Mock(return_value={"exit_code": 0})monkeypatch.setattr(api, "avault_agent_deliver_run", deliver)+ monkeypatch.setattr(api, "avault_agent_release", Mock(return_value={"released": True}))monkeypatch.setattr(api, "avault_deliver_run", Mock())code = cli.cmd_vault_run(_ns(env=["PROTECTED_ASK"], command_argv=["python3", "-c", "pass"], session_id="ses_cli"))@@ -706,7 +721,7 @@ def test_run_fast_path_does_not_reuse_reserved_protected_always_ask_grant(tmp_padef test_inject_fast_path_reserves_protected_always_ask_grant(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_protected_always_ask_grant("PROTECTED_ASK", session_id="ses_cli")+ grant = _set_protected_always_ask_grant("PROTECTED_ASK", session_id="ses_cli", purpose="inject")deliver = Mock()monkeypatch.setattr(api, "avault_agent_deliver_inject", deliver)monkeypatch.setattr(api, "avault_deliver_inject", Mock())@@ -749,8 +764,8 @@ def test_run_mixed_grants_releases_reserved_always_ask_grants_before_delivery(tmdef test_inject_mixed_grants_releases_reserved_always_ask_grants_before_delivery(tmp_path, capfd, monkeypatch):from vibe import api- grant_a = _set_protected_always_ask_grant("A_ASK", session_id="ses_cli")- grant_b = _set_protected_always_ask_grant("B_ASK", session_id="ses_cli")+ grant_a = _set_protected_always_ask_grant("A_ASK", session_id="ses_cli", purpose="inject")+ grant_b = _set_protected_always_ask_grant("B_ASK", session_id="ses_cli", purpose="inject")deliver = Mock()monkeypatch.setattr(api, "avault_agent_deliver_inject", deliver)monkeypatch.setattr(api, "avault_deliver_inject", Mock())@@ -799,6 +814,58 @@ def test_run_reuses_reserved_grant_for_duplicate_always_ask_secret(tmp_path, capassert status == "expired"+def test_run_reuses_multi_secret_standard_one_shot_grant(tmp_path, capfd, monkeypatch):+ from vibe import api++ grant = _set_always_ask_standard_tag_grant(["ASK_A", "ASK_B"], session_id="ses_cli")+ deliver = Mock(return_value={"exit_code": 0, "delivered": True})+ monkeypatch.setattr(api, "avault_deliver_run", deliver)++ code = cli.cmd_vault_run(+ _ns(+ env=["A=ASK_A", "B=ASK_B"],+ command_argv=["python3", "-c", "pass"],+ session_id="ses_cli",+ )+ )++ assert code == 0+ deliver.assert_called_once_with(+ [+ {"name": "ASK_A", "env": "A", "envelope": _sealed("ask_a")},+ {"name": "ASK_B", "env": "B", "envelope": _sealed("ask_b")},+ ],+ ["python3", "-c", "pass"],+ )+ with cli._open_vault_engine().connect() as conn:+ status = conn.execute(vault_grants.select().where(vault_grants.c.id == grant["id"])).mappings().one()["status"]+ assert status == "expired"+++def test_inject_reuses_multi_secret_standard_one_shot_grant(tmp_path, capfd, monkeypatch):+ from vibe import api++ grant = _set_always_ask_standard_tag_grant(["ASK_A", "ASK_B"], session_id="ses_cli", purpose="inject")+ deliver = Mock(return_value=None)+ monkeypatch.setattr(api, "avault_deliver_inject", deliver)+ out = tmp_path / "out.env"++ code = cli.cmd_vault_inject(_ns(keys="ASK_A,ASK_B", out=str(out), format="dotenv", session_id="ses_cli"))++ assert code == 0+ deliver.assert_called_once_with(+ str(out),+ "dotenv",+ [+ {"name": "ASK_A", "key": "ASK_A", "envelope": _sealed("ask_a")},+ {"name": "ASK_B", "key": "ASK_B", "envelope": _sealed("ask_b")},+ ],+ )+ with cli._open_vault_engine().connect() as conn:+ status = conn.execute(vault_grants.select().where(vault_grants.c.id == grant["id"])).mappings().one()["status"]+ assert status == "expired"++def test_run_does_not_consume_always_ask_grant_when_later_secret_needs_approval(tmp_path, capfd, monkeypatch):from vibe import api@@ -922,7 +989,7 @@ def test_run_releases_one_shot_grant_when_later_resolution_aborts_before_handoffdef test_inject_consumes_standard_always_ask_grant_when_avault_errors_after_handoff(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli")+ grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli", purpose="inject")deliver = Mock(side_effect=api.AvaultError("write failed after possible handoff"))monkeypatch.setattr(api, "avault_deliver_inject", deliver)@@ -940,7 +1007,7 @@ def test_inject_consumes_standard_always_ask_grant_when_avault_errors_after_handdef test_inject_releases_standard_always_ask_grant_when_avault_fails_before_handoff(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli")+ grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli", purpose="inject")deliver = Mock(side_effect=api.AvaultPreHandoffError("avault is required for vault inject"))monkeypatch.setattr(api, "avault_deliver_inject", deliver)@@ -958,7 +1025,7 @@ def test_inject_releases_standard_always_ask_grant_when_avault_fails_before_handdef test_inject_uses_resolved_output_path_for_standard_always_ask_delivery(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli")+ grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli", purpose="inject")deliver = Mock(return_value=None)monkeypatch.setattr(api, "avault_deliver_inject", deliver)monkeypatch.setenv("HOME", str(tmp_path))@@ -978,7 +1045,7 @@ def test_inject_uses_resolved_output_path_for_standard_always_ask_delivery(tmp_pdef test_inject_rejects_unwritable_output_before_reserving_one_shot_grant(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli")+ grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli", purpose="inject")deliver = Mock()monkeypatch.setattr(api, "avault_deliver_inject", deliver)@@ -998,7 +1065,7 @@ def test_inject_rejects_unwritable_output_before_reserving_one_shot_grant(tmp_padef test_inject_rejects_existing_directory_output_before_reserving_one_shot_grant(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli")+ grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli", purpose="inject")deliver = Mock()monkeypatch.setattr(api, "avault_deliver_inject", deliver)out = tmp_path / "out.env"@@ -1018,7 +1085,7 @@ def test_inject_rejects_existing_directory_output_before_reserving_one_shot_grandef test_inject_releases_one_shot_grant_when_later_resolution_aborts_before_handoff(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli")+ grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli", purpose="inject")with cli._open_vault_engine().begin() as conn:vault_service.create_secret(conn, name="ETH_KEY", sealed=_sealed("eth"), kind="keypair", signer_kind="local")deliver = Mock()@@ -1045,13 +1112,7 @@ def test_expire_agent_grant_after_missing_does_not_reserve_replacement_grant(tmprequester={"source": "cli", "session_id": "ses_cli"},delivery={"mode": "run", "session_id": "ses_cli"},)- replacement = vault_service.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_cli",- created_by_request_id=req["id"],- )+ replacement = _grant_from_request(conn, req, session_id="ses_cli")cli._expire_agent_grant_after_missing(engine,@@ -1114,12 +1175,13 @@ def test_run_expires_grant_when_agent_cache_is_missing(capfd, monkeypatch):assert requests[0]["secret_name"] == "PROTECTED_KEY"assert requests[0]["requester"]["session_id"] == "ses_cli"assert requests[0]["delivery"]["session_id"] == "ses_cli"+ assert requests[0]["card"]["grant_options"][0]["purpose"] == "run"-def test_run_reopens_only_one_approval_when_group_agent_cache_is_missing(capfd, monkeypatch):+def test_run_reopens_only_one_approval_when_tag_agent_cache_is_missing(capfd, monkeypatch):from vibe import api- grant = _set_group_grant(["A_KEY", "B_KEY"])+ grant = _set_tag_grant(["A_KEY", "B_KEY"])monkeypatch.setattr(api, "avault_agent_deliver_run", Mock(side_effect=api.AvaultError("grant is missing or expired")))code = cli.cmd_vault_run(_ns(env=["A_KEY", "B_KEY"], command_argv=["python3", "-c", "pass"]))@@ -1138,7 +1200,7 @@ def test_run_reopens_only_one_approval_when_group_agent_cache_is_missing(capfd,def test_fetch_reopens_session_bound_approval_when_agent_cache_is_missing(capfd, monkeypatch):from vibe import api- grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli")+ grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli", purpose="fetch")with cli._open_vault_engine().begin() as conn:conn.execute(vault_service.vault_secrets.update()@@ -1159,12 +1221,13 @@ def test_fetch_reopens_session_bound_approval_when_agent_cache_is_missing(capfd,assert requests[0]["secret_name"] == "PROTECTED_KEY"assert requests[0]["requester"]["session_id"] == "ses_cli"assert requests[0]["delivery"]["session_id"] == "ses_cli"+ assert requests[0]["card"]["grant_options"][0]["purpose"] == "fetch"def test_inject_reopens_session_bound_approval_when_agent_cache_is_missing(tmp_path, capfd, monkeypatch):from vibe import api- grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli")+ grant = _set_protected_grant("PROTECTED_KEY", session_id="ses_cli", purpose="inject")monkeypatch.setattr(api, "avault_agent_deliver_inject", Mock(side_effect=api.AvaultError("grant is missing or expired")))out = tmp_path / "out.env"@@ -1180,6 +1243,7 @@ def test_inject_reopens_session_bound_approval_when_agent_cache_is_missing(tmp_passert requests[0]["secret_name"] == "PROTECTED_KEY"assert requests[0]["requester"]["session_id"] == "ses_cli"assert requests[0]["delivery"]["session_id"] == "ses_cli"+ assert requests[0]["card"]["grant_options"][0]["purpose"] == "inject"def test_run_persists_protected_approval_request_without_grant(capfd):@@ -1300,7 +1364,6 @@ def test_request_accepts_spec_path(tmp_path, capfd):spec_path.write_text(json.dumps({- "group": "github","tags": ["github"],"protection": "protected","policy": {"allowed_hosts": ["api.github.com"], "auth": {"type": "bearer"}},@@ -1314,7 +1377,7 @@ def test_request_accepts_spec_path(tmp_path, capfd):payload = json.loads(capfd.readouterr().out)assert code == 0- assert payload["request"]["card"]["spec"]["group"] == "github"+ assert payload["request"]["card"]["spec"]["tags"] == ["github", "skill:github-pr-review"]assert payload["request"]["card"]["spec"]["policy"]["allowed_hosts"] == ["api.github.com"]assert payload["request"]["card"]["spec"]["links"] == {"skills": ["github-pr-review"]}assert payload["request_id"] in payload["message"]diff --git a/tests/test_vault_export_inject.py b/tests/test_vault_export_inject.pyindex 9e6c01de0..2ab9ed391 100644--- a/tests/test_vault_export_inject.py+++ b/tests/test_vault_export_inject.py@@ -42,22 +42,29 @@ def _create_standard_secret(name: str, *, sealed: Sealed | None = None):vault_service.create_secret(conn, name=name, sealed=sealed or _sealed(name.lower()))+def _grant_from_request(conn, request: dict, *, session_id: str | None = None) -> dict:+ option = request["card"]["grant_options"][0]+ return vault_service.create_grant(+ conn,+ member_names=option["member_snapshot"],+ source_selector=option["source_selector"],+ purpose=option["purpose"],+ session_id=session_id,+ request_id=request["id"],+ )++def _set_protected_grant(name: str, *, session_id: str | None = None) -> dict:with cli._open_vault_engine().begin() as conn:vault_service.create_secret(conn, name=name, protection="protected", sealed=_sealed(name.lower()))req = vault_service.create_access_request(conn,name,+ purpose="inject",requester={"source": "cli", "session_id": session_id} if session_id else {"source": "cli"},delivery={"session_id": session_id, "mode": "inject"} if session_id else {"mode": "inject"},)- return vault_service.create_grant(- conn,- scope_type="secret",- scope_ref=name,- session_id=session_id,- created_by_request_id=req["id"],- )+ return _grant_from_request(conn, req, session_id=session_id)def test_export_is_deprecated_and_does_not_touch_db(capfd):@@ -131,8 +138,7 @@ def test_inject_uses_agent_delivery_for_protected_grant(tmp_path, capfd, monkeypassert cli.cmd_vault_inject(_ns(keys="PROTECTED_KEY", out=str(out), format="dotenv")) == 0inject.assert_called_once_with(- scope_type=grant["scope_type"],- scope_ref=grant["scope_ref"],+ grant_id=grant["id"],path=str(out),fmt="dotenv",secrets=[{"name": "PROTECTED_KEY", "key": "PROTECTED_KEY", "envelope": _sealed("protected_key")}],@@ -156,8 +162,7 @@ def test_inject_resolves_protected_relative_output_in_caller_cwd(tmp_path, capfdpayload = json.loads(capfd.readouterr().out)inject.assert_called_once_with(- scope_type=grant["scope_type"],- scope_ref=grant["scope_ref"],+ grant_id=grant["id"],path=expected,fmt="dotenv",secrets=[{"name": "PROTECTED_KEY", "key": "PROTECTED_KEY", "envelope": _sealed("protected_key")}],diff --git a/tests/test_vault_fetch.py b/tests/test_vault_fetch.pyindex aa5f908c2..c8c318c0d 100644--- a/tests/test_vault_fetch.py+++ b/tests/test_vault_fetch.py@@ -67,6 +67,18 @@ def _create_standard_secret()+def _grant_from_request(conn, request: dict, *, session_id: str | None = None) -> dict:+ option = request["card"]["grant_options"][0]+ return vault_service.create_grant(+ conn,+ member_names=option["member_snapshot"],+ source_selector=option["source_selector"],+ purpose=option["purpose"],+ session_id=session_id,+ request_id=request["id"],+ )++def _set_protected_grant(name: str, *, allow_host: list[str], session_id: str | None = None) -> dict:with cli._open_vault_engine().begin() as conn:vault_service.create_secret(@@ -79,16 +91,11 @@ def _set_protected_grant(name: str, *, allow_host: list[str], session_id: str |req = vault_service.create_access_request(conn,name,+ purpose="fetch",requester={"source": "cli", "session_id": session_id} if session_id else {"source": "cli"},delivery={"session_id": session_id, "mode": "fetch"} if session_id else {"mode": "fetch"},)- return vault_service.create_grant(- conn,- scope_type="secret",- scope_ref=name,- session_id=session_id,- created_by_request_id=req["id"],- )+ return _grant_from_request(conn, req, session_id=session_id)def _set_always_ask_grant(name: str, *, allow_host: list[str]) -> dict:@@ -102,15 +109,11 @@ def _set_always_ask_grant(name: str, *, allow_host: list[str]) -> dict:req = vault_service.create_access_request(conn,name,+ purpose="fetch",requester={"source": "cli"},delivery={"mode": "fetch"},)- return vault_service.create_grant(- conn,- scope_type="secret",- scope_ref=name,- created_by_request_id=req["id"],- )+ return _grant_from_request(conn, req)def test_fetch_passes_bearer_request_to_avault_and_writes_stdout(tmp_path, capfd, monkeypatch):@@ -181,8 +184,7 @@ def test_fetch_uses_agent_delivery_for_protected_grant(capfd, monkeypatch):assert code == 0assert captured.out == '{"ok":true}'fetch.assert_called_once()- assert fetch.call_args.kwargs["scope_type"] == grant["scope_type"]- assert fetch.call_args.kwargs["scope_ref"] == grant["scope_ref"]+ assert fetch.call_args.kwargs["grant_id"] == grant["id"]assert fetch.call_args.kwargs["sealed"] == _sealed("gh_pat")assert "value" not in repr(fetch.call_args.kwargs)diff --git a/tests/test_vault_rest.py b/tests/test_vault_rest.pyindex 8a0cfa50b..fb3a040cc 100644--- a/tests/test_vault_rest.py+++ b/tests/test_vault_rest.py@@ -67,6 +67,15 @@ def test_rest_create_rejects_standard_plaintext_value(monkeypatch):seal.assert_not_called()+def test_rest_list_invalid_tag_returns_vault_error():+ client = app.test_client()++ response = client.get("/api/vault/secrets?tag=bad%20tag")++ assert response.status_code == 409+ assert response.get_json()["code"] == "invalid_request"++def test_rest_create_rejects_plaintext_value_in_mixed_payloads(monkeypatch):seal = Mock()monkeypatch.setattr(api, "avault_seal_blind_box", seal)@@ -175,8 +184,6 @@ def test_rest_requests_and_grants_routes(monkeypatch):grant_response = client.post("/api/vault/grants",json={- "scope_type": "secret",- "scope_ref": "PROTECTED_REST","session_id": "ses_1","request_id": req["id"],"deks": [@@ -255,8 +262,8 @@ def test_rest_grant_rejects_mismatched_request(monkeypatch):response = client.post("/api/vault/grants",json={- "scope_type": "secret",- "scope_ref": "B_KEY",+ "member_names": ["B_KEY"],+ "source_selector": {"env": ["B_KEY"]},"session_id": "ses_1","request_id": req["id"],"deks": [diff --git a/tests/test_vault_schema.py b/tests/test_vault_schema.pyindex 662223c57..e1a15540b 100644--- a/tests/test_vault_schema.py+++ b/tests/test_vault_schema.py@@ -1,30 +1,39 @@-"""Migration smoke test: the vault tables exist and the default group is seeded-after the standard state-init path. Relies on the autouse ``VIBE_REMOTE_HOME``-isolation in conftest, so this builds a fresh DB under tmp — never the real home.-"""-from __future__ import annotations-import sqlite3+from sqlalchemy import text++from storage.db import create_sqlite_engine+from storage.models import metadata+-from config import paths-from storage.importer import ensure_sqlite_state+_VAULT_TABLES = ("vault_secrets", "vault_requests", "vault_grants", "vault_audit")-_VAULT_TABLES = ("vault_groups", "vault_secrets", "vault_links", "vault_requests", "vault_grants", "vault_audit")+def test_vault_metadata_schema_matches_grant_id_tag_model(tmp_path):+ engine = create_sqlite_engine(tmp_path / "vault_schema.sqlite")+ metadata.create_all(engine)-def test_vault_tables_created_and_default_group_seeded():- ensure_sqlite_state(primary_platform=None)- conn = sqlite3.connect(paths.get_sqlite_state_path())- try:- tables = {row[0] for row in conn.execute("select name from sqlite_master where type='table'")}- for table in _VAULT_TABLES:- assert table in tables, f"missing vault table: {table}"+ with engine.connect() as conn:+ tables = {row[0] for row in conn.execute(text("select name from sqlite_master where type='table'"))}+ assert set(_VAULT_TABLES) <= tables+ assert "vault_groups" not in tables+ assert "vault_links" not in tables- secret_cols = {row[1] for row in conn.execute('pragma table_info("vault_secrets")')}- assert {"name", "group_name", "kind", "protection", "ciphertext", "nonce", "wrap_meta"} <= secret_cols+ secret_cols = {row[1] for row in conn.execute(text("pragma table_info(vault_secrets)"))}+ assert {"name", "tags", "kind", "protection", "ciphertext", "nonce", "wrap_meta"} <= secret_cols+ assert "group_name" not in secret_cols- groups = {row[0]: row[1] for row in conn.execute("select name, grantable from vault_groups")}- assert groups.get("default") == 1- finally:- conn.close()+ grant_cols = {row[1] for row in conn.execute(text("pragma table_info(vault_grants)"))}+ assert {+ "id",+ "member_snapshot",+ "source_selector",+ "request_id",+ "session_id",+ "purpose",+ "one_shot",+ "expires_at",+ "agent_ready_at",+ } <= grant_cols+ assert "scope_type" not in grant_cols+ assert "scope_ref" not in grant_colsdiff --git a/tests/test_vault_service.py b/tests/test_vault_service.pyindex 8f4bb12e7..a27099a91 100644--- a/tests/test_vault_service.py+++ b/tests/test_vault_service.py@@ -1,8 +1,4 @@-"""Unit tests for storage/vault_service.py.--The data layer stores avault-produced envelopes and masked metadata only. It never-sees plaintext, machine keys, or Python crypto.-"""+"""Unit tests for the Vaults service final grant-id/tag model."""from __future__ import annotations@@ -14,12 +10,13 @@ from sqlalchemy import selectfrom storage import vault_service as vsfrom storage.db import create_sqlite_engine-from storage.models import metadata, vault_audit, vault_grants, vault_groups, vault_links, vault_requests, vault_secrets+from storage.models import metadata, vault_grants, vault_requests, vault_secretsfrom storage.vault_crypto import Sealed@pytest.fixturedef vault(tmp_path):+ vs.GRANT_RUNTIME_CACHE.clear()engine = create_sqlite_engine(tmp_path / "vault_test.sqlite")metadata.create_all(engine)return engine@@ -29,2279 +26,311 @@ def _sealed(suffix: str = "1") -> Sealed:return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")-PROTECTED_SIGNING_PUBLIC_META = {- "signing_public_key": {- "curve": "secp256k1",- "public_key": "02" + "cd" * 32,- }-}--def _create(engine, **kw):with engine.begin() as conn:- return vs.create_secret(conn, sealed=_sealed(), **kw)---def _access_request(conn, name: str, *, session_id: str = "ses_1", skill: str | None = None) -> dict:- payload = {"session_id": session_id}- if skill:- payload["skill"] = skill- return vs.create_access_request(conn, name, requester=payload, delivery=payload)---def _row(engine, name: str) -> dict:- with engine.connect() as conn:- return dict(conn.execute(select(vault_secrets).where(vault_secrets.c.name == name)).mappings().one())+ return vs.create_secret(conn, sealed=_sealed(kw.get("name", "x").lower()), **kw)+++def _grant_from_request(conn, request: dict, *, cache_ready: bool = True, ttl_seconds: int | None = None) -> dict:+ option = request["card"]["grant_options"][0]+ return vs.create_grant(+ conn,+ member_names=option["member_snapshot"],+ source_selector=option["source_selector"],+ purpose=option["purpose"],+ request_id=request["id"],+ ttl_seconds=ttl_seconds,+ cache_ready=cache_ready,+ )-def test_create_stores_envelope_and_value_free_meta(vault):- meta = _create(- vault,- name="OPENAI_API_KEY",- description="key",- policy={"allowed_hosts": ["api.example.com"]},- )+def test_secret_metadata_is_global_name_plus_tags(vault):+ meta = _create(vault, name="OPENAI_API_KEY", description="key", tags=["prod", "skill:deploy"])assert meta["name"] == "OPENAI_API_KEY"- assert meta["protection"] == "standard"- assert meta["group"] == "default"+ assert meta["tags"] == ["prod", "skill:deploy"]+ assert "group" not in metaassert "preview" not in meta- assert meta["policy"] == {"allowed_hosts": ["api.example.com"]}- assert "plaintext" not in json.dumps(meta)- row = _row(vault, "OPENAI_API_KEY")- assert row["ciphertext"] == "ct-1"- assert row["nonce"] == "n-1"- assert row["wrap_meta"] == "wm-1"- assert json.loads(row["public_meta"]) == {"description": "key"}---def test_create_persists_no_value_derived_public_meta(vault):- secret_value = "sk-ant-abcd1234"- value_tail = secret_value[-4:]- _create(vault, name="NO_PREVIEW_KEY")-- row = _row(vault, "NO_PREVIEW_KEY")- assert row["public_meta"] is Nonewith vault.connect() as conn:- meta = vs.get_secret_meta(conn, "NO_PREVIEW_KEY")- listed = vs.list_secrets(conn)+ row = conn.execute(select(vault_secrets).where(vault_secrets.c.name == "OPENAI_API_KEY")).mappings().one()+ assert row["ciphertext"] == "ct-openai_api_key"+ assert json.loads(row["public_meta"]) == {"description": "key"}+ assert vs.list_secrets(conn, tag="prod")[0]["name"] == "OPENAI_API_KEY"- assert "preview" not in meta- assert "preview" not in json.dumps(listed)- assert value_tail not in json.dumps(meta)- assert value_tail not in json.dumps(listed)+def test_skill_links_are_stored_as_skill_tags(vault):+ _create(vault, name="GH_PAT", tags=["github"])-def test_standard_static_secret_is_agent_access_grantable(vault):- _create(vault, name="STANDARD_KEY", protection="standard", group="default")- with vault.begin() as conn:- resolved = vs.resolve_secret_access(conn, "STANDARD_KEY", session_id="ses_1")- request = vs.create_access_request(conn, "STANDARD_KEY", requester={"session_id": "ses_1"})- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="STANDARD_KEY",- session_id="ses_1",- created_by_request_id=request["id"],- )- listed = vs.list_secrets(conn)-- assert listed[0]["access_grantable"] is True- assert listed[0]["per_use_sign"] is False- assert request["status"] == "pending"- assert request["card"]["scope_options"][0]["scope_ref"] == "STANDARD_KEY"- assert grant["delivery_ready"] is True- assert grant["delivery_status"] == "standard_ready"with vault.begin() as conn:- row = conn.execute(select(vault_grants).where(vault_grants.c.id == grant["id"])).mappings().one()- release_scopes = vs.agent_release_scopes_after_rows(conn, [dict(row)])- assert int(row["agent_ready"] or 0) == 0- assert release_scopes == []- assert resolved["status"] == "standard"- assert resolved["envelope"] == _sealed()-+ vs.link_secret_to_skills(conn, "GH_PAT", ["github-release", "github-release"])+ meta = vs.get_secret_meta(conn, "GH_PAT")-def test_inactive_standard_grants_are_not_delivery_ready(vault):- _create(vault, name="STANDARD_KEY", protection="standard", group="default")- with vault.begin() as conn:- request = vs.create_access_request(conn, "STANDARD_KEY", requester={"session_id": "ses_1"})- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="STANDARD_KEY",- session_id="ses_1",- created_by_request_id=request["id"],- )- revoked = vs.revoke_grant(conn, grant["id"])+ assert meta["tags"] == ["github", "skill:github-release"]- assert revoked["status"] == "revoked"- assert revoked["delivery_ready"] is False- assert revoked["delivery_status"] == "agent_cache_unverified"+def test_selector_expansion_unions_env_tags_and_skills(vault):+ _create(vault, name="A_KEY", protection="protected", tags=["deploy"])+ _create(vault, name="B_KEY", protection="standard", tags=["deploy", "skill:release"])+ _create(vault, name="C_KEY", protection="standard", tags=["other"])-def test_expired_standard_grants_are_not_delivery_ready(vault):- _create(vault, name="STANDARD_KEY", protection="standard", group="default")with vault.begin() as conn:- request = vs.create_access_request(conn, "STANDARD_KEY", requester={"session_id": "ses_1"})- grant = vs.create_grant(+ expanded = vs.expand_value_delivery_selector(conn,- scope_type="secret",- scope_ref="STANDARD_KEY",- session_id="ses_1",- created_by_request_id=request["id"],+ env=["LOCAL_C=C_KEY"],+ tags=["deploy"],+ skills=["release"],)- expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()- conn.execute(vault_grants.update().where(vault_grants.c.id == grant["id"]).values(expires_at=expired_at))- payload = vs.get_grant_created_by_request(conn, request["id"])-- assert payload is not None- assert payload["status"] == "active"- assert payload["delivery_ready"] is False- assert payload["delivery_status"] == "agent_cache_unverified"---def test_deny_request_marks_pending_denied_and_audits(vault):- _create(vault, name="STANDARD_KEY", protection="standard")- with vault.begin() as conn:- request = vs.create_access_request(conn, "STANDARD_KEY", requester={"session_id": "ses_1"})- denied = vs.deny_request(conn, request["id"], requester={"source": "gatekeeper"}, reason="no")- event = conn.execute(- select(vault_audit).where(vault_audit.c.request_id == request["id"], vault_audit.c.event == "request-denied")- ).mappings().one()-- assert denied["status"] == "denied"- assert denied["decided_at"] is not None- assert json.loads(event["delivery"]) == {"request_type": "access", "reason": "no"}--def test_deny_request_rejects_non_pending(vault):- _create(vault, name="STANDARD_KEY", protection="standard")- with vault.begin() as conn:- request = vs.create_access_request(conn, "STANDARD_KEY")- vs.deny_request(conn, request["id"])- with pytest.raises(vs.InvalidRequestError):- vs.deny_request(conn, request["id"])---def test_deny_request_expires_timed_out_request_before_denial(vault):- _create(vault, name="STANDARD_KEY", protection="standard")- expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()- with vault.begin() as conn:- request = vs.create_access_request(conn, "STANDARD_KEY", requester={"session_id": "ses_1"}, expires_at=expired_at)- with pytest.raises(vs.InvalidRequestError, match="expired"):- vs.deny_request(conn, request["id"], requester={"source": "gatekeeper"}, reason="late")- row = conn.execute(select(vault_requests).where(vault_requests.c.id == request["id"])).mappings().one()- events = [- item["event"]- for item in conn.execute(select(vault_audit.c.event).where(vault_audit.c.request_id == request["id"])).mappings()- ]-- assert row["status"] == "expired"- assert "request-expired" in events- assert "request-denied" not in events---def test_pubkey_pin_metadata_round_trips_through_masked_meta(vault):- _create(vault, name="ETH_KEY", protection="protected", kind="keypair", signer_kind="local")- pin = {- "public_key": "02" + "ab" * 32,- "fingerprint": "fp_123",- "attested_at": "2026-06-26T00:00:00Z",- "attestation": {"source": "avault"},- "ignored": "nope",- }-- with vault.begin() as conn:- stored = vs.store_pubkey_pin(conn, "ETH_KEY", pin)- listed = vs.list_secrets(conn)-- assert stored["avault_pubkey_pin"] == {- "public_key": pin["public_key"],- "fingerprint": "fp_123",- "attested_at": "2026-06-26T00:00:00Z",- "attestation": {"source": "avault"},- }- listed_meta = next(item for item in listed if item["name"] == "ETH_KEY")- assert listed_meta["avault_pubkey_pin"]["fingerprint"] == "fp_123"- assert "ignored" not in listed_meta["avault_pubkey_pin"]---def test_keypair_signing_public_key_surfaces_in_masked_meta(vault):- public_key = "02" + "cd" * 32- _create(- vault,- name="ETH_KEY",- kind="keypair",- signer_kind="local",- public_meta={- "signing_public_key": {- "curve": "secp256k1",- "public_key": public_key,- "ignored": "nope",- }- },- )+ assert expanded["source_selector"] == {"env": ["LOCAL_C=C_KEY"], "tags": ["deploy", "skill:release"]}+ assert expanded["secrets"] == [+ {"name": "C_KEY", "env": "LOCAL_C", "kind": "static", "protection": "standard"},+ {"name": "A_KEY", "env": "A_KEY", "kind": "static", "protection": "protected"},+ {"name": "B_KEY", "env": "B_KEY", "kind": "static", "protection": "standard"},+ ]- with vault.connect() as conn:- meta = vs.get_secret_meta(conn, "ETH_KEY")- listed = vs.list_secrets(conn)-- assert meta["signing_public_key"] == {"curve": "secp256k1", "public_key": public_key}- listed_meta = next(item for item in listed if item["name"] == "ETH_KEY")- assert listed_meta["signing_public_key"] == {"curve": "secp256k1", "public_key": public_key}- assert "ignored" not in listed_meta["signing_public_key"]---def test_protected_keypair_requires_signing_public_key_for_per_use_sign(vault):- _create(- vault,- name="UNPINNED_KEY",- kind="keypair",- protection="protected",- signer_kind="local",- )- with vault.connect() as conn:- meta = vs.get_secret_meta(conn, "UNPINNED_KEY")- listed = vs.list_secrets(conn)- listed_meta = next(item for item in listed if item["name"] == "UNPINNED_KEY")+def test_selector_rejects_env_conflicts_and_keypairs(vault):+ _create(vault, name="A_KEY", tags=["deploy"])+ _create(vault, name="SIGNING_KEY", kind="keypair", signer_kind="local", tags=["deploy"])- assert meta["per_use_sign"] is False- assert listed_meta["per_use_sign"] is False- assert "signing_public_key" not in metawith vault.begin() as conn:with pytest.raises(vs.InvalidRequestError):- vs.create_sign_request(conn, "UNPINNED_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")---def test_protected_keypair_with_signing_public_key_is_per_use_signable(vault):- public_key = "02" + "cd" * 32- _create(- vault,- name="PINNED_KEY",- kind="keypair",- protection="protected",- signer_kind="local",- public_meta={"signing_public_key": {"curve": "secp256k1", "public_key": public_key}},- )-- with vault.connect() as conn:- meta = vs.get_secret_meta(conn, "PINNED_KEY")-- assert meta["per_use_sign"] is True---def test_pubkey_pin_does_not_change_secret_version(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- before = dict(conn.execute(select(vault_secrets).where(vault_secrets.c.name == "A_KEY")).mappings().one())- vs.store_pubkey_pin(conn, "A_KEY", {"public_key": "02" + "ab" * 32, "fingerprint": "fp_123"})- after = dict(conn.execute(select(vault_secrets).where(vault_secrets.c.name == "A_KEY")).mappings().one())- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- )-- assert before["updated_at"] == after["updated_at"]- assert grant["member_snapshot"] == ["A_KEY"]---def test_get_envelope_and_get_envelopes_return_stored_envelopes(vault):- _create(vault, name="A_KEY")- with vault.begin() as conn:- vs.create_secret(conn, name="B_KEY", sealed=_sealed("2"))- with vault.connect() as conn:- assert vs.get_envelope(conn, "A_KEY") == _sealed()- assert vs.get_envelopes(conn, ["B_KEY", "A_KEY"]) == {- "B_KEY": _sealed("2"),- "A_KEY": _sealed(),- }---def test_get_envelopes_validates_batch_before_returning(vault):- _create(vault, name="A_KEY")- with vault.connect() as conn, pytest.raises(vs.SecretNotFoundError):- vs.get_envelopes(conn, ["A_KEY", "NOPE"])---def test_keypair_is_not_value_deliverable(vault):- _create(vault, name="ETH_KEY", kind="keypair", signer_kind="local")- with vault.connect() as conn:- with pytest.raises(vs.KeypairNotValueDeliverableError):- vs.get_envelope(conn, "ETH_KEY")+ vs.expand_value_delivery_selector(conn, env=["ONE=A_KEY", "TWO=A_KEY"])with pytest.raises(vs.KeypairNotValueDeliverableError):- vs.get_envelopes(conn, ["ETH_KEY"])- with pytest.raises(vs.KeypairNotValueDeliverableError):- vs.resolve_secret_access(conn, "ETH_KEY")- assert vs.get_key_envelope(conn, "ETH_KEY") == _sealed()---def test_record_deliveries_bumps_usage_and_audits(vault):- _create(vault, name="DB_URL")- with vault.begin() as conn:- assert vs.get_secret_meta(conn, "DB_URL")["use_count"] == 0- vs.record_deliveries(conn, ["DB_URL"], requester={"agent": "claude"}, mode="run")- with vault.connect() as conn:- meta = vs.get_secret_meta(conn, "DB_URL")- rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]- assert meta["use_count"] == 1- assert meta["last_used_at"] is not None- assert "delivered" in {r["event"] for r in rows}---def test_record_proxy_use_bumps_usage_and_audits(vault):- _create(vault, name="GH_PAT")- with vault.begin() as conn:- vs.record_proxy_use(conn, "GH_PAT", requester={"source": "cli"}, delivery={"status": 200})- with vault.connect() as conn:- meta = vs.get_secret_meta(conn, "GH_PAT")- rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]- assert meta["use_count"] == 1- assert meta["last_used_at"] is not None- assert "proxied" in {r["event"] for r in rows}---def test_list_secrets_masked_and_group_filtered(vault):- _create(vault, name="A_KEY", group="default")- _create(vault, name="B_KEY", group="crypto")- _create(vault, name="C_KEY", group="crypto")- with vault.connect() as conn:- all_names = [m["name"] for m in vs.list_secrets(conn)]- crypto_names = [m["name"] for m in vs.list_secrets(conn, group="crypto")]- assert all_names == ["A_KEY", "B_KEY", "C_KEY"]- assert crypto_names == ["B_KEY", "C_KEY"]---def test_duplicate_name_rejected(vault):- _create(vault, name="DUP")- with pytest.raises(vs.SecretExistsError):- _create(vault, name="DUP")---def test_invalid_name_rejected(vault):- with pytest.raises(vs.InvalidSecretNameError):- _create(vault, name="lower_case")---def test_create_protected_stores_browser_envelope_without_decrypting(vault):- meta = _create(vault, name="SECRET", protection="protected")-- assert meta["protection"] == "protected"- with vault.connect() as conn:- row = _row(vault, "SECRET")- assert row["ciphertext"] == "ct-1"- assert row["nonce"] == "n-1"- assert row["wrap_meta"] == "wm-1"- with pytest.raises(vs.UnsupportedProtectionError):- vs.get_envelope(conn, "SECRET")---def test_rotate_changes_envelope_and_strips_legacy_preview(vault):- _create(vault, name="ROT", description="rotating")- with vault.begin() as conn:- conn.execute(- vault_secrets.update()- .where(vault_secrets.c.name == "ROT")- .values(public_meta=json.dumps({"description": "rotating", "preview": "…9999"}))- )- with vault.begin() as conn:- meta = vs.rotate_secret(conn, "ROT", _sealed("new"))- assert "preview" not in meta- assert meta["description"] == "rotating"- with vault.connect() as conn:- assert vs.get_envelope(conn, "ROT") == _sealed("new")- row = _row(vault, "ROT")- assert json.loads(row["public_meta"]) == {"description": "rotating"}---def test_delete_removes_secret(vault):- _create(vault, name="GONE")- with vault.begin() as conn:- vs.delete_secret(conn, "GONE")- with vault.connect() as conn, pytest.raises(vs.SecretNotFoundError):- vs.get_secret_meta(conn, "GONE")---def test_audit_records_events_without_values(vault):- _create(vault, name="AUD")- with vault.begin() as conn:- vs.record_deliveries(conn, ["AUD"], requester={"agent": "claude"}, mode="run")- vs.delete_secret(conn, "AUD")- rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]- events = {r["event"] for r in rows}- assert {"created", "delivered", "deleted"} <= events- assert all("topsecretvalue42" not in json.dumps(r) for r in rows)---def test_create_auto_creates_missing_group(vault):- meta = _create(vault, name="NEW_GROUP_KEY", group="brandnew")- assert meta["group"] == "brandnew"- with vault.connect() as conn:- from storage.models import vault_groups-- groups = {r[0] for r in conn.execute(vault_groups.select().with_only_columns(vault_groups.c.name))}- assert "brandnew" in groups+ vs.expand_value_delivery_selector(conn, tags=["deploy"])-def test_create_fulfills_pending_provision_request(vault):- with vault.begin() as conn:- req = vs.create_provision_request(conn, "ASKED_KEY", requester={"agent": "claude"})- _create(vault, name="ASKED_KEY")- with vault.connect() as conn:- status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == req["id"])).scalar_one()- assert status == "fulfilled"+def test_access_request_for_tag_selector_freezes_protected_subset_only(vault):+ _create(vault, name="PROTECTED_A", protection="protected", tags=["deploy"])+ _create(vault, name="STANDARD_B", protection="standard", tags=["deploy"])--def test_request_specific_create_uses_target_spec_and_fulfills_sibling_requests(vault):with vault.begin() as conn:- old_req = vs.create_provision_request(conn, "ASKED_KEY", spec={"group": "old"})- new_req = vs.create_provision_request(conn, "ASKED_KEY", spec={"group": "new"})- meta = vs.create_secret(+ expanded = vs.expand_value_delivery_selector(conn, tags=["deploy"])+ request = vs.create_access_request(conn,- name="ASKED_KEY",- sealed=_sealed("new"),- group="new",- provision_request_id=new_req["id"],+ source_selector=expanded["source_selector"],+ purpose="run",+ requester={"session_id": "ses_1"},+ delivery={"session_id": "ses_1", "command": "python deploy.py"},)+ card = request["card"]- assert meta["group"] == "new"- with vault.connect() as conn:- rows = {- row["id"]: row["status"]- for row in conn.execute(- select(vault_requests.c.id, vault_requests.c.status).where(- vault_requests.c.id.in_([old_req["id"], new_req["id"]])- )- ).mappings()- }- assert rows == {old_req["id"]: "fulfilled", new_req["id"]: "fulfilled"}-+ assert card["source_selector"] == {"tags": ["deploy"]}+ assert card["protected_secret_names"] == ["PROTECTED_A"]+ assert card["grant_options"][0]["grant_id"].startswith("vgr_")+ assert card["grant_options"][0]["member_snapshot"] == ["PROTECTED_A"]+ assert "STANDARD_B" not in json.dumps(card["grant_options"])-def test_request_specific_create_treats_fulfilled_replay_as_existing(vault):- with vault.begin() as conn:- req = vs.create_provision_request(conn, "ASKED_KEY")- vs.create_secret(conn, name="ASKED_KEY", sealed=_sealed("first"), provision_request_id=req["id"])- with pytest.raises(vs.SecretExistsError):- vs.create_secret(conn, name="ASKED_KEY", sealed=_sealed("second"), provision_request_id=req["id"])---def test_fulfilled_replay_leaves_cleanup_to_rest_conflict_handler(vault):- with vault.begin() as conn:- req = vs.create_provision_request(conn, "ASKED_KEY")- vs.create_secret(conn, name="ASKED_KEY", sealed=_sealed("first"), provision_request_id=req["id"])- stale = vs.create_provision_request(conn, "ASKED_KEY")- conn.execute(vault_requests.update().where(vault_requests.c.id == stale["id"]).values(status="pending"))- with pytest.raises(vs.SecretExistsError):- vs.create_secret(conn, name="ASKED_KEY", sealed=_sealed("second"), provision_request_id=req["id"])+def test_tag_edits_do_not_mutate_existing_grant_snapshot(vault):+ _create(vault, name="A_KEY", protection="protected", tags=["deploy"])- stale_status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == stale["id"])).scalar_one()-- assert stale_status == "pending"---def test_request_specific_create_rejects_mismatched_provision_name(vault):- with vault.begin() as conn:- req = vs.create_provision_request(conn, "OTHER_KEY")- with pytest.raises(vs.InvalidRequestError, match="provision request secret name does not match"):- vs.create_secret(- conn,- name="ASKED_KEY",- sealed=_sealed("asked"),- provision_request_id=req["id"],- )---def test_request_for_existing_secret_is_born_fulfilled(vault):- _create(vault, name="ALREADY")with vault.begin() as conn:- req = vs.create_provision_request(conn, "ALREADY")- assert req["status"] == "fulfilled"+ req = vs.create_access_request(conn, "A_KEY", requester={"session_id": "ses_1"}, delivery={"session_id": "ses_1"})+ grant = _grant_from_request(conn, req)+ vs.create_secret(conn, name="B_KEY", protection="protected", sealed=_sealed("b"), tags=["deploy"])+ vs.update_secret_tags(conn, "B_KEY", ["deploy", "new-tag"])+ row = conn.execute(select(vault_grants).where(vault_grants.c.id == grant["id"])).mappings().one()+ assert json.loads(row["member_snapshot"]) == ["A_KEY"]+ assert grant["member_snapshot"] == ["A_KEY"]-def test_provision_request_and_fulfill(vault):- with vault.begin() as conn:- req = vs.create_provision_request(conn, "NEW_KEY", reason="sync needs it", requester={"agent": "claude"})- assert req["status"] == "pending"- with vault.begin() as conn:- meta = vs.fulfill_provision(conn, req["id"], _sealed("filled"), description="filled")- assert "preview" not in meta- assert meta["description"] == "filled"- with vault.connect() as conn:- assert vs.get_envelope(conn, "NEW_KEY") == _sealed("filled")- status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == req["id"])).scalar_one()- assert status == "fulfilled"+def test_create_grant_stores_final_fields_and_readiness_by_grant_id(vault):+ _create(vault, name="A_KEY", protection="protected", tags=["deploy"])-def test_provision_request_carries_secure_input_card_without_value(vault):with vault.begin() as conn:- req = vs.create_provision_request(+ req = vs.create_access_request(conn,- "NEW_CARD_KEY",- reason="deploy",- spec={- "kind": "static",- "protection": "protected",- "group": "github",- "description": "GitHub token",- "tags": ["github", "deploy"],- "policy": {"allowed_hosts": ["api.github.com"], "auth": {"type": "bearer"}},- "links": {"skills": ["release"]},- },+ source_selector={"tags": ["deploy"]},+ purpose="inject",+ requester={"session_id": "ses_1"},+ delivery={"session_id": "ses_1"},)- assert req["card"]["card_type"] == "secure_input"- assert req["card"]["secret_name"] == "NEW_CARD_KEY"- assert req["card"]["value"] is None- assert req["card"]["spec"]["group"] == "github"- assert req["card"]["spec"]["links"] == {"skills": ["release"]}- with vault.connect() as conn:- listed = vs.list_requests(conn)- assert listed[0]["card"]["default_protection"] == "protected"- assert listed[0]["card"]["spec"]["policy"]["allowed_hosts"] == ["api.github.com"]- assert "secret-value" not in json.dumps(listed)---def test_provision_request_spec_normalizes_allowed_hosts(vault):- with vault.begin() as conn:- req = vs.create_provision_request(+ grant = _grant_from_request(conn, req)+ ready = vs.mark_grant_agent_ready(conn, grant["id"], ttl_seconds=300)+ release_refs = vs.agent_release_scopes_after_rows(conn,- "HOST_KEY",- spec={"policy": {"allowed_hosts": ["https://api.github.com/v1", "api.github.com:443", ".Example.com"]}},- )-- assert req["card"]["spec"]["policy"]["allowed_hosts"] == ["api.github.com", ".example.com"]---def test_provision_request_spec_rejects_secret_material(vault):- with vault.begin() as conn:- with pytest.raises(vs.VaultServiceError):- vs.create_provision_request(conn, "BAD_CARD_KEY", spec={"policy": {"value": "secret"}})---def test_provision_request_spec_rejects_object_valued_scalar_fields(vault):- with vault.begin() as conn:- with pytest.raises(vs.VaultServiceError, match="spec.description must be a string"):- vs.create_provision_request(conn, "BAD_DESC_KEY", spec={"description": {"text": "not allowed"}})- with pytest.raises(vs.VaultServiceError, match="spec.policy.auth.name must be a string"):- vs.create_provision_request(- conn,- "BAD_AUTH_KEY",- spec={"policy": {"auth": {"type": "header", "name": {"header": "X-Api-Key"}}}},- )---def test_get_pending_provision_request_resolves_by_request_id(vault):- with vault.begin() as conn:- conn.execute(- vault_requests.insert(),- [- {- "id": "vrq_old",- "request_type": "provision",- "secret_name": "DUP_KEY",- "requester": None,- "delivery": json.dumps({"card": vs._secure_input_card("DUP_KEY", request_id="vrq_old", spec={"group": "old"})}),- "status": "pending",- "message_id": None,- "created_at": "2026-01-01T00:00:00+00:00",- },- {- "id": "vrq_new",- "request_type": "provision",- "secret_name": "DUP_KEY",- "requester": None,- "delivery": json.dumps({"card": vs._secure_input_card("DUP_KEY", request_id="vrq_new", spec={"group": "new"})}),- "status": "pending",- "message_id": None,- "created_at": "2026-01-01T00:00:01+00:00",- },- ],+ [dict(conn.execute(select(vault_grants).where(vault_grants.c.id == grant["id"])).mappings().one())],)- with vault.begin() as conn:- old_lookup = vs.get_pending_provision_request(conn, "vrq_old")- ambiguous_by_name = vs.find_pending_provision_request(conn, "DUP_KEY")+ assert ready["source_selector"] == {"tags": ["deploy"]}+ assert ready["id"] == req["card"]["grant_options"][0]["grant_id"]+ assert ready["purpose"] == "inject"+ assert ready["request_id"] == req["id"]+ assert ready["delivery_ready"] is True+ assert release_refs == [{"grant_id": grant["id"]}]- assert old_lookup["id"] == "vrq_old"- assert old_lookup["card"]["spec"]["group"] == "old"- assert ambiguous_by_name is None+def test_create_grant_caps_ttl_to_approval_options(vault):+ _create(vault, name="A_KEY", protection="protected", tags=["deploy"])-def test_create_secret_can_link_to_requested_skill(vault):- _create(vault, name="LINKED_KEY")with vault.begin() as conn:- vs.link_secret_to_skills(conn, "LINKED_KEY", ["release"])- with vault.connect() as conn:- rows = conn.execute(select(vault_links.c.skill_name).where(vault_links.c.secret_name == "LINKED_KEY")).scalars().all()- assert rows == ["release"]-+ req = vs.create_access_request(conn, source_selector={"tags": ["deploy"]})+ grant = _grant_from_request(conn, req, ttl_seconds=86_400)-def test_create_grant_freezes_scope_members_and_keeps_key_material_out_of_python(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- _create(vault, name="B_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- ttl_seconds=900,- created_by_request_id=req["id"],- cache=cache,- )+ created = datetime.fromisoformat(grant["created_at"])+ expires = datetime.fromisoformat(grant["expires_at"])+ assert expires - created == timedelta(seconds=3600)- assert grant["scope_type"] == "group"- assert grant["member_snapshot"] == ["A_KEY", "B_KEY"]- assert grant["runtime_member_count"] == 2- assert cache.get(grant["id"], "A_KEY") is None- with vault.connect() as conn:- row = dict(conn.execute(select(vault_grants).where(vault_grants.c.id == grant["id"])).mappings().one())- assert "dek-a" not in json.dumps(row)- assert json.loads(row["member_snapshot"]) == ["A_KEY", "B_KEY"]+def test_sibling_approval_requires_matching_purpose(vault):+ _create(vault, name="A_KEY", protection="protected", tags=["deploy"])-def test_find_active_grant_for_secrets_chooses_covering_scope(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- _create(vault, name="B_KEY", protection="protected", group="crypto")with vault.begin() as conn:- req_a = _access_request(conn, "A_KEY", session_id="ses_1")- secret_grant = vs.create_grant(+ run_req = vs.create_access_request(conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req_a["id"],+ source_selector={"tags": ["deploy"]},+ purpose="run",+ requester={"session_id": "ses_1"},+ delivery={"session_id": "ses_1"},)- req_group = _access_request(conn, "A_KEY", session_id="ses_1")- group_grant = vs.create_grant(+ fetch_req = vs.create_access_request(conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req_group["id"],+ source_selector={"tags": ["deploy"]},+ purpose="fetch",+ requester={"session_id": "ses_1"},+ delivery={"session_id": "ses_1"},)+ _grant_from_request(conn, run_req)+ fetch_row = conn.execute(select(vault_requests).where(vault_requests.c.id == fetch_req["id"])).mappings().one()- selected = vs.find_active_grant_for_secrets(conn, ["A_KEY", "B_KEY"], session_id="ses_1")+ assert fetch_row["status"] == "pending"- assert selected is not None- assert selected["id"] == group_grant["id"]- assert selected["id"] != secret_grant["id"]+def test_secret_delete_rotate_and_classification_changes_expire_covering_grants(vault):+ _create(vault, name="A_KEY", protection="protected")+ _create(vault, name="B_KEY", protection="protected")+ _create(vault, name="C_KEY", protection="protected")-def test_group_grant_approves_sibling_requests_in_same_session(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- _create(vault, name="B_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()with vault.begin() as conn:- req_a = _access_request(conn, "A_KEY", session_id="ses_1")- req_b = _access_request(conn, "B_KEY", session_id="ses_1")- req_other = _access_request(conn, "B_KEY", session_id="ses_2")- grant = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req_a["id"],- cache=cache,- )+ grant_a = _grant_from_request(conn, vs.create_access_request(conn, "A_KEY"))+ grant_b = _grant_from_request(conn, vs.create_access_request(conn, "B_KEY"))+ grant_c = _grant_from_request(conn, vs.create_access_request(conn, "C_KEY"))+ vs.rotate_secret(conn, "A_KEY", _sealed("rotated"))+ vs.delete_secret(conn, "B_KEY")+ vs.update_secret_classification(conn, "C_KEY", protection="standard")statuses = {row["id"]: row["status"]- for row in conn.execute(- select(vault_requests.c.id, vault_requests.c.status).where(- vault_requests.c.id.in_([req_a["id"], req_b["id"], req_other["id"]])- )- ).mappings()+ for row in conn.execute(select(vault_grants).where(vault_grants.c.id.in_([grant_a["id"], grant_b["id"], grant_c["id"]]))).mappings()}- assert grant["member_snapshot"] == ["A_KEY", "B_KEY"]- assert statuses == {- req_a["id"]: "approved",- req_b["id"]: "approved",- req_other["id"]: "pending",- }---def test_group_grant_expires_stale_sibling_requests(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- _create(vault, name="B_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()- expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()- with vault.begin() as conn:- req_a = _access_request(conn, "A_KEY", session_id="ses_1")- req_b = vs.create_access_request(- conn,- "B_KEY",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- expires_at=expired_at,- )- vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req_a["id"],- cache=cache,- )- statuses = {- row["id"]: row["status"]- for row in conn.execute(- select(vault_requests.c.id, vault_requests.c.status).where(- vault_requests.c.id.in_([req_a["id"], req_b["id"]])- )- ).mappings()- }+ assert statuses == {grant_a["id"]: "expired", grant_b["id"]: "expired", grant_c["id"]: "expired"}- assert statuses == {- req_a["id"]: "approved",- req_b["id"]: "expired",- }+def test_standard_secret_does_not_create_access_request_unless_always_ask(vault):+ _create(vault, name="STANDARD_KEY", protection="standard")+ _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})-def test_grant_uses_approval_member_snapshot_not_later_group_members(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- vs.create_secret(conn, name="B_KEY", protection="protected", group="crypto", sealed=_sealed("b"))- grant = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,- )+ assert vs.resolve_secret_access(conn, "STANDARD_KEY")["status"] == "standard"+ with pytest.raises(vs.NotGrantableError):+ vs.create_access_request(conn, "STANDARD_KEY")+ req = vs.create_access_request(conn, "ASK_KEY", requester={"session_id": "ses_1"}, delivery={"session_id": "ses_1"})+ grant = _grant_from_request(conn, req)+ reserved = vs.find_active_grant_for_secret(conn, "ASK_KEY", session_id="ses_1", reserve_one_shot=True)- assert grant["member_snapshot"] == ["A_KEY"]- assert grant["runtime_member_count"] == 1- assert cache.has(grant["id"], "A_KEY")- assert not cache.has(grant["id"], "B_KEY")+ assert req["card"]["one_shot"] is True+ assert grant["one_shot"] is True+ assert reserved["status"] == "reserved"-def test_reusing_approval_request_does_not_create_second_grant(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- first = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,- )- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,- )- grants = list(conn.execute(select(vault_grants)).mappings())-- assert [row["id"] for row in grants] == [first["id"]]- assert cache.has(first["id"], "A_KEY")- assert cache.get(first["id"], "A_KEY") is None---def test_find_active_grant_uses_persisted_readiness_across_process_cache(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()+def test_multi_member_one_shot_grant_is_consumed_once(vault):+ _create(vault, name="ASK_KEY", protection="standard", tags=["deploy"], policy={"always_ask": True})+ _create(vault, name="PROTECTED_KEY", protection="protected", tags=["deploy"])+with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(+ req = vs.create_access_request(conn, source_selector={"tags": ["deploy"]}, requester={"session_id": "ses_1"})+ grant = _grant_from_request(conn, req)+ reserved = vs.find_active_grant_for_secret(conn,- scope_type="secret",- scope_ref="A_KEY",+ "ASK_KEY",session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,+ reserve_one_shot=True,)- process_cache = vs.VaultGrantRuntimeCache()- active = vs.find_active_grant_for_secret(conn, "A_KEY", session_id="ses_1", cache=process_cache)- listed = vs.list_grants(conn, cache=process_cache)- assert active is not None- assert active["id"] == grant["id"]- assert listed[0]["id"] == grant["id"]- assert listed[0]["delivery_ready"] is True- assert listed[0]["delivery_status"] == "agent_cache_ready"- assert process_cache.has(grant["id"], "A_KEY")- with vault.connect() as conn:- status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()- assert status == "active"+ releases = vs.consume_one_shot_grant(conn, grant["id"])+ row = conn.execute(select(vault_grants).where(vault_grants.c.id == grant["id"])).mappings().one()+ assert req["card"]["one_shot"] is True+ assert grant["one_shot"] is True+ assert reserved["status"] == "reserved"+ assert row["status"] == "expired"+ assert releases == [{"grant_id": grant["id"]}]-def test_unrelayed_grant_is_not_selected_for_delivery(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache_ready=False,- cache=cache,- )- active = vs.find_active_grant_for_secret(conn, "A_KEY", session_id="ses_1", cache=cache)- resolved = vs.resolve_secret_access(conn, "A_KEY", session_id="ses_1", create_request=False, cache=cache)- ready = vs.mark_grant_agent_ready(conn, grant["id"], cache=cache)- process_cache = vs.VaultGrantRuntimeCache()- active_after_ready = vs.find_active_grant_for_secret(conn, "A_KEY", session_id="ses_1", cache=process_cache)-- assert active is None- assert resolved["status"] == "approval_required"- assert ready["delivery_ready"] is True- assert active_after_ready is not None- assert active_after_ready["id"] == grant["id"]- assert process_cache.has(grant["id"], "A_KEY")+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"])-def test_mark_grant_agent_ready_refreshes_expiry_to_relay_ttl(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- ttl_seconds=300,- created_by_request_id=req["id"],- cache_ready=False,- cache=cache,- )- before = datetime.now(timezone.utc)- ready = vs.mark_grant_agent_ready(conn, grant["id"], ttl_seconds=300, cache=cache)- after = datetime.now(timezone.utc)+ req = vs.create_access_request(conn, source_selector={"tags": ["deploy"]})+ assert req["secret_name"] is None+ expired = vs.rotate_secret(conn, "A_KEY", _sealed("rotated"))+ row = conn.execute(select(vault_requests).where(vault_requests.c.id == req["id"])).mappings().one()++ assert expired["name"] == "A_KEY"+ assert row["status"] == "expired"- expires_at = datetime.fromisoformat(ready["expires_at"])- assert before + timedelta(seconds=299) <= expires_at <= after + timedelta(seconds=301)- assert ready["delivery_ready"] is True+def test_selector_request_restores_after_failed_grant(vault):+ _create(vault, name="A_KEY", protection="protected", tags=["deploy"])+ _create(vault, name="B_KEY", protection="protected", tags=["deploy"])-def test_resolve_secret_prefers_cache_ready_grant_over_stale_scope(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- _create(vault, name="B_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()with vault.begin() as conn:- req_group = _access_request(conn, "A_KEY", session_id="ses_1")- stale_group = vs.create_grant(+ req = vs.create_access_request(conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req_group["id"],- cache_ready=False,- cache=cache,+ source_selector={"tags": ["deploy"]},+ requester={"session_id": "ses_1"},+ delivery={"session_id": "ses_1"},)- req_secret = _access_request(conn, "A_KEY", session_id="ses_1")- ready_secret = vs.create_grant(+ grant = _grant_from_request(conn, req, cache_ready=False)+ restored = vs.restore_access_request_after_failed_grant(conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req_secret["id"],- cache=cache,+ request_id=req["id"],+ member_names=grant["member_snapshot"],+ session_id=grant["session_id"],)+ row = conn.execute(select(vault_requests).where(vault_requests.c.id == req["id"])).mappings().one()- active = vs.find_active_grant_for_secret(conn, "A_KEY", session_id="ses_1", cache=cache)- resolved = vs.resolve_secret_access(conn, "A_KEY", session_id="ses_1", create_request=False, cache=cache)+ assert restored == 1+ assert row["status"] == "pending"+ assert row["decided_at"] is None- assert active is not None- assert active["id"] == ready_secret["id"]- assert active["id"] != stale_group["id"]- assert resolved["status"] == "agent_delivery_ready"- assert resolved["grant"]["id"] == ready_secret["id"]+def test_request_payload_hydrates_unlock_material_only_for_ui(vault):+ _create(vault, name="PROTECTED_KEY", protection="protected")-def test_agent_release_scope_requires_remaining_grants_cover_removed_members(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()with vault.begin() as conn:- req_narrow = _access_request(conn, "A_KEY", session_id="ses_narrow")- narrow_grant = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_narrow",- created_by_request_id=req_narrow["id"],- cache=cache,- )- vs.create_secret(conn, name="B_KEY", protection="protected", group="crypto", sealed=_sealed("b"))- req_group = _access_request(conn, "A_KEY", session_id="ses_group")- group_grant = vs.create_grant(+ req = vs.create_access_request(conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_group",- created_by_request_id=req_group["id"],- cache=cache,+ "PROTECTED_KEY",+ requester={"source": "agent-cli", "session_id": "ses_1"},+ delivery={"session_id": "ses_1"},)- rows = [dict(conn.execute(select(vault_grants).where(vault_grants.c.id == group_grant["id"])).mappings().one())]- vs.revoke_grant(conn, group_grant["id"], cache=cache)- release_scopes = vs.agent_release_scopes_after_rows(conn, rows, cache=cache)+ agent_payload = vs.get_request(conn, req["id"], audience=vs.REQUEST_AUDIENCE_AGENT)+ ui_payload = vs.get_request(conn, req["id"], audience=vs.REQUEST_AUDIENCE_UI)- assert release_scopes == [{"scope_type": "group", "scope_ref": "crypto"}]- assert not cache.has(group_grant["id"], "A_KEY")- assert not cache.has(narrow_grant["id"], "A_KEY")- with vault.connect() as conn:- listed = {grant["id"]: grant for grant in vs.list_grants(conn, status=None, cache=vs.VaultGrantRuntimeCache())}- assert listed[narrow_grant["id"]]["delivery_ready"] is False+ assert "unlock_material" not in json.dumps(agent_payload)+ assert ui_payload["card"]["grant_options"][0]["unlock_material"][0]["name"] == "PROTECTED_KEY"-def test_agent_release_scope_skips_when_remaining_members_cover_removed_scope(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- _create(vault, name="B_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()+def test_expired_request_cannot_create_grant(vault):+ _create(vault, name="A_KEY", protection="protected")+ expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()+with vault.begin() as conn:- req_1 = _access_request(conn, "A_KEY", session_id="ses_1")- grant_1 = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req_1["id"],- cache=cache,- )- req_2 = _access_request(conn, "A_KEY", session_id="ses_2")- grant_2 = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_2",- created_by_request_id=req_2["id"],- cache=cache,- )- rows = [dict(conn.execute(select(vault_grants).where(vault_grants.c.id == grant_1["id"])).mappings().one())]- vs.revoke_grant(conn, grant_1["id"], cache=cache)- release_scopes = vs.agent_release_scopes_after_rows(conn, rows, cache=cache)+ req = vs.create_access_request(conn, "A_KEY", expires_at=expired_at)+ with pytest.raises(vs.InvalidRequestError):+ _grant_from_request(conn, req)- assert release_scopes == []- assert not cache.has(grant_1["id"], "A_KEY")- assert cache.has(grant_2["id"], "A_KEY")+def test_get_grant_created_by_request_uses_request_id(vault):+ _create(vault, name="A_KEY", protection="protected")-def test_agent_release_scope_ignores_unready_remaining_grants(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()with vault.begin() as conn:- req_1 = _access_request(conn, "A_KEY", session_id="ses_1")- grant_1 = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req_1["id"],- cache=cache,- )- req_2 = _access_request(conn, "A_KEY", session_id="ses_2")- grant_2 = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_2",- created_by_request_id=req_2["id"],- cache_ready=False,- cache=cache,- )- rows = [dict(conn.execute(select(vault_grants).where(vault_grants.c.id == grant_1["id"])).mappings().one())]- vs.revoke_grant(conn, grant_1["id"], cache=cache)- release_scopes = vs.agent_release_scopes_after_rows(conn, rows, cache=cache)-- assert release_scopes == [{"scope_type": "group", "scope_ref": "crypto"}]- assert not cache.has(grant_1["id"], "A_KEY")- assert not cache.has(grant_2["id"], "A_KEY")- with vault.connect() as conn:- listed = {grant["id"]: grant for grant in vs.list_grants(conn, status=None, cache=vs.VaultGrantRuntimeCache())}- assert listed[grant_2["id"]]["delivery_ready"] is False+ req = vs.create_access_request(conn, "A_KEY")+ grant = _grant_from_request(conn, req)+ fetched = vs.get_grant_created_by_request(conn, req["id"])--def test_agent_release_scope_ignores_expired_remaining_grants(vault):- _create(vault, name="A_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req_1 = _access_request(conn, "A_KEY", session_id="ses_1")- grant_1 = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_1",- created_by_request_id=req_1["id"],- cache=cache,- )- req_2 = _access_request(conn, "A_KEY", session_id="ses_2")- grant_2 = vs.create_grant(- conn,- scope_type="group",- scope_ref="crypto",- session_id="ses_2",- created_by_request_id=req_2["id"],- cache=cache,- )- conn.execute(- vault_grants.update()- .where(vault_grants.c.id == grant_2["id"])- .values(expires_at=(datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat())- )- rows = [dict(conn.execute(select(vault_grants).where(vault_grants.c.id == grant_1["id"])).mappings().one())]- vs.revoke_grant(conn, grant_1["id"], cache=cache)- release_scopes = vs.agent_release_scopes_after_rows(conn, rows, cache=cache)-- assert release_scopes == [{"scope_type": "group", "scope_ref": "crypto"}]- assert not cache.has(grant_1["id"], "A_KEY")- assert not cache.has(grant_2["id"], "A_KEY")- with vault.connect() as conn:- listed = {grant["id"]: grant for grant in vs.list_grants(conn, status=None, cache=vs.VaultGrantRuntimeCache())}- assert listed[grant_2["id"]]["status"] == "expired"- assert listed[grant_2["id"]]["delivery_ready"] is False---def test_grant_runtime_cache_drops_coverage_at_expiry_without_key_material():- cache = vs.VaultGrantRuntimeCache()- expires_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()-- cache.put("vgr_old", ["A_KEY"], expires_at=expires_at)-- assert not cache.has("vgr_old", "A_KEY")- assert cache.get("vgr_old", "A_KEY") is None- assert cache.covered_names("vgr_old") == []---def test_rotate_protected_secret_expires_active_grants(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,- )- vs.rotate_secret(conn, "A_KEY", _sealed("rotated"), cache=cache)- resolved = vs.resolve_secret_access(conn, "A_KEY", session_id="ses_1", create_request=False, cache=cache)-- assert resolved["status"] == "approval_required"- with vault.connect() as conn:- status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()- assert status == "expired"- assert not cache.has(grant["id"], "A_KEY")---def test_delete_protected_secret_expires_active_grants_before_recreate(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,- )- vs.delete_secret(conn, "A_KEY", cache=cache)- vs.create_secret(conn, name="A_KEY", protection="protected", sealed=_sealed("recreated"))- resolved = vs.resolve_secret_access(conn, "A_KEY", session_id="ses_1", create_request=False, cache=cache)-- assert resolved["status"] == "approval_required"- with vault.connect() as conn:- status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()- assert status == "expired"- assert not cache.has(grant["id"], "A_KEY")---def test_unrelayed_active_grant_list_keeps_metadata_when_runtime_cache_is_empty(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache_ready=False,- cache=cache,- )- cache.clear()- listed = vs.list_grants(conn, cache=cache)- assert len(listed) == 1- assert listed[0]["id"] == grant["id"]- assert listed[0]["runtime_member_count"] == 0- assert listed[0]["delivery_ready"] is False- assert listed[0]["delivery_status"] == "agent_cache_unverified"- with vault.connect() as conn:- status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()- assert status == "active"---def test_resolve_protected_without_grant_returns_approval_card(vault):- _create(vault, name="PROTECTED_KEY", protection="protected", group="crypto")- with vault.begin() as conn:- vs.create_secret(conn, name="GROUP_KEY", protection="protected", group="crypto", sealed=_sealed("group"))- with vault.begin() as conn:- result = vs.resolve_secret_access(- conn,- "PROTECTED_KEY",- session_id="ses_1",- requester={"session_id": "ses_1", "skill": "deploy"},- delivery={"command": "python sync.py", "egress": "local child process", "skill": "deploy"},- )- assert result["status"] == "approval_required"- card = result["request"]["card"]- assert card["card_type"] == "approval"- assert card["secret_name"] == "PROTECTED_KEY"- assert card["command"] == "python sync.py"- assert any(option["scope_type"] == "secret" for option in card["scope_options"])- assert all("value" not in json.dumps(option) for option in card["scope_options"])- assert card["secret_unlock_material"] == {- "name": "PROTECTED_KEY",- "kind": "static",- "envelope": {"ciphertext": "ct-1", "nonce": "n-1", "wrap_meta": "wm-1"},- }- group_option = next(option for option in card["scope_options"] if option["scope_type"] == "group")- assert group_option["member_snapshot"] == ["GROUP_KEY", "PROTECTED_KEY"]- assert group_option["unlock_material"] == [- {- "name": "GROUP_KEY",- "kind": "static",- "envelope": {"ciphertext": "ct-group", "nonce": "n-group", "wrap_meta": "wm-group"},- },- {- "name": "PROTECTED_KEY",- "kind": "static",- "envelope": {"ciphertext": "ct-1", "nonce": "n-1", "wrap_meta": "wm-1"},- },- ]- assert all("member_versions" in option for option in card["scope_options"])- with vault.connect() as conn:- request_row = conn.execute(select(vault_requests).where(vault_requests.c.id == result["request"]["id"])).mappings().one()- delivery = json.loads(request_row["delivery"])- audit_delivery = conn.execute(- select(vault_audit.c.delivery).where(vault_audit.c.event == "access_requested")- ).scalar_one()- persisted = json.dumps({"delivery": delivery, "audit_delivery": audit_delivery})- assert "secret_unlock_material" not in persisted- assert "unlock_material" not in persisted- assert "ct-1" not in persisted- assert "ct-group" not in persisted---def test_resolve_protected_with_grant_reports_agent_delivery_ready(vault):- _create(vault, name="PROTECTED_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "PROTECTED_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="PROTECTED_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,- )- result = vs.resolve_secret_access(conn, "PROTECTED_KEY", session_id="ses_1", create_request=False, cache=cache)-- assert result["status"] == "agent_delivery_ready"- assert result["request"] is None- assert result["grant"]["id"] == grant["id"]- assert result["grant"]["delivery_ready"] is True- assert result["envelope"] == _sealed()---def test_expire_grant_after_agent_cache_missing_reopens_approval(vault):- _create(vault, name="PROTECTED_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "PROTECTED_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="PROTECTED_KEY",- session_id="ses_1",- created_by_request_id=req["id"],- cache=cache,- )- expired = vs.expire_grant(conn, grant["id"], cache=cache, reason="grant-expired-agent-cache-missing")- result = vs.resolve_secret_access(conn, "PROTECTED_KEY", session_id="ses_1", cache=cache)-- assert expired["status"] == "expired"- assert result["status"] == "approval_required"- assert result["request"]["secret_name"] == "PROTECTED_KEY"---def test_request_inbox_hydrates_unlock_material_without_persisting_it(vault):- _create(vault, name="PROTECTED_KEY", protection="protected", group="crypto")- with vault.begin() as conn:- req = vs.create_access_request(conn, "PROTECTED_KEY", delivery={"command": "python sync.py"})- with vault.connect() as conn:- listed = vs.list_requests(conn)- raw_delivery = conn.execute(select(vault_requests.c.delivery).where(vault_requests.c.id == req["id"])).scalar_one()-- assert listed[0]["card"]["secret_unlock_material"]["envelope"] == {- "ciphertext": "ct-1",- "nonce": "n-1",- "wrap_meta": "wm-1",- }- assert "secret_unlock_material" not in raw_delivery- assert "ct-1" not in raw_delivery---def test_agent_created_request_hydrates_only_for_ui_inbox(vault):- _create(vault, name="STANDARD_KEY", protection="standard", group="crypto")- with vault.begin() as conn:- vs.create_secret(conn, name="PROTECTED_KEY", protection="protected", group="crypto", sealed=_sealed("protected"))- req = vs.create_access_request(- conn,- "STANDARD_KEY",- requester={"source": "agent-cli", "session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- ui_payload = vs.get_request(conn, req["id"])- agent_payload = vs.get_request(conn, req["id"], audience=vs.REQUEST_AUDIENCE_AGENT)- listed = vs.list_requests(conn)-- agent_encoded = json.dumps(agent_payload)- assert "secret_unlock_material" not in agent_encoded- assert "unlock_material" not in agent_encoded- assert "ct-protected" not in agent_encoded- assert "wm-protected" not in agent_encoded- ui_encoded = json.dumps({"ui": ui_payload, "listed": listed})- assert "unlock_material" in ui_encoded- assert "ct-protected" in ui_encoded- assert "wm-protected" in ui_encoded- group_option = next(option for option in listed[0]["card"]["scope_options"] if option["scope_type"] == "group")- assert group_option["unlock_material"] == [- {- "name": "PROTECTED_KEY",- "kind": "static",- "envelope": {- "ciphertext": "ct-protected",- "nonce": "n-protected",- "wrap_meta": "wm-protected",- },- }- ]---def test_cli_resolve_protected_request_hydrates_only_for_ui_inbox(vault):- _create(vault, name="PROTECTED_KEY", protection="protected", group="crypto")- with vault.begin() as conn:- result = vs.resolve_secret_access(- conn,- "PROTECTED_KEY",- session_id="ses_1",- requester={"source": "cli", "session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- listed = vs.list_requests(conn)- raw_delivery = conn.execute(- select(vault_requests.c.delivery).where(vault_requests.c.id == result["request"]["id"])- ).scalar_one()-- agent_encoded = json.dumps(result["request"]["card"])- assert result["status"] == "approval_required"- assert "secret_unlock_material" not in agent_encoded- assert "ct-1" not in agent_encoded- assert listed[0]["card"]["secret_unlock_material"]["envelope"] == {- "ciphertext": "ct-1",- "nonce": "n-1",- "wrap_meta": "wm-1",- }- assert "secret_unlock_material" not in raw_delivery- assert "ct-1" not in raw_delivery---def test_resolve_access_card_uses_delivery_session_fallback(vault):- _create(vault, name="PROTECTED_KEY", protection="protected", group="crypto")- with vault.begin() as conn:- result = vs.resolve_secret_access(conn, "PROTECTED_KEY", session_id="ses_delivery", requester={}, delivery={})- card = result["request"]["card"]- assert card["session_id"] == "ses_delivery"- req_id = result["request"]["id"]- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="PROTECTED_KEY",- created_by_request_id=req_id,- )- assert grant["session_id"] == "ses_delivery"---def test_resolve_access_preserves_delivery_session_when_argument_is_missing(vault):- _create(vault, name="PROTECTED_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- result = vs.resolve_secret_access(- conn,- "PROTECTED_KEY",- requester={},- delivery={"session_id": "ses_delivery", "command": "deploy"},- cache=cache,- )- card = result["request"]["card"]- req_id = result["request"]["id"]- raw_delivery = conn.execute(select(vault_requests.c.delivery).where(vault_requests.c.id == req_id)).scalar_one()- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="PROTECTED_KEY",- created_by_request_id=req_id,- cache=cache,- )- same_session = vs.resolve_secret_access(- conn,- "PROTECTED_KEY",- delivery={"session_id": "ses_delivery"},- create_request=False,- cache=cache,- )- other_session = vs.resolve_secret_access(- conn,- "PROTECTED_KEY",- delivery={"session_id": "ses_other"},- create_request=False,- cache=cache,- )-- assert card["session_id"] == "ses_delivery"- assert json.loads(raw_delivery)["session_id"] == "ses_delivery"- assert grant["session_id"] == "ses_delivery"- assert same_session["status"] == "agent_delivery_ready"- assert other_session["status"] == "approval_required"---def test_resolve_access_uses_requester_session_for_grant_lookup(vault):- _create(vault, name="PROTECTED_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = vs.create_access_request(- conn,- "PROTECTED_KEY",- requester={"session_id": "ses_requester"},- )- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="PROTECTED_KEY",- created_by_request_id=req["id"],- cache=cache,- )- same_session = vs.resolve_secret_access(- conn,- "PROTECTED_KEY",- requester={"session_id": "ses_requester"},- create_request=False,- cache=cache,- )- other_session = vs.resolve_secret_access(- conn,- "PROTECTED_KEY",- requester={"session_id": "ses_other"},- create_request=False,- cache=cache,- )-- assert grant["session_id"] == "ses_requester"- assert same_session["status"] == "agent_delivery_ready"- assert same_session["grant"]["id"] == grant["id"]- assert other_session["status"] == "approval_required"---def test_grant_can_be_intentionally_unbound_from_request_session(vault):- _create(vault, name="PROTECTED_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- req = _access_request(conn, "PROTECTED_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="PROTECTED_KEY",- created_by_request_id=req["id"],- inherit_request_session=False,- cache=cache,- )-- assert grant["session_id"] is None- assert cache.has(grant["id"], "PROTECTED_KEY")---def test_keypair_is_not_value_requestable_and_always_ask_is_not_pregrantable(vault):- _create(- vault,- name="ETH_KEY",- protection="protected",- kind="keypair",- signer_kind="local",- public_meta=PROTECTED_SIGNING_PUBLIC_META,- policy={"always_ask": True},- )- _create(vault, name="STATIC_KEY", protection="protected", policy={"always_ask": True})- with vault.begin() as conn:- with pytest.raises(vs.NotGrantableError):- vs.create_access_request(conn, "ETH_KEY", requester={"session_id": "ses_1"})- req = vs.create_access_request(conn, "STATIC_KEY", requester={"session_id": "ses_1"})- meta = vs.get_secret_meta(conn, "STATIC_KEY")- pregrant_members = vs.grantable_member_metas(conn, "secret", "STATIC_KEY")- requests = conn.execute(- select(vault_requests).where(vault_requests.c.secret_name.in_(["ETH_KEY", "STATIC_KEY"]))- ).mappings().all()- sign_req = vs.create_sign_request(conn, "ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")-- assert meta["access_grantable"] is False- assert pregrant_members == []- assert [row["secret_name"] for row in requests] == ["STATIC_KEY"]- assert req["card"]["one_shot"] is True- assert len(req["card"]["scope_options"]) == 1- assert req["card"]["scope_options"][0]["scope_type"] == "secret"- assert req["card"]["scope_options"][0]["scope_ref"] == "STATIC_KEY"- assert req["card"]["scope_options"][0]["member_snapshot"] == ["STATIC_KEY"]- assert req["card"]["scope_options"][0]["one_shot"] is True- assert sign_req["request_type"] == "sign"- assert sign_req["card"]["one_shot"] is False- assert sign_req["card"]["scope_options"] == []---def test_always_ask_honors_group_grantability(vault):- _create(vault, name="STATIC_KEY", protection="protected", group="locked", policy={"always_ask": True})- with vault.begin() as conn:- conn.execute(vault_groups.update().where(vault_groups.c.name == "locked").values(grantable=0))- req = vs.create_access_request(conn, "STATIC_KEY", requester={"session_id": "ses_1"})- request_members = vs.request_grantable_member_metas(conn, "secret", "STATIC_KEY", req["id"])- with pytest.raises(vs.NotGrantableError):- vs.create_grant(conn, scope_type="secret", scope_ref="STATIC_KEY", created_by_request_id=req["id"])-- assert req["card"]["scope_options"] == []- assert request_members == []---def test_always_ask_one_shot_card_ttl_is_capped_by_group_policy(vault):- _create(vault, name="STATIC_KEY", protection="protected", group="strict", policy={"always_ask": True})- with vault.begin() as conn:- conn.execute(vault_groups.update().where(vault_groups.c.name == "strict").values(max_grant_ttl_seconds=120))- req = vs.create_access_request(conn, "STATIC_KEY", requester={"session_id": "ses_1"})- option = req["card"]["scope_options"][0]- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="STATIC_KEY",- ttl_seconds=3600,- created_by_request_id=req["id"],- )-- created_at = datetime.fromisoformat(grant["created_at"])- expires_at = datetime.fromisoformat(grant["expires_at"])- assert option["one_shot"] is True- assert option["default_ttl_seconds"] == 120- assert option["ttl_options_seconds"] == []- assert int((expires_at - created_at).total_seconds()) == 120---def test_standard_always_ask_routes_every_access_through_one_shot_request(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- assert first["status"] == "approval_required"- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- delivered = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- still_active = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- create_request=False,- reserve_one_shot=True,- )- vs.consume_one_shot_grant(conn, grant["id"])- second = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- request_rows = conn.execute(- select(vault_requests.c.id, vault_requests.c.status).where(vault_requests.c.secret_name == "ASK_KEY")- ).mappings().all()- grant_status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()-- assert grant["one_shot"] is True- assert delivered["status"] == "standard"- assert delivered["grant"]["id"] == grant["id"]- assert delivered["grant"]["status"] == "reserved"- assert delivered["envelope"] == _sealed()- assert still_active["status"] == "approval_required"- assert still_active["request"] is None- assert grant_status == "expired"- assert second["status"] == "approval_required"- assert second["request"]["id"] != first["request"]["id"]- assert [(row["id"], row["status"]) for row in request_rows] == [- (first["request"]["id"], "approved"),- (second["request"]["id"], "pending"),- ]---def test_protected_always_ask_routes_every_access_through_one_shot_request(vault):- _create(vault, name="ASK_KEY", protection="protected", group="crypto", policy={"always_ask": True})- _create(vault, name="GROUP_KEY", protection="protected", group="crypto")- cache = vs.VaultGrantRuntimeCache()- with vault.begin() as conn:- conn.execute(vault_links.insert().values(id="ln_ask", secret_name="ASK_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- conn.execute(vault_links.insert().values(id="ln_group", secret_name="GROUP_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1", "skill": "deploy"},- delivery={"skill": "deploy"},- cache=cache,- )- assert first["status"] == "approval_required"- assert first["request"]["card"]["scope_options"][0]["scope_ref"] == "ASK_KEY"- assert all(option["scope_ref"] != "crypto" for option in first["request"]["card"]["scope_options"])- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- created_by_request_id=first["request"]["id"],- cache=cache,- )- delivered = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1", "skill": "deploy"},- delivery={"skill": "deploy"},- cache=cache,- reserve_one_shot=True,- )- still_active = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1", "skill": "deploy"},- delivery={"skill": "deploy"},- cache=cache,- create_request=False,- reserve_one_shot=True,- )- vs.consume_one_shot_grant(conn, grant["id"], cache=cache)- second = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1", "skill": "deploy"},- delivery={"skill": "deploy"},- cache=cache,- )- requests = conn.execute(select(vault_requests).where(vault_requests.c.secret_name == "ASK_KEY")).mappings().all()- grant_status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()-- assert grant["one_shot"] is True- assert grant["session_id"] == "ses_1"- assert delivered["status"] == "agent_delivery_ready"- assert delivered["grant"]["id"] == grant["id"]- assert delivered["grant"]["status"] == "reserved"- assert delivered["envelope"] == _sealed()- assert still_active["status"] == "approval_required"- assert still_active["request"] is None- assert grant_status == "expired"- assert not cache.has(grant["id"], "ASK_KEY")- assert second["status"] == "approval_required"- assert [row["status"] for row in requests] == ["approved", "pending"]---def test_one_shot_reservation_can_be_released_before_delivery(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- reserved = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- missing = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- create_request=False,- reserve_one_shot=True,- )- released = vs.release_one_shot_reservation(conn, grant["id"])- available = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )-- assert reserved["grant"]["status"] == "reserved"- assert missing["status"] == "approval_required"- assert missing["request"] is None- assert released["status"] == "active"- assert available["status"] == "standard"- assert available["grant"]["id"] == grant["id"]- assert available["grant"]["status"] == "reserved"---def test_resolve_secret_access_default_does_not_reserve_one_shot_grant(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- resolved = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()-- assert resolved["status"] == "standard"- assert resolved["grant"]["id"] == grant["id"]- assert resolved["grant"]["status"] == "active"- assert status == "active"---def test_non_claiming_lookup_skips_reserved_one_shot_grant(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- reserved = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- resolved = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- create_request=False,- )-- assert reserved["grant"]["id"] == grant["id"]- assert reserved["grant"]["status"] == "reserved"- assert resolved["status"] == "approval_required"- assert resolved["request"] is None---def test_list_active_grants_includes_reserved_one_shot_grants(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- active = vs.list_grants(conn)-- assert [(item["id"], item["status"]) for item in active] == [(grant["id"], "reserved")]---def test_delivery_resolver_skips_reserved_one_shot_and_claims_next_active_grant(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant_1 = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- reserved = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- second_req = vs.create_access_request(- conn,- "ASK_KEY",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant_2 = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=second_req["id"],- )- claimed = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- statuses = {- row["id"]: row["status"]- for row in conn.execute(select(vault_grants.c.id, vault_grants.c.status).where(vault_grants.c.id.in_([grant_1["id"], grant_2["id"]]))).mappings()- }-- assert reserved["grant"]["id"] == grant_1["id"]- assert claimed["status"] == "standard"- assert claimed["grant"]["id"] == grant_2["id"]- assert statuses == {grant_1["id"]: "reserved", grant_2["id"]: "reserved"}---def test_reserved_one_shot_grants_are_expired_by_ttl_sweep(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- reserved = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- conn.execute(- vault_grants.update()- .where(vault_grants.c.id == grant["id"])- .values(expires_at=(datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat())- )- vs.expire_grants(conn)- status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()-- assert reserved["grant"]["status"] == "reserved"- assert status == "expired"---def test_reserved_one_shot_grants_are_revoked_with_session(vault):- _create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})- with vault.begin() as conn:- first = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- )- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="ASK_KEY",- session_id="ses_1",- created_by_request_id=first["request"]["id"],- )- reserved = vs.resolve_secret_access(- conn,- "ASK_KEY",- session_id="ses_1",- requester={"session_id": "ses_1"},- delivery={"session_id": "ses_1"},- reserve_one_shot=True,- )- count = vs.revoke_session_grants(conn, "ses_1")- status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()-- assert reserved["grant"]["status"] == "reserved"- assert count == 1- assert status == "revoked"---def test_grant_creation_does_not_require_python_dek_material(vault):- _create(vault, name="A_KEY", protection="protected")- with vault.begin() as conn:- req = _access_request(conn, "A_KEY")- grant = vs.create_grant(conn, scope_type="secret", scope_ref="A_KEY", created_by_request_id=req["id"])-- assert grant["member_snapshot"] == ["A_KEY"]- assert grant["delivery_status"] == "agent_cache_ready"---def test_grant_creation_rejects_expected_member_mismatch_without_claiming_request(vault):- _create(vault, name="A_KEY", protection="protected")- with vault.begin() as conn:- req = _access_request(conn, "A_KEY")-- with pytest.raises(vs.InvalidGrantError):- with vault.begin() as conn:- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- created_by_request_id=req["id"],- expected_member_names={"B_KEY"},- )-- with vault.connect() as conn:- status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.secret_name == "A_KEY")).scalar_one()- grants = conn.execute(select(vault_grants)).mappings().all()-- assert status == "pending"- assert grants == []---def test_grant_creation_must_match_pending_access_request(vault):- _create(vault, name="A_KEY", protection="protected")- _create(vault, name="B_KEY", protection="protected")- _create(- vault,- name="ETH_KEY",- protection="protected",- kind="keypair",- signer_kind="local",- public_meta=PROTECTED_SIGNING_PUBLIC_META,- )- with vault.begin() as conn:- access_req = _access_request(conn, "A_KEY", session_id="ses_1")- sign_req = vs.create_sign_request(conn, "ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="secret",- scope_ref="B_KEY",- session_id="ses_1",- created_by_request_id=access_req["id"],- )- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=sign_req["id"],- )- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=access_req["id"],- )- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=access_req["id"],- )---def test_grant_creation_rejects_expired_access_request(vault):- _create(vault, name="A_KEY", protection="protected")- cache = vs.VaultGrantRuntimeCache()- expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()- with vault.begin() as conn:- req = vs.create_access_request(conn, "A_KEY", expires_at=expired_at)- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- created_by_request_id=req["id"],- cache=cache,- )- status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == req["id"])).scalar_one()- grants = conn.execute(select(vault_grants)).mappings().all()-- assert status == "expired"- assert grants == []---def test_rotating_protected_secret_expires_pending_access_and_sign_requests(vault):- _create(vault, name="A_KEY", protection="protected")- _create(- vault,- name="ETH_KEY",- protection="protected",- kind="keypair",- signer_kind="local",- public_meta=PROTECTED_SIGNING_PUBLIC_META,- )- with vault.begin() as conn:- access_req = _access_request(conn, "A_KEY", session_id="ses_1")- vs.rotate_secret(conn, "A_KEY", _sealed("rotated"))- access_status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == access_req["id"])).scalar_one()- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- created_by_request_id=access_req["id"],- )-- sign_req = vs.create_sign_request(conn, "ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")- vs.rotate_secret(conn, "ETH_KEY", _sealed("rotated-key"))- sign_status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == sign_req["id"])).scalar_one()- with pytest.raises(vs.InvalidRequestError):- vs.complete_sign_request(- conn,- sign_req["id"],- name="ETH_KEY",- digest="00" * 32,- scheme="ecdsa-secp256k1-recoverable",- signature={"signature": "sig"},- )-- assert access_status == "expired"- assert sign_status == "expired"---def test_rotating_standard_secret_expires_pending_requests_and_active_grants(vault):- _create(vault, name="A_KEY", protection="standard")- _create(vault, name="ETH_KEY", protection="standard", kind="keypair", signer_kind="local")- with vault.begin() as conn:- access_req = _access_request(conn, "A_KEY", session_id="ses_1")- grant = vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_1",- created_by_request_id=access_req["id"],- )- pending_access_req = _access_request(conn, "A_KEY", session_id="ses_2")- vs.rotate_secret(conn, "A_KEY", _sealed("rotated"))- access_status = conn.execute(- select(vault_requests.c.status).where(vault_requests.c.id == pending_access_req["id"])- ).scalar_one()- grant_status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="secret",- scope_ref="A_KEY",- session_id="ses_2",- created_by_request_id=pending_access_req["id"],- )-- sign_req = vs.create_sign_request(conn, "ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")- vs.rotate_secret(conn, "ETH_KEY", _sealed("rotated-key"))- sign_status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == sign_req["id"])).scalar_one()- with pytest.raises(vs.InvalidRequestError):- vs.claim_sign_request(- conn,- sign_req["id"],- name="ETH_KEY",- digest="00" * 32,- scheme="ecdsa-secp256k1-recoverable",- )-- assert access_status == "expired"- assert grant_status == "expired"- assert sign_status == "expired"---def test_deleting_protected_secret_expires_pending_access_requests(vault):- _create(vault, name="A_KEY", protection="protected")- with vault.begin() as conn:- access_req = _access_request(conn, "A_KEY", session_id="ses_1")- vs.delete_secret(conn, "A_KEY")- status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == access_req["id"])).scalar_one()-- assert status == "expired"---def test_deleting_standard_secret_expires_pending_access_and_sign_requests(vault):- _create(vault, name="A_KEY", protection="standard")- _create(vault, name="ETH_KEY", protection="standard", kind="keypair", signer_kind="local")- with vault.begin() as conn:- access_req = _access_request(conn, "A_KEY", session_id="ses_1")- vs.delete_secret(conn, "A_KEY")- access_status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == access_req["id"])).scalar_one()-- sign_req = vs.create_sign_request(conn, "ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")- vs.delete_secret(conn, "ETH_KEY")- sign_status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == sign_req["id"])).scalar_one()-- assert access_status == "expired"- assert sign_status == "expired"---def test_sign_request_completion_can_only_claim_pending_once(vault):- _create(- vault,- name="ETH_KEY",- protection="protected",- kind="keypair",- signer_kind="local",- public_meta=PROTECTED_SIGNING_PUBLIC_META,- )- digest = "00" * 32- with vault.begin() as conn:- sign_req = vs.create_sign_request(conn, "ETH_KEY", digest=digest, scheme="ecdsa-secp256k1-recoverable")- first = vs.complete_sign_request(- conn,- sign_req["id"],- name="ETH_KEY",- digest=digest,- scheme="ecdsa-secp256k1-recoverable",- signature={"signature": "ab" * 64, "recovery_id": 1},- )- with pytest.raises(vs.InvalidRequestError):- vs.complete_sign_request(- conn,- sign_req["id"],- name="ETH_KEY",- digest=digest,- scheme="ecdsa-secp256k1-recoverable",- signature={"signature": "cd" * 64, "recovery_id": 1},- )- signed_events = [- row["event"]- for row in conn.execute(select(vault_audit.c.event).where(vault_audit.c.event == "signed")).mappings()- ]- meta = vs.get_secret_meta(conn, "ETH_KEY")-- assert first["status"] == "approved"- assert signed_events == ["signed"]- assert meta["use_count"] == 1- assert meta["last_used_at"] is not None---def test_get_request_expires_timed_out_pending_request(vault):- _create(vault, name="A_KEY")- expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()- with vault.begin() as conn:- req = vs.create_access_request(conn, "A_KEY", expires_at=expired_at)- fetched = vs.get_request(conn, req["id"])- audit_events = [- row["event"]- for row in conn.execute(select(vault_audit.c.event).where(vault_audit.c.request_id == req["id"])).mappings()- ]-- assert fetched["status"] == "expired"- assert "request-expired" in audit_events---def test_list_requests_expires_timed_out_pending_requests(vault):- _create(vault, name="A_KEY")- expired_at = (datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat()- with vault.begin() as conn:- req = vs.create_access_request(conn, "A_KEY", expires_at=expired_at)- pending = vs.list_requests(conn, status="pending")- expired = vs.get_request(conn, req["id"])-- assert pending == []- assert expired["status"] == "expired"---def test_claim_sign_request_prevents_concurrent_deny_before_completion(vault):- _create(vault, name="ETH_KEY", kind="keypair", signer_kind="local")- digest = "00" * 32- with vault.begin() as conn:- req = vs.create_sign_request(conn, "ETH_KEY", digest=digest, scheme="ecdsa-secp256k1-recoverable")- claimed = vs.claim_sign_request(conn, req["id"], name="ETH_KEY", digest=digest, scheme="ecdsa-secp256k1-recoverable")- with pytest.raises(vs.InvalidRequestError):- vs.deny_request(conn, req["id"])- completed = vs.complete_sign_request(- conn,- req["id"],- name="ETH_KEY",- digest=digest,- scheme="ecdsa-secp256k1-recoverable",- signature={"signature": "ab" * 64, "recovery_id": 1},- )-- assert claimed["status"] == "signing"- assert completed["status"] == "approved"---def test_sign_request_completion_rejects_malformed_signatures(vault):- _create(- vault,- name="ETH_KEY",- protection="protected",- kind="keypair",- signer_kind="local",- public_meta=PROTECTED_SIGNING_PUBLIC_META,- )- digest = "00" * 32- with vault.begin() as conn:- req = vs.create_sign_request(conn, "ETH_KEY", digest=digest, scheme="ecdsa-secp256k1-recoverable")- with pytest.raises(vs.InvalidRequestError):- vs.complete_sign_request(- conn,- req["id"],- name="ETH_KEY",- digest=digest,- scheme="ecdsa-secp256k1-recoverable",- signature={"signature": "not-hex", "recovery_id": 1},- )- with pytest.raises(vs.InvalidRequestError):- vs.complete_sign_request(- conn,- req["id"],- name="ETH_KEY",- digest=digest,- scheme="ecdsa-secp256k1-recoverable",- signature={"signature": "ab" * 64},- )- status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == req["id"])).scalar_one()- meta = vs.get_secret_meta(conn, "ETH_KEY")-- assert status == "pending"- assert meta["use_count"] == 0---def test_skill_grant_uses_vault_links(vault):- _create(vault, name="A_KEY", protection="protected")- _create(vault, name="B_KEY", protection="protected")- with vault.begin() as conn:- conn.execute(vault_links.insert().values(id="ln_a", secret_name="A_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- conn.execute(vault_links.insert().values(id="ln_b", secret_name="B_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- req = _access_request(conn, "A_KEY", skill="deploy")- grant = vs.create_grant(- conn,- scope_type="skill",- scope_ref="deploy",- session_id="ses_1",- created_by_request_id=req["id"],- )- assert grant["member_snapshot"] == ["A_KEY", "B_KEY"]---def test_scope_grant_rejects_stale_member_snapshot_after_rotation(vault):- _create(vault, name="A_KEY", protection="protected")- _create(vault, name="B_KEY", protection="protected")- with vault.begin() as conn:- conn.execute(vault_links.insert().values(id="ln_a", secret_name="A_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- conn.execute(vault_links.insert().values(id="ln_b", secret_name="B_KEY", skill_name="deploy", source="user", required=1, created_at="now"))- req = _access_request(conn, "A_KEY", skill="deploy")- vs.rotate_secret(conn, "B_KEY", _sealed("rotated-b"))- with pytest.raises(vs.InvalidRequestError):- vs.create_grant(- conn,- scope_type="skill",- scope_ref="deploy",- session_id="ses_1",- created_by_request_id=req["id"],- )- status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == req["id"])).scalar_one()-- assert status == "pending"+ assert fetched["id"] == grant["id"]diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsxindex 506523c42..7d3035999 100644--- a/ui/src/components/ui/vault-approval-card.tsx+++ b/ui/src/components/ui/vault-approval-card.tsx@@ -21,14 +21,10 @@ import { VaultProtectedUnlock } from './vault-protected-unlock';/*** The fixed protected grant the daemon attaches to an access request's card. In the* grant-id model there is exactly one: the protected set covered by the request's- * selector. `scope_type`/`scope_ref` are NOT a product concept — they are the opaque- * binding the DEK blind box is sealed against (blindBoxAgentDeliverOperationHash),- * relayed verbatim to the resident avault agent pending the avault-side grant_id- * migration (Track A). The UI never renders them.+ * selector. `grant_id` is the avault runtime scope and the DEK blind-box AAD binding.*/type GrantOption = {- scope_type?: string;- scope_ref?: string;+ grant_id: string;default_ttl_seconds?: number;session_binding_default?: boolean;member_count?: number;@@ -42,6 +38,8 @@ type ApprovalCard = {card_type?: string;request_type?: 'access' | 'sign';secret_name?: string;+ secret_names?: string[];+ protected_secret_names?: string[];kind?: string | null;protection?: string | null;command?: string | null;@@ -51,9 +49,8 @@ type ApprovalCard = {/** How the protected set was selected: explicit env names vs tags/skills. */source_selector?: VaultSourceSelector;default_ttl_seconds?: number;- /** The fixed protected grant. New backend sends `grant_options`; older sends `scope_options`. */+ /** The fixed protected grant. */grant_options?: GrantOption[];- scope_options?: GrantOption[];/** Hydrated for UI audience when the requested secret is protected. */secret_unlock_material?: ProtectedUnlockMaterial | null;};@@ -115,26 +112,22 @@ export const VaultApprovalCard: React.FC<{const card = (request.card ?? null) as ApprovalCard | null;const delivery = (request.delivery ?? {}) as { digest?: string; scheme?: string };const isSign = (card?.request_type ?? request.request_type) === 'sign';- const isProtected = card?.protection === 'protected';const isKeypair = card?.kind === 'keypair';// A grant covers a fixed protected set — there is no scope picker.- const grantOptions = useMemo(() => card?.grant_options ?? card?.scope_options ?? [], [card]);- const option = useMemo(() => {- if (!grantOptions.length) return undefined;- // New backend: exactly one fixed protected set covered by the request's selector.- if (card?.grant_options?.length) return grantOptions[0];- // Legacy pre-refactor scope_options are ordered [secret, skill, group] and only options- // containing protected members get hydrated unlock_material. Prefer the EXACT- // requested-secret scope so approving never auto-selects a broader skill/group option that- // would release unrelated protected secrets; fall back to a protected option only if the- // secret scope is absent.- const exact = grantOptions.find((o) => o.scope_type === 'secret');- return exact ?? grantOptions.find((o) => (o.unlock_material?.length ?? 0) > 0) ?? grantOptions[0];- }, [grantOptions, card]);+ const grantOptions = useMemo(() => card?.grant_options ?? [], [card]);+ const option = useMemo(() => grantOptions[0], [grantOptions]);const materials = useMemo(() => option?.unlock_material ?? [], [option]);+ const memberNames = useMemo(() => {+ if (isSign) return card?.secret_name ? [card.secret_name] : [];+ return option?.member_snapshot?.length ? option.member_snapshot : (card?.secret_names ?? (card?.secret_name ? [card.secret_name] : []));+ }, [card, isSign, option]);// Protected secret names to be granted (design: "show the protected secret names covered").- const protectedNames = useMemo(() => materials.map((m) => m.name), [materials]);+ const protectedNames = useMemo(() => {+ const materialNames = materials.map((m) => m.name);+ return materialNames.length ? materialNames : (card?.protected_secret_names ?? []);+ }, [card, materials]);+ const isProtected = isSign ? card?.protection === 'protected' : protectedNames.length > 0 || card?.protection === 'protected';const source = useMemo<VaultSourceSelector>(() => card?.source_selector ?? option?.source_selector ?? {}, [card, option]);const sourceChips = useMemo(() => {const chips: Array<{ key: string; label: string; icon: typeof KeyRound; mono?: boolean }> = [];@@ -153,7 +146,7 @@ export const VaultApprovalCard: React.FC<{// A request needs the browser VMK unlocked when it touches protected key material:// a protected sign, or an access whose fixed set includes protected members.- const needsUnlock = isSign ? isProtected : materials.length > 0;+ const needsUnlock = isSign ? isProtected : protectedNames.length > 0;const unlocked = vault.status === 'unlocked';useEffect(() => {@@ -180,21 +173,18 @@ export const VaultApprovalCard: React.FC<{const approveAccess = () =>finish(async () => {if (!option) throw new Error(t('vaults.approval.errors.noScope'));+ const grantId = option.grant_id?.trim();+ if (!grantId) throw new Error(t('vaults.approval.errors.failed'));// A protected secret with no hydrated unlock material means the request was read// without UI-audience hydration — fail clearly instead of taking the standard path// (which the daemon rejects for a protected secret anyway).if (isProtected && materials.length === 0) throw new Error(t('vaults.approval.errors.missingMaterial'));- // `scope_type`/`scope_ref` are the opaque binding the DEK blind box is sealed against- // and relayed with; the backend supplies them (grant_id bridge). Never shown to the user.- const bindScopeType = option.scope_type ?? '';- const bindScopeRef = option.scope_ref ?? '';if (materials.length === 0) {// No protected members (a hidden always-ask standard case) — metadata-only grant, no DEK.failIfNotOk(await api.createVaultGrant({request_id: request.id,- scope_type: bindScopeType,- scope_ref: bindScopeRef,+ grant_id: grantId,ttl_seconds: ttlSeconds,this_session_only: thisSessionOnly,}),@@ -210,8 +200,8 @@ export const VaultApprovalCard: React.FC<{const approvalNonce = crypto.getRandomValues(new Uint8Array(16));const context = await protectedDekReleaseBlindBoxContext(material.name, {kind: 'agent-deliver',- scopeType: bindScopeType,- scopeRef: bindScopeRef,+ scopeType: 'grant',+ scopeRef: grantId,ttlSecs: ttlSeconds,approval: { nonce: approvalNonce, expiresAtUnix },operationHash: await blindBoxAgentDeliverOperationHash(material.name, ttlSeconds),@@ -227,8 +217,7 @@ export const VaultApprovalCard: React.FC<{}failIfNotOk(await api.fulfillVaultAccessRequest(request.id, {- scope_type: bindScopeType,- scope_ref: bindScopeRef,+ grant_id: grantId,ttl_seconds: ttlSeconds,this_session_only: thisSessionOnly,agent_pubkey: agentPubkey,@@ -313,7 +302,15 @@ export const VaultApprovalCard: React.FC<{{/* Details — borderless list, sentence-case labels. */}<div className="flex flex-col gap-3.5"><DetailRow label={isSign ? t('vaults.approval.key') : t('vaults.approval.secret')}>- <span className="truncate font-mono text-[13px] font-semibold">{card.secret_name}</span>+ {memberNames.length > 1 ? (+ memberNames.map((name) => (+ <Badge key={name} variant="outline" className="font-mono">+ {name}+ </Badge>+ ))+ ) : (+ <span className="truncate font-mono text-[13px] font-semibold">{memberNames[0] ?? card?.secret_name ?? ''}</span>+ )}{isProtected ? (<Badge variant="warning">{t('vaults.protected')}</Badge>) : (diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 43f437f87..df65083f7 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useState } from 'react';-import { Check, Clock, Copy, Globe, History, Inbox, KeyRound, Layers, Link2, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';+import { Check, Clock, Copy, Globe, History, Inbox, KeyRound, Link2, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { CapabilityTabs } from './CapabilityTabs';@@ -163,8 +163,7 @@ function chipCountdown(rem: { h: number; m: number; s: number }): string {* (skills, tags, explicit env), so a mixed grant (e.g. same skill but a different `--tag`* or `--env`) stays distinguishable and revoke targets the right access. Returns a compact* `label` (truncated for the chip) and a `full` form (every token) for the tooltip and the- * revoke confirmation. For a legacy pre-refactor grant (no source_selector) it falls back to- * the scope ref / member names until the grant-id backend lands.+ * revoke confirmation.*/function describeGrant(g: VaultGrant, t: TFunction): { Icon: typeof KeyRound; label: string; full: string } {const compact = (tokens: string[]): string =>@@ -179,11 +178,6 @@ function describeGrant(g: VaultGrant, t: TFunction): { Icon: typeof KeyRound; laconst Icon = skills.length ? Puzzle : tags.length ? Tag : KeyRound;return { Icon, label: compact(tokens), full: tokens.join(', ') };}- // Legacy grant: no source_selector. Use the concrete scope ref / member names.- if (g.scope_ref) {- const Icon = g.scope_type === 'skill' ? Puzzle : g.scope_type === 'group' ? Layers : KeyRound;- return { Icon, label: g.scope_ref, full: g.scope_ref };- }const names = g.member_snapshot ?? [];if (names.length) return { Icon: KeyRound, label: compact(names), full: names.join(', ') };const count = t('vaults.grants.secretCount', { count: g.member_count || 0 });@@ -194,7 +188,7 @@ function describeGrant(g: VaultGrant, t: TFunction): { Icon: typeof KeyRound; la* Active-grant chip (design.pen `y4rw5Q` ACTIVE GRANTS row): a compact mint pill describing* how the protected set was selected (explicit secrets, a tag, or a skill), a live countdown,* and an inline × to revoke. A grant is a fixed protected set keyed by grant_id — the chip- * summarizes its `source_selector` (or the legacy scope during the bridge), never a group.+ * summarizes its `source_selector`, never a group.*/const GrantChip: React.FC<{ grant: VaultGrant; now: number; onRevoke: (grant: VaultGrant) => void }> = ({grant: g,diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 80a4f6b6e..fca8e5602 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -97,12 +97,9 @@ export type VaultGrant = {member_snapshot: string[];member_count: number;runtime_member_count: number;+ delivery_ready?: boolean;+ delivery_status?: string;one_shot?: boolean;- /** Legacy pre-refactor bridge only: the current backend still returns scope_type/scope_ref- * (no source_selector). Read to keep grant chips distinguishable until Track B lands; not- * part of the final product shape and never written by the UI. */- scope_type?: string;- scope_ref?: string;};type VaultBlindBox = {@@ -115,14 +112,9 @@ type VaultBlindBox = {* Browser-relayed protected access fulfillment. The browser releases each protected* DEK as an opaque HPKE blind box addressed to the resident avault agent and submits* ONLY `{name, dek_blindbox, approval}` per secret — never a raw DEK or plaintext.- *- * `scope_type`/`scope_ref` are NOT a product concept: they are the opaque binding the- * DEK blind box is sealed against (blindBoxAgentDeliverOperationHash), relayed verbatim- * pending the avault-side grant_id migration (Track A). The UI never shows them.*/export type VaultAccessFulfillmentPayload = {- scope_type?: string;- scope_ref?: string;+ grant_id?: string;session_id?: string | null;ttl_seconds?: number;this_session_only?: boolean;diff --git a/vibe/api.py b/vibe/api.pyindex 6a1b409b4..2354b56c9 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1332,12 +1332,15 @@ def _vault_engine():return create_sqlite_engine(paths.get_sqlite_state_path())-def get_vault_secrets(*, group: Optional[str] = None) -> dict:+def get_vault_secrets(*, tag: Optional[str] = None) -> dict:from storage import vault_serviceengine = _vault_engine()- with engine.connect() as conn:- secrets = vault_service.list_secrets(conn, group=group)+ try:+ with engine.connect() as conn:+ secrets = vault_service.list_secrets(conn, tag=tag)+ except vault_service.VaultServiceError as exc:+ raise VaultApiError(str(exc), code="invalid_request", status=409) from excreturn {"ok": True, "secrets": secrets}@@ -1409,10 +1412,15 @@ def create_vault_secret(payload: dict) -> dict:name = str(payload.get("name") or "").strip()if not vault_crypto.is_valid_secret_name(name):raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name")- tags = payload.get("tags") if isinstance(payload.get("tags"), list) else None+ tags = [str(tag) for tag in payload.get("tags", []) if isinstance(tag, str)] if isinstance(payload.get("tags"), list) else []policy = payload.get("policy") if isinstance(payload.get("policy"), dict) else Nonepublic_meta = payload.get("public_meta") if isinstance(payload.get("public_meta"), dict) else Nonelinks = payload.get("links") if isinstance(payload.get("links"), dict) else None+ try:+ if links and isinstance(links.get("skills"), list):+ tags.extend(vault_service.skill_tag(str(skill)) for skill in links["skills"] if isinstance(skill, str))+ except vault_service.VaultServiceError as exc:+ raise VaultApiError(str(exc), code="invalid_request", status=409) from excprotection = str(payload.get("protection") or "standard").strip().lower()establishing_vmk = bool(payload.get("establishing_vmk"))kind = str(payload.get("kind") or "static").strip().lower()@@ -1444,8 +1452,7 @@ def create_vault_secret(payload: dict) -> dict:conn,name=name,sealed=sealed,- group=str(payload.get("group") or vault_service.DEFAULT_GROUP),- tags=tags,+ tags=tags or None,protection=protection,kind=kind,signer_kind=signer_kind,@@ -1455,13 +1462,6 @@ def create_vault_secret(payload: dict) -> dict:establishing_vmk=establishing_vmk,provision_request_id=str(payload.get("provision_request_id") or "") or None,)- if links and isinstance(links.get("skills"), list):- vault_service.link_secret_to_skills(- conn,- name,- [str(skill) for skill in links["skills"] if isinstance(skill, str)],- source="agent",- )except vault_service.InvalidSecretNameError as exc:raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name") from excexcept vault_service.SecretExistsError as exc:@@ -1536,6 +1536,21 @@ def get_vault_provision_request(request_id: str) -> dict:return {"ok": True, "request": request}+def _vault_request_grant_members_and_purpose(request: dict) -> tuple[list[str], str]:+ card = request.get("card") if isinstance(request.get("card"), dict) else {}+ purpose = str(card.get("purpose") or "run")+ options = card.get("grant_options") if isinstance(card, dict) else None+ if isinstance(options, list) and options and isinstance(options[0], dict):+ option = options[0]+ purpose = str(option.get("purpose") or purpose)+ snapshot = option.get("member_snapshot")+ if isinstance(snapshot, list):+ members = [str(name) for name in snapshot if isinstance(name, str) and name]+ return sorted(set(members)), purpose+ secret_name = str(request.get("secret_name") or "").strip()+ return ([secret_name] if secret_name else []), purpose++def _vault_request_result(conn, request: dict) -> dict | None:from storage import vault_service@@ -1548,11 +1563,22 @@ def _vault_request_result(conn, request: dict) -> dict | None:requester = request.get("requester") if isinstance(request.get("requester"), dict) else {}delivery = request.get("delivery") if isinstance(request.get("delivery"), dict) else {}session_id = str(requester.get("session_id") or delivery.get("session_id") or "").strip() or None- grant = vault_service.find_active_grant_for_secret(- conn,- str(request["secret_name"]),- session_id=session_id,- )+ secret_name = str(request.get("secret_name") or "").strip()+ member_names, purpose = _vault_request_grant_members_and_purpose(request)+ if secret_name:+ grant = vault_service.find_active_grant_for_secret(+ conn,+ secret_name,+ session_id=session_id,+ purpose=purpose,+ )+ elif member_names:+ grant = vault_service.find_active_grant_for_secrets(+ conn,+ member_names,+ session_id=session_id,+ purpose=purpose,+ )if grant is None:return Nonereturn {"type": "grant", "grant": grant}@@ -1625,26 +1651,39 @@ def request_vault_access(payload: dict) -> dict:if not isinstance(payload, dict):raise VaultApiError("payload must be an object", code="invalid_payload")name = str(payload.get("name") or "").strip()- if not vault_crypto.is_valid_secret_name(name):+ raw_selector = payload.get("source_selector")+ source_selector = dict(raw_selector) if isinstance(raw_selector, dict) else None+ if not name and source_selector is None:+ raise VaultApiError("name or source_selector is required", code="invalid_request", status=409)+ if name and not vault_crypto.is_valid_secret_name(name):raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name")+ purpose = str(payload.get("purpose") or "run")engine = _vault_engine()try:with engine.begin() as conn:- vault_service.get_secret_meta(conn, name)+ if name:+ vault_service.get_secret_meta(conn, name)request = vault_service.create_access_request(conn,- name,+ name or None,+ source_selector=source_selector,+ purpose=purpose,requester=_vault_requester_payload(payload),delivery=_vault_delivery_payload(payload),expires_at=_expires_at_from_ttl(payload),audience=vault_service.REQUEST_AUDIENCE_AGENT,)except vault_service.SecretNotFoundError as exc:- raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc+ missing_name = name or str(exc)+ raise VaultApiError(f"secret '{missing_name}' not found", code="secret_not_found", status=404) from excexcept vault_service.NotGrantableError as exc:raise VaultApiError(str(exc), code="not_grantable", status=409) from exc+ except vault_service.KeypairNotValueDeliverableError as exc:+ raise VaultApiError(str(exc), code="keypair_not_value_deliverable", status=409) from excexcept vault_service.InvalidRequestError as exc:raise VaultApiError(str(exc), code="invalid_request", status=409) from exc+ except vault_service.VaultServiceError as exc:+ raise VaultApiError(str(exc), code="invalid_request", status=409) from excreturn {"ok": True, "request": request}@@ -1745,7 +1784,7 @@ def _grant_ttl_seconds(grant: dict) -> int:def _release_one_shot_agent_grant(grant: dict | None, *, reason: str) -> None:if not isinstance(grant, dict) or grant.get("one_shot") is not True:return- release_vault_agent_scopes(_grant_scope_payload(grant), reason=reason)+ release_vault_agent_scopes(_grant_release_payload(grant), reason=reason)def consume_one_shot_grants(grants: list[dict] | tuple[dict, ...] | None, *, reason: str) -> None:@@ -1790,7 +1829,7 @@ def _restore_access_request_after_failed_agent_grant(with contextlib.suppress(Exception), engine.begin() as conn:vault_service.restore_access_request_after_failed_grant(conn,- created_by_request_id=str(request_id),+ request_id=str(request_id),member_names=list(member_names or []),session_id=session_id,)@@ -1882,12 +1921,41 @@ def _access_request_secret_name(request_id: str) -> str:return name-def _grant_scope_payload(grant: dict) -> list[dict[str, str]]:- scope_type = str(grant.get("scope_type") or "")- scope_ref = str(grant.get("scope_ref") or "")- if not scope_type or not scope_ref:+def _grant_release_payload(grant: dict) -> list[dict[str, str]]:+ grant_id = str(grant.get("id") or grant.get("grant_id") or "")+ if not grant_id:return []- return [{"scope_type": scope_type, "scope_ref": scope_ref}]+ return [{"grant_id": grant_id}]+++def _grant_option_from_request(conn, request_id: str) -> dict[str, Any]:+ from storage import vault_service++ request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)+ if request.get("request_type") != "access":+ raise VaultApiError("grant approval must complete an access request", code="invalid_request", status=409)+ card = request.get("card") if isinstance(request.get("card"), dict) else {}+ options = card.get("grant_options") if isinstance(card, dict) else None+ if not isinstance(options, list) or len(options) != 1 or not isinstance(options[0], dict):+ raise VaultApiError("access request is missing a grant option", code="invalid_request", status=409)+ option = options[0]+ grant_id = str(option.get("grant_id") or "").strip()+ if not grant_id:+ raise VaultApiError("access request is missing a grant id", code="invalid_request", status=409)+ members = option.get("member_snapshot")+ if not isinstance(members, list) or not all(isinstance(name, str) and name for name in members):+ raise VaultApiError("access request has an invalid grant member snapshot", code="invalid_request", status=409)+ source_selector = option.get("source_selector")+ if not isinstance(source_selector, dict):+ raise VaultApiError("access request has an invalid source selector", code="invalid_request", status=409)+ purpose = str(option.get("purpose") or "run")+ return {+ "grant_id": grant_id,+ "member_names": list(members),+ "source_selector": source_selector,+ "purpose": purpose,+ "one_shot": bool(option.get("one_shot")),+ }def _cleanup_failed_agent_grant(@@ -1916,10 +1984,10 @@ def _cleanup_failed_agent_grant(release_scopes = (vault_service.agent_release_scopes_after_rows(conn, grant_rows)if grant_rows- else _grant_scope_payload(grant)+ else _grant_release_payload(grant))if force_release_scope:- forced_scopes = _grant_scope_payload(grant)+ forced_scopes = _grant_release_payload(grant)for scope in forced_scopes:raw_scope_members = grant.get("member_snapshot") or []scope_members = set(raw_scope_members if isinstance(raw_scope_members, list) else [])@@ -1927,8 +1995,7 @@ def _cleanup_failed_agent_grant(for active in conn.execute(select(vault_service.vault_grants).where(vault_service.vault_grants.c.status.in_(vault_service.ACTIVE_GRANT_STATES),- vault_service.vault_grants.c.scope_type == scope["scope_type"],- vault_service.vault_grants.c.scope_ref == scope["scope_ref"],+ vault_service.vault_grants.c.id == scope["grant_id"],)).mappings():active_row = dict(active)@@ -1942,7 +2009,7 @@ def _cleanup_failed_agent_grant(if not force_release_on_cleanup_failure:raiselogger.warning("%s: failed to update grant DB state; releasing resident scope", reason, exc_info=True)- release_scopes = _grant_scope_payload(grant)+ release_scopes = _grant_release_payload(grant)release_vault_agent_scopes(release_scopes, reason=reason)@@ -1951,29 +2018,34 @@ def create_vault_grant(payload: dict) -> dict:if not isinstance(payload, dict):raise VaultApiError("payload must be an object", code="invalid_payload")- try:- scope_type = str(payload["scope_type"])- scope_ref = str(payload["scope_ref"])- except KeyError as exc:- raise VaultApiError("scope_type and scope_ref are required", code="invalid_grant") from excttl = payload.get("ttl_seconds")try:ttl_seconds = int(ttl) if ttl is not None else Noneexcept (TypeError, ValueError) as exc:raise VaultApiError("ttl_seconds must be an integer", code="invalid_grant") from exc- request_id = payload.get("request_id") or payload.get("created_by_request_id")+ request_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 = Nonewith engine.begin() as conn:try:- grantable_members = vault_service.request_grantable_member_metas(- conn,- scope_type,- scope_ref,- str(request_id),- )+ option = _grant_option_from_request(conn, request_id)+ 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"]+ purpose = str(payload.get("purpose") or option["purpose"])+ grant_id = str(payload.get("grant_id") or "").strip()+ if grant_id and grant_id != option["grant_id"]:+ raise vault_service.InvalidRequestError("grant id does not match the approval request")+ if set(member_names) != set(option["member_names"]):+ raise vault_service.InvalidRequestError("grant members do not match the approval request")+ if source_selector != option["source_selector"]:+ raise vault_service.InvalidRequestError("grant source selector does not match the approval request")+ if purpose != option["purpose"]:+ raise vault_service.InvalidRequestError("grant purpose does not match the approval request")+ grantable_members = vault_service.request_grantable_member_metas(conn, request_id)except (vault_service.SecretNotFoundError,vault_service.RequestNotFoundError,@@ -1991,7 +2063,7 @@ def create_vault_grant(payload: dict) -> dict:if isinstance(preflight_error, vault_service.InvalidGrantError):raise VaultApiError(str(preflight_error), code="invalid_grant") from preflight_errorif not grantable_members:- raise VaultApiError(f"{scope_type}:{scope_ref} has no grantable static secrets", code="not_grantable", status=409)+ 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)@@ -2015,11 +2087,12 @@ def create_vault_grant(payload: dict) -> dict:with engine.begin() as conn:grant = vault_service.create_grant(conn,- scope_type=scope_type,- scope_ref=scope_ref,+ member_names=member_names,+ source_selector=source_selector,+ purpose=purpose,session_id=str(session_id) if session_id else None,ttl_seconds=ttl_seconds,- created_by_request_id=str(request_id),+ request_id=request_id,inherit_request_session=inherit_request_session,expected_member_names=expected_member_names,cache_ready=False,@@ -2040,8 +2113,8 @@ def create_vault_grant(payload: dict) -> dict:try:relay_ttl = _grant_ttl_seconds(grant)agent_result = avault_agent_grant(- scope_type=str(grant["scope_type"]),- scope_ref=str(grant["scope_ref"]),+ grant_id=str(grant["id"]),+ purpose=str(grant.get("purpose") or purpose),ttl_secs=relay_ttl,deks=agent_deks,expected_pubkey=expected_pubkey,@@ -2107,9 +2180,6 @@ def fulfill_vault_access_request(request_id: str, payload: dict | None = None) -request_id = str(request_id or "").strip()if not request_id:raise VaultApiError("request_id is required to fulfill protected access", code="missing_request_id")- if not body.get("scope_type") or not body.get("scope_ref"):- body.setdefault("scope_type", "secret")- body.setdefault("scope_ref", _access_request_secret_name(request_id))body["request_id"] = request_idcreated = create_vault_grant(body)return {@@ -5289,8 +5359,8 @@ def _agent_secret_payload(secret: dict, *, target_field: str) -> dict:def avault_agent_grant(*,- scope_type: str,- scope_ref: str,+ grant_id: str,+ purpose: str,ttl_secs: int,deks: list[dict],expected_pubkey: dict | None = None,@@ -5302,8 +5372,8 @@ def avault_agent_grant(validate_avault_agent_pubkey(expected_pubkey)try:return _avault_agent_client().grant(- scope_type=scope_type,- scope_ref=scope_ref,+ grant_id=grant_id,+ purpose=purpose,ttl_secs=ttl_secs,deks=deks,)@@ -5324,13 +5394,13 @@ def validate_avault_agent_pubkey(expected_pubkey: dict | None) -> None:raise AvaultError("avault agent public key mismatch")-def avault_agent_release(*, scope_type: str, scope_ref: str) -> dict:+def avault_agent_release(*, grant_id: str) -> dict:"""Drop a resident-agent protected grant if present."""from vibe.avault_agent import AvaultAgentClient, AvaultAgentError_require_avault_p2_surface("resident agent release")try:- return AvaultAgentClient(_avault_agent_manager().socket_path, timeout=1.0).release(scope_type=scope_type, scope_ref=scope_ref)+ return AvaultAgentClient(_avault_agent_manager().socket_path, timeout=1.0).release(grant_id=grant_id)except AvaultAgentError as exc:raise AvaultError(str(exc)) from exc@@ -5377,9 +5447,9 @@ def _fail_closed_resident_agent_after_release_failure() -> None:)-def _release_failed_grant_scope(scope_type: str, scope_ref: str, *, reason: str) -> None:+def _release_failed_grant_scope(grant_id: str, *, reason: str) -> None:try:- release_vault_agent_scopes([{"scope_type": scope_type, "scope_ref": scope_ref}], reason=reason)+ release_vault_agent_scopes([{"grant_id": grant_id}], reason=reason)except AvaultError:logger.warning("%s: failed to clear resident agent scope after failed grant relay",@@ -5389,39 +5459,35 @@ def _release_failed_grant_scope(scope_type: str, scope_ref: str, *, reason: str)def release_vault_agent_scopes(scopes: list[dict[str, str]], *, reason: str) -> None:- seen: set[tuple[str, str]] = set()+ seen: set[str] = set()for scope in scopes:- scope_type = str(scope.get("scope_type") or "")- scope_ref = str(scope.get("scope_ref") or "")- if not scope_type or not scope_ref:+ grant_id = str(scope.get("grant_id") or "")+ if not grant_id:continue- key = (scope_type, scope_ref)- if key in seen:+ if grant_id in seen:continue- seen.add(key)+ seen.add(grant_id)try:- avault_agent_release(scope_type=scope_type, scope_ref=scope_ref)+ avault_agent_release(grant_id=grant_id)except AvaultError as exc:if _agent_release_failure_is_absent(exc):- logger.debug("%s: resident agent absent while releasing grant %s:%s", reason, scope_type, scope_ref)+ logger.debug("%s: resident agent absent while releasing grant %s", reason, grant_id)continuetry:_fail_closed_resident_agent_after_release_failure()except OSError as reset_exc:raise AvaultError("failed to clear resident agent after release failure") from reset_exclogger.warning(- "%s: release failed for resident agent grant %s:%s; reset resident agent cache",+ "%s: release failed for resident agent grant %s; reset resident agent cache",reason,- scope_type,- scope_ref,+ grant_id,exc_info=True,)def avault_agent_deliver_run(*,- scope_type: str,- scope_ref: str,+ grant_id: str,secrets: list[dict],command: list[str],) -> dict:@@ -5431,8 +5497,7 @@ def avault_agent_deliver_run(_require_avault_p2_surface("resident agent deliver run")try:result = _avault_agent_manager().client(timeout=None).deliver_run(- scope_type=scope_type,- scope_ref=scope_ref,+ grant_id=grant_id,command=command,secrets=[_agent_secret_payload(secret, target_field="env") for secret in secrets],)@@ -5449,8 +5514,7 @@ def avault_agent_deliver_run(def avault_agent_deliver_fetch(*,- scope_type: str,- scope_ref: str,+ grant_id: str,name: str,sealed,request: dict,@@ -5461,8 +5525,7 @@ def avault_agent_deliver_fetch(_require_avault_p2_surface("resident agent deliver fetch")try:return _avault_agent_manager().client(timeout=_AVAULT_FETCH_TIMEOUT_SECONDS).deliver_fetch(- scope_type=scope_type,- scope_ref=scope_ref,+ grant_id=grant_id,name=name,envelope=_envelope_payload(sealed),request=request,@@ -5475,8 +5538,7 @@ def avault_agent_deliver_fetch(def avault_agent_deliver_inject(*,- scope_type: str,- scope_ref: str,+ grant_id: str,path: str,fmt: str,secrets: list[dict],@@ -5487,8 +5549,7 @@ def avault_agent_deliver_inject(_require_avault_p2_surface("resident agent deliver inject")try:result = _avault_agent_client().deliver_inject(- scope_type=scope_type,- scope_ref=scope_ref,+ grant_id=grant_id,path=str(path),fmt=fmt,secrets=[_agent_secret_payload(secret, target_field="key") for secret in secrets],diff --git a/vibe/avault_agent.py b/vibe/avault_agent.pyindex 580f5216f..9e96f21a7 100644--- a/vibe/avault_agent.py+++ b/vibe/avault_agent.py@@ -1,7 +1,7 @@"""Resident avault agent socket client.The resident agent is the protected-tier delivery boundary: Python sends names,-sealed envelopes, scopes, and browser-sealed DEK blind boxes over a Unix socket.+ sealed envelopes, grant ids, and browser-sealed DEK blind boxes over a Unix socket.Plaintext and DEKs stay inside ``avault``."""@@ -103,37 +103,35 @@ class AvaultAgentClient:def grant(self,*,- scope_type: str,- scope_ref: str,+ grant_id: str,+ purpose: str,ttl_secs: int,deks: list[dict[str, Any]],) -> dict[str, Any]:return self.request({"type": "grant",- "scope_type": scope_type,- "scope_ref": scope_ref,+ "grant_id": grant_id,+ "purpose": purpose,"ttl_secs": ttl_secs,"deks": deks,})- def release(self, *, scope_type: str, scope_ref: str) -> dict[str, Any]:- return self.request({"type": "release", "scope_type": scope_type, "scope_ref": scope_ref})+ def release(self, *, grant_id: str) -> dict[str, Any]:+ return self.request({"type": "release", "grant_id": grant_id})def deliver_run(self,*,- scope_type: str,- scope_ref: str,+ grant_id: str,command: list[str],secrets: list[dict[str, Any]],) -> dict[str, Any]:return self.request({"type": "deliver",- "scope_type": scope_type,- "scope_ref": scope_ref,+ "grant_id": grant_id,"mode": "run","command": command,"secrets": secrets,@@ -143,8 +141,7 @@ class AvaultAgentClient:def deliver_fetch(self,*,- scope_type: str,- scope_ref: str,+ grant_id: str,name: str,envelope: dict[str, Any],request: dict[str, Any],@@ -152,8 +149,7 @@ class AvaultAgentClient:return self.request({"type": "deliver",- "scope_type": scope_type,- "scope_ref": scope_ref,+ "grant_id": grant_id,"mode": "fetch","name": name,"envelope": envelope,@@ -164,8 +160,7 @@ class AvaultAgentClient:def deliver_inject(self,*,- scope_type: str,- scope_ref: str,+ grant_id: str,path: str,fmt: str,secrets: list[dict[str, Any]],@@ -173,8 +168,7 @@ class AvaultAgentClient:return self.request({"type": "deliver",- "scope_type": scope_type,- "scope_ref": scope_ref,+ "grant_id": grant_id,"mode": "inject","path": path,"format": fmt,diff --git a/vibe/cli.py b/vibe/cli.pyindex 0ed789bc2..071a1c31a 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -4719,7 +4719,7 @@ def cmd_vault_list(args):try:engine = _open_vault_engine()with engine.connect() as conn:- secrets = vault_service.list_secrets(conn, group=getattr(args, "group", None))+ secrets = vault_service.list_secrets(conn, tag=getattr(args, "tag", None))_print_cli_payload("vault_secrets", secrets=secrets)return 0except Exception as exc:@@ -4733,7 +4733,7 @@ def cmd_vault_discover(args):try:engine = _open_vault_engine()with engine.connect() as conn:- secrets = vault_service.list_secrets(conn, group=getattr(args, "group", None))+ secrets = vault_service.list_secrets(conn, tag=getattr(args, "tag", None))kind = (getattr(args, "kind", None) or "").strip()if kind:secrets = [secret for secret in secrets if secret.get("kind") == kind]@@ -4825,6 +4825,7 @@ def _expire_agent_grant_after_missing(*,requester: dict | None = None,delivery: dict | None = None,+ purpose: str = "run",) -> dict | None:from storage import vault_service@@ -4838,6 +4839,7 @@ def _expire_agent_grant_after_missing(name,requester=requester or {"source": "cli", "pid": os.getpid()},delivery=delivery or {},+ purpose=purpose,)if first_request is None and isinstance(resolved.get("request"), dict):first_request = resolved["request"]@@ -5261,12 +5263,14 @@ def _resolve_vault_run_delivery(engine, mapping: dict[str, str], command_argv: lrequester, delivery, session_id = _vault_cli_delivery_context(args, mode="run", command=command_argv)metas = _preflight_vault_run_batch(engine, mapping)- if metas and {str(meta.get("protection") or "standard") for meta in metas.values()} == {"protected"}:+ tiers = {str(meta.get("protection") or "standard") for meta in metas.values()}+ if metas and tiers == {"protected"}:with engine.begin() as conn:common_grant = vault_service.find_active_grant_for_secrets(conn,list(mapping.values()),session_id=session_id,+ purpose="run",reserve_one_shot=True,)if common_grant is not None:@@ -5274,6 +5278,21 @@ def _resolve_vault_run_delivery(engine, mapping: dict[str, str], command_argv: l{"name": vault_name, "env": env_name, "envelope": vault_service.get_protected_envelope(conn, vault_name)}for env_name, vault_name in mapping.items()]+ if metas and tiers == {"standard"}:+ with engine.begin() as conn:+ standard_secrets = [+ {"name": vault_name, "env": env_name, "envelope": vault_service.get_envelope(conn, vault_name)}+ for env_name, vault_name in mapping.items()+ ]+ common_grant = vault_service.find_active_grant_for_secrets(+ conn,+ list(mapping.values()),+ session_id=session_id,+ purpose="run",+ reserve_one_shot=True,+ )+ if isinstance(common_grant, dict) and common_grant.get("one_shot") is True:+ return None, [common_grant], standard_secretssecrets = []grant: dict | None = Noneone_shot_grants: list[dict] = []@@ -5288,6 +5307,7 @@ def _resolve_vault_run_delivery(engine, mapping: dict[str, str], command_argv: lresolved = vault_service.resolve_secret_access(conn,vault_name,+ purpose="run",requester=requester,delivery=delivery,reserve_one_shot=True,@@ -5311,7 +5331,7 @@ def _resolve_vault_run_delivery(engine, mapping: dict[str, str], command_argv: lcurrent_grant = resolved["grant"]if grant is None:grant = current_grant- elif grant["scope_type"] != current_grant["scope_type"] or grant["scope_ref"] != current_grant["scope_ref"]:+ elif grant["id"] != current_grant["id"]:if current_grant.get("one_shot") is True:one_shot_grants.append(current_grant)pre_delivery_error = _mixed_grants_error(@@ -5349,6 +5369,7 @@ def _resolve_single_vault_delivery(*,requester: dict,delivery: dict,+ purpose: str = "run",) -> tuple[dict | None, dict | None, object]:from storage import vault_service@@ -5356,6 +5377,7 @@ def _resolve_single_vault_delivery(resolved = vault_service.resolve_secret_access(conn,name,+ purpose=purpose,requester=requester,delivery=delivery,reserve_one_shot=True,@@ -5381,12 +5403,14 @@ def _resolve_vault_inject_delivery(engine, names: list[str], *, path: str, fmt:requester, delivery, session_id = _vault_cli_delivery_context(args, mode="inject", path=path, format=fmt)metas = _preflight_vault_inject_batch(engine, names)- if metas and {str(meta.get("protection") or "standard") for meta in metas.values()} == {"protected"}:+ tiers = {str(meta.get("protection") or "standard") for meta in metas.values()}+ if metas and tiers == {"protected"}:with engine.begin() as conn:common_grant = vault_service.find_active_grant_for_secrets(conn,names,session_id=session_id,+ purpose="inject",reserve_one_shot=True,)if common_grant is not None:@@ -5394,6 +5418,21 @@ def _resolve_vault_inject_delivery(engine, names: list[str], *, path: str, fmt:{"name": name, "key": name, "envelope": vault_service.get_protected_envelope(conn, name)}for name in names]+ if metas and tiers == {"standard"}:+ with engine.begin() as conn:+ standard_secrets = [+ {"name": name, "key": name, "envelope": vault_service.get_envelope(conn, name)}+ for name in names+ ]+ common_grant = vault_service.find_active_grant_for_secrets(+ conn,+ names,+ session_id=session_id,+ purpose="inject",+ reserve_one_shot=True,+ )+ if isinstance(common_grant, dict) and common_grant.get("one_shot") is True:+ return None, [common_grant], standard_secretssecrets = []grant: dict | None = Noneone_shot_grants: list[dict] = []@@ -5408,6 +5447,7 @@ def _resolve_vault_inject_delivery(engine, names: list[str], *, path: str, fmt:resolved = vault_service.resolve_secret_access(conn,name,+ purpose="inject",requester=requester,delivery=delivery,reserve_one_shot=True,@@ -5431,7 +5471,7 @@ def _resolve_vault_inject_delivery(engine, names: list[str], *, path: str, fmt:current_grant = resolved["grant"]if grant is None:grant = current_grant- elif grant["scope_type"] != current_grant["scope_type"] or grant["scope_ref"] != current_grant["scope_ref"]:+ elif grant["id"] != current_grant["id"]:if current_grant.get("one_shot") is True:one_shot_grants.append(current_grant)pre_delivery_error = _mixed_grants_error(@@ -5525,8 +5565,7 @@ def cmd_vault_run(args):) as output_bridge:handoff_started = Trueresult = api.avault_agent_deliver_run(- scope_type=grant["scope_type"],- scope_ref=grant["scope_ref"],+ grant_id=grant["id"],secrets=secrets,command=_agent_run_command(command_argv,@@ -5559,6 +5598,7 @@ def cmd_vault_run(args):sorted(set(mapping.values())),requester=requester,delivery=delivery,+ purpose="run",)_print_task_error(TaskCliError("protected grant expired; approve the request again", code="approval_required", help_command=help_command))return 1@@ -5822,7 +5862,7 @@ def _vault_request_pending_message(name: str, request: dict[str, object], *, hasreturn (f"Recorded a request for '{name}'. The user fulfills request {request['id']} from the Vaults page pending "f"requests list by opening its Provide secret row; that request-specific form preserves the requested "- f"group, policy, and skill links. Then use: vibe vault run --env {name} -- <command>"+ f"tags, policy, and skill links. Then use: vibe vault run --env {name} -- <command>")return (f"Recorded a request for '{name}'. The user fulfills it from the Vaults page pending requests list "@@ -6051,12 +6091,12 @@ def cmd_vault_fetch(args):name,requester=requester,delivery=delivery,+ purpose="fetch",)handoff_started = Trueif grant is not None:result = api.avault_agent_deliver_fetch(- scope_type=grant["scope_type"],- scope_ref=grant["scope_ref"],+ grant_id=grant["id"],name=name,sealed=sealed,request=request,@@ -6112,6 +6152,7 @@ def cmd_vault_fetch(args):[name],requester=requester,delivery=delivery,+ purpose="fetch",)_print_task_error(TaskCliError("protected grant expired; approve the request again", code="approval_required", help_command=help_command))return 1@@ -6226,8 +6267,7 @@ def cmd_vault_inject(args):handoff_started = Trueif grant is not None:api.avault_agent_deliver_inject(- scope_type=grant["scope_type"],- scope_ref=grant["scope_ref"],+ grant_id=grant["id"],path=resolved_out,fmt=fmt,secrets=secrets,@@ -6275,6 +6315,7 @@ def cmd_vault_inject(args):keys,requester=requester,delivery=delivery,+ purpose="inject",)_print_task_error(TaskCliError("protected grant expired; approve the request again", code="approval_required", help_command=help_command))return 1@@ -9680,7 +9721,7 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe vault list --help",)- vault_list_parser.add_argument("--group", help="Only list secrets in this group")+ vault_list_parser.add_argument("--tag", help="Only list secrets with this tag")_add_json_noop(vault_list_parser)vault_discover_parser = vault_subparsers.add_parser(@@ -9690,7 +9731,7 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe vault discover --help",)- vault_discover_parser.add_argument("--group", help="Only list secrets in this group")+ vault_discover_parser.add_argument("--tag", help="Only list secrets with this tag")vault_discover_parser.add_argument("--kind", choices=["static", "keypair"], help="Only show this secret kind")vault_discover_parser.add_argument("--protection", choices=["standard", "protected"], help="Only show this protection tier")_add_json_noop(vault_discover_parser)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex ef4254877..f0c0bc0c9 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2657,7 +2657,10 @@ def _vault_error_response(exc):def vault_secrets_get():from vibe import api- return jsonify(api.get_vault_secrets(group=request.args.get("group") or None))+ try:+ return jsonify(api.get_vault_secrets(tag=request.args.get("tag") or None))+ except ValueError as exc:+ return _vault_error_response(exc)@app.route("/api/vault/pubkey", methods=["GET"])