fix(qq): preserve settings and onboarding credentials
This commit is contained in:
1 parent
3ba93ba8e3
commit
85bee83247
3 files changed
+175
-13
No files matched your search
@@ -12,11 +12,12 @@ import asyncio
|
||||
import base64
|
||||
import secrets
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, cast
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
from filelock import FileLock
|
||||
|
||||
from nanobot.channels.connect import ChannelConnectError, QueryParams, query_first
|
||||
|
||||
@@ -36,6 +37,7 @@ class QQConnectSession:
|
||||
key: str
|
||||
created_wall: float
|
||||
deadline: float
|
||||
credentials: tuple[str, str] | None = field(default=None, repr=False)
|
||||
|
||||
|
||||
def _decrypt_secret(encrypted: str, key: str) -> str:
|
||||
@@ -72,15 +74,18 @@ async def _portal_post(path: str, body: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def save_credentials(app_id: str, secret: str) -> None:
|
||||
"""Persist credentials before the post-connect enable step reads config."""
|
||||
"""Merge credentials under the same file lock as settings mutations."""
|
||||
from nanobot.config.loader import get_config_path, load_config, save_config
|
||||
|
||||
config = load_config()
|
||||
raw = getattr(config.channels, "qq", None)
|
||||
values: dict[str, Any] = dict(cast(dict[str, Any], raw)) if isinstance(raw, dict) else {}
|
||||
values.update(appId=app_id, secret=secret)
|
||||
setattr(config.channels, "qq", values)
|
||||
save_config(config, get_config_path())
|
||||
path = get_config_path().expanduser().resolve(strict=False)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with FileLock(str(path.with_suffix(f"{path.suffix}.lock"))):
|
||||
config = load_config(path)
|
||||
raw = getattr(config.channels, "qq", None)
|
||||
values: dict[str, Any] = dict(cast(dict[str, Any], raw)) if isinstance(raw, dict) else {}
|
||||
values.update(appId=app_id, secret=secret)
|
||||
setattr(config.channels, "qq", values)
|
||||
save_config(config, path)
|
||||
|
||||
|
||||
class QQConnectStore:
|
||||
@@ -147,6 +152,7 @@ class QQConnectStore:
|
||||
return _payload(session_id, "failed", "QQ confirmed the scan but returned no credentials.")
|
||||
|
||||
await asyncio.to_thread(save_credentials, app_id, secret)
|
||||
session.credentials = (app_id, secret)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "succeeded",
|
||||
@@ -157,8 +163,8 @@ class QQConnectStore:
|
||||
self._sessions.pop(session_id, None)
|
||||
return _payload(session_id, "cancelled", "QQ login cancelled.")
|
||||
|
||||
async def login(self) -> bool:
|
||||
"""Blocking CLI login: print the QR and poll until scanned."""
|
||||
async def login(self) -> tuple[str, str] | None:
|
||||
"""Print the QR and return committed credentials to the CLI config owner."""
|
||||
try:
|
||||
task_id, key = await create_bind_task()
|
||||
except Exception as exc:
|
||||
@@ -169,7 +175,7 @@ class QQConnectStore:
|
||||
while True:
|
||||
payload = await self.poll(session.id)
|
||||
if payload["status"] != "pending":
|
||||
return payload["status"] == "succeeded"
|
||||
return session.credentials if payload["status"] == "succeeded" else None
|
||||
await asyncio.sleep(POLL_INTERVAL_MS / 1000)
|
||||
finally:
|
||||
self._sessions.pop(session.id, None)
|
||||
|
||||
@@ -371,7 +371,11 @@ class QQChannel(BaseChannel):
|
||||
|
||||
if not force and self.config.app_id and self.config.secret:
|
||||
return True
|
||||
return await QQConnectStore().login()
|
||||
credentials = await QQConnectStore().login()
|
||||
if credentials is None:
|
||||
return False
|
||||
self.config.app_id, self.config.secret = credentials
|
||||
return True
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start the QQ bot with auto-reconnect loop."""
|
||||
|
||||
@@ -3,6 +3,8 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
@@ -92,7 +94,7 @@ async def test_qq_login_scans_and_persists(monkeypatch: pytest.MonkeyPatch, _iso
|
||||
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
|
||||
monkeypatch.setattr(connect, "_print_qr", lambda _url: None)
|
||||
|
||||
assert await asyncio.wait_for(QQConnectStore().login(), timeout=5) is True
|
||||
assert await asyncio.wait_for(QQConnectStore().login(), timeout=5) == ("2048", "new")
|
||||
saved = json.loads(_isolated_config.read_text(encoding="utf-8"))["channels"]["qq"]
|
||||
assert (saved["appId"], saved["secret"]) == ("2048", "new")
|
||||
|
||||
@@ -110,6 +112,156 @@ async def test_qq_login_skips_scan_when_credentials_configured(monkeypatch: pyte
|
||||
assert await channel.login() is True
|
||||
|
||||
|
||||
def test_qq_credentials_serialize_with_settings_mutations(monkeypatch: pytest.MonkeyPatch, _isolated_config):
|
||||
from filelock import FileLock
|
||||
|
||||
from nanobot.config import loader
|
||||
from nanobot.webui import settings_api
|
||||
from nanobot.webui.settings_services import WebUISettingsServices
|
||||
|
||||
settings = WebUISettingsServices.create(_isolated_config)
|
||||
settings_loaded = threading.Event()
|
||||
release_settings = threading.Event()
|
||||
settings_saved = threading.Event()
|
||||
qq_started = threading.Event()
|
||||
errors: list[BaseException] = []
|
||||
original_settings_load = settings_api._load_settings_config
|
||||
original_load = loader.load_config
|
||||
original_acquire = FileLock.acquire
|
||||
|
||||
def settings_load(path: Path | None) -> Config:
|
||||
config = original_settings_load(path)
|
||||
settings_loaded.set()
|
||||
if not release_settings.wait(timeout=5):
|
||||
raise TimeoutError("settings mutation was not released")
|
||||
return config
|
||||
|
||||
def qq_load(path: Path | None = None) -> Config:
|
||||
config = original_load(path)
|
||||
# An unlocked QQ read must finish after Settings, exposing a stale write.
|
||||
qq_started.set()
|
||||
if not settings_saved.wait(timeout=5):
|
||||
raise TimeoutError("settings mutation did not finish")
|
||||
return config
|
||||
|
||||
def acquire(lock, *args, **kwargs):
|
||||
# Observe contention without replacing the real cross-process file lock.
|
||||
if threading.current_thread().name == "qq-credentials":
|
||||
qq_started.set()
|
||||
return original_acquire(lock, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(settings_api, "_load_settings_config", settings_load)
|
||||
monkeypatch.setattr(loader, "load_config", qq_load)
|
||||
monkeypatch.setattr(FileLock, "acquire", acquire)
|
||||
|
||||
def save_settings() -> None:
|
||||
try:
|
||||
settings.mutate(
|
||||
settings_api.update_runtime_config_settings,
|
||||
{"tools.restrict_to_workspace": True},
|
||||
local_browser=True,
|
||||
)
|
||||
except BaseException as exc: # noqa: BLE001 - checked after joining the thread
|
||||
errors.append(exc)
|
||||
finally:
|
||||
settings_saved.set()
|
||||
|
||||
def save_qq() -> None:
|
||||
try:
|
||||
connect.save_credentials("2048", "new")
|
||||
except BaseException as exc: # noqa: BLE001 - checked after joining the thread
|
||||
errors.append(exc)
|
||||
|
||||
settings_thread = threading.Thread(target=save_settings)
|
||||
qq_thread = threading.Thread(target=save_qq, name="qq-credentials")
|
||||
settings_thread.start()
|
||||
try:
|
||||
assert settings_loaded.wait(timeout=5)
|
||||
qq_thread.start()
|
||||
assert qq_started.wait(timeout=5)
|
||||
finally:
|
||||
release_settings.set()
|
||||
settings_thread.join(timeout=5)
|
||||
if qq_thread.ident is not None:
|
||||
qq_thread.join(timeout=5)
|
||||
|
||||
assert not settings_thread.is_alive()
|
||||
assert not qq_thread.is_alive()
|
||||
assert not errors
|
||||
saved = original_load(_isolated_config)
|
||||
assert saved.tools.restrict_to_workspace is True
|
||||
assert (saved.channels.qq["appId"], saved.channels.qq["secret"]) == ("2048", "new")
|
||||
assert saved.channels.qq["allowFrom"] == ["42"]
|
||||
|
||||
|
||||
def test_qq_onboard_keeps_scanned_credentials_on_final_save(monkeypatch: pytest.MonkeyPatch, _isolated_config):
|
||||
from nanobot.channels.qq import runtime
|
||||
from nanobot.cli import onboard
|
||||
from nanobot.config.loader import load_config
|
||||
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
|
||||
async def fake_create() -> tuple[str, str]:
|
||||
return "wizard-task", key
|
||||
|
||||
async def fake_poll(_task_id: str) -> dict[str, Any]:
|
||||
return {"status": 2, "bot_appid": "2048", "bot_encrypt_secret": _encrypt("new", key)}
|
||||
|
||||
monkeypatch.setattr(connect, "create_bind_task", fake_create)
|
||||
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
|
||||
monkeypatch.setattr(connect, "_print_qr", lambda _url: None)
|
||||
monkeypatch.setattr(onboard, "_get_channel_class", lambda _name: runtime.QQChannel)
|
||||
monkeypatch.setattr(runtime, "get_media_dir", lambda _name: _isolated_config.parent / "media")
|
||||
config = load_config(_isolated_config)
|
||||
model = runtime.QQConfig.model_validate(config.channels.qq)
|
||||
|
||||
assert onboard._run_channel_login(config, "qq", model, "QQ") is True
|
||||
save_config(config, _isolated_config)
|
||||
|
||||
saved = load_config(_isolated_config).channels.qq
|
||||
assert (saved["appId"], saved["secret"]) == ("2048", "new")
|
||||
assert saved["enabled"] is True
|
||||
assert saved["allowFrom"] == ["42"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("outcome", ["connected", "expired", "save_failed"])
|
||||
async def test_qq_forced_login_commits_model_only_after_saving(
|
||||
monkeypatch: pytest.MonkeyPatch, _isolated_config, outcome: str,
|
||||
):
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.qq import runtime
|
||||
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
|
||||
async def fake_create() -> tuple[str, str]:
|
||||
return "replacement-task", key
|
||||
|
||||
async def fake_poll(_task_id: str) -> dict[str, Any]:
|
||||
if outcome == "expired":
|
||||
return {"status": 3}
|
||||
return {"status": 2, "bot_appid": "2048", "bot_encrypt_secret": _encrypt("new", key)}
|
||||
|
||||
def fail_save(_app_id: str, _secret: str) -> None:
|
||||
raise OSError("config is not writable")
|
||||
|
||||
monkeypatch.setattr(connect, "create_bind_task", fake_create)
|
||||
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
|
||||
monkeypatch.setattr(connect, "_print_qr", lambda _url: None)
|
||||
monkeypatch.setattr(runtime, "get_media_dir", lambda _name: _isolated_config.parent / "media")
|
||||
channel = runtime.QQChannel({"appId": "1024", "secret": "old"}, MessageBus())
|
||||
|
||||
if outcome == "save_failed":
|
||||
monkeypatch.setattr(connect, "save_credentials", fail_save)
|
||||
with pytest.raises(OSError, match="config is not writable"):
|
||||
await channel.login(force=True)
|
||||
else:
|
||||
assert await channel.login(force=True) is (outcome == "connected")
|
||||
|
||||
expected = ("2048", "new") if outcome == "connected" else ("1024", "old")
|
||||
assert (channel.config.app_id, channel.config.secret) == expected
|
||||
|
||||
|
||||
def test_decrypt_secret_rejects_wrong_key():
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
encrypted = _encrypt("s3cret", key)
|
||||
|
||||
Reference in new issue
Block a user