Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(vault): make protected establishment atomic (#863)
Call Whitee71758301644
diff --git a/storage/vault_service.py b/storage/vault_service.pyindex 4959498fc..b7b5b7cdb 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -49,6 +49,7 @@ logger = logging.getLogger(__name__)SKILL_TAG_PREFIX = "skill:"VAULT_SETTINGS_META_KEY = "vault_settings"+PROTECTED_VAULT_ESTABLISHMENT_LOCK_META_KEY = "vault_protected_establishment_lock"DEFAULT_UNLOCK_WINDOW_SECONDS = 600UNLOCK_WINDOW_OPTIONS_SECONDS = (300, 600, 1800)GRANT_DURATION_ONE_TIME = "one-time"@@ -2035,22 +2036,40 @@ def create_secret(raise VaultServiceError(f"invalid vault secret kind: {kind!r}")if kind != "keypair" and signer_kind is not None:raise VaultServiceError("signer_kind is only valid for keypair secrets")+ establishing_protected_vault = establishing_vmk and protection == "protected"+ if establishing_protected_vault:+ # This must be the transaction's first database access: a deferred SQLite+ # transaction cannot safely promote an older read snapshot after another+ # initializer commits. The row is only a mutex; protected-secret existence+ # remains the source of truth.+ lock_updated_at = _now()+ lock_stmt = sqlite_insert(state_meta).values(+ key=PROTECTED_VAULT_ESTABLISHMENT_LOCK_META_KEY,+ value_json="{}",+ updated_at=lock_updated_at,+ )+ conn.execute(+ lock_stmt.on_conflict_do_update(+ index_elements=[state_meta.c.key],+ set_={+ "value_json": lock_stmt.excluded.value_json,+ "updated_at": lock_stmt.excluded.updated_at,+ },+ )+ )+ if (+ conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.protection == "protected").limit(1)).first()+ is not None+ ):+ raise VaultAlreadyInitializedError("a protected vault already exists; unlock it instead of re-initializing")+provision_row, _existing_secret = _preflight_secret_create_name(conn,name=name,provision_request_id=provision_request_id,)- if establishing_vmk and protection == "protected":- # Atomic single-init guard: this runs inside the write transaction (SQLite- # serialises writers), so two concurrent first-time setups cannot both pass —- # the loser is rejected instead of splitting the vault key history with a- # second VMK. The browser then reloads and unlocks the established vault.- if (- conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.protection == "protected").limit(1)).first()- is not None- ):- raise VaultAlreadyInitializedError("a protected vault already exists; unlock it instead of re-initializing")+ if establishing_protected_vault:if not isinstance(authz_factor_registration, dict):raise ProtectedAuthzSetupRequiredError("protected vault establishment requires a passkey authorization factor")diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex 84fe86a38..0232ae3ad 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -1622,7 +1622,8 @@ def test_create_vault_reveal_context_rejects_protected_keypair(monkeypatch):assert exc.value.code == "keypair_not_value_deliverable"-def test_protected_create_establishing_vmk_rejects_second_init(monkeypatch):[email protected]("second_name", ["FIRST_PROTECTED", "SECOND_PROTECTED"])+def test_protected_create_establishing_vmk_rejects_second_init(monkeypatch, second_name):_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"@@ -1632,7 +1633,7 @@ def test_protected_create_establishing_vmk_rejects_second_init(monkeypatch):with pytest.raises(api.VaultApiError) as exc:api.create_vault_secret({- "name": "SECOND_PROTECTED",+ "name": second_name,"protection": "protected","sealed": {"ciphertext": "ct2", "nonce": "n2", "wrap_meta": {"v": 1, "copies": [], "wrapped_dek": "d2"}},"establishing_vmk": True,diff --git a/tests/test_vault_service.py b/tests/test_vault_service.pyindex c3da58894..36d000953 100644--- a/tests/test_vault_service.py+++ b/tests/test_vault_service.py@@ -8,7 +8,7 @@ import threadingfrom datetime import datetime, timedelta, timezoneimport pytest-from sqlalchemy import select+from sqlalchemy import event, selectfrom sqlalchemy.exc import IntegrityErrorfrom storage import vault_service as vs, vault_webauthn@@ -383,6 +383,82 @@ def test_save_vault_settings_first_write_is_atomic_under_concurrency(vault):assert {result["last_grant_ttl"] for result in results}.issubset({300, 900})+def test_protected_vault_establishment_is_atomic_under_concurrency(vault, monkeypatch):+ init_lock_key = vs.PROTECTED_VAULT_ESTABLISHMENT_LOCK_META_KEY+ monkeypatch.setattr(vs, "register_webauthn_factor", lambda *_args, **_kwargs: None)++ lock_barrier = threading.Barrier(2)+ pre_guard_barrier = threading.Barrier(2)+ post_guard_barrier = threading.Barrier(2)+ lock_seen = threading.Event()+ database_access_before_lock = threading.Event()+ thread_state = threading.local()++ def is_init_lock(statement: str, parameters) -> bool:+ return statement.lstrip().upper().startswith("INSERT INTO STATE_META") and init_lock_key in parameters++ def is_protected_guard(statement: str) -> bool:+ normalized = " ".join(statement.upper().split())+ return "FROM VAULT_SECRETS" in normalized and "WHERE VAULT_SECRETS.PROTECTION =" in normalized++ def synchronize_before_guard(_conn, _cursor, statement, parameters, _context, _executemany):+ if is_init_lock(statement, parameters):+ thread_state.init_lock_seen = True+ lock_seen.set()+ lock_barrier.wait(timeout=5)+ else:+ if not getattr(thread_state, "init_lock_seen", False):+ database_access_before_lock.set()+ if not lock_seen.is_set() and is_protected_guard(statement):+ # On the unfixed implementation, force both deferred transactions+ # through the empty-vault read before either reaches its first write.+ pre_guard_barrier.wait(timeout=5)++ def synchronize_after_guard(_conn, _cursor, statement, _parameters, _context, _executemany):+ if not lock_seen.is_set() and is_protected_guard(statement):+ post_guard_barrier.wait(timeout=5)++ event.listen(vault, "before_cursor_execute", synchronize_before_guard)+ event.listen(vault, "after_cursor_execute", synchronize_after_guard)++ def establish(index: int):+ try:+ with vault.begin() as conn:+ return vs.create_secret(+ conn,+ name="CONCURRENT_PROTECTED",+ sealed=_sealed(f"concurrent-{index}"),+ protection="protected",+ establishing_vmk=True,+ authz_factor_registration={},+ )+ except vs.VaultServiceError as exc:+ return exc++ try:+ with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:+ results = list(executor.map(establish, range(2)))+ finally:+ event.remove(vault, "before_cursor_execute", synchronize_before_guard)+ event.remove(vault, "after_cursor_execute", synchronize_after_guard)++ successes = [result for result in results if isinstance(result, dict)]+ failures = [result for result in results if isinstance(result, vs.VaultServiceError)]+ assert len(successes) == 1+ assert len(failures) == 1+ assert isinstance(failures[0], vs.VaultAlreadyInitializedError)+ assert not database_access_before_lock.is_set()++ with vault.connect() as conn:+ protected_names = list(+ conn.execute(select(vault_secrets.c.name).where(vault_secrets.c.protection == "protected")).scalars()+ )+ lock_row = conn.execute(select(state_meta).where(state_meta.c.key == init_lock_key)).mappings().one()++ assert protected_names == [successes[0]["name"]]+ assert lock_row["value_json"] == "{}"++def test_sibling_approval_requires_matching_purpose(vault):_create(vault, name="A_KEY", protection="protected", tags=["deploy"])diff --git a/vibe/api.py b/vibe/api.pyindex 10e961eaf..f1653887c 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -2336,14 +2336,18 @@ def create_vault_secret(payload: dict, *, origin: str | None = None) -> dict:if signer_kind is not None:signer_kind = str(signer_kind)provision_request_id = str(payload.get("provision_request_id") or "") or None+ atomic_protected_establishment = establishing_vmk and protection == "protected"engine = _vault_engine()try:- with engine.begin() as conn:- vault_service.preflight_secret_create(- conn,- name=name,- provision_request_id=provision_request_id,- )+ # Establishment defers preflight to create_secret's write-serialized+ # transaction so a same-name loser receives vault_already_initialized.+ if not atomic_protected_establishment:+ with engine.begin() as conn:+ vault_service.preflight_secret_create(+ conn,+ name=name,+ provision_request_id=provision_request_id,+ )except vault_service.InvalidSecretNameError as exc:raise VaultApiError("invalid secret name (use ^[A-Za-z_][A-Za-z0-9_]*$)", code="invalid_name") from excexcept vault_service.SecretNameCaseConflictError as exc: