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(acl): close revocation and lifecycle gaps

Maxvint8bd312a64cd9
diff --git a/core/services/skills.py b/core/services/skills.py
index 07e8480d6..2a1b744c8 100644
--- a/core/services/skills.py
+++ b/core/services/skills.py
@@ -547,7 +547,9 @@ async def _installed_skill_resource_ids(
["list", *_list_scope_flag(scope), *_agent_flags(backends)],
cwd=_cwd_for(scope, project_dir),
)
- raw_skills = listing.get("skills") if isinstance(listing.get("skills"), list) else []
+ if not listing.get("ok") or not isinstance(listing.get("skills"), list):
+ raise SkillAccessError()
+ raw_skills = listing["skills"]
target_name = _normalize_skill_name(name)
resource_ids: list[str] = []
for skill in raw_skills:
@@ -574,6 +576,8 @@ async def _installed_skill_resource_ids(
name=str(skill["name"]),
)
)
+ if not resource_ids:
+ raise SkillAccessError()
return list(dict.fromkeys(resource_ids))
@@ -732,12 +736,11 @@ async def remove_skill(
project_dir=project_dir,
backends=backends,
)
- if resource_ids:
- _require_skill_management_access(
- resource_ids,
- user_context=context,
- allow_missing_policy=False,
- )
+ _require_skill_management_access(
+ resource_ids,
+ user_context=context,
+ allow_missing_policy=False,
+ )
args = ["remove", name, *_target_scope_flag(scope), *_agent_flags(backends)]
result = await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
if result.get("ok"):
@@ -803,11 +806,10 @@ async def update(
project_dir=project_dir,
backends=None,
)
- if resource_ids:
- _require_skill_management_access(
- resource_ids,
- user_context=context,
- allow_missing_policy=False,
- )
+ _require_skill_management_access(
+ resource_ids,
+ user_context=context,
+ allow_missing_policy=False,
+ )
args = ["update", name, *_target_scope_flag(scope), "-y"]
return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index d110351d9..5fbb36207 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -225,6 +225,26 @@ def ensure_default_agent_access(
return agent
+def ensure_session_agent_access(
+ connection,
+ session: dict[str, Any],
+ *,
+ user_context: Any = None,
+) -> VibeAgent | None:
+ """Revalidate the Agent selected by a persisted session before dispatch."""
+
+ 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,
+ )
+ if not session.get("agent_backend"):
+ return ensure_default_agent_access(connection, user_context=user_context)
+ return None
+
+
@dataclass(frozen=True)
class AgentImportCandidate:
name: str
@@ -430,6 +450,8 @@ class VibeAgentStore:
return self.update(name, enabled=enabled)
def remove(self, name: str) -> bool:
+ from storage import resource_access_service
+
agent = self.get(name)
if agent is None:
return False
@@ -438,6 +460,8 @@ class VibeAgentStore:
normalized = agent.normalized_name
with self.engine.begin() as conn:
result = conn.execute(agents.delete().where(agents.c.normalized_name == normalized))
+ if result.rowcount:
+ resource_access_service.delete_resource_policy(conn, "agent", agent.id)
return bool(result.rowcount)
def reference_counts(self, name: str) -> dict[str, int]:
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 31361cdaf..8553cafe2 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -2593,11 +2593,14 @@ def delete_secret(
cache: VaultGrantRuntimeCache = GRANT_RUNTIME_CACHE,
user_context: Any = None,
) -> None:
+ from storage import resource_access_service
+
context = resolve_resource_access_context(user_context)
row = _require_secret_resource_management(conn, _require_row(conn, name), context)
_expire_pending_requests_for_secret(conn, name, reason="request-expired-envelope-changed")
_expire_active_grants_for_secret(conn, name, cache=cache, reason="grant-expired-envelope-changed")
conn.execute(vault_secrets.delete().where(vault_secrets.c.name == name))
+ resource_access_service.delete_resource_policy(conn, "vault_secret", str(row["id"]))
if row.get("protection") == "protected":
_disable_webauthn_factors_if_vault_deestablished(conn)
audit(conn, "deleted", secret_name=name)
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index b52eeca2e..dd75433b7 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -153,6 +153,29 @@ def test_session_cookie_persists_validated_organization_claims() -> None:
) is True
+def test_session_cookie_rejects_organization_claims_that_exceed_browser_limits() -> None:
+ config = _config()
+ group_ids = [f"00000000-0000-4000-8000-{index:012d}" for index in range(100)]
+
+ with pytest.raises(remote_access.OAuthCodeExchangeError) as error:
+ remote_access.make_session_cookie(
+ config,
+ "user-1",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-1",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": group_ids,
+ },
+ )
+
+ assert error.value.reason == "session_cookie_too_large"
+
+
def test_session_claims_accept_organization_member_authorized_by_email() -> None:
config = _config()
diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.py
index 263724e2a..3c0a3aae8 100644
--- a/tests/test_resource_acl_agents.py
+++ b/tests/test_resource_acl_agents.py
@@ -1,12 +1,14 @@
from __future__ import annotations
import pytest
+from sqlalchemy import select
from core.scheduled_tasks import ScheduledTaskStore
from core.vibe_agents import AgentImportCandidate, VibeAgent, VibeAgentAccessError, VibeAgentStore
from core.watches import ManagedWatchStore
from storage import resource_access_service, workbench_sessions_service
from storage.db import get_cached_sqlite_engine
+from storage.models import resource_access_groups, resource_access_policies
from storage.settings_service import upsert_scope
from tests.test_ui_remote_access_auth import _remote_peer, _save_config
from tests.ui_server_test_helpers import csrf_headers
@@ -106,6 +108,43 @@ def test_agent_catalog_filters_private_public_scope_and_missing_group_context(mo
assert no_group_names == {"public-agent"}
+def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = VibeAgentStore()
+ try:
+ agent = store.create(name="removed-agent", backend="codex")
+ with store.engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="agent",
+ resource_id=agent.id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="scope",
+ group_ids=["group-engineering"],
+ )
+
+ assert store.remove(agent.name) is True
+ with store.engine.connect() as connection:
+ policies = connection.execute(
+ select(resource_access_policies).where(
+ resource_access_policies.c.resource_kind == "agent",
+ resource_access_policies.c.resource_id == agent.id,
+ )
+ ).all()
+ groups = connection.execute(
+ select(resource_access_groups).where(
+ resource_access_groups.c.resource_kind == "agent",
+ resource_access_groups.c.resource_id == agent.id,
+ )
+ ).all()
+ finally:
+ store.close()
+
+ assert policies == []
+ assert groups == []
+
+
def test_remote_agent_creation_defaults_to_private_organization_policy(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
@@ -228,6 +267,34 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatc
assert session["agent_name"] == public_agent.name
assert session["agent_backend"] == public_agent.backend
+ dispatch_calls = []
+
+ async def dispatch_async(payload):
+ dispatch_calls.append(payload)
+ return {"status_code": 202, "body": {}}
+
+ monkeypatch.setattr("vibe.internal_client.dispatch_async", dispatch_async)
+ with engine.begin() as connection:
+ resource_access_service.apply_control_plane_intent(
+ connection,
+ organization_id="org-1",
+ resource_kind="agent",
+ resource_id=public_agent.id,
+ revision=1,
+ access_level="private",
+ group_ids=[],
+ )
+ revoked_turn = client.post(
+ f"/api/sessions/{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 revoked_turn.status_code == 403
+ assert revoked_turn.get_json()["code"] == "agent_access_forbidden"
+ assert dispatch_calls == []
+
with pytest.raises(VibeAgentAccessError):
ScheduledTaskStore(tmp_path / "tasks.json").add_task(
session_key="avibe::project::proj_acl_agents",
diff --git a/tests/test_resource_acl_vaults.py b/tests/test_resource_acl_vaults.py
index 147cef315..a92c364dd 100644
--- a/tests/test_resource_acl_vaults.py
+++ b/tests/test_resource_acl_vaults.py
@@ -7,7 +7,14 @@ from sqlalchemy import select
from storage import resource_access_service, vault_service
from storage.db import create_sqlite_engine
-from storage.models import metadata, vault_grants, vault_requests, vault_secrets
+from storage.models import (
+ metadata,
+ resource_access_groups,
+ resource_access_policies,
+ vault_grants,
+ vault_requests,
+ vault_secrets,
+)
from storage.vault_crypto import Sealed
from vibe import remote_access
@@ -190,6 +197,34 @@ def test_remote_created_secret_registers_private_organization_policy(vault) -> N
assert policy["access_level"] == "private"
+def test_vault_secret_removal_deletes_resource_policy_and_groups(vault) -> None:
+ with vault.begin() as conn:
+ _create_secret(conn, "REMOVED_SECRET")
+ resource_id = _set_policy(
+ conn,
+ "REMOVED_SECRET",
+ access_level="scope",
+ group_ids=["group-engineering"],
+ )
+
+ vault_service.delete_secret(conn, "REMOVED_SECRET", user_context=_context("owner-1"))
+ policies = conn.execute(
+ select(resource_access_policies).where(
+ resource_access_policies.c.resource_kind == "vault_secret",
+ resource_access_policies.c.resource_id == resource_id,
+ )
+ ).all()
+ groups = conn.execute(
+ select(resource_access_groups).where(
+ resource_access_groups.c.resource_kind == "vault_secret",
+ resource_access_groups.c.resource_id == resource_id,
+ )
+ ).all()
+
+ assert policies == []
+ assert groups == []
+
+
def test_public_vault_use_does_not_grant_management(vault) -> None:
with vault.begin() as conn:
_create_secret(conn, "PUBLIC_MANAGEMENT")
diff --git a/tests/test_skills_service.py b/tests/test_skills_service.py
index b620d4c79..a7ebb74e1 100644
--- a/tests/test_skills_service.py
+++ b/tests/test_skills_service.py
@@ -405,6 +405,47 @@ def test_remove_skill_deletes_only_policies_for_removed_backends(monkeypatch, tm
assert claude_policy is not None
[email protected]("operation", ["remove", "update"])
+ "listing",
+ [
+ {"ok": False, "error": {"code": "list_failed"}},
+ {"ok": True, "skills": []},
+ {"ok": True, "skills": "invalid"},
+ ],
+)
+def test_remote_skill_mutations_fail_closed_when_preflight_cannot_resolve_target(
+ monkeypatch,
+ tmp_path,
+ operation: str,
+ listing: dict,
+) -> None:
+ engine = _skills_engine(monkeypatch, tmp_path)
+ recorder = _SequenceRecorder([listing])
+ monkeypatch.setattr(skills, "_run_askill", recorder)
+ try:
+ if operation == "remove":
+ mutation = skills.remove_skill(
+ "askill",
+ "missing-skill",
+ scope="global",
+ user_context=_organization_context("owner-1"),
+ )
+ else:
+ mutation = skills.update(
+ "askill",
+ "missing-skill",
+ scope="global",
+ user_context=_organization_context("owner-1"),
+ )
+ with pytest.raises(skills.SkillAccessError):
+ _run(mutation)
+ finally:
+ engine.dispose()
+
+ assert [call["args"] for call in recorder.calls] == [["list", "-g"]]
+
+
def test_remote_skill_add_registers_private_policy(monkeypatch, tmp_path) -> None:
engine = _skills_engine(monkeypatch, tmp_path)
try:
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index b834b8bc0..4bf4afd2d 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -1174,6 +1174,52 @@ def test_remote_callback_rejects_nonce_mismatch(monkeypatch, tmp_path):
assert 'href="/dashboard"' in response.text
+def test_remote_callback_rejects_oversized_session_cookie_without_redirect_loop(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+
+ with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):
+ redirect = ui_server._redirect_to_vibe_cloud_login(config)
+ oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]
+ client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")
+ oauth_state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)
+ group_ids = [f"00000000-0000-4000-8000-{index:012d}" for index in range(100)]
+
+ monkeypatch.setattr(
+ remote_access,
+ "exchange_oauth_code",
+ lambda cfg, code, verifier: {
+ "claims": {
+ "email": "[email protected]",
+ "sub": "user-1",
+ "nonce": oauth_state["nonce"],
+ },
+ "session_claims": {
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-1",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": group_ids,
+ },
+ },
+ )
+
+ response = client.get(
+ f"/auth/callback?code=test-code&state={oauth_state['state']}",
+ base_url="https://alex.avibe.bot",
+ )
+
+ assert response.status_code == 400
+ assert "reason: session_cookie_too_large" in response.text
+ assert not any(
+ header.startswith(f"{remote_access.SESSION_COOKIE_NAME}=")
+ for header in response.headers.getlist("Set-Cookie")
+ )
+
+
def test_remote_callback_explains_pairing_mismatch(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index a3068d2f7..857ea1c1d 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -46,6 +46,9 @@ CLOUDFLARED_BASE_URL = "https://github.com/cloudflare/cloudflared/releases/lates
SESSION_COOKIE_NAME = "__Host-vibe_remote_session"
SESSION_TTL_SECONDS = 24 * 60 * 60
SESSION_AUTHORIZATION_REFRESH_SECONDS = SESSION_TTL_SECONDS // 2
+# Keep enough headroom for the cookie name and attributes under the common
+# 4096-byte per-cookie browser limit.
+SESSION_COOKIE_MAX_VALUE_BYTES = 3800
OAUTH_ID_TOKEN_CLOCK_LEEWAY_SECONDS = 30
_CONNECTOR_LOCK = threading.RLock()
_STATUS_HEARTBEAT_LOCK = threading.Lock()
@@ -2487,12 +2490,17 @@ def make_session_cookie(
payload["claims_issued_at"] = issued_at
payload_text = urllib.parse.quote(json.dumps(payload, separators=(",", ":")), safe="")
signature = _session_signature(cloud.session_secret, payload_text)
- return f"{payload_text}.{signature}"
+ cookie_value = f"{payload_text}.{signature}"
+ if len(cookie_value.encode("ascii")) > SESSION_COOKIE_MAX_VALUE_BYTES:
+ raise OAuthCodeExchangeError("session_cookie_too_large")
+ return cookie_value
def parse_session_cookie(config: V2Config, cookie_value: str | None) -> dict[str, Any] | None:
if not cookie_value or "." not in cookie_value:
return None
+ if len(cookie_value.encode("utf-8")) > SESSION_COOKIE_MAX_VALUE_BYTES:
+ return None
cloud = config.remote_access.vibe_cloud
if not cloud.session_secret:
return None
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 6cf4841bf..e22c7e782 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4700,16 +4700,23 @@ def remote_access_auth_callback():
return _oauth_callback_error_response(error, next_target=next_target, diagnostics=diagnostics)
if claims.get("nonce") != handshake_nonce:
return _oauth_callback_error_response("invalid_oauth_nonce", next_target=next_target)
- response = Response(status=302)
- response.headers["Location"] = _safe_remote_redirect_target(next_target)
- response.set_cookie(
- remote_access.SESSION_COOKIE_NAME,
- remote_access.make_session_cookie(
+ try:
+ session_cookie = remote_access.make_session_cookie(
config,
str(claims.get("email", "")),
str(claims.get("sub", "")),
session_claims=session_claims,
- ),
+ )
+ except Exception as exc:
+ reason = exc.reason if isinstance(exc, remote_access.OAuthCodeExchangeError) else exc.__class__.__name__
+ _log_oauth_diag("exchange_failed", "vibe cloud session cookie creation failed: reason=%s", reason)
+ error, diagnostics = _oauth_exchange_error_diagnostics(exc)
+ return _oauth_callback_error_response(error, next_target=next_target, diagnostics=diagnostics)
+ response = Response(status=302)
+ response.headers["Location"] = _safe_remote_redirect_target(next_target)
+ response.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ session_cookie,
httponly=True,
secure=True,
samesite="Lax",
@@ -7866,6 +7873,9 @@ async def sessions_messages_create(session_id: str):
try:
with engine.connect() as conn:
session = workbench_sessions_service.get_session(conn, session_id)
+ from core.vibe_agents import ensure_session_agent_access
+
+ ensure_session_agent_access(conn, session)
# Archived sessions are terminal + inert: refuse to start a turn on one
# even via a stale/direct request (the workbench hides them from the
# list, so this only fires on a leftover tab or a hand-crafted call).
@@ -7881,6 +7891,8 @@ async def sessions_messages_create(session_id: str):
return jsonify({"already_answered": True}), 200
except LookupError as err:
return jsonify({"error": str(err)}), 404
+ except PermissionError as err:
+ return jsonify({"error": str(err), "code": "agent_access_forbidden"}), 403
dispatch_text = (
(text if isinstance(text, str) else None)