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(org): close integration authorization gaps

Max59d6e057dc46
diff --git a/core/caller_context.py b/core/caller_context.py
index 309b7e9b2..e8ae61884 100644
--- a/core/caller_context.py
+++ b/core/caller_context.py
@@ -3,8 +3,9 @@
from __future__ import annotations
from dataclasses import dataclass, replace
+import json
import os
-from typing import Mapping, Optional
+from typing import Any, Mapping, Optional
AVIBE_SESSION_ID_ENV = "AVIBE_SESSION_ID"
AVIBE_RUN_ID_ENV = "AVIBE_RUN_ID"
@@ -21,6 +22,10 @@ AVIBE_CALLER_CHANNEL_ID_ENV = "AVIBE_CALLER_CHANNEL_ID"
AVIBE_CALLER_SESSION_KEY_ENV = "AVIBE_CALLER_SESSION_KEY"
AVIBE_CALLER_MESSAGE_ID_ENV = "AVIBE_CALLER_MESSAGE_ID"
AVIBE_CALLER_WORKSPACE_ID_ENV = "AVIBE_CALLER_WORKSPACE_ID"
+AVIBE_CALLER_REMOTE_ENV = "AVIBE_CALLER_REMOTE"
+AVIBE_CALLER_RESOURCE_CONTEXT_ENV = "AVIBE_CALLER_RESOURCE_CONTEXT"
+
+_RESOURCE_USER_CONTEXT_METADATA_KEY = "resource_user_context"
@dataclass(frozen=True)
@@ -59,6 +64,8 @@ class CallerContext:
session_key: Optional[str] = None
message_id: Optional[str] = None
workspace_id: Optional[str] = None
+ is_remote: bool = False
+ resource_user_context: Optional[Mapping[str, Any]] = None
def session_stable(self) -> "CallerContext":
"""This context minus every origin field that changes from turn to turn.
@@ -79,11 +86,13 @@ class CallerContext:
person, which is worse than not notifying anybody.
What survives is what the SESSION owns: platform, channel, session key,
- workspace. So a Claude-created definition still names the conversation it came
- from and still lights up rung (3); it gets no owner-DM rung and no deep link,
- because a permalink needs the message id this deliberately drops. Codex and
- OpenCode rewrite their caller env per turn (a ``BASH_ENV`` script and a binding
- file respectively) and therefore keep the full origin.
+ workspace. A trusted remote Workbench authorization snapshot also survives:
+ unlike an IM author id, it is required to authorize any CLI resource write.
+ When that snapshot changes the Claude cache comparison deliberately recreates
+ the client, so one remote user's ACL can never be reused for another. Thus a
+ Claude-created definition still names its conversation and remote authority,
+ while ordinary IM sessions get no owner-DM rung or deep link. Codex and
+ OpenCode rewrite their caller env per turn and keep the full origin.
A DM is the case where nothing is lost: its session key is
``<platform>::user::<id>``, so the person is carried by the scope itself.
@@ -115,6 +124,14 @@ class CallerContext:
env[AVIBE_CALLER_MESSAGE_ID_ENV] = self.message_id
if self.workspace_id:
env[AVIBE_CALLER_WORKSPACE_ID_ENV] = self.workspace_id
+ if self.is_remote:
+ env[AVIBE_CALLER_REMOTE_ENV] = "1"
+ if self.resource_user_context is not None:
+ env[AVIBE_CALLER_RESOURCE_CONTEXT_ENV] = json.dumps(
+ dict(self.resource_user_context),
+ separators=(",", ":"),
+ sort_keys=True,
+ )
return env
def to_metadata(self) -> dict[str, str]:
@@ -163,6 +180,30 @@ def _clean(value: object) -> str:
return str(value or "").strip()
+def _resource_context_from_env(source: Mapping[str, str]) -> Optional[dict[str, Any]]:
+ raw = _clean(source.get(AVIBE_CALLER_RESOURCE_CONTEXT_ENV))
+ if not raw:
+ return None
+ try:
+ parsed = json.loads(raw)
+ except (TypeError, ValueError, json.JSONDecodeError):
+ return None
+ return dict(parsed) if isinstance(parsed, dict) else None
+
+
+def caller_resource_user_context(context: Optional[CallerContext]) -> Optional[Mapping[str, Any]]:
+ """Return explicit remote ACL context for a CLI write.
+
+ ``None`` is reserved for a genuinely local caller. A remote Agent invocation
+ with missing or malformed authorization provenance returns an empty mapping,
+ which resource services parse as an anonymous remote context and reject.
+ """
+
+ if context is None or not context.is_remote:
+ return None
+ return dict(context.resource_user_context or {})
+
+
def _scope_id_from_session_key(session_key: str) -> Optional[str]:
parts = _clean(session_key).split("::")
if len(parts) != 5:
@@ -275,6 +316,8 @@ def caller_context_from_env(env: Mapping[str, str] | None = None) -> Optional[Ca
session_key=_clean(source.get(AVIBE_CALLER_SESSION_KEY_ENV)) or None,
message_id=_clean(source.get(AVIBE_CALLER_MESSAGE_ID_ENV)) or None,
workspace_id=_clean(source.get(AVIBE_CALLER_WORKSPACE_ID_ENV)) or None,
+ is_remote=_clean(source.get(AVIBE_CALLER_REMOTE_ENV)).lower() in {"1", "true"},
+ resource_user_context=_resource_context_from_env(source),
)
@@ -335,6 +378,16 @@ def caller_context_from_platform_payload(
)
workspace_id = _origin_workspace_id(platform, payload)
+ is_remote = platform == "avibe" and user_id.startswith("remote:")
+ resource_user_context: Optional[dict[str, Any]] = None
+ message_metadata = payload.get("message_metadata")
+ if is_remote and isinstance(message_metadata, Mapping):
+ raw_resource_context = message_metadata.get(_RESOURCE_USER_CONTEXT_METADATA_KEY)
+ if isinstance(raw_resource_context, Mapping):
+ subject = _clean(raw_resource_context.get("sub"))
+ if subject and user_id == f"remote:{subject}":
+ resource_user_context = dict(raw_resource_context)
+
return CallerContext(
session_id=session_id,
run_id=run_id or None,
@@ -347,6 +400,8 @@ def caller_context_from_platform_payload(
session_key=session_key,
message_id=message_id or None,
workspace_id=workspace_id,
+ is_remote=is_remote,
+ resource_user_context=resource_user_context,
)
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 164891950..33d17a805 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -466,11 +466,10 @@ class SessionHandler(BaseHandler):
SESSION-STABLE ONLY, and that is not a shortcut. This env is baked into a Claude
SDK client at spawn and is also the value compared to decide whether a cached
- client may be reused, so a field that changes per turn would respawn the Agent on
- every message, and a field that changes per author would attribute one
- participant's definition to another. ``CallerContext.session_stable`` documents
- both, and what a Claude-created definition therefore keeps: the conversation, not
- the author or the individual message.
+ client may be reused, so ordinary IM author/message fields are dropped. A trusted
+ remote Workbench ACL snapshot is retained: changing remote identity or revision
+ must recreate the client rather than let one user's resource authority leak into
+ another user's turn. ``CallerContext.session_stable`` documents both cases.
"""
return caller_env_for_platform_payload(
diff --git a/core/services/sessions.py b/core/services/sessions.py
index f955a695b..0078891c2 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -51,7 +51,6 @@ from storage.workbench_sessions_service import (
is_session_archived,
list_sessions,
list_sessions_page,
- reset_running_agent_status,
require_enabled_agent_backend,
require_enabled_agent_identity,
set_agent_status,
@@ -76,7 +75,6 @@ __all__ = [
"is_session_archived",
"list_sessions",
"list_sessions_page",
- "reset_running_agent_status",
"set_agent_status",
"session_archived_message",
"touch_session",
diff --git a/core/session_turns.py b/core/session_turns.py
index 90b7db197..8708deb66 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -131,6 +131,13 @@ _EXECUTION_ROUTING_KEYS = _FLUSH_REBUILT_KEYS | frozenset(
SCHEDULED_TARGET_AGENT_KEY = "scheduled_target_agent_name"
MEMORY_USER_ID_METADATA = "_memory_user_id"
MEMORY_ORDINARY_TEXT_METADATA = "_memory_ordinary_text"
+_MEMORY_METADATA_KEYS = frozenset(
+ {
+ MEMORY_USER_ID_METADATA,
+ MEMORY_ORDINARY_TEXT_METADATA,
+ "_memory_cli_admitted",
+ }
+)
_NON_RESTORABLE_RUNTIME_BACKENDS = frozenset({"claude", "codex"})
_MAX_AUTOMATIC_UNKNOWN_START_REPLAYS = 1
@@ -308,6 +315,7 @@ def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]
return segment
segment: list[dict[str, Any]] = []
+ segment_is_memory_scoped: bool | None = None
segment_owner: str | None = None
for row in rows:
if _scheduled_provenance(row) is not None:
@@ -315,11 +323,18 @@ def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]
if delivery_store.message_merge_identity(row) != message_identity:
break
metadata = row.get("metadata") or {}
+ is_memory_scoped = any(key in metadata for key in _MEMORY_METADATA_KEYS)
owner = str(metadata.get(MEMORY_USER_ID_METADATA) or "").strip() or None
if segment and (
- owner is None
- or segment_owner is None
- or owner != segment_owner
+ is_memory_scoped != segment_is_memory_scoped
+ or (
+ is_memory_scoped
+ and (
+ owner is None
+ or segment_owner is None
+ or owner != segment_owner
+ )
+ )
):
break
native_message_id = str(row.get("native_message_id") or "").strip()
@@ -328,8 +343,10 @@ def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]
segment.append(row)
break
segment.append(row)
+ if len(segment) == 1:
+ segment_is_memory_scoped = is_memory_scoped
segment_owner = owner
- if owner is None:
+ if is_memory_scoped and owner is None:
break
return segment
@@ -1228,14 +1245,7 @@ class SessionTurnManager:
for payload in payloads
]
memory_metadata_present = any(
- any(
- key in metadata
- for key in (
- MEMORY_USER_ID_METADATA,
- MEMORY_ORDINARY_TEXT_METADATA,
- "_memory_cli_admitted",
- )
- )
+ any(key in metadata for key in _MEMORY_METADATA_KEYS)
for metadata in metadata_rows
)
memory_users = list(
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index c4b872092..bd2c0932f 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -830,10 +830,6 @@ class VibeAgentStore:
def require_manageable(self, name: str, *, user_context: Any = None) -> VibeAgent:
"""Return an Agent only when the caller may change its resource."""
-
- from storage import resource_access_service
-
- context = resolve_resource_access_context(user_context)
with self.engine.connect() as conn:
row = conn.execute(
select(agents).where(agents.c.normalized_name == normalize_agent_name(name)).limit(1)
@@ -841,14 +837,32 @@ class VibeAgentStore:
if row is None:
raise ValueError(f"agent '{name}' not found")
agent = self._from_row(row)
- if not resource_access_service.can_manage_resource_acl(
- context,
- "agent",
- agent.id,
- connection=conn,
- ):
- raise VibeAgentAccessError("Agent access is not permitted.")
- return agent
+ return self._require_manageable_agent(
+ conn,
+ agent,
+ user_context=user_context,
+ )
+
+ @staticmethod
+ def _require_manageable_agent(
+ conn: Connection,
+ agent: VibeAgent,
+ *,
+ user_context: Any = None,
+ ) -> VibeAgent:
+ """Check mutation access using the transaction that owns the Agent row."""
+
+ from storage import resource_access_service
+
+ context = resolve_resource_access_context(user_context)
+ if not resource_access_service.can_manage_resource_acl(
+ context,
+ "agent",
+ agent.id,
+ connection=conn,
+ ):
+ raise VibeAgentAccessError("Agent access is not permitted.")
+ return agent
def create(
self,
@@ -921,7 +935,6 @@ class VibeAgentStore:
user_context: Any = None,
) -> VibeAgent:
normalized = normalize_agent_name(name)
- self.require_manageable(name, user_context=user_context)
with self.engine.begin() as conn:
reserve_write_lock(conn)
row = conn.execute(
@@ -932,6 +945,11 @@ class VibeAgentStore:
f"agent '{name}' not found", agent_name=name, reason="missing"
)
existing = self._from_row(row)
+ self._require_manageable_agent(
+ conn,
+ existing,
+ user_context=user_context,
+ )
if existing.archived_at is not None:
raise AgentArchivedEditError(agent_name=name)
@@ -971,7 +989,6 @@ class VibeAgentStore:
*,
user_context: Any = None,
) -> VibeAgent:
- self.require_manageable(name, user_context=user_context)
raw_new_name, new_normalized = _validated_public_agent_name(new_name)
old_normalized = normalize_agent_name(name)
now = _utc_now_iso()
@@ -984,8 +1001,13 @@ class VibeAgentStore:
if row is None:
raise AgentUnavailableError(
f"agent '{name}' not found", agent_name=name, reason="missing"
- )
+ )
agent = self._from_row(row)
+ self._require_manageable_agent(
+ conn,
+ agent,
+ user_context=user_context,
+ )
if agent.archived_at is not None:
raise AgentArchivedEditError(agent_name=name)
if is_builtin_default_agent(agent):
@@ -1048,10 +1070,18 @@ class VibeAgentStore:
legacy = self._legacy_archive_for_original_name(conn, normalized)
if legacy is None:
return None
- self.require_manageable(legacy.name, user_context=user_context)
+ self._require_manageable_agent(
+ conn,
+ legacy,
+ user_context=user_context,
+ )
return self._compact_legacy_archive(conn, legacy, now=now)
agent = self._from_row(row)
- self.require_manageable(agent.name, user_context=user_context)
+ self._require_manageable_agent(
+ conn,
+ agent,
+ user_context=user_context,
+ )
if is_builtin_default_agent(agent):
raise AgentArchiveError(
code="agent_builtin",
@@ -1220,15 +1250,24 @@ class VibeAgentStore:
def remove(self, name: str, *, user_context: Any = None) -> bool:
from storage import resource_access_service
- agent = self.get(name)
- if agent is None:
- return False
- self.require_manageable(name, user_context=user_context)
- if is_builtin_default_agent(agent):
- raise ValueError(f"agent '{agent.name}' is built in and cannot be deleted")
- normalized = agent.normalized_name
with self.engine.begin() as conn:
- result = conn.execute(agents.delete().where(agents.c.normalized_name == normalized))
+ reserve_write_lock(conn)
+ row = conn.execute(
+ select(agents)
+ .where(agents.c.normalized_name == normalize_agent_name(name))
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return False
+ agent = self._from_row(row)
+ self._require_manageable_agent(
+ conn,
+ agent,
+ user_context=user_context,
+ )
+ if is_builtin_default_agent(agent):
+ raise ValueError(f"agent '{agent.name}' is built in and cannot be deleted")
+ result = conn.execute(agents.delete().where(agents.c.id == agent.id))
if result.rowcount:
resource_access_service.delete_resource_policy(conn, "agent", agent.id)
return bool(result.rowcount)
@@ -1612,7 +1651,6 @@ class VibeAgentStore:
user_context: Any = None,
) -> None:
normalized = normalize_agent_name(name)
- self.require_manageable(name, user_context=user_context)
now = _utc_now_iso()
with self.engine.begin() as conn:
reserve_write_lock(conn)
@@ -1624,6 +1662,11 @@ class VibeAgentStore:
f"agent '{name}' not found", agent_name=name, reason="missing"
)
agent = self._from_row(row)
+ self._require_manageable_agent(
+ conn,
+ agent,
+ user_context=user_context,
+ )
if not agent.enabled or agent.archived_at is not None:
raise AgentUnavailableError(
f"agent '{agent.name}' is disabled",
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index afd3a3f62..88de49145 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -158,6 +158,7 @@ def web_push_authorization_context_record(
"vibe_organization_member_id": context.organization_member_id,
"vibe_organization_role": context.organization_role,
"vibe_membership_version": context.membership_version,
+ "vibe_instance_authorization_revision": context.authorization_revision,
}
record.update({key: value for key, value in optional_claims.items() if value is not None})
return record
@@ -169,6 +170,15 @@ def _metadata_authorization_contexts(metadata: dict[str, Any]) -> dict[str, Auth
raw_contexts = metadata.get(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA)
if not isinstance(raw_contexts, list):
return {}
+ try:
+ from core.services import settings as settings_service
+
+ config = settings_service.load_config()
+ except FileNotFoundError:
+ config = None
+ except Exception:
+ logger.debug("web push: could not load authorization revision config", exc_info=True)
+ return {}
contexts: dict[str, AuthorizationContext] = {}
for raw_context in raw_contexts:
if not isinstance(raw_context, dict):
@@ -178,6 +188,13 @@ def _metadata_authorization_contexts(metadata: dict[str, Any]) -> dict[str, Auth
continue
if remote_access.session_needs_authorization_refresh(raw_context):
continue
+ if config is not None:
+ if not remote_access.session_authorization_is_current(config, raw_context):
+ continue
+ elif raw_context.get("vibe_instance_authorization_revision") is not None:
+ # A signed revision cannot be validated without the paired-device
+ # configuration and fresh local watermark.
+ 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
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index 876ebd2e8..729617cb7 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -371,7 +371,8 @@ def public_delivery_payload(row: dict[str, Any]) -> dict[str, Any]:
payload["metadata"] = {
key: value
for key, value in metadata.items()
- if not str(key).startswith(("_web_push_", "_memory_"))
+ if key != "resource_user_context"
+ and not str(key).startswith(("_web_push_", "_memory_"))
}
return payload
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 415ab9af3..5d3e33d8d 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -70,6 +70,7 @@ def _new_message_id() -> str:
_PRIVATE_WEB_PUSH_METADATA_PREFIX = "_web_push_"
+_PRIVATE_RESOURCE_USER_CONTEXT_KEY = "resource_user_context"
def _row_to_payload(
@@ -91,7 +92,8 @@ def _row_to_payload(
metadata = {
key: value
for key, value in metadata.items()
- if not str(key).startswith(_PRIVATE_WEB_PUSH_METADATA_PREFIX)
+ if key != _PRIVATE_RESOURCE_USER_CONTEXT_KEY
+ and not str(key).startswith(_PRIVATE_WEB_PUSH_METADATA_PREFIX)
}
return {
"id": row["id"],
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 45f6fba27..609f287a8 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -222,6 +222,8 @@ def metadata_with_resource_user_context(
"vibe_membership_version": context.membership_version,
"vibe_instance_role": context.instance_role,
"vibe_instance_access_source": context.instance_access_source,
+ "claims_issued_at": context.claims_issued_at,
+ "vibe_instance_authorization_revision": context.authorization_revision,
"authorization_expires_at": _resource_context_expires_at(context),
}
return result
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 91c7ace71..18883ff50 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -1434,14 +1434,3 @@ def set_agent_status(conn: Connection, session_id: str, status: str) -> bool:
update(agent_sessions).where(agent_sessions.c.id == session_id).values(agent_status=status)
)
return True
-
-
-def reset_running_agent_status(conn: Connection) -> int:
- """Reset legacy ``running`` projections to ``idle`` during recovery."""
-
- result = conn.execute(
- update(agent_sessions)
- .where(agent_sessions.c.agent_status == "running")
- .values(agent_status="idle")
- )
- return result.rowcount or 0
diff --git a/tests/test_caller_context.py b/tests/test_caller_context.py
index c702019b8..9db2d1530 100644
--- a/tests/test_caller_context.py
+++ b/tests/test_caller_context.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import json
+
import pytest
from core.caller_context import (
@@ -7,6 +9,8 @@ from core.caller_context import (
AVIBE_CALLER_CHANNEL_ID_ENV,
AVIBE_CALLER_MESSAGE_ID_ENV,
AVIBE_CALLER_PLATFORM_ENV,
+ AVIBE_CALLER_REMOTE_ENV,
+ AVIBE_CALLER_RESOURCE_CONTEXT_ENV,
AVIBE_CALLER_SESSION_KEY_ENV,
AVIBE_CALLER_SOURCE_ENV,
AVIBE_CALLER_USER_ID_ENV,
@@ -16,6 +20,7 @@ from core.caller_context import (
AVIBE_SESSION_ID_ENV,
caller_context_from_env,
caller_context_from_platform_payload,
+ caller_resource_user_context,
)
@@ -443,6 +448,73 @@ def test_a_session_scoped_caller_env_drops_only_the_per_turn_origin() -> None:
assert set(full) - set(scoped) == {AVIBE_CALLER_USER_ID_ENV, AVIBE_CALLER_MESSAGE_ID_ENV}
+def test_remote_workbench_caller_context_survives_env_and_claude_stable_form() -> None:
+ from modules.im import MessageContext
+
+ resource_context = {
+ "sub": "user-1",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_group_ids": ["group-engineering"],
+ "claims_issued_at": 1_900_000_000,
+ "vibe_instance_authorization_revision": 41,
+ "authorization_expires_at": 1_900_043_200,
+ }
+ payload = _agent_turn_payload(
+ {
+ "message_metadata": {"resource_user_context": resource_context},
+ }
+ )
+ context = caller_context_from_platform_payload(
+ payload,
+ message=MessageContext(
+ user_id="remote:user-1",
+ channel_id="proj-1",
+ platform="avibe",
+ ),
+ fallback_platform="avibe",
+ )
+
+ assert context is not None and context.is_remote is True
+ stable = context.session_stable()
+ assert stable.user_id is None
+ assert caller_resource_user_context(stable) == resource_context
+ env = stable.to_env()
+ assert env[AVIBE_CALLER_REMOTE_ENV] == "1"
+ assert json.loads(env[AVIBE_CALLER_RESOURCE_CONTEXT_ENV]) == resource_context
+ restored = caller_context_from_env(env)
+ assert restored is not None
+ assert caller_resource_user_context(restored) == resource_context
+
+
+def test_remote_workbench_caller_without_matching_snapshot_fails_closed() -> None:
+ from modules.im import MessageContext
+
+ context = caller_context_from_platform_payload(
+ _agent_turn_payload(
+ {
+ "message_metadata": {
+ "resource_user_context": {
+ "sub": "different-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ }
+ }
+ }
+ ),
+ message=MessageContext(
+ user_id="remote:user-1",
+ channel_id="proj-1",
+ platform="avibe",
+ ),
+ fallback_platform="avibe",
+ )
+
+ assert context is not None and context.is_remote is True
+ assert caller_resource_user_context(context) == {}
+
+
def test_a_dm_loses_nothing_to_the_session_scoped_form() -> None:
"""The case where the person IS the scope.
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 36982bb18..5eb9ef9bc 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -754,6 +754,17 @@ def test_task_add_records_caller_context_metadata(tmp_path: Path, capsys, monkey
"AVIBE_CALLER_SOURCE": "agent_turn",
"AVIBE_CALLER_BACKEND": "codex",
"AVIBE_NATIVE_SESSION_ID": "native-codex-1",
+ "AVIBE_CALLER_REMOTE": "1",
+ "AVIBE_CALLER_RESOURCE_CONTEXT": json.dumps(
+ {
+ "sub": "remote-editor",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_group_ids": [],
+ "claims_issued_at": 1_900_000_000,
+ "authorization_expires_at": 1_900_043_200,
+ }
+ ),
}
with (
@@ -780,6 +791,7 @@ def test_task_add_records_caller_context_metadata(tmp_path: Path, capsys, monkey
stored = cli.ScheduledTaskStore(store_path).get_task(payload["definition"]["id"])
assert stored is not None
assert stored.metadata["created_by"] == expected
+ assert stored.metadata["resource_user_context"]["sub"] == "remote-editor"
def test_task_add_create_per_run_scope_id_records_session_scope_metadata(tmp_path: Path, capsys) -> None:
@@ -4058,6 +4070,8 @@ _CALLER_CONTEXT_ENV_VARS = (
"AVIBE_CALLER_SESSION_KEY",
"AVIBE_CALLER_MESSAGE_ID",
"AVIBE_CALLER_WORKSPACE_ID",
+ "AVIBE_CALLER_REMOTE",
+ "AVIBE_CALLER_RESOURCE_CONTEXT",
)
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 39548820f..19bd9e6b2 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -442,6 +442,17 @@ def test_watch_add_records_caller_context_metadata(tmp_path: Path, capsys) -> No
"AVIBE_CALLER_SOURCE": "agent_turn",
"AVIBE_CALLER_BACKEND": "opencode",
"AVIBE_NATIVE_SESSION_ID": "native-opencode-1",
+ "AVIBE_CALLER_REMOTE": "1",
+ "AVIBE_CALLER_RESOURCE_CONTEXT": json.dumps(
+ {
+ "sub": "remote-editor",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_group_ids": [],
+ "claims_issued_at": 1_900_000_000,
+ "authorization_expires_at": 1_900_043_200,
+ }
+ ),
}
with (
@@ -469,6 +480,7 @@ def test_watch_add_records_caller_context_metadata(tmp_path: Path, capsys) -> No
stored = ManagedWatchStore(store_path).get_watch(payload["definition"]["id"])
assert stored is not None
assert stored.metadata["created_by"] == expected
+ assert stored.metadata["resource_user_context"]["sub"] == "remote-editor"
def test_watch_add_create_per_run_scope_id_records_session_scope_metadata(tmp_path: Path, capsys) -> None:
@@ -1850,6 +1862,8 @@ def _no_caller_context(monkeypatch) -> None:
same test would exercise a different path locally than in CI.
"""
monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)
+ monkeypatch.delenv("AVIBE_CALLER_REMOTE", raising=False)
+ monkeypatch.delenv("AVIBE_CALLER_RESOURCE_CONTEXT", raising=False)
def _reserved_session_cli_db(tmp_path: Path):
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index be584f6e5..2c1125e4f 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -76,7 +76,6 @@ def test_public_surface_is_stable():
"is_session_archived",
"list_sessions",
"list_sessions_page",
- "reset_running_agent_status",
"set_agent_status",
"touch_session",
"update_session",
@@ -116,7 +115,6 @@ def test_each_workbench_function_delegates_to_storage():
"get_session",
"is_session_archived",
"list_sessions",
- "reset_running_agent_status",
"set_agent_status",
"touch_session",
"update_session",
@@ -884,19 +882,3 @@ def test_workbench_default_action_drops_the_explicit_override_marker(isolated_st
f"dispatch handed the backend reasoning_effort="
f"{request.vibe_agent_reasoning_effort!r} instead of the default Agent's"
)
-
-
-def test_reset_running_agent_status_clears_only_running(isolated_state):
- """Startup recovery: stale ``running`` → ``idle``; failed/idle untouched."""
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- scope_id = _seed_avibe_scope(conn)
- running = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]
- failed = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]
- sessions_service.set_agent_status(conn, running, "running")
- sessions_service.set_agent_status(conn, failed, "failed")
- reset = sessions_service.reset_running_agent_status(conn)
- assert reset == 1
- with engine.connect() as conn:
- assert sessions_service.get_session(conn, running)["agent_status"] == "idle"
- assert sessions_service.get_session(conn, failed)["agent_status"] == "failed"
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 8439cd96b..3c3b7841e 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -63,12 +63,14 @@ def test_context_uses_role_not_diagnostic_source_for_owner() -> None:
"vibe_instance_id": "inst-1",
"vibe_instance_role": "editor",
"vibe_instance_access_source": "owner",
+ "vibe_instance_authorization_revision": 0,
}
)
assert context.is_instance_owner is False
assert context.can_chat is True
assert context.can_manage_instance is False
+ assert context.authorization_revision == 0
def test_malformed_role_context_fails_closed() -> None:
diff --git a/tests/test_message_handler_auth_setup.py b/tests/test_message_handler_auth_setup.py
index bc484c60d..e26391939 100644
--- a/tests/test_message_handler_auth_setup.py
+++ b/tests/test_message_handler_auth_setup.py
@@ -80,6 +80,9 @@ class _StubSessions:
self.recorded.append(key)
return True
+ def seed_legacy_claim(self, channel_id, thread_ts, message_ts):
+ self._claimed.add((channel_id, thread_ts, message_ts))
+
class _StubSettingsManager:
def __init__(self):
@@ -233,11 +236,7 @@ class MessageHandlerAuthSetupTests(unittest.IsolatedAsyncioTestCase):
)
handler = MessageHandler(controller)
handler._is_duplicate_human_delivery = Mock(
- side_effect=lambda context: controller.settings_manager.sessions.is_message_already_processed(
- context.channel_id,
- context.thread_id or context.message_id,
- context.message_id,
- )
+ side_effect=lambda context: handler._native_human_event_processed(context)
)
context = MessageContext(
user_id="U1",
@@ -252,7 +251,7 @@ class MessageHandlerAuthSetupTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(consumed, ["sk-opencode-secret"])
self.assertEqual(
controller.settings_manager.sessions.recorded,
- [("C1", "m-setup", "m-setup")],
+ [("im:slack:C1", "im:slack:m-setup", "im:slack:m-setup")],
)
self.assertEqual(
controller.agent_auth_service.maybe_consume_setup_reply.await_count,
diff --git a/tests/test_scheduled_command_task_integration.py b/tests/test_scheduled_command_task_integration.py
index c657d97c3..d8d073c35 100644
--- a/tests/test_scheduled_command_task_integration.py
+++ b/tests/test_scheduled_command_task_integration.py
@@ -21,6 +21,8 @@ from core.caller_context import (
AVIBE_CALLER_CHANNEL_ID_ENV,
AVIBE_CALLER_MESSAGE_ID_ENV,
AVIBE_CALLER_PLATFORM_ENV,
+ AVIBE_CALLER_REMOTE_ENV,
+ AVIBE_CALLER_RESOURCE_CONTEXT_ENV,
AVIBE_CALLER_SESSION_KEY_ENV,
AVIBE_CALLER_SOURCE_ENV,
AVIBE_CALLER_USER_ID_ENV,
@@ -48,6 +50,8 @@ _CALLER_ENV_VARS = (
AVIBE_CALLER_SESSION_KEY_ENV,
AVIBE_CALLER_MESSAGE_ID_ENV,
AVIBE_CALLER_WORKSPACE_ID_ENV,
+ AVIBE_CALLER_REMOTE_ENV,
+ AVIBE_CALLER_RESOURCE_CONTEXT_ENV,
)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 25af3fd51..43bc7d042 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -8183,6 +8183,8 @@ def test_drain_requests_reserves_watch_create_per_run_before_session_validation(
"task_id": "watch-1",
"trigger_kind": "watch",
"agent_name": "release-reviewer",
+ "metadata": {},
+ "user_context": None,
"_capture_dispatch_result": True,
}
]
@@ -8301,6 +8303,8 @@ def test_drain_requests_records_scheduled_create_per_run_reserved_session(tmp_pa
"task_id": task.id,
"trigger_kind": "scheduled",
"agent_name": "release-reviewer",
+ "metadata": {},
+ "user_context": None,
"_capture_dispatch_result": True,
}
]
@@ -8406,6 +8410,8 @@ def test_claimed_request_keeps_agent_identity_when_archive_lands_after_refresh(
"task_id": None,
"trigger_kind": "hook",
"agent_name": "pm",
+ "metadata": {},
+ "user_context": None,
"_capture_dispatch_result": True,
"agent_id": agent.id,
}
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 37c51acd4..3f65e90f5 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -264,6 +264,44 @@ def test_fifo_segment_starts_one_turn_and_materializes_one_merged_message(manage
assert stored["delivered_at"] == accepted[0]["materialized_at"]
+def test_memory_fifo_segment_merges_only_one_user(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ active_turn_id, _ = asyncio.run(_activate(manager, text="active"))
+ queued = [
+ asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content=text,
+ metadata={
+ "_memory_user_id": user_id,
+ "_memory_ordinary_text": True,
+ },
+ ),
+ context=_context(),
+ )
+ )
+ for text, user_id in (
+ ("alice one", "remote:alice"),
+ ("alice two", "remote:alice"),
+ ("bob one", "remote:bob"),
+ )
+ ]
+
+ assert asyncio.run(manager.terminalize_turn(active_turn_id))
+ queued_starts = [(turn_id, text) for turn_id, text in starts if turn_id != active_turn_id]
+ assert len(queued_starts) == 1
+ alice_turn_id, dispatch_text = queued_starts[0]
+ assert dispatch_text == "alice one\nalice two"
+
+ first, second, third = [_row(engine, str(item.delivery_id)) for item in queued]
+ assert first["turn_id"] == alice_turn_id
+ assert second["turn_id"] == alice_turn_id
+ assert third["turn_id"] is None
+ assert third["state"] == "queued"
+
+
def test_fifo_segment_does_not_merge_different_message_authors(managers) -> None:
manager, _other, engine, _engine_b, starts = managers
active_turn_id, _ = asyncio.run(_activate(manager, text="active"))
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index bd2dce624..598f7136a 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1455,7 +1455,7 @@ def test_detect_cli_sorts_prerelease_numerically_in_nvm(monkeypatch, tmp_path, o
assert result["path"] == str(rc10)
-def test_detect_cli_finds_codex_in_npm_global_prefix(monkeypatch, tmp_path):
+def test_detect_cli_finds_codex_in_npm_global_prefix(monkeypatch, tmp_path, only_tmp_binaries):
npm_path = tmp_path / "tools" / "npm"
npm_path.parent.mkdir(parents=True, exist_ok=True)
npm_path.write_text("#!/bin/sh\n")
@@ -2658,6 +2658,7 @@ def test_telegram_auth_test_returns_response(monkeypatch):
return {"id": 1, "username": "vibe_remote_bot"}
monkeypatch.setattr(api, "_telegram_get_me", fake_get_me)
+ monkeypatch.setattr("vibe.proxy.resolve_proxy", lambda proxy_url: proxy_url)
result = api.telegram_auth_test("123456:test-token")
@@ -2673,6 +2674,7 @@ def test_telegram_auth_test_uses_stored_token_when_request_omits_secret(monkeypa
monkeypatch.setattr(api, "_telegram_get_me", fake_get_me)
monkeypatch.setattr(api, "_stored_platform_secret", lambda platform, field: "123456:stored-token")
+ monkeypatch.setattr("vibe.proxy.resolve_proxy", lambda proxy_url: proxy_url)
result = api.telegram_auth_test("")
@@ -2833,7 +2835,7 @@ def test_vibe_agent_api_localizes_archive_refusal(tmp_path, monkeypatch):
def test_vibe_agent_api_localizes_invalid_reference_metadata_on_rename(monkeypatch):
class RefusingStore:
- def rename(self, _name, _new_name):
+ def rename(self, _name, _new_name, *, user_context=None):
raise api.AgentReferenceRewriteError()
def close(self):
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index 4b9c916fa..0c15c2fb6 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -218,7 +218,9 @@ def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tm
inbox = _get(client, "/api/inbox").get_json()
assert [row["session_id"] for row in inbox["sessions"]] == [ids["session_a"]]
assert set(inbox["unread_by_session"]) == {ids["session_a"]}
- assert _get(client, f"/api/media/{ids['media_a']}").status_code == 200
+ media_response = _get(client, f"/api/media/{ids['media_a']}")
+ assert media_response.status_code == 200
+ assert media_response.headers["Cache-Control"] == "private, no-store"
assert _get(client, f"/api/media/{ids['media_b']}").status_code == 404
show_pages = _get(client, "/api/show-pages").get_json()
assert show_pages["pages"] == [{"session_id": ids["session_a"]}]
@@ -510,7 +512,12 @@ def test_remote_message_persists_trusted_web_push_authorization_context(
"metadata": {
"_web_push_authorization_contexts": [
{"user_key": "remote:spoofed", "email": "[email protected]"}
- ]
+ ],
+ "resource_user_context": {
+ "sub": "spoofed",
+ "vibe_instance_role": "owner",
+ "vibe_instance_access_source": "owner",
+ },
},
},
)
@@ -518,6 +525,7 @@ def test_remote_message_persists_trusted_web_push_authorization_context(
assert response.status_code == 201
payload = response.get_json()
assert not any(key.startswith("_web_push_") for key in payload["metadata"])
+ assert "resource_user_context" not in payload["metadata"]
with engine.connect() as conn:
metadata_json = conn.execute(
@@ -539,9 +547,17 @@ def test_remote_message_persists_trusted_web_push_authorization_context(
"vibe_instance_role": "editor",
}
]
+ resource_context = persisted_metadata["resource_user_context"]
+ assert resource_context["sub"] == persisted_metadata["_web_push_user_key"].removeprefix(
+ "remote:"
+ )
+ assert resource_context["vibe_instance_role"] == "editor"
+ assert resource_context["vibe_instance_access_source"] == "owner"
+ assert resource_context["authorization_expires_at"] > resource_context["claims_issued_at"]
transcript = _get(client, f"/api/sessions/{ids['session_a']}/messages").get_json()
stored_payload = next(row for row in transcript["messages"] if row["id"] == payload["id"])
assert not any(key.startswith("_web_push_") for key in stored_payload["metadata"])
+ assert "resource_user_context" not in stored_payload["metadata"]
def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 8baf7cab1..c0e50f08f 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1335,6 +1335,8 @@ def test_project_patch_forwards_stable_agent_ids_and_localizes_conflicts(monkeyp
headers=csrf_headers(client),
)
+ authorization_context = captured.pop("authorization_context")
+ assert authorization_context.is_instance_owner
assert captured == {
"project_id": "proj-stale",
"display_name": None,
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 45bafbfaa..c18337765 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -172,6 +172,21 @@ def _settle_reserved_delivery(payload: dict, *, state: str) -> dict:
return settled
+def _accepted_dispatch(session_id: str):
+ async def dispatch(payload: dict) -> dict:
+ settled = _settle_reserved_delivery(payload, state="accepted")
+ return {
+ "status_code": 202,
+ "body": {
+ "ok": True,
+ "session_id": session_id,
+ "delivery_state": settled["state"],
+ },
+ }
+
+ return dispatch
+
+
def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
"""The web Chat POST persists the user row AND fire-and-forgets the turn via
``/internal/dispatch_async``. The reply arrives over the persistent
@@ -183,18 +198,7 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
_, session_id = _make_session(tmp_path)
- async def dispatch(payload):
- settled = _settle_reserved_delivery(payload, state="accepted")
- return {
- "status_code": 202,
- "body": {
- "ok": True,
- "session_id": session_id,
- "delivery_state": settled["state"],
- },
- }
-
- dispatch_mock = AsyncMock(side_effect=dispatch)
+ dispatch_mock = AsyncMock(side_effect=_accepted_dispatch(session_id))
with (
patch("vibe.internal_client.dispatch_async", dispatch_mock),
patch("vibe.ui_server._web_push_user_key", return_value="remote:user-a"),
@@ -238,9 +242,7 @@ def test_workbench_side_actions_are_not_marked_as_ordinary_memory_input(
from vibe.ui_server import app
_, session_id = _make_session(tmp_path)
- dispatch = AsyncMock(
- return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}}
- )
+ dispatch = AsyncMock(side_effect=_accepted_dispatch(session_id))
with patch("vibe.internal_client.dispatch_async", dispatch):
client = app.test_client()
response = client.post(
@@ -262,16 +264,11 @@ def test_workbench_memory_text_is_persisted_and_dispatched_as_ordinary_input(
from vibe.ui_server import app
_, session_id = _make_session(tmp_path)
- dispatch = AsyncMock(
- return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}}
- )
+ dispatch = AsyncMock(side_effect=_accepted_dispatch(session_id))
client = app.test_client()
headers = csrf_headers(client, "http://127.0.0.1:15131")
- with (
- patch("vibe.internal_client.dispatch_async", dispatch),
- patch.object(messages_service, "append", wraps=messages_service.append) as append,
- ):
+ with patch("vibe.internal_client.dispatch_async", dispatch):
response = client.post(
f"/api/sessions/{session_id}/messages",
json={"text": "/memory status"},
@@ -281,7 +278,10 @@ def test_workbench_memory_text_is_persisted_and_dispatched_as_ordinary_input(
)
assert response.status_code == 201
- append.assert_called_once()
+ with create_sqlite_engine().connect() as conn:
+ persisted = messages_service.get_message(conn, response.get_json()["id"])
+ assert persisted is not None
+ assert persisted["text"] == "/memory status"
payload = dispatch.await_args.args[0]
assert payload["text"] == "/memory status"
assert payload["user_id"] == "local"
@@ -319,9 +319,7 @@ def test_workbench_dispatch_propagates_attachment_and_resolved_identity(
from vibe.ui_server import app
_, session_id = _make_session(tmp_path)
- dispatch = AsyncMock(
- return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}}
- )
+ dispatch = AsyncMock(side_effect=_accepted_dispatch(session_id))
client = app.test_client()
headers = csrf_headers(client, "http://127.0.0.1:15131")
upload = client.post(
@@ -824,7 +822,8 @@ def test_create_and_patch_session_canonicalize_agent_identity(isolated_state, tm
cleared = cleared_response.get_json()
assert cleared["agent_id"] is None
assert cleared["agent_name"] is None
- assert cleared["agent_backend"] == ""
+ # Clearing the Agent selector does not clear the durable backend pin.
+ assert cleared["agent_backend"] == "codex"
def test_fork_session_creates_new_workbench_session(isolated_state, tmp_path):
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index 626a4e67d..20c9b0551 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -27,6 +27,21 @@ def _remote_authorization_record(user_key: str) -> dict:
return record
+def _paired_revision_config(revision: int):
+ from core.services.settings import default_config
+
+ config = default_config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.instance_id = "inst-push"
+ cloud.instance_secret = "device-secret"
+ cloud.backend_url = "https://backend.test"
+ config.save()
+ remote_access._clear_authorization_revision_cache()
+ remote_access._replace_authorization_revision(config, revision)
+ return config
+
+
def test_maybe_notify_inbox_message_schedules_agent_result(monkeypatch):
calls = []
@@ -316,6 +331,129 @@ def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeyp
]
+def test_send_to_enabled_subscriptions_rejects_stale_instance_authorization_revision(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_revision_config(41)
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-08-04T00:00:00Z"
+ authorization_record = web_push_notifications.web_push_authorization_context_record(
+ "remote:user-a",
+ AuthorizationContext(
+ instance_role="editor",
+ subject="user-a",
+ instance_access_source="email",
+ claims_issued_at=int(web_push_notifications.time.time()),
+ authorization_revision=41,
+ is_remote=True,
+ ),
+ )
+ assert authorization_record is not None
+ assert authorization_record["vibe_instance_authorization_revision"] == 41
+
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_revision",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_push_revision",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_push_revision",
+ native_session_id="",
+ title="Revision Push",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_revision",
+ 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",
+ )
+ first_result = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_revision",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done before revocation",
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:user-a",
+ payload={
+ "endpoint": "https://push.example.test/revision",
+ "keys": {"p256dh": "revision-key", "auth": "revision-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": "Revision Push",
+ "body": "Done before revocation",
+ "session_id": "ses_push_revision",
+ "message_id": first_result["id"],
+ }
+ )
+ assert len(sends) == 1
+
+ remote_access._replace_authorization_revision(config, 42)
+ with engine.begin() as conn:
+ stale_result = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_push_revision",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done after revocation",
+ )
+ web_push_notifications._send_to_enabled_subscriptions(
+ {
+ "title": "Revision Push",
+ "body": "Done after revocation",
+ "session_id": "ses_push_revision",
+ "message_id": stale_result["id"],
+ }
+ )
+
+ assert len(sends) == 1
+ engine.dispose()
+
+
def test_send_to_enabled_subscriptions_rechecks_restricted_project_access(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
ensure_sqlite_state()
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 97f0fdc42..927de9251 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -50,6 +50,7 @@ class AuthorizationContext:
group_ids: frozenset[str] = frozenset()
membership_version: str | None = None
claims_issued_at: int | None = None
+ authorization_revision: int | None = None
is_remote: bool = False
is_trusted_local: bool = False
@@ -157,6 +158,16 @@ def _optional_positive_int(value: Any) -> int | None:
return parsed if parsed > 0 else None
+def _optional_nonnegative_int(value: Any) -> int | None:
+ if isinstance(value, bool):
+ return None
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ return None
+ return parsed if parsed >= 0 else None
+
+
def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationContext:
role = _optional_string(payload.get("vibe_instance_role", payload.get("instance_role")))
if role not in INSTANCE_ROLES:
@@ -197,6 +208,12 @@ def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationCon
claims_issued_at=_optional_positive_int(
payload.get("claims_issued_at", payload.get("iat"))
),
+ authorization_revision=_optional_nonnegative_int(
+ payload.get(
+ "vibe_instance_authorization_revision",
+ payload.get("authorization_revision"),
+ )
+ ),
is_remote=True,
)
diff --git a/vibe/cli.py b/vibe/cli.py
index 3419b9b38..77bf7cd7f 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -47,7 +47,7 @@ from core.scheduled_tasks import (
resolve_session_id_target,
session_anchor_for_target,
)
-from core.caller_context import caller_context_from_env
+from core.caller_context import caller_context_from_env, caller_resource_user_context
from core.command_runner import command_line_preview
from core.vibe_agents import AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
@@ -3374,6 +3374,7 @@ def cmd_task_add(args):
reserved_session_id: Optional[str] = None
try:
caller_context = caller_context_from_env()
+ caller_user_context = caller_resource_user_context(caller_context)
command, shell_command, has_command = _resolve_task_command(
args,
help_command="vibe task add --help",
@@ -3549,6 +3550,7 @@ def cmd_task_add(args):
metadata=metadata,
expected_enabled_agent_id=expected_enabled_agent_id,
expected_reference_agent_id=expected_reference_agent_id,
+ user_context=caller_user_context,
)
else:
try:
@@ -3581,6 +3583,7 @@ def cmd_task_add(args):
metadata=metadata,
expected_enabled_agent_id=expected_enabled_agent_id,
expected_reference_agent_id=expected_reference_agent_id,
+ user_context=caller_user_context,
)
reserved_session_id = None
warnings = _collect_target_warnings(session_target, delivery_target)
@@ -3972,6 +3975,7 @@ def cmd_task_update(args):
help_command="vibe task update --help",
)
caller_context = caller_context_from_env()
+ caller_user_context = caller_resource_user_context(caller_context)
scope_arg_present = (getattr(args, "scope_id", None) is not None) or bool(getattr(args, "same_scope", False))
if scope_arg_present and not (
bool(getattr(args, "create_session", False)) or bool(getattr(args, "create_session_per_run", False))
@@ -4279,6 +4283,7 @@ def cmd_task_update(args):
metadata=metadata,
expected_enabled_agent_id=expected_enabled_agent_id,
expected_reference_agent_id=expected_reference_agent_id,
+ user_context=caller_user_context,
)
reserved_session_id = None
warnings = _collect_target_warnings(session_target, delivery_target)
@@ -9377,6 +9382,7 @@ def cmd_watch_add(args):
reserved_session_id: Optional[str] = None
try:
caller_context = caller_context_from_env()
+ caller_user_context = caller_resource_user_context(caller_context)
session_default_notice = _apply_caller_session_default(
args,
caller_context,
@@ -9478,6 +9484,7 @@ def cmd_watch_add(args):
metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=session_workdir),
expected_enabled_agent_id=expected_enabled_agent_id,
expected_reference_agent_id=expected_reference_agent_id,
+ user_context=caller_user_context,
)
reserved_session_id = None
runtime_store = _watch_runtime_store()
@@ -9602,6 +9609,7 @@ def cmd_watch_update(args):
help_command="vibe watch update --help",
)
caller_context = caller_context_from_env()
+ caller_user_context = caller_resource_user_context(caller_context)
scope_arg_present = (getattr(args, "scope_id", None) is not None) or bool(getattr(args, "same_scope", False))
if scope_arg_present and not (
bool(getattr(args, "create_session", False)) or bool(getattr(args, "create_session_per_run", False))
@@ -9906,6 +9914,7 @@ def cmd_watch_update(args):
**changes,
expected_enabled_agent_id=expected_enabled_agent_id,
expected_reference_agent_id=expected_reference_agent_id,
+ user_context=caller_user_context,
)
reserved_session_id = None
runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index fd0b4213f..ac4aba73c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9168,18 +9168,10 @@ def _registered_media_response(
response = send_file(candidate, mimetype=mime_type)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "no-referrer"
- # Cache for a bounded window so re-renders / scrolling / re-opening the chat
- # reuse the bytes instead of re-fetching — but do NOT promise immutability: a
- # token maps to a MUTABLE ``local_path`` (an agent can overwrite a file in
- # place), so an eternal ``immutable`` cache could pin stale bytes in one
- # client while another reads new bytes from disk. Cheap revalidation isn't an
- # option here — Starlette's FileResponse doesn't emit 304s (verified; it
- # re-sends 200), so ``must-revalidate`` would force a full re-download every
- # time and reintroduce the very re-fetch this avoids. A short max-age is the
- # balance: no re-fetch during active use, and any stale/split window is
- # bounded to an hour, after which the next fetch re-reads the current file.
- # ``private`` because the file is auth-gated (served only to its user).
- response.headers["Cache-Control"] = "private, max-age=3600"
+ # Authorization is checked on every request and can change independently of
+ # the opaque token. Browser-profile account switching must not reuse bytes
+ # cached under a previous remote identity.
+ response.headers["Cache-Control"] = "private, no-store"
filename = row.get("file_name") or candidate.name
# Force download for non-allowlisted (active) types even without ?download=1,
# so previewing an agent-produced HTML/SVG can't run script on this origin.
@@ -9596,7 +9588,7 @@ async def sessions_messages_create(session_id: str):
web_push_authorization_context_record,
)
from modules.im.message_facts import is_ordinary_workbench_text
- from storage import messages_service
+ from storage import messages_service, resource_access_service
from storage.agent_session_rows import session_is_runtime_owned
from vibe import internal_client
@@ -9655,7 +9647,7 @@ async def sessions_messages_create(session_id: str):
except LookupError as err:
return jsonify({"error": str(err)}), 404
except PermissionError as err:
- return jsonify({"error": str(err), "code": "agent_access_forbidden"}), 403
+ return _coded_error_response("agent_access_forbidden", str(err), 403)
dispatch_text = (
(text if isinstance(text, str) else None)
@@ -9686,13 +9678,16 @@ async def sessions_messages_create(session_id: str):
if workbench_sessions_service.is_session_archived(conn, session_id):
return None
delivery_id = message_deliveries.new_delivery_id()
- message_metadata = {
- **(payload.get("metadata") or {}),
- "_web_push_user_key": web_push_user_key,
- "_memory_user_id": memory_user_id,
- "_memory_cli_admitted": memory_cli_admitted,
- "_memory_ordinary_text": memory_ordinary_text,
- }
+ message_metadata = resource_access_service.metadata_with_resource_user_context(
+ {
+ **(payload.get("metadata") or {}),
+ "_web_push_user_key": web_push_user_key,
+ "_memory_user_id": memory_user_id,
+ "_memory_cli_admitted": memory_cli_admitted,
+ "_memory_ordinary_text": memory_ordinary_text,
+ },
+ getattr(g, "authorization_context", None),
+ )
message_metadata.pop(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA, None)
if web_push_authorization_context is not None:
message_metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = [