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(acl): close remote authorization retry gaps
Maxvint05e1d700e494
diff --git a/core/vibe_agents.py b/core/vibe_agents.pyindex 5fbb36207..9cc0e7121 100644--- a/core/vibe_agents.py+++ b/core/vibe_agents.py@@ -233,15 +233,18 @@ def ensure_session_agent_access() -> VibeAgent | None:"""Revalidate the Agent selected by a persisted session before dispatch."""+ context = resolve_resource_access_context(user_context)if session.get("agent_id") or session.get("agent_name"):return ensure_agent_selection_access(connection,agent_name=session.get("agent_name"),agent_id=session.get("agent_id"),- user_context=user_context,+ user_context=context,)if not session.get("agent_backend"):- return ensure_default_agent_access(connection, user_context=user_context)+ return ensure_default_agent_access(connection, user_context=context)+ if context.is_remote:+ raise VibeAgentAccessError("Agent access is not permitted.")return Nonediff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 7bebf221a..a176f517a 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -342,16 +342,21 @@ def create_session()context = resolve_resource_access_context(user_context)- if context.is_remote and not agent_name and not agent_id and not agent_backend:- default_agent = ensure_default_agent_access(- conn,- user_context=context,- missing_is_error=True,- )- assert default_agent is not None- agent_id = default_agent.id- agent_name = default_agent.name- agent_backend = default_agent.backend+ if context.is_remote and not agent_name and not agent_id:+ if agent_backend:+ from core.vibe_agents import VibeAgentAccessError++ raise VibeAgentAccessError("Agent access is not permitted.")+ else:+ default_agent = ensure_default_agent_access(+ conn,+ user_context=context,+ missing_is_error=True,+ )+ assert default_agent is not None+ agent_id = default_agent.id+ agent_name = default_agent.name+ agent_backend = default_agent.backendif agent_name or agent_id:ensure_agent_selection_access(@@ -446,14 +451,26 @@ def update_session(agent_backend = _backend_for_agent_name(conn, str(agent_name or "")) if agent_name else Nonederived_backend = True- if agent_name is not _UNSET or agent_id is not _UNSET:- from core.vibe_agents import ensure_agent_selection_access+ from core.vibe_agents import VibeAgentAccessError, ensure_agent_selection_access, resolve_resource_access_context++ context = resolve_resource_access_context(user_context)+ requested_agent_name = "" if agent_name is _UNSET else str(agent_name or "").strip()+ requested_agent_id = "" if agent_id is _UNSET else str(agent_id or "").strip()+ if (+ context.is_remote+ and agent_backend is not _UNSET+ and bool(str(agent_backend or "").strip())+ and not requested_agent_name+ and not requested_agent_id+ ):+ raise VibeAgentAccessError("Agent access is not permitted.")+ if agent_name is not _UNSET or agent_id is not _UNSET:ensure_agent_selection_access(conn,agent_name=None if agent_name is _UNSET else agent_name,agent_id=None if agent_id is _UNSET else agent_id,- user_context=user_context,+ user_context=context,)# Backend is pinned once a NATIVE conversation exists: the native can onlydiff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.pyindex 3c0a3aae8..e1ed58730 100644--- a/tests/test_resource_acl_agents.py+++ b/tests/test_resource_acl_agents.py@@ -240,6 +240,27 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatcagent_backend="",user_context=context,)+ with pytest.raises(VibeAgentAccessError):+ workbench_sessions_service.create_session(+ connection,+ scope_id=scope_id,+ agent_backend="codex",+ user_context=context,+ )+ backend_only_session = workbench_sessions_service.create_session(+ connection,+ scope_id=scope_id,+ agent_backend="codex",+ user_context=resource_access_service.ResourceUserContext(is_trusted_local=True),+ )+ with pytest.raises(VibeAgentAccessError):+ workbench_sessions_service.update_session(+ connection,+ backend_only_session["id"],+ agent_backend="claude",+ agent_name=None,+ user_context=context,+ )blocked_default = client.post("/api/sessions",json={"project_id": "proj_acl_agents"},@@ -248,6 +269,14 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatcenviron_base=_remote_peer(),)assert blocked_default.status_code == 403+ blocked_backend_only = client.post(+ "/api/sessions",+ json={"project_id": "proj_acl_agents", "agent_backend": "codex"},+ headers=csrf_headers(client, "https://alex.avibe.bot"),+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert blocked_backend_only.status_code == 403store = VibeAgentStore()try:@@ -274,6 +303,17 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatcreturn {"status_code": 202, "body": {}}monkeypatch.setattr("vibe.internal_client.dispatch_async", dispatch_async)+ blocked_legacy_turn = client.post(+ f"/api/sessions/{backend_only_session['id']}/messages",+ json={"text": "must not dispatch"},+ headers=csrf_headers(client, "https://alex.avibe.bot"),+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert blocked_legacy_turn.status_code == 403+ assert blocked_legacy_turn.get_json()["code"] == "agent_access_forbidden"+ assert dispatch_calls == []+with engine.begin() as connection:resource_access_service.apply_control_plane_intent(connection,diff --git a/tests/test_resource_acl_vaults.py b/tests/test_resource_acl_vaults.pyindex a92c364dd..84283658f 100644--- a/tests/test_resource_acl_vaults.py+++ b/tests/test_resource_acl_vaults.py@@ -11,6 +11,7 @@ from storage.models import (metadata,resource_access_groups,resource_access_policies,+ state_meta,vault_grants,vault_requests,vault_secrets,@@ -337,3 +338,76 @@ def test_narrowed_vault_policy_revokes_active_grants(status = conn.execute(select(vault_grants.c.status).where(vault_grants.c.id == grant["id"])).scalar_one()assert status == "revoked"assert releases == [{"scopes": [{"grant_id": grant["id"]}], "reason": "resource-access-policy-narrowed"}]+++def test_narrowed_vault_release_failure_stays_pending_until_retry_succeeds(vault, monkeypatch) -> None:+ owner = _context("owner-1")+ with vault.begin() as conn:+ _create_secret(conn, "RETRY_RELEASE_KEY", protection="protected")+ resource_id = _set_policy(conn, "RETRY_RELEASE_KEY", access_level="public")+ request = vault_service.create_access_request(conn, "RETRY_RELEASE_KEY", user_context=owner)+ grant = _grant_from_request(conn, request, user_context=owner)++ intent = {+ "resource_kind": "vault_secret",+ "resource_id": resource_id,+ "revision": 2,+ "access_level": "private",+ "group_ids": [],+ }+ monkeypatch.setattr("storage.db.get_cached_sqlite_engine", lambda: vault)+ monkeypatch.setattr(+ remote_access,+ "publish_resource_index",+ lambda *_args, **_kwargs: {"organization_id": "org-1", "resources": []},+ )+ monkeypatch.setattr(+ remote_access,+ "pull_resource_acl_intents",+ lambda *_args, **_kwargs: {"organization_id": "org-1", "intents": [intent]},+ )+ acknowledgements: list[dict] = []+ monkeypatch.setattr(+ remote_access,+ "acknowledge_resource_acl_intent",+ lambda *_args, **kwargs: acknowledgements.append(kwargs),+ )+ releases: list[list[dict[str, str]]] = []++ def release(scopes, *, reason):+ releases.append([dict(scope) for scope in scopes])+ if len(releases) == 1:+ raise RuntimeError("resident release failed")++ monkeypatch.setattr(remote_access.api, "release_vault_agent_scopes", release)++ first = remote_access._sync_one_organization(None, organization_id="org-1", resources=[])+ pending_key = remote_access._pending_vault_release_key("org-1", resource_id, 2)+ with vault.connect() as conn:+ pending_after_failure = conn.execute(+ select(state_meta.c.value_json).where(state_meta.c.key == pending_key)+ ).scalar_one_or_none()++ second = remote_access._sync_one_organization(None, organization_id="org-1", resources=[])+ with vault.connect() as conn:+ pending_after_success = conn.execute(+ select(state_meta.c.value_json).where(state_meta.c.key == pending_key)+ ).scalar_one_or_none()++ assert first["ok"] is False+ assert first["applied"] == 1+ assert first["acknowledged"] == 0+ assert first["ack_errors"] == 1+ assert pending_after_failure is not None+ assert second["ok"] is True+ assert second["acknowledged"] == 1+ assert pending_after_success is None+ assert releases == [[{"grant_id": grant["id"]}], [{"grant_id": grant["id"]}]]+ assert acknowledgements == [+ {+ "resource_kind": "vault_secret",+ "resource_id": resource_id,+ "revision": 2,+ "outcome": "applied",+ }+ ]diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.tsindex be044baee..02dc37c70 100644--- a/ui/src/lib/apiFetch.test.ts+++ b/ui/src/lib/apiFetch.test.ts@@ -19,20 +19,21 @@ describe('apiFetch remote auth recovery', () => {vi.clearAllMocks();});- it('hands an expired remote session to the PWA auth gate', async () => {- vi.stubGlobal(- 'fetch',- vi.fn(async () =>- Response.json({ error: 'remote_access_login_required' }, { status: 401 }),- ),- );-- const response = await apiFetch('/api/inbox');-- expect(response.status).toBe(401);- await vi.waitFor(() => expect(deferRemoteAuthRedirect).toHaveBeenCalledOnce());- expect(window.location.assign).not.toHaveBeenCalled();- });+ it.each(['remote_access_login_required', 'remote_access_authorization_refresh_required'])(+ 'hands remote auth recovery error %s to the PWA auth gate',+ async (error) => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => Response.json({ error }, { status: 401 })),+ );++ const response = await apiFetch('/api/inbox');++ expect(response.status).toBe(401);+ await vi.waitFor(() => expect(deferRemoteAuthRedirect).toHaveBeenCalledOnce());+ expect(window.location.assign).not.toHaveBeenCalled();+ },+ );it('does not start remote auth for an unrelated 401', async () => {vi.stubGlobal(diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.tsindex 6936dba98..869a49430 100644--- a/ui/src/lib/apiFetch.ts+++ b/ui/src/lib/apiFetch.ts@@ -3,6 +3,10 @@ import { deferRemoteAuthRedirect } from './remoteAuth';const CSRF_COOKIE_NAME = 'vibe_csrf_token';const CSRF_HEADER_NAME = 'X-Vibe-CSRF-Token';const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);+const REMOTE_AUTH_RECOVERY_ERRORS = new Set([+ 'remote_access_login_required',+ 'remote_access_authorization_refresh_required',+]);let csrfTokenPromise: Promise<string> | null = null;@@ -73,7 +77,7 @@ export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {})// once and then stops re-running on ordinary navigation (so it doesn't// re-mount the shell on every sidebar click). If the Avibe Cloud cookie// expires after that, no component re-checks auth — but the server starts- // answering /api/* with 401 `remote_access_login_required`. Detect it here+ // answering /api/* with a remote login/authorization-refresh 401. Detect it here// and trigger the same full-page login redirect the guard uses, so the user// lands on the login flow instead of a wall of silently-failing fetches.if (response.status === 401) {@@ -95,7 +99,7 @@ async function maybeRedirectOnRemoteAuthExpiry(response: Response): Promise<void// Non-JSON 401 — not the remote-access signal; let the caller handle it.return;}- if ((payload as { error?: string } | null)?.error !== 'remote_access_login_required') {+ if (!REMOTE_AUTH_RECOVERY_ERRORS.has((payload as { error?: string } | null)?.error || '')) {return;}// A cross-origin OAuth redirect from an iOS Home-Screen app opens in adiff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 857ea1c1d..3d2cc098d 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -87,6 +87,7 @@ _RESOURCE_ACL_SYNC_ERROR_CODE_RE = re.compile(r"\A[a-z0-9][a-z0-9_:-]{0,119}\Z")_RESOURCE_ACL_RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill", "show_page"})_RESOURCE_ACL_ACCESS_LEVELS = frozenset({"public", "scope", "private"})_RESOURCE_ACL_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error", "deleted"})+_RESOURCE_ACL_PENDING_VAULT_RELEASE_PREFIX = "resource_acl_pending_vault_release:"_INSTANCE_ACCESS_ROLES = frozenset({"owner", "editor", "viewer"})_INSTANCE_ACCESS_SOURCES = frozenset({"owner", "public_instance", "email", "email_domain", "organization_group"})_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})@@ -873,6 +874,45 @@ def _validated_intent_fields(intent: Any) -> tuple[str, str, int, str, list[str]return str(resource_kind), resource_id, revision, str(access_level), group_ids+def _pending_vault_release_key(organization_id: str, resource_id: str, revision: int) -> str:+ digest = hashlib.sha256(f"{organization_id}\0{resource_id}\0{revision}".encode()).hexdigest()+ return f"{_RESOURCE_ACL_PENDING_VAULT_RELEASE_PREFIX}{digest}"+++def _load_pending_vault_release_scopes(connection, key: str) -> list[dict[str, str]]:+ from sqlalchemy import select+ from storage.models import state_meta++ raw_value = connection.execute(select(state_meta.c.value_json).where(state_meta.c.key == key)).scalar_one_or_none()+ try:+ value = json.loads(raw_value) if raw_value else []+ except (TypeError, ValueError):+ return []+ if not isinstance(value, list):+ return []+ grant_ids = [str(item.get("grant_id") or "") for item in value if isinstance(item, Mapping)]+ return [{"grant_id": grant_id} for grant_id in dict.fromkeys(grant_ids) if grant_id]+++def _store_pending_vault_release_scopes(connection, key: str, scopes: list[dict[str, str]]) -> None:+ from storage.models import state_meta++ connection.execute(state_meta.delete().where(state_meta.c.key == key))+ connection.execute(+ state_meta.insert().values(+ key=key,+ value_json=json.dumps(scopes, separators=(",", ":")),+ updated_at=datetime.now().astimezone().isoformat(),+ )+ )+++def _clear_pending_vault_release_scopes(connection, key: str) -> None:+ from storage.models import state_meta++ connection.execute(state_meta.delete().where(state_meta.c.key == key))++def _sync_one_organization(config: V2Config,*,@@ -912,6 +952,11 @@ def _sync_one_organization(rejected += 1continuerelease_scopes: list[dict[str, str]] = []+ release_key = (+ _pending_vault_release_key(organization, resource_id, revision)+ if resource_kind == "vault_secret"+ else None+ )try:with engine.begin() as connection:previous_policy = resource_access_service.get_resource_policy(@@ -937,6 +982,12 @@ def _sync_one_organization(resource_id,)release_scopes = vault_service.agent_release_scopes_after_rows(connection, revoked_rows)+ if release_scopes and release_key is not None:+ _store_pending_vault_release_scopes(connection, release_key, release_scopes)+ if release_key is not None:+ release_scopes = _load_pending_vault_release_scopes(connection, release_key)+ if outcome["status"] == "applied":+ applied += 1if release_scopes:try:api.release_vault_agent_scopes(@@ -945,11 +996,19 @@ def _sync_one_organization()except Exception:logger.warning("failed to release narrowed Vault grant scopes", exc_info=True)+ ack_errors += 1+ continue+ try:+ with engine.begin() as connection:+ assert release_key is not None+ _clear_pending_vault_release_scopes(connection, release_key)+ except Exception:+ logger.warning("failed to clear pending narrowed Vault grant release", exc_info=True)+ ack_errors += 1+ continueif outcome["status"] == "stale":skipped += 1continue- if outcome["status"] == "applied":- applied += 1try:acknowledge_resource_acl_intent(config,