Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(channels): operator-gate IM /pairing control plane (GHSA-fwpw)

Haozhe Wua8f75628d685
diff --git a/README.md b/README.md
index 7c502bbc7..ab94f6cc1 100644
--- a/README.md
+++ b/README.md
@@ -790,10 +790,12 @@ The built-in adapters cover `websocket`, `telegram`, `slack`, `discord`, `matrix
| `/new` | Reset the current session — the next message starts a fresh conversation |
| `/reset` | Alias for `/new` |
| `/newsession` | Alias for `/new` |
-| `/pairing list` | Show pending sender-pairing requests |
+| `/pairing list` | Show pending sender-pairing requests (operators only) |
Commands are case-insensitive and must be sent as the entire message (e.g. `hello /new` is treated as a regular message, not a reset).
+> **`/pairing` is operator-gated.** In-chat pairing-control commands are rejected unless the sender is listed as an operator — set `channels.operators` (cross-channel authority) or a channel section's own `operators` list in your channels config. With no operators configured, in-chat `/pairing` is refused (fail-closed) and pairing is managed only through the authenticated CLI (`vibe-trading channels pairing …`) and the auth-gated REST endpoint. This prevents any allow-listed group member from taking over pairing across channels.
+
</details>
---
diff --git a/agent/src/api/state.py b/agent/src/api/state.py
index c4350d8b8..469e14cbb 100644
--- a/agent/src/api/state.py
+++ b/agent/src/api/state.py
@@ -95,11 +95,14 @@ def _get_channel_runtime():
_channel_bus = MessageBus()
config = load_channels_config()
_channel_manager = ChannelManager(config, _channel_bus, session_service=svc)
+ global_operators, channel_operators = ChannelRuntime.operators_from_config(config)
_channel_runtime = ChannelRuntime(
bus=_channel_bus,
session_service=svc,
manager=_channel_manager,
reply_timeout_s=config["reply_timeout_s"],
+ operators=global_operators,
+ channel_operators=channel_operators,
)
_set_host_attr("_channel_runtime", _channel_runtime)
_set_host_attr("_channel_bus", _channel_bus)
diff --git a/agent/src/channels/pairing/store.py b/agent/src/channels/pairing/store.py
index b75f74377..20c47ca32 100644
--- a/agent/src/channels/pairing/store.py
+++ b/agent/src/channels/pairing/store.py
@@ -103,19 +103,30 @@ def generate_code(
return code
-def approve_code(code: str) -> tuple[str, str] | None:
+def approve_code(code: str, *, restrict_channel: str | None = None) -> tuple[str, str] | None:
"""Approve a pending pairing code.
+ Args:
+ code: The pairing code to approve.
+ restrict_channel: When set, only approve the code if its pending
+ request belongs to this channel. A code on a different channel is
+ treated as not-found (returns ``None``) so callers scoped to one
+ channel cannot approve — or even probe the existence of — pairing
+ requests on other channels.
+
Returns ``(channel, sender_id)`` on success, or ``None`` if the code
- does not exist or has expired.
+ does not exist, has expired, or is out of the requested channel scope.
"""
with _LOCK:
data = _load()
_gc_pending(data)
pending: dict[str, Any] = data.get("pending", {})
- info = pending.pop(code, None)
+ info = pending.get(code)
if info is None:
return None
+ if restrict_channel is not None and info.get("channel") != restrict_channel:
+ return None
+ del pending[code]
channel = info["channel"]
sender_id = str(info["sender_id"])
data.setdefault("approved", {}).setdefault(channel, set()).add(sender_id)
@@ -124,21 +135,30 @@ def approve_code(code: str) -> tuple[str, str] | None:
return channel, sender_id
-def deny_code(code: str) -> bool:
+def deny_code(code: str, *, restrict_channel: str | None = None) -> bool:
"""Reject and discard a pending pairing code.
- Returns ``True`` if the code existed and was removed.
+ Args:
+ code: The pairing code to deny.
+ restrict_channel: When set, only deny the code if its pending request
+ belongs to this channel; a code on another channel is treated as
+ not-found (returns ``False``).
+
+ Returns ``True`` if the code existed (within scope) and was removed.
"""
with _LOCK:
data = _load()
_gc_pending(data)
pending: dict[str, Any] = data.get("pending", {})
- if code in pending:
- del pending[code]
- _save(data)
- logger.info("Denied pairing code %s", code)
- return True
- return False
+ info = pending.get(code)
+ if info is None:
+ return False
+ if restrict_channel is not None and info.get("channel") != restrict_channel:
+ return False
+ del pending[code]
+ _save(data)
+ logger.info("Denied pairing code %s", code)
+ return True
def is_approved(channel: str, sender_id: str) -> bool:
@@ -149,14 +169,21 @@ def is_approved(channel: str, sender_id: str) -> bool:
return str(sender_id) in approved.get(channel, set())
-def list_pending() -> list[dict[str, Any]]:
- """Return all non-expired pending pairing requests."""
+def list_pending(restrict_channel: str | None = None) -> list[dict[str, Any]]:
+ """Return non-expired pending pairing requests.
+
+ Args:
+ restrict_channel: When set, return only requests for this channel.
+ Used to scope a per-channel operator's view so they cannot see
+ pending codes or sender IDs from other channels.
+ """
with _LOCK:
data = _load()
_gc_pending(data)
return [
{"code": code, **info}
for code, info in data.get("pending", {}).items()
+ if restrict_channel is None or info.get("channel") == restrict_channel
]
@@ -203,18 +230,45 @@ def format_expiry(expires_at: float) -> str:
return f"{remaining}s" if remaining > 0 else "expired"
-def handle_pairing_command(channel: str, subcommand_text: str) -> str:
+def handle_pairing_command(
+ channel: str,
+ subcommand_text: str,
+ *,
+ requesting_channel: str | None = None,
+ is_global_operator: bool = True,
+) -> str:
"""Execute a pairing subcommand and return the reply text.
This is a pure function (no side effects other than store mutations)
- so it can be used from both the CLI and the agent CommandRouter.
+ so it can be used from the CLI, the REST admin endpoint, and the IM
+ channel runtime.
+
+ Args:
+ channel: The default channel used for single-argument ``revoke``.
+ subcommand_text: The pairing subcommand and its arguments.
+ requesting_channel: The channel the command arrived on. Used together
+ with ``is_global_operator`` to scope a non-global operator to a
+ single channel. ``None`` (the default) applies no channel scope.
+ is_global_operator: ``True`` (the default) grants cross-channel
+ authority and full request details — this is the behavior for the
+ authenticated CLI/REST admin plane and for configured global
+ operators. ``False`` restricts the caller to ``requesting_channel``:
+ ``list`` shows only that channel, ``approve``/``deny`` act only on
+ codes for that channel, and cross-channel ``revoke`` is refused.
+
+ Returns:
+ The reply text to send back to the caller.
"""
parts = subcommand_text.split()
sub = parts[0].lower() if parts else "list"
arg = parts[1] if len(parts) > 1 else None
+ # Non-global operators are pinned to the channel the command arrived on so
+ # they cannot read, approve, or revoke pairing state on other channels.
+ scope = None if is_global_operator else requesting_channel
+
if sub in ("list",):
- pending = list_pending()
+ pending = list_pending(restrict_channel=scope)
if not pending:
return "No pending pairing requests."
lines = ["Pending pairing requests:"]
@@ -228,7 +282,7 @@ def handle_pairing_command(channel: str, subcommand_text: str) -> str:
elif sub == "approve":
if arg is None:
return "Usage: `/pairing approve <code>`"
- result = approve_code(arg)
+ result = approve_code(arg, restrict_channel=scope)
if result is None:
return f"Invalid or expired pairing code: `{arg}`"
ch, sid = result
@@ -237,7 +291,7 @@ def handle_pairing_command(channel: str, subcommand_text: str) -> str:
elif sub == "deny":
if arg is None:
return "Usage: `/pairing deny <code>`"
- if deny_code(arg):
+ if deny_code(arg, restrict_channel=scope):
return f"Denied pairing code `{arg}`"
return f"Pairing code `{arg}` not found or already expired"
@@ -249,6 +303,8 @@ def handle_pairing_command(channel: str, subcommand_text: str) -> str:
else f"{arg} was not in the approved list for {channel}"
)
if len(parts) == 3:
+ if not is_global_operator and parts[1] != requesting_channel:
+ return "Not authorized: cross-channel revoke requires a global operator."
return (
f"Revoked {parts[2]} from {arg}"
if revoke(arg, parts[2])
diff --git a/agent/src/channels/runtime.py b/agent/src/channels/runtime.py
index c7546b300..337f8c52c 100644
--- a/agent/src/channels/runtime.py
+++ b/agent/src/channels/runtime.py
@@ -7,6 +7,7 @@ import json
import logging
import time
from contextlib import suppress
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -41,6 +42,8 @@ class ChannelRuntime:
session_map_path: Path | None = None,
reply_timeout_s: float = 600.0,
poll_interval_s: float = 0.25,
+ operators: Iterable[str] | None = None,
+ channel_operators: Mapping[str, Iterable[str]] | None = None,
) -> None:
self.bus = bus
self.session_service = session_service
@@ -49,6 +52,15 @@ class ChannelRuntime:
reply_timeout_s=reply_timeout_s,
poll_interval_s=poll_interval_s,
)
+ # Channel-independent (global) operators may run /pairing on any channel
+ # with cross-channel authority. Per-channel operators may run /pairing
+ # only on their own channel. Both empty by default → IM /pairing is
+ # fail-closed and pairing is managed via the authenticated CLI/REST plane.
+ self._operators: set[str] = {str(o) for o in (operators or ())}
+ self._channel_operators: dict[str, set[str]] = {
+ str(ch): {str(o) for o in ops}
+ for ch, ops in (channel_operators or {}).items()
+ }
self.session_map_path = session_map_path or (get_data_dir() / "channels" / "sessions.json")
self._session_map: dict[str, str] = {}
self._consumer_task: asyncio.Task[None] | None = None
@@ -108,7 +120,31 @@ class ChannelRuntime:
async def _handle_inbound(self, msg: InboundMessage) -> None:
try:
if self._is_pairing_command(msg.content):
- reply = handle_pairing_command(msg.channel, self._pairing_subcommand_text(msg.content))
+ is_operator, is_global = self._resolve_operator(msg.channel, msg.sender_id)
+ if not is_operator:
+ logger.warning(
+ "Rejected /pairing from non-operator %s on %s",
+ msg.sender_id,
+ msg.channel,
+ )
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=(
+ "Not authorized: pairing management is restricted to "
+ "configured operators."
+ ),
+ metadata={PAIRING_COMMAND_META_KEY: True, "unauthorized": True},
+ )
+ )
+ return
+ reply = handle_pairing_command(
+ msg.channel,
+ self._pairing_subcommand_text(msg.content),
+ requesting_channel=msg.channel,
+ is_global_operator=is_global,
+ )
await self.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
@@ -232,6 +268,48 @@ class ChannelRuntime:
self._save_session_map()
return removed
+ def _resolve_operator(self, channel: str, sender_id: str | None) -> tuple[bool, bool]:
+ """Resolve pairing authorization for a sender.
+
+ Args:
+ channel: The channel the command arrived on.
+ sender_id: The inbound message sender id.
+
+ Returns:
+ ``(is_operator, is_global_operator)``. ``is_operator`` is ``True``
+ for global operators or per-channel operators of ``channel``;
+ ``is_global_operator`` is ``True`` only for channel-independent
+ operators, who may act cross-channel with full request details.
+ """
+ sid = str(sender_id)
+ is_global = sid in self._operators
+ is_channel = sid in self._channel_operators.get(channel, set())
+ return (is_global or is_channel, is_global)
+
+ @staticmethod
+ def operators_from_config(
+ config: Mapping[str, Any] | None,
+ ) -> tuple[set[str], dict[str, set[str]]]:
+ """Extract global and per-channel operators from a channels config dict.
+
+ Args:
+ config: The channels config mapping (as produced by
+ ``ChannelsConfig.model_dump``). Top-level ``operators`` are
+ global; a per-channel section's own ``operators`` list is
+ channel-scoped.
+
+ Returns:
+ ``(global_operators, channel_operators)``.
+ """
+ if not config:
+ return set(), {}
+ global_ops = {str(o) for o in (config.get("operators") or ())}
+ channel_ops: dict[str, set[str]] = {}
+ for key, value in config.items():
+ if isinstance(value, Mapping) and value.get("operators"):
+ channel_ops[str(key)] = {str(o) for o in value["operators"]}
+ return global_ops, channel_ops
+
@staticmethod
def _is_pairing_command(content: str) -> bool:
stripped = content.strip().lower()
diff --git a/agent/src/channels/signal.py b/agent/src/channels/signal.py
index e56cfd8e1..f915f0d7e 100644
--- a/agent/src/channels/signal.py
+++ b/agent/src/channels/signal.py
@@ -849,6 +849,24 @@ class SignalChannel(BaseChannel):
)
is_command = bool(message_text and message_text.strip().startswith("/"))
+ is_control_plane = is_command and message_text.strip().lower().startswith("/pairing")
+ if is_control_plane:
+ # Control-plane commands (/pairing) must never be authorized by
+ # group membership alone: require the sender to pass the
+ # per-sender allowlist, otherwise any member of an allowed group
+ # could drive pairing takeover. The runtime operator gate is the
+ # authoritative check; this just avoids even publishing an
+ # unauthorized control-plane command. Ordinary commands
+ # (/new, /reset) keep their existing group behavior — no
+ # asymmetry vs other channels.
+ if not self.is_allowed(sender_id):
+ self.logger.info(
+ "Ignoring group control-plane command from unauthorized sender {} in {}",
+ sender_id,
+ chat_id,
+ )
+ return False, chat_id
+ return True, chat_id
if not is_command and not self._should_respond_in_group(message_text, mentions):
self.logger.info(
"Ignoring group message (require_mention: {})",
diff --git a/agent/src/config/schema.py b/agent/src/config/schema.py
index 13c5d0f74..8062dadeb 100644
--- a/agent/src/config/schema.py
+++ b/agent/src/config/schema.py
@@ -440,6 +440,13 @@ class ChannelsConfig(ConfigBase):
send_tool_hints: bool = False
send_max_retries: int = Field(default=2, ge=1, le=10)
reply_timeout_s: float = Field(default=600.0, ge=1.0, le=86400.0)
+ # Channel-independent operator allowlist. Sender IDs listed here may run
+ # ``/pairing`` control-plane commands from any IM channel with cross-channel
+ # authority. Empty by default (fail closed): with no operators configured,
+ # IM ``/pairing`` is rejected and pairing is managed only through the
+ # authenticated CLI/REST admin plane. Per-channel operators (channel-scoped
+ # authority) live under each channel section's own ``operators`` list.
+ operators: list[str] = Field(default_factory=list)
class AgentConfig(ConfigBase):
diff --git a/agent/tests/test_channels_runtime.py b/agent/tests/test_channels_runtime.py
index 796210312..e8ec771bc 100644
--- a/agent/tests/test_channels_runtime.py
+++ b/agent/tests/test_channels_runtime.py
@@ -289,9 +289,10 @@ def test_channel_runtime_routes_inbound_to_session_and_outbound(tmp_path: Path)
def test_channel_runtime_handles_pairing_commands_without_agent(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
async def scenario() -> None:
+ from src.channels.pairing import store as pairing_store
from src.channels.runtime import ChannelRuntime
- monkeypatch.setenv("VIBE_TRADING_DATA_DIR", str(tmp_path / "data"))
+ monkeypatch.setattr(pairing_store, "_store_path", lambda: tmp_path / "pairing.json")
bus = MessageBus()
service = FakeSessionService()
runtime = ChannelRuntime(
@@ -301,6 +302,7 @@ def test_channel_runtime_handles_pairing_commands_without_agent(tmp_path: Path,
session_map_path=tmp_path / "channel_sessions.json",
reply_timeout_s=1,
poll_interval_s=0.01,
+ operators=["owner"],
)
await runtime.start(start_manager=False)
try:
@@ -325,6 +327,269 @@ def test_channel_runtime_handles_pairing_commands_without_agent(tmp_path: Path,
asyncio.run(scenario())
+def test_channel_runtime_rejects_pairing_from_non_operator(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A non-operator /pairing command is refused without touching the store (GHSA-fwpw)."""
+
+ async def scenario() -> None:
+ from src.channels import pairing
+ from src.channels.pairing import store as pairing_store
+ from src.channels.runtime import ChannelRuntime
+
+ monkeypatch.setattr(pairing_store, "_store_path", lambda: tmp_path / "pairing.json")
+ # A pending code exists on another channel; a non-operator must not be
+ # able to approve it or even learn it exists.
+ code = pairing.generate_code("signal", "victim-sender")
+
+ bus = MessageBus()
+ service = FakeSessionService()
+ runtime = ChannelRuntime(
+ bus=bus,
+ session_service=service,
+ manager=None,
+ session_map_path=tmp_path / "channel_sessions.json",
+ reply_timeout_s=1,
+ poll_interval_s=0.01,
+ operators=["owner"],
+ )
+ await runtime.start(start_manager=False)
+ try:
+ await bus.publish_inbound(
+ InboundMessage(
+ channel="telegram",
+ sender_id="stranger",
+ chat_id="chat-1",
+ content=f"/pairing approve {code}",
+ )
+ )
+ outbound = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
+ finally:
+ await runtime.stop()
+
+ assert service.sent == []
+ assert outbound.metadata.get("unauthorized") is True
+ assert "Not authorized" in outbound.content
+ # The code must NOT have been consumed by the rejected attempt.
+ assert pairing.is_approved("signal", "victim-sender") is False
+ assert any(item["code"] == code for item in pairing.list_pending())
+
+ asyncio.run(scenario())
+
+
+def test_channel_runtime_operator_can_pair(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A configured operator can approve a pending pairing code end to end."""
+
+ async def scenario() -> None:
+ from src.channels import pairing
+ from src.channels.pairing import store as pairing_store
+ from src.channels.runtime import ChannelRuntime
+
+ monkeypatch.setattr(pairing_store, "_store_path", lambda: tmp_path / "pairing.json")
+ code = pairing.generate_code("telegram", "new-user")
+
+ bus = MessageBus()
+ service = FakeSessionService()
+ runtime = ChannelRuntime(
+ bus=bus,
+ session_service=service,
+ manager=None,
+ session_map_path=tmp_path / "channel_sessions.json",
+ reply_timeout_s=1,
+ poll_interval_s=0.01,
+ operators=["owner"],
+ )
+ await runtime.start(start_manager=False)
+ try:
+ await bus.publish_inbound(
+ InboundMessage(
+ channel="telegram",
+ sender_id="owner",
+ chat_id="chat-1",
+ content=f"/pairing approve {code}",
+ )
+ )
+ outbound = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
+ finally:
+ await runtime.stop()
+
+ assert outbound.metadata.get("unauthorized") is not True
+ assert "Approved pairing code" in outbound.content
+ assert pairing.is_approved("telegram", "new-user") is True
+
+ asyncio.run(scenario())
+
+
+def test_channel_runtime_channel_operator_cannot_act_cross_channel(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A per-channel (non-global) operator cannot approve codes on other channels."""
+
+ async def scenario() -> None:
+ from src.channels import pairing
+ from src.channels.pairing import store as pairing_store
+ from src.channels.runtime import ChannelRuntime
+
+ monkeypatch.setattr(pairing_store, "_store_path", lambda: tmp_path / "pairing.json")
+ # Pending code lives on signal; the operator is scoped to telegram only.
+ code = pairing.generate_code("signal", "signal-victim")
+
+ bus = MessageBus()
+ service = FakeSessionService()
+ runtime = ChannelRuntime(
+ bus=bus,
+ session_service=service,
+ manager=None,
+ session_map_path=tmp_path / "channel_sessions.json",
+ reply_timeout_s=1,
+ poll_interval_s=0.01,
+ channel_operators={"telegram": ["tg-op"]},
+ )
+ await runtime.start(start_manager=False)
+ try:
+ # 1) Approve attempt against another channel's code is refused and
+ # does not consume the code (no cross-channel oracle).
+ await bus.publish_inbound(
+ InboundMessage(
+ channel="telegram",
+ sender_id="tg-op",
+ chat_id="chat-1",
+ content=f"/pairing approve {code}",
+ )
+ )
+ approve_reply = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
+
+ # 2) list must not leak the other channel's pending request.
+ await bus.publish_inbound(
+ InboundMessage(
+ channel="telegram",
+ sender_id="tg-op",
+ chat_id="chat-1",
+ content="/pairing list",
+ )
+ )
+ list_reply = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
+
+ # 3) explicit cross-channel revoke is refused.
+ await bus.publish_inbound(
+ InboundMessage(
+ channel="telegram",
+ sender_id="tg-op",
+ chat_id="chat-1",
+ content="/pairing revoke signal signal-victim",
+ )
+ )
+ revoke_reply = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
+ finally:
+ await runtime.stop()
+
+ assert "Invalid or expired pairing code" in approve_reply.content
+ assert pairing.is_approved("signal", "signal-victim") is False
+ assert any(item["code"] == code for item in pairing.list_pending())
+
+ assert code not in list_reply.content
+ assert "signal-victim" not in list_reply.content
+
+ assert "Not authorized" in revoke_reply.content
+
+ asyncio.run(scenario())
+
+
+def test_channel_runtime_pairing_fail_closed_when_no_operators_configured(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """With no operators configured, ALL in-chat /pairing is rejected (fail-closed)."""
+
+ async def scenario() -> None:
+ from src.channels import pairing
+ from src.channels.pairing import store as pairing_store
+ from src.channels.runtime import ChannelRuntime
+
+ monkeypatch.setattr(pairing_store, "_store_path", lambda: tmp_path / "pairing.json")
+ code = pairing.generate_code("telegram", "new-user")
+
+ bus = MessageBus()
+ service = FakeSessionService()
+ runtime = ChannelRuntime(
+ bus=bus,
+ session_service=service,
+ manager=None,
+ session_map_path=tmp_path / "channel_sessions.json",
+ reply_timeout_s=1,
+ poll_interval_s=0.01,
+ # operators / channel_operators both unset -> fail closed.
+ )
+ await runtime.start(start_manager=False)
+ try:
+ await bus.publish_inbound(
+ InboundMessage(
+ channel="telegram",
+ sender_id="anyone",
+ chat_id="chat-1",
+ content=f"/pairing approve {code}",
+ )
+ )
+ outbound = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
+ finally:
+ await runtime.stop()
+
+ assert outbound.metadata.get("unauthorized") is True
+ assert "Not authorized" in outbound.content
+ # Nothing was approved; the pending code survives untouched.
+ assert pairing.is_approved("telegram", "new-user") is False
+ assert any(item["code"] == code for item in pairing.list_pending())
+
+ asyncio.run(scenario())
+
+
+def test_channel_runtime_non_operator_list_does_not_leak_codes(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A non-operator's rejected /pairing list must not disclose codes or sender ids."""
+
+ async def scenario() -> None:
+ from src.channels import pairing
+ from src.channels.pairing import store as pairing_store
+ from src.channels.runtime import ChannelRuntime
+
+ monkeypatch.setattr(pairing_store, "_store_path", lambda: tmp_path / "pairing.json")
+ code = pairing.generate_code("signal", "victim-sender")
+
+ bus = MessageBus()
+ service = FakeSessionService()
+ runtime = ChannelRuntime(
+ bus=bus,
+ session_service=service,
+ manager=None,
+ session_map_path=tmp_path / "channel_sessions.json",
+ reply_timeout_s=1,
+ poll_interval_s=0.01,
+ operators=["owner"],
+ )
+ await runtime.start(start_manager=False)
+ try:
+ await bus.publish_inbound(
+ InboundMessage(
+ channel="telegram",
+ sender_id="stranger",
+ chat_id="chat-1",
+ content="/pairing list",
+ )
+ )
+ outbound = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
+ finally:
+ await runtime.stop()
+
+ assert outbound.metadata.get("unauthorized") is True
+ assert "Not authorized" in outbound.content
+ assert code not in outbound.content
+ assert "victim-sender" not in outbound.content
+
+ asyncio.run(scenario())
+
+
def test_channel_runtime_new_command_resets_session_and_creates_fresh_one(tmp_path: Path) -> None:
async def scenario() -> None:
from src.channels.runtime import ChannelRuntime
@@ -510,3 +775,52 @@ def test_channel_runtime_session_map_persisted_after_reset(tmp_path: Path) -> No
await runtime.stop()
asyncio.run(scenario())
+
+
+def test_signal_group_command_requires_per_sender_authorization() -> None:
+ """A slash-command in an allowed group needs per-sender auth (GHSA-fwpw).
+
+ Group membership alone must not authorize control-plane commands: an
+ unauthorized member's ``/pairing`` is dropped, while an allowlisted
+ sender's command passes even without a mention.
+ """
+ from src.channels.signal import SignalChannel, SignalConfig, SignalDMConfig, SignalGroupConfig
+
+ config = SignalConfig(
+ enabled=True,
+ phone_number="+15550000",
+ dm=SignalDMConfig(enabled=True, allow_from=["+15550001"]),
+ group=SignalGroupConfig(
+ enabled=True,
+ policy="allowlist",
+ allow_from=["group-1"],
+ require_mention=True,
+ ),
+ )
+ channel = SignalChannel(config, MessageBus())
+
+ denied, denied_chat = channel._check_inbound_policy(
+ sender_id="+15559999",
+ sender_number="+15559999",
+ group_id="group-1",
+ is_group_message=True,
+ message_text="/pairing list",
+ mentions=[],
+ sender_name="Mallory",
+ timestamp=None,
+ )
+ assert denied is False
+ assert denied_chat == "group-1"
+
+ allowed, allowed_chat = channel._check_inbound_policy(
+ sender_id="+15550001",
+ sender_number="+15550001",
+ group_id="group-1",
+ is_group_message=True,
+ message_text="/pairing list",
+ mentions=[],
+ sender_name="Owner",
+ timestamp=None,
+ )
+ assert allowed is True
+ assert allowed_chat == "group-1"