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): harden local state persistence

Maxfa80ff1d758f
diff --git a/tests/test_permissions.py b/tests/test_permissions.py
index 94df01e02..d83989618 100644
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -294,7 +294,8 @@ def test_permissions_offline_cache_is_sanitized_and_exact_instance_bound(monkeyp
cache = json.loads(permissions._cache_path().read_text(encoding="utf-8")) # noqa: SLF001
assert "must-not-persist" not in json.dumps(cache)
assert cache["projection"]["debug"] == {"note": "kept"}
- assert permissions._cache_path().stat().st_mode & 0o777 == 0o600 # noqa: SLF001
+ if permissions.os.name == "posix":
+ assert permissions._cache_path().stat().st_mode & 0o777 == 0o600 # noqa: SLF001
monkeypatch.setattr(
permissions.requests,
@@ -309,6 +310,44 @@ def test_permissions_offline_cache_is_sanitized_and_exact_instance_bound(monkeyp
permissions.get_current_permissions(_config("inst-other"))
+def test_permissions_cache_remains_atomic_without_os_fchmod(monkeypatch) -> None:
+ monkeypatch.delattr(permissions.os, "fchmod", raising=False)
+ projection = _complete_projection()
+ monkeypatch.setattr(
+ permissions.requests,
+ "request",
+ lambda *_args, **_kwargs: _Response(200, projection),
+ )
+
+ result = permissions.get_current_permissions(_config())
+ cached = permissions._read_cache("inst-123") # noqa: SLF001
+ assert result.source == "live"
+ assert cached is not None
+ assert cached.projection == projection
+
+ newer = _complete_projection()
+ newer["instance"]["authorization_revision"] = 4
+ monkeypatch.setattr(
+ permissions.os,
+ "replace",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("replace failed")),
+ )
+ monkeypatch.setattr(
+ permissions.requests,
+ "request",
+ lambda *_args, **_kwargs: _Response(200, newer),
+ )
+
+ live = permissions.get_current_permissions(_config())
+ retained = permissions._read_cache("inst-123") # noqa: SLF001
+
+ assert live.projection == newer
+ assert retained is not None
+ assert retained.projection == projection
+ cache_path = permissions._cache_path() # noqa: SLF001
+ assert list(cache_path.parent.glob(f".{cache_path.name}.*")) == []
+
+
@pytest.mark.parametrize(
"status",
[*sorted(permissions._CACHE_FALLBACK_HTTP_STATUSES), 503], # noqa: SLF001
@@ -914,6 +953,101 @@ def test_permissions_mutations_advance_and_publish_the_authorization_watermark(
]
[email protected]("operation", ("authorized_users", "project_access"))
+def test_committed_permissions_mutations_survive_watermark_persistence_failure(
+ monkeypatch,
+ operation: str,
+) -> None:
+ config = _config()
+ projection = _complete_projection()
+ permissions._cache_projection("inst-123", projection) # noqa: SLF001
+ remote_access._clear_authorization_revision_cache() # noqa: SLF001
+ remote_access._replace_authorization_revision(config, 3) # noqa: SLF001
+ published = []
+ monkeypatch.setattr(
+ broker,
+ "publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ monkeypatch.setattr(
+ remote_access.runtime,
+ "write_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
+ )
+ updated_entries = [
+ {"kind": "email", "value": "[email protected]", "role": "editor"}
+ ]
+ updated_project = {
+ **projection["projects"][0],
+ "access": {
+ **projection["projects"][0]["access"],
+ "revision": 3,
+ },
+ }
+
+ def request(_method, url, **_kwargs):
+ if url.endswith("/authorized-users"):
+ return _Response(
+ 200,
+ {
+ "ok": True,
+ "entries": updated_entries,
+ "authorization_revision": 4,
+ },
+ )
+ return _Response(
+ 200,
+ {
+ "ok": True,
+ "project": updated_project,
+ "authorization_revision": 4,
+ },
+ )
+
+ monkeypatch.setattr(permissions.requests, "request", request)
+
+ if operation == "authorized_users":
+ result = permissions.replace_authorized_users(
+ {
+ "entries": updated_entries,
+ "if_match_revision": 3,
+ "if_match_instance_id": "inst-123",
+ },
+ config,
+ )
+ else:
+ result = permissions.update_project_access(
+ "project-1",
+ {
+ "mode": "restricted",
+ "bindings": updated_project["access"]["bindings"],
+ "if_match_revision": 2,
+ "if_match_instance_id": "inst-123",
+ },
+ config,
+ )
+
+ cached = permissions._read_cache("inst-123") # noqa: SLF001
+ persisted = json.loads(
+ remote_access._authorization_revision_state_path().read_text(encoding="utf-8") # noqa: SLF001
+ )
+ assert result["authorization_revision"] == 4
+ assert remote_access.current_authorization_revision(config) == 4
+ assert persisted["authorization_revision"] == 3
+ assert remote_access.acknowledge_authorization_revision(config, 4) == 4
+ assert remote_access.acknowledge_authorization_revision(config, 3) == 4
+ assert remote_access.current_authorization_revision(config) == 4
+ assert published == [
+ ("authorization.changed", {"instance_authorization_revision": 4})
+ ]
+ assert cached is not None
+ assert cached.projection["instance"]["authorization_revision"] == 4
+ if operation == "authorized_users":
+ assert cached.projection["access"]["entries"] == updated_entries
+ else:
+ assert cached.projection["projects"] == [updated_project]
+
+
def test_out_of_order_mutation_acknowledgement_keeps_the_newer_watermark_epoch(
monkeypatch,
) -> None:
diff --git a/tests/test_remote_authorization_revision.py b/tests/test_remote_authorization_revision.py
index cdfe0104d..511fa5d0a 100644
--- a/tests/test_remote_authorization_revision.py
+++ b/tests/test_remote_authorization_revision.py
@@ -878,6 +878,29 @@ def test_authorization_revision_device_contract_is_monotonic(monkeypatch, tmp_pa
assert remote_access.current_authorization_revision(config) == 42
+def test_authorization_revision_sync_rejects_an_unpersisted_watermark(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *_args, **_kwargs: {"authorization_revision": 42},
+ )
+ monkeypatch.setattr(
+ remote_access.runtime,
+ "write_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
+ )
+
+ assert remote_access.sync_authorization_revision_once(config) == {
+ "ok": False,
+ "error": "authorization_revision_sync_failed",
+ }
+ assert remote_access.current_authorization_revision(config) == 41
+
+
def test_paired_session_requires_signed_current_revision(monkeypatch, tmp_path):
"""I1057-AC4: unsigned, missing, and stale authorization versions fail closed."""
diff --git a/vibe/permissions.py b/vibe/permissions.py
index f0d4e5c3a..26c64315f 100644
--- a/vibe/permissions.py
+++ b/vibe/permissions.py
@@ -360,7 +360,7 @@ def _write_cache(instance_id: str, projection: dict[str, Any]) -> None:
prefix=f".{cache_path.name}.",
)
try:
- os.fchmod(fd, 0o600)
+ # mkstemp creates the file owner-private without relying on Unix-only APIs.
with os.fdopen(fd, "w", encoding="utf-8") as handle:
fd = -1
json.dump(envelope, handle, ensure_ascii=True, separators=(",", ":"))
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index e4bd457df..3ff6e1581 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -711,7 +711,12 @@ def current_authorization_revision(
return revision
-def _replace_authorization_revision(config: V2Config, value: Any) -> int:
+def _install_authorization_revision(
+ config: V2Config,
+ value: Any,
+ *,
+ persistence_required: bool,
+) -> int:
global _AUTHORIZATION_REVISION_CACHE
revision = _normalize_authorization_revision(value)
@@ -747,8 +752,16 @@ def _replace_authorization_revision(config: V2Config, value: Any) -> int:
"authorization_revision": revision,
"source_updated_at": source_updated_at,
}
- state_path.parent.mkdir(parents=True, exist_ok=True)
- runtime.write_json(state_path, payload)
+ try:
+ state_path.parent.mkdir(parents=True, exist_ok=True)
+ runtime.write_json(state_path, payload)
+ except OSError:
+ if persistence_required:
+ raise
+ logger.warning(
+ "Authorization revision acknowledgement could not be persisted",
+ exc_info=True,
+ )
_AUTHORIZATION_REVISION_CACHE = (
state_path,
instance_id,
@@ -768,11 +781,23 @@ def _replace_authorization_revision(config: V2Config, value: Any) -> int:
return revision
+def _replace_authorization_revision(config: V2Config, value: Any) -> int:
+ return _install_authorization_revision(
+ config,
+ value,
+ persistence_required=True,
+ )
+
+
def acknowledge_authorization_revision(config: V2Config, value: Any) -> int:
"""Record a mutation acknowledgement without regressing a newer watermark."""
try:
- return _replace_authorization_revision(config, value)
+ return _install_authorization_revision(
+ config,
+ value,
+ persistence_required=False,
+ )
except ValueError as exc:
if str(exc) != "authorization_revision_regressed":
raise