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): recheck delayed project deliveries

Maxvintc7861f129564
diff --git a/core/session_turns.py b/core/session_turns.py
index be9f45bd6..d2ddb7e96 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -27,7 +27,11 @@ from sqlalchemy import select
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
-from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATA
+from core.web_push_notifications import (
+ WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA,
+ WEB_PUSH_USER_KEY_METADATA,
+ WEB_PUSH_USER_KEYS_METADATA,
+)
from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
from storage import messages_service
from storage.db import get_cached_sqlite_engine
@@ -1004,6 +1008,25 @@ class SessionTurnManager:
user_metadata = {WEB_PUSH_USER_KEY_METADATA: user_owner}
elif user_owners:
user_metadata = {WEB_PUSH_USER_KEYS_METADATA: user_owners}
+ authorization_contexts: dict[str, dict[str, Any]] = {}
+ for row in segment:
+ raw_contexts = (row.get("metadata") or {}).get(
+ WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA
+ )
+ if not isinstance(raw_contexts, list):
+ continue
+ for raw_context in raw_contexts:
+ if not isinstance(raw_context, dict):
+ continue
+ context_user_key = raw_context.get("user_key")
+ if context_user_key in user_owners:
+ authorization_contexts[str(context_user_key)] = raw_context
+ if authorization_contexts:
+ if user_metadata is None:
+ user_metadata = {}
+ user_metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = list(
+ authorization_contexts.values()
+ )
attachment_specs = resolve_attachment_specs(
conn, session_id=session_id, attachments=queued_attachments
)
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index 3d72c6afb..1a5c36156 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -13,6 +13,7 @@ from sqlalchemy import or_, select
from core.backend_failure import is_backend_failure_notification
from storage import messages_service, web_push_service
from storage.models import agent_sessions, messages
+from vibe.authorization import AuthorizationContext, context_from_session_payload
logger = logging.getLogger(__name__)
@@ -21,6 +22,7 @@ _UNREAD_GATED_TYPES = {"result"}
WEB_PUSH_NOTIFICATION_DELAY_SECONDS = 3.0
WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"
WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"
+WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA = "_web_push_authorization_contexts"
def _is_notifiable_message(message_type: Any, metadata: Any = None) -> bool:
@@ -107,8 +109,61 @@ def _metadata_user_keys(metadata: dict[str, Any]) -> list[str]:
return list(dict.fromkeys(keys))
-def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[str]:
- """Resolve trusted browser owners for a Workbench agent message.
+def web_push_authorization_context_record(
+ user_key: str,
+ context: AuthorizationContext | None,
+) -> dict[str, Any] | None:
+ """Serialize the trusted remote claims needed to recheck Project access."""
+
+ if (
+ not user_key.startswith("remote:")
+ or context is None
+ or not context.is_remote
+ or not context.subject
+ or user_key != f"remote:{context.subject}"
+ ):
+ return None
+ record: dict[str, Any] = {
+ "user_key": user_key,
+ "sub": context.subject,
+ "vibe_instance_role": context.instance_role,
+ "vibe_instance_access_source": context.instance_access_source,
+ "vibe_group_ids": sorted(context.group_ids),
+ }
+ optional_claims = {
+ "email": context.email,
+ "vibe_instance_id": context.instance_id,
+ "vibe_organization_id": context.organization_id,
+ "vibe_organization_member_id": context.organization_member_id,
+ "vibe_organization_role": context.organization_role,
+ "vibe_membership_version": context.membership_version,
+ }
+ record.update({key: value for key, value in optional_claims.items() if value is not None})
+ return record
+
+
+def _metadata_authorization_contexts(metadata: dict[str, Any]) -> dict[str, AuthorizationContext]:
+ raw_contexts = metadata.get(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA)
+ if not isinstance(raw_contexts, list):
+ return {}
+ contexts: dict[str, AuthorizationContext] = {}
+ for raw_context in raw_contexts:
+ if not isinstance(raw_context, dict):
+ continue
+ user_key = raw_context.get("user_key")
+ if not isinstance(user_key, str) or not user_key.startswith("remote:"):
+ continue
+ context = context_from_session_payload(raw_context)
+ if context.subject and user_key == f"remote:{context.subject}" and context.can_read_instance:
+ contexts[user_key] = context
+ return contexts
+
+
+def _web_push_owner_metadata_for_message(
+ conn: Any,
+ message_id: str | None,
+) -> tuple[str | None, dict[str, Any]]:
+ """Resolve trusted browser-owner metadata for a Workbench agent message.
New sessions do not write a Web Push owner field: that made future behavior
depend on session creation time. For upgraded rows, still honor the legacy
@@ -117,7 +172,7 @@ def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[s
"""
if not message_id:
- return []
+ return None, {}
agent_row = conn.execute(
select(
messages.c.session_id,
@@ -135,7 +190,7 @@ def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[s
agent_row[3],
_parse_metadata(agent_row[4]),
):
- return []
+ return None, {}
session_id, created_at, row_id = agent_row[0], agent_row[1], agent_row[2]
user_rows = conn.execute(
@@ -159,19 +214,65 @@ def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[s
).all()
for user_row in user_rows:
try:
- user_keys = _metadata_user_keys(json.loads(user_row[0] or "{}") or {})
+ metadata = json.loads(user_row[0] or "{}") or {}
except (TypeError, ValueError):
continue
- if user_keys:
- return user_keys
+ if isinstance(metadata, dict) and _metadata_user_keys(metadata):
+ return str(session_id), metadata
session_metadata = conn.execute(
select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)
).scalar_one_or_none()
try:
- return _metadata_user_keys(json.loads(session_metadata or "{}") or {})
+ metadata = json.loads(session_metadata or "{}") or {}
except (TypeError, ValueError):
- return []
+ return str(session_id), {}
+ return str(session_id), metadata if isinstance(metadata, dict) else {}
+
+
+def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[str]:
+ """Resolve trusted browser owners for a Workbench agent message."""
+
+ _session_id, metadata = _web_push_owner_metadata_for_message(conn, message_id)
+ return _metadata_user_keys(metadata)
+
+
+def _filter_project_authorized_user_keys(
+ conn: Any,
+ *,
+ session_id: str | None,
+ metadata: dict[str, Any],
+ user_keys: list[str],
+) -> list[str]:
+ """Recheck delayed remote deliveries against the current Project policy."""
+
+ if not session_id or not user_keys:
+ return user_keys
+ from storage import project_access_service
+
+ 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_access_service.project_id_from_scope_id(scope_id)
+ if project_id is None:
+ return user_keys
+ policy = project_access_service.get_project_policy(conn, project_id)
+ if policy is None or policy.get("mode") != "restricted":
+ return user_keys
+
+ contexts = _metadata_authorization_contexts(metadata)
+ authorized: list[str] = []
+ for user_key in user_keys:
+ if user_key == "local":
+ authorized.append(user_key)
+ continue
+ context = contexts.get(user_key)
+ if context is not None and project_access_service.role_allows(
+ project_access_service.get_effective_session_role(conn, context, session_id),
+ "viewer",
+ ):
+ authorized.append(user_key)
+ return authorized
def _remote_access_enabled() -> bool:
@@ -203,7 +304,16 @@ def _send_to_enabled_subscriptions(payload: dict[str, Any]) -> None:
# The app-icon badge is one global number; compute the live total now
# (post-debounce) so it matches the in-app Inbox badge on open.
payload["badge_count"] = messages_service.total_unread(conn, platform="avibe")
- user_keys = _web_push_user_keys_for_message(conn, payload.get("message_id"))
+ session_id, owner_metadata = _web_push_owner_metadata_for_message(
+ conn,
+ payload.get("message_id"),
+ )
+ user_keys = _filter_project_authorized_user_keys(
+ conn,
+ session_id=session_id,
+ metadata=owner_metadata,
+ user_keys=_metadata_user_keys(owner_metadata),
+ )
if not user_keys and not _remote_access_enabled():
user_keys = ["local"] if web_push_service.has_enabled_user_key(conn, user_key="local") else []
if not user_keys:
diff --git a/storage/media_service.py b/storage/media_service.py
index 88866ccaf..999f5b97a 100644
--- a/storage/media_service.py
+++ b/storage/media_service.py
@@ -74,14 +74,13 @@ def register(
"""Register *local_path* under a token and return it, reusing an existing
token for the same file so its proxy URL is stable + cacheable.
- Dedup is machine-global on the ``(local_path, size_bytes, mtime_ns)``
- fingerprint — scope/session are intentionally NOT part of the key, so the
- same file referenced from any message or session resolves to one URL the
- browser can cache. ``mtime_ns`` + ``size_bytes`` is a stat-only change
- detector: a rewritten file (new size/mtime) mints a fresh token, busting the
- cache. ``content_type`` / ``file_ext`` / ``size_bytes`` are derived from the
- path when not supplied so the proxy response and UI card don't re-compute
- them.
+ Dedup is scoped to the referencing session. A shared path referenced from
+ different sessions receives separate tokens so each token retains the
+ correct authorization target. ``mtime_ns`` + ``size_bytes`` is a stat-only
+ change detector: a rewritten file (new size/mtime) mints a fresh token,
+ busting the cache. ``content_type`` / ``file_ext`` / ``size_bytes`` are
+ derived from the path when not supplied so the proxy response and UI card
+ don't re-compute them.
"""
path = Path(local_path)
name = file_name or path.name
@@ -107,6 +106,8 @@ def register(
media_objects.c.local_path == str(local_path),
media_objects.c.size_bytes == size,
media_objects.c.mtime_ns == mtime_ns,
+ media_objects.c.scope_id == scope_id,
+ media_objects.c.session_id == session_id,
media_objects.c.revoked_at.is_(None),
)
).scalar()
diff --git a/storage/models.py b/storage/models.py
index d2c6e8d6b..951dc4504 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -461,14 +461,14 @@ messages = Table(
# file referenced by an agent reply (or uploaded by the user) is registered
# here and served back over ``/api/media/<token>``. The URL carries only the
# opaque ``token`` — never a filesystem path, never a session — so it is stable
-# across messages/sessions and the browser can cache it. ``content_type`` /
+# within the referencing session and the browser can cache it. ``content_type`` /
# ``file_ext`` are stored so the response and the UI file card don't have to
# re-derive them; ``kind`` (image|file) selects inline-image vs download-card
# rendering; ``source`` distinguishes agent output from user uploads so one
# table serves both. ``size_bytes`` + ``mtime_ns`` are the content fingerprint:
# :func:`storage.media_service.register` reuses an existing token for the same
-# (local_path, size_bytes, mtime_ns) so a re-referenced file keeps one cacheable
-# URL, while a changed file mints a fresh token (busting the browser cache).
+# session and (local_path, size_bytes, mtime_ns), while a different session or
+# changed file mints a fresh token.
media_objects = Table(
"media_objects",
metadata,
@@ -494,7 +494,7 @@ media_objects = Table(
Column("revoked_at", String, nullable=True),
Index("ix_media_objects_session", "session_id"),
Index("ix_media_objects_scope_created", "scope_id", "created_at"),
- # Backs register()'s dedup lookup (machine-global content fingerprint).
+ # Backs the fingerprint prefix of register()'s session-scoped dedup lookup.
Index("ix_media_objects_dedup", "local_path", "size_bytes", "mtime_ns"),
)
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index e735ca393..b13e2fe09 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -2979,7 +2979,19 @@ def test_flush_mixed_owner_user_rows_preserves_owner_list(tmp_path, monkeypatch)
message_type=messages_service.QUEUED_TYPE,
text=text,
author_id=owner,
- metadata={"_web_push_user_key": owner},
+ metadata={
+ "_web_push_user_key": owner,
+ "_web_push_authorization_contexts": [
+ {
+ "user_key": owner,
+ "sub": owner.removeprefix("remote:"),
+ "email": f"{owner.removeprefix('remote:')}@example.com",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_group_ids": [],
+ }
+ ],
+ },
)
mgr, runs = _manager_capturing_runs()
@@ -2993,6 +3005,10 @@ def test_flush_mixed_owner_user_rows_preserves_owner_list(tmp_path, monkeypatch)
"remote:user-a",
"remote:user-b",
]
+ assert [
+ record["user_key"]
+ for record in transcript["messages"][0]["metadata"]["_web_push_authorization_contexts"]
+ ] == ["remote:user-a", "remote:user-b"]
assert "_web_push_user_key" not in transcript["messages"][0]["metadata"]
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index 902c7431e..796c3b41c 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -17,7 +17,7 @@ from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.workbench_sessions_service import create_session
from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
-from vibe import api, remote_access, ui_server
+from vibe import api, internal_client, remote_access, ui_server
from vibe.authorization import AuthorizationContext
from vibe.sse_broker import broker
from vibe.ui_server import app
@@ -89,10 +89,8 @@ def _setup_state(tmp_path) -> tuple[V2Config, dict[str, str]]:
project_b_dir = tmp_path / "project-b"
project_a_dir.mkdir()
project_b_dir.mkdir()
- media_a = tmp_path / "a.txt"
- media_b = tmp_path / "b.txt"
- media_a.write_text("project a", encoding="utf-8")
- media_b.write_text("project b", encoding="utf-8")
+ shared_media = tmp_path / "shared.txt"
+ shared_media.write_text("shared media", encoding="utf-8")
with engine.begin() as conn:
project_a = projects_service.create_project(conn, str(project_a_dir), display_name="A")
project_b = projects_service.create_project(conn, str(project_b_dir), display_name="B")
@@ -115,7 +113,7 @@ def _setup_state(tmp_path) -> tuple[V2Config, dict[str, str]]:
session_id=session_a["id"],
kind="file",
source="agent_reply",
- local_path=str(media_a.resolve()),
+ local_path=str(shared_media.resolve()),
)
media_b_token = media_service.register(
conn,
@@ -123,8 +121,9 @@ def _setup_state(tmp_path) -> tuple[V2Config, dict[str, str]]:
session_id=session_b["id"],
kind="file",
source="agent_reply",
- local_path=str(media_b.resolve()),
+ local_path=str(shared_media.resolve()),
)
+ assert media_a_token != media_b_token
project_access_service.apply_project_access_intent(
conn,
_intent(project_a["id"], "[email protected]"),
@@ -332,6 +331,50 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
assert editor_payload["draft"] == {"text": "editor-only draft"}
+def test_remote_message_persists_trusted_web_push_authorization_context(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ client = _remote_client(config, role="editor", email="[email protected]")
+
+ async def dispatch_async(_payload):
+ return {"status_code": 202, "body": {"ok": True}}
+
+ monkeypatch.setattr(internal_client, "dispatch_async", dispatch_async)
+ response = client.post(
+ f"/api/sessions/{ids['session_a']}/messages",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=csrf_headers(client, REMOTE_ORIGIN),
+ json={
+ "text": "Run it",
+ "metadata": {
+ "_web_push_authorization_contexts": [
+ {"user_key": "remote:spoofed", "email": "[email protected]"}
+ ]
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ payload = response.get_json()
+ assert payload["metadata"]["_web_push_user_key"].startswith("remote:")
+ records = payload["metadata"]["_web_push_authorization_contexts"]
+ assert records == [
+ {
+ "email": "[email protected]",
+ "sub": payload["metadata"]["_web_push_user_key"].removeprefix("remote:"),
+ "user_key": payload["metadata"]["_web_push_user_key"],
+ "vibe_group_ids": [],
+ "vibe_instance_access_source": "owner",
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "editor",
+ }
+ ]
+
+
def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
@@ -374,6 +417,8 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
] == [ids["project_b"]]
assert _get(organization_member, f"/api/sessions/{ids['session_b']}").status_code == 200
assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 404
+ assert _get(organization_member, f"/api/media/{ids['media_b']}").status_code == 200
+ assert _get(organization_member, f"/api/media/{ids['media_a']}").status_code == 404
owner = _remote_client(config, role="owner", email="[email protected]")
assert {row["id"] for row in _get(owner, "/api/projects").get_json()["projects"]} == {
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index af9b167e4..5a23b02f5 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -1,11 +1,12 @@
from __future__ import annotations
from core import web_push_notifications
-from storage import messages_service, web_push_service
+from storage import messages_service, project_access_service, web_push_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions
from storage.settings_service import upsert_scope
+from vibe.authorization import AuthorizationContext
def test_maybe_notify_inbox_message_schedules_agent_result(monkeypatch):
@@ -264,6 +265,152 @@ def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeyp
]
+def test_send_to_enabled_subscriptions_rechecks_restricted_project_access(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-06-04T00:00:00Z"
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="user-a",
+ instance_access_source="email",
+ is_remote=True,
+ )
+ authorization_record = web_push_notifications.web_push_authorization_context_record(
+ "remote:user-a",
+ context,
+ )
+ assert authorization_record is not None
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_acl",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_acl",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="ses_push_acl",
+ native_session_id="",
+ title="Push ACL",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ assert project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": "proj_push_acl",
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "editor",
+ }
+ ],
+ },
+ ).outcome == "applied"
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_acl",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:user-a",
+ metadata={
+ "_web_push_user_key": "remote:user-a",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ allowed_message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_acl",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Allowed",
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload={
+ "endpoint": "https://push.example.test/a",
+ "keys": {"p256dh": "a-key", "auth": "a-auth"},
+ },
+ )
+
+ sends = []
+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ "core.web_push.send_web_push",
+ lambda *, subscription, payload: sends.append((subscription, payload)),
+ )
+
+ web_push_notifications._send_to_enabled_subscriptions(
+ {
+ "title": "Push ACL",
+ "body": "Allowed",
+ "session_id": "ses_push_acl",
+ "message_id": allowed_message["id"],
+ }
+ )
+ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]
+
+ with engine.begin() as conn:
+ assert project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": "proj_push_acl",
+ "revision": 2,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "editor",
+ }
+ ],
+ },
+ ).outcome == "applied"
+ revoked_message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_acl",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Revoked",
+ )
+
+ web_push_notifications._send_to_enabled_subscriptions(
+ {
+ "title": "Push ACL",
+ "body": "Revoked",
+ "session_id": "ses_push_acl",
+ "message_id": revoked_message["id"],
+ }
+ )
+ assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]
+
+
def test_send_to_enabled_subscriptions_sets_global_badge_count(monkeypatch, tmp_path):
"""badge_count in the sent payload is the GLOBAL unread total, not the
triggering session's per-session count — the app-icon badge is one number."""
diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.py
index 62227c4ba..1e076c93f 100644
--- a/tests/test_workbench_media.py
+++ b/tests/test_workbench_media.py
@@ -252,17 +252,36 @@ def test_register_dedups_same_fingerprint(tmp_path):
with engine.begin() as conn:
scope_id = _seed_scope_and_session(conn)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="other",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="other-anchor",
+ native_session_id="other-native",
+ status="active",
+ metadata_json="{}",
+ created_at=_now(),
+ updated_at=_now(),
+ )
+ )
t1 = media_service.register(
conn, scope_id=scope_id, session_id="sess_x", kind="image",
source="agent_reply", local_path=str(shot),
)
- # Same file (path + size + mtime), DIFFERENT session → same token: dedup is
- # machine-global, so the proxy URL stays stable + cacheable.
+ # Same file in the same authorization scope stays stable + cacheable.
+ assert media_service.register(
+ conn, scope_id=scope_id, session_id="sess_x", kind="image",
+ source="agent_reply", local_path=str(shot),
+ ) == t1
+ # A different session receives a distinct token so authorization checks
+ # use that referencing session instead of the first dedup registration.
t2 = media_service.register(
conn, scope_id=scope_id, session_id="other", kind="image",
source="agent_reply", local_path=str(shot),
)
- assert t2 == t1
+ assert t2 != t1
# Content change (new size + mtime) → fresh token, busting the cache.
shot.write_bytes(b"abcdef-changed")
t3 = media_service.register(
@@ -273,7 +292,7 @@ def test_register_dedups_same_fingerprint(tmp_path):
with engine.connect() as conn:
rows = conn.execute(select(media_objects)).mappings().all()
- assert len(rows) == 2 # original (reused once) + the changed file
+ assert len(rows) == 3 # two authorization scopes + changed content
def test_register_reads_image_dimensions(tmp_path):
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index b592a84ff..6d4c66c90 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -7711,13 +7711,12 @@ _INLINE_SAFE_MEDIA_TYPES = {
def media_get(token: str):
"""Serve a registered chat-media file (agent reply / upload) by opaque token.
- The token — not a path, not a session — is the capability: only files we
- minted into ``media_objects`` are reachable, and the same token resolves to
- one stable URL the browser can cache across messages/sessions. Lives under
- ``/api/*`` so the remote-access auth middleware already gates it, and a
- same-origin ``<img>`` / anchor GET carries the session cookie. Defaults to
- ``inline`` (so images render in ``<img>`` and PDFs preview); ``?download=1``
- forces an attachment download.
+ Only files minted into ``media_objects`` are reachable. Tokens stay stable
+ within their referencing session, and the row's Project/session scope is
+ authorized on every request. Lives under ``/api/*`` so the remote-access
+ auth middleware already gates it, and a same-origin ``<img>`` / anchor GET
+ carries the session cookie. Defaults to ``inline`` (so images render in
+ ``<img>`` and PDFs preview); ``?download=1`` forces an attachment download.
"""
return _registered_media_response(token)
@@ -7988,6 +7987,10 @@ async def sessions_messages_create(session_id: str):
"""
from core.services import sessions as workbench_sessions_service
+ from core.web_push_notifications import (
+ WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA,
+ web_push_authorization_context_record,
+ )
from storage import messages_service
from vibe import internal_client
from vibe.sse_broker import broker
@@ -8000,6 +8003,10 @@ async def sessions_messages_create(session_id: str):
# A quick-reply click tags the row with the agent message it answers.
quick_reply_for = (payload.get("metadata") or {}).get("quick_reply_for")
web_push_user_key = _web_push_user_key()
+ web_push_authorization_context = web_push_authorization_context_record(
+ web_push_user_key,
+ getattr(g, "authorization_context", None),
+ )
engine = _projects_engine()
try:
@@ -8054,6 +8061,15 @@ async def sessions_messages_create(session_id: str):
# must stay terminal — no new row, no turn.
if workbench_sessions_service.is_session_archived(conn, session_id):
return None
+ message_metadata = {
+ **(payload.get("metadata") or {}),
+ "_web_push_user_key": web_push_user_key,
+ }
+ message_metadata.pop(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA, None)
+ if web_push_authorization_context is not None:
+ message_metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = [
+ web_push_authorization_context
+ ]
row = messages_service.append(
conn,
scope_id=session["scope_id"],
@@ -8064,10 +8080,7 @@ async def sessions_messages_create(session_id: str):
message_type=messages_service.PENDING_TYPE,
text=text if isinstance(text, str) else None,
content=content if isinstance(content, dict) else None,
- metadata={
- **(payload.get("metadata") or {}),
- "_web_push_user_key": web_push_user_key,
- },
+ metadata=message_metadata,
author_id=web_push_user_key,
author_name=payload.get("author_name"),
)