Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(vault): close protected delete HTTP authz hole (#824)

Call White7ea172f2c885
diff --git a/storage/alembic/versions/20260707_0029_vault_protected_delete_authz.py b/storage/alembic/versions/20260707_0029_vault_protected_delete_authz.py
new file mode 100644
index 000000000..1e5b87139
--- /dev/null
+++ b/storage/alembic/versions/20260707_0029_vault_protected_delete_authz.py
@@ -0,0 +1,90 @@
+"""vault protected delete WebAuthn authz
+
+Revision ID: 20260707_0029
+Revises: 20260705_0028
+Create Date: 2026-07-07
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260707_0029"
+down_revision = "20260705_0028"
+branch_labels = None
+depends_on = None
+
+
+def _table_exists(name: str) -> bool:
+ bind = op.get_bind()
+ return bind.exec_driver_sql(
+ "select 1 from sqlite_master where type = 'table' and name = ?",
+ (name,),
+ ).first() is not None
+
+
+def upgrade() -> None:
+ if not _table_exists("vault_auth_factors"):
+ op.create_table(
+ "vault_auth_factors",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("kind", sa.String(), nullable=False),
+ sa.Column("label", sa.Text(), nullable=True),
+ sa.Column("rp_id", sa.String(), nullable=False),
+ sa.Column("credential_id", sa.Text(), nullable=False),
+ sa.Column("public_key", sa.Text(), nullable=False),
+ sa.Column("alg", sa.Integer(), nullable=False),
+ sa.Column("sign_count", sa.Integer(), nullable=False, server_default="0"),
+ sa.Column("transports", sa.Text(), nullable=True),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.Column("last_used_at", sa.String(), nullable=True),
+ sa.Column("disabled_at", sa.String(), nullable=True),
+ sa.UniqueConstraint("credential_id", name="uq_vault_auth_factors_credential_id"),
+ )
+ op.create_index(
+ "ix_vault_auth_factors_kind_rp",
+ "vault_auth_factors",
+ ["kind", "rp_id", "disabled_at"],
+ if_not_exists=True,
+ )
+
+ if not _table_exists("vault_operation_challenges"):
+ op.create_table(
+ "vault_operation_challenges",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("operation", sa.String(), nullable=False),
+ sa.Column("secret_name", sa.String(), nullable=True),
+ sa.Column("secret_id", sa.String(), nullable=True),
+ sa.Column("secret_updated_at", sa.String(), nullable=True),
+ sa.Column("challenge_hash", sa.String(), nullable=False),
+ sa.Column("rp_id", sa.String(), nullable=False),
+ sa.Column("origin", sa.Text(), nullable=False),
+ sa.Column("expires_at", sa.String(), nullable=False),
+ sa.Column("consumed_at", sa.String(), nullable=True),
+ sa.Column("factor_id", sa.String(), nullable=True),
+ sa.Column("created_at", sa.String(), nullable=False),
+ )
+ op.create_index(
+ "ix_vault_operation_challenges_lookup",
+ "vault_operation_challenges",
+ ["operation", "secret_name", "expires_at"],
+ if_not_exists=True,
+ )
+ op.create_index(
+ "ix_vault_operation_challenges_consumed",
+ "vault_operation_challenges",
+ ["consumed_at", "expires_at"],
+ if_not_exists=True,
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_vault_operation_challenges_consumed", table_name="vault_operation_challenges", if_exists=True)
+ op.drop_index("ix_vault_operation_challenges_lookup", table_name="vault_operation_challenges", if_exists=True)
+ if _table_exists("vault_operation_challenges"):
+ op.drop_table("vault_operation_challenges")
+ op.drop_index("ix_vault_auth_factors_kind_rp", table_name="vault_auth_factors", if_exists=True)
+ if _table_exists("vault_auth_factors"):
+ op.drop_table("vault_auth_factors")
diff --git a/storage/migrations.py b/storage/migrations.py
index b7cb9a00f..91f2b8ea7 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -40,6 +40,12 @@ HEAD_TABLES = INITIAL_TABLES | {
"show_session_events",
"media_objects",
"web_push_subscriptions",
+ "vault_secrets",
+ "vault_requests",
+ "vault_grants",
+ "vault_audit",
+ "vault_auth_factors",
+ "vault_operation_challenges",
}
PRE_SHOW_SESSION_EVENTS_HEAD_TABLES = INITIAL_TABLES | {
"run_definitions",
@@ -88,6 +94,10 @@ HEAD_REQUIRED_COLUMNS = {
}
HEAD_ONLY_REQUIRED_COLUMNS = {
"web_push_subscriptions": {"device_id"},
+ "vault_requests": {"callback_status"},
+ "vault_grants": {"agent_ready", "agent_ready_at"},
+ "vault_auth_factors": {"credential_id", "public_key", "alg", "sign_count"},
+ "vault_operation_challenges": {"challenge_hash", "rp_id", "origin", "expires_at", "consumed_at"},
}
UNRELEASED_OLD_INITIAL_TABLES = [
"session_messages",
@@ -606,6 +616,23 @@ def _ensure_agent_events_indexes(conn: sqlite3.Connection, tables: set[str]) ->
)
+def _ensure_vault_authz_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:
+ if "vault_auth_factors" in tables:
+ conn.execute(
+ "create index if not exists ix_vault_auth_factors_kind_rp "
+ "on vault_auth_factors (kind, rp_id, disabled_at)"
+ )
+ if "vault_operation_challenges" in tables:
+ conn.execute(
+ "create index if not exists ix_vault_operation_challenges_lookup "
+ "on vault_operation_challenges (operation, secret_name, expires_at)"
+ )
+ conn.execute(
+ "create index if not exists ix_vault_operation_challenges_consumed "
+ "on vault_operation_challenges (consumed_at, expires_at)"
+ )
+
+
def _delete_historical_message_tool_calls(conn: sqlite3.Connection, tables: set[str]) -> None:
if "messages" not in tables:
return
@@ -633,6 +660,7 @@ def _ensure_head_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:
_ensure_new_background_indexes(conn)
_ensure_messages_query_indexes(conn, tables)
_ensure_agent_events_indexes(conn, tables)
+ _ensure_vault_authz_indexes(conn, tables)
def _missing_head_schema_description(conn: sqlite3.Connection, tables: set[str]) -> str:
diff --git a/storage/models.py b/storage/models.py
index 671a445c3..c0435f6b4 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -594,6 +594,45 @@ vault_grants = Table(
Index("ix_vault_grants_session_purpose", "session_id", "purpose"),
)
+vault_auth_factors = Table(
+ "vault_auth_factors",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("kind", String, nullable=False),
+ Column("label", Text, nullable=True),
+ Column("rp_id", String, nullable=False),
+ Column("credential_id", Text, nullable=False),
+ Column("public_key", Text, nullable=False),
+ Column("alg", Integer, nullable=False),
+ Column("sign_count", Integer, nullable=False, server_default=text("0")),
+ Column("transports", Text, nullable=True),
+ Column("created_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ Column("last_used_at", String, nullable=True),
+ Column("disabled_at", String, nullable=True),
+ UniqueConstraint("credential_id", name="uq_vault_auth_factors_credential_id"),
+ Index("ix_vault_auth_factors_kind_rp", "kind", "rp_id", "disabled_at"),
+)
+
+vault_operation_challenges = Table(
+ "vault_operation_challenges",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("operation", String, nullable=False),
+ Column("secret_name", String, nullable=True),
+ Column("secret_id", String, nullable=True),
+ Column("secret_updated_at", String, nullable=True),
+ Column("challenge_hash", String, nullable=False),
+ Column("rp_id", String, nullable=False),
+ Column("origin", Text, nullable=False),
+ Column("expires_at", String, nullable=False),
+ Column("consumed_at", String, nullable=True),
+ Column("factor_id", String, nullable=True),
+ Column("created_at", String, nullable=False),
+ Index("ix_vault_operation_challenges_lookup", "operation", "secret_name", "expires_at"),
+ Index("ix_vault_operation_challenges_consumed", "consumed_at", "expires_at"),
+)
+
# Append-only audit log. Secret VALUES never appear here — only names, requesters,
# and delivery summaries.
vault_audit = Table(
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 0df3d3311..ac69df049 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import json
import logging
import re
+import secrets
import threading
import uuid
from dataclasses import dataclass
@@ -28,8 +29,15 @@ from sqlalchemy import func, or_, select
from sqlalchemy.engine import Connection
from sqlalchemy.exc import IntegrityError
-from storage import vault_crypto
-from storage.models import vault_audit, vault_grants, vault_requests, vault_secrets
+from storage import vault_crypto, vault_webauthn
+from storage.models import (
+ vault_audit,
+ vault_auth_factors,
+ vault_grants,
+ vault_operation_challenges,
+ vault_requests,
+ vault_secrets,
+)
from storage.vault_addresses import derive_addresses
from storage.vault_crypto import Sealed
@@ -38,6 +46,8 @@ logger = logging.getLogger(__name__)
SKILL_TAG_PREFIX = "skill:"
DEFAULT_ENV_GRANT_TTL_SECONDS = 300
DEFAULT_TAG_GRANT_TTL_SECONDS = 900
+DEFAULT_AUTHZ_CHALLENGE_TTL_SECONDS = 120
+AUTH_FACTOR_REGISTRATION_AUTHZ_OPERATION = "authorize_webauthn_factor_registration"
DEFAULT_GRANT_TTL_SECONDS = {
"env": DEFAULT_ENV_GRANT_TTL_SECONDS,
"tag": DEFAULT_TAG_GRANT_TTL_SECONDS,
@@ -117,6 +127,16 @@ class CardHydrationPolicy:
include_protected_unlock_material: bool
+@dataclass(frozen=True)
+class ProtectedOperationAuthz:
+ operation: str
+ secret_name: str
+ secret_id: str
+ secret_updated_at: str | None
+ challenge_id: str
+ factor_id: str
+
+
class VaultServiceError(Exception):
"""Base class for vault data-layer errors."""
@@ -176,6 +196,22 @@ class VaultAlreadyInitializedError(VaultServiceError):
pass
+class SecretNotProtectedError(VaultServiceError):
+ pass
+
+
+class ProtectedAuthRequiredError(VaultServiceError):
+ pass
+
+
+class ProtectedAuthzSetupRequiredError(VaultServiceError):
+ pass
+
+
+class InvalidProtectedAuthzError(VaultServiceError):
+ pass
+
+
class VaultGrantRuntimeCache:
"""Process-local grant delivery readiness tracker.
@@ -1301,6 +1337,447 @@ def _require_row(conn: Connection, name: str) -> dict[str, Any]:
return dict(row)
+def _new_challenge() -> tuple[str, str]:
+ challenge = secrets.token_bytes(32)
+ return vault_webauthn.b64encode(challenge), vault_webauthn.challenge_hash(challenge)
+
+
+def _challenge_expiry(ttl_seconds: int = DEFAULT_AUTHZ_CHALLENGE_TTL_SECONDS) -> str:
+ return (datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)).isoformat()
+
+
+def _stored_json_list(raw: str | None) -> list[str]:
+ value = _loads(raw)
+ if not isinstance(value, list):
+ return []
+ return [str(item) for item in value if isinstance(item, str) and item]
+
+
+def _factor_payload(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "kind": row.get("kind"),
+ "label": row.get("label"),
+ "rp_id": row.get("rp_id"),
+ "credential_id": row.get("credential_id"),
+ "alg": row.get("alg"),
+ "transports": _stored_json_list(row.get("transports")),
+ "created_at": row.get("created_at"),
+ "last_used_at": row.get("last_used_at"),
+ }
+
+
+def _usable_webauthn_factor_rows(conn: Connection, *, rp_id: str) -> list[dict[str, Any]]:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(vault_auth_factors).where(
+ vault_auth_factors.c.kind == "webauthn",
+ vault_auth_factors.c.rp_id == rp_id,
+ vault_auth_factors.c.disabled_at.is_(None),
+ )
+ ).mappings()
+ ]
+
+
+def _has_any_webauthn_factor(conn: Connection) -> bool:
+ return (
+ conn.execute(
+ select(vault_auth_factors.c.id)
+ .where(
+ vault_auth_factors.c.kind == "webauthn",
+ vault_auth_factors.c.disabled_at.is_(None),
+ )
+ .limit(1)
+ ).first()
+ is not None
+ )
+
+
+def list_webauthn_auth_factors(conn: Connection, *, rp_id: str | None = None) -> list[dict[str, Any]]:
+ stmt = select(vault_auth_factors).where(
+ vault_auth_factors.c.kind == "webauthn",
+ vault_auth_factors.c.disabled_at.is_(None),
+ )
+ if rp_id:
+ stmt = stmt.where(vault_auth_factors.c.rp_id == rp_id)
+ return [_factor_payload(dict(row)) for row in conn.execute(stmt).mappings()]
+
+
+def _challenge_row(conn: Connection, challenge_id: str, *, operation: str) -> dict[str, Any]:
+ row = conn.execute(
+ select(vault_operation_challenges).where(
+ vault_operation_challenges.c.id == challenge_id,
+ vault_operation_challenges.c.operation == operation,
+ )
+ ).mappings().first()
+ if row is None:
+ raise InvalidProtectedAuthzError("protected operation challenge was not found")
+ return dict(row)
+
+
+def _reject_unusable_challenge(row: dict[str, Any]) -> None:
+ if row.get("consumed_at"):
+ raise InvalidProtectedAuthzError("protected operation challenge was already used")
+ expires_at = _parse_iso_datetime(row.get("expires_at"))
+ if expires_at is None or expires_at <= datetime.now(timezone.utc):
+ raise InvalidProtectedAuthzError("protected operation challenge expired")
+
+
+def _consume_challenge(conn: Connection, challenge_id: str, *, factor_id: str) -> None:
+ result = conn.execute(
+ vault_operation_challenges.update()
+ .where(vault_operation_challenges.c.id == challenge_id, vault_operation_challenges.c.consumed_at.is_(None))
+ .values(consumed_at=_now(), factor_id=factor_id)
+ )
+ if result.rowcount != 1:
+ raise InvalidProtectedAuthzError("protected operation challenge was already used")
+
+
+def _create_webauthn_assertion_challenge(
+ conn: Connection,
+ *,
+ operation: str,
+ rp_id: str,
+ origin: str,
+ factors: list[dict[str, Any]],
+ ttl_seconds: int,
+) -> dict[str, Any]:
+ challenge, challenge_digest = _new_challenge()
+ challenge_id = _id("vop")
+ expires_at = _challenge_expiry(ttl_seconds)
+ conn.execute(
+ vault_operation_challenges.insert().values(
+ id=challenge_id,
+ operation=operation,
+ secret_name=None,
+ secret_id=None,
+ secret_updated_at=None,
+ challenge_hash=challenge_digest,
+ rp_id=rp_id,
+ origin=origin,
+ expires_at=expires_at,
+ created_at=_now(),
+ )
+ )
+ allow_credentials = []
+ for factor in factors:
+ credential: dict[str, Any] = {
+ "type": "public-key",
+ "id": factor["credential_id"],
+ "factor_id": factor["id"],
+ }
+ transports = _stored_json_list(factor.get("transports"))
+ if transports:
+ credential["transports"] = transports
+ allow_credentials.append(credential)
+ return {
+ "challenge_id": challenge_id,
+ "expires_at": expires_at,
+ "webauthn": {
+ "challenge": challenge,
+ "rpId": rp_id,
+ "userVerification": "required",
+ "allowCredentials": allow_credentials,
+ },
+ }
+
+
+def _verify_webauthn_operation_authz(
+ conn: Connection,
+ payload: dict[str, Any] | None,
+ *,
+ operation: str,
+ required_rp_id: str | None = None,
+ required_origin: str | None = None,
+) -> tuple[str, dict[str, Any]]:
+ if not isinstance(payload, dict):
+ raise ProtectedAuthRequiredError("protected operation requires WebAuthn authorization")
+ if payload.get("kind") != "webauthn":
+ raise InvalidProtectedAuthzError("protected operation requires WebAuthn authorization")
+ challenge_id = str(payload.get("challenge_id") or "").strip()
+ factor_id = str(payload.get("factor_id") or "").strip()
+ if not challenge_id or not factor_id:
+ raise InvalidProtectedAuthzError("protected operation authorization is incomplete")
+ challenge = _challenge_row(conn, challenge_id, operation=operation)
+ _reject_unusable_challenge(challenge)
+ if required_rp_id is not None and challenge.get("rp_id") != required_rp_id:
+ raise InvalidProtectedAuthzError("protected operation authorization RP mismatch")
+ if required_origin is not None and challenge.get("origin") != required_origin:
+ raise InvalidProtectedAuthzError("protected operation authorization origin mismatch")
+ factor = conn.execute(
+ select(vault_auth_factors).where(
+ vault_auth_factors.c.id == factor_id,
+ vault_auth_factors.c.kind == "webauthn",
+ vault_auth_factors.c.disabled_at.is_(None),
+ )
+ ).mappings().first()
+ if factor is None:
+ raise InvalidProtectedAuthzError("protected operation authorization factor was not found")
+ factor = dict(factor)
+ if factor.get("rp_id") != challenge.get("rp_id"):
+ raise InvalidProtectedAuthzError("protected operation authorization factor RP mismatch")
+ assertion = payload.get("assertion")
+ try:
+ result = vault_webauthn.verify_assertion(
+ assertion if isinstance(assertion, dict) else {},
+ credential_id=str(factor["credential_id"]),
+ public_key=str(factor["public_key"]),
+ alg=int(factor["alg"]),
+ stored_sign_count=int(factor.get("sign_count") or 0),
+ expected_challenge_hash=str(challenge["challenge_hash"]),
+ expected_origin=str(challenge["origin"]),
+ rp_id=str(challenge["rp_id"]),
+ )
+ except vault_webauthn.WebAuthnVerificationError as exc:
+ raise InvalidProtectedAuthzError(str(exc)) from exc
+ now = _now()
+ next_sign_count = max(int(factor.get("sign_count") or 0), result.sign_count)
+ conn.execute(
+ vault_auth_factors.update()
+ .where(vault_auth_factors.c.id == factor_id)
+ .values(sign_count=next_sign_count, last_used_at=now, updated_at=now)
+ )
+ _consume_challenge(conn, challenge_id, factor_id=factor_id)
+ return factor_id, challenge
+
+
+def create_webauthn_registration_options(
+ conn: Connection,
+ *,
+ rp_id: str,
+ origin: str,
+ ttl_seconds: int = DEFAULT_AUTHZ_CHALLENGE_TTL_SECONDS,
+) -> dict[str, Any]:
+ challenge, challenge_digest = _new_challenge()
+ challenge_id = _id("vop")
+ expires_at = _challenge_expiry(ttl_seconds)
+ now = _now()
+ existing_factors = _usable_webauthn_factor_rows(conn, rp_id=rp_id)
+ conn.execute(
+ vault_operation_challenges.insert().values(
+ id=challenge_id,
+ operation="register_webauthn_factor",
+ secret_name=None,
+ secret_id=None,
+ secret_updated_at=None,
+ challenge_hash=challenge_digest,
+ rp_id=rp_id,
+ origin=origin,
+ expires_at=expires_at,
+ created_at=now,
+ )
+ )
+ response = {
+ "ok": True,
+ "challenge_id": challenge_id,
+ "expires_at": expires_at,
+ "rp_id": rp_id,
+ "origin": origin,
+ "requires_existing_factor": bool(existing_factors),
+ "webauthn": {
+ "rp": {"name": "Avibe Vault", "id": rp_id},
+ "user": {
+ "id": vault_webauthn.b64encode(b"avibe-vault"),
+ "name": "avibe-vault",
+ "displayName": "Avibe Vault",
+ },
+ "challenge": challenge,
+ "pubKeyCredParams": [
+ {"type": "public-key", "alg": vault_webauthn.ALG_ES256},
+ {"type": "public-key", "alg": vault_webauthn.ALG_RS256},
+ ],
+ "authenticatorSelection": {"residentKey": "required", "userVerification": "required"},
+ "extensions": {"prf": {}},
+ },
+ }
+ if existing_factors:
+ response["authorization"] = _create_webauthn_assertion_challenge(
+ conn,
+ operation=AUTH_FACTOR_REGISTRATION_AUTHZ_OPERATION,
+ rp_id=rp_id,
+ origin=origin,
+ factors=existing_factors,
+ ttl_seconds=ttl_seconds,
+ )
+ return response
+
+
+def register_webauthn_factor(
+ conn: Connection,
+ payload: dict[str, Any],
+ *,
+ rp_id: str | None = None,
+ origin: str | None = None,
+ establishment: bool = False,
+) -> dict[str, Any]:
+ if not isinstance(payload, dict):
+ raise InvalidProtectedAuthzError("WebAuthn factor registration payload must be an object")
+ challenge_id = str(payload.get("challenge_id") or "").strip()
+ if not challenge_id:
+ raise InvalidProtectedAuthzError("WebAuthn factor registration challenge_id is required")
+ challenge = _challenge_row(conn, challenge_id, operation="register_webauthn_factor")
+ _reject_unusable_challenge(challenge)
+ challenge_rp_id = str(challenge.get("rp_id") or "")
+ challenge_origin = str(challenge.get("origin") or "")
+ if (rp_id is not None and challenge_rp_id != rp_id) or (origin is not None and challenge_origin != origin):
+ raise InvalidProtectedAuthzError("WebAuthn factor registration origin mismatch")
+ rp_id = rp_id or challenge_rp_id
+ origin = origin or challenge_origin
+ existing_factors = _usable_webauthn_factor_rows(conn, rp_id=rp_id)
+ if establishment:
+ if _has_any_webauthn_factor(conn):
+ raise InvalidProtectedAuthzError("first WebAuthn factor can only be registered once during vault establishment")
+ elif not existing_factors:
+ raise ProtectedAuthzSetupRequiredError(
+ "first WebAuthn factor must be registered during protected vault establishment; re-create this protected vault"
+ )
+ else:
+ _verify_webauthn_operation_authz(
+ conn,
+ payload.get("authz") if isinstance(payload.get("authz"), dict) else None,
+ operation=AUTH_FACTOR_REGISTRATION_AUTHZ_OPERATION,
+ required_rp_id=rp_id,
+ required_origin=origin,
+ )
+ credential = payload.get("credential")
+ if not isinstance(credential, dict):
+ raise InvalidProtectedAuthzError("WebAuthn factor registration credential is required")
+ try:
+ registration = vault_webauthn.verify_registration(
+ credential,
+ expected_challenge_hash=str(challenge["challenge_hash"]),
+ expected_origin=origin,
+ rp_id=rp_id,
+ )
+ except vault_webauthn.WebAuthnVerificationError as exc:
+ raise InvalidProtectedAuthzError(str(exc)) from exc
+ response = credential.get("response") if isinstance(credential.get("response"), dict) else {}
+ transports = _string_list(response.get("transports"), field="transports") if "transports" in response else []
+ label = _optional_string(payload.get("label"), field="label") if "label" in payload else None
+ factor_id = _id("vaf")
+ now = _now()
+ try:
+ conn.execute(
+ vault_auth_factors.insert().values(
+ id=factor_id,
+ kind="webauthn",
+ label=label,
+ rp_id=rp_id,
+ credential_id=registration.credential_id,
+ public_key=registration.public_key,
+ alg=registration.alg,
+ sign_count=registration.sign_count,
+ transports=json.dumps(transports) if transports else None,
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ except IntegrityError as exc:
+ raise InvalidProtectedAuthzError("WebAuthn credential is already registered") from exc
+ _consume_challenge(conn, challenge_id, factor_id=factor_id)
+ audit(conn, "auth-factor-registered", delivery={"factor_id": factor_id, "kind": "webauthn", "rp_id": rp_id})
+ row = conn.execute(select(vault_auth_factors).where(vault_auth_factors.c.id == factor_id)).mappings().one()
+ return {"ok": True, "factor": _factor_payload(dict(row))}
+
+
+def create_delete_challenge(
+ conn: Connection,
+ name: str,
+ *,
+ rp_id: str,
+ origin: str,
+ ttl_seconds: int = DEFAULT_AUTHZ_CHALLENGE_TTL_SECONDS,
+) -> dict[str, Any]:
+ row = _require_row(conn, name)
+ if row.get("protection") != "protected":
+ raise SecretNotProtectedError(name)
+ factors = _usable_webauthn_factor_rows(conn, rp_id=rp_id)
+ if not factors:
+ raise ProtectedAuthzSetupRequiredError("protected delete requires a registered passkey authorization factor")
+ challenge, challenge_digest = _new_challenge()
+ challenge_id = _id("vop")
+ expires_at = _challenge_expiry(ttl_seconds)
+ conn.execute(
+ vault_operation_challenges.insert().values(
+ id=challenge_id,
+ operation="delete_secret",
+ secret_name=name,
+ secret_id=row.get("id"),
+ secret_updated_at=row.get("updated_at"),
+ challenge_hash=challenge_digest,
+ rp_id=rp_id,
+ origin=origin,
+ expires_at=expires_at,
+ created_at=_now(),
+ )
+ )
+ audit(
+ conn,
+ "delete-challenge-issued",
+ secret_name=name,
+ delivery={"challenge_id": challenge_id, "rp_id": rp_id},
+ )
+ allow_credentials = []
+ for factor in factors:
+ credential: dict[str, Any] = {
+ "type": "public-key",
+ "id": factor["credential_id"],
+ "factor_id": factor["id"],
+ }
+ transports = _stored_json_list(factor.get("transports"))
+ if transports:
+ credential["transports"] = transports
+ allow_credentials.append(credential)
+ return {
+ "ok": True,
+ "challenge_id": challenge_id,
+ "expires_at": expires_at,
+ "operation": "delete_secret",
+ "secret_name": name,
+ "webauthn": {
+ "challenge": challenge,
+ "rpId": rp_id,
+ "userVerification": "required",
+ "allowCredentials": allow_credentials,
+ },
+ }
+
+
+def verify_delete_secret_authz(conn: Connection, name: str, payload: dict[str, Any] | None) -> ProtectedOperationAuthz:
+ if not isinstance(payload, dict):
+ raise ProtectedAuthRequiredError("protected delete requires WebAuthn authorization")
+ row = _require_row(conn, name)
+ if row.get("protection") != "protected":
+ raise SecretNotProtectedError(name)
+ factor_id, challenge = _verify_webauthn_operation_authz(
+ conn,
+ payload,
+ operation="delete_secret",
+ )
+ challenge_id = str(payload.get("challenge_id") or "").strip()
+ if (
+ challenge.get("secret_name") != name
+ or challenge.get("secret_id") != row.get("id")
+ or challenge.get("secret_updated_at") != row.get("updated_at")
+ ):
+ raise InvalidProtectedAuthzError("protected delete challenge does not match the current secret row")
+ audit(
+ conn,
+ "delete-authorized",
+ secret_name=name,
+ delivery={"challenge_id": challenge_id, "factor_id": factor_id},
+ )
+ return ProtectedOperationAuthz(
+ operation="delete_secret",
+ secret_name=name,
+ secret_id=str(row["id"]),
+ secret_updated_at=row.get("updated_at"),
+ challenge_id=challenge_id,
+ factor_id=factor_id,
+ )
+
+
def fulfill_pending_provision_requests_for_secret(
conn: Connection,
name: str,
@@ -1333,6 +1810,8 @@ def create_secret(
policy: dict[str, Any] | None = None,
public_meta: dict[str, Any] | None = None,
establishing_vmk: bool = False,
+ authz_factor_registration: dict[str, Any] | None = None,
+ authz_factor_origin: str | None = None,
provision_request_id: str | None = None,
) -> dict[str, Any]:
"""Create a secret from a caller-supplied encrypted envelope; return masked metadata.
@@ -1369,6 +1848,8 @@ def create_secret(
is not None
):
raise VaultAlreadyInitializedError("a protected vault already exists; unlock it instead of re-initializing")
+ if not isinstance(authz_factor_registration, dict):
+ raise ProtectedAuthzSetupRequiredError("protected vault establishment requires a passkey authorization factor")
now = _now()
normalized_tags = _normalize_tags(tags)
@@ -1405,6 +1886,13 @@ def create_secret(
raise SecretNameCaseConflictError(name, existing_name) from exc
raise SecretExistsError(name) from exc
audit(conn, "created", secret_name=name)
+ if establishing_vmk and protection == "protected":
+ register_webauthn_factor(
+ conn,
+ authz_factor_registration or {},
+ origin=authz_factor_origin,
+ establishment=True,
+ )
decided_at = _now()
if provision_row is not None:
result = conn.execute(
@@ -1736,13 +2224,54 @@ def rotate_secret(
return _meta_payload(_require_row(conn, name))
-def delete_secret(conn: Connection, name: str, *, cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE) -> None:
+def _reject_missing_protected_delete_authz(row: dict[str, Any], authz: ProtectedOperationAuthz | None) -> None:
+ if row.get("protection") != "protected":
+ return
+ if authz is None:
+ raise ProtectedAuthRequiredError("protected delete requires verified authorization")
+ if (
+ authz.operation != "delete_secret"
+ or authz.secret_name != row.get("name")
+ or authz.secret_id != row.get("id")
+ or authz.secret_updated_at != row.get("updated_at")
+ ):
+ raise InvalidProtectedAuthzError("protected delete authorization does not match the current secret row")
+
+
+def _disable_webauthn_factors_if_vault_deestablished(conn: Connection) -> None:
+ protected_row = conn.execute(
+ select(vault_secrets.c.id).where(vault_secrets.c.protection == "protected").limit(1)
+ ).first()
+ if protected_row is not None:
+ return
+ now = _now()
+ result = conn.execute(
+ vault_auth_factors.update()
+ .where(vault_auth_factors.c.kind == "webauthn", vault_auth_factors.c.disabled_at.is_(None))
+ .values(disabled_at=now, updated_at=now)
+ )
+ disabled_count = int(result.rowcount or 0)
+ if disabled_count:
+ audit(conn, "auth-factors-disabled", delivery={"reason": "vault-deestablished", "count": disabled_count})
+
+
+def delete_secret(
+ conn: Connection,
+ name: str,
+ *,
+ protected_authz: ProtectedOperationAuthz | None = None,
+ cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,
+) -> None:
row = conn.execute(select(vault_secrets).where(vault_secrets.c.name == name)).mappings().first()
if row is None:
raise SecretNotFoundError(name)
+ row = dict(row)
+ _reject_missing_protected_delete_authz(row, protected_authz)
_expire_pending_requests_for_secret(conn, name, reason="request-expired-envelope-changed")
_expire_active_grants_for_secret(conn, name, cache=cache, reason="grant-expired-envelope-changed")
conn.execute(vault_secrets.delete().where(vault_secrets.c.name == name))
+ if row.get("protection") == "protected":
+ _disable_webauthn_factors_if_vault_deestablished(conn)
audit(conn, "deleted", secret_name=name)
diff --git a/storage/vault_webauthn.py b/storage/vault_webauthn.py
new file mode 100644
index 000000000..61dcc553c
--- /dev/null
+++ b/storage/vault_webauthn.py
@@ -0,0 +1,352 @@
+"""Minimal WebAuthn registration/assertion verification for Vault authz.
+
+This module intentionally implements only the server-verifiable pieces Vaults
+need today: passkey registration public-key capture and fresh assertion checks
+for protected operations. Passkeys commonly use ``none`` attestation, so device
+provenance and the registration signature are not a trust anchor here. The
+authorization factor trust anchor is instead enforced by ``vault_service``:
+the first factor is bound to the one-time protected-vault establishment
+transaction, and later factors must chain from a fresh assertion by an existing
+factor.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+from dataclasses import dataclass
+from typing import Any
+from urllib.parse import urlsplit
+
+from cryptography.exceptions import InvalidSignature
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
+
+WEBAUTHN_CREATE_TYPE = "webauthn.create"
+WEBAUTHN_GET_TYPE = "webauthn.get"
+ALG_ES256 = -7
+ALG_RS256 = -257
+SUPPORTED_ALGS = {ALG_ES256, ALG_RS256}
+
+_FLAG_UP = 0x01
+_FLAG_UV = 0x04
+_FLAG_AT = 0x40
+
+
+class WebAuthnVerificationError(ValueError):
+ """Raised when a WebAuthn ceremony cannot be verified."""
+
+
+@dataclass(frozen=True)
+class WebAuthnRpContext:
+ origin: str
+ rp_id: str
+
+
+@dataclass(frozen=True)
+class WebAuthnRegistration:
+ credential_id: str
+ public_key: str
+ alg: int
+ sign_count: int
+
+
+@dataclass(frozen=True)
+class WebAuthnAssertion:
+ credential_id: str
+ sign_count: int
+
+
+def b64encode(data: bytes) -> str:
+ return base64.b64encode(data).decode("ascii")
+
+
+def b64decode(value: str) -> bytes:
+ raw = str(value or "").strip()
+ if not raw:
+ raise WebAuthnVerificationError("missing base64 field")
+ padded = raw + "=" * (-len(raw) % 4)
+ try:
+ if "-" in raw or "_" in raw:
+ return base64.urlsafe_b64decode(padded)
+ return base64.b64decode(padded, validate=True)
+ except Exception as exc:
+ try:
+ return base64.urlsafe_b64decode(padded)
+ except Exception:
+ raise WebAuthnVerificationError("invalid base64 field") from exc
+
+
+def challenge_hash(challenge: bytes) -> str:
+ return hashlib.sha256(challenge).hexdigest()
+
+
+def rp_context_from_origin(origin: str) -> WebAuthnRpContext:
+ parsed = urlsplit(str(origin or "").strip())
+ scheme = parsed.scheme.lower()
+ host = (parsed.hostname or "").lower()
+ if not scheme or not host:
+ raise WebAuthnVerificationError("invalid WebAuthn origin")
+ if host == "localhost":
+ if scheme not in {"http", "https"}:
+ raise WebAuthnVerificationError("localhost WebAuthn origin must be http or https")
+ elif scheme != "https":
+ raise WebAuthnVerificationError("WebAuthn origin must be https outside localhost")
+ if _is_raw_ip(host) or ":" in host or (host != "localhost" and "." not in host):
+ raise WebAuthnVerificationError("WebAuthn RP id must be localhost or a domain")
+ netloc = parsed.netloc.lower()
+ if not netloc:
+ raise WebAuthnVerificationError("invalid WebAuthn origin")
+ return WebAuthnRpContext(origin=f"{scheme}://{netloc}", rp_id=host)
+
+
+def _is_raw_ip(host: str) -> bool:
+ parts = host.split(".")
+ return len(parts) == 4 and all(part.isdigit() and 0 <= int(part) <= 255 for part in parts)
+
+
+class _CborReader:
+ def __init__(self, data: bytes):
+ self._data = data
+ self._pos = 0
+
+ @property
+ def pos(self) -> int:
+ return self._pos
+
+ def decode(self) -> Any:
+ initial = self._read_byte()
+ major = initial >> 5
+ add = initial & 0x1F
+ if major == 0:
+ return self._read_uint(add)
+ if major == 1:
+ return -1 - self._read_uint(add)
+ if major == 2:
+ return self._read(self._read_uint(add))
+ if major == 3:
+ return self._read(self._read_uint(add)).decode("utf-8")
+ if major == 4:
+ return [self.decode() for _ in range(self._read_uint(add))]
+ if major == 5:
+ return {self.decode(): self.decode() for _ in range(self._read_uint(add))}
+ if major == 6:
+ self._read_uint(add)
+ return self.decode()
+ if major == 7:
+ if add == 20:
+ return False
+ if add == 21:
+ return True
+ if add == 22:
+ return None
+ raise WebAuthnVerificationError("unsupported CBOR simple value")
+ raise WebAuthnVerificationError("unsupported CBOR value")
+
+ def _read_uint(self, add: int) -> int:
+ if add < 24:
+ return add
+ if add == 24:
+ return self._read_byte()
+ if add == 25:
+ return int.from_bytes(self._read(2), "big")
+ if add == 26:
+ return int.from_bytes(self._read(4), "big")
+ if add == 27:
+ return int.from_bytes(self._read(8), "big")
+ raise WebAuthnVerificationError("indefinite CBOR values are not supported")
+
+ def _read_byte(self) -> int:
+ return self._read(1)[0]
+
+ def _read(self, length: int) -> bytes:
+ end = self._pos + length
+ if end > len(self._data):
+ raise WebAuthnVerificationError("truncated CBOR value")
+ out = self._data[self._pos : end]
+ self._pos = end
+ return out
+
+
+def _cbor_decode(data: bytes) -> Any:
+ reader = _CborReader(data)
+ value = reader.decode()
+ if reader.pos != len(data):
+ raise WebAuthnVerificationError("trailing CBOR bytes")
+ return value
+
+
+def _cbor_decode_first(data: bytes) -> Any:
+ reader = _CborReader(data)
+ return reader.decode()
+
+
+def _client_data(client_data_json_b64: str, *, expected_type: str, expected_challenge_hash: str, expected_origin: str) -> tuple[dict[str, Any], bytes]:
+ client_data_json = b64decode(client_data_json_b64)
+ try:
+ client_data = json.loads(client_data_json)
+ except json.JSONDecodeError as exc:
+ raise WebAuthnVerificationError("invalid clientDataJSON") from exc
+ if client_data.get("type") != expected_type:
+ raise WebAuthnVerificationError("unexpected WebAuthn client data type")
+ if client_data.get("origin") != expected_origin:
+ raise WebAuthnVerificationError("unexpected WebAuthn origin")
+ if client_data.get("crossOrigin") not in {None, False}:
+ raise WebAuthnVerificationError("cross-origin WebAuthn assertions are not accepted")
+ challenge = b64decode(str(client_data.get("challenge") or ""))
+ if challenge_hash(challenge) != expected_challenge_hash:
+ raise WebAuthnVerificationError("WebAuthn challenge mismatch")
+ return client_data, client_data_json
+
+
+def _parse_authenticator_data(auth_data: bytes, *, rp_id: str, require_attested: bool) -> tuple[int, int, bytes | None, bytes | None]:
+ if len(auth_data) < 37:
+ raise WebAuthnVerificationError("authenticatorData is too short")
+ rp_id_hash = auth_data[:32]
+ expected_rp_id_hash = hashlib.sha256(rp_id.encode("utf-8")).digest()
+ if rp_id_hash != expected_rp_id_hash:
+ raise WebAuthnVerificationError("WebAuthn RP id hash mismatch")
+ flags = auth_data[32]
+ if flags & _FLAG_UP != _FLAG_UP:
+ raise WebAuthnVerificationError("WebAuthn user presence is required")
+ if flags & _FLAG_UV != _FLAG_UV:
+ raise WebAuthnVerificationError("WebAuthn user verification is required")
+ sign_count = int.from_bytes(auth_data[33:37], "big")
+ if not require_attested:
+ return flags, sign_count, None, None
+ if flags & _FLAG_AT != _FLAG_AT:
+ raise WebAuthnVerificationError("WebAuthn attested credential data is required")
+ offset = 37 + 16
+ if len(auth_data) < offset + 2:
+ raise WebAuthnVerificationError("WebAuthn credential id is truncated")
+ credential_id_len = int.from_bytes(auth_data[offset : offset + 2], "big")
+ offset += 2
+ credential_id = auth_data[offset : offset + credential_id_len]
+ if len(credential_id) != credential_id_len:
+ raise WebAuthnVerificationError("WebAuthn credential id is truncated")
+ offset += credential_id_len
+ public_key = auth_data[offset:]
+ if not public_key:
+ raise WebAuthnVerificationError("WebAuthn credential public key is missing")
+ _public_key_from_cose(public_key)
+ return flags, sign_count, credential_id, public_key
+
+
+def _public_key_from_cose(public_key_cose: bytes):
+ # Authenticator data may include extension output bytes after the COSE key.
+ # The first CBOR item is the credentialPublicKey; trailing bytes belong to
+ # extension data and should not make registration fail.
+ cose = _cbor_decode_first(public_key_cose)
+ if not isinstance(cose, dict):
+ raise WebAuthnVerificationError("invalid COSE public key")
+ alg = cose.get(3)
+ if alg not in SUPPORTED_ALGS:
+ raise WebAuthnVerificationError("unsupported WebAuthn public key algorithm")
+ kty = cose.get(1)
+ if alg == ALG_ES256:
+ if kty != 2 or cose.get(-1) != 1 or not isinstance(cose.get(-2), bytes) or not isinstance(cose.get(-3), bytes):
+ raise WebAuthnVerificationError("invalid ES256 COSE public key")
+ x = int.from_bytes(cose[-2], "big")
+ y = int.from_bytes(cose[-3], "big")
+ try:
+ return ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1()).public_key(), alg
+ except Exception as exc:
+ raise WebAuthnVerificationError("invalid ES256 COSE public key") from exc
+ if kty != 3 or not isinstance(cose.get(-1), bytes) or not isinstance(cose.get(-2), bytes):
+ raise WebAuthnVerificationError("invalid RS256 COSE public key")
+ n = int.from_bytes(cose[-1], "big")
+ e = int.from_bytes(cose[-2], "big")
+ try:
+ return rsa.RSAPublicNumbers(e, n).public_key(), alg
+ except Exception as exc:
+ raise WebAuthnVerificationError("invalid RS256 COSE public key") from exc
+
+
+def verify_registration(
+ credential: dict[str, Any],
+ *,
+ expected_challenge_hash: str,
+ expected_origin: str,
+ rp_id: str,
+) -> WebAuthnRegistration:
+ if not isinstance(credential, dict):
+ raise WebAuthnVerificationError("WebAuthn credential must be an object")
+ response = credential.get("response")
+ if not isinstance(response, dict):
+ raise WebAuthnVerificationError("WebAuthn registration response is missing")
+ _client_data(
+ str(response.get("clientDataJSON") or ""),
+ expected_type=WEBAUTHN_CREATE_TYPE,
+ expected_challenge_hash=expected_challenge_hash,
+ expected_origin=expected_origin,
+ )
+ attestation_object = _cbor_decode(b64decode(str(response.get("attestationObject") or "")))
+ if not isinstance(attestation_object, dict) or not isinstance(attestation_object.get("authData"), bytes):
+ raise WebAuthnVerificationError("invalid WebAuthn attestation object")
+ _flags, sign_count, credential_id, public_key = _parse_authenticator_data(
+ attestation_object["authData"],
+ rp_id=rp_id,
+ require_attested=True,
+ )
+ assert credential_id is not None and public_key is not None
+ raw_id = b64decode(str(credential.get("rawId") or ""))
+ if raw_id != credential_id:
+ raise WebAuthnVerificationError("WebAuthn credential id mismatch")
+ _public_key, alg = _public_key_from_cose(public_key)
+ return WebAuthnRegistration(
+ credential_id=b64encode(credential_id),
+ public_key=b64encode(public_key),
+ alg=alg,
+ sign_count=sign_count,
+ )
+
+
+def verify_assertion(
+ assertion: dict[str, Any],
+ *,
+ credential_id: str,
+ public_key: str,
+ alg: int,
+ stored_sign_count: int,
+ expected_challenge_hash: str,
+ expected_origin: str,
+ rp_id: str,
+) -> WebAuthnAssertion:
+ if not isinstance(assertion, dict):
+ raise WebAuthnVerificationError("WebAuthn assertion must be an object")
+ response = assertion.get("response")
+ if not isinstance(response, dict):
+ raise WebAuthnVerificationError("WebAuthn assertion response is missing")
+ raw_id = b64decode(str(assertion.get("rawId") or ""))
+ if b64encode(raw_id) != credential_id:
+ raise WebAuthnVerificationError("WebAuthn assertion credential mismatch")
+ _client_data_payload, client_data_json = _client_data(
+ str(response.get("clientDataJSON") or ""),
+ expected_type=WEBAUTHN_GET_TYPE,
+ expected_challenge_hash=expected_challenge_hash,
+ expected_origin=expected_origin,
+ )
+ auth_data = b64decode(str(response.get("authenticatorData") or ""))
+ _flags, sign_count, _credential_id, _public_key = _parse_authenticator_data(
+ auth_data,
+ rp_id=rp_id,
+ require_attested=False,
+ )
+ if stored_sign_count > 0 and sign_count <= stored_sign_count:
+ raise WebAuthnVerificationError("WebAuthn signature counter replay")
+ signature = b64decode(str(response.get("signature") or ""))
+ verifier, parsed_alg = _public_key_from_cose(b64decode(public_key))
+ if parsed_alg != alg:
+ raise WebAuthnVerificationError("WebAuthn public key algorithm mismatch")
+ signed = auth_data + hashlib.sha256(client_data_json).digest()
+ try:
+ if alg == ALG_ES256:
+ verifier.verify(signature, signed, ec.ECDSA(hashes.SHA256()))
+ elif alg == ALG_RS256:
+ verifier.verify(signature, signed, padding.PKCS1v15(), hashes.SHA256())
+ else:
+ raise WebAuthnVerificationError("unsupported WebAuthn public key algorithm")
+ except InvalidSignature as exc:
+ raise WebAuthnVerificationError("invalid WebAuthn assertion signature") from exc
+ return WebAuthnAssertion(credential_id=credential_id, sign_count=sign_count)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index df0c739d6..0b6d7c6fb 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -17,7 +17,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260705_0028"
+HEAD_REVISION = "20260707_0029"
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
@@ -50,6 +50,8 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "agent_events" in tables
assert "media_objects" in tables
assert "web_push_subscriptions" in tables
+ assert "vault_auth_factors" in tables
+ assert "vault_operation_challenges" in tables
agent_event_indexes = {
row[1]
for row in conn.execute(
@@ -78,6 +80,18 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
"select name from sqlite_master where type = 'trigger' and tbl_name = 'vault_requests'",
)
}
+ vault_auth_factor_indexes = {
+ row[1]
+ for row in conn.execute(
+ "select seq, name from pragma_index_list('vault_auth_factors')",
+ )
+ }
+ vault_challenge_indexes = {
+ row[1]
+ for row in conn.execute(
+ "select seq, name from pragma_index_list('vault_operation_challenges')",
+ )
+ }
assert "ix_messages_session_created_id" in message_indexes
assert "ix_messages_session_type_created_id" in message_indexes
assert "ix_messages_platform_session_created_id" in message_indexes
@@ -90,6 +104,9 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_user_send")
assert "uq_vault_secrets_name_folded" in vault_secret_indexes
assert "lower(name)" in _index_sql(conn, "uq_vault_secrets_name_folded").lower()
+ assert "ix_vault_auth_factors_kind_rp" in vault_auth_factor_indexes
+ assert "ix_vault_operation_challenges_lookup" in vault_challenge_indexes
+ assert "ix_vault_operation_challenges_consumed" in vault_challenge_indexes
assert "trg_vault_requests_pending_provision_name_case_insert" in vault_request_triggers
assert "trg_vault_requests_pending_provision_name_case_update" in vault_request_triggers
agent_session_indexes = {
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index dd3e1e1dc..cb5fa1096 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -16,8 +16,9 @@ import pytest
from sqlalchemy import select
from storage import vault_service
-from storage.models import vault_audit, vault_requests, vault_secrets
+from storage.models import vault_audit, vault_auth_factors, vault_requests, vault_secrets
from storage.vault_crypto import Sealed
+from tests.vault_webauthn_helpers import WebAuthnTestCredential
from vibe import api
@@ -71,6 +72,46 @@ def _assert_no_unlock_material(payload: object) -> None:
assert "wm-protected" not in encoded
+def _auth_factor_for_credential(credential: WebAuthnTestCredential) -> dict:
+ with api._vault_engine().connect() as conn:
+ row = conn.execute(
+ select(vault_auth_factors).where(vault_auth_factors.c.credential_id == credential.credential_id_b64)
+ ).mappings().one()
+ return dict(row)
+
+
+def _establish_protected_secret_with_factor(
+ name: str = "PROTECTED_DELETE",
+ credential: WebAuthnTestCredential | None = None,
+) -> tuple[WebAuthnTestCredential, dict]:
+ credential = credential or WebAuthnTestCredential()
+ options = api.create_vault_authz_webauthn_options(origin=credential.origin)
+ api.create_vault_secret(
+ {
+ "name": name,
+ "protection": "protected",
+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": {"v": 1, "copies": [], "wrapped_dek": "d"}},
+ "establishing_vmk": True,
+ "authz_factor_registration": credential.registration_payload(
+ challenge_id=options["challenge_id"],
+ challenge_b64=options["webauthn"]["challenge"],
+ ),
+ },
+ origin=credential.origin,
+ )
+ return credential, _auth_factor_for_credential(credential)
+
+
+def _delete_authz_for_secret(credential: WebAuthnTestCredential, factor: dict, name: str, *, sign_count: int = 2) -> dict:
+ challenge = api.create_vault_delete_challenge(name, origin=credential.origin)
+ return credential.assertion_authz(
+ challenge_id=challenge["challenge_id"],
+ factor_id=factor["id"],
+ challenge_b64=challenge["webauthn"]["challenge"],
+ sign_count=sign_count,
+ )
+
+
@pytest.fixture
def avault_p2(monkeypatch):
monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)
@@ -836,6 +877,149 @@ def test_delete_missing_is_404():
assert exc.value.status == 404
+def test_delete_protected_secret_without_assertion_is_rejected(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ api.create_vault_secret(
+ {"name": "PROTECTED_DELETE", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}}
+ )
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.delete_vault_secret("PROTECTED_DELETE")
+
+ assert exc.value.code == "protected_auth_required"
+ assert exc.value.status == 409
+ with api._vault_engine().connect() as conn:
+ assert vault_service.get_secret_meta(conn, "PROTECTED_DELETE")["protection"] == "protected"
+
+
+def test_delete_protected_secret_with_valid_assertion_deletes(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ credential, factor = _establish_protected_secret_with_factor("PROTECTED_DELETE")
+ authz = _delete_authz_for_secret(credential, factor, "PROTECTED_DELETE")
+
+ removed = api.delete_vault_secret("PROTECTED_DELETE", authz=authz)
+
+ assert removed == {"ok": True, "removed": True, "name": "PROTECTED_DELETE"}
+ with api._vault_engine().connect() as conn:
+ with pytest.raises(vault_service.SecretNotFoundError):
+ vault_service.get_secret_meta(conn, "PROTECTED_DELETE")
+
+
+def test_deleting_last_protected_secret_allows_fresh_vault_establishment(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ first, first_factor = _establish_protected_secret_with_factor("FIRST_PROTECTED")
+ authz = _delete_authz_for_secret(first, first_factor, "FIRST_PROTECTED")
+
+ removed = api.delete_vault_secret("FIRST_PROTECTED", authz=authz)
+
+ assert removed["removed"] is True
+ with api._vault_engine().connect() as conn:
+ old_factor = conn.execute(
+ select(vault_auth_factors).where(vault_auth_factors.c.id == first_factor["id"])
+ ).mappings().one()
+ assert old_factor["disabled_at"] is not None
+
+ second = WebAuthnTestCredential(credential_id=b"second-vault-first-factor")
+ _credential, second_factor = _establish_protected_secret_with_factor("SECOND_PROTECTED", second)
+
+ assert second_factor["credential_id"] == second.credential_id_b64
+
+
+def test_forged_webauthn_factor_registration_cannot_authorize_delete(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ _establish_protected_secret_with_factor("PROTECTED_DELETE")
+ forged = WebAuthnTestCredential(credential_id=b"forged-agent-factor")
+ options = api.create_vault_authz_webauthn_options(origin=forged.origin)
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.register_vault_authz_webauthn_factor(
+ forged.registration_payload(
+ challenge_id=options["challenge_id"],
+ challenge_b64=options["webauthn"]["challenge"],
+ ),
+ origin=forged.origin,
+ )
+
+ assert exc.value.code == "protected_auth_required"
+ challenge = api.create_vault_delete_challenge("PROTECTED_DELETE", origin=forged.origin)
+ forged_authz = forged.assertion_authz(
+ challenge_id=challenge["challenge_id"],
+ factor_id="vaf_forged",
+ challenge_b64=challenge["webauthn"]["challenge"],
+ )
+ with pytest.raises(api.VaultApiError) as delete_exc:
+ api.delete_vault_secret("PROTECTED_DELETE", authz=forged_authz)
+ assert delete_exc.value.code == "invalid_protected_authz"
+ with api._vault_engine().connect() as conn:
+ assert vault_service.get_secret_meta(conn, "PROTECTED_DELETE")["protection"] == "protected"
+
+
+def test_registering_second_webauthn_factor_requires_existing_factor_assertion(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ first, first_factor = _establish_protected_secret_with_factor("PROTECTED_DELETE")
+ second = WebAuthnTestCredential(credential_id=b"second-factor")
+ options = api.create_vault_authz_webauthn_options(origin=second.origin)
+ payload = second.registration_payload(
+ challenge_id=options["challenge_id"],
+ challenge_b64=options["webauthn"]["challenge"],
+ )
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.register_vault_authz_webauthn_factor(payload, origin=second.origin)
+ assert exc.value.code == "protected_auth_required"
+
+ payload["authz"] = first.assertion_authz(
+ challenge_id=options["authorization"]["challenge_id"],
+ factor_id=first_factor["id"],
+ challenge_b64=options["authorization"]["webauthn"]["challenge"],
+ )
+ result = api.register_vault_authz_webauthn_factor(payload, origin=second.origin)
+
+ assert result["factor"]["credential_id"] == second.credential_id_b64
+
+
+def test_first_webauthn_factor_registration_only_happens_during_establishment(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ credential = WebAuthnTestCredential()
+ options = api.create_vault_authz_webauthn_options(origin=credential.origin)
+ payload = credential.registration_payload(
+ challenge_id=options["challenge_id"],
+ challenge_b64=options["webauthn"]["challenge"],
+ )
+
+ with pytest.raises(api.VaultApiError) as empty_exc:
+ api.register_vault_authz_webauthn_factor(payload, origin=credential.origin)
+ assert empty_exc.value.code == "protected_authz_setup_required"
+
+ api.create_vault_secret(
+ {"name": "FACTORLESS", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}}
+ )
+ late = WebAuthnTestCredential(credential_id=b"late-first-factor")
+ late_options = api.create_vault_authz_webauthn_options(origin=late.origin)
+ with pytest.raises(api.VaultApiError) as late_exc:
+ api.register_vault_authz_webauthn_factor(
+ late.registration_payload(
+ challenge_id=late_options["challenge_id"],
+ challenge_b64=late_options["webauthn"]["challenge"],
+ ),
+ origin=late.origin,
+ )
+ assert late_exc.value.code == "protected_authz_setup_required"
+
+
+def test_factorless_protected_secret_surfaces_recreate_state_for_delete_challenge(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ api.create_vault_secret(
+ {"name": "FACTORLESS", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}}
+ )
+ credential = WebAuthnTestCredential()
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_delete_challenge("FACTORLESS", origin=credential.origin)
+
+ assert exc.value.code == "protected_authz_setup_required"
+
+
def test_audit_lists_events_without_values(monkeypatch):
from unittest.mock import Mock
@@ -885,15 +1069,9 @@ def test_create_protected_stores_browser_envelope_without_avault(monkeypatch):
def test_protected_create_establishing_vmk_rejects_second_init(monkeypatch):
- first = api.create_vault_secret(
- {
- "name": "FIRST_PROTECTED",
- "protection": "protected",
- "sealed": {"ciphertext": "ct1", "nonce": "n1", "wrap_meta": {"v": 1, "copies": [], "wrapped_dek": "d1"}},
- "establishing_vmk": True,
- }
- )
- assert first["ok"] is True
+ _establish_protected_secret_with_factor("FIRST_PROTECTED")
+ with api._vault_engine().connect() as conn:
+ assert vault_service.get_secret_meta(conn, "FIRST_PROTECTED")["protection"] == "protected"
# A second "establishing" create (concurrent first-time setup) must be rejected so
# the vault key history can't split under a different VMK.
@@ -2342,9 +2520,7 @@ def test_delete_protected_secret_releases_agent_scope(monkeypatch):
monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
agent_release = Mock(return_value={"released": True})
monkeypatch.setattr(api, "avault_agent_release", agent_release)
- api.create_vault_secret(
- {"name": "GRANT_KEY", "protection": "protected", "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"}}
- )
+ credential, factor = _establish_protected_secret_with_factor("GRANT_KEY")
with api._vault_engine().begin() as conn:
req = vault_service.create_access_request(
conn,
@@ -2353,8 +2529,9 @@ def test_delete_protected_secret_releases_agent_scope(monkeypatch):
delivery={"session_id": "ses_1"},
)
grant = _grant_from_request(conn, req, session_id="ses_1")
+ authz = _delete_authz_for_secret(credential, factor, "GRANT_KEY")
- removed = api.delete_vault_secret("GRANT_KEY")
+ removed = api.delete_vault_secret("GRANT_KEY", authz=authz)
assert removed["removed"] is True
agent_release.assert_called_once_with(grant_id=grant["id"])
diff --git a/tests/test_vault_rest.py b/tests/test_vault_rest.py
index da5461797..231b7eae1 100644
--- a/tests/test_vault_rest.py
+++ b/tests/test_vault_rest.py
@@ -4,6 +4,7 @@ import json
from unittest.mock import Mock
+from storage import vault_service
from storage.vault_crypto import Sealed
from tests.ui_server_test_helpers import csrf_headers
from vibe import api
@@ -77,6 +78,25 @@ def test_rest_list_invalid_tag_returns_vault_error():
assert response.get_json()["code"] == "invalid_request"
+def test_rest_delete_protected_without_assertion_is_rejected(monkeypatch):
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+ api.create_vault_secret(
+ {
+ "name": "PROTECTED_HTTP_DELETE",
+ "protection": "protected",
+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},
+ }
+ )
+ client = app.test_client()
+
+ response = client.delete("/api/vault/secrets/PROTECTED_HTTP_DELETE", headers=csrf_headers(client))
+
+ assert response.status_code == 409
+ assert response.get_json()["code"] == "protected_auth_required"
+ with api._vault_engine().connect() as conn:
+ assert vault_service.get_secret_meta(conn, "PROTECTED_HTTP_DELETE")["protection"] == "protected"
+
+
def test_rest_create_rejects_plaintext_value_in_mixed_payloads(monkeypatch):
seal = Mock()
monkeypatch.setattr(api, "avault_seal_blind_box", seal)
diff --git a/tests/test_vault_service.py b/tests/test_vault_service.py
index c05216492..f2cdedee0 100644
--- a/tests/test_vault_service.py
+++ b/tests/test_vault_service.py
@@ -9,10 +9,11 @@ import pytest
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
-from storage import vault_service as vs
+from storage import vault_service as vs, vault_webauthn
from storage.db import create_sqlite_engine
-from storage.models import metadata, vault_grants, vault_requests, vault_secrets
+from storage.models import metadata, vault_auth_factors, vault_grants, vault_operation_challenges, vault_requests, vault_secrets
from storage.vault_crypto import Sealed
+from tests.vault_webauthn_helpers import WebAuthnTestCredential
@pytest.fixture
@@ -32,6 +33,43 @@ def _create(engine, **kw):
return vs.create_secret(conn, sealed=_sealed(kw.get("name", "x").lower()), **kw)
+def _protected_delete_authz(conn, name: str) -> vs.ProtectedOperationAuthz:
+ row = conn.execute(select(vault_secrets).where(vault_secrets.c.name == name)).mappings().one()
+ return vs.ProtectedOperationAuthz(
+ operation="delete_secret",
+ secret_name=row["name"],
+ secret_id=row["id"],
+ secret_updated_at=row["updated_at"],
+ challenge_id="test-challenge",
+ factor_id="test-factor",
+ )
+
+
+def _establish_protected_secret(conn, name: str, credential: WebAuthnTestCredential | None = None) -> tuple[WebAuthnTestCredential, dict]:
+ credential = credential or WebAuthnTestCredential()
+ options = vs.create_webauthn_registration_options(
+ conn,
+ rp_id=credential.rp_id,
+ origin=credential.origin,
+ )
+ vs.create_secret(
+ conn,
+ name=name,
+ protection="protected",
+ sealed=_sealed(name.lower()),
+ establishing_vmk=True,
+ authz_factor_registration=credential.registration_payload(
+ challenge_id=options["challenge_id"],
+ challenge_b64=options["webauthn"]["challenge"],
+ ),
+ authz_factor_origin=credential.origin,
+ )
+ factor = conn.execute(
+ select(vault_auth_factors).where(vault_auth_factors.c.credential_id == credential.credential_id_b64)
+ ).mappings().one()
+ return credential, dict(factor)
+
+
def _grant_from_request(conn, request: dict, *, cache_ready: bool = True, ttl_seconds: int | None = None) -> dict:
option = request["card"]["grant_options"][0]
return vs.create_grant(
@@ -341,7 +379,7 @@ def test_secret_delete_rotate_and_classification_changes_expire_covering_grants(
grant_b = _grant_from_request(conn, vs.create_access_request(conn, "B_KEY"))
grant_c = _grant_from_request(conn, vs.create_access_request(conn, "C_KEY"))
vs.rotate_secret(conn, "A_KEY", _sealed("rotated"))
- vs.delete_secret(conn, "B_KEY")
+ vs.delete_secret(conn, "B_KEY", protected_authz=_protected_delete_authz(conn, "B_KEY"))
vs.update_secret_classification(conn, "C_KEY", protection="standard")
statuses = {
row["id"]: row["status"]
@@ -351,6 +389,150 @@ def test_secret_delete_rotate_and_classification_changes_expire_covering_grants(
assert statuses == {grant_a["id"]: "expired", grant_b["id"]: "expired", grant_c["id"]: "expired"}
+def test_protected_delete_requires_verified_authz_at_chokepoint(vault):
+ _create(vault, name="PROTECTED_KEY", protection="protected")
+
+ with vault.begin() as conn:
+ with pytest.raises(vs.ProtectedAuthRequiredError):
+ vs.delete_secret(conn, "PROTECTED_KEY")
+ assert vs.get_secret_meta(conn, "PROTECTED_KEY")["protection"] == "protected"
+
+
+def test_standard_delete_does_not_require_authz(vault):
+ _create(vault, name="STANDARD_KEY", protection="standard")
+
+ with vault.begin() as conn:
+ vs.delete_secret(conn, "STANDARD_KEY")
+ with pytest.raises(vs.SecretNotFoundError):
+ vs.get_secret_meta(conn, "STANDARD_KEY")
+
+
+def test_webauthn_factor_registration_stores_public_key(vault):
+ credential = WebAuthnTestCredential()
+
+ with vault.begin() as conn:
+ _credential, factor = _establish_protected_secret(conn, "PROTECTED_KEY", credential)
+ row = conn.execute(select(vault_auth_factors).where(vault_auth_factors.c.id == factor["id"])).mappings().one()
+
+ assert factor["credential_id"] == credential.credential_id_b64
+ assert row["public_key"]
+ assert row["alg"] == -7
+ assert json.loads(row["transports"]) == ["internal"]
+
+
+def test_delete_challenge_expiry_and_replay_are_rejected(vault):
+ credential = WebAuthnTestCredential()
+
+ with vault.begin() as conn:
+ _credential, registered = _establish_protected_secret(conn, "PROTECTED_KEY", credential)
+ expired = vs.create_delete_challenge(conn, "PROTECTED_KEY", rp_id=credential.rp_id, origin=credential.origin)
+ conn.execute(
+ vault_operation_challenges.update()
+ .where(vault_operation_challenges.c.id == expired["challenge_id"])
+ .values(expires_at=(datetime.now(timezone.utc) - timedelta(seconds=1)).isoformat())
+ )
+ with pytest.raises(vs.InvalidProtectedAuthzError):
+ vs.verify_delete_secret_authz(
+ conn,
+ "PROTECTED_KEY",
+ credential.assertion_authz(
+ challenge_id=expired["challenge_id"],
+ factor_id=registered["id"],
+ challenge_b64=expired["webauthn"]["challenge"],
+ ),
+ )
+
+ fresh = vs.create_delete_challenge(conn, "PROTECTED_KEY", rp_id=credential.rp_id, origin=credential.origin)
+ authz = credential.assertion_authz(
+ challenge_id=fresh["challenge_id"],
+ factor_id=registered["id"],
+ challenge_b64=fresh["webauthn"]["challenge"],
+ sign_count=3,
+ )
+ assert vs.verify_delete_secret_authz(conn, "PROTECTED_KEY", authz).challenge_id == fresh["challenge_id"]
+ with pytest.raises(vs.InvalidProtectedAuthzError):
+ vs.verify_delete_secret_authz(conn, "PROTECTED_KEY", authz)
+
+
+def test_webauthn_counter_regression_rejects_zero_after_nonzero_counter():
+ credential = WebAuthnTestCredential()
+ challenge = b"counter-challenge"
+ challenge_b64 = vault_webauthn.b64encode(challenge)
+ public_key = vault_webauthn.b64encode(credential.public_key_cose())
+
+ zero_assertion = credential.assertion_authz(
+ challenge_id="vop_counter",
+ factor_id="vaf_counter",
+ challenge_b64=challenge_b64,
+ sign_count=0,
+ )["assertion"]
+ assert (
+ vault_webauthn.verify_assertion(
+ zero_assertion,
+ credential_id=credential.credential_id_b64,
+ public_key=public_key,
+ alg=vault_webauthn.ALG_ES256,
+ stored_sign_count=0,
+ expected_challenge_hash=vault_webauthn.challenge_hash(challenge),
+ expected_origin=credential.origin,
+ rp_id=credential.rp_id,
+ ).sign_count
+ == 0
+ )
+ with pytest.raises(vault_webauthn.WebAuthnVerificationError):
+ vault_webauthn.verify_assertion(
+ zero_assertion,
+ credential_id=credential.credential_id_b64,
+ public_key=public_key,
+ alg=vault_webauthn.ALG_ES256,
+ stored_sign_count=1,
+ expected_challenge_hash=vault_webauthn.challenge_hash(challenge),
+ expected_origin=credential.origin,
+ rp_id=credential.rp_id,
+ )
+
+ increasing_assertion = credential.assertion_authz(
+ challenge_id="vop_counter",
+ factor_id="vaf_counter",
+ challenge_b64=challenge_b64,
+ sign_count=2,
+ )["assertion"]
+ assert (
+ vault_webauthn.verify_assertion(
+ increasing_assertion,
+ credential_id=credential.credential_id_b64,
+ public_key=public_key,
+ alg=vault_webauthn.ALG_ES256,
+ stored_sign_count=1,
+ expected_challenge_hash=vault_webauthn.challenge_hash(challenge),
+ expected_origin=credential.origin,
+ rp_id=credential.rp_id,
+ ).sign_count
+ == 2
+ )
+
+
+def test_webauthn_registration_invalid_cose_point_fails_closed(vault):
+ credential = WebAuthnTestCredential()
+
+ with vault.begin() as conn:
+ options = vs.create_webauthn_registration_options(
+ conn,
+ rp_id=credential.rp_id,
+ origin=credential.origin,
+ )
+ payload = credential.registration_payload(
+ challenge_id=options["challenge_id"],
+ challenge_b64=options["webauthn"]["challenge"],
+ public_key_cose=WebAuthnTestCredential.es256_public_key_cose(1, 1),
+ )
+
+ with pytest.raises(vs.InvalidProtectedAuthzError) as exc:
+ vs.register_webauthn_factor(conn, payload, rp_id=credential.rp_id, origin=credential.origin, establishment=True)
+
+ assert isinstance(exc.value.__cause__, vault_webauthn.WebAuthnVerificationError)
+
+
def test_standard_secret_does_not_create_access_request_unless_always_ask(vault):
_create(vault, name="STANDARD_KEY", protection="standard")
_create(vault, name="ASK_KEY", protection="standard", policy={"always_ask": True})
diff --git a/tests/vault_webauthn_helpers.py b/tests/vault_webauthn_helpers.py
new file mode 100644
index 000000000..6a43330a4
--- /dev/null
+++ b/tests/vault_webauthn_helpers.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+from dataclasses import dataclass
+
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.asymmetric import ec
+
+from storage import vault_webauthn
+
+
+def _b64(data: bytes) -> str:
+ return base64.b64encode(data).decode("ascii")
+
+
+def _b64url(data: bytes) -> str:
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
+
+
+def _b64decode(value: str) -> bytes:
+ return base64.b64decode(value)
+
+
+def _cbor_uint(value: int) -> bytes:
+ if value < 24:
+ return bytes([value])
+ if value < 256:
+ return b"\x18" + value.to_bytes(1, "big")
+ if value < 65536:
+ return b"\x19" + value.to_bytes(2, "big")
+ return b"\x1a" + value.to_bytes(4, "big")
+
+
+def _cbor_int(value: int) -> bytes:
+ if value >= 0:
+ return _cbor_uint(value)
+ encoded = -1 - value
+ raw = _cbor_uint(encoded)
+ return bytes([raw[0] | 0x20]) + raw[1:]
+
+
+def _cbor_bytes(value: bytes) -> bytes:
+ raw = _cbor_uint(len(value))
+ return bytes([raw[0] | 0x40]) + raw[1:] + value
+
+
+def _cbor_text(value: str) -> bytes:
+ encoded = value.encode("utf-8")
+ raw = _cbor_uint(len(encoded))
+ return bytes([raw[0] | 0x60]) + raw[1:] + encoded
+
+
+def _cbor_array(value: list) -> bytes:
+ raw = _cbor_uint(len(value))
+ return bytes([raw[0] | 0x80]) + raw[1:] + b"".join(_cbor(item) for item in value)
+
+
+def _cbor_map(value: dict) -> bytes:
+ raw = _cbor_uint(len(value))
+ return bytes([raw[0] | 0xA0]) + raw[1:] + b"".join(_cbor(key) + _cbor(item) for key, item in value.items())
+
+
+def _cbor(value) -> bytes:
+ if isinstance(value, int):
+ return _cbor_int(value)
+ if isinstance(value, bytes):
+ return _cbor_bytes(value)
+ if isinstance(value, str):
+ return _cbor_text(value)
+ if isinstance(value, list):
+ return _cbor_array(value)
+ if isinstance(value, dict):
+ return _cbor_map(value)
+ raise TypeError(f"unsupported CBOR test value: {type(value).__name__}")
+
+
+def _client_data(*, typ: str, challenge_b64: str, origin: str) -> bytes:
+ return json.dumps(
+ {
+ "type": typ,
+ "challenge": _b64url(_b64decode(challenge_b64)),
+ "origin": origin,
+ "crossOrigin": False,
+ },
+ separators=(",", ":"),
+ ).encode("utf-8")
+
+
+@dataclass
+class WebAuthnTestCredential:
+ rp_id: str = "alex-app.avibe.bot"
+ origin: str = "https://alex-app.avibe.bot"
+ credential_id: bytes = b"test-credential-id"
+
+ def __post_init__(self) -> None:
+ self.private_key = ec.generate_private_key(ec.SECP256R1())
+
+ @property
+ def credential_id_b64(self) -> str:
+ return _b64(self.credential_id)
+
+ @staticmethod
+ def es256_public_key_cose(x: int, y: int) -> bytes:
+ return _cbor(
+ {
+ 1: 2,
+ 3: vault_webauthn.ALG_ES256,
+ -1: 1,
+ -2: x.to_bytes(32, "big"),
+ -3: y.to_bytes(32, "big"),
+ }
+ )
+
+ def public_key_cose(self) -> bytes:
+ numbers = self.private_key.public_key().public_numbers()
+ return self.es256_public_key_cose(numbers.x, numbers.y)
+
+ def registration_payload(
+ self,
+ *,
+ challenge_id: str,
+ challenge_b64: str,
+ sign_count: int = 1,
+ public_key_cose: bytes | None = None,
+ ) -> dict:
+ client_data = _client_data(
+ typ=vault_webauthn.WEBAUTHN_CREATE_TYPE,
+ challenge_b64=challenge_b64,
+ origin=self.origin,
+ )
+ flags = 0x01 | 0x04 | 0x40
+ auth_data = (
+ hashlib.sha256(self.rp_id.encode("utf-8")).digest()
+ + bytes([flags])
+ + sign_count.to_bytes(4, "big")
+ + (b"\x00" * 16)
+ + len(self.credential_id).to_bytes(2, "big")
+ + self.credential_id
+ + (public_key_cose or self.public_key_cose())
+ )
+ attestation_object = _cbor({"fmt": "none", "authData": auth_data, "attStmt": {}})
+ return {
+ "challenge_id": challenge_id,
+ "credential": {
+ "id": _b64url(self.credential_id),
+ "rawId": self.credential_id_b64,
+ "type": "public-key",
+ "response": {
+ "clientDataJSON": _b64(client_data),
+ "attestationObject": _b64(attestation_object),
+ "transports": ["internal"],
+ },
+ },
+ }
+
+ def assertion_authz(
+ self,
+ *,
+ challenge_id: str,
+ factor_id: str,
+ challenge_b64: str,
+ sign_count: int = 2,
+ ) -> dict:
+ client_data = _client_data(
+ typ=vault_webauthn.WEBAUTHN_GET_TYPE,
+ challenge_b64=challenge_b64,
+ origin=self.origin,
+ )
+ auth_data = (
+ hashlib.sha256(self.rp_id.encode("utf-8")).digest()
+ + bytes([0x01 | 0x04])
+ + sign_count.to_bytes(4, "big")
+ )
+ signature = self.private_key.sign(auth_data + hashlib.sha256(client_data).digest(), ec.ECDSA(hashes.SHA256()))
+ return {
+ "kind": "webauthn",
+ "challenge_id": challenge_id,
+ "factor_id": factor_id,
+ "assertion": {
+ "id": _b64url(self.credential_id),
+ "rawId": self.credential_id_b64,
+ "type": "public-key",
+ "response": {
+ "clientDataJSON": _b64(client_data),
+ "authenticatorData": _b64(auth_data),
+ "signature": _b64(signature),
+ "userHandle": None,
+ },
+ },
+ }
diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsx
index f6dc79719..86d4bab66 100644
--- a/ui/src/components/ui/vault-secret-form.tsx
+++ b/ui/src/components/ui/vault-secret-form.tsx
@@ -494,18 +494,29 @@ export const VaultSecretForm: React.FC<{
| { sealed: ProtectedRecordEnvelope }
| { blind_box: Awaited<ReturnType<typeof sealBlindBox>> };
let establishingVmk = false;
+ let authzFactorRegistration: Awaited<ReturnType<typeof protectedVault.sealValue>>['authzFactorRegistration'];
if (protection === 'protected') {
// Browser-sealed under the session VMK; the daemon stores it opaquely (no avault, no
// plaintext). For a signing key this seals the raw 32-byte private key, not a string.
const sealed = await protectedVault.sealValue(secretName, plaintext);
cryptoFields = { sealed: sealed.envelope };
establishingVmk = sealed.establishingVmk;
+ authzFactorRegistration = sealed.authzFactorRegistration;
} else {
const pubkey = await api.getVaultPubkey();
cryptoFields = { blind_box: await sealBlindBox(plaintext, pubkey, standardCreateBlindBoxContext(secretName)) };
}
const created = await api.createVaultSecret(
- { ...base, ...cryptoFields, ...(establishingVmk ? { establishing_vmk: true } : {}) },
+ {
+ ...base,
+ ...cryptoFields,
+ ...(establishingVmk
+ ? {
+ establishing_vmk: true,
+ authz_factor_registration: authzFactorRegistration,
+ }
+ : {}),
+ },
{ handleError: false },
);
if (!created.ok) {
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index e33ecbd2f..f22ad8aef 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -10,11 +10,10 @@ import { Button } from '../ui/button';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { VaultLockIndicator } from '../ui/vault-lock-indicator';
-import { VaultProtectedUnlock } from '../ui/vault-protected-unlock';
import { cn } from '../../lib/utils';
import { partitionTags } from '../../lib/vaultTags';
-import { useProtectedVault, vaultFreshSetup, vaultUnlocked } from '../../lib/useProtectedVault';
-import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';
+import { useProtectedVault } from '../../lib/useProtectedVault';
+import { ApiError, useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import type { ApprovalOutcome } from '../ui/vault-approval-card';
import { SigningAddressList } from '../ui/signing-address-list';
@@ -26,6 +25,15 @@ const PENDING_REQUEST_EXPIRY_GRACE_MS = 100;
const MAX_BROWSER_TIMEOUT_MS = 2_147_483_647;
const messageFromError = (err: unknown) => (err instanceof Error ? err.message : String(err));
+const deleteMessageFromError = (err: unknown, t: TFunction) => {
+ const code = err instanceof ApiError ? err.code : err instanceof Error ? err.message : String(err);
+ if (code === 'protected_authz_setup_required') return t('vaults.deleteDialog.authzSetupRequired');
+ if (code === 'invalid_protected_authz') return t('vaults.deleteDialog.authzInvalid');
+ if (code === 'protected_auth_required') return t('vaults.deleteDialog.authzRequired');
+ if (code === 'webauthn_origin_unsupported') return t('vaults.deleteDialog.authzUnavailable');
+ if (code === 'passkey-cancelled') return t('vaults.protectedUnlock.errors.cancelled');
+ return messageFromError(err);
+};
/** All allowed proxy-fetch hosts on a secret (for the `proxy · <host> +N` badge). */
const proxyHosts = (s: VaultSecret): string[] => {
const hosts = (s.policy as { allowed_hosts?: string[] })?.allowed_hosts;
@@ -678,37 +686,19 @@ export const VaultsPage: React.FC = () => {
const protectedVault = useProtectedVault();
const [deleteTarget, setDeleteTarget] = useState<VaultSecret | null>(null);
const [editTarget, setEditTarget] = useState<VaultSecret | null>(null);
- // Deleting a protected secret requires the user present at an unlocked vault (a passkey
- // ceremony) — discover the current lock state when the delete dialog opens for one.
- useEffect(() => {
- if (deleteTarget?.protection !== 'protected') return;
- // A freshly set-up, uncommitted local VMK isn't a proven unlock of this secret's real vault
- // (first-init collision) — drop it and rediscover the server vault so the user must unlock the
- // actual one; otherwise just discover the current lock state.
- if (vaultFreshSetup()) void protectedVault.discardAndRefresh();
- else void protectedVault.refresh();
- // eslint-disable-next-line react-hooks/exhaustive-deps -- vault callbacks are stable; re-run only on target change
- }, [deleteTarget]);
- // Gate on the wall-clock lock state (vaultUnlocked), not the hook's cached status — a delayed
- // auto-lock timer (tab resumed after the deadline) can leave status stale-'unlocked', which must
- // NOT enable a protected delete without a fresh unlock.
- const deleteNeedsUnlock =
- deleteTarget?.protection === 'protected' && (!vaultUnlocked() || vaultFreshSetup());
const onDelete = (secret: VaultSecret) => setDeleteTarget(secret);
const onEdit = (secret: VaultSecret) => setEditTarget(secret);
const confirmDelete = async () => {
const secret = deleteTarget;
if (!secret) return;
- // Belt-and-suspenders at the mutation point: a protected secret must have a committed,
- // wall-clock-valid unlock right now — closes the delayed-auto-lock resume window where the
- // button could momentarily be stale-enabled.
- if (secret.protection === 'protected' && (!vaultUnlocked() || vaultFreshSetup())) return;
try {
- await api.deleteVaultSecret(secret.name);
+ setError(null);
+ const authz = secret.protection === 'protected' ? await protectedVault.authorizeProtectedDelete(secret.name) : undefined;
+ await api.deleteVaultSecret(secret.name, authz);
showToast(t('vaults.deleted', { name: secret.name }), 'success');
refresh();
} catch (err: unknown) {
- setError(messageFromError(err));
+ setError(deleteMessageFromError(err, t));
} finally {
setDeleteTarget(null);
}
@@ -872,7 +862,6 @@ export const VaultsPage: React.FC = () => {
description={t('vaults.deleteDialog.description')}
confirmLabel={t('common.delete')}
holdSeconds={deleteTarget?.kind === 'keypair' ? 5 : 0}
- confirmDisabled={deleteNeedsUnlock}
onConfirm={confirmDelete}
>
{deleteTarget?.kind === 'keypair' ? (
@@ -887,10 +876,12 @@ export const VaultsPage: React.FC = () => {
</span>
</div>
) : null}
- {deleteNeedsUnlock ? (
- <div className="flex flex-col gap-2">
- <p className="text-[12.5px] leading-snug text-muted-foreground">{t('vaults.deleteDialog.protectedUnlockNote')}</p>
- <VaultProtectedUnlock vault={protectedVault} secretName={deleteTarget?.name} />
+ {deleteTarget?.protection === 'protected' ? (
+ <div className="flex flex-col gap-2 rounded-[10px] border border-warning/30 bg-warning/5 px-3 py-2.5 text-[12.5px] leading-snug text-foreground">
+ <span className="flex items-start gap-2">
+ <ShieldCheck className="mt-0.5 size-4 shrink-0 text-warning" />
+ <span>{t('vaults.deleteDialog.protectedPasskeyNote')}</span>
+ </span>
</div>
) : null}
</ConfirmDialog>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 7d7c4e3f6..195bb0593 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -142,6 +142,76 @@ export type VaultVmkResult = {
wrap_meta: string | null;
};
+export type VaultWebAuthnCredentialDescriptor = {
+ type: 'public-key';
+ id: string;
+ factor_id?: string;
+ transports?: AuthenticatorTransport[];
+};
+
+export type VaultWebAuthnRegistrationOptions = {
+ ok: boolean;
+ challenge_id: string;
+ expires_at: string;
+ rp_id: string;
+ origin: string;
+ requires_existing_factor?: boolean;
+ webauthn: {
+ rp: { name: string; id: string };
+ user: { id: string; name: string; displayName: string };
+ challenge: string;
+ pubKeyCredParams: PublicKeyCredentialParameters[];
+ authenticatorSelection: AuthenticatorSelectionCriteria;
+ extensions?: AuthenticationExtensionsClientInputs;
+ };
+ authorization?: {
+ challenge_id: string;
+ expires_at: string;
+ webauthn: VaultDeleteChallengeResult['webauthn'];
+ };
+ code?: string;
+ message?: string;
+};
+
+export type VaultWebAuthnSerializedCredential = {
+ id: string;
+ rawId: string;
+ type: string;
+ response: Record<string, unknown>;
+};
+
+export type VaultWebAuthnAuthz = {
+ kind: 'webauthn';
+ challenge_id: string;
+ factor_id: string;
+ assertion: VaultWebAuthnSerializedCredential;
+};
+
+export type VaultWebAuthnRegistrationPayload = {
+ challenge_id: string;
+ credential: VaultWebAuthnSerializedCredential;
+ label?: string;
+ authz?: VaultWebAuthnAuthz;
+};
+
+export type VaultDeleteAuthz = VaultWebAuthnAuthz;
+
+export type VaultDeleteChallengeResult = {
+ ok: boolean;
+ challenge_id: string;
+ expires_at: string;
+ operation: 'delete_secret';
+ secret_name: string;
+ webauthn: {
+ challenge: string;
+ rpId: string;
+ userVerification: UserVerificationRequirement;
+ allowCredentials: VaultWebAuthnCredentialDescriptor[];
+ };
+ code?: string;
+ message?: string;
+};
+
export type VaultCreatePayload = {
name: string;
protection?: 'standard' | 'protected';
@@ -162,6 +232,8 @@ export type VaultCreatePayload = {
provision_request_id?: string;
/** Set on the first protected secret so the daemon atomically guards single VMK init. */
establishing_vmk?: boolean;
+ /** First protected-vault setup registers the delete-authz public key in the same transaction. */
+ authz_factor_registration?: VaultWebAuthnRegistrationPayload;
};
/**
@@ -385,9 +457,14 @@ export type ApiContextType = {
getVaultPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;
getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;
deriveSigningAddresses: (publicKey: string) => Promise<{ ok: boolean; addresses?: SigningAddresses; code?: string; message?: string }>;
+ createVaultAuthzWebAuthnOptions: () => Promise<VaultWebAuthnRegistrationOptions>;
+ registerVaultAuthzWebAuthnFactor: (
+ payload: VaultWebAuthnRegistrationPayload,
+ ) => Promise<{ ok: boolean; factor?: Record<string, unknown>; code?: string; message?: string }>;
createVaultSecret: (payload: VaultCreatePayload, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;
updateVaultSecret: (name: string, payload: VaultMetadataUpdatePayload, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;
- deleteVaultSecret: (name: string) => Promise<{ ok: boolean; removed?: boolean; code?: string; message?: string }>;
+ createVaultDeleteChallenge: (name: string, opts?: { handleError?: boolean }) => Promise<VaultDeleteChallengeResult>;
+ deleteVaultSecret: (name: string, authz?: VaultDeleteAuthz) => Promise<{ ok: boolean; removed?: boolean; code?: string; message?: string }>;
getVaultProvisionRequest: (
name: string,
opts?: { handleError?: boolean },
@@ -2180,9 +2257,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),
deriveSigningAddresses: (publicKey) =>
postJson('/api/vault/signing-addresses', { public_key: publicKey }, { handleError: false }),
+ createVaultAuthzWebAuthnOptions: () => postJson('/api/vault/authz/factors/webauthn/options', {}),
+ registerVaultAuthzWebAuthnFactor: (payload) => postJson('/api/vault/authz/factors/webauthn', payload),
createVaultSecret: (payload, opts) => postJson('/api/vault/secrets', payload, opts),
updateVaultSecret: (name, payload, opts) => patchJson(`/api/vault/secrets/${encodeURIComponent(name)}`, payload, opts),
- deleteVaultSecret: (name) => deleteJson(`/api/vault/secrets/${encodeURIComponent(name)}`),
+ createVaultDeleteChallenge: (name, opts) =>
+ postJson(`/api/vault/secrets/${encodeURIComponent(name)}/delete-challenge`, {}, opts),
+ deleteVaultSecret: (name, authz) =>
+ deleteJson(`/api/vault/secrets/${encodeURIComponent(name)}`, authz ? { authz } : undefined),
getVaultProvisionRequest: (name, opts) =>
getCachedJson(`/api/vault/provision-requests/${encodeURIComponent(name)}`, 1500, opts),
getVaultProvisionRequestById: (requestId, opts) =>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7b9b95434..3f1da6303 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2241,7 +2241,12 @@
"description": "Agents will no longer be able to use this secret.",
"keypairIrreversible": "This is a signing key — deleting it permanently destroys the private key. There is no backup and it cannot be recovered.",
"keypairFunds": "If this key's address holds any funds, move them out first, or they will be lost for good.",
- "protectedUnlockNote": "This is a protected secret — unlock the vault to confirm it's you before deleting."
+ "protectedUnlockNote": "This is a protected secret — unlock the vault to confirm it's you before deleting.",
+ "protectedPasskeyNote": "This protected secret requires a fresh passkey authorization. The passkey prompt appears after you confirm.",
+ "authzSetupRequired": "Protected delete authorization is missing for this vault. Re-create the protected vault so setup can register the passkey authorization factor.",
+ "authzInvalid": "That passkey authorization expired or could not be verified. Try deleting again.",
+ "authzRequired": "Protected secrets require passkey authorization before deletion.",
+ "authzUnavailable": "Protected delete needs a passkey-capable origin. Open Vaults from localhost or your avibe.bot address."
},
"deleted": "Deleted {{name}}",
"created": "Saved {{name}}",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 82f0c690f..9592f2b21 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2241,7 +2241,12 @@
"description": "Agent 将无法再使用这条密钥。",
"keypairIrreversible": "这是一把签名密钥——删除会永久销毁私钥,没有备份,无法恢复。",
"keypairFunds": "如果这把密钥的地址里还有资金,请先转出,否则将永久丢失。",
- "protectedUnlockNote": "这是保护档密钥——删除前先解锁保险库,验证是你本人。"
+ "protectedUnlockNote": "这是保护档密钥——删除前先解锁保险库,验证是你本人。",
+ "protectedPasskeyNote": "删除这条保护档密钥需要一次新的 passkey 授权。确认后会弹出 passkey 验证。",
+ "authzSetupRequired": "这个保险库缺少保护档删除授权。请重新创建保护档保险库,让 setup 流程注册 passkey 授权因子。",
+ "authzInvalid": "这次 passkey 授权已过期或无法验证。请重新删除一次。",
+ "authzRequired": "保护档密钥删除前必须完成 passkey 授权。",
+ "authzUnavailable": "保护档删除需要支持 passkey 的访问来源。请从 localhost 或你的 avibe.bot 地址打开 Vaults。"
},
"deleted": "已删除 {{name}}",
"created": "已保存 {{name}}",
diff --git a/ui/src/lib/useProtectedVault.test.ts b/ui/src/lib/useProtectedVault.test.ts
index a05674389..eb3a42c73 100644
--- a/ui/src/lib/useProtectedVault.test.ts
+++ b/ui/src/lib/useProtectedVault.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { bytesToBase64 } from './vaultCrypto';
-import { passkeyCreationOptions, passkeyPrfAssertionOptions, readPasskeyPrfResult } from './useProtectedVault';
+import { passkeyAssertionOptionsFromServer, passkeyCreationOptions, passkeyPrfAssertionOptions, readPasskeyPrfResult } from './useProtectedVault';
function passkeyCredential(first?: ArrayBuffer | ArrayBufferView | number[]): PublicKeyCredential {
return {
@@ -53,6 +53,37 @@ describe('protected vault WebAuthn PRF result handling', () => {
).toThrow(/passkey-multiple-not-supported/);
});
+ it('builds delete assertion options from the server challenge without leaking factor ids to WebAuthn', () => {
+ const challenge = new Uint8Array(32).fill(0x44);
+ const credentialId = new Uint8Array([5, 6, 7, 8]);
+ const options = passkeyAssertionOptionsFromServer({
+ challenge: bytesToBase64(challenge),
+ rpId: 'alex-app.avibe.bot',
+ userVerification: 'required',
+ allowCredentials: [
+ {
+ type: 'public-key',
+ id: bytesToBase64(credentialId),
+ factor_id: 'vaf_test',
+ transports: ['internal'],
+ },
+ ],
+ });
+
+ expect(new Uint8Array(options.challenge as ArrayBuffer)).toEqual(challenge);
+ expect(options.rpId).toBe('alex-app.avibe.bot');
+ expect(options.userVerification).toBe('required');
+ expect(options.allowCredentials).toEqual([
+ {
+ type: 'public-key',
+ id: options.allowCredentials?.[0]?.id,
+ transports: ['internal'],
+ },
+ ]);
+ expect(new Uint8Array(options.allowCredentials?.[0]?.id as ArrayBuffer)).toEqual(credentialId);
+ expect('factor_id' in (options.allowCredentials?.[0] as Record<string, unknown>)).toBe(false);
+ });
+
it('copies the PRF output before handing it to the VMK wrap chain', () => {
const source = new Uint8Array(32).fill(0x22);
const backing = source.buffer as ArrayBuffer;
diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.ts
index 0566c4e12..8a1600f9e 100644
--- a/ui/src/lib/useProtectedVault.ts
+++ b/ui/src/lib/useProtectedVault.ts
@@ -1,6 +1,13 @@
import { useCallback, useEffect, useReducer, useState } from 'react';
-import { useApi } from '@/context/ApiContext';
+import {
+ useApi,
+ type ApiContextType,
+ type VaultDeleteAuthz,
+ type VaultDeleteChallengeResult,
+ type VaultWebAuthnRegistrationPayload,
+ type VaultWebAuthnSerializedCredential,
+} from '@/context/ApiContext';
import {
base64ToBytes,
buildWrapMeta,
@@ -48,10 +55,16 @@ export type ProtectedUnlockMaterial = {
*/
export type ProtectedVaultStatus = 'checking' | 'needs-setup' | 'locked' | 'unlocked' | 'error';
-const sessionVault: { vmk: Uint8Array | null; wrapMeta: string | null; freshSetup: boolean } = {
+const sessionVault: {
+ vmk: Uint8Array | null;
+ wrapMeta: string | null;
+ freshSetup: boolean;
+ authzFactorRegistration: VaultWebAuthnRegistrationPayload | null;
+} = {
vmk: null,
wrapMeta: null,
freshSetup: false,
+ authzFactorRegistration: null,
};
/**
@@ -166,6 +179,7 @@ function clearVmk(): void {
// expiry in vaultUnlocked() — leaves a consistent state.
sessionVault.wrapMeta = null;
sessionVault.freshSetup = false;
+ sessionVault.authzFactorRegistration = null;
}
}
@@ -215,6 +229,10 @@ function randomChallenge(): ArrayBuffer {
return bufferSource(crypto.getRandomValues(new Uint8Array(32)));
}
+function bufferSourceFromBase64(value: string): ArrayBuffer {
+ return bufferSource(base64ToBytes(value));
+}
+
/** Strip a stored record's DEK fields back to the bare VMK wrap_meta ({v, copies, scheme?}). */
function baseVmkWrapMeta(wrapMeta: string): string {
const parsed = JSON.parse(wrapMeta) as Record<string, unknown>;
@@ -258,11 +276,14 @@ function singlePasskeyEntry(entries: PasskeyEntry[]): PasskeyEntry {
return entries[0];
}
-export function passkeyCreationOptions(rpId: string): PublicKeyCredentialCreationOptions {
+export function passkeyCreationOptions(
+ rpId: string,
+ challenge: ArrayBuffer | ArrayBufferView | ArrayLike<number> = randomChallenge(),
+): PublicKeyCredentialCreationOptions {
return {
rp: { name: WEBAUTHN_RP_NAME, id: rpId },
user: { id: bufferSource(WEBAUTHN_USER_HANDLE), name: 'avibe-vault', displayName: WEBAUTHN_RP_NAME },
- challenge: randomChallenge(),
+ challenge: bufferSource(toUint8(challenge)),
pubKeyCredParams: [
{ type: 'public-key', alg: -7 },
{ type: 'public-key', alg: -257 },
@@ -272,6 +293,19 @@ export function passkeyCreationOptions(rpId: string): PublicKeyCredentialCreatio
};
}
+function passkeyCreationOptionsFromServer(
+ webauthn: Awaited<ReturnType<ApiContextType['createVaultAuthzWebAuthnOptions']>>['webauthn'],
+): PublicKeyCredentialCreationOptions {
+ return {
+ rp: webauthn.rp,
+ user: { ...webauthn.user, id: bufferSourceFromBase64(webauthn.user.id) },
+ challenge: bufferSourceFromBase64(webauthn.challenge),
+ pubKeyCredParams: webauthn.pubKeyCredParams,
+ authenticatorSelection: webauthn.authenticatorSelection,
+ extensions: webauthn.extensions,
+ };
+}
+
export function passkeyPrfAssertionOptions(entries: PasskeyEntry[], rpId: string): PublicKeyCredentialRequestOptions {
const entry = singlePasskeyEntry(entries);
const options: PublicKeyCredentialRequestOptions = {
@@ -291,6 +325,55 @@ export function passkeyPrfAssertionOptions(entries: PasskeyEntry[], rpId: string
return options;
}
+export function passkeyAssertionOptionsFromServer(
+ webauthn: VaultDeleteChallengeResult['webauthn'],
+): PublicKeyCredentialRequestOptions {
+ return {
+ challenge: bufferSourceFromBase64(webauthn.challenge),
+ rpId: webauthn.rpId,
+ userVerification: webauthn.userVerification,
+ allowCredentials: webauthn.allowCredentials.map((entry) => ({
+ type: 'public-key' as const,
+ id: bufferSourceFromBase64(entry.id),
+ ...(entry.transports ? { transports: entry.transports } : {}),
+ })),
+ };
+}
+
+function serializeCredentialBase(credential: PublicKeyCredential): Pick<VaultWebAuthnSerializedCredential, 'id' | 'rawId' | 'type'> {
+ return {
+ id: credential.id,
+ rawId: bytesToBase64(toUint8(credential.rawId)),
+ type: credential.type,
+ };
+}
+
+export function serializeAttestationCredential(credential: PublicKeyCredential): VaultWebAuthnSerializedCredential {
+ const response = credential.response as AuthenticatorAttestationResponse;
+ const transports = typeof response.getTransports === 'function' ? response.getTransports() : [];
+ return {
+ ...serializeCredentialBase(credential),
+ response: {
+ clientDataJSON: bytesToBase64(toUint8(response.clientDataJSON)),
+ attestationObject: bytesToBase64(toUint8(response.attestationObject)),
+ transports,
+ },
+ };
+}
+
+export function serializeAssertionCredential(credential: PublicKeyCredential): VaultWebAuthnSerializedCredential {
+ const response = credential.response as AuthenticatorAssertionResponse;
+ return {
+ ...serializeCredentialBase(credential),
+ response: {
+ clientDataJSON: bytesToBase64(toUint8(response.clientDataJSON)),
+ authenticatorData: bytesToBase64(toUint8(response.authenticatorData)),
+ signature: bytesToBase64(toUint8(response.signature)),
+ userHandle: response.userHandle ? bytesToBase64(toUint8(response.userHandle)) : null,
+ },
+ };
+}
+
/**
* Assert the vault passkey and extract its PRF output. Keep the assertion on the
* simple `prf.eval` path: iOS 1Password currently fails on `evalByCredential`,
@@ -308,14 +391,26 @@ async function assertPasskeyPrf(entries: PasskeyEntry[]): Promise<{ prfOutput: U
}
/** Create a resident passkey, then assert it once to extract the PRF output. */
-async function setupPasskeyFactor(prfSalt: Uint8Array): Promise<{ prfOutput: Uint8Array; credentialId: string }> {
+async function setupPasskeyFactor(
+ api: ApiContextType,
+ prfSalt: Uint8Array,
+): Promise<{ prfOutput: Uint8Array; credentialId: string; registration: VaultWebAuthnRegistrationPayload }> {
+ const options = await api.createVaultAuthzWebAuthnOptions();
+ if (!options?.ok) throw new Error(options?.code || 'passkey-registration-options-failed');
const created = (await navigator.credentials.create({
- publicKey: passkeyCreationOptions(window.location.hostname),
+ publicKey: passkeyCreationOptionsFromServer(options.webauthn),
})) as PublicKeyCredential | null;
if (!created) throw new Error('passkey-cancelled');
const credentialId = bytesToBase64(toUint8(created.rawId));
const { prfOutput } = await assertPasskeyPrf([{ credentialId, prfSalt }]);
- return { prfOutput, credentialId };
+ return {
+ prfOutput,
+ credentialId,
+ registration: {
+ challenge_id: options.challenge_id,
+ credential: serializeAttestationCredential(created),
+ },
+ };
}
export function useProtectedVault() {
@@ -366,11 +461,17 @@ export function useProtectedVault() {
}
}, [api]);
- const commit = (vmk: Uint8Array, wrapMeta: string, freshSetup: boolean) => {
+ const commit = (
+ vmk: Uint8Array,
+ wrapMeta: string,
+ freshSetup: boolean,
+ authzFactorRegistration: VaultWebAuthnRegistrationPayload | null = null,
+ ) => {
sessionVault.vmk?.fill(0);
sessionVault.vmk = vmk;
sessionVault.wrapMeta = wrapMeta;
sessionVault.freshSetup = freshSetup;
+ sessionVault.authzFactorRegistration = authzFactorRegistration;
armVaultAutoLock();
setStatus('unlocked');
setError(null);
@@ -380,11 +481,11 @@ export function useProtectedVault() {
// UI requires an explicit acknowledgement before calling this.
const setupPasskey = useCallback(async () => {
const prfSalt = newPasskeyPrfSalt();
- const { prfOutput, credentialId } = await setupPasskeyFactor(prfSalt);
+ const { prfOutput, credentialId, registration } = await setupPasskeyFactor(api, prfSalt);
const vmk = newVmk();
const wrapMeta = await buildWrapMeta(vmk, [{ kind: 'passkey', prfOutput, prfSalt, credentialId }]);
- commit(vmk, withRpId(wrapMeta, window.location.hostname), true);
- }, []);
+ commit(vmk, withRpId(wrapMeta, window.location.hostname), true, registration);
+ }, [api]);
const unlockPasskey = useCallback(async () => {
const wrapMeta = sessionVault.wrapMeta;
@@ -401,7 +502,14 @@ export function useProtectedVault() {
* signing keys seal the key material itself, not a UTF-8 string.
*/
const sealValue = useCallback(
- async (name: string, value: Uint8Array | string): Promise<{ envelope: ProtectedRecordEnvelope; establishingVmk: boolean }> => {
+ async (
+ name: string,
+ value: Uint8Array | string,
+ ): Promise<{
+ envelope: ProtectedRecordEnvelope;
+ establishingVmk: boolean;
+ authzFactorRegistration?: VaultWebAuthnRegistrationPayload;
+ }> => {
if (!enforceAutoLock()) throw new Error('vault-locked');
const { vmk, wrapMeta, freshSetup } = sessionVault;
if (!vmk || !wrapMeta) throw new Error('vault-locked');
@@ -411,7 +519,11 @@ export function useProtectedVault() {
// `establishingVmk` lets the create transaction enforce the atomic single-init
// guard server-side (a UI re-check here can't be race-free); the daemon rejects a
// second VMK so concurrent first-time setups can't split the key history.
- return { envelope: packProtectedRecord(sealed, wrapMeta), establishingVmk: freshSetup };
+ return {
+ envelope: packProtectedRecord(sealed, wrapMeta),
+ establishingVmk: freshSetup,
+ authzFactorRegistration: freshSetup ? (sessionVault.authzFactorRegistration ?? undefined) : undefined,
+ };
},
[],
);
@@ -419,6 +531,7 @@ export function useProtectedVault() {
const afterCreated = useCallback(() => {
// The vault now exists server-side; subsequent creates this session aren't "establishing".
sessionVault.freshSetup = false;
+ sessionVault.authzFactorRegistration = null;
}, []);
/**
@@ -461,6 +574,29 @@ export function useProtectedVault() {
[],
);
+ const authorizeProtectedDelete = useCallback(
+ async (name: string): Promise<VaultDeleteAuthz> => {
+ const challenge = await api.createVaultDeleteChallenge(name, { handleError: false });
+ if (!challenge?.ok) {
+ throw new Error(challenge?.code || challenge?.message || 'protected-delete-challenge-failed');
+ }
+ const assertion = (await navigator.credentials.get({
+ publicKey: passkeyAssertionOptionsFromServer(challenge.webauthn),
+ })) as PublicKeyCredential | null;
+ if (!assertion) throw new Error('passkey-cancelled');
+ const rawId = bytesToBase64(toUint8(assertion.rawId));
+ const factor = challenge.webauthn.allowCredentials.find((entry) => entry.id === rawId);
+ if (!factor?.factor_id) throw new Error('protected-authz-factor-missing');
+ return {
+ kind: 'webauthn',
+ challenge_id: challenge.challenge_id,
+ factor_id: factor.factor_id,
+ assertion: serializeAssertionCredential(assertion),
+ };
+ },
+ [api],
+ );
+
const lock = useCallback(() => {
lockVault(true);
setStatus(vaultStatusNow());
@@ -473,6 +609,7 @@ export function useProtectedVault() {
clearVmk();
sessionVault.wrapMeta = null;
sessionVault.freshSetup = false;
+ sessionVault.authzFactorRegistration = null;
notifyVaultLockChange();
await refresh();
}, [refresh]);
@@ -511,6 +648,7 @@ export function useProtectedVault() {
sealValue,
signProtectedRequest,
releaseProtectedDelivery,
+ authorizeProtectedDelete,
afterCreated,
lock,
discardAndRefresh,
diff --git a/vibe/api.py b/vibe/api.py
index 38d925bca..81737d0b0 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1473,6 +1473,71 @@ def get_vault_vmk() -> dict:
return {"ok": True, "exists": wrap_meta is not None, "wrap_meta": wrap_meta}
+def _vault_webauthn_context(origin: str | None):
+ from storage import vault_webauthn
+
+ try:
+ return vault_webauthn.rp_context_from_origin(origin or "")
+ except vault_webauthn.WebAuthnVerificationError as exc:
+ raise VaultApiError(str(exc), code="webauthn_origin_unsupported", status=409) from exc
+
+
+def create_vault_authz_webauthn_options(*, origin: str | None = None) -> dict:
+ from storage import vault_service
+
+ context = _vault_webauthn_context(origin)
+ engine = _vault_engine()
+ with engine.begin() as conn:
+ return vault_service.create_webauthn_registration_options(
+ conn,
+ rp_id=context.rp_id,
+ origin=context.origin,
+ )
+
+
+def register_vault_authz_webauthn_factor(payload: dict, *, origin: str | None = None) -> dict:
+ from storage import vault_service
+
+ context = _vault_webauthn_context(origin)
+ engine = _vault_engine()
+ try:
+ with engine.begin() as conn:
+ result = vault_service.register_webauthn_factor(
+ conn,
+ payload,
+ rp_id=context.rp_id,
+ origin=context.origin,
+ )
+ except vault_service.InvalidProtectedAuthzError as exc:
+ raise VaultApiError(str(exc), code="invalid_protected_authz", status=409) from exc
+ except vault_service.ProtectedAuthRequiredError as exc:
+ raise VaultApiError(str(exc), code="protected_auth_required", status=409) from exc
+ except vault_service.ProtectedAuthzSetupRequiredError as exc:
+ raise VaultApiError(str(exc), code="protected_authz_setup_required", status=409) from exc
+ return result
+
+
+def create_vault_delete_challenge(name: str, *, origin: str | None = None) -> dict:
+ from storage import vault_service
+
+ context = _vault_webauthn_context(origin)
+ engine = _vault_engine()
+ try:
+ with engine.begin() as conn:
+ return vault_service.create_delete_challenge(
+ conn,
+ name,
+ rp_id=context.rp_id,
+ origin=context.origin,
+ )
+ except vault_service.SecretNotFoundError as exc:
+ raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc
+ except vault_service.SecretNotProtectedError as exc:
+ raise VaultApiError(f"secret '{name}' is not protected", code="not_protected", status=409) from exc
+ except vault_service.ProtectedAuthzSetupRequiredError as exc:
+ raise VaultApiError(str(exc), code="protected_authz_setup_required", status=409) from exc
+
+
def _reject_plaintext_value_fields(payload: object) -> None:
if isinstance(payload, dict):
if "value" in payload:
@@ -1537,7 +1602,7 @@ def _sealed_from_payload(payload: dict):
return Sealed(ciphertext=ciphertext, nonce=nonce, wrap_meta=wrap_meta)
-def create_vault_secret(payload: dict) -> dict:
+def create_vault_secret(payload: dict, *, origin: str | None = None) -> dict:
from storage import vault_crypto, vault_service
if not isinstance(payload, dict):
@@ -1550,6 +1615,7 @@ def create_vault_secret(payload: dict) -> dict:
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
+ authz_factor_registration = payload.get("authz_factor_registration")
try:
if links and isinstance(links.get("skills"), list):
tags.extend(vault_service.skill_tag(str(skill)) for skill in links["skills"] if isinstance(skill, str))
@@ -1623,6 +1689,8 @@ def create_vault_secret(payload: dict) -> dict:
policy=policy,
public_meta=public_meta,
establishing_vmk=establishing_vmk,
+ authz_factor_registration=authz_factor_registration if isinstance(authz_factor_registration, dict) else None,
+ authz_factor_origin=origin,
provision_request_id=provision_request_id,
)
except vault_service.InvalidSecretNameError as exc:
@@ -1645,6 +1713,10 @@ def create_vault_secret(payload: dict) -> dict:
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
+ except vault_service.ProtectedAuthzSetupRequiredError as exc:
+ raise VaultApiError(str(exc), code="protected_authz_setup_required", status=409) from exc
+ except vault_service.InvalidProtectedAuthzError as exc:
+ raise VaultApiError(str(exc), code="invalid_protected_authz", status=409) from exc
except vault_service.VaultServiceError as exc:
raise VaultApiError(str(exc), code="vault_error") from exc
_publish_vaults_updated(
@@ -1689,18 +1761,30 @@ def update_vault_secret(name: str, payload: dict) -> dict:
return {"ok": True, "secret": meta}
-def delete_vault_secret(name: str) -> dict:
+def delete_vault_secret(name: str, authz: dict | None = None) -> dict:
from storage import vault_service
engine = _vault_engine()
release_scopes: list[dict[str, str]] = []
try:
with engine.begin() as conn:
+ meta = vault_service.get_secret_meta(conn, name)
+ protected_authz = (
+ vault_service.verify_delete_secret_authz(conn, name, authz)
+ if meta.get("protection") == "protected"
+ else None
+ )
grant_rows = vault_service.active_grant_rows_for_secret(conn, name)
- vault_service.delete_secret(conn, name)
+ vault_service.delete_secret(conn, name, protected_authz=protected_authz)
release_scopes = vault_service.agent_release_scopes_after_rows(conn, grant_rows)
except vault_service.SecretNotFoundError as exc:
raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc
+ except vault_service.ProtectedAuthRequiredError as exc:
+ raise VaultApiError(str(exc), code="protected_auth_required", status=409) from exc
+ except vault_service.ProtectedAuthzSetupRequiredError as exc:
+ raise VaultApiError(str(exc), code="protected_authz_setup_required", status=409) from exc
+ except vault_service.InvalidProtectedAuthzError as exc:
+ raise VaultApiError(str(exc), code="invalid_protected_authz", status=409) from exc
release_vault_agent_scopes(release_scopes, reason="delete_vault_secret")
_publish_vaults_updated(scope="secret", secret_name=name)
return {"ok": True, "removed": True, "name": name}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 94da85de1..519bcb375 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3082,6 +3082,15 @@ def _vault_error_response(exc):
return jsonify({"ok": False, "code": "vault_error", "message": str(exc)}), 400
+def _webauthn_request_origin() -> str:
+ origin = request.headers.get("Origin")
+ if origin:
+ return origin
+ scheme = request.headers.get("X-Forwarded-Proto") or request.scheme
+ host = request.headers.get("X-Forwarded-Host") or request.host
+ return f"{scheme}://{host}"
+
+
@app.route("/api/vault/secrets", methods=["GET"])
def vault_secrets_get():
from vibe import api
@@ -3137,6 +3146,26 @@ def vault_vmk_get():
return jsonify(api.get_vault_vmk())
[email protected]("/api/vault/authz/factors/webauthn/options", methods=["POST"])
+def vault_authz_webauthn_options_post():
+ from vibe import api
+
+ try:
+ return jsonify(api.create_vault_authz_webauthn_options(origin=_webauthn_request_origin()))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
[email protected]("/api/vault/authz/factors/webauthn", methods=["POST"])
+def vault_authz_webauthn_register_post():
+ from vibe import api
+
+ try:
+ return jsonify(api.register_vault_authz_webauthn_factor(request.json or {}, origin=_webauthn_request_origin()))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
@app.route("/api/vault/signing-addresses", methods=["POST"])
def vault_signing_addresses_post():
from vibe import api
@@ -3152,7 +3181,7 @@ def vault_secrets_post():
from vibe import api
try:
- return jsonify(api.create_vault_secret(request.json or {}))
+ return jsonify(api.create_vault_secret(request.json or {}, origin=_webauthn_request_origin()))
except ValueError as exc:
return _vault_error_response(exc)
@@ -3167,12 +3196,24 @@ def vault_secret_patch(name):
return _vault_error_response(exc)
[email protected]("/api/vault/secrets/<name>/delete-challenge", methods=["POST"])
+def vault_secret_delete_challenge(name):
+ from vibe import api
+
+ try:
+ return jsonify(api.create_vault_delete_challenge(name, origin=_webauthn_request_origin()))
+ 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
try:
- return jsonify(api.delete_vault_secret(name))
+ payload = request.json or {}
+ authz = payload.get("authz") if isinstance(payload, dict) else None
+ return jsonify(api.delete_vault_secret(name, authz=authz))
except ValueError as exc:
return _vault_error_response(exc)