Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(vault): wait for protected approvals in run and fetch (#826)

Call White2331f57b843e
diff --git a/storage/vault_service.py b/storage/vault_service.py
index ac69df049..67f4e7c1a 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -47,6 +47,7 @@ SKILL_TAG_PREFIX = "skill:"
DEFAULT_ENV_GRANT_TTL_SECONDS = 300
DEFAULT_TAG_GRANT_TTL_SECONDS = 900
DEFAULT_AUTHZ_CHALLENGE_TTL_SECONDS = 120
+DEFAULT_REQUEST_TTL_SECONDS = 30 * 60
AUTH_FACTOR_REGISTRATION_AUTHZ_OPERATION = "authorize_webauthn_factor_registration"
DEFAULT_GRANT_TTL_SECONDS = {
"env": DEFAULT_ENV_GRANT_TTL_SECONDS,
@@ -289,6 +290,10 @@ def _now() -> str:
return datetime.now(timezone.utc).isoformat()
+def _request_expiry(ttl_seconds: int = DEFAULT_REQUEST_TTL_SECONDS) -> str:
+ return (datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)).isoformat()
+
+
def _parse_iso_datetime(value: str | None) -> datetime | None:
if not value:
return None
@@ -904,6 +909,151 @@ def _request_json_payloads(row: dict[str, Any]) -> tuple[Any, Any]:
return _loads(row.get("requester")), _loads(row.get("delivery"))
+def _request_waiter(delivery: Any) -> dict[str, Any]:
+ if not isinstance(delivery, dict):
+ return {}
+ waiter = delivery.get("waiter")
+ return waiter if isinstance(waiter, dict) else {}
+
+
+def _request_waiter_active(row: dict[str, Any]) -> bool:
+ _, delivery = _request_json_payloads(row)
+ waiter = _request_waiter(delivery)
+ if waiter.get("status") != "active":
+ return False
+ deadline = _parse_iso_datetime(waiter.get("deadline_at"))
+ return deadline is not None and deadline > datetime.now(timezone.utc)
+
+
+def _grant_owner_waiter_active(conn: Connection, grants: list[dict[str, Any]]) -> bool:
+ request_ids = [
+ str(grant.get("request_id") or "")
+ for grant in grants
+ if isinstance(grant, dict) and str(grant.get("request_id") or "")
+ ]
+ if not request_ids:
+ return False
+ rows = conn.execute(select(vault_requests).where(vault_requests.c.id.in_(request_ids))).mappings()
+ return any(_request_waiter_active(dict(row)) for row in rows)
+
+
+def _skip_sibling_callbacks_for_completed_waiter(conn: Connection, request_id: str) -> None:
+ grant_rows = [
+ dict(row)
+ for row in conn.execute(select(vault_grants).where(vault_grants.c.request_id == request_id)).mappings()
+ ]
+ if not grant_rows:
+ return
+ sibling_ids: set[str] = set()
+ for grant in grant_rows:
+ session_id = str(grant.get("session_id") or "")
+ purpose = str(grant.get("purpose") or "")
+ member_set = {str(name) for name in (_loads(grant.get("member_snapshot")) or []) if str(name)}
+ if not session_id or not purpose or not member_set:
+ continue
+ rows = conn.execute(
+ select(vault_requests).where(
+ vault_requests.c.id != request_id,
+ vault_requests.c.request_type == "access",
+ vault_requests.c.status == "approved",
+ vault_requests.c.callback_status == "pending",
+ )
+ ).mappings()
+ for row in rows:
+ row_dict = dict(row)
+ try:
+ option = _request_grant_option(row_dict)
+ except InvalidRequestError:
+ continue
+ if (
+ _request_session_id(row_dict) == session_id
+ and option.purpose == purpose
+ and _request_members_are_subset(row_dict, member_set)
+ ):
+ sibling_ids.add(str(row_dict["id"]))
+ if sibling_ids:
+ conn.execute(
+ vault_requests.update()
+ .where(vault_requests.c.id.in_(sorted(sibling_ids)), vault_requests.c.callback_status == "pending")
+ .values(callback_status="skipped")
+ )
+
+
+def _update_request_waiter(
+ conn: Connection,
+ request_id: str,
+ *,
+ waiter_id: str,
+ status: str,
+ deadline_at: str | None = None,
+ completed_at: str | None = None,
+ timed_out_at: str | None = None,
+) -> dict[str, Any]:
+ row = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().first()
+ if row is None:
+ raise RequestNotFoundError(request_id)
+ row_dict = dict(row)
+ _, delivery = _request_json_payloads(row_dict)
+ delivery_payload = dict(delivery) if isinstance(delivery, dict) else {}
+ current = _request_waiter(delivery_payload)
+ if current and current.get("id") and current.get("id") != waiter_id:
+ raise InvalidRequestError("request waiter id does not match")
+ waiter = {
+ "id": waiter_id,
+ "status": status,
+ "updated_at": _now(),
+ }
+ if deadline_at:
+ waiter["deadline_at"] = deadline_at
+ elif current.get("deadline_at"):
+ waiter["deadline_at"] = current["deadline_at"]
+ if completed_at:
+ waiter["completed_at"] = completed_at
+ if timed_out_at:
+ waiter["timed_out_at"] = timed_out_at
+ delivery_payload["waiter"] = waiter
+
+ values: dict[str, Any] = {"delivery": json.dumps(delivery_payload)}
+ if status == "completed" and row_dict.get("callback_status") == "pending":
+ values["callback_status"] = "skipped"
+
+ conn.execute(vault_requests.update().where(vault_requests.c.id == request_id).values(**values))
+ if status == "completed":
+ _skip_sibling_callbacks_for_completed_waiter(conn, request_id)
+ updated = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()
+ return _request_row_payload(dict(updated), conn=conn, audience=REQUEST_AUDIENCE_AGENT)
+
+
+def arm_request_waiter(conn: Connection, request_id: str, *, waiter_id: str, deadline_at: str) -> dict[str, Any]:
+ return _update_request_waiter(
+ conn,
+ request_id,
+ waiter_id=waiter_id,
+ status="active",
+ deadline_at=deadline_at,
+ )
+
+
+def complete_request_waiter(conn: Connection, request_id: str, *, waiter_id: str) -> dict[str, Any]:
+ return _update_request_waiter(
+ conn,
+ request_id,
+ waiter_id=waiter_id,
+ status="completed",
+ completed_at=_now(),
+ )
+
+
+def timeout_request_waiter(conn: Connection, request_id: str, *, waiter_id: str) -> dict[str, Any]:
+ return _update_request_waiter(
+ conn,
+ request_id,
+ waiter_id=waiter_id,
+ status="timed_out",
+ timed_out_at=_now(),
+ )
+
+
def _request_session_id(row: dict[str, Any]) -> str | None:
requester, delivery = _request_json_payloads(row)
for payload in (requester, delivery):
@@ -1119,8 +1269,12 @@ def request_callback_ready(conn: Connection, row: dict[str, Any]) -> bool:
members. Every other terminal state (provision/sign/deny/expire, and standard grants which are
ready on approval) is deliverable immediately; no active covering grant does not block forever.
"""
+ if _request_waiter_active(row):
+ return False
if str(row.get("request_type") or "") == "access" and str(row.get("status") or "") == "approved":
grants = _request_covering_grant_payloads(conn, row)
+ if grants and _grant_owner_waiter_active(conn, grants):
+ return False
if grants and not any(grant.get("delivery_ready") for grant in grants):
return False
return True
@@ -2800,7 +2954,7 @@ def create_access_request(
status="pending",
message_id=message_id,
created_at=_now(),
- expires_at=expires_at,
+ expires_at=expires_at or _request_expiry(),
)
)
audit(conn, "access_requested", secret_name=name, requester=requester, delivery=delivery_payload, request_id=request_id)
@@ -2853,7 +3007,7 @@ def create_sign_request(
status="pending",
message_id=message_id,
created_at=_now(),
- expires_at=expires_at,
+ expires_at=expires_at or _request_expiry(),
)
)
audit(conn, "sign_requested", secret_name=name, requester=requester, delivery=delivery_payload, request_id=request_id)
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index 0c6c29b77..53f4e399c 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -10,6 +10,7 @@ import io
import json
import shutil
import threading
+import time
from pathlib import Path
from unittest.mock import Mock
@@ -40,6 +41,8 @@ def _ns(**kw):
spec_json=None,
wait=None,
no_wait=False,
+ approval_wait=0,
+ no_approval_wait=False,
json=False,
out=None,
file=None,
@@ -91,6 +94,24 @@ def _set_protected_grant(name: str, *, session_id: str | None = None, purpose: s
return _grant_from_request(conn, req, session_id=session_id)
+def _approve_next_pending_access_request(*, session_id: str | None = None, purpose: str = "run") -> dict:
+ deadline = time.monotonic() + 2
+ while time.monotonic() < deadline:
+ with cli._open_vault_engine().begin() as conn:
+ requests = []
+ for request in vault_service.list_requests(conn, status="pending"):
+ card = request.get("card") or {}
+ if request.get("request_type") == "access" and card.get("grant_options"):
+ requests.append(request)
+ if requests:
+ request = requests[0]
+ grant = _grant_from_request(conn, request, session_id=session_id)
+ assert grant["purpose"] == purpose
+ return {"request": request, "grant": grant}
+ time.sleep(0.01)
+ raise AssertionError("pending access request was not created")
+
+
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(
@@ -975,6 +996,66 @@ def test_run_uses_session_bound_protected_grant(tmp_path, capfd, monkeypatch):
assert deliver.call_args.kwargs["grant_id"]
+def test_run_waits_for_protected_approval_then_delivers(tmp_path, capfd, monkeypatch):
+ from vibe import api
+
+ monkeypatch.chdir(tmp_path)
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(conn, name="PROTECTED_KEY", protection="protected", sealed=_sealed("protected"))
+ approved: dict = {}
+
+ def approve_request():
+ approved.update(_approve_next_pending_access_request(session_id="ses_cli", purpose="run"))
+
+ approver = threading.Thread(target=approve_request)
+ approver.start()
+ deliver = Mock(return_value={"exit_code": 0})
+ monkeypatch.setattr(api, "avault_agent_deliver_run", deliver)
+ monkeypatch.setattr(api, "avault_deliver_run", Mock())
+
+ code = cli.cmd_vault_run(
+ _ns(env=["PROTECTED_KEY"], command_argv=["python3", "-c", "pass"], session_id="ses_cli", approval_wait=2)
+ )
+ approver.join(timeout=2)
+ captured = capfd.readouterr()
+
+ assert code == 0
+ assert not approver.is_alive()
+ assert "Waiting for Vault approval in the browser for vault run" in captured.err
+ deliver.assert_called_once()
+ assert deliver.call_args.kwargs["grant_id"] == approved["grant"]["id"]
+ with cli._open_vault_engine().connect() as conn:
+ row = conn.execute(vault_requests.select().where(vault_requests.c.id == approved["request"]["id"])).mappings().one()
+ assert row["callback_status"] == "skipped"
+ assert json.loads(row["delivery"])["waiter"]["status"] == "completed"
+
+
+def test_run_approval_wait_timeout_keeps_callback_armed_for_later_resolution(capfd):
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(conn, name="PROTECTED_KEY", protection="protected", sealed=_sealed("protected"))
+
+ code = cli.cmd_vault_run(
+ _ns(env=["PROTECTED_KEY"], command_argv=["python3", "-c", "pass"], session_id="ses_cli", approval_wait=0.01)
+ )
+ captured = capfd.readouterr()
+ payload = json.loads(captured.err[captured.err.index("{") :])
+
+ assert code == 1
+ assert payload["code"] == "approval_wait_timeout"
+ assert payload["details"]["callback_expected"] is True
+ request_id = payload["details"]["request_id"]
+ with cli._open_vault_engine().begin() as conn:
+ row = conn.execute(vault_requests.select().where(vault_requests.c.id == request_id)).mappings().one()
+ assert row["status"] == "pending"
+ assert row["callback_status"] is None
+ assert json.loads(row["delivery"])["waiter"]["status"] == "timed_out"
+ request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)
+ _grant_from_request(conn, request, session_id="ses_cli")
+ resolved = dict(conn.execute(vault_requests.select().where(vault_requests.c.id == request_id)).mappings().one())
+ assert resolved["callback_status"] == "pending"
+ assert vault_service.request_callback_ready(conn, resolved) is True
+
+
def test_fetch_uses_session_bound_protected_grant(capfd, monkeypatch):
from vibe import api
diff --git a/tests/test_vault_fetch.py b/tests/test_vault_fetch.py
index c8c318c0d..bb5f7a9db 100644
--- a/tests/test_vault_fetch.py
+++ b/tests/test_vault_fetch.py
@@ -8,6 +8,8 @@ from __future__ import annotations
import argparse
import json
+import threading
+import time
import pytest
@@ -34,6 +36,8 @@ def _ns(**kw):
data=None,
data_file=None,
output=None,
+ approval_wait=0,
+ no_approval_wait=False,
json=False,
)
base.update(kw)
@@ -98,6 +102,23 @@ def _set_protected_grant(name: str, *, allow_host: list[str], session_id: str |
return _grant_from_request(conn, req, session_id=session_id)
+def _approve_next_pending_access_request(*, session_id: str | None = None) -> dict:
+ deadline = time.monotonic() + 2
+ while time.monotonic() < deadline:
+ with cli._open_vault_engine().begin() as conn:
+ requests = []
+ for request in vault_service.list_requests(conn, status="pending"):
+ card = request.get("card") or {}
+ if request.get("request_type") == "access" and card.get("grant_options"):
+ requests.append(request)
+ if requests:
+ request = requests[0]
+ grant = _grant_from_request(conn, request, session_id=session_id)
+ return {"request": request, "grant": grant}
+ time.sleep(0.01)
+ raise AssertionError("pending access request was not created")
+
+
def _set_always_ask_grant(name: str, *, allow_host: list[str]) -> dict:
with cli._open_vault_engine().begin() as conn:
vault_service.create_secret(
@@ -212,6 +233,127 @@ def test_fetch_persists_protected_approval_request_without_grant(capfd):
assert requests[0]["delivery"]["host"] == "api.github.com"
+def test_fetch_waits_for_protected_approval_then_delivers(capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="GH_PAT",
+ protection="protected",
+ sealed=_sealed("gh_pat"),
+ policy={"allowed_hosts": ["api.github.com"]},
+ )
+ approved: dict = {}
+
+ def approve_request():
+ approved.update(_approve_next_pending_access_request(session_id="ses_cli"))
+
+ approver = threading.Thread(target=approve_request)
+ approver.start()
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": '{"ok":true}'})
+ monkeypatch.setattr(api, "avault_agent_deliver_fetch", fetch)
+ monkeypatch.setattr(api, "avault_deliver_fetch", Mock())
+
+ code = cli.cmd_vault_fetch(
+ _ns(auth="GH_PAT", url="https://api.github.com/repos/o/r", session_id="ses_cli", approval_wait=2)
+ )
+ approver.join(timeout=2)
+ captured = capfd.readouterr()
+
+ assert code == 0
+ assert captured.out == '{"ok":true}'
+ assert "Waiting for Vault approval in the browser for vault fetch" in captured.err
+ assert not approver.is_alive()
+ fetch.assert_called_once()
+ assert fetch.call_args.kwargs["grant_id"] == approved["grant"]["id"]
+
+
+def test_fetch_revalidates_policy_after_approval_wait(capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="GH_PAT",
+ protection="protected",
+ sealed=_sealed("gh_pat"),
+ policy={"allowed_hosts": ["api.github.com"]},
+ )
+
+ def approve_and_change_policy(args, exc, *, timeout, help_command, operation):
+ request_id = exc.details["request_id"]
+ with cli._open_vault_engine().begin() as conn:
+ request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)
+ _grant_from_request(conn, request, session_id="ses_cli")
+ conn.execute(
+ vault_service.vault_secrets.update()
+ .where(vault_service.vault_secrets.c.name == "GH_PAT")
+ .values(policy=json.dumps({"allowed_hosts": ["api.example.com"]}))
+ )
+
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(cli, "_wait_for_vault_delivery_approval", approve_and_change_policy)
+ monkeypatch.setattr(api, "avault_agent_deliver_fetch", fetch)
+ monkeypatch.setattr(api, "avault_deliver_fetch", Mock())
+
+ code = cli.cmd_vault_fetch(
+ _ns(auth="GH_PAT", url="https://api.github.com/repos/o/r", session_id="ses_cli", approval_wait=2)
+ )
+ captured = capfd.readouterr()
+
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "host_not_allowed"
+ fetch.assert_not_called()
+
+
+def test_fetch_revalidates_output_after_approval_wait(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ out = tmp_path / "response.json"
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="GH_PAT",
+ protection="protected",
+ sealed=_sealed("gh_pat"),
+ policy={"allowed_hosts": ["api.github.com"]},
+ )
+
+ def approve_and_block_output(args, exc, *, timeout, help_command, operation):
+ request_id = exc.details["request_id"]
+ with cli._open_vault_engine().begin() as conn:
+ request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)
+ _grant_from_request(conn, request, session_id="ses_cli")
+ out.mkdir()
+
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(cli, "_wait_for_vault_delivery_approval", approve_and_block_output)
+ monkeypatch.setattr(api, "avault_agent_deliver_fetch", fetch)
+ monkeypatch.setattr(api, "avault_deliver_fetch", Mock())
+
+ code = cli.cmd_vault_fetch(
+ _ns(
+ auth="GH_PAT",
+ url="https://api.github.com/repos/o/r",
+ session_id="ses_cli",
+ approval_wait=2,
+ output=str(out),
+ )
+ )
+ captured = capfd.readouterr()
+
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "output_unwritable"
+ fetch.assert_not_called()
+
+
def test_fetch_header_auth_request_shape(tmp_path, capfd, monkeypatch):
from unittest.mock import Mock
diff --git a/tests/test_vault_request_callbacks.py b/tests/test_vault_request_callbacks.py
index a0076cc92..416f10dd3 100644
--- a/tests/test_vault_request_callbacks.py
+++ b/tests/test_vault_request_callbacks.py
@@ -329,6 +329,70 @@ def test_request_callback_ready_defers_approved_access_until_grant_ready(vault):
assert vs.request_callback_ready(None, {"request_type": "access", "status": "denied", "id": "y"}) is True
+def test_request_callback_ready_defers_while_cli_waiter_is_active(vault):
+ future = (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()
+ with vault.begin() as conn:
+ vs.create_secret(conn, name="WAIT_GR_KEY", sealed=_sealed(), protection="protected")
+ req = vs.create_access_request(conn, "WAIT_GR_KEY", requester={"session_id": "ses_wait"})
+ vs.arm_request_waiter(conn, req["id"], waiter_id="vw_test", deadline_at=future)
+ _grant_from_request(conn, req)
+
+ row = _row(conn, req["id"])
+ assert row["callback_status"] == "pending"
+ assert vs.request_callback_ready(conn, row) is False
+
+ vs.timeout_request_waiter(conn, req["id"], waiter_id="vw_test")
+ row = _row(conn, req["id"])
+ assert vs.request_callback_ready(conn, row) is True
+
+
+def test_complete_request_waiter_suppresses_redundant_callback(vault):
+ future = (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()
+ with vault.begin() as conn:
+ vs.create_secret(conn, name="DONE_GR_KEY", sealed=_sealed(), protection="protected")
+ req = vs.create_access_request(conn, "DONE_GR_KEY", requester={"session_id": "ses_done"})
+ vs.arm_request_waiter(conn, req["id"], waiter_id="vw_done", deadline_at=future)
+ _grant_from_request(conn, req)
+
+ vs.complete_request_waiter(conn, req["id"], waiter_id="vw_done")
+
+ row = _row(conn, req["id"])
+ assert row["callback_status"] == "skipped"
+ assert vs.list_pending_request_callbacks(conn) == []
+
+
+def test_covering_grant_owner_waiter_suppresses_sibling_callbacks(vault):
+ future = (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()
+ with vault.begin() as conn:
+ vs.create_secret(conn, name="WAIT_A", sealed=_sealed("a"), protection="protected", tags=["deploy"])
+ vs.create_secret(conn, name="WAIT_B", sealed=_sealed("b"), protection="protected", tags=["deploy"])
+ primary = vs.create_access_request(
+ conn,
+ source_selector={"tags": ["deploy"]},
+ requester={"session_id": "ses_wait"},
+ delivery={"session_id": "ses_wait"},
+ )
+ sibling = vs.create_access_request(
+ conn,
+ "WAIT_A",
+ requester={"session_id": "ses_wait"},
+ delivery={"session_id": "ses_wait"},
+ )
+ vs.arm_request_waiter(conn, primary["id"], waiter_id="vw_primary", deadline_at=future)
+ _grant_from_request(conn, primary)
+
+ sibling_row = _row(conn, sibling["id"])
+ assert sibling_row["status"] == "approved"
+ assert sibling_row["callback_status"] == "pending"
+ assert vs.request_callback_ready(conn, sibling_row) is False
+
+ vs.complete_request_waiter(conn, primary["id"], waiter_id="vw_primary")
+
+ assert _callback_status(conn, primary["id"]) == "skipped"
+ assert _callback_status(conn, sibling["id"]) == "skipped"
+ assert vs.list_pending_request_callbacks(conn) == []
+
+
def test_request_callback_ready_defers_sibling_access_until_covering_grant_ready(vault):
with vault.begin() as conn:
vs.create_secret(conn, name="GR_A", sealed=_sealed("a"), protection="protected", tags=["deploy"])
diff --git a/vibe/cli.py b/vibe/cli.py
index ded000c59..4a66a5c26 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -88,6 +88,7 @@ DOCTOR_REPAIR_DRY_RUN_MESSAGES = {
"stale-restart-state": "Would remove stale restart metadata and refresh runtime status.",
}
+DEFAULT_VAULT_APPROVAL_WAIT_SECONDS = 9 * 60
WATCH_STARTUP_STABLE_RUNNING_SECONDS = 1.5
WATCH_STARTUP_JITTER_BUFFER_SECONDS = 1.0
@@ -200,6 +201,23 @@ def _add_pagination_args(parser, *, help_command: str) -> None:
parser.error_help_command = help_command
+def _add_vault_approval_wait_args(parser, *, default_seconds: int = DEFAULT_VAULT_APPROVAL_WAIT_SECONDS) -> None:
+ parser.add_argument(
+ "--approval-wait",
+ type=_non_negative_float,
+ metavar="SECONDS",
+ help=(
+ "Wait this many seconds for a protected approval before returning approval_wait_timeout "
+ f"(default {default_seconds})."
+ ),
+ )
+ parser.add_argument(
+ "--no-approval-wait",
+ action="store_true",
+ help="Return approval_required immediately instead of waiting for browser approval.",
+ )
+
+
def _page_request_from_args(args, *, help_command: str) -> PageRequest | None:
try:
return make_page_request(
@@ -6187,13 +6205,30 @@ def cmd_vault_run(args):
help_command=help_command,
example="vibe vault run --env OPENAI_API_KEY -- python sync.py",
)
- grant, one_shot_grants, secrets = _resolve_vault_run_delivery(
- engine,
- mapping,
- command_argv,
- args=args,
- source_selector=source_selector,
- )
+ approval_wait = _vault_approval_wait_seconds(args, help_command=help_command)
+ waited_for_approval = False
+ while True:
+ try:
+ grant, one_shot_grants, secrets = _resolve_vault_run_delivery(
+ engine,
+ mapping,
+ command_argv,
+ args=args,
+ source_selector=source_selector,
+ )
+ break
+ except TaskCliError as exc:
+ if exc.code == "approval_required" and approval_wait > 0 and not waited_for_approval:
+ _wait_for_vault_delivery_approval(
+ args,
+ exc,
+ timeout=approval_wait,
+ help_command=help_command,
+ operation="vault run",
+ )
+ waited_for_approval = True
+ continue
+ raise
except vault_service.SecretNotFoundError as exc:
_print_task_error(TaskCliError(f"secret '{exc}' not found", code="secret_not_found", help_command=help_command))
return 1
@@ -6313,7 +6348,7 @@ def _wait_for_provision(request_id: str, *, timeout: float, poll_interval: float
deadline = time.monotonic() + timeout
engine = _open_vault_engine()
- while time.monotonic() < deadline:
+ while True:
with engine.begin() as conn:
try:
request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)
@@ -6328,12 +6363,27 @@ def _wait_for_provision(request_id: str, *, timeout: float, poll_interval: float
return None
-def _wait_for_vault_request(request_id: str, *, timeout: float, poll_interval: float = 2.0) -> dict | None:
+def _vault_access_delivery_ready(request: dict, result: dict | None) -> bool:
+ if request.get("request_type") != "access":
+ return True
+ if not isinstance(result, dict) or result.get("type") != "grant":
+ return True
+ grant = result.get("grant")
+ return not isinstance(grant, dict) or bool(grant.get("delivery_ready"))
+
+
+def _wait_for_vault_request(
+ request_id: str,
+ *,
+ timeout: float,
+ poll_interval: float = 2.0,
+ require_delivery_ready: bool = False,
+) -> dict | None:
from storage import vault_service
deadline = time.monotonic() + timeout
engine = _open_vault_engine()
- while time.monotonic() < deadline:
+ while True:
with engine.begin() as conn:
try:
request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)
@@ -6343,7 +6393,8 @@ def _wait_for_vault_request(request_id: str, *, timeout: float, poll_interval: f
if request.get("status") == "approved":
result = api._vault_request_result(conn, request)
if request.get("status") in {"approved", "denied", "expired", "failed", "fulfilled"}:
- return {"request": request, "result": result}
+ if not (require_delivery_ready and not _vault_access_delivery_ready(request, result)):
+ return {"request": request, "result": result}
remaining = deadline - time.monotonic()
if remaining <= 0:
break
@@ -6351,6 +6402,105 @@ def _wait_for_vault_request(request_id: str, *, timeout: float, poll_interval: f
return None
+def _vault_approval_wait_seconds(args, *, help_command: str) -> float:
+ wait_value = getattr(args, "approval_wait", None)
+ no_wait = bool(getattr(args, "no_approval_wait", False))
+ if no_wait and wait_value is not None:
+ raise TaskCliError("use --approval-wait or --no-approval-wait, not both", code="invalid_wait", help_command=help_command)
+ if no_wait:
+ return 0.0
+ if wait_value is None:
+ return float(DEFAULT_VAULT_APPROVAL_WAIT_SECONDS)
+ return float(wait_value)
+
+
+def _approval_wait_callback_expected(args) -> bool:
+ return not _vault_callback_disabled(args) and bool(_vault_cli_session_id(args))
+
+
+def _approval_wait_timeout_hint(args, request_id: str) -> str:
+ if _approval_wait_callback_expected(args):
+ return (
+ "Avibe will resume this Session when the user approves or denies the request. "
+ "After approval, retry the original vault run/fetch command."
+ )
+ return f"Check the request later with: vibe vault await {request_id}"
+
+
+def _print_vault_approval_wait_notice(request_id: str, *, timeout: float, operation: str) -> None:
+ print(
+ f"Waiting for Vault approval in the browser for {operation} "
+ f"(request {request_id}, timeout {timeout:g}s)...",
+ file=sys.stderr,
+ flush=True,
+ )
+
+
+def _vault_terminal_request_error(request: dict, *, help_command: str) -> TaskCliError | None:
+ request_id = str(request.get("id") or "")
+ status = str(request.get("status") or "")
+ if status == "denied":
+ return TaskCliError(
+ f"Vault request '{request_id}' was denied",
+ code="request_denied",
+ help_command=help_command,
+ details={"request_id": request_id},
+ )
+ if status == "expired":
+ return TaskCliError(
+ f"Vault request '{request_id}' expired before approval",
+ code="request_expired",
+ help_command=help_command,
+ details={"request_id": request_id},
+ )
+ if status == "failed":
+ return TaskCliError(
+ f"Vault request '{request_id}' failed",
+ code="request_failed",
+ help_command=help_command,
+ details={"request_id": request_id},
+ )
+ return None
+
+
+def _wait_for_vault_delivery_approval(args, exc: TaskCliError, *, timeout: float, help_command: str, operation: str) -> None:
+ from storage import vault_service
+
+ request_id = str((exc.details or {}).get("request_id") or "").strip()
+ if not request_id:
+ raise exc
+ waiter_id = f"vw_{uuid4().hex[:12]}"
+ deadline_at = (datetime.now(timezone.utc) + timedelta(seconds=timeout)).isoformat()
+ engine = _open_vault_engine()
+ with engine.begin() as conn:
+ vault_service.arm_request_waiter(conn, request_id, waiter_id=waiter_id, deadline_at=deadline_at)
+ _print_vault_approval_wait_notice(request_id, timeout=timeout, operation=operation)
+ waited = _wait_for_vault_request(request_id, timeout=timeout, require_delivery_ready=True)
+ if waited is None:
+ try:
+ with engine.begin() as conn:
+ vault_service.timeout_request_waiter(conn, request_id, waiter_id=waiter_id)
+ except Exception:
+ logger.debug("failed to mark vault request waiter timed out", exc_info=True)
+ raise TaskCliError(
+ f"Vault approval request '{request_id}' is still waiting for the user",
+ code="approval_wait_timeout",
+ hint=_approval_wait_timeout_hint(args, request_id),
+ help_command=help_command,
+ details={
+ "request_id": request_id,
+ "timeout_seconds": timeout,
+ "callback_expected": _approval_wait_callback_expected(args),
+ },
+ )
+ request = waited.get("request") or {}
+ terminal_error = _vault_terminal_request_error(request, help_command=help_command)
+ with engine.begin() as conn:
+ vault_service.complete_request_waiter(conn, request_id, waiter_id=waiter_id)
+ if terminal_error is not None:
+ raise terminal_error
+
+
def cmd_vault_request(args):
from storage import vault_crypto, vault_service
@@ -6753,6 +6903,88 @@ def _read_request_body(args):
return None
+def _validate_vault_fetch_output(output: str | None, *, help_command: str) -> None:
+ if not output:
+ return
+ out_path = Path(output)
+ if out_path.exists():
+ # Require an existing regular file: a dir can't be written as a file, and a
+ # FIFO / device (e.g. /dev/full) passes os.access but write_bytes can block or
+ # fail AFTER the credential-bearing request already ran.
+ writable = out_path.is_file() and os.access(out_path, os.W_OK)
+ else:
+ writable = out_path.parent.is_dir() and os.access(out_path.parent, os.W_OK)
+ if not writable:
+ raise TaskCliError(
+ f"output path is not writable: {output}",
+ code="output_unwritable",
+ help_command=help_command,
+ )
+
+
+def _build_vault_fetch_request(
+ engine,
+ *,
+ name: str,
+ url: str,
+ host: str,
+ method: str,
+ headers: dict,
+ body,
+ help_command: str,
+) -> dict:
+ from storage import vault_service
+
+ # Read policy in a read connection. The host check runs BEFORE handing the envelope to
+ # avault, so a disallowed target never even unwraps the secret. Callers run this both before
+ # and after an approval wait so a mid-wait metadata edit cannot leave a stale allowlist or auth
+ # injection policy in the egress frame.
+ with engine.connect() as conn:
+ policy = vault_service.get_secret_policy(conn, name)
+ meta = vault_service.get_secret_meta(conn, name)
+ if meta.get("kind") == "keypair":
+ raise vault_service.KeypairNotValueDeliverableError(
+ f"{name} is a signing key; use vault_sign instead of value delivery"
+ )
+ allowed = policy.get("allowed_hosts") or []
+ if not allowed:
+ raise TaskCliError(
+ f"secret '{name}' has no allowed_hosts; it cannot be used via fetch "
+ "(configure allowed hosts in the Vaults UI)",
+ code="proxy_unbound",
+ help_command=help_command,
+ )
+ if not _host_allowed(host, allowed):
+ raise TaskCliError(
+ f"host {host!r} is not allowed for secret '{name}'",
+ code="host_not_allowed",
+ help_command=help_command,
+ details={"host": host, "allowed_hosts": allowed},
+ )
+ auth = policy.get("auth") or {"type": "bearer"}
+ if auth.get("type") == "header":
+ # Defensive: set-time validation blocks new Host auth-headers; this also guards
+ # legacy / hand-edited policies. Reject BEFORE handing off so a bad policy never
+ # even unwraps the secret.
+ _reject_forbidden_header(auth.get("name", ""), help_command=help_command)
+
+ auth_type = auth.get("type") or "bearer"
+ if auth_type == "header":
+ inject = {"type": "header", "name": auth.get("name", "")}
+ elif auth_type == "query":
+ inject = {"type": "query", "name": auth.get("name", "")}
+ else:
+ inject = {"type": "bearer"}
+ return {
+ "method": method,
+ "url": url,
+ "allowed_hosts": allowed,
+ "headers": headers,
+ "body": body.decode("utf-8") if isinstance(body, (bytes, bytearray)) else body,
+ "inject": inject,
+ }
+
+
def cmd_vault_fetch(args):
from urllib.parse import urlsplit
@@ -6786,21 +7018,7 @@ def cmd_vault_fetch(args):
# the target itself (an existing dir, or an existing file we can't write), not just the
# parent.
output = getattr(args, "output", None)
- if output:
- out_path = Path(output)
- if out_path.exists():
- # Require an existing regular file: a dir can't be written as a file, and a
- # FIFO / device (e.g. /dev/full) passes os.access but write_bytes can block or
- # fail AFTER the credential-bearing request already ran.
- writable = out_path.is_file() and os.access(out_path, os.W_OK)
- else:
- writable = out_path.parent.is_dir() and os.access(out_path.parent, os.W_OK)
- if not writable:
- raise TaskCliError(
- f"output path is not writable: {output}",
- code="output_unwritable",
- help_command=help_command,
- )
+ _validate_vault_fetch_output(output, help_command=help_command)
host = urlsplit(url).hostname
if not host:
raise TaskCliError(f"invalid --url: {url!r}", code="invalid_url", help_command=help_command)
@@ -6816,65 +7034,53 @@ def cmd_vault_fetch(args):
)
engine = _open_vault_engine()
- # Read policy + envelope in a read connection. The host check runs BEFORE handing the
- # envelope to avault, so a disallowed target never even unwraps the secret.
- with engine.connect() as conn:
- policy = vault_service.get_secret_policy(conn, name)
- meta = vault_service.get_secret_meta(conn, name)
- if meta.get("kind") == "keypair":
- raise vault_service.KeypairNotValueDeliverableError(
- f"{name} is a signing key; use vault_sign instead of value delivery"
- )
- allowed = policy.get("allowed_hosts") or []
- if not allowed:
- raise TaskCliError(
- f"secret '{name}' has no allowed_hosts; it cannot be used via fetch "
- "(configure allowed hosts in the Vaults UI)",
- code="proxy_unbound",
- help_command=help_command,
- )
- if not _host_allowed(host, allowed):
- raise TaskCliError(
- f"host {host!r} is not allowed for secret '{name}'",
- code="host_not_allowed",
- help_command=help_command,
- details={"host": host, "allowed_hosts": allowed},
- )
- auth = policy.get("auth") or {"type": "bearer"}
- if auth.get("type") == "header":
- # Defensive: set-time validation blocks new Host auth-headers; this also guards
- # legacy / hand-edited policies. Reject BEFORE handing off so a bad policy never
- # even unwraps the secret.
- _reject_forbidden_header(auth.get("name", ""), help_command=help_command)
- # Envelope resolution happens below through resolve_secret_access so
- # protected-tier secrets can use an active resident-agent grant.
-
- # Hand the envelope + request to avault: it injects the credential at egress, performs
- # the request, and returns ONLY the response (status/headers/body) — the value never
- # returns here. avault re-enforces the allowed_hosts allowlist before decrypting.
- auth_type = auth.get("type") or "bearer"
- if auth_type == "header":
- inject = {"type": "header", "name": auth.get("name", "")}
- elif auth_type == "query":
- inject = {"type": "query", "name": auth.get("name", "")}
- else:
- inject = {"type": "bearer"}
- request = {
- "method": method,
- "url": url,
- "allowed_hosts": allowed,
- "headers": headers,
- "body": body.decode("utf-8") if isinstance(body, (bytes, bytearray)) else body,
- "inject": inject,
- }
- requester, delivery, _session_id = _vault_cli_delivery_context(args, mode="fetch", host=host, method=method)
- grant, one_shot_grant, sealed = _resolve_single_vault_delivery(
+ request = _build_vault_fetch_request(
engine,
- name,
- requester=requester,
- delivery=delivery,
- purpose="fetch",
+ name=name,
+ url=url,
+ host=host,
+ method=method,
+ headers=headers,
+ body=body,
+ help_command=help_command,
)
+ requester, delivery, _session_id = _vault_cli_delivery_context(args, mode="fetch", host=host, method=method)
+ approval_wait = _vault_approval_wait_seconds(args, help_command=help_command)
+ waited_for_approval = False
+ while True:
+ try:
+ grant, one_shot_grant, sealed = _resolve_single_vault_delivery(
+ engine,
+ name,
+ requester=requester,
+ delivery=delivery,
+ purpose="fetch",
+ )
+ break
+ except TaskCliError as exc:
+ if exc.code == "approval_required" and approval_wait > 0 and not waited_for_approval:
+ _wait_for_vault_delivery_approval(
+ args,
+ exc,
+ timeout=approval_wait,
+ help_command=help_command,
+ operation="vault fetch",
+ )
+ waited_for_approval = True
+ continue
+ raise
+ if waited_for_approval:
+ _validate_vault_fetch_output(output, help_command=help_command)
+ request = _build_vault_fetch_request(
+ engine,
+ name=name,
+ url=url,
+ host=host,
+ method=method,
+ headers=headers,
+ body=body,
+ help_command=help_command,
+ )
handoff_started = True
if grant is not None:
result = api.avault_agent_deliver_fetch(
@@ -10609,6 +10815,7 @@ def build_parser():
)
vault_run_parser.add_argument("--tag", action="append", metavar="TAG", help="Inject all value-deliverable secrets with this tag. Repeatable.")
vault_run_parser.add_argument("--skill", action="append", metavar="SKILL", help="Sugar for --tag skill:SKILL. Repeatable.")
+ _add_vault_approval_wait_args(vault_run_parser)
vault_run_parser.add_argument("command_argv", nargs=argparse.REMAINDER, help="-- followed by the command to run")
_add_json_noop(vault_run_parser)
@@ -10632,6 +10839,7 @@ def build_parser():
vault_fetch_parser.add_argument("--data", help="Request body (string)")
vault_fetch_parser.add_argument("--data-file", help="Request body read from this file")
vault_fetch_parser.add_argument("--output", help="Write the response body to this file instead of stdout")
+ _add_vault_approval_wait_args(vault_fetch_parser)
_add_json_noop(vault_fetch_parser)
vault_access_parser = vault_subparsers.add_parser(