fix(webui): refresh pairing prompts on gateway changes (#6401)
This commit is contained in:
1 parent
9e9e22d331
commit
8af6313c56
26 files changed
+630
-82
No files matched your search
@@ -18,6 +18,7 @@ from nanobot.pairing import (
|
||||
is_approved,
|
||||
record_delivery,
|
||||
)
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
|
||||
|
||||
class BaseChannel(ABC):
|
||||
@@ -275,6 +276,9 @@ class BaseChannel(ABC):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _pairing_changed(self) -> None:
|
||||
self.bus.publish_nowait(PairingChanged())
|
||||
|
||||
async def _handle_message(
|
||||
self,
|
||||
sender_id: str,
|
||||
@@ -299,7 +303,7 @@ class BaseChannel(ABC):
|
||||
if not self.is_allowed(permission_id):
|
||||
if is_dm:
|
||||
try:
|
||||
code = generate_code(self.name, str(sender_id))
|
||||
code = generate_code(self.name, str(sender_id), on_change=self._pairing_changed)
|
||||
except OSError:
|
||||
# Transient pairing-store I/O failure: skip the pairing
|
||||
# reply for this message rather than crash the handler.
|
||||
@@ -307,7 +311,7 @@ class BaseChannel(ABC):
|
||||
"Pairing store unavailable; dropping DM from {}", sender_id
|
||||
)
|
||||
return
|
||||
record_delivery(code, "sending")
|
||||
record_delivery(code, "sending", on_change=self._pairing_changed)
|
||||
try:
|
||||
await self.send(
|
||||
OutboundMessage(
|
||||
@@ -318,9 +322,9 @@ class BaseChannel(ABC):
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
record_delivery(code, "failed")
|
||||
record_delivery(code, "failed", on_change=self._pairing_changed)
|
||||
raise
|
||||
record_delivery(code, "sent")
|
||||
record_delivery(code, "sent", on_change=self._pairing_changed)
|
||||
self.logger.info(
|
||||
"Sent pairing code {} to sender {} in chat {}",
|
||||
code, sender_id, chat_id,
|
||||
|
||||
@@ -625,7 +625,7 @@ async def test_on_message_unauthorized_dm_sends_pairing_code(monkeypatch) -> Non
|
||||
channel._running = True
|
||||
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda _ch, _sid: False)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
|
||||
)
|
||||
|
||||
await channel._on_message(message)
|
||||
|
||||
@@ -250,7 +250,7 @@ class MattermostChannel(BaseChannel):
|
||||
|
||||
if not await self._is_allowed(sender_id, channel_id, channel_type):
|
||||
if is_dm and self.config.dm.enabled:
|
||||
code = generate_code(self.name, str(sender_id))
|
||||
code = generate_code(self.name, str(sender_id), on_change=self._pairing_changed)
|
||||
await self.send(
|
||||
OutboundMessage(
|
||||
channel=self.name,
|
||||
|
||||
@@ -2462,7 +2462,7 @@ async def test_forward_command_pairs_unauthorized_private_user(monkeypatch) -> N
|
||||
)
|
||||
_install_ready_app(channel)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
|
||||
)
|
||||
|
||||
await channel._forward_command(_make_telegram_update(text="/new", chat_type="private"), None)
|
||||
@@ -2689,7 +2689,7 @@ async def test_on_start_sends_pairing_code_to_unauthorized_private_user(monkeypa
|
||||
update = _make_telegram_update(text="/start", chat_type="private")
|
||||
update.message.reply_text = AsyncMock()
|
||||
monkeypatch.setattr(
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
|
||||
)
|
||||
|
||||
await channel._on_start(update, None)
|
||||
@@ -2709,7 +2709,7 @@ async def test_on_help_sends_pairing_code_to_unauthorized_private_user(monkeypat
|
||||
update = _make_telegram_update(text="/help", chat_type="private")
|
||||
update.message.reply_text = AsyncMock()
|
||||
monkeypatch.setattr(
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
|
||||
)
|
||||
|
||||
await channel._on_help(update, None)
|
||||
@@ -2733,7 +2733,7 @@ async def test_on_message_pairs_unauthorized_private_user_before_side_effects(
|
||||
channel._add_reaction = AsyncMock(return_value=None)
|
||||
channel._download_message_media = AsyncMock(return_value=([], []))
|
||||
monkeypatch.setattr(
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
|
||||
)
|
||||
|
||||
await channel._on_message(_make_telegram_update(text="hello", chat_type="private"), None)
|
||||
|
||||
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
@@ -816,11 +817,13 @@ class WebSocketChannel(BaseChannel):
|
||||
if self._server is server:
|
||||
self._server = None
|
||||
|
||||
disconnect_pairing = self.bus.subscribe(self._queue_pairing_changed, PairingChanged)
|
||||
task = asyncio.create_task(runner())
|
||||
self._server_task = task
|
||||
try:
|
||||
await task
|
||||
finally:
|
||||
disconnect_pairing()
|
||||
prune_task.cancel()
|
||||
await asyncio.gather(prune_task, return_exceptions=True)
|
||||
self._uploads.store.clear()
|
||||
@@ -1552,6 +1555,14 @@ class WebSocketChannel(BaseChannel):
|
||||
for connection in conns:
|
||||
await self._safe_send_to(connection, raw, label=" user_message ")
|
||||
|
||||
async def _queue_pairing_changed(self, event: PairingChanged) -> None:
|
||||
await self.bus.publish_event(event, channel=self.name, chat_id="*")
|
||||
|
||||
async def send_pairing_changed(self) -> None:
|
||||
"""Project invalidation only to bootstrap-authenticated WebUI clients."""
|
||||
for connection in tuple(self._webui_connections):
|
||||
await self._send_event(connection, "pairing_changed")
|
||||
|
||||
async def send_runtime_model_updated(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -50,6 +50,7 @@ from nanobot.channels.websocket.runtime import (
|
||||
)
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
|
||||
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
|
||||
@@ -2371,6 +2372,21 @@ async def test_send_delivers_json_message_with_media_and_reply() -> None:
|
||||
assert payload["media"] == ["/tmp/a.png"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pairing_invalidation_reaches_only_authenticated_webui_connections() -> None:
|
||||
bus = MessageBus()
|
||||
channel = _ch(bus)
|
||||
webui, ordinary = AsyncMock(), AsyncMock()
|
||||
channel._attach(webui, "chat-1")
|
||||
channel._attach(ordinary, "chat-1")
|
||||
channel._webui_connections.add(webui)
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket", chat_id="*", content="", event=PairingChanged(),
|
||||
))
|
||||
assert json.loads(webui.send.call_args[0][0]) == {"event": "pairing_changed"}
|
||||
ordinary.send.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_broadcasts_runtime_model_updates() -> None:
|
||||
bus = MessageBus()
|
||||
|
||||
@@ -1230,11 +1230,11 @@ async def test_pairing_routes_require_token_and_approve_or_deny(
|
||||
monkeypatch.setattr("nanobot.webui.settings_routes.list_pending", lambda: list(pending))
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.approve_code",
|
||||
lambda code: approved.append(code) or ("feishu", "ou_123") if code == "ABCD-EFGH" else None,
|
||||
lambda code, **_kwargs: approved.append(code) or ("feishu", "ou_123") if code == "ABCD-EFGH" else None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.deny_code",
|
||||
lambda code: denied.append(code) or code == "ABCD-EFGH",
|
||||
lambda code, **_kwargs: denied.append(code) or code == "ABCD-EFGH",
|
||||
)
|
||||
|
||||
channel = _ch(bus, session_manager=_seed_session(tmp_path), port=_free_port())
|
||||
@@ -1291,6 +1291,28 @@ async def test_pairing_routes_require_token_and_approve_or_deny(
|
||||
assert "Missing pairing code" in missing_code.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("action", ["approve", "deny"])
|
||||
async def test_pairing_mutation_publishes_committed_snapshot(action, tmp_path, monkeypatch):
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.pairing import store
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
|
||||
monkeypatch.setattr(store, "_store_path", lambda: tmp_path / "pairing.json")
|
||||
code = store.generate_code("telegram", "alice")
|
||||
bus = MessageBus()
|
||||
snapshots = []
|
||||
bus.subscribe(lambda _event: snapshots.append(store.list_pending()), PairingChanged)
|
||||
channel = _ch(bus, session_manager=_seed_session(tmp_path), port=_free_port())
|
||||
result = await _webui_mutate(channel, f"settings.pairing.{action}", {"code": code})
|
||||
await bus.drain()
|
||||
assert result.status_code == 200 and snapshots == [[]]
|
||||
assert store.is_approved("telegram", "alice") == (action == "approve")
|
||||
missing = await _webui_mutate(channel, f"settings.pairing.{action}", {"code": code})
|
||||
await bus.drain()
|
||||
assert missing.status_code == 404 and snapshots == [[]]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nanobot_feature_remote_install_requires_opt_in(
|
||||
bus: MagicMock,
|
||||
|
||||
@@ -8,6 +8,7 @@ import pytest
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel
|
||||
from nanobot.pairing.events import PairingChanged
|
||||
|
||||
|
||||
class _FakeSocket:
|
||||
@@ -70,6 +71,8 @@ async def test_websocket_does_not_report_running_before_bind_succeeds(monkeypatc
|
||||
|
||||
assert exc_info.value is bind_error
|
||||
assert channel.is_running is False
|
||||
await channel.bus.publish(PairingChanged())
|
||||
assert channel.bus.outbound_size == 0
|
||||
assert not any(
|
||||
call.args and call.args[0] == "WebSocket server listening on {}"
|
||||
for call in channel.logger.info.call_args_list
|
||||
@@ -112,6 +115,10 @@ async def test_websocket_restarts_only_its_listener_after_serving_socket_is_lost
|
||||
break
|
||||
await asyncio.sleep(0)
|
||||
assert channel.is_running is True
|
||||
await channel.bus.publish(PairingChanged())
|
||||
notification = await channel.bus.consume_outbound()
|
||||
assert notification.channel == "websocket" and notification.chat_id == "*"
|
||||
assert isinstance(notification.event, PairingChanged)
|
||||
|
||||
first.socket.open = False
|
||||
for _ in range(50):
|
||||
@@ -129,3 +136,5 @@ async def test_websocket_restarts_only_its_listener_after_serving_socket_is_lost
|
||||
await start_task
|
||||
|
||||
assert second.closed is True
|
||||
await channel.bus.publish(PairingChanged())
|
||||
assert channel.bus.outbound_size == 0
|
||||
@@ -351,7 +351,7 @@ async def test_process_message_pairs_unauthorized_sender_before_media_side_effec
|
||||
channel._get_typing_ticket = AsyncMock(return_value="")
|
||||
channel._send_text = AsyncMock()
|
||||
monkeypatch.setattr(
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
|
||||
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
|
||||
)
|
||||
|
||||
await channel._process_message(
|
||||
|
||||
@@ -798,7 +798,7 @@ async def test_unauthorized_voice_message_does_not_download_or_transcribe(
|
||||
@pytest.mark.asyncio
|
||||
async def test_unauthorized_dm_uses_base_pairing_flow(monkeypatch) -> None:
|
||||
_patch_neonize_api(monkeypatch)
|
||||
monkeypatch.setattr("nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH")
|
||||
monkeypatch.setattr("nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH")
|
||||
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda _ch, _sid: False)
|
||||
client = SimpleNamespace(send_message=AsyncMock(), download_any=AsyncMock())
|
||||
ch = WhatsAppChannel({"enabled": True, "allowFrom": []}, MagicMock())
|
||||
|
||||
Reference in new issue
Block a user