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.

Edit Vault secret metadata (#806)

Call White9915fb250a5d
diff --git a/storage/vault_service.py b/storage/vault_service.py
index f4a46f614..b80f3a24a 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import json
import logging
+import re
import threading
import uuid
from dataclasses import dataclass
@@ -73,6 +74,10 @@ PROVISION_SPEC_ALLOWED_KEYS = {
}
PROVISION_SPEC_ALLOWED_POLICY_KEYS = {"allowed_hosts", "auth"}
PROVISION_SPEC_ALLOWED_AUTH_KEYS = {"type", "name"}
+FETCH_AUTH_HEADER_NAME_RE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
+FETCH_AUTH_QUERY_NAME_RE = re.compile(r"^[A-Za-z0-9._~-]+$")
+FORBIDDEN_FETCH_AUTH_HEADER_NAMES = frozenset({"host"})
+_UNSET = object()
@dataclass(frozen=True)
@@ -433,6 +438,72 @@ def _optional_string(value: Any, *, field: str) -> str | None:
return stripped or None
+def _validate_fetch_auth_name(auth_type: str, auth_name: str, *, field: str) -> None:
+ if auth_type == "header":
+ if auth_name.strip().lower() in FORBIDDEN_FETCH_AUTH_HEADER_NAMES:
+ raise VaultServiceError(f"{field} cannot be {auth_name!r}")
+ if not FETCH_AUTH_HEADER_NAME_RE.fullmatch(auth_name):
+ raise VaultServiceError(f"{field} must be a valid HTTP header name")
+ elif auth_type == "query" and not FETCH_AUTH_QUERY_NAME_RE.fullmatch(auth_name):
+ raise VaultServiceError(f"{field} must be a valid query parameter name")
+
+
+def _normalize_fetch_policy(policy: Any, *, field: str = "policy", allowed_extra_keys: set[str] | None = None) -> dict[str, Any]:
+ if policy is None:
+ return {}
+ if not isinstance(policy, dict):
+ raise VaultServiceError(f"{field} must be an object")
+ extra_policy_keys = set(policy) - PROVISION_SPEC_ALLOWED_POLICY_KEYS - (allowed_extra_keys or set())
+ if extra_policy_keys:
+ raise VaultServiceError(f"unsupported {field} fields: {', '.join(sorted(extra_policy_keys))}")
+ normalized_policy: dict[str, Any] = {}
+ allowed_hosts = _allowed_host_list(policy.get("allowed_hosts"), field=f"{field}.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(f"{field}.auth must be an object")
+ extra_auth_keys = set(auth) - PROVISION_SPEC_ALLOWED_AUTH_KEYS
+ if extra_auth_keys:
+ raise VaultServiceError(f"unsupported {field}.auth fields: {', '.join(sorted(extra_auth_keys))}")
+ raw_auth_type = auth.get("type") or "bearer"
+ if not isinstance(raw_auth_type, str):
+ raise VaultServiceError(f"{field}.auth.type must be a string")
+ auth_type = raw_auth_type.strip().lower()
+ if auth_type not in {"bearer", "header", "query"}:
+ raise VaultServiceError(f"{field}.auth.type must be bearer, header, or query")
+ normalized_auth: dict[str, Any] = {"type": auth_type}
+ auth_name = _optional_string(auth.get("name"), field=f"{field}.auth.name") if "name" in auth else None
+ if auth_type in {"header", "query"}:
+ if not auth_name:
+ raise VaultServiceError(f"{field}.auth.name is required for header/query auth")
+ _validate_fetch_auth_name(auth_type, auth_name, field=f"{field}.auth.name")
+ normalized_auth["name"] = auth_name
+ elif auth_name:
+ normalized_auth["name"] = auth_name
+ normalized_policy["auth"] = normalized_auth
+ return normalized_policy
+
+
+def _stored_fetch_policy_visible_snapshot(policy: dict[str, Any]) -> dict[str, Any]:
+ """Best-effort comparable view of persisted fetch policy.
+
+ Older or hand-edited rows may contain auth names that the current write path
+ rejects. Do not normalize the old value here; edits must still be able to
+ replace an unsafe legacy policy with a valid one.
+ """
+
+ snapshot: dict[str, Any] = {}
+ allowed_hosts = policy.get("allowed_hosts")
+ if allowed_hosts:
+ snapshot["allowed_hosts"] = allowed_hosts
+ auth = policy.get("auth")
+ if auth is not None:
+ snapshot["auth"] = auth
+ return snapshot
+
+
def normalize_provision_spec(spec: Any) -> dict[str, Any]:
"""Return non-secret creation hints for a provision request.
@@ -476,39 +547,8 @@ def normalize_provision_spec(spec: Any) -> dict[str, Any]:
tags = _string_list(spec.get("tags"), field="spec.tags") if "tags" in spec else []
tags = _normalize_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 "policy" in spec:
+ normalized_policy = _normalize_fetch_policy(spec.get("policy"), field="spec.policy")
if normalized_policy:
normalized["policy"] = normalized_policy
@@ -1406,6 +1446,83 @@ def update_secret_tags(conn: Connection, secret_name: str, tags: list[str]) -> d
return _meta_payload(dict(row) | {"tags": json.dumps(normalized) if normalized else None})
+def update_secret_metadata(
+ conn: Connection,
+ secret_name: str,
+ *,
+ description: Any = _UNSET,
+ tags: Any = _UNSET,
+ policy: Any = _UNSET,
+ cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,
+ release_scopes: list[dict[str, str]] | None = None,
+) -> dict[str, Any]:
+ """Update value-free metadata only.
+
+ Tags and display metadata deliberately do not expire active grants: grants are
+ scoped to a frozen secret set, not to selectors. Fetch policy is an
+ authorization boundary, so policy changes expire relevant requests/grants.
+ """
+
+ row = _require_row(conn, secret_name)
+ values: dict[str, Any] = {}
+ fields: list[str] = []
+
+ if description is not _UNSET:
+ public_meta = _public_meta(row.get("public_meta"))
+ normalized_description = _optional_string(description, field="description")
+ if normalized_description:
+ public_meta["description"] = normalized_description
+ else:
+ public_meta.pop("description", None)
+ values["public_meta"] = json.dumps(public_meta) if public_meta else None
+ fields.append("description")
+
+ if tags is not _UNSET:
+ normalized_tags = _normalize_tags(_string_list(tags, field="tags"))
+ values["tags"] = json.dumps(normalized_tags) if normalized_tags else None
+ fields.append("tags")
+
+ if policy is not _UNSET:
+ if policy is None:
+ policy = {}
+ if not isinstance(policy, dict):
+ raise VaultServiceError("policy must be an object")
+ existing_policy = _secret_policy(row)
+ internal_policy_keys = set(existing_policy) - PROVISION_SPEC_ALLOWED_POLICY_KEYS
+ incoming_internal_keys = set(policy) - PROVISION_SPEC_ALLOWED_POLICY_KEYS
+ unsupported_internal_keys = incoming_internal_keys - internal_policy_keys
+ if unsupported_internal_keys:
+ raise VaultServiceError(f"unsupported policy fields: {', '.join(sorted(unsupported_internal_keys))}")
+ changed_internal_keys = [key for key in sorted(incoming_internal_keys) if policy.get(key) != existing_policy.get(key)]
+ if changed_internal_keys:
+ raise VaultServiceError(f"policy.{changed_internal_keys[0]} is read-only")
+ # Preserve internal policy keys such as always_ask; metadata editing owns
+ # only the user-visible fetch policy fields.
+ preserved_policy = {
+ key: value
+ for key, value in existing_policy.items()
+ if key not in PROVISION_SPEC_ALLOWED_POLICY_KEYS
+ }
+ existing_visible_policy = _stored_fetch_policy_visible_snapshot(existing_policy)
+ normalized_policy = _normalize_fetch_policy(policy, field="policy", allowed_extra_keys=internal_policy_keys)
+ next_policy = {**preserved_policy, **normalized_policy}
+ values["policy"] = json.dumps(next_policy) if next_policy else None
+ fields.append("policy")
+ if normalized_policy != existing_visible_policy:
+ grant_rows = active_grant_rows_for_secret(conn, secret_name)
+ _expire_pending_requests_for_secret(conn, secret_name, reason="request-expired-policy-changed")
+ _expire_grant_rows(conn, grant_rows, cache=cache, reason="grant-expired-policy-changed")
+ if release_scopes is not None:
+ release_scopes.extend(agent_release_scopes_after_rows(conn, grant_rows, cache=cache))
+
+ if not values:
+ return _meta_payload(row)
+
+ conn.execute(vault_secrets.update().where(vault_secrets.c.name == secret_name).values(**values))
+ audit(conn, "metadata-updated", secret_name=secret_name, delivery={"fields": fields})
+ return _meta_payload(_require_row(conn, secret_name))
+
+
def update_secret_classification(
conn: Connection,
secret_name: str,
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index 8a7aeb30e..f522ef60f 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -223,6 +223,206 @@ def test_create_with_policy_persists_allowed_hosts(monkeypatch):
assert secret["policy"]["allowed_hosts"] == ["api.github.com"]
+def test_update_secret_metadata_preserves_grants_and_internal_policy(monkeypatch):
+ published = []
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda event_type, data: published.append((event_type, data)))
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
+
+ with api._vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="FETCH_TOKEN",
+ protection="protected",
+ sealed=_sealed("fetch"),
+ tags=["old", "skill:legacy"],
+ description="Old description",
+ policy={"allowed_hosts": ["old.example.com"], "auth": {"type": "bearer"}},
+ )
+ request = vault_service.create_access_request(
+ conn,
+ source_selector={"tags": ["old"]},
+ requester={"source": "test", "session_id": "ses_1"},
+ delivery={"session_id": "ses_1", "mode": "run"},
+ )
+ grant = _grant_from_request(conn, request, session_id="ses_1")
+ conn.execute(
+ vault_secrets.update()
+ .where(vault_secrets.c.name == "FETCH_TOKEN")
+ .values(policy=json.dumps({"allowed_hosts": ["old.example.com"], "auth": {"type": "bearer"}, "always_ask": True}))
+ )
+ original_updated_at = conn.execute(select(vault_secrets.c.updated_at).where(vault_secrets.c.name == "FETCH_TOKEN")).scalar_one()
+
+ updated = api.update_vault_secret(
+ "FETCH_TOKEN",
+ {
+ "description": "New description",
+ "tags": ["prod", "skill:github"],
+ "policy": {
+ "always_ask": True,
+ "allowed_hosts": ["old.example.com"],
+ "auth": {"type": "bearer"},
+ },
+ },
+ )
+
+ assert updated["ok"] is True
+ secret = updated["secret"]
+ assert secret["description"] == "New description"
+ assert secret["tags"] == ["prod", "skill:github"]
+ assert secret["policy"] == {
+ "always_ask": True,
+ "allowed_hosts": ["old.example.com"],
+ "auth": {"type": "bearer"},
+ }
+ assert ("vaults.updated", {"scope": "secret", "secret_name": "FETCH_TOKEN"}) in published
+ with api._vault_engine().connect() as conn:
+ grant_row = conn.execute(select(vault_service.vault_grants).where(vault_service.vault_grants.c.id == grant["id"])).mappings().one()
+ assert grant_row["status"] == "active"
+ assert conn.execute(select(vault_secrets.c.updated_at).where(vault_secrets.c.name == "FETCH_TOKEN")).scalar_one() == original_updated_at
+ events = conn.execute(select(vault_audit.c.event, vault_audit.c.secret_name)).all()
+ assert ("metadata-updated", "FETCH_TOKEN") in events
+
+
+def test_update_secret_metadata_expires_grants_when_fetch_policy_changes(monkeypatch, avault_p2):
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda *args, **kwargs: None)
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
+ agent_release = Mock(return_value={"released": True})
+ monkeypatch.setattr(api, "avault_agent_release", agent_release)
+
+ with api._vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="FETCH_POLICY_CHANGE",
+ protection="protected",
+ sealed=_sealed("fetch-policy"),
+ policy={"allowed_hosts": ["old.example.com"], "auth": {"type": "bearer"}},
+ )
+ request = vault_service.create_access_request(
+ conn,
+ "FETCH_POLICY_CHANGE",
+ purpose="fetch",
+ requester={"source": "test", "session_id": "ses_1"},
+ delivery={"session_id": "ses_1", "mode": "fetch"},
+ )
+ grant = _grant_from_request(conn, request, session_id="ses_1")
+
+ updated = api.update_vault_secret(
+ "FETCH_POLICY_CHANGE",
+ {"policy": {"allowed_hosts": ["api.github.com"], "auth": {"type": "header", "name": "X-GitHub-Token"}}},
+ )
+
+ assert updated["ok"] is True
+ assert updated["secret"]["policy"] == {
+ "allowed_hosts": ["api.github.com"],
+ "auth": {"type": "header", "name": "X-GitHub-Token"},
+ }
+ with api._vault_engine().connect() as conn:
+ grant_row = conn.execute(select(vault_service.vault_grants).where(vault_service.vault_grants.c.id == grant["id"])).mappings().one()
+ assert grant_row["status"] == "expired"
+ events = conn.execute(select(vault_audit.c.event, vault_audit.c.grant_id)).all()
+ assert ("grant-expired-policy-changed", grant["id"]) in events
+ agent_release.assert_called_once_with(grant_id=grant["id"])
+
+
+def test_update_secret_metadata_repairs_invalid_stored_fetch_policy(monkeypatch):
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda *args, **kwargs: None)
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
+ with api._vault_engine().begin() as conn:
+ vault_service.create_secret(conn, name="FETCH_REPAIR", sealed=_sealed("fetch-repair"))
+ conn.execute(
+ vault_secrets.update()
+ .where(vault_secrets.c.name == "FETCH_REPAIR")
+ .values(policy=json.dumps({"allowed_hosts": ["api.github.com"], "auth": {"type": "header", "name": "Host"}}))
+ )
+
+ updated = api.update_vault_secret(
+ "FETCH_REPAIR",
+ {"policy": {"allowed_hosts": ["api.github.com"], "auth": {"type": "header", "name": "X-Api-Key"}}},
+ )
+
+ assert updated["ok"] is True
+ assert updated["secret"]["policy"] == {
+ "allowed_hosts": ["api.github.com"],
+ "auth": {"type": "header", "name": "X-Api-Key"},
+ }
+
+
+def test_update_secret_metadata_rejects_unusable_fetch_auth_names(monkeypatch):
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda *args, **kwargs: None)
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
+ with api._vault_engine().begin() as conn:
+ vault_service.create_secret(conn, name="FETCH_BAD_AUTH", sealed=_sealed("fetch-bad-auth"))
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.update_vault_secret(
+ "FETCH_BAD_AUTH",
+ {"policy": {"allowed_hosts": ["api.github.com"], "auth": {"type": "header", "name": "Host"}}},
+ )
+
+ assert exc.value.code == "invalid_metadata"
+
+
+def test_update_secret_metadata_does_not_stale_pending_protected_grant(monkeypatch, avault_p2):
+ agent_grant = Mock(return_value={"granted": 1, "ttl_secs": 300})
+ monkeypatch.setattr(api, "avault_agent_grant", agent_grant)
+ monkeypatch.setattr(api, "validate_avault_agent_pubkey", Mock())
+
+ api.create_vault_secret(
+ {
+ "name": "PENDING_PROTECTED",
+ "protection": "protected",
+ "sealed": {"ciphertext": "ct-protected", "nonce": "n-protected", "wrap_meta": "wm-protected"},
+ "tags": ["old"],
+ }
+ )
+ requested = api.request_vault_access({"name": "PENDING_PROTECTED", "session_id": "ses_1"})
+ request_id = requested["request"]["id"]
+ grant_id = requested["request"]["card"]["grant_options"][0]["grant_id"]
+
+ api.update_vault_secret("PENDING_PROTECTED", {"description": "Edited while pending", "tags": ["new"]})
+
+ hydrated = api.get_vault_request(request_id, audience=vault_service.REQUEST_AUDIENCE_UI)
+ unlock_material = hydrated["request"]["card"]["grant_options"][0]["unlock_material"]
+ assert unlock_material[0]["name"] == "PENDING_PROTECTED"
+
+ fulfilled = api.fulfill_vault_access_request(
+ request_id,
+ {
+ "grant_id": grant_id,
+ "session_id": "ses_1",
+ "agent_pubkey": {"public_key": "pk", "fingerprint": "fp"},
+ "deks": [
+ {
+ "name": "PENDING_PROTECTED",
+ "dek_blindbox": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "approval": {"nonce": "bm9uY2UtMTIzNDU2", "expires_at_unix": 4102444800},
+ }
+ ],
+ },
+ )
+
+ assert fulfilled["ok"] is True
+ assert fulfilled["grant"]["id"] == grant_id
+ assert fulfilled["grant"]["member_snapshot"] == ["PENDING_PROTECTED"]
+
+
+def test_update_secret_metadata_rejects_secret_material(monkeypatch):
+ from unittest.mock import Mock
+
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ api.create_vault_secret(
+ {
+ "name": "NO_VALUE_PATCH",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ }
+ )
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.update_vault_secret("NO_VALUE_PATCH", {"tags": ["prod"], "value": "plaintext"})
+
+ assert exc.value.code == "secret_material_rejected"
+
+
def test_create_with_links_persists_skill_link(monkeypatch):
from unittest.mock import Mock
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index b223a9264..8704f2428 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -14,6 +14,7 @@ from pathlib import Path
from unittest.mock import Mock
import pytest
+from sqlalchemy import select
from storage import vault_service
from storage.models import vault_audit, vault_grants, vault_requests
@@ -224,6 +225,97 @@ def test_vault_sign_command_flag_does_not_shadow_root_command():
assert cli._vault_cli_delivery(args)["command"] == "wallet sign"
+def test_edit_updates_value_free_metadata(capfd):
+ _create_standard_secret(
+ "EDIT_ME",
+ tags=["old"],
+ description="old description",
+ policy={"allowed_hosts": ["old.example.com"], "auth": {"type": "bearer"}, "always_ask": True},
+ )
+
+ code = cli.cmd_vault_edit(
+ _ns(
+ name="EDIT_ME",
+ description="new description",
+ tag=["prod,deploy"],
+ skill=["github-review"],
+ allow_host=["https://api.github.com/repos"],
+ fetch_auth="header",
+ auth_name="X-GitHub-Token",
+ )
+ )
+
+ assert code == 0
+ payload = json.loads(capfd.readouterr().out)
+ secret = payload["secret"]
+ assert secret["description"] == "new description"
+ assert secret["tags"] == ["prod", "deploy", "skill:github-review"]
+ assert secret["policy"] == {
+ "always_ask": True,
+ "allowed_hosts": ["api.github.com"],
+ "auth": {"type": "header", "name": "X-GitHub-Token"},
+ }
+
+
+def test_edit_preserves_untouched_tag_classes(capfd):
+ _create_standard_secret("EDIT_TAG_CLASSES", tags=["old", "skill:legacy"])
+
+ code = cli.cmd_vault_edit(_ns(name="EDIT_TAG_CLASSES", tag=["prod"]))
+
+ assert code == 0
+ payload = json.loads(capfd.readouterr().out)
+ assert payload["secret"]["tags"] == ["prod", "skill:legacy"]
+
+ code = cli.cmd_vault_edit(_ns(name="EDIT_TAG_CLASSES", skill=["github-review"]))
+
+ assert code == 0
+ payload = json.loads(capfd.readouterr().out)
+ assert payload["secret"]["tags"] == ["prod", "skill:github-review"]
+
+
+def test_edit_policy_releases_resident_grant(capfd, monkeypatch):
+ from vibe import api
+
+ agent_release = Mock(return_value={"released": True})
+ monkeypatch.setattr(api, "avault_agent_release", agent_release)
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="EDIT_POLICY_GRANT",
+ protection="protected",
+ sealed=_sealed("edit-policy-grant"),
+ policy={"allowed_hosts": ["old.example.com"], "auth": {"type": "bearer"}},
+ )
+ req = vault_service.create_access_request(
+ conn,
+ "EDIT_POLICY_GRANT",
+ purpose="fetch",
+ requester={"session_id": "ses_1"},
+ delivery={"session_id": "ses_1", "mode": "fetch"},
+ )
+ grant = _grant_from_request(conn, req, session_id="ses_1")
+
+ code = cli.cmd_vault_edit(_ns(name="EDIT_POLICY_GRANT", allow_host=["api.github.com"], fetch_auth="bearer"))
+
+ assert code == 0
+ payload = json.loads(capfd.readouterr().out)
+ assert payload["secret"]["policy"] == {"allowed_hosts": ["api.github.com"], "auth": {"type": "bearer"}}
+ agent_release.assert_called_once_with(grant_id=grant["id"])
+ with cli._open_vault_engine().connect() as conn:
+ status = conn.execute(select(vault_service.vault_grants.c.status).where(vault_service.vault_grants.c.id == grant["id"])).scalar_one()
+ assert status == "expired"
+
+
+def test_edit_metadata_json_rejects_secret_material(capfd):
+ _create_standard_secret("EDIT_SAFE")
+
+ code = cli.cmd_vault_edit(_ns(name="EDIT_SAFE", metadata_json='{"tags":["prod"],"value":"plaintext"}'))
+
+ assert code == 1
+ payload = json.loads(capfd.readouterr().err)
+ assert payload["code"] == "secret_material_rejected"
+
+
def test_discover_reports_value_free_capabilities(tmp_path, capfd, monkeypatch):
_create_standard_secret("STANDARD_KEY")
with cli._open_vault_engine().begin() as conn:
diff --git a/vibe/api.py b/vibe/api.py
index 5c0e2dac5..b8e2aaf44 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1461,6 +1461,34 @@ def _reject_plaintext_value_fields(payload: object) -> None:
_reject_plaintext_value_fields(item)
+_VAULT_METADATA_ALLOWED_FIELDS = {"description", "tags", "policy"}
+_VAULT_METADATA_SECRET_FIELDS = {
+ "value",
+ "sealed",
+ "envelope",
+ "blind_box",
+ "ciphertext",
+ "nonce",
+ "wrap_meta",
+ "private_key",
+ "secret",
+}
+
+
+def _reject_vault_metadata_secret_fields(payload: object, *, path: str = "payload") -> None:
+ if isinstance(payload, dict):
+ for key, item in payload.items():
+ if str(key) in _VAULT_METADATA_SECRET_FIELDS:
+ raise VaultApiError(
+ f"{path}.{key} is not allowed in vault metadata updates",
+ code="secret_material_rejected",
+ )
+ _reject_vault_metadata_secret_fields(item, path=f"{path}.{key}")
+ elif isinstance(payload, list):
+ for index, item in enumerate(payload):
+ _reject_vault_metadata_secret_fields(item, path=f"{path}[{index}]")
+
+
def _sealed_from_payload(payload: dict):
from storage.vault_crypto import Sealed
@@ -1602,6 +1630,39 @@ def create_vault_secret(payload: dict) -> dict:
return {"ok": True, "secret": meta}
+def update_vault_secret(name: str, payload: dict) -> dict:
+ from storage import vault_crypto, vault_service
+
+ if not isinstance(payload, dict):
+ raise VaultApiError("payload must be an object", code="invalid_payload")
+ _reject_vault_metadata_secret_fields(payload)
+ secret_name = str(name or "").strip()
+ if not vault_crypto.is_valid_secret_name(secret_name):
+ raise VaultApiError("invalid secret name (use ^[A-Za-z_][A-Za-z0-9_]*$)", code="invalid_name")
+ extra_fields = set(payload) - _VAULT_METADATA_ALLOWED_FIELDS
+ if extra_fields:
+ raise VaultApiError(
+ f"unsupported vault metadata fields: {', '.join(sorted(extra_fields))}",
+ code="invalid_metadata",
+ status=409,
+ )
+ kwargs = {field: payload[field] for field in _VAULT_METADATA_ALLOWED_FIELDS if field in payload}
+ if not kwargs:
+ raise VaultApiError("no metadata fields were provided", code="missing_metadata", status=409)
+ engine = _vault_engine()
+ release_scopes: list[dict[str, str]] = []
+ try:
+ with engine.begin() as conn:
+ meta = vault_service.update_secret_metadata(conn, secret_name, release_scopes=release_scopes, **kwargs)
+ except vault_service.SecretNotFoundError as exc:
+ raise VaultApiError(f"secret '{secret_name}' not found", code="secret_not_found", status=404) from exc
+ except vault_service.VaultServiceError as exc:
+ raise VaultApiError(str(exc), code="invalid_metadata", status=409) from exc
+ release_vault_agent_scopes(release_scopes, reason="update_vault_secret")
+ _publish_vaults_updated(scope="secret", secret_name=meta.get("name") or secret_name)
+ return {"ok": True, "secret": meta}
+
+
def delete_vault_secret(name: str) -> dict:
from storage import vault_service
diff --git a/vibe/cli.py b/vibe/cli.py
index c71c979ea..32bc68796 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -4972,6 +4972,183 @@ def cmd_vault_rm(args):
return 1
+def _split_vault_metadata_values(values: list[str] | None) -> list[str]:
+ out: list[str] = []
+ for raw in values or []:
+ for item in str(raw).split(","):
+ item = item.strip()
+ if item:
+ out.append(item)
+ return out
+
+
+_VAULT_EDIT_ALLOWED_FIELDS = {"description", "tags", "policy"}
+_VAULT_EDIT_SECRET_FIELDS = {
+ "value",
+ "sealed",
+ "envelope",
+ "blind_box",
+ "ciphertext",
+ "nonce",
+ "wrap_meta",
+ "private_key",
+ "secret",
+}
+
+
+def _reject_vault_edit_secret_fields(value: object, *, path: str = "metadata") -> None:
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if str(key) in _VAULT_EDIT_SECRET_FIELDS:
+ raise TaskCliError(f"{path}.{key} is not allowed in vault metadata", code="secret_material_rejected")
+ _reject_vault_edit_secret_fields(item, path=f"{path}.{key}")
+ elif isinstance(value, list):
+ for index, item in enumerate(value):
+ _reject_vault_edit_secret_fields(item, path=f"{path}[{index}]")
+
+
+def _vault_edit_payload_from_args(args, *, current: dict, help_command: str) -> dict:
+ metadata_json = getattr(args, "metadata_json", None)
+ flag_fields = [
+ getattr(args, "description", None) is not None,
+ bool(getattr(args, "clear_description", False)),
+ bool(getattr(args, "tag", None)),
+ bool(getattr(args, "skill", None)),
+ bool(getattr(args, "clear_tags", False)),
+ bool(getattr(args, "allow_host", None)),
+ bool(getattr(args, "clear_allowed_hosts", False)),
+ getattr(args, "fetch_auth", None) is not None,
+ bool(getattr(args, "clear_fetch_auth", False)),
+ getattr(args, "auth_name", None) is not None,
+ ]
+ if metadata_json and any(flag_fields):
+ raise TaskCliError("use --metadata-json or field flags, not both", code="invalid_metadata", help_command=help_command)
+ if metadata_json:
+ try:
+ payload = json.loads(str(metadata_json))
+ except ValueError as exc:
+ raise TaskCliError(f"invalid metadata JSON: {exc}", code="invalid_metadata", help_command=help_command) from exc
+ if not isinstance(payload, dict):
+ raise TaskCliError("metadata JSON must be an object", code="invalid_metadata", help_command=help_command)
+ try:
+ _reject_vault_edit_secret_fields(payload)
+ except TaskCliError as exc:
+ exc.help_command = help_command
+ raise
+ extra_fields = set(payload) - _VAULT_EDIT_ALLOWED_FIELDS
+ if extra_fields:
+ raise TaskCliError(
+ f"unsupported vault metadata fields: {', '.join(sorted(extra_fields))}",
+ code="invalid_metadata",
+ help_command=help_command,
+ )
+ return payload
+
+ payload: dict[str, object] = {}
+ if getattr(args, "description", None) is not None and getattr(args, "clear_description", False):
+ raise TaskCliError("use --description or --clear-description, not both", code="invalid_metadata", help_command=help_command)
+ if getattr(args, "description", None) is not None:
+ payload["description"] = str(args.description)
+ elif getattr(args, "clear_description", False):
+ payload["description"] = None
+
+ if getattr(args, "clear_tags", False) and (getattr(args, "tag", None) or getattr(args, "skill", None)):
+ raise TaskCliError("use --clear-tags or --tag/--skill, not both", code="invalid_metadata", help_command=help_command)
+ if getattr(args, "clear_tags", False):
+ payload["tags"] = []
+ elif getattr(args, "tag", None) or getattr(args, "skill", None):
+ current_tags = [str(tag) for tag in current.get("tags") or [] if isinstance(tag, str) and tag]
+ current_plain_tags = [tag for tag in current_tags if not tag.startswith("skill:")]
+ current_skill_tags = [tag for tag in current_tags if tag.startswith("skill:")]
+ tags = _split_vault_metadata_values(getattr(args, "tag", None)) if getattr(args, "tag", None) else current_plain_tags
+ skill_tags = (
+ [
+ skill if skill.startswith("skill:") else f"skill:{skill}"
+ for skill in _split_vault_metadata_values(getattr(args, "skill", None))
+ ]
+ if getattr(args, "skill", None)
+ else current_skill_tags
+ )
+ tags.extend(skill_tags)
+ payload["tags"] = tags
+
+ policy_requested = any(
+ [
+ getattr(args, "allow_host", None),
+ getattr(args, "clear_allowed_hosts", False),
+ getattr(args, "fetch_auth", None) is not None,
+ getattr(args, "clear_fetch_auth", False),
+ getattr(args, "auth_name", None) is not None,
+ ]
+ )
+ if policy_requested:
+ if getattr(args, "clear_allowed_hosts", False) and getattr(args, "allow_host", None):
+ raise TaskCliError("use --clear-allowed-hosts or --allow-host, not both", code="invalid_metadata", help_command=help_command)
+ if getattr(args, "clear_fetch_auth", False) and getattr(args, "fetch_auth", None) is not None:
+ raise TaskCliError("use --clear-fetch-auth or --fetch-auth, not both", code="invalid_metadata", help_command=help_command)
+ if getattr(args, "auth_name", None) is not None and getattr(args, "fetch_auth", None) not in {"header", "query"}:
+ raise TaskCliError("--auth-name requires --fetch-auth header or --fetch-auth query", code="invalid_metadata", help_command=help_command)
+ current_policy = current.get("policy") if isinstance(current.get("policy"), dict) else {}
+ policy: dict[str, object] = {}
+ if getattr(args, "clear_allowed_hosts", False):
+ policy["allowed_hosts"] = []
+ elif getattr(args, "allow_host", None):
+ policy["allowed_hosts"] = _split_vault_metadata_values(getattr(args, "allow_host", None))
+ elif current_policy.get("allowed_hosts") is not None:
+ policy["allowed_hosts"] = current_policy.get("allowed_hosts")
+
+ if not getattr(args, "clear_fetch_auth", False):
+ auth_type = getattr(args, "fetch_auth", None)
+ if auth_type is None:
+ current_auth = current_policy.get("auth") if isinstance(current_policy.get("auth"), dict) else None
+ if current_auth:
+ policy["auth"] = current_auth
+ elif auth_type == "bearer":
+ policy["auth"] = {"type": "bearer"}
+ else:
+ policy["auth"] = {"type": auth_type, "name": str(getattr(args, "auth_name", "") or "").strip()}
+ payload["policy"] = policy
+
+ if not payload:
+ raise TaskCliError("no metadata fields were provided", code="missing_metadata", help_command=help_command)
+ return payload
+
+
+def cmd_vault_edit(args):
+ from storage import vault_service
+ from vibe import api
+
+ help_command = "vibe vault edit --help"
+ try:
+ engine = _open_vault_engine()
+ release_scopes: list[dict[str, str]] = []
+ with engine.begin() as conn:
+ current = vault_service.get_secret_meta(conn, args.name)
+ payload = _vault_edit_payload_from_args(args, current=current, help_command=help_command)
+ secret = vault_service.update_secret_metadata(
+ conn,
+ args.name,
+ release_scopes=release_scopes,
+ **{key: payload[key] for key in ("description", "tags", "policy") if key in payload},
+ )
+ api.release_vault_agent_scopes(release_scopes, reason="vault_edit")
+ _publish_cli_vaults_updated(scope="secret", secret_name=secret.get("name") or args.name)
+ _print_cli_payload("vault_secret", secret=secret)
+ return 0
+ except vault_service.SecretNotFoundError:
+ _print_task_error(TaskCliError(f"secret '{args.name}' not found", code="secret_not_found", help_command=help_command))
+ return 1
+ except vault_service.VaultServiceError as exc:
+ _print_task_error(TaskCliError(str(exc), code="invalid_metadata", help_command=help_command))
+ return 1
+ except TaskCliError as exc:
+ _print_task_error(exc)
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
def cmd_vault_access(args):
from storage import vault_crypto, vault_service
@@ -10149,7 +10326,7 @@ def build_parser():
)
vault_subparsers = vault_parser.add_subparsers(
dest="vault_command",
- metavar="{list,discover,rm,run,fetch,access,sign,await,request,export,inject,key}",
+ metavar="{list,discover,edit,rm,run,fetch,access,sign,await,request,export,inject,key}",
)
vault_subparsers.required = True
@@ -10185,6 +10362,36 @@ def build_parser():
vault_rm_parser.add_argument("name", help="Secret name to delete")
_add_json_noop(vault_rm_parser)
+ vault_edit_parser = vault_subparsers.add_parser(
+ "edit",
+ help="Edit value-free secret metadata",
+ description=(
+ "Edit Vault metadata only: description, tags/skill tags, and brokered-fetch policy. "
+ "This command never accepts or changes secret values, key material, kind, protection tier, or name."
+ ),
+ epilog=(
+ "Examples:\n"
+ " vibe vault edit OPENAI_API_KEY --description 'OpenAI production key' --tag prod --skill support\n"
+ " vibe vault edit GITHUB_TOKEN --allow-host api.github.com --fetch-auth bearer\n"
+ " vibe vault edit GITHUB_TOKEN --metadata-json '{\"tags\":[\"prod\"],\"policy\":{\"allowed_hosts\":[\"api.github.com\"]}}'"
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault edit --help",
+ )
+ vault_edit_parser.add_argument("name", help="Secret name to edit")
+ vault_edit_parser.add_argument("--description", help="Replace the description")
+ vault_edit_parser.add_argument("--clear-description", action="store_true", help="Clear the description")
+ vault_edit_parser.add_argument("--tag", action="append", metavar="TAG[,TAG2]", help="Replace normal tags. Repeatable; comma-separated values allowed.")
+ vault_edit_parser.add_argument("--skill", action="append", metavar="SKILL[,SKILL2]", help="Replace skill tags using skill:<name>. Repeatable.")
+ vault_edit_parser.add_argument("--clear-tags", action="store_true", help="Clear all normal and skill tags")
+ vault_edit_parser.add_argument("--allow-host", action="append", metavar="HOST[,HOST2]", help="Replace allowed fetch hosts. Repeatable; comma-separated values allowed.")
+ vault_edit_parser.add_argument("--clear-allowed-hosts", action="store_true", help="Clear allowed fetch hosts")
+ vault_edit_parser.add_argument("--fetch-auth", choices=["bearer", "header", "query"], help="Set the fetch credential injection mode")
+ vault_edit_parser.add_argument("--auth-name", help="Header or query parameter name for --fetch-auth header/query")
+ vault_edit_parser.add_argument("--clear-fetch-auth", action="store_true", help="Clear explicit fetch auth policy")
+ vault_edit_parser.add_argument("--metadata-json", help="Inline JSON object with description, tags, and/or policy")
+ _add_json_noop(vault_edit_parser)
+
vault_run_parser = vault_subparsers.add_parser(
"run",
help="Run a command with secrets injected into its environment",
@@ -11117,6 +11324,8 @@ def main():
sys.exit(cmd_vault_list(args))
if args.vault_command == "discover":
sys.exit(cmd_vault_discover(args))
+ if args.vault_command == "edit":
+ sys.exit(cmd_vault_edit(args))
if args.vault_command == "rm":
sys.exit(cmd_vault_rm(args))
if args.vault_command == "run":
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 96db76e43..0f6bc6193 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3139,6 +3139,16 @@ def vault_secrets_post():
return _vault_error_response(exc)
[email protected]("/api/vault/secrets/<name>", methods=["PATCH"])
+def vault_secret_patch(name):
+ from vibe import api
+
+ try:
+ return jsonify(api.update_vault_secret(name, request.json or {}))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
@app.route("/api/vault/secrets/<name>", methods=["DELETE"])
def vault_secret_delete(name):
from vibe import api