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(auth): redact Viewer host paths (#1400)

Call Whitefc0daa883ab3
diff --git a/core/services/skills.py b/core/services/skills.py
index 97ab65a52..6b5243b45 100644
--- a/core/services/skills.py
+++ b/core/services/skills.py
@@ -378,10 +378,11 @@ def _filter_skill_listing(
if not result.get("ok") or not isinstance(result.get("skills"), list):
return result
context = resolve_resource_access_context(user_context)
- if context.has_role("editor"):
+ if _project_role_allows_editor(context, project_id):
return result
raw_skills = [dict(skill) for skill in result["skills"] if isinstance(skill, dict)]
+ instance_editor = context.has_role("editor")
descriptors = _skill_resource_descriptors(
raw_skills,
requested_scope=scope,
@@ -406,6 +407,9 @@ def _filter_skill_listing(
allowed = {(item["skill_index"], item["agent_index"]) for item in accessible}
filtered_skills = []
for skill_index, skill in enumerate(raw_skills):
+ if instance_editor and _skill_scope(skill, scope) == "global":
+ filtered_skills.append(skill)
+ continue
matching = [item for item in descriptors if item["skill_index"] == skill_index]
if not matching or not any((item["skill_index"], item["agent_index"]) in allowed for item in matching):
continue
@@ -461,6 +465,35 @@ def _remote_safe_skill_payload(skill: dict[str, Any]) -> dict[str, Any]:
return projected
+def _project_role_allows_editor(user_context: Any, project_id: Optional[str]) -> bool:
+ """Return whether the caller has effective Editor access to a project."""
+
+ context = resolve_resource_access_context(user_context)
+ if context.is_instance_owner:
+ return True
+ if not project_id:
+ return context.has_role("editor")
+
+ from storage import project_access_service
+ from storage.db import get_cached_sqlite_engine
+
+ engine = get_cached_sqlite_engine()
+ with engine.connect() as connection:
+ role = project_access_service.get_effective_project_role(
+ connection,
+ context,
+ str(project_id),
+ )
+ return project_access_service.role_allows(role, "editor")
+
+
+def require_project_editor_access(user_context: Any, project_id: Optional[str]) -> None:
+ """Require effective project Editor access for a project-scoped mutation."""
+
+ if project_id and not _project_role_allows_editor(user_context, project_id):
+ raise SkillAccessError()
+
+
def _resource_ids_for_skill_name(
name: str,
*,
@@ -785,7 +818,11 @@ async def preview_source(
"""
if not source:
raise SkillsError("missing_source", "no source provided")
- _require_skill_create_access(resolve_resource_access_context(user_context))
+ context = resolve_resource_access_context(user_context)
+ if project_dir and project_id:
+ require_project_editor_access(context, project_id)
+ else:
+ _require_skill_create_access(context)
return await _run_askill(askill_path, ["add", source, "--list"], cwd=project_dir)
@@ -814,6 +851,8 @@ async def add_skill(
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "install scope must be global or project")
context = resolve_resource_access_context(user_context)
+ if scope == "project":
+ require_project_editor_access(context, project_id)
if not (
context.is_instance_owner
or context.has_role("editor")
@@ -921,6 +960,8 @@ async def remove_skill(
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "remove scope must be global or project")
context = resolve_resource_access_context(user_context)
+ if scope == "project":
+ require_project_editor_access(context, project_id)
if not (
context.is_instance_owner
or context.has_role("editor")
@@ -999,11 +1040,7 @@ async def check(
backends=list(BACKEND_TO_AGENT),
user_context=context,
)
- if (
- context.is_instance_owner
- or context.has_role("editor")
- or not isinstance(filtered.get("summary"), dict)
- ):
+ if _project_role_allows_editor(context, project_id) or not isinstance(filtered.get("summary"), dict):
return filtered
skills = filtered.get("skills") if isinstance(filtered.get("skills"), list) else []
statuses = [str(skill.get("status") or "") for skill in skills if isinstance(skill, dict)]
@@ -1031,6 +1068,8 @@ async def update(
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "update scope must be global or project")
context = resolve_resource_access_context(user_context)
+ if scope == "project":
+ require_project_editor_access(context, project_id)
if not (
context.is_instance_owner
or context.has_role("editor")
diff --git a/storage/project_access_service.py b/storage/project_access_service.py
index 5fb97d216..de536b282 100644
--- a/storage/project_access_service.py
+++ b/storage/project_access_service.py
@@ -361,15 +361,29 @@ def get_effective_session_role(
context: AuthorizationContext,
session_id: str,
) -> str | None:
- scope_id = conn.execute(
- select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id).limit(1)
- ).scalar_one_or_none()
- project_id = project_id_from_scope_id(scope_id)
+ project_id = get_session_project_id(conn, session_id)
if project_id is None:
return "owner" if context.is_instance_owner else None
return get_effective_project_role(conn, context, project_id)
+def get_session_project_id(conn: Connection, session_id: str) -> str | None:
+ """Return a session's owning project id without applying caller access."""
+
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id).limit(1)
+ ).scalar_one_or_none()
+ return project_id_from_scope_id(scope_id)
+
+
+def session_exists(conn: Connection, session_id: str) -> bool:
+ """Return whether the session row still exists."""
+
+ return conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.id == session_id).limit(1)
+ ).scalar_one_or_none() is not None
+
+
def accessible_project_ids(
conn: Connection,
context: AuthorizationContext,
diff --git a/storage/projects_service.py b/storage/projects_service.py
index 3c875e089..0dc885925 100644
--- a/storage/projects_service.py
+++ b/storage/projects_service.py
@@ -206,13 +206,20 @@ def _project_for_context(
"""Return the Project fields and capabilities safe for this caller."""
payload = dict(project)
+ project_id = str(project.get("id") or "")
+ effective_role = project_access_service.get_effective_project_role(
+ conn,
+ context,
+ project_id,
+ )
payload["capabilities"] = {
- "can_chat": project_access_service.can_chat_project(
- conn,
- context,
- str(project.get("id") or ""),
- )
+ "can_chat": project_access_service.role_allows(effective_role, "editor"),
+ "has_folder": bool(payload.get("folder_path")),
}
+ if not project_access_service.role_allows(effective_role, "editor"):
+ # Effective Viewers must not disclose host-local filesystem details.
+ payload["folder_path"] = ""
+ payload["metadata"] = {}
return payload
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index b24c878ca..9f0eebdf0 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -245,8 +245,12 @@ def test_remote_show_page_access_does_not_bypass_acl(
expected = {"ses-private", "ses-public", "ses-scope"} if instance_role == "owner" else {
"ses-public", "ses-scope"
}
- assert {item["session_id"] for item in catalog.get_json()["pages"]} == expected
- assert all(item.get("path") for item in catalog.get_json()["pages"])
+ pages = catalog.get_json()["pages"]
+ assert {item["session_id"] for item in pages} == expected
+ if instance_role == "owner":
+ assert all(item.get("path") for item in pages)
+ else:
+ assert all("path" not in item for item in pages)
assert mutation.status_code == (200 if instance_role == "owner" else 403)
assert page.status_code == (200 if instance_role == "owner" else 302)
diff --git a/tests/test_skills_service.py b/tests/test_skills_service.py
index 8299c2942..c230a1da4 100644
--- a/tests/test_skills_service.py
+++ b/tests/test_skills_service.py
@@ -470,6 +470,112 @@ def test_active_org_members_list_project_skills_without_project_acl(monkeypatch,
engine.dispose()
+def test_effective_project_viewer_gets_safe_skill_payload_and_cannot_mutate(monkeypatch, tmp_path) -> None:
+ engine = _skills_engine(monkeypatch, tmp_path)
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ listing = {
+ "ok": True,
+ "summary": {"total": 3, "updateAvailable": 2, "upToDate": 1, "uncheckable": 0},
+ "skills": [
+ {
+ **_skill_row("global-skill"),
+ "path": "/global/skills/global-skill",
+ },
+ {
+ **_skill_row("project-skill"),
+ "scope": "project",
+ "path": str(project_dir / ".agents" / "skills" / "project-skill"),
+ "status": "update_available",
+ }
+ ],
+ }
+ try:
+ with engine.begin() as connection:
+ project = projects_service.create_project(connection, str(project_dir))
+ result = project_access_service.apply_project_access_intent(
+ connection,
+ {
+ "project_id": project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "organization_id": "org-1",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "viewer",
+ }
+ ],
+ },
+ )
+ assert result.outcome == "applied"
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="skill",
+ resource_id=skills.skill_resource_id(
+ "codex",
+ scope="project",
+ project_dir=str(project_dir),
+ project_id=project["id"],
+ name="project-skill",
+ ),
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
+
+ recorder = _Recorder(listing)
+ monkeypatch.setattr(skills, "_run_askill", recorder)
+ viewer = _organization_context("member-1")
+ safe = _run(
+ skills.list_skills(
+ "askill",
+ scope="project",
+ project_dir=str(project_dir),
+ project_id=project["id"],
+ user_context=viewer,
+ )
+ )
+ assert safe["skills"][0]["path"] == "/global/skills/global-skill"
+ assert safe["skills"][1]["path"] == ""
+ checked = _run(
+ skills.check(
+ "askill",
+ scope="project",
+ project_dir=str(project_dir),
+ project_id=project["id"],
+ user_context=viewer,
+ )
+ )
+ assert checked["summary"] == {"total": 2, "updateAvailable": 1, "upToDate": 0, "uncheckable": 0}
+
+ with pytest.raises(skills.SkillAccessError):
+ _run(
+ skills.add_skill(
+ "askill",
+ "gh:owner/repo",
+ scope="project",
+ project_dir=str(project_dir),
+ project_id=project["id"],
+ user_context=viewer,
+ )
+ )
+ with pytest.raises(skills.SkillAccessError):
+ _run(
+ skills.preview_source(
+ "askill",
+ ".",
+ project_dir=str(project_dir),
+ project_id=project["id"],
+ user_context=viewer,
+ )
+ )
+ assert len(recorder.calls) == 2
+ finally:
+ engine.dispose()
+
+
def test_active_org_skill_listing_returns_complete_runtime_payload(monkeypatch, tmp_path) -> None:
engine = _skills_engine(monkeypatch, tmp_path)
raw_skill = {
@@ -805,7 +911,7 @@ def test_active_org_editor_can_upload_skill_zip(monkeypatch, tmp_path) -> None:
with zipfile.ZipFile(archive_bytes, "w") as archive:
archive.writestr("uploaded-skill/SKILL.md", "# Uploaded Skill\n")
- async def preview_uploaded_skill(_callback):
+ async def preview_uploaded_skill(_callback, **_kwargs):
return {"ok": True, "skills": [{"name": "uploaded-skill"}]}
monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
@@ -833,7 +939,7 @@ def test_viewer_cannot_upload_skill_zip(monkeypatch) -> None:
from vibe import api
from vibe.authorization import InstanceAuthorizationError
- async def unexpected_preview(_callback):
+ async def unexpected_preview(_callback, **_kwargs):
raise AssertionError("viewer upload must fail before inspecting the archive")
monkeypatch.setattr(api, "_skills_guarded", unexpected_preview)
@@ -888,3 +994,11 @@ def test_subprocess_env_prepends_binary_dir(monkeypatch):
def test_missing_binary_raises_lookup():
with pytest.raises(LookupError):
_run(skills._run_askill("", ["list"]))
+
+
+def test_missing_project_dir_error_preserves_host_path_for_authorized_service_call(tmp_path):
+ missing = tmp_path / "deleted-project"
+ with pytest.raises(skills.SkillsError) as info:
+ _run(skills._run_askill("askill", ["list"], cwd=str(missing)))
+ assert info.value.code == "project_dir_missing"
+ assert str(missing) in info.value.message
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index d6beac08d..3436663a4 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -226,7 +226,7 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
project_a = next(row for row in project_rows if row["id"] == ids["project_a"])
assert project_a["folder_path"] == str((tmp_path / "project-a").resolve())
assert project_a["metadata"] == {"host_path_hint": "/private/host"}
- assert project_a["capabilities"] == {"can_chat": True}
+ assert project_a["capabilities"] == {"can_chat": True, "has_folder": True}
sessions = _get(client, "/api/sessions?status=active").get_json()["sessions"]
assert {row["id"] for row in sessions} == {
ids["session_a"],
@@ -345,7 +345,9 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
client = _remote_client(config, role="editor", email="[email protected]")
viewer_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()
- assert viewer_project["capabilities"] == {"can_chat": False}
+ assert viewer_project["capabilities"] == {"can_chat": False, "has_folder": True}
+ assert viewer_project["folder_path"] == ""
+ assert viewer_project["metadata"] == {}
viewer_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")
@@ -413,7 +415,7 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
with engine.connect() as conn:
assert message_deliveries.get_draft(conn, ids["session_a"])["text"] == "remote overwrite"
editor_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()
- assert editor_project["capabilities"] == {"can_chat": True}
+ assert editor_project["capabilities"] == {"can_chat": True, "has_folder": True}
def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path) -> None:
@@ -624,6 +626,13 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
engine.dispose()
viewer = _remote_client(config, role="viewer", email="[email protected]")
+ viewer_projects = _get(viewer, "/api/projects").get_json()["projects"]
+ viewer_project = next(row for row in viewer_projects if row["id"] == ids["project_a"])
+ assert viewer_project["folder_path"] == ""
+ assert viewer_project["metadata"] == {}
+ viewer_project_detail = _get(viewer, f"/api/projects/{ids['project_a']}").get_json()
+ assert viewer_project_detail["folder_path"] == ""
+ assert viewer_project_detail["metadata"] == {}
assert _get(viewer, f"/api/sessions/{ids['session_a']}").status_code == 200
assert _get(viewer, f"/api/sessions/{ids['session_b']}").status_code == 404
headers = csrf_headers(viewer, REMOTE_ORIGIN)
@@ -736,6 +745,264 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
assert local.get(f"/api/sessions/{ids['unscoped']}", base_url="http://localhost").status_code == 200
+def test_show_page_payload_redacts_path_for_viewers(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ **_intent(ids["project_a"], "[email protected]", role="viewer"),
+ "revision": 2,
+ },
+ )
+ monkeypatch.setattr(
+ api,
+ "list_show_pages",
+ lambda **_kwargs: {
+ "ok": True,
+ "count": 1,
+ "pages": [{"session_id": ids["session_a"], "path": "/private/show-page"}],
+ },
+ )
+
+ viewer = _remote_client(config, role="viewer", email="[email protected]")
+ viewer_page = _get(viewer, "/api/show-pages").get_json()["pages"][0]
+ assert "path" not in viewer_page
+
+ editor = _remote_client(config, role="editor", email="[email protected]")
+ editor_page = _get(editor, "/api/show-pages").get_json()["pages"][0]
+ assert "path" not in editor_page
+
+ owner = _remote_client(config, role="owner", email="[email protected]")
+ owner_page = _get(owner, "/api/show-pages").get_json()["pages"][0]
+ assert owner_page["path"] == "/private/show-page"
+
+
+def test_show_page_mutation_payload_redacts_direct_and_nested_pages(monkeypatch) -> None:
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="user-editor",
+ is_remote=True,
+ )
+
+ class _Connection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ class _Engine:
+ def connect(self):
+ return _Connection()
+
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: _Engine())
+ monkeypatch.setattr(
+ project_access_service,
+ "get_effective_session_role",
+ lambda _conn, _context, _session_id: "viewer",
+ )
+ monkeypatch.setattr(
+ project_access_service,
+ "get_session_project_id",
+ lambda _conn, _session_id: "project-1",
+ )
+ monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: True)
+ monkeypatch.setattr(
+ resource_access_service,
+ "can_manage_resource_acl",
+ lambda _context, _kind, _resource_id, *, connection: False,
+ )
+
+ direct = ui_server._show_page_response_for_request(
+ {"ok": True, "session_id": "session-a", "path": "/private/page"},
+ context,
+ )
+ nested = ui_server._show_page_response_for_request(
+ {
+ "ok": True,
+ "page": {"session_id": "session-a", "path": "/private/page"},
+ },
+ context,
+ )
+
+ assert "path" not in direct
+ assert "path" not in nested["page"]
+
+
+def test_show_page_payload_preserves_path_for_non_project_page_owner(monkeypatch) -> None:
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="user-editor",
+ is_remote=True,
+ )
+
+ class _Connection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ class _Engine:
+ def connect(self):
+ return _Connection()
+
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: _Engine())
+ monkeypatch.setattr(
+ project_access_service,
+ "get_effective_session_role",
+ lambda _conn, _context, _session_id: None,
+ )
+ monkeypatch.setattr(
+ project_access_service,
+ "get_session_project_id",
+ lambda _conn, _session_id: None,
+ )
+ monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: True)
+ monkeypatch.setattr(
+ resource_access_service,
+ "can_manage_resource_acl",
+ lambda _context, _kind, _resource_id, *, connection: True,
+ )
+
+ payload = ui_server._show_page_response_for_request(
+ {"ok": True, "session_id": "im-session", "path": "/private/page"},
+ context,
+ )
+
+ assert payload["path"] == "/private/page"
+
+
+def test_show_page_payload_does_not_bypass_project_viewer_with_resource_manager(monkeypatch) -> None:
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="user-editor",
+ is_remote=True,
+ )
+
+ class _Connection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ class _Engine:
+ def connect(self):
+ return _Connection()
+
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: _Engine())
+ monkeypatch.setattr(
+ project_access_service,
+ "get_effective_session_role",
+ lambda _conn, _context, _session_id: "viewer",
+ )
+ monkeypatch.setattr(
+ project_access_service,
+ "get_session_project_id",
+ lambda _conn, _session_id: "project-1",
+ )
+ monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: True)
+ monkeypatch.setattr(
+ resource_access_service,
+ "can_manage_resource_acl",
+ lambda _context, _kind, _resource_id, *, connection: True,
+ )
+
+ payload = ui_server._show_page_response_for_request(
+ {"ok": True, "session_id": "project-session", "path": "/private/page"},
+ context,
+ )
+
+ assert "path" not in payload
+
+
+def test_show_page_payload_does_not_treat_inaccessible_project_as_unscoped(monkeypatch) -> None:
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="user-editor",
+ is_remote=True,
+ )
+
+ class _Connection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ class _Engine:
+ def connect(self):
+ return _Connection()
+
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: _Engine())
+ monkeypatch.setattr(
+ project_access_service,
+ "get_effective_session_role",
+ lambda _conn, _context, _session_id: None,
+ )
+ monkeypatch.setattr(
+ project_access_service,
+ "get_session_project_id",
+ lambda _conn, _session_id: "project-removed-binding",
+ )
+ monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: True)
+ monkeypatch.setattr(
+ resource_access_service,
+ "can_manage_resource_acl",
+ lambda _context, _kind, _resource_id, *, connection: True,
+ )
+
+ payload = ui_server._show_page_response_for_request(
+ {"ok": True, "session_id": "project-session", "path": "/private/page"},
+ context,
+ )
+
+ assert "path" not in payload
+
+
+def test_show_page_payload_redacts_path_when_session_is_missing(monkeypatch) -> None:
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="user-editor",
+ is_remote=True,
+ )
+
+ class _Connection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ class _Engine:
+ def connect(self):
+ return _Connection()
+
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: _Engine())
+ monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: False)
+ monkeypatch.setattr(
+ resource_access_service,
+ "can_manage_resource_acl",
+ lambda _context, _kind, _resource_id, *, connection: True,
+ )
+
+ payload = ui_server._show_page_response_for_request(
+ {"ok": True, "session_id": "deleted-session", "path": "/private/page"},
+ context,
+ )
+
+ assert "path" not in payload
+
+
def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
diff --git a/tests/test_ui_server_skills_routes.py b/tests/test_ui_server_skills_routes.py
index df57c09ce..bd0813a11 100644
--- a/tests/test_ui_server_skills_routes.py
+++ b/tests/test_ui_server_skills_routes.py
@@ -10,6 +10,8 @@ project-scoped mutations return a clear ``project_no_folder`` error.
from __future__ import annotations
+import asyncio
+
import pytest
from vibe import api, ui_server
@@ -35,6 +37,76 @@ def _boom(*_args, **_kwargs):
raise AssertionError("askill must not be reached for a folderless project")
+def test_skills_guarded_redacts_missing_project_path(monkeypatch, tmp_path):
+ from core.services import skills as skills_service
+ from storage import project_access_service
+ from vibe.authorization import AuthorizationContext
+
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _name: "askill")
+
+ async def fail(_askill, _service):
+ raise skills_service.SkillsError(
+ "project_dir_missing",
+ f"project folder not found: {tmp_path / 'deleted-project'}",
+ )
+
+ class _Engine:
+ class _Connection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ def connect(self):
+ return self._Connection()
+
+ monkeypatch.setattr("storage.db.get_cached_sqlite_engine", lambda: _Engine())
+ monkeypatch.setattr(project_access_service, "get_effective_project_role", lambda *_args: "viewer")
+ context = AuthorizationContext(instance_role="editor", subject="viewer", is_remote=True)
+ result = asyncio.run(
+ api._skills_guarded(fail, user_context=context, project_id="proj-viewer")
+ )
+
+ assert result["error"]["code"] == "project_dir_missing"
+ assert result["error"]["message"] == "The configured project folder is unavailable."
+ assert str(tmp_path) not in result["error"]["message"]
+
+
+def test_skills_guarded_preserves_missing_project_path_for_effective_editor(monkeypatch, tmp_path):
+ from core.services import skills as skills_service
+ from storage import project_access_service
+ from vibe.authorization import AuthorizationContext
+
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _name: "askill")
+
+ async def fail(_askill, _service):
+ raise skills_service.SkillsError(
+ "project_dir_missing",
+ f"project folder not found: {tmp_path / 'deleted-project'}",
+ )
+
+ class _Engine:
+ class _Connection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ def connect(self):
+ return self._Connection()
+
+ monkeypatch.setattr("storage.db.get_cached_sqlite_engine", lambda: _Engine())
+ monkeypatch.setattr(project_access_service, "get_effective_project_role", lambda *_args: "editor")
+ context = AuthorizationContext(instance_role="editor", subject="editor", is_remote=True)
+ result = asyncio.run(
+ api._skills_guarded(fail, user_context=context, project_id="proj-editor")
+ )
+
+ assert str(tmp_path) in result["error"]["message"]
+
+
def test_list_degrades_to_global_with_flag(folderless, monkeypatch):
async def fake_list(*, scope, project_dir=None, backends=None, user_context=None):
assert scope == "global"
@@ -70,13 +142,13 @@ def test_resolve_project_dir_uses_request_authorization_context(monkeypatch):
def connect(self):
return self._Connection()
- def fake_get_project(conn, project_id, *, authorization_context=None):
+ def fake_get_project_workdir(conn, project_id, *, authorization_context=None):
seen["project_id"] = project_id
seen["authorization_context"] = authorization_context
- return {"folder_path": "/tmp/project"}
+ return "/tmp/project"
monkeypatch.setattr(ui_server, "_projects_engine", lambda: _Engine())
- monkeypatch.setattr("storage.projects_service.get_project", fake_get_project)
+ monkeypatch.setattr("storage.projects_service.get_project_workdir", fake_get_project_workdir)
remote_context = AuthorizationContext(instance_role="editor", is_remote=True, subject="user-1")
with app.test_request_context("/api/skills?project_id=proj-restricted"):
@@ -193,6 +265,31 @@ def test_upload_preserves_project_id_for_real_project(monkeypatch):
}
+def test_project_viewer_cannot_reach_skill_mutations(monkeypatch):
+ denied = ui_server._coded_error_response(
+ "resource_access_forbidden",
+ "Skill access is not permitted.",
+ 403,
+ )
+ monkeypatch.setattr(
+ ui_server,
+ "_require_project_editor_for_skill_mutation",
+ lambda project_id, **_kwargs: denied if project_id == "proj-viewer" else None,
+ )
+ monkeypatch.setattr(ui_server, "_resolve_project_dir", lambda _project_id: "/tmp/project")
+ monkeypatch.setattr(api, "add_skill", _boom)
+
+ client = app.test_client()
+ response = client.post(
+ "/api/skills",
+ json={"project_id": "proj-viewer", "source": "gh:owner/repo"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["error"]["code"] == "resource_access_forbidden"
+
+
@pytest.mark.parametrize(
"method,path,attr,payload",
[
diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsx
index bcbe47c7c..8bd35991e 100644
--- a/ui/src/components/workbench/SkillsPage.tsx
+++ b/ui/src/components/workbench/SkillsPage.tsx
@@ -52,8 +52,9 @@ export const SkillsPage: React.FC = () => {
// A folderless project can't hold project-scoped skills (askill needs a real
// cwd), so the add/browse flows treat it as global-only: the add dialog drops
// the project-scope option, and browse installs land in global.
- const projectHasFolder = Boolean(activeProject?.folder_path);
- const addDialogProjectId = projectHasFolder ? activeProject?.id : undefined;
+ const projectHasFolder = Boolean(activeProject?.capabilities?.has_folder ?? activeProject?.folder_path);
+ const projectCanManage = canManage && (scope !== 'project' || Boolean(activeProject?.capabilities?.can_chat));
+ const addDialogProjectId = scope === 'project' && projectCanManage && projectHasFolder ? activeProject?.id : undefined;
const browseScope: SkillScope = scope === 'project' && projectHasFolder ? 'project' : 'global';
const browseProjectId = browseScope === 'project' ? activeProject?.id : undefined;
@@ -285,7 +286,7 @@ export const SkillsPage: React.FC = () => {
<BackendFilter value={backendFilter} onChange={setBackendFilter} />
- {canManage ? (
+ {projectCanManage ? (
<>
<Button type="button" variant="outline" size="xs" onClick={() => setShowBrowse(true)}>
<Compass className="size-3.5 text-cyan" />
@@ -322,7 +323,7 @@ export const SkillsPage: React.FC = () => {
<Terminal className="size-7 text-muted" />
<div className="text-[14px] font-semibold text-foreground">{t('skills.notInstalled')}</div>
<div className="max-w-md font-mono text-[11.5px] text-muted">{t('skills.notInstalledHint')}</div>
- {canManage ? <Button
+ {projectCanManage ? <Button
variant="brand"
size="sm"
className="mt-1"
@@ -409,13 +410,13 @@ export const SkillsPage: React.FC = () => {
onToggleBackend={onToggleBackend}
onUpdate={onUpdate}
onRemove={onRemove}
- canManage={canManage}
+ canManage={canManage && (selected.scope !== 'project' || Boolean(activeProject?.capabilities?.can_chat))}
/>
) : null}
</div>
)}
- {canManage && showAdd ? (
+ {projectCanManage && showAdd ? (
<AddSkillDialog
defaultScope={scope}
projectId={addDialogProjectId}
@@ -424,7 +425,7 @@ export const SkillsPage: React.FC = () => {
onInstalled={afterDialog}
/>
) : null}
- {canManage && showBrowse ? (
+ {projectCanManage && showBrowse ? (
<BrowseRegistryDialog
scope={browseScope}
projectId={browseProjectId}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 7219c6c3f..685d5da99 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -897,6 +897,7 @@ export type WorkbenchProject = {
metadata?: Record<string, unknown>;
capabilities: {
can_chat: boolean;
+ has_folder: boolean;
};
};
diff --git a/vibe/api.py b/vibe/api.py
index 866f672e5..846735d62 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -12196,7 +12196,21 @@ def _stop_temp_ws_internal():
# service so core/ never imports vibe/. See docs/plans/workbench-skills-page.md.
-async def _skills_guarded(call):
+def _skills_error_message(exc, context, project_id):
+ if exc.code != "project_dir_missing" or not project_id or context is None:
+ return exc.message
+ from storage import project_access_service
+ from storage.db import get_cached_sqlite_engine
+
+ engine = get_cached_sqlite_engine()
+ with engine.connect() as connection:
+ role = project_access_service.get_effective_project_role(connection, context, project_id)
+ if project_access_service.role_allows(role, "editor"):
+ return exc.message
+ return "The configured project folder is unavailable."
+
+
+async def _skills_guarded(call, *, user_context=None, project_id=None):
askill = resolve_cli_path("askill")
if not askill:
return {"ok": False, "error": {"code": "askill_not_found", "message": "askill CLI not found on PATH"}}
@@ -12205,7 +12219,8 @@ async def _skills_guarded(call):
try:
return await call(askill, skills_service)
except skills_service.SkillsError as exc:
- return {"ok": False, "error": {"code": exc.code, "message": exc.message, "details": exc.details}}
+ message = _skills_error_message(exc, user_context, project_id)
+ return {"ok": False, "error": {"code": exc.code, "message": message, "details": exc.details}}
except LookupError:
return {"ok": False, "error": {"code": "askill_not_found", "message": "askill CLI not found on PATH"}}
@@ -12227,7 +12242,9 @@ async def list_skills(
project_id=project_id,
backends=backends,
user_context=context,
- )
+ ),
+ user_context=context,
+ project_id=project_id,
)
@@ -12246,7 +12263,9 @@ async def preview_skill_source(
project_dir=project_dir,
project_id=project_id,
user_context=context,
- )
+ ),
+ user_context=context,
+ project_id=project_id,
)
@@ -12275,7 +12294,9 @@ async def add_skill(
skill=skill,
copy=copy,
user_context=context,
- )
+ ),
+ user_context=context,
+ project_id=project_id,
)
@@ -12298,7 +12319,9 @@ async def remove_skill(
project_id=project_id,
backends=backends,
user_context=context,
- )
+ ),
+ user_context=context,
+ project_id=project_id,
)
@@ -12324,7 +12347,9 @@ async def check_skills(
project_dir=project_dir,
project_id=project_id,
user_context=context,
- )
+ ),
+ user_context=context,
+ project_id=project_id,
)
@@ -12345,7 +12370,9 @@ async def update_skill(
project_dir=project_dir,
project_id=project_id,
user_context=context,
- )
+ ),
+ user_context=context,
+ project_id=project_id,
)
@@ -12371,9 +12398,16 @@ async def upload_skill_zip(
import zipfile
from vibe.authorization import require_instance_role
+ from core.services import skills as skills_service
context = resolve_resource_access_context() if user_context is None else user_context
- require_instance_role(context, "editor")
+ try:
+ if project_id:
+ skills_service.require_project_editor_access(context, project_id)
+ else:
+ require_instance_role(context, "editor")
+ except skills_service.SkillsError as exc:
+ return {"ok": False, "error": {"code": exc.code, "message": exc.message}}
max_b64 = 24 * 1024 * 1024 # ~18 MB archive — skills are tiny; cap the body.
max_uncompressed = 64 * 1024 * 1024
@@ -12442,7 +12476,9 @@ async def upload_skill_zip(
project_dir=project_dir,
project_id=project_id,
user_context=context,
- )
+ ),
+ user_context=context,
+ project_id=project_id,
)
if preview.get("ok"):
preview["dir"] = unpack
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 98ea32636..5ae5e055e 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5052,8 +5052,70 @@ def _is_remote_show_page_request() -> bool:
)
-def _show_page_payload_for_request(payload: dict) -> dict:
- return payload
+def _show_page_payload_for_request(payload: dict, context: Any = None) -> dict:
+ context = _request_authorization_context(context)
+ if context is None or _has_runtime_owner_access(context):
+ return payload
+ from storage import project_access_service
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ return _show_page_payload_for_connection(payload, context, conn)
+
+
+def _show_page_payload_for_connection(payload: dict, context: Any, conn: Any) -> dict:
+ from storage import project_access_service
+ from storage import resource_access_service
+
+ session_id = str(payload.get("session_id") or "")
+ if not project_access_service.session_exists(conn, session_id):
+ return {key: value for key, value in payload.items() if key != "path"}
+ project_id = project_access_service.get_session_project_id(conn, session_id)
+ effective_role = project_access_service.get_effective_session_role(
+ conn,
+ context,
+ session_id,
+ )
+ if project_access_service.role_allows(effective_role, "editor"):
+ return payload
+ # Legacy and IM-scoped pages have no project role. Their resource ACL
+ # remains the authority for the page owner/editor, but it must not override
+ # an effective project Viewer downgrade on project-attached sessions.
+ if project_id is None and resource_access_service.can_manage_resource_acl(
+ context,
+ "show_page",
+ session_id,
+ connection=conn,
+ ):
+ return payload
+ return {key: value for key, value in payload.items() if key != "path"}
+
+
+def _show_page_payloads_for_request(payloads: list[dict], context: Any = None) -> list[dict]:
+ context = _request_authorization_context(context)
+ if context is None or _has_runtime_owner_access(context):
+ return payloads
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ return [
+ _show_page_payload_for_connection(payload, context, conn)
+ for payload in payloads
+ ]
+
+
+def _show_page_response_for_request(response: Any, context: Any = None) -> Any:
+ """Project every Show Page payload embedded in a mutation response."""
+
+ if not isinstance(response, dict):
+ return response
+ if isinstance(response.get("session_id"), str):
+ return _show_page_payload_for_request(response, context)
+ projected = dict(response)
+ for key in ("page", "show_page"):
+ payload = response.get(key)
+ if isinstance(payload, dict) and isinstance(payload.get("session_id"), str):
+ projected[key] = _show_page_payload_for_request(payload, context)
+ return projected
@app.route("/api/show-pages", methods=["GET"])
@@ -5063,14 +5125,10 @@ def show_pages_list_get():
context = getattr(g, "authorization_context", None)
resource_context = _request_authorization_context(context)
payload = api.list_show_pages(user_context=resource_context)
- if _is_remote_show_page_request():
- payload = {
- **payload,
- "pages": [
- _show_page_payload_for_request(page)
- for page in payload.get("pages", [])
- ],
- }
+ payload = {
+ **payload,
+ "pages": _show_page_payloads_for_request(payload.get("pages", []), context),
+ }
return jsonify(payload)
@@ -5081,12 +5139,13 @@ def show_page_visibility_post(session_id):
payload = request.json or {}
try:
+ context = _request_authorization_context()
return jsonify(
- api.set_show_page_visibility(
+ _show_page_response_for_request(api.set_show_page_visibility(
session_id,
str(payload.get("visibility") or ""),
- user_context=_request_authorization_context(),
- )
+ user_context=context,
+ ), context)
)
except ShowPageError as exc:
return _show_page_error_response(exc)
@@ -5098,12 +5157,14 @@ def show_page_ensure_post(session_id):
from vibe import api
try:
+ context = _request_authorization_context()
return jsonify(
_show_page_payload_for_request(
api.ensure_show_page(
session_id,
- user_context=_request_authorization_context(),
- )
+ user_context=context,
+ ),
+ context,
)
)
except ShowPageError as exc:
@@ -5164,12 +5225,13 @@ def show_page_authorized_emails_put(session_id):
ShowPageError("Invalid Show Page email audience.", code="invalid_email")
)
try:
+ context = _request_authorization_context()
return jsonify(
- api.replace_show_page_authorized_emails(
+ _show_page_response_for_request(api.replace_show_page_authorized_emails(
session_id,
emails,
- user_context=_request_authorization_context(),
- )
+ user_context=context,
+ ), context)
)
except ShowPageError as exc:
return _show_page_error_response(exc)
@@ -5181,11 +5243,12 @@ def show_page_rotate_share_post(session_id):
from vibe import api
try:
+ context = _request_authorization_context()
return jsonify(
- api.rotate_show_page_share(
+ _show_page_response_for_request(api.rotate_show_page_share(
session_id,
- user_context=_request_authorization_context(),
- )
+ user_context=context,
+ ), context)
)
except ShowPageError as exc:
return _show_page_error_response(exc)
@@ -5198,12 +5261,13 @@ def show_page_set_share_id_post(session_id):
payload = request.json or {}
try:
+ context = _request_authorization_context()
return jsonify(
- api.set_show_page_share_id(
+ _show_page_response_for_request(api.set_show_page_share_id(
session_id,
str(payload.get("share_id") or ""),
- user_context=_request_authorization_context(),
- )
+ user_context=context,
+ ), context)
)
except ShowPageError as exc:
return _show_page_error_response(exc)
@@ -8063,17 +8127,17 @@ def _resolve_project_dir(project_id):
"""
if not project_id:
return None
+ authorization_context = getattr(g, "authorization_context", None)
from storage import projects_service
- authorization_context = getattr(g, "authorization_context", None)
engine = _projects_engine()
with engine.connect() as conn:
- project = projects_service.get_project(
+ folder = projects_service.get_project_workdir(
conn,
project_id,
authorization_context=authorization_context,
)
- folder = (project.get("folder_path") or "").strip()
+ folder = str(folder or "").strip()
if not folder:
raise _ProjectNoFolder(project_id)
return folder
@@ -8119,6 +8183,27 @@ def _skills_user_context_kwargs(context: Any) -> dict[str, Any]:
return {}
+def _require_project_editor_for_skill_mutation(
+ project_id: str | None,
+ *,
+ scope: str = "project",
+):
+ """Reject project Skill mutations below the effective Editor role."""
+
+ if not project_id or scope != "project":
+ return None
+ from core.services import skills as skills_service
+
+ try:
+ skills_service.require_project_editor_access(
+ getattr(g, "authorization_context", None),
+ project_id,
+ )
+ except skills_service.SkillsError as exc:
+ return _coded_error_response(exc.code, exc.message, 403)
+ return None
+
+
@app.route("/api/projects/<project_id>/agents-md", methods=["GET"])
def project_agents_md_get(project_id: str):
"""Read the project's AGENTS.md (falling back to CLAUDE.md) for the editor."""
@@ -8270,6 +8355,12 @@ async def skills_add():
return _project_not_found(err)
except _ProjectNoFolder:
return _project_no_folder_error()
+ denied = _require_project_editor_for_skill_mutation(
+ project_id,
+ scope=str(payload.get("scope") or "project"),
+ )
+ if denied is not None:
+ return denied
return jsonify(
await api.add_skill(
str(payload.get("source") or ""),
@@ -8298,6 +8389,12 @@ async def skills_remove(name):
return _project_not_found(err)
except _ProjectNoFolder:
return _project_no_folder_error()
+ denied = _require_project_editor_for_skill_mutation(
+ project_id,
+ scope=request.args.get("scope") or "project",
+ )
+ if denied is not None:
+ return denied
return jsonify(
await api.remove_skill(
name,
@@ -8359,6 +8456,12 @@ async def skills_update():
return _project_not_found(err)
except _ProjectNoFolder:
return _project_no_folder_error()
+ denied = _require_project_editor_for_skill_mutation(
+ project_id,
+ scope=str(payload.get("scope") or "project"),
+ )
+ if denied is not None:
+ return denied
return jsonify(
await api.update_skill(
str(payload.get("name") or ""),
@@ -8385,6 +8488,9 @@ async def skills_upload():
# The zip is unpacked to a temp dir (project-independent); the install
# step picks the scope. Drop the cwd like preview rather than erroring.
project_dir = None
+ denied = _require_project_editor_for_skill_mutation(project_id)
+ if denied is not None:
+ return denied
return jsonify(
await api.upload_skill_zip(
payload,
@@ -9845,6 +9951,10 @@ async def show_page_icon_upload(session_id: str, starlette_request: FastAPIReque
content_type=upload.content_type,
user_context=_request_authorization_context(),
)
+ result = _show_page_response_for_request(
+ result,
+ _request_authorization_context(),
+ )
# Broadcast so EVERY already-mounted inventory (Dock, WindowLayer, mobile
# drawer, app search) reloads and picks up the new icon_version — the
# optimistic mergePage only updates the Library instance that uploaded