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.

Support Vault request specs (#748)

Call White8028e4b97b08
diff --git a/docs/plans/vaults-p0-implementation.md b/docs/plans/vaults-p0-implementation.md
index 334316318..fdfdb548f 100644
--- a/docs/plans/vaults-p0-implementation.md
+++ b/docs/plans/vaults-p0-implementation.md
@@ -160,7 +160,7 @@ create_secret(name, value, *, group, tags, protection, policy) # validates nam
list_secrets(*, group=None, skill=None) -> [masked] # never returns values; masked preview
rotate_secret(name, new_value) / delete_secret(name)
resolve(names, *, mode, requester) -> {name: value} # P0: standard only (machine key); audit 'delivered'
-create_provision_request(name, *, reason, skill, requester) -> request
+create_provision_request(name, *, reason, spec, requester) -> request
fulfill_provision(request_id, value, *, protection) # store secret; mark fulfilled; wake-up (name only)
audit(event, **fields)
```
@@ -191,7 +191,7 @@ vibe vault list [--group G] [--skill S(P1)] [--json]
vibe vault rm NAME
vibe vault run --env NAME[,N2] [--env LOCAL=NAME] [--env-skill S(P1)] -- cmd... # M1, promoted
vibe vault fetch --auth NAME [curl-like args] # M4, promoted
-vibe vault request NAME [--reason s] [--skill s] [--wait s | --no-wait] # dynamic ask
+vibe vault request NAME [--reason s] [--spec file|- | --spec-json json] [--wait s | --no-wait] # dynamic ask
# help-only (NOT in agent-facing guidance):
vibe vault export --env NAME[,N2] # M1', eval "$(...)"
vibe vault inject --keys A,B --out f [--format dotenv|json|yaml|toml] [--ttl 10m] # M2
diff --git a/docs/plans/vaults.md b/docs/plans/vaults.md
index acb40a305..5decfef4c 100644
--- a/docs/plans/vaults.md
+++ b/docs/plans/vaults.md
@@ -215,7 +215,10 @@ not promoted.
fences) → `provision` request. Web: inline **SecureInputCard** (out-of-band TLS
submit). IM: `🔐 Agent requests OPENAI_API_KEY → [Open Vaults](…?request=id)`.
`vibe vault request NAME --wait` long-polls; `--no-wait` → `hook_send` on
-fulfillment. **Wake-up carries the name only, never the value.**
+fulfillment. Creation hints use `--spec file|-` or `--spec-json` and may include
+non-secret fields such as `protection`, `group`, `tags`, `policy`, and
+`links.skills`; the request CLI intentionally has no `--skill` flag. **Wake-up
+carries the name only, never the value.**
## 7. Crypto & auth (Q1: password + passkey, layered)
@@ -458,7 +461,7 @@ Internal UDS `/internal/vault/*`: `resolve`, `provision`, `sign`, `fetch`,
CLI `vibe vault …`: create/set is intentionally not exposed to agents; values
enter through browser-side sealed/blind-box payloads. `list [--skill S] [--group G] [--tag t] [--json]` · `rm` · `run` (promoted) ·
-`fetch` (promoted) · `sign` (promoted) · `request` · `link/unlink --skill S NAME` ·
+`fetch` (promoted) · `sign` (promoted) · `request [--spec file|- | --spec-json json]` · `link/unlink --skill S NAME` ·
`audit` · `key export/import` · `import 1password [--vault V]` (§13.5) · `export` /
`inject` (help-only, not promoted). No `vibe vault get`; no command prints a value.
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 4c01571d8..a29393b9e 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -20,6 +20,7 @@ import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any
+from urllib.parse import urlsplit
from sqlalchemy import or_, select
from sqlalchemy.engine import Connection
@@ -41,6 +42,28 @@ SUPPORTED_SIGNATURE_SCHEMES = {
REQUEST_AUDIENCE_AGENT = "agent"
REQUEST_AUDIENCE_UI = "ui"
REQUEST_AUDIENCES = {REQUEST_AUDIENCE_AGENT, REQUEST_AUDIENCE_UI}
+PROVISION_SPEC_FORBIDDEN_KEYS = {
+ "value",
+ "sealed",
+ "envelope",
+ "blind_box",
+ "ciphertext",
+ "nonce",
+ "wrap_meta",
+ "private_key",
+ "secret",
+}
+PROVISION_SPEC_ALLOWED_KEYS = {
+ "kind",
+ "protection",
+ "group",
+ "description",
+ "tags",
+ "policy",
+ "links",
+}
+PROVISION_SPEC_ALLOWED_POLICY_KEYS = {"allowed_hosts", "auth"}
+PROVISION_SPEC_ALLOWED_AUTH_KEYS = {"type", "name"}
@dataclass(frozen=True)
@@ -224,6 +247,160 @@ def _public_meta(raw: str | None) -> dict[str, Any]:
return payload if isinstance(payload, dict) else {}
+def _reject_provision_spec_secret_fields(value: Any, *, path: str = "spec") -> None:
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if str(key) in PROVISION_SPEC_FORBIDDEN_KEYS:
+ raise VaultServiceError(f"{path}.{key} is not allowed in vault request spec")
+ _reject_provision_spec_secret_fields(item, path=f"{path}.{key}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ _reject_provision_spec_secret_fields(item, path=f"{path}[{index}]")
+
+
+def _string_list(value: Any, *, field: str) -> list[str]:
+ if value is None:
+ return []
+ if not isinstance(value, list):
+ raise VaultServiceError(f"{field} must be an array of strings")
+ out: list[str] = []
+ for item in value:
+ if not isinstance(item, str):
+ raise VaultServiceError(f"{field} must be an array of strings")
+ stripped = item.strip()
+ if stripped:
+ out.append(stripped)
+ return out
+
+
+def _normalize_allowed_host(value: str, *, field: str) -> str:
+ raw = value.strip().lower()
+ if not raw:
+ raise VaultServiceError(f"{field} must contain non-empty host strings")
+ leading_dot = raw.startswith(".")
+ hostish = raw[1:] if leading_dot else raw
+ if "://" in hostish:
+ host = urlsplit(hostish).hostname or ""
+ elif hostish.startswith("[") or "/" in hostish or "?" in hostish or "#" in hostish or hostish.count(":") == 1:
+ host = urlsplit(f"//{hostish}").hostname or ""
+ else:
+ host = hostish
+ if not host or any(ch.isspace() for ch in host) or "/" in host or "*" in host:
+ raise VaultServiceError(f"{field} entries must be hostnames, URLs, or host:port values")
+ return f".{host}" if leading_dot else host
+
+
+def _allowed_host_list(value: Any, *, field: str) -> list[str]:
+ return list(dict.fromkeys(_normalize_allowed_host(item, field=field) for item in _string_list(value, field=field)))
+
+
+def _optional_string(value: Any, *, field: str) -> str | None:
+ if value is None:
+ return None
+ if not isinstance(value, str):
+ raise VaultServiceError(f"{field} must be a string")
+ stripped = value.strip()
+ return stripped or None
+
+
+def normalize_provision_spec(spec: Any) -> dict[str, Any]:
+ """Return non-secret creation hints for a provision request.
+
+ The request spec is agent-provided metadata only. It can pre-fill the browser
+ form and propose skill links, but it must never carry plaintext or sealed
+ value material.
+ """
+
+ if spec is None:
+ return {}
+ if not isinstance(spec, dict):
+ raise VaultServiceError("vault request spec must be a JSON object")
+ _reject_provision_spec_secret_fields(spec)
+ extra_keys = set(spec) - PROVISION_SPEC_ALLOWED_KEYS
+ if extra_keys:
+ raise VaultServiceError(f"unsupported vault request spec fields: {', '.join(sorted(extra_keys))}")
+
+ normalized: dict[str, Any] = {}
+ kind = spec.get("kind")
+ if kind is not None:
+ if not isinstance(kind, str):
+ raise VaultServiceError("spec.kind must be a string")
+ kind = kind.strip().lower()
+ if kind != "static":
+ raise VaultServiceError("spec.kind currently supports only 'static' for provision requests")
+ normalized["kind"] = kind
+
+ protection = spec.get("protection")
+ if protection is not None:
+ if not isinstance(protection, str):
+ raise VaultServiceError("spec.protection must be a string")
+ protection = protection.strip().lower()
+ if protection not in {"standard", "protected"}:
+ 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 None
+ if description:
+ normalized["description"] = description
+
+ tags = _string_list(spec.get("tags"), field="spec.tags") if "tags" in spec else []
+ if tags:
+ normalized["tags"] = tags
+
+ policy = spec.get("policy")
+ if policy is not None:
+ if not isinstance(policy, dict):
+ raise VaultServiceError("spec.policy must be an object")
+ extra_policy_keys = set(policy) - PROVISION_SPEC_ALLOWED_POLICY_KEYS
+ if extra_policy_keys:
+ raise VaultServiceError(f"unsupported spec.policy fields: {', '.join(sorted(extra_policy_keys))}")
+ normalized_policy: dict[str, Any] = {}
+ allowed_hosts = _allowed_host_list(policy.get("allowed_hosts"), field="spec.policy.allowed_hosts") if "allowed_hosts" in policy else []
+ if allowed_hosts:
+ normalized_policy["allowed_hosts"] = allowed_hosts
+ auth = policy.get("auth")
+ if auth is not None:
+ if not isinstance(auth, dict):
+ raise VaultServiceError("spec.policy.auth must be an object")
+ extra_auth_keys = set(auth) - PROVISION_SPEC_ALLOWED_AUTH_KEYS
+ if extra_auth_keys:
+ raise VaultServiceError(f"unsupported spec.policy.auth fields: {', '.join(sorted(extra_auth_keys))}")
+ raw_auth_type = auth.get("type") or "bearer"
+ if not isinstance(raw_auth_type, str):
+ raise VaultServiceError("spec.policy.auth.type must be a string")
+ auth_type = raw_auth_type.strip().lower()
+ if auth_type not in {"bearer", "header", "query"}:
+ raise VaultServiceError("spec.policy.auth.type must be bearer, header, or query")
+ normalized_auth: dict[str, Any] = {"type": auth_type}
+ auth_name = _optional_string(auth.get("name"), field="spec.policy.auth.name") if "name" in auth else None
+ if auth_type in {"header", "query"}:
+ if not auth_name:
+ raise VaultServiceError("spec.policy.auth.name is required for header/query auth")
+ normalized_auth["name"] = auth_name
+ elif auth_name:
+ normalized_auth["name"] = auth_name
+ normalized_policy["auth"] = normalized_auth
+ if normalized_policy:
+ normalized["policy"] = normalized_policy
+
+ links = spec.get("links")
+ if links is not None:
+ if not isinstance(links, dict):
+ raise VaultServiceError("spec.links must be an object")
+ extra_link_keys = set(links) - {"skills"}
+ if extra_link_keys:
+ 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}
+
+ return normalized
+
+
def _meta_payload(row: dict[str, Any]) -> dict[str, Any]:
"""Masked, value-free metadata for a secret row."""
public_meta = _public_meta(row.get("public_meta"))
@@ -737,6 +914,23 @@ def _require_row(conn: Connection, name: str) -> dict[str, Any]:
return dict(row)
+def fulfill_pending_provision_requests_for_secret(
+ conn: Connection,
+ name: str,
+ *,
+ decided_at: str | None = None,
+) -> None:
+ conn.execute(
+ vault_requests.update()
+ .where(
+ vault_requests.c.request_type == "provision",
+ vault_requests.c.secret_name == name,
+ vault_requests.c.status == "pending",
+ )
+ .values(status="fulfilled", decided_at=decided_at or _now())
+ )
+
+
def create_secret(
conn: Connection,
*,
@@ -752,6 +946,7 @@ def create_secret(
policy: dict[str, Any] | None = None,
public_meta: dict[str, Any] | None = None,
establishing_vmk: bool = False,
+ provision_request_id: str | None = None,
) -> dict[str, Any]:
"""Create a secret from a caller-supplied encrypted envelope; return masked metadata.
@@ -771,7 +966,22 @@ def create_secret(
raise VaultServiceError(f"invalid vault secret kind: {kind!r}")
if kind != "keypair" and signer_kind is not None:
raise VaultServiceError("signer_kind is only valid for keypair secrets")
- if conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.name == name)).first() is not None:
+ provision_row: dict[str, Any] | None = None
+ existing_secret = conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.name == name)).first() is not None
+ if provision_request_id:
+ _expire_pending_requests(conn)
+ provision_row = _load_request_row(conn, provision_request_id)
+ if provision_row.get("request_type") != "provision":
+ raise InvalidRequestError("secret create must complete a provision request")
+ if provision_row.get("secret_name") != name:
+ raise InvalidRequestError("provision request secret name does not match")
+ if provision_row.get("status") == "expired":
+ raise InvalidRequestError("provision request has expired")
+ if provision_row.get("status") == "fulfilled" and existing_secret:
+ raise SecretExistsError(name)
+ if provision_row.get("status") != "pending":
+ raise InvalidRequestError("provision request is not pending")
+ if existing_secret:
raise SecretExistsError(name)
if establishing_vmk and protection == "protected":
@@ -817,21 +1027,43 @@ def create_secret(
# SecretExistsError → 409 so the racing already-fulfilled ask is handled, not a 500.
raise SecretExistsError(name) from exc
audit(conn, "created", secret_name=name)
- # Any pending dynamic-ask (provision) request for this name is now satisfied,
- # regardless of which create path stored it (CLI / API / inline card) — so a
- # `vibe vault request --wait` resolves instead of timing out.
- conn.execute(
- vault_requests.update()
- .where(
- vault_requests.c.request_type == "provision",
- vault_requests.c.secret_name == name,
- vault_requests.c.status == "pending",
+ decided_at = _now()
+ if provision_row is not None:
+ result = conn.execute(
+ vault_requests.update()
+ .where(vault_requests.c.id == provision_row["id"], vault_requests.c.status == "pending")
+ .values(status="fulfilled", decided_at=decided_at)
)
- .values(status="fulfilled", decided_at=_now())
- )
+ if result.rowcount != 1:
+ raise InvalidRequestError("provision request is not pending")
+ # Once the secret exists, every same-name pending provision ask is satisfied. A
+ # request-specific create still uses only that request's spec for the secret metadata,
+ # but sibling waiters should not keep timing out or resurfacing stale rows.
+ fulfill_pending_provision_requests_for_secret(conn, name, decided_at=decided_at)
return _meta_payload(_require_row(conn, name))
+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
+
+
def get_secret_meta(conn: Connection, name: str) -> dict[str, Any]:
return _meta_payload(_require_row(conn, name))
@@ -1033,7 +1265,7 @@ def create_provision_request(
name: str,
*,
reason: str | None = None,
- skill: str | None = None,
+ spec: dict[str, Any] | None = None,
requester: Any = None,
message_id: str | None = None,
) -> dict[str, Any]:
@@ -1047,12 +1279,13 @@ def create_provision_request(
now = _now()
already = conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.name == name)).first() is not None
status = "fulfilled" if already else "pending"
- card = _secure_input_card(name, request_id=request_id, reason=reason, skill=skill)
+ normalized_spec = normalize_provision_spec(spec)
+ card = _secure_input_card(name, request_id=request_id, reason=reason, spec=normalized_spec)
delivery_payload: dict[str, Any] = {"card": card}
if reason:
delivery_payload["reason"] = reason
- if skill:
- delivery_payload["skill"] = skill
+ if normalized_spec:
+ delivery_payload["spec"] = normalized_spec
conn.execute(
vault_requests.insert().values(
id=request_id,
@@ -1094,11 +1327,7 @@ def fulfill_provision(
sealed=sealed,
group=group,
description=description,
- )
- conn.execute(
- vault_requests.update()
- .where(vault_requests.c.id == request_id)
- .values(status="fulfilled", decided_at=_now())
+ provision_request_id=request_id,
)
return meta
@@ -1108,18 +1337,21 @@ def _secure_input_card(
*,
request_id: str,
reason: str | None = None,
- skill: str | None = None,
+ spec: dict[str, Any] | None = None,
) -> dict[str, Any]:
- return {
+ normalized_spec = normalize_provision_spec(spec)
+ card = {
"card_type": "secure_input",
"request_id": request_id,
"secret_name": name,
"reason": reason,
- "skill": skill,
"protection_options": ["standard", "protected"],
- "default_protection": "protected",
+ "default_protection": normalized_spec.get("protection") or "protected",
"value": None,
}
+ if normalized_spec:
+ card["spec"] = normalized_spec
+ return card
def _grant_member_rows(conn: Connection, scope_type: str, scope_ref: str) -> list[dict[str, Any]]:
@@ -1728,6 +1960,50 @@ def list_requests(
]
+def resolve_pending_provision_request_by_name(conn: Connection, name: str) -> tuple[dict[str, Any] | None, bool]:
+ _expire_pending_requests(conn)
+ rows = list(
+ conn.execute(
+ select(vault_requests)
+ .where(
+ vault_requests.c.status == "pending",
+ vault_requests.c.request_type == "provision",
+ vault_requests.c.secret_name == name,
+ )
+ .order_by(vault_requests.c.created_at.desc(), vault_requests.c.id.desc())
+ .limit(2)
+ ).mappings()
+ )
+ if len(rows) == 1:
+ return _request_row_payload(dict(rows[0]), conn=conn, audience=REQUEST_AUDIENCE_UI), False
+ return None, len(rows) > 1
+
+
+def find_pending_provision_request(conn: Connection, name: str) -> dict[str, Any] | None:
+ request, _ambiguous = resolve_pending_provision_request_by_name(conn, name)
+ return request
+
+
+def get_pending_provision_request(conn: Connection, request_id: str) -> dict[str, Any] | None:
+ _expire_pending_requests(conn)
+ row = (
+ conn.execute(
+ select(vault_requests)
+ .where(
+ vault_requests.c.id == request_id,
+ vault_requests.c.status == "pending",
+ vault_requests.c.request_type == "provision",
+ )
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is None:
+ return None
+ return _request_row_payload(dict(row), conn=conn, audience=REQUEST_AUDIENCE_UI)
+
+
def _expire_grant_rows(
conn: Connection,
rows: list[dict[str, Any]],
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index e4dacf1bb..28697b8de 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -16,7 +16,7 @@ import pytest
from sqlalchemy import select
from storage import vault_service
-from storage.models import vault_links, vault_secrets
+from storage.models import vault_links, vault_requests, vault_secrets
from storage.vault_crypto import Sealed
from vibe import api
@@ -191,6 +191,142 @@ def test_create_with_policy_persists_allowed_hosts(monkeypatch):
assert secret["policy"]["allowed_hosts"] == ["api.github.com"]
+def test_create_with_links_persists_skill_link(monkeypatch):
+ from unittest.mock import Mock
+
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ api.create_vault_secret(
+ {
+ "name": "GH_PAT",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "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"]
+
+
+def test_get_provision_request_by_name_returns_pending_spec():
+ with api._vault_engine().begin() as conn:
+ req = vault_service.create_provision_request(
+ conn,
+ "GH_TOKEN",
+ spec={"group": "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["ambiguous"] is False
+
+
+def test_get_provision_request_returns_request_id_match():
+ with api._vault_engine().begin() as conn:
+ old_req = vault_service.create_provision_request(
+ conn,
+ "GH_TOKEN",
+ spec={"group": "old"},
+ )
+ vault_service.create_provision_request(
+ conn,
+ "GH_TOKEN",
+ spec={"group": "new"},
+ )
+
+ result = api.get_vault_provision_request(old_req["id"])
+
+ assert result["request"]["id"] == old_req["id"]
+ assert result["request"]["card"]["spec"]["group"] == "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"})
+
+ result = api.get_vault_provision_request_by_name("GH_TOKEN")
+
+ assert result["request"] is None
+ assert result["ambiguous"] is True
+
+
+def test_create_secret_with_provision_request_id_fulfills_sibling_requests(monkeypatch):
+ seal = 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"})
+
+ created = api.create_vault_secret(
+ {
+ "name": "GH_TOKEN",
+ "group": "new",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "provision_request_id": new_req["id"],
+ }
+ )
+
+ assert created["secret"]["group"] == "new"
+ with api._vault_engine().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"}
+
+
+def test_create_secret_with_fulfilled_provision_request_returns_secret_exists(monkeypatch):
+ seal = Mock(side_effect=[_sealed("first"), _sealed("second")])
+ monkeypatch.setattr(api, "avault_seal_blind_box", seal)
+ with api._vault_engine().begin() as conn:
+ req = vault_service.create_provision_request(conn, "GH_TOKEN")
+
+ payload = {
+ "name": "GH_TOKEN",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "provision_request_id": req["id"],
+ }
+ created = api.create_vault_secret(payload)
+ assert created["ok"] is True
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({**payload, "blind_box": {**payload["blind_box"], "enc": "enc2", "ct": "ct2"}})
+
+ assert exc.value.code == "secret_exists"
+ assert exc.value.status == 409
+
+
+def test_secret_exists_response_commits_stale_pending_provision_cleanup(monkeypatch):
+ seal = Mock(side_effect=[_sealed("first"), _sealed("second")])
+ monkeypatch.setattr(api, "avault_seal_blind_box", seal)
+ with api._vault_engine().begin() as conn:
+ req = vault_service.create_provision_request(conn, "GH_TOKEN")
+
+ payload = {
+ "name": "GH_TOKEN",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "provision_request_id": req["id"],
+ }
+ api.create_vault_secret(payload)
+ with api._vault_engine().begin() as conn:
+ stale = vault_service.create_provision_request(conn, "GH_TOKEN")
+ conn.execute(vault_requests.update().where(vault_requests.c.id == stale["id"]).values(status="pending"))
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({**payload, "blind_box": {**payload["blind_box"], "enc": "enc2", "ct": "ct2"}})
+
+ assert exc.value.code == "secret_exists"
+ with api._vault_engine().connect() as conn:
+ stale_status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == stale["id"])).scalar_one()
+ assert stale_status == "fulfilled"
+
+
def test_duplicate_name_conflict(monkeypatch):
from unittest.mock import Mock
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index 8691be9b5..c6c427a06 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -35,7 +35,8 @@ def _ns(**kw):
env=None,
command_argv=None,
reason=None,
- skill=None,
+ spec=None,
+ spec_json=None,
wait=None,
no_wait=False,
json=False,
@@ -1294,12 +1295,59 @@ def test_request_creates_pending(capfd):
assert payload["request_id"].startswith("vrq_")
+def test_request_accepts_spec_path(tmp_path, capfd):
+ spec_path = tmp_path / "request-spec.json"
+ spec_path.write_text(
+ json.dumps(
+ {
+ "group": "github",
+ "tags": ["github"],
+ "protection": "protected",
+ "policy": {"allowed_hosts": ["api.github.com"], "auth": {"type": "bearer"}},
+ "links": {"skills": ["github-pr-review"]},
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ code = cli.cmd_vault_request(_ns(name="GITHUB_TOKEN", reason="need PR status", spec=str(spec_path)))
+ payload = json.loads(capfd.readouterr().out)
+
+ assert code == 0
+ assert payload["request"]["card"]["spec"]["group"] == "github"
+ 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"]
+ assert "Provide secret" in payload["message"]
+ assert "Add secret" not in payload["message"]
+
+
+def test_request_rejects_spec_with_plaintext_value(capfd):
+ code = cli.cmd_vault_request(_ns(name="BAD_KEY", spec_json='{"policy":{"value":"secret"}}'))
+ payload = json.loads(capfd.readouterr().err)
+
+ assert code == 1
+ assert payload["code"] == "invalid_spec"
+
+
def test_request_for_existing_secret_returns_fulfilled(tmp_path, capfd, monkeypatch):
_create_standard_secret("HAVE_KEY")
assert cli.cmd_vault_request(_ns(name="HAVE_KEY", wait=30)) == 0
assert json.loads(capfd.readouterr().out)["status"] == "fulfilled"
+def test_request_wait_outputs_fulfilled_request(capfd, monkeypatch):
+ def wait_mock(request_id, *, timeout, poll_interval=2.0):
+ return {"id": request_id, "status": "fulfilled", "request_type": "provision", "secret_name": "WAIT_KEY"}
+
+ monkeypatch.setattr(cli, "_wait_for_provision", wait_mock)
+
+ assert cli.cmd_vault_request(_ns(name="WAIT_KEY", wait=30)) == 0
+ payload = json.loads(capfd.readouterr().out)
+ assert payload["status"] == "fulfilled"
+ assert payload["request"]["status"] == "fulfilled"
+
+
def test_key_export_calls_avault_and_audits(tmp_path, capfd, monkeypatch):
from unittest.mock import Mock
diff --git a/tests/test_vault_service.py b/tests/test_vault_service.py
index efc12d841..8f4bb12e7 100644
--- a/tests/test_vault_service.py
+++ b/tests/test_vault_service.py
@@ -457,6 +457,66 @@ def test_create_fulfills_pending_provision_request(vault):
assert status == "fulfilled"
+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(
+ conn,
+ name="ASKED_KEY",
+ sealed=_sealed("new"),
+ group="new",
+ provision_request_id=new_req["id"],
+ )
+
+ 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"}
+
+
+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"])
+
+ 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:
@@ -480,16 +540,107 @@ def test_provision_request_and_fulfill(vault):
def test_provision_request_carries_secure_input_card_without_value(vault):
with vault.begin() as conn:
- req = vs.create_provision_request(conn, "NEW_CARD_KEY", reason="deploy", skill="release")
+ req = vs.create_provision_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"]},
+ },
+ )
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(
+ 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",
+ },
+ ],
+ )
+
+ 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 old_lookup["id"] == "vrq_old"
+ assert old_lookup["card"]["spec"]["group"] == "old"
+ assert ambiguous_by_name is None
+
+
+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"]
+
+
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")
diff --git a/ui/src/components/ui/secret-request-card.tsx b/ui/src/components/ui/secret-request-card.tsx
index d0f738e72..16acbc8bc 100644
--- a/ui/src/components/ui/secret-request-card.tsx
+++ b/ui/src/components/ui/secret-request-card.tsx
@@ -1,9 +1,10 @@
-import { useState } from 'react';
-import { CheckCircle2, KeyRound } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { CheckCircle2, KeyRound, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { badgeVariants } from './badge';
import { Dialog, DialogContent, DialogTitle } from './dialog';
import { VaultSecretForm } from './vault-secret-form';
+import { useApi, type VaultRequest, type VaultRequestSpec } from '@/context/ApiContext';
import { cn } from '@/lib/utils';
/**
@@ -11,10 +12,44 @@ import { cn } from '@/lib/utils';
* asked for a secret; this card is self-contained so it can live inline inside the
* markdown renderer. Browser-side sealing is required before the UI can submit values.
*/
-export const SecretRequestCard: React.FC<{ name: string }> = ({ name }) => {
+export const SecretRequestCard: React.FC<{ name: string; requestId?: string }> = ({ name, requestId }) => {
const { t } = useTranslation();
+ const api = useApi();
const [open, setOpen] = useState(false);
const [fulfilled, setFulfilled] = useState(false);
+ const [requestSpec, setRequestSpec] = useState<VaultRequestSpec | null>(null);
+ const [resolvedRequest, setResolvedRequest] = useState<VaultRequest | null>(null);
+ const [requestLoaded, setRequestLoaded] = useState(false);
+ const [requestAmbiguous, setRequestAmbiguous] = useState(false);
+
+ useEffect(() => {
+ if (!open) return;
+ let alive = true;
+ setRequestLoaded(false);
+ setRequestAmbiguous(false);
+ const loadRequest = requestId
+ ? api.getVaultProvisionRequestById(requestId, { handleError: false })
+ : api.getVaultProvisionRequest(name, { handleError: false });
+ loadRequest
+ .then((res) => {
+ if (!alive) return;
+ setResolvedRequest(res.request ?? null);
+ setRequestSpec(((res.request?.card as { spec?: VaultRequestSpec } | null)?.spec ?? null) as VaultRequestSpec | null);
+ setRequestAmbiguous(!requestId && Boolean('ambiguous' in res && res.ambiguous));
+ })
+ .catch(() => {
+ if (!alive) return;
+ setResolvedRequest(null);
+ setRequestSpec(null);
+ setRequestAmbiguous(false);
+ })
+ .finally(() => {
+ if (alive) setRequestLoaded(true);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [api, name, open, requestId]);
if (fulfilled) {
return (
@@ -24,6 +59,11 @@ export const SecretRequestCard: React.FC<{ name: string }> = ({ name }) => {
</span>
);
}
+ const requestCard = (resolvedRequest?.card ?? null) as { default_protection?: unknown } | null;
+ const defaultProtection =
+ requestCard?.default_protection === 'standard' || requestCard?.default_protection === 'protected'
+ ? requestCard.default_protection
+ : undefined;
return (
<>
@@ -50,15 +90,31 @@ export const SecretRequestCard: React.FC<{ name: string }> = ({ name }) => {
<span className="text-xs text-muted-foreground">{t('vaults.request.help')}</span>
</div>
</div>
- <VaultSecretForm
- fixedName={name}
- onCancel={() => setOpen(false)}
- onCreated={() => {
- setFulfilled(true);
- setOpen(false);
- }}
- treatExistingAsFulfilled
- />
+ {requestLoaded ? (
+ requestAmbiguous ? (
+ <div className="rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-muted">
+ {t('vaults.request.ambiguousProvision')}
+ </div>
+ ) : (
+ <VaultSecretForm
+ fixedName={name}
+ provisionRequestId={resolvedRequest?.id ?? requestId ?? null}
+ requestSpec={requestSpec}
+ defaultProtection={defaultProtection}
+ onCancel={() => setOpen(false)}
+ onCreated={() => {
+ setFulfilled(true);
+ setOpen(false);
+ }}
+ treatExistingAsFulfilled
+ />
+ )
+ ) : (
+ <div className="flex items-center gap-2 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-muted">
+ <Loader2 className="size-4 animate-spin" />
+ {t('common.loading')}
+ </div>
+ )}
</DialogContent>
</Dialog>
</>
diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsx
index 5fc9a4f24..eefbb9f6a 100644
--- a/ui/src/components/ui/vault-secret-form.tsx
+++ b/ui/src/components/ui/vault-secret-form.tsx
@@ -17,7 +17,7 @@ import {
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { ApiError, useApi, type DependencyItem } from '@/context/ApiContext';
+import { ApiError, useApi, type DependencyItem, type VaultRequestSpec } from '@/context/ApiContext';
import { cn } from '@/lib/utils';
import {
generateSigningKey,
@@ -110,6 +110,8 @@ export const VaultSecretForm: React.FC<{
onCreated: (name: string, reason?: 'created' | 'already_exists') => void;
className?: string;
defaultProtection?: VaultProtection;
+ provisionRequestId?: string | null;
+ requestSpec?: VaultRequestSpec | null;
treatExistingAsFulfilled?: boolean;
groups?: string[];
}> = ({
@@ -118,6 +120,8 @@ export const VaultSecretForm: React.FC<{
onCreated,
className,
defaultProtection = 'standard',
+ provisionRequestId,
+ requestSpec,
treatExistingAsFulfilled = false,
groups = [],
}) => {
@@ -127,22 +131,24 @@ export const VaultSecretForm: React.FC<{
const [value, setValue] = useState('');
const [staticSource, setStaticSource] = useState<StaticSecretSource>('text');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
- const [kind, setKind] = useState<VaultKind>('static');
+ const [kind, setKind] = useState<VaultKind>(requestSpec?.kind ?? 'static');
const [signingSource, setSigningSource] = useState<'generate' | 'import'>('generate');
const [importHex, setImportHex] = useState('');
const [signingKey, setSigningKey] = useState<SigningKeyMaterial | null>(null);
const [signingError, setSigningError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
- const [group, setGroup] = useState(DEFAULT_GROUP);
- const [tags, setTags] = useState<string[]>([]);
- const [description, setDescription] = useState('');
- const [allowHosts, setAllowHosts] = useState<string[]>([]);
- const [fetchAuthMode, setFetchAuthMode] = useState<FetchAuthMode>('bearer');
- const [fetchAuthName, setFetchAuthName] = useState('');
- const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [group, setGroup] = useState(requestSpec?.group ?? DEFAULT_GROUP);
+ const [tags, setTags] = useState<string[]>(requestSpec?.tags ?? []);
+ const [description, setDescription] = useState(requestSpec?.description ?? '');
+ const [allowHosts, setAllowHosts] = useState<string[]>(requestSpec?.policy?.allowed_hosts ?? []);
+ const [linkedSkills, setLinkedSkills] = useState<string[]>(requestSpec?.links?.skills ?? []);
+ const [fetchAuthMode, setFetchAuthMode] = useState<FetchAuthMode>(requestSpec?.policy?.auth?.type ?? 'bearer');
+ const [fetchAuthName, setFetchAuthName] = useState(requestSpec?.policy?.auth?.name ?? '');
+ const [advancedOpen, setAdvancedOpen] = useState(Boolean(requestSpec?.description || requestSpec?.tags?.length || requestSpec?.policy));
const [tagsPending, setTagsPending] = useState(false);
const [hostsPending, setHostsPending] = useState(false);
- const [protection, setProtection] = useState<VaultProtection>(defaultProtection);
+ const [skillsPending, setSkillsPending] = useState(false);
+ const [protection, setProtection] = useState<VaultProtection>(requestSpec?.protection ?? defaultProtection);
const [showValue, setShowValue] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [checkingAvault, setCheckingAvault] = useState(true);
@@ -177,11 +183,26 @@ export const VaultSecretForm: React.FC<{
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [protection]);
+ useEffect(() => {
+ if (!requestSpec) return;
+ if (requestSpec.kind) setKind(requestSpec.kind);
+ if (requestSpec.protection) setProtection(requestSpec.protection);
+ if (requestSpec.group) setGroup(requestSpec.group);
+ if (requestSpec.description) setDescription(requestSpec.description);
+ if (requestSpec.tags) setTags(requestSpec.tags);
+ if (requestSpec.policy?.allowed_hosts) setAllowHosts(requestSpec.policy.allowed_hosts);
+ if (requestSpec.links?.skills) setLinkedSkills(requestSpec.links.skills);
+ if (requestSpec.policy?.auth?.type) setFetchAuthMode(requestSpec.policy.auth.type);
+ if (requestSpec.policy?.auth?.name) setFetchAuthName(requestSpec.policy.auth.name);
+ if (requestSpec.description || requestSpec.tags?.length || requestSpec.policy) setAdvancedOpen(true);
+ }, [requestSpec]);
+
const p2Ready = useMemo(() => avaultP2Ready(avaultDep), [avaultDep]);
const secretName = (fixedName ?? name).trim().toUpperCase();
const protectedCreateReady = protectedVault.status === 'unlocked';
const isKeypair = kind === 'keypair';
const isProvision = Boolean(fixedName);
+ const showLinkedSkills = isProvision && Boolean(requestSpec?.links?.skills?.length || linkedSkills.length);
const fileInputRef = useRef<HTMLInputElement | null>(null);
// Hold the latest key material in a ref too, so the unmount cleanup can zero
@@ -264,12 +285,13 @@ export const VaultSecretForm: React.FC<{
event.preventDefault();
if (!canSubmit) return;
let fileBytesToWipe: Uint8Array | null = null;
- // Don't silently drop a half-typed tag/host chip the user can still see. Tags live in the
- // create-mode Advanced collapsible; the allowed-hosts input is in Advanced (create) and
- // always visible in provision mode — guard whichever is on screen. Collapsing Advanced
- // clears the pending flags, so a hidden draft can never block submit.
+ // Don't silently drop a half-typed tag/host chip the user can still see. Tags/hosts live in
+ // the create-mode Advanced collapsible and are always visible in provision mode — guard
+ // whichever is on screen. Collapsing Advanced clears the pending flags, so a hidden draft can
+ // never block submit.
+ const tagsVisible = isProvision || advancedOpen;
const hostsVisible = isProvision || advancedOpen;
- if ((advancedOpen && tagsPending) || (hostsVisible && hostsPending)) {
+ if ((tagsVisible && tagsPending) || (hostsVisible && hostsPending) || (showLinkedSkills && skillsPending)) {
setError(t('vaults.dialog.errors.pendingDraft'));
return;
}
@@ -318,6 +340,8 @@ export const VaultSecretForm: React.FC<{
description: description.trim() || undefined,
tags: tags.length ? tags : undefined,
policy: Object.keys(policy).length ? policy : undefined,
+ links: linkedSkills.length ? { skills: linkedSkills } : undefined,
+ provision_request_id: provisionRequestId || undefined,
...(isKeypair && signingKey
? {
kind: 'keypair',
@@ -583,8 +607,9 @@ export const VaultSecretForm: React.FC<{
);
// ---- Provision ($NAME) mode — design.pen `F4N19` (SecureInputCard) ------------------
- // A provision fulfils a specific value the agent asked for, so the kind/group/advanced
- // controls are hidden: it must stay a static secret. The same submit path is used.
+ // A provision fulfils a specific value the agent asked for, so kind stays fixed to static.
+ // Spec-derived metadata remains visible here so the user can confirm or adjust what the
+ // agent prefilled before anything is saved.
if (isProvision) {
return (
<form className={cn('flex flex-col gap-4', className)} onSubmit={onSubmit}>
@@ -619,6 +644,60 @@ export const VaultSecretForm: React.FC<{
</div>
</div>
+ <label className="flex flex-col gap-1.5">
+ <span className={FIELD_LABEL}>{t('vaults.dialog.group')}</span>
+ <Combobox
+ options={[...new Set([DEFAULT_GROUP, ...groups])].map((g) => ({ value: g, label: g }))}
+ value={group}
+ onValueChange={setGroup}
+ allowCustomValue
+ commitOnClose
+ withFolderIcon
+ createLabel={(v) => t('vaults.dialog.groupCreate', { name: v })}
+ createButtonLabel={t('vaults.dialog.groupCreateCta')}
+ createHeading={t('vaults.dialog.groupCreateHeading')}
+ placeholder={t('vaults.dialog.groupPlaceholder')}
+ searchPlaceholder={t('vaults.dialog.groupSearch')}
+ />
+ </label>
+
+ <label className="flex flex-col gap-1.5">
+ <span className={FIELD_LABEL}>{t('vaults.dialog.description')}</span>
+ <Input
+ value={description}
+ onChange={(event) => setDescription(event.target.value)}
+ placeholder={t('vaults.dialog.descriptionPlaceholder')}
+ />
+ </label>
+
+ <div className="flex flex-col gap-1.5">
+ <span className={FIELD_LABEL}>{t('vaults.dialog.tags')}</span>
+ <TagInput
+ values={tags}
+ onChange={setTags}
+ placeholder={t('vaults.dialog.tagsPlaceholder')}
+ ariaLabel={t('vaults.dialog.tags')}
+ removeLabel={(value) => t('vaults.dialog.removeChip', { value })}
+ onPendingChange={setTagsPending}
+ />
+ <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.tagsHelp')}</span>
+ </div>
+
+ {showLinkedSkills && (
+ <div className="flex flex-col gap-1.5">
+ <span className={FIELD_LABEL}>{t('vaults.dialog.linkedSkills')}</span>
+ <TagInput
+ values={linkedSkills}
+ onChange={setLinkedSkills}
+ placeholder={t('vaults.dialog.linkedSkillsPlaceholder')}
+ ariaLabel={t('vaults.dialog.linkedSkills')}
+ removeLabel={(value) => t('vaults.dialog.removeChip', { value })}
+ onPendingChange={setSkillsPending}
+ />
+ <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.linkedSkillsHelp')}</span>
+ </div>
+ )}
+
{/* Allowed hosts — a provisioned secret used for brokered HTTP fetch needs at least
one allowed host, else vibe/cli.py refuses the fetch as proxy_unbound. */}
<div className="flex flex-col gap-1.5">
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index 05f42b461..8e039ed28 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -7,7 +7,7 @@ import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog';
import { cn } from '../../lib/utils';
-import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';
+import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultRequestSpec, type VaultSecret } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { VaultApprovalCard, type ApprovalOutcome } from '../ui/vault-approval-card';
import { VaultSecretForm } from '../ui/vault-secret-form';
@@ -16,8 +16,16 @@ const AddSecretDialog: React.FC<{
onClose: () => void;
onCreated: (name: string, reason?: 'created' | 'already_exists') => void;
groups: string[];
-}> = ({ onClose, onCreated, groups }) => {
+ request?: VaultRequest | null;
+}> = ({ onClose, onCreated, groups, request }) => {
const { t } = useTranslation();
+ const requestCard = (request?.card ?? null) as { default_protection?: unknown; spec?: VaultRequestSpec } | null;
+ const requestSpec = (requestCard?.spec ?? null) as VaultRequestSpec | null;
+ const defaultProtection =
+ requestCard?.default_protection === 'standard' || requestCard?.default_protection === 'protected'
+ ? requestCard.default_protection
+ : undefined;
+ const fixedName = request?.secret_name ?? undefined;
return (
<Dialog
@@ -28,9 +36,18 @@ const AddSecretDialog: React.FC<{
>
<DialogContent>
<DialogHeader>
- <DialogTitle>{t('vaults.dialog.title')}</DialogTitle>
+ <DialogTitle>{request ? t('vaults.request.title') : t('vaults.dialog.title')}</DialogTitle>
</DialogHeader>
- <VaultSecretForm onCancel={onClose} onCreated={onCreated} groups={groups} />
+ <VaultSecretForm
+ fixedName={fixedName}
+ provisionRequestId={request?.id ?? null}
+ requestSpec={requestSpec}
+ defaultProtection={defaultProtection}
+ onCancel={onClose}
+ onCreated={onCreated}
+ groups={groups}
+ treatExistingAsFulfilled={Boolean(request)}
+ />
</DialogContent>
</Dialog>
);
@@ -188,7 +205,9 @@ const GrantChip: React.FC<{ grant: VaultGrant; now: number; onRevoke: (grant: Va
const RequestRow: React.FC<{ request: VaultRequest; onReview: (request: VaultRequest) => void }> = ({ request: r, onReview }) => {
const { t } = useTranslation();
const card = (r.card ?? {}) as { request_type?: string; kind?: string; protection?: string; session_id?: string };
- const isSign = (card.request_type ?? r.request_type) === 'sign';
+ const type = card.request_type ?? r.request_type;
+ const isSign = type === 'sign';
+ const isProvision = type === 'provision';
const isProtected = card.protection === 'protected';
const Icon = isSign || card.kind === 'keypair' ? Wallet : KeyRound;
return (
@@ -199,12 +218,14 @@ const RequestRow: React.FC<{ request: VaultRequest; onReview: (request: VaultReq
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<span className="truncate font-mono text-sm font-semibold">{r.secret_name}</span>
- <Badge variant="info">{isSign ? t('vaults.requests.sign') : t('vaults.requests.access')}</Badge>
+ <Badge variant="info">
+ {isProvision ? t('vaults.requests.provision') : isSign ? t('vaults.requests.sign') : t('vaults.requests.access')}
+ </Badge>
{isProtected ? <Badge variant="warning">{t('vaults.protected')}</Badge> : null}
</div>
<span className="flex items-center gap-1.5 text-xs text-muted">
<Clock className="size-3" />
- {t('vaults.requests.waiting')}
+ {isProvision ? t('vaults.requests.waitingForValue') : t('vaults.requests.waiting')}
{card.session_id ? (
<>
<span aria-hidden>·</span>
@@ -215,7 +236,7 @@ const RequestRow: React.FC<{ request: VaultRequest; onReview: (request: VaultReq
</div>
<div className="ml-auto">
<Button size="sm" onClick={() => onReview(r)}>
- {t('vaults.requests.review')}
+ {isProvision ? t('vaults.request.provide') : t('vaults.requests.review')}
</Button>
</div>
</div>
@@ -228,23 +249,22 @@ const RequestRow: React.FC<{ request: VaultRequest; onReview: (request: VaultReq
* Best-effort — a requests fetch failure (e.g. an older backend without the route) must
* not surface an error or blank the rest of the hub.
*/
-const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolved }) => {
+const PendingRequestsSection: React.FC<{ groups: string[]; onResolved: () => void }> = ({ groups, onResolved }) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
const [requests, setRequests] = useState<VaultRequest[]>([]);
const [reviewing, setReviewing] = useState<VaultRequest | null>(null);
+ const [provisioning, setProvisioning] = useState<VaultRequest | null>(null);
const load = useCallback(async () => {
try {
// Best-effort with suppressed errors so an older backend without the route doesn't
- // spam global toasts on every 5s poll. Only approval (access/sign) requests render
- // here — a provision request ($NAME secure-input) has no grant scope and would show
- // a broken Review row, so filter it out.
+ // spam global toasts on every 5s poll.
const res = await api.getVaultRequests({ status: 'pending' }, { handleError: false });
const pending = (res.requests ?? []).filter((r) => {
const type = (r.card as { request_type?: string } | null)?.request_type ?? r.request_type;
- return type === 'access' || type === 'sign';
+ return type === 'access' || type === 'sign' || type === 'provision';
});
setRequests(pending);
} catch {
@@ -289,7 +309,18 @@ const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolv
<span className="hidden text-xs text-muted sm:inline">{t('vaults.requests.subtitle')}</span>
</div>
{requests.map((r) => (
- <RequestRow key={r.id} request={r} onReview={setReviewing} />
+ <RequestRow
+ key={r.id}
+ request={r}
+ onReview={(request) => {
+ const type = (request.card as { request_type?: string } | null)?.request_type ?? request.request_type;
+ if (type === 'provision') {
+ setProvisioning(request);
+ } else {
+ setReviewing(request);
+ }
+ }}
+ />
))}
<Dialog
open={reviewing != null}
@@ -306,6 +337,22 @@ const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolv
) : null}
</DialogContent>
</Dialog>
+ {provisioning != null ? (
+ <AddSecretDialog
+ request={provisioning}
+ groups={groups}
+ onClose={() => setProvisioning(null)}
+ onCreated={(name, reason) => {
+ setProvisioning(null);
+ if (reason !== 'already_exists') {
+ showToast(t('vaults.created', { name }), 'success');
+ }
+ setRequests((prev) => prev.filter((r) => r.id !== provisioning.id));
+ load();
+ onResolved();
+ }}
+ />
+ ) : null}
</div>
);
};
@@ -438,7 +485,7 @@ export const VaultsPage: React.FC = () => {
{error && (
<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</div>
)}
- <PendingRequestsSection onResolved={refresh} />
+ <PendingRequestsSection groups={groups.map(([g]) => g)} onResolved={refresh} />
{grants.length > 0 && (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 px-1">
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index a7ca49c20..951cf38fc 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -58,6 +58,19 @@ export type VaultRequest = {
card?: Record<string, unknown> | null;
};
+export type VaultRequestSpec = {
+ kind?: 'static';
+ protection?: 'standard' | 'protected';
+ group?: string;
+ description?: string;
+ tags?: string[];
+ policy?: {
+ allowed_hosts?: string[];
+ auth?: { type?: 'bearer' | 'header' | 'query'; name?: string };
+ };
+ links?: { skills?: string[] };
+};
+
export type VaultGrant = {
id: string;
scope_type: 'secret' | 'skill' | 'group';
@@ -122,6 +135,8 @@ export type VaultCreatePayload = {
signer_kind?: string | null;
policy?: Record<string, unknown>;
public_meta?: Record<string, unknown>;
+ links?: { skills?: string[] };
+ provision_request_id?: string;
/** Set on the first protected secret so the daemon atomically guards single VMK init. */
establishing_vmk?: boolean;
};
@@ -336,6 +351,11 @@ export type ApiContextType = {
getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;
createVaultSecret: (payload: VaultCreatePayload, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;
deleteVaultSecret: (name: string) => Promise<{ ok: boolean; removed?: boolean; code?: string; message?: string }>;
+ getVaultProvisionRequest: (
+ name: string,
+ opts?: { handleError?: boolean },
+ ) => Promise<{ ok: boolean; request: VaultRequest | null; ambiguous?: boolean }>;
+ getVaultProvisionRequestById: (requestId: string, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; request: VaultRequest | null }>;
getVaultRequests: (params?: { status?: string; type?: string; limit?: number }, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; requests: VaultRequest[] }>;
denyVaultRequest: (requestId: string) => Promise<{ ok: boolean; request?: VaultRequest; code?: string; message?: string }>;
fulfillVaultAccessRequest: (requestId: string, payload: VaultAccessFulfillmentPayload) => Promise<{ ok: boolean; request_id?: string; grant?: VaultGrant; result?: { type: string; grant?: VaultGrant }; code?: string; message?: string }>;
@@ -2049,6 +2069,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),
createVaultSecret: (payload, opts) => postJson('/api/vault/secrets', payload, opts),
deleteVaultSecret: (name) => deleteJson(`/api/vault/secrets/${encodeURIComponent(name)}`),
+ getVaultProvisionRequest: (name, opts) =>
+ getCachedJson(`/api/vault/provision-requests/${encodeURIComponent(name)}`, 1500, opts),
+ getVaultProvisionRequestById: (requestId, opts) =>
+ getCachedJson(`/api/vault/provision-requests/by-id/${encodeURIComponent(requestId)}`, 1500, opts),
getVaultRequests: (params, opts) => {
const search = new URLSearchParams();
if (params?.status) search.set('status', params.status);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index e420df87b..8824c6d80 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2333,6 +2333,9 @@
"tags": "Tags",
"tagsPlaceholder": "tag, then Enter",
"tagsHelp": "Optional labels to find and group secrets.",
+ "linkedSkills": "Linked skills",
+ "linkedSkillsPlaceholder": "skill name, then Enter",
+ "linkedSkillsHelp": "Suggested by the requesting agent. Remove any skill that should not receive this secret through skill-scope grants.",
"removeChip": "Remove {{value}}",
"protection": "Protection",
"protectedProtection": "Protected",
@@ -2365,8 +2368,10 @@
"reviewTitle": "Review request",
"review": "Review",
"waiting": "Waiting for approval",
+ "waitingForValue": "Waiting for value",
"access": "Use secret",
"sign": "Sign",
+ "provision": "Provide secret",
"approved": "Access approved",
"signed": "Signature returned",
"denied": "Request denied"
@@ -2414,6 +2419,7 @@
"notSetYet": "not set yet",
"dismiss": "Dismiss",
"saveAndWake": "Save & wake agent",
+ "ambiguousProvision": "Multiple pending requests need this secret. Open the request-specific Provide secret row in Vaults so the requested details are preserved.",
"saveFailed": "Couldn't save the secret. Please try again."
},
"history": "History",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b1960902a..cbcabfd43 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2332,6 +2332,9 @@
"tags": "标签",
"tagsPlaceholder": "输入标签后回车",
"tagsHelp": "可选,用来查找和归类密钥。",
+ "linkedSkills": "关联技能",
+ "linkedSkillsPlaceholder": "输入技能名称后回车",
+ "linkedSkillsHelp": "由请求的 Agent 建议。若某个技能不应通过技能级授权拿到这条密钥,请先移除。",
"removeChip": "移除 {{value}}",
"protection": "保护级别",
"protectedProtection": "受保护",
@@ -2364,8 +2367,10 @@
"reviewTitle": "审阅请求",
"review": "审阅",
"waiting": "等待批准",
+ "waitingForValue": "等待填写",
"access": "使用密钥",
"sign": "签名",
+ "provision": "填写密钥",
"approved": "已批准访问",
"signed": "已返回签名",
"denied": "已拒绝请求"
@@ -2413,6 +2418,7 @@
"notSetYet": "尚未设置",
"dismiss": "忽略",
"saveAndWake": "保存并唤醒 Agent",
+ "ambiguousProvision": "有多个待处理请求都需要这个密钥。请在 Vaults 里打开对应请求的填写行,这样才能保留请求里的详细设置。",
"saveFailed": "保存失败,请重试。"
},
"history": "历史",
diff --git a/vibe/api.py b/vibe/api.py
index c4a459979..2e9456bb8 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1412,6 +1412,7 @@ def create_vault_secret(payload: dict) -> dict:
tags = payload.get("tags") if isinstance(payload.get("tags"), list) else None
policy = payload.get("policy") if isinstance(payload.get("policy"), dict) else None
public_meta = payload.get("public_meta") if isinstance(payload.get("public_meta"), dict) else None
+ links = payload.get("links") if isinstance(payload.get("links"), dict) else None
protection = str(payload.get("protection") or "standard").strip().lower()
establishing_vmk = bool(payload.get("establishing_vmk"))
kind = str(payload.get("kind") or "static").strip().lower()
@@ -1452,10 +1453,23 @@ def create_vault_secret(payload: dict) -> dict:
policy=policy,
public_meta=public_meta,
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 exc
except vault_service.SecretExistsError as exc:
+ try:
+ with engine.begin() as conn:
+ vault_service.fulfill_pending_provision_requests_for_secret(conn, name)
+ except Exception:
+ logger.warning("failed to settle pending provision requests for existing secret %s", name, exc_info=True)
raise VaultApiError(f"secret '{name}' already exists", code="secret_exists", status=409) from exc
except vault_service.VaultAlreadyInitializedError as exc:
raise VaultApiError(str(exc), code="vault_already_initialized", status=409) from exc
@@ -1498,6 +1512,30 @@ def get_vault_requests(*, status: Optional[str] = "pending", request_type: Optio
return {"ok": True, "requests": requests}
+def get_vault_provision_request_by_name(name: str) -> dict:
+ from storage import vault_crypto, vault_service
+
+ requested_name = str(name or "").strip()
+ if not vault_crypto.is_valid_secret_name(requested_name):
+ raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name")
+ engine = _vault_engine()
+ with engine.begin() as conn:
+ request, ambiguous = vault_service.resolve_pending_provision_request_by_name(conn, requested_name)
+ return {"ok": True, "request": request, "ambiguous": ambiguous}
+
+
+def get_vault_provision_request(request_id: str) -> dict:
+ from storage import vault_service
+
+ requested_id = str(request_id or "").strip()
+ if not requested_id:
+ raise VaultApiError("request_id is required", code="missing_request_id")
+ engine = _vault_engine()
+ with engine.begin() as conn:
+ request = vault_service.get_pending_provision_request(conn, requested_id)
+ return {"ok": True, "request": request}
+
+
def _vault_request_result(conn, request: dict) -> dict | None:
from storage import vault_service
diff --git a/vibe/cli.py b/vibe/cli.py
index bd9b82031..30f48e20b 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -5119,21 +5119,24 @@ def cmd_vault_run(args):
return exit_code
-def _wait_for_provision(request_id: str, *, timeout: float, poll_interval: float = 2.0) -> bool:
- from storage.models import vault_requests
+def _wait_for_provision(request_id: str, *, timeout: float, poll_interval: float = 2.0) -> dict | None:
+ from storage import vault_service
deadline = time.monotonic() + timeout
engine = _open_vault_engine()
while time.monotonic() < deadline:
- with engine.connect() as conn:
- row = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == request_id)).first()
- if row and row[0] == "fulfilled":
- return True
+ with engine.begin() as conn:
+ try:
+ request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)
+ except vault_service.RequestNotFoundError:
+ raise
+ if request.get("status") == "fulfilled":
+ return request
remaining = deadline - time.monotonic()
if remaining <= 0:
break
time.sleep(min(poll_interval, remaining))
- return False
+ return None
def _wait_for_vault_request(request_id: str, *, timeout: float, poll_interval: float = 2.0) -> dict | None:
@@ -5167,13 +5170,14 @@ def cmd_vault_request(args):
name = args.name
if not vault_crypto.is_valid_secret_name(name):
raise TaskCliError(f"invalid secret name: {name!r} (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name", help_command=help_command)
+ spec = _load_vault_request_spec(args, help_command=help_command)
engine = _open_vault_engine()
with engine.begin() as conn:
req = vault_service.create_provision_request(
conn,
name,
reason=getattr(args, "reason", None),
- skill=getattr(args, "skill", None),
+ spec=spec,
requester={"source": "cli", "pid": os.getpid()},
)
if req.get("status") == "fulfilled":
@@ -5183,17 +5187,20 @@ def cmd_vault_request(args):
request_id=req["id"],
secret_name=name,
status="fulfilled",
+ request=req,
message=f"'{name}' is already in the vault — use it via: vibe vault run --env {name} -- <command>",
)
return 0
wait_seconds = getattr(args, "wait", None)
if wait_seconds:
- if _wait_for_provision(req["id"], timeout=float(wait_seconds)):
+ waited = _wait_for_provision(req["id"], timeout=float(wait_seconds))
+ if waited:
_print_cli_payload(
"vault_request",
request_id=req["id"],
secret_name=name,
status="fulfilled",
+ request=waited,
message=f"'{name}' is now available — use it via: vibe vault run --env {name} -- <command>",
)
return 0
@@ -5211,16 +5218,16 @@ def cmd_vault_request(args):
request_id=req["id"],
secret_name=name,
status="pending",
- message=(
- f"Recorded a request for '{name}'. The user fulfills it by adding a secret named "
- f"{name} on the Vaults page (Add secret) — saving it marks this request fulfilled. "
- f"Then use: vibe vault run --env {name} -- <command>"
- ),
+ request=req,
+ message=_vault_request_pending_message(name, req, has_spec=bool(spec)),
)
return 0
except TaskCliError as exc:
_print_task_error(exc)
return 1
+ except vault_service.VaultServiceError as exc:
+ _print_task_error(TaskCliError(str(exc), code="invalid_spec", help_command=help_command))
+ return 1
except Exception as exc:
_print_task_error(exc, help_command=help_command)
return 1
@@ -5344,6 +5351,56 @@ def cmd_vault_await(args):
return 1
+def _vault_request_pending_message(name: str, request: dict[str, object], *, has_spec: bool) -> str:
+ if has_spec:
+ return (
+ 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>"
+ )
+ return (
+ f"Recorded a request for '{name}'. The user fulfills it from the Vaults page pending requests list "
+ f"(Provide secret) or by adding a secret named {name}; saving it marks this request fulfilled. "
+ f"Then use: vibe vault run --env {name} -- <command>"
+ )
+
+
+def _load_vault_request_spec(args, *, help_command: str) -> dict | None:
+ spec_sources = [
+ value
+ for value in (
+ getattr(args, "spec_json", None),
+ getattr(args, "spec", None),
+ )
+ if value
+ ]
+ if len(spec_sources) > 1:
+ raise TaskCliError("use only one of --spec-json or --spec", code="invalid_spec", help_command=help_command)
+
+ raw: str | None = None
+ if getattr(args, "spec_json", None):
+ raw = str(args.spec_json)
+ elif getattr(args, "spec", None):
+ spec_arg = str(args.spec)
+ if spec_arg == "-":
+ raw = sys.stdin.read()
+ else:
+ try:
+ raw = Path(spec_arg).read_text(encoding="utf-8")
+ except OSError as exc:
+ raise TaskCliError(f"cannot read --spec: {exc}", code="spec_unreadable", help_command=help_command) from exc
+
+ if raw is None:
+ return None
+ try:
+ parsed = json.loads(raw)
+ except ValueError as exc:
+ raise TaskCliError(f"invalid request spec JSON: {exc}", code="invalid_spec", help_command=help_command) from exc
+ if not isinstance(parsed, dict):
+ raise TaskCliError("request spec must be a JSON object", code="invalid_spec", help_command=help_command)
+ return parsed
+
+
def _host_allowed(host, allowed) -> bool:
"""Exact host match, or a leading-dot entry (``.github.com``) matching subdomains.
@@ -8978,7 +9035,8 @@ def build_parser():
)
vault_request_parser.add_argument("name", help="Secret name being requested")
vault_request_parser.add_argument("--reason", help="Why the secret is needed (shown to the user)")
- vault_request_parser.add_argument("--skill", help="Skill that needs it (shown to the user)")
+ vault_request_parser.add_argument("--spec", help="Read non-secret creation hints from this JSON file, or '-' for stdin")
+ vault_request_parser.add_argument("--spec-json", help="Inline JSON object with non-secret creation hints")
vault_request_parser.add_argument("--wait", type=float, metavar="SECONDS", help="Block until fulfilled, up to SECONDS")
vault_request_parser.add_argument("--no-wait", action="store_true", help="Return immediately (default)")
_add_json_noop(vault_request_parser)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 7fe44f19d..d362ab1db 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2744,6 +2744,26 @@ def vault_request_get(request_id):
return _vault_error_response(exc)
[email protected]("/api/vault/provision-requests/<name>", methods=["GET"])
+def vault_provision_request_by_name_get(name):
+ from vibe import api
+
+ try:
+ return jsonify(api.get_vault_provision_request_by_name(name))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
[email protected]("/api/vault/provision-requests/by-id/<request_id>", methods=["GET"])
+def vault_provision_request_get(request_id):
+ from vibe import api
+
+ try:
+ return jsonify(api.get_vault_provision_request(request_id))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
@app.route("/api/vault/requests/access", methods=["POST"])
def vault_access_request_post():
from vibe import api