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(permissions): close workspace access races
Maxd747fa3aeb48
diff --git a/core/show_pages.py b/core/show_pages.pyindex 655fa5868..0cebd9868 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -764,8 +764,9 @@ class ShowPageStore:return permissions.resolve_current_instance_ownership()- @staticmethod+ @classmethoddef _reconcile_resource_policy(+ cls,connection,session_id: str,user_context: Any,@@ -773,6 +774,13 @@ class ShowPageStore:) -> dict[str, Any]:from storage import resource_access_service+ current_policy = resource_access_service.get_resource_policy(+ "show_page",+ session_id,+ connection=connection,+ )+ if current_policy is None and not user_context.can_use_show_page(session_id):+ cls._require_project_edit_access(connection, session_id, user_context)owner_user_id = (user_context.subjectif user_context.subject and user_context.has_role("editor")diff --git a/tests/test_permissions.py b/tests/test_permissions.pyindex 493d7d5d5..372e81143 100644--- a/tests/test_permissions.py+++ b/tests/test_permissions.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import multiprocessing as mpfrom typing import Anyimport pytest@@ -39,9 +40,29 @@ def _config(instance_id: str = "inst-123") -> V2Config:cloud.backend_url = "https://backend.example"cloud.instance_id = instance_idcloud.instance_secret = "device-secret"+ config.save()return config+def _cache_projection_process(+ projection: dict[str, Any],+ entered_write,+ release_write,+) -> None:+ original_write = permissions._write_cache # noqa: SLF001++ if entered_write is not None:+ def delayed_write(instance_id: str, candidate: dict[str, Any]) -> None:+ entered_write.set()+ if not release_write.wait(10):+ raise TimeoutError("cache write was not released")+ original_write(instance_id, candidate)++ permissions._write_cache = delayed_write # noqa: SLF001++ permissions._cache_projection("inst-123", projection) # noqa: SLF001++def _projection(instance_id: str = "inst-123") -> dict:return {"schema_version": 1,@@ -518,13 +539,14 @@ def test_permissions_offline_cache_is_sanitized_and_exact_instance_bound(monkeypdef test_permissions_cache_remains_atomic_without_os_fchmod(monkeypatch) -> None:monkeypatch.delattr(permissions.os, "fchmod", raising=False)projection = _complete_projection()+ config = _config()monkeypatch.setattr(permissions.requests,"request",lambda *_args, **_kwargs: _Response(200, projection),)- result = permissions.get_current_permissions(_config())+ result = permissions.get_current_permissions(config)cached = permissions._read_cache("inst-123") # noqa: SLF001assert result.source == "live"assert cached is not None@@ -543,7 +565,7 @@ def test_permissions_cache_remains_atomic_without_os_fchmod(monkeypatch) -> Nonelambda *_args, **_kwargs: _Response(200, newer),)- live = permissions.get_current_permissions(_config())+ live = permissions.get_current_permissions(config)retained = permissions._read_cache("inst-123") # noqa: SLF001assert live.projection == newer@@ -553,6 +575,44 @@ def test_permissions_cache_remains_atomic_without_os_fchmod(monkeypatch) -> Noneassert list(cache_path.parent.glob(f".{cache_path.name}.*")) == []+def test_permissions_cache_revision_is_monotonic_across_processes() -> None:+ stale = _complete_projection()+ stale["instance"]["authorization_revision"] = 3+ newer = _complete_projection()+ newer["instance"]["authorization_revision"] = 4+ context = mp.get_context("spawn")+ entered_write = context.Event()+ release_write = context.Event()+ stale_writer = context.Process(+ target=_cache_projection_process,+ args=(stale, entered_write, release_write),+ )+ newer_writer = context.Process(+ target=_cache_projection_process,+ args=(newer, None, None),+ )++ try:+ stale_writer.start()+ assert entered_write.wait(10)+ newer_writer.start()+ release_write.set()+ stale_writer.join(10)+ newer_writer.join(10)+ assert stale_writer.exitcode == 0+ assert newer_writer.exitcode == 0+ finally:+ release_write.set()+ for process in (stale_writer, newer_writer):+ if process.is_alive():+ process.terminate()+ process.join(5)++ cached = permissions._read_cache("inst-123") # noqa: SLF001+ assert cached is not None+ assert cached.projection["instance"]["authorization_revision"] == 4++@pytest.mark.parametrize("status",[*sorted(permissions._CACHE_FALLBACK_HTTP_STATUSES), 503], # noqa: SLF001@@ -782,7 +842,9 @@ def test_permissions_rejects_inflight_results_after_the_pairing_tuple_changes(return super().json()def request(_method, _url, **_kwargs):- setattr(config.remote_access.vibe_cloud, credential_field, replacement)+ current = V2Config.load()+ setattr(current.remote_access.vibe_cloud, credential_field, replacement)+ current.save()if operation == "get":payload = backend_projectionelif operation == "authorized_users":@@ -848,7 +910,9 @@ def test_permissions_rejects_cached_fallback_after_inflight_pairing_change(permissions._cache_projection("inst-123", cached_projection) # noqa: SLF001def request(_method, _url, **_kwargs):- config.remote_access.vibe_cloud.instance_id = "inst-new"+ current = V2Config.load()+ current.remote_access.vibe_cloud.instance_id = "inst-new"+ current.save()raise requests.ConnectionError()monkeypatch.setattr(permissions.requests, "request", request)diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.pyindex 34f5ea363..9e95b33bc 100644--- a/tests/test_resource_acl_show_pages.py+++ b/tests/test_resource_acl_show_pages.py@@ -609,6 +609,82 @@ def test_existing_show_page_is_adopted_idempotently_without_changing_link_accessstore.close()+def test_legacy_show_page_policy_reconciliation_requires_existing_page_or_project_access(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ project_path = tmp_path / "project"+ project_path.mkdir()+ editor = _organization_context("editor-1", instance_role="editor")+ try:+ with store.engine.begin() as connection:+ project = projects_service.create_project(connection, str(project_path))+ session_id = sessions_service.create_session(+ connection,+ scope_id=project["scope_id"],+ agent_backend="codex",+ )["id"]+ store.ensure(session_id)+ _paired_config(tmp_path, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "resolve_current_instance_ownership",+ lambda: _ownership("organization", organization_id="org-1"),+ )+ with store.engine.begin() as connection:+ project_access_service.apply_project_access_intent(+ connection,+ {+ "project_id": project["id"],+ "revision": 1,+ "mode": "restricted",+ "bindings": [],+ },+ )++ with pytest.raises(ShowPageError, match="Show Page access is not permitted"):+ api.get_show_page_access(session_id, user_context=editor)+ with store.engine.connect() as connection:+ assert resource_access_service.get_resource_policy(+ "show_page",+ session_id,+ connection=connection,+ ) is None++ with store.engine.begin() as connection:+ project_access_service.apply_project_access_intent(+ connection,+ {+ "project_id": project["id"],+ "revision": 2,+ "mode": "restricted",+ "bindings": [{+ "principal_kind": "email",+ "principal_value": "[email protected]",+ "access_role": "editor",+ }],+ },+ )++ response = api.get_show_page_access(session_id, user_context=editor)+ with store.engine.connect() as connection:+ policy = resource_access_service.get_resource_policy(+ "show_page",+ session_id,+ connection=connection,+ )+ assert response["ownership_status"] == "created"+ assert response["can_use"] is True+ assert response["can_manage"] is True+ assert policy is not None+ assert policy["owner_user_id"] == "editor-1"+ assert policy["organization_id"] == "org-1"+ finally:+ store.close()++def test_show_page_access_api_distinguishes_personal_and_organization_modes(monkeypatch, tmp_path) -> None:personal_home = tmp_path / "personal"monkeypatch.setenv("AVIBE_HOME", str(personal_home))diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsxindex 9b6b981fe..8f23fe10e 100644--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx@@ -1,10 +1,11 @@/** @vitest-environment jsdom */-import { act, cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, render, screen, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { PermissionsApiError } from '@/features/permissions/api';+import { requiresResourcePolicyNarrowing } from '@/features/permissions/policy';import type {DirectoryGroup,PermissionResource,@@ -51,6 +52,8 @@ const translations: Record<string, string> = {'chat.showPage.workspaceReadOnly': 'Avibe Cloud owns this policy. Edit it in Avibe Cloud.','chat.showPage.workspaceOwnerOnly': 'Only the Instance Owner can change Workspace access.','chat.showPage.workspaceLoadError': 'Workspace access could not be loaded.',+ 'chat.showPage.workspaceNarrowTitle': 'Narrow Workspace access?',+ 'chat.showPage.workspaceNarrowBody': 'Some people may lose access as soon as this policy is applied.','chat.showPage.applyWorkspaceAccess': 'Apply','chat.showPage.workspaceSync.pending': 'The policy is waiting for this Avibe to apply it.','chat.showPage.workspaceSync.offline': 'This Avibe has not acknowledged the latest policy.',@@ -199,6 +202,48 @@ afterEach(() => {});describe('ShowPageWorkspaceAccessControl', () => {+ it('classifies every Workspace policy reduction at the shared boundary', () => {+ expect(requiresResourcePolicyNarrowing('public', [], 'private', [])).toBe(true);+ expect(requiresResourcePolicyNarrowing('public', [], 'scope', ['group-active'])).toBe(true);+ expect(requiresResourcePolicyNarrowing('scope', ['group-active'], 'private', [])).toBe(true);+ expect(requiresResourcePolicyNarrowing(+ 'scope',+ ['group-active', 'group-archived'],+ 'scope',+ ['group-active'],+ )).toBe(true);+ expect(requiresResourcePolicyNarrowing('scope', ['group-active'], 'public', [])).toBe(false);+ expect(requiresResourcePolicyNarrowing('private', [], 'public', [])).toBe(false);+ });++ it('confirms a Workspace policy reduction before sending it', async () => {+ api.getResourceAccess.mockResolvedValue({+ resource: resource({ level: 'public' }),+ });+ api.updateResourceAccess.mockResolvedValue({+ ok: true,+ resource: resource({ level: 'private', revision: 5 }),+ });+ const user = userEvent.setup();+ renderControl();++ await user.click(await screen.findByRole('radio', { name: 'Private' }));+ await user.click(screen.getByRole('button', { name: 'Apply' }));++ const dialog = screen.getByText('Narrow Workspace access?').closest('[role="dialog"]');+ expect(dialog).toBeTruthy();+ expect(api.updateResourceAccess).not.toHaveBeenCalled();++ await user.click(within(dialog as HTMLElement).getByRole('button', { name: 'Apply' }));+ expect(api.updateResourceAccess).toHaveBeenCalledWith(+ { resource_kind: 'show_page', resource_id: 'ses-1' },+ 'private',+ [],+ 4,+ 'inst-1',+ );+ });+it('saves Organization and selected-group policies and reloads the canonical group selection', async () => {api.updateResourceAccess.mockResolvedValueOnce({ ok: true, resource: resource({ level: 'public', revision: 5 }) })@@ -222,6 +267,8 @@ describe('ShowPageWorkspaceAccessControl', () => {await user.click(screen.getByRole('radio', { name: 'Selected groups' }));await user.click(screen.getByRole('checkbox', { name: 'Design' }));await user.click(screen.getByRole('button', { name: 'Apply' }));+ const narrowingDialog = screen.getByText('Narrow Workspace access?').closest('[role="dialog"]');+ await user.click(within(narrowingDialog as HTMLElement).getByRole('button', { name: 'Apply' }));expect(api.updateResourceAccess).toHaveBeenLastCalledWith({ resource_kind: 'show_page', resource_id: 'ses-1' },'scope',@@ -307,6 +354,8 @@ describe('ShowPageWorkspaceAccessControl', () => {await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));await user.click(screen.getByRole('checkbox', { name: 'Design' }));await user.click(screen.getByRole('button', { name: 'Apply' }));+ const narrowingDialog = screen.getByText('Narrow Workspace access?').closest('[role="dialog"]');+ await user.click(within(narrowingDialog as HTMLElement).getByRole('button', { name: 'Apply' }));expect(await screen.findByText(/Your draft was kept/)).toBeTruthy();expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');@@ -324,6 +373,30 @@ describe('ShowPageWorkspaceAccessControl', () => {);});+ it('disables the mounted editor when the authoritative conflict refresh fails', async () => {+ api.getPermissions+ .mockResolvedValueOnce(permissions())+ .mockRejectedValueOnce(new PermissionsApiError(503, {+ error: 'permissions_backend_unavailable',+ }));+ api.updateResourceAccess.mockRejectedValueOnce(new PermissionsApiError(409, {+ error: 'permission_revision_conflict',+ current_revision: 5,+ }));+ const user = userEvent.setup();+ renderControl();++ await user.click(await screen.findByRole('radio', { name: 'Organization' }));+ await user.click(screen.getByRole('button', { name: 'Apply' }));++ expect(await screen.findByText('Workspace access could not be loaded.')).toBeTruthy();+ expect((screen.getByRole('radio', { name: 'Private' }) as HTMLButtonElement).disabled).toBe(true);+ const apply = screen.getByRole('button', { name: 'Apply' }) as HTMLButtonElement;+ expect(apply.disabled).toBe(true);+ await user.click(apply);+ expect(api.updateResourceAccess).toHaveBeenCalledTimes(1);+ });+it('fails closed for personal, pending, and conflicting ownership without contacting Permissions', () => {const personal = renderControl(showPageAccess({mode: 'personal',diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsxindex 7a0532220..cb541bdb5 100644--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';+import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { SegmentedRadio } from '@/components/ui/segmented';import {getPermissions,@@ -12,6 +13,7 @@ import {PermissionsApiError,updateResourceAccess,} from '@/features/permissions/api';+import { requiresResourcePolicyNarrowing } from '@/features/permissions/policy';import type {DirectoryGroup,PermissionResource,@@ -63,6 +65,7 @@ export function ShowPageWorkspaceAccessControl({const [level, setLevel] = useState<ResourceAccessLevel>('private');const [groupIds, setGroupIds] = useState<string[]>([]);const [saving, setSaving] = useState(false);+ const [confirmNarrowing, setConfirmNarrowing] = useState(false);const [errorCode, setErrorCode] = useState<string | null>(null);const generationRef = useRef(0);const sessionIdRef = useRef(sessionId);@@ -154,6 +157,7 @@ export function ShowPageWorkspaceAccessControl({setLevel('private');setGroupIds([]);setSaving(false);+ setConfirmNarrowing(false);setErrorCode(null);if (active && organizationReady) void load();return () => {@@ -181,11 +185,11 @@ export function ShowPageWorkspaceAccessControl({);const editable = canManageInstance&& localMutationAllowed- && gate !== 'loading'+ && (gate === 'ready' || gate === 'conflict')&& !saving;const invalid = level === 'scope' && targetGroupIds.length === 0;- const save = async () => {+ const commit = async () => {if (!resource || !instanceId || !dirty || invalid || !editable) return;const generation = generationRef.current;const requestSessionId = sessionId;@@ -216,6 +220,7 @@ export function ShowPageWorkspaceAccessControl({) return;if (isRevisionConflict(caught)) {setSaving(false);+ setConfirmNarrowing(false);await load('conflict', draft);return;}@@ -225,8 +230,26 @@ export function ShowPageWorkspaceAccessControl({if (generation === generationRef.current&& requestSessionId === sessionIdRef.current- ) setSaving(false);+ ) {+ setSaving(false);+ setConfirmNarrowing(false);+ }+ }+ };++ const save = async () => {+ if (!resource || !instanceId || !dirty || invalid || !editable) return;+ const draft = draftRef.current;+ if (requiresResourcePolicyNarrowing(+ resource.access.access_level,+ resource.access.group_ids,+ draft.level,+ draft.level === 'scope' ? uniqueSorted(draft.groupIds) : [],+ )) {+ setConfirmNarrowing(true);+ return;}+ await commit();};return (@@ -376,6 +399,15 @@ export function ShowPageWorkspaceAccessControl({</Button></div>) : null}+ <ConfirmDialog+ open={confirmNarrowing}+ onOpenChange={setConfirmNarrowing}+ title={t('chat.showPage.workspaceNarrowTitle')}+ description={t('chat.showPage.workspaceNarrowBody')}+ confirmLabel={t('chat.showPage.applyWorkspaceAccess')}+ confirmDisabled={!editable}+ onConfirm={commit}+ /></section>);}diff --git a/ui/src/features/permissions/policy.ts b/ui/src/features/permissions/policy.tsindex 8219cab6b..5424ab4df 100644--- a/ui/src/features/permissions/policy.ts+++ b/ui/src/features/permissions/policy.ts@@ -3,6 +3,7 @@ import type {PermissionProject,PrincipalKind,ProjectBinding,+ ResourceAccessLevel,} from './types';export type ProjectAccessMode = 'inherit' | 'owner_only' | 'restricted';@@ -66,3 +67,17 @@ export function requiresProjectNarrowing(return !next || (binding.access_role === 'editor' && next.access_role === 'viewer');});}++export function requiresResourcePolicyNarrowing(+ currentLevel: ResourceAccessLevel,+ currentGroupIds: string[],+ nextLevel: ResourceAccessLevel,+ nextGroupIds: string[],+): boolean {+ if (currentLevel === 'public') return nextLevel !== 'public';+ if (currentLevel === 'private') return nextLevel === 'scope';+ if (nextLevel === 'private') return true;+ if (nextLevel === 'public') return false;+ const nextGroups = new Set(nextGroupIds);+ return currentGroupIds.some((groupId) => !nextGroups.has(groupId));+}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 78caa6e4b..803834e8e 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -3595,6 +3595,8 @@"workspaceReadOnly": "Avibe Cloud owns this policy. Edit it in Avibe Cloud.","workspaceOwnerOnly": "Only the Instance Owner can change Workspace access.","workspaceLoadError": "Workspace access could not be loaded.",+ "workspaceNarrowTitle": "Narrow Workspace access?",+ "workspaceNarrowBody": "Some people may lose access as soon as this policy is applied.","applyWorkspaceAccess": "Apply","workspaceSync": {"pending": "The policy is waiting for this Avibe to apply it.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 84ba0697e..64e3591cc 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -3595,6 +3595,8 @@"workspaceReadOnly": "此策略由 Avibe Cloud 管理,请前往 Avibe Cloud 修改。","workspaceOwnerOnly": "只有 Instance Owner 可以修改 Workspace 访问。","workspaceLoadError": "无法加载 Workspace 访问设置。",+ "workspaceNarrowTitle": "收紧 Workspace 访问权限?",+ "workspaceNarrowBody": "策略应用后,部分用户可能立即失去访问权限。","applyWorkspaceAccess": "应用","workspaceSync": {"pending": "策略正在等待此 Avibe 应用。",diff --git a/vibe/permissions.py b/vibe/permissions.pyindex c01420b38..ff67a5c0b 100644--- a/vibe/permissions.py+++ b/vibe/permissions.py@@ -468,9 +468,7 @@ def _runtime_credentials(config: V2Config) -> tuple[str, str, str]:def _request_config(config: V2Config | None,) -> tuple[V2Config, Callable[[], V2Config]]:- if config is not None:- return config, lambda: config- return V2Config.load(), V2Config.load+ return (config if config is not None else V2Config.load()), V2Config.loaddef _guard_current_pairing(@@ -498,6 +496,15 @@ def _cache_path() -> Path:return paths.get_state_dir() / CACHE_FILENAME+def _cache_file_lock(path: Path):+ """Return the cross-process lock for projection read-compare-write updates."""++ # Import lazily because storage's package initializer imports V2Config.+ from storage.lock import MigrationFileLock++ return MigrationFileLock(path.with_name(f".{path.stem}.lock"))++def _write_cache(instance_id: str, projection: dict[str, Any]) -> None:cache_path = _cache_path()cache_path.parent.mkdir(parents=True, exist_ok=True)@@ -556,16 +563,19 @@ def _read_cache(instance_id: str) -> PermissionsProjectionResult | None:def _cache_projection(instance_id: str, projection: Any) -> None:validated = _validated_projection(projection, instance_id)with _CACHE_LOCK:- cached = _read_cache(instance_id)- if (- cached is not None- and cached.projection["instance"]["authorization_revision"]- > validated["instance"]["authorization_revision"]- ):- returntry:- _write_cache(instance_id, validated)- except OSError:+ cache_path = _cache_path()+ cache_path.parent.mkdir(parents=True, exist_ok=True)+ with _cache_file_lock(cache_path):+ cached = _read_cache(instance_id)+ if (+ cached is not None+ and cached.projection["instance"]["authorization_revision"]+ > validated["instance"]["authorization_revision"]+ ):+ return+ _write_cache(instance_id, validated)+ except (OSError, TimeoutError):logger.warning("Unable to cache the current Permissions projection", exc_info=True)