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.

fix(permissions): resolve authorization review findings

Maxbf4b8a0a2fea
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 7c671576c..389a4475f 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -254,5 +254,4 @@ scenarios:
layer: scenario
backend: codex
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_codex_connection_probe_reuses_persistent_app_server
-next_priority:
- - AUTH-SETUP-301
+next_priority: []
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 77614e636..c85ac96dd 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -14,6 +14,7 @@ from unittest.mock import AsyncMock, patch
import httpx
import jwt
import pytest
+import yaml
from cryptography.hazmat.primitives.asymmetric import rsa
ROOT = Path(__file__).resolve().parents[3]
@@ -60,6 +61,13 @@ from vibe import remote_access, show_identity, ui_server
from vibe.ui_server import app
+def test_auth_setup_catalog_priorities_reference_live_scenarios():
+ catalog = yaml.safe_load((ROOT / "tests/scenarios/auth_setup/catalog.yaml").read_text())
+ live_ids = {scenario["id"] for scenario in catalog["scenarios"]}
+
+ assert set(catalog.get("next_priority", [])) <= live_ids
+
+
class ShowPageEmailAccessScenarioTests(unittest.TestCase):
def setUp(self):
self.harness = ShowPageEmailAccessScenarioHarness()
diff --git a/tests/test_remote_authorization_revision.py b/tests/test_remote_authorization_revision.py
index 511fa5d0a..8fcb6643b 100644
--- a/tests/test_remote_authorization_revision.py
+++ b/tests/test_remote_authorization_revision.py
@@ -878,6 +878,40 @@ def test_authorization_revision_device_contract_is_monotonic(monkeypatch, tmp_pa
assert remote_access.current_authorization_revision(config) == 42
+def test_authorization_revision_cache_observes_another_process_watermark(
+ monkeypatch,
+ tmp_path,
+):
+ """A controller cache must observe a mutation persisted by the UI server."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path, revision=41)
+ claims = _organization_claims(config, revision=41)
+ source_updated_at = time.time()
+
+ assert remote_access.session_authorization_revision_state(
+ config,
+ claims,
+ now=source_updated_at,
+ ) == "current"
+
+ remote_access.runtime.write_json(
+ remote_access._authorization_revision_state_path(), # noqa: SLF001
+ {
+ "schema_version": 1,
+ "instance_id": "inst_123",
+ "authorization_revision": 42,
+ "source_updated_at": source_updated_at,
+ },
+ )
+
+ assert remote_access.session_authorization_revision_state(
+ config,
+ claims,
+ now=source_updated_at,
+ ) == "mismatch"
+
+
def test_authorization_revision_sync_rejects_an_unpersisted_watermark(
monkeypatch,
tmp_path,
diff --git a/ui/src/features/permissions/PermissionsPage.test.tsx b/ui/src/features/permissions/PermissionsPage.test.tsx
index 5e5b83c8b..84eea1c6c 100644
--- a/ui/src/features/permissions/PermissionsPage.test.tsx
+++ b/ui/src/features/permissions/PermissionsPage.test.tsx
@@ -961,6 +961,67 @@ describe('PermissionsPage conflict handling', () => {
]);
});
+ it('closes an access addition when conflict refresh shows the draft was already applied', async () => {
+ const initial = response();
+ const latest = response();
+ latest.projection.instance.authorization_revision = 5;
+ latest.projection.access.entries = [
+ { kind: 'email', value: '[email protected]', role: 'viewer' },
+ ];
+ api.getPermissions
+ .mockResolvedValueOnce(initial)
+ .mockResolvedValueOnce(latest);
+ api.replaceAuthorizedUsers.mockRejectedValueOnce(new PermissionsApiError(409, {
+ error: 'permission_revision_conflict',
+ current_revision: 5,
+ }));
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(await screen.findByRole('button', { name: 'permissions.actions.addAccess' }));
+ await user.type(screen.getByLabelText('permissions.fields.principal'), '[email protected]');
+ await user.click(screen.getByRole('button', { name: 'permissions.actions.save' }));
+
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(screen.getByText('[email protected]')).toBeTruthy();
+ expect(api.replaceAuthorizedUsers).toHaveBeenCalledOnce();
+ });
+
+ it('closes a principal replacement when conflict refresh shows it was already applied', async () => {
+ const initial = response();
+ initial.projection.access.entries = [
+ { kind: 'email', value: '[email protected]', role: 'viewer' },
+ ];
+ const latest = response();
+ latest.projection.instance.authorization_revision = 5;
+ latest.projection.access.entries = [
+ { kind: 'email', value: '[email protected]', role: 'viewer' },
+ ];
+ api.getPermissions
+ .mockResolvedValueOnce(initial)
+ .mockResolvedValueOnce(latest);
+ api.replaceAuthorizedUsers.mockRejectedValueOnce(new PermissionsApiError(409, {
+ error: 'permission_revision_conflict',
+ current_revision: 5,
+ }));
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(await screen.findByRole('button', { name: 'permissions.actions.editAccess' }));
+ await user.clear(screen.getByLabelText('permissions.fields.principal'));
+ await user.type(screen.getByLabelText('permissions.fields.principal'), '[email protected]');
+ await user.click(screen.getByRole('button', { name: 'permissions.actions.save' }));
+ const narrowingDialog = (await screen.findByText('permissions.access.narrowTitle')).closest('[role="dialog"]');
+ await user.click(within(narrowingDialog as HTMLElement).getByRole('button', {
+ name: 'permissions.actions.save',
+ }));
+
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(screen.getByText('[email protected]')).toBeTruthy();
+ expect(screen.queryByText('[email protected]')).toBeNull();
+ expect(api.replaceAuthorizedUsers).toHaveBeenCalledOnce();
+ });
+
it('keeps an access draft mounted when the conflict refresh fails', async () => {
const initial = response();
initial.projection.access.entries = [
diff --git a/ui/src/features/permissions/PermissionsPage.tsx b/ui/src/features/permissions/PermissionsPage.tsx
index 4a6b67f57..87f8b7076 100644
--- a/ui/src/features/permissions/PermissionsPage.tsx
+++ b/ui/src/features/permissions/PermissionsPage.tsx
@@ -357,11 +357,24 @@ function AccessEntryDialog({
setError('permissions_pairing_changed');
return false;
}
- baselineEntry.current = originalKey === null
+ const latestEntries = latest.response.projection.access.entries;
+ const latestOriginal = originalKey === null
? null
- : latest.response.projection.access.entries.find(
- (entry) => accessEntryKey(entry) === originalKey,
- ) ?? null;
+ : latestEntries.find((entry) => accessEntryKey(entry) === originalKey) ?? null;
+ const latestCandidate = latestEntries.find(
+ (entry) => accessEntryKey(entry) === accessEntryKey(candidate),
+ );
+ if (
+ latestCandidate?.role === candidate.role
+ && (originalKey === null || originalKey === accessEntryKey(candidate) || latestOriginal === null)
+ ) {
+ setConflict(false);
+ setRefreshRequired(false);
+ setError(undefined);
+ onOpenChange(false);
+ return true;
+ }
+ baselineEntry.current = latestOriginal;
setRevision(latest.response.projection.instance.authorization_revision);
setRefreshRequired(false);
setError(undefined);
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 3ff6e1581..fd89557f6 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -80,7 +80,18 @@ _ACTIVE_HOSTNAMES_CACHE: tuple[Path, str, frozenset[str], float | None] | None =
_AUTHORIZATION_REVISION_KEY = "vibe_instance_authorization_revision"
_AUTHORIZATION_CHECKED_REVISION_KEY = "_authorization_checked_revision"
_AUTHORIZATION_REVISION_LOCK = threading.Lock()
-_AUTHORIZATION_REVISION_CACHE: tuple[Path, str, int, float] | None = None
+
+
+@dataclass(frozen=True)
+class _AuthorizationRevisionCache:
+ state_path: Path
+ instance_id: str
+ revision: int
+ source_updated_at: float
+ file_signature: tuple[int, int, int, int] | None
+
+
+_AUTHORIZATION_REVISION_CACHE: _AuthorizationRevisionCache | None = None
_AUTHORIZATION_REVISION_SYNC_LOCK = threading.Lock()
_AUTHORIZATION_REVISION_POLL_LOCK = threading.Lock()
_AUTHORIZATION_REVISION_POLL_STARTED = False
@@ -663,6 +674,19 @@ def _normalize_authorization_revision(value: Any) -> int:
return value
+def _authorization_revision_file_signature(path: Path) -> tuple[int, int, int, int] | None:
+ try:
+ metadata = path.stat()
+ except OSError:
+ return None
+ return (
+ metadata.st_mtime_ns,
+ metadata.st_ctime_ns,
+ metadata.st_size,
+ metadata.st_ino,
+ )
+
+
def _load_authorization_revision_snapshot(config: V2Config) -> tuple[int, float] | None:
global _AUTHORIZATION_REVISION_CACHE
@@ -671,24 +695,40 @@ def _load_authorization_revision_snapshot(config: V2Config) -> tuple[int, float]
return None
state_path = _authorization_revision_state_path()
with _AUTHORIZATION_REVISION_LOCK:
+ file_signature = _authorization_revision_file_signature(state_path)
cached = _AUTHORIZATION_REVISION_CACHE
- if cached is not None and cached[0] == state_path and cached[1] == instance_id:
- return cached[2], cached[3]
+ cache_matches = (
+ cached is not None
+ and cached.state_path == state_path
+ and cached.instance_id == instance_id
+ )
+ if cache_matches and cached.file_signature == file_signature:
+ return cached.revision, cached.source_updated_at
payload = runtime.read_json(state_path)
if not isinstance(payload, dict) or payload.get("schema_version") != 1:
+ if cache_matches:
+ _AUTHORIZATION_REVISION_CACHE = None
return None
if str(payload.get("instance_id") or "").strip() != instance_id:
+ if cache_matches:
+ _AUTHORIZATION_REVISION_CACHE = None
return None
try:
revision = _normalize_authorization_revision(payload.get("authorization_revision"))
source_updated_at = float(payload["source_updated_at"])
except (KeyError, TypeError, ValueError):
+ if cache_matches:
+ _AUTHORIZATION_REVISION_CACHE = None
return None
- _AUTHORIZATION_REVISION_CACHE = (
- state_path,
- instance_id,
- revision,
- source_updated_at,
+ if cache_matches and cached.revision > revision:
+ revision = cached.revision
+ source_updated_at = cached.source_updated_at
+ _AUTHORIZATION_REVISION_CACHE = _AuthorizationRevisionCache(
+ state_path=state_path,
+ instance_id=instance_id,
+ revision=revision,
+ source_updated_at=source_updated_at,
+ file_signature=file_signature,
)
return revision, source_updated_at
@@ -727,8 +767,12 @@ def _install_authorization_revision(
source_updated_at = time.time()
with _AUTHORIZATION_REVISION_LOCK:
cached = _AUTHORIZATION_REVISION_CACHE
- if cached is not None and cached[0] == state_path and cached[1] == instance_id:
- previous_revision = cached[2]
+ if (
+ cached is not None
+ and cached.state_path == state_path
+ and cached.instance_id == instance_id
+ ):
+ previous_revision = cached.revision
else:
payload = runtime.read_json(state_path)
previous_revision = None
@@ -762,11 +806,12 @@ def _install_authorization_revision(
"Authorization revision acknowledgement could not be persisted",
exc_info=True,
)
- _AUTHORIZATION_REVISION_CACHE = (
- state_path,
- instance_id,
- revision,
- source_updated_at,
+ _AUTHORIZATION_REVISION_CACHE = _AuthorizationRevisionCache(
+ state_path=state_path,
+ instance_id=instance_id,
+ revision=revision,
+ source_updated_at=source_updated_at,
+ file_signature=_authorization_revision_file_signature(state_path),
)
if changed:
try: