fix(webui): complete Copilot device sign-in in the browser
Reuse the device-flow adapter from #5498, expose its prompt in the existing OAuth dialog, and keep credential persistence scoped to uncancelled completion. Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
1 parent
aca59431fe
commit
a44f28e656
24 files changed
+563
-39
No files matched your search
@@ -0,0 +1,130 @@
|
||||
"""Device authorization exposes its prompt before waiting for browser approval."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.providers import github_copilot_provider as provider
|
||||
from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
|
||||
|
||||
|
||||
def test_device_prompt_precedes_approval_and_success_persists_token(monkeypatch):
|
||||
saved = []
|
||||
approved = False
|
||||
|
||||
def respond(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path.endswith("/device/code"):
|
||||
return httpx.Response(200, json={
|
||||
"device_code": "device-secret", "user_code": "ABCD-EFGH",
|
||||
"verification_uri": "https://github.com/login/device",
|
||||
"interval": 1, "expires_in": 60,
|
||||
})
|
||||
if request.url.path.endswith("/access_token"):
|
||||
return httpx.Response(200, json={"access_token": "account-secret"} if approved
|
||||
else {"error": "authorization_pending"})
|
||||
return httpx.Response(200, json={"login": "test-account"})
|
||||
|
||||
client = httpx.Client(transport=httpx.MockTransport(respond))
|
||||
monkeypatch.setattr(provider.httpx, "Client", lambda **_kwargs: client)
|
||||
monkeypatch.setattr(provider, "get_storage", lambda: SimpleNamespace(save=saved.append))
|
||||
monkeypatch.setattr(provider.webbrowser, "open", lambda *_args: (_ for _ in ()).throw(
|
||||
AssertionError("The gateway must not open the user's browser")
|
||||
))
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
try:
|
||||
flow.start()
|
||||
assert flow.user_code == "ABCD-EFGH"
|
||||
assert flow.authorization_url == "https://github.com/login/device"
|
||||
assert flow.complete() is None
|
||||
assert saved == []
|
||||
approved = True
|
||||
deadline = time.monotonic() + 3
|
||||
token = flow.complete()
|
||||
while token is None and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
token = flow.complete()
|
||||
assert token is not None
|
||||
assert token.account_id == "test-account"
|
||||
assert saved == [token]
|
||||
finally:
|
||||
flow.cancel()
|
||||
|
||||
|
||||
def test_cancelling_device_flow_interrupts_polling_without_saving(monkeypatch):
|
||||
saved = []
|
||||
|
||||
def respond(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path.endswith("/device/code"):
|
||||
return httpx.Response(200, json={
|
||||
"device_code": "device-secret", "user_code": "ABCD-EFGH",
|
||||
"verification_uri": "https://github.com/login/device",
|
||||
"interval": 30, "expires_in": 60,
|
||||
})
|
||||
return httpx.Response(200, json={"error": "authorization_pending"})
|
||||
|
||||
client = httpx.Client(transport=httpx.MockTransport(respond))
|
||||
monkeypatch.setattr(provider.httpx, "Client", lambda **_kwargs: client)
|
||||
monkeypatch.setattr(provider, "get_storage", lambda: SimpleNamespace(save=saved.append))
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
flow.start()
|
||||
flow.cancel()
|
||||
deadline = time.monotonic() + 2
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
flow.complete()
|
||||
except RuntimeError as exc:
|
||||
assert "cancelled" in str(exc)
|
||||
break
|
||||
time.sleep(0.01)
|
||||
else:
|
||||
raise AssertionError("Device polling did not stop after cancellation")
|
||||
assert saved == []
|
||||
assert flow.expired
|
||||
|
||||
|
||||
def test_approval_after_cancellation_cannot_overwrite_saved_credentials(monkeypatch):
|
||||
from nanobot.providers import github_copilot_oauth as oauth
|
||||
|
||||
approved = threading.Event()
|
||||
finished = threading.Event()
|
||||
saved = []
|
||||
|
||||
def login(*, on_authorization, persist, **_kwargs):
|
||||
assert persist is False
|
||||
on_authorization("https://github.com/login/device", "ABCD-EFGH", 60)
|
||||
approved.wait(2)
|
||||
finished.set()
|
||||
return SimpleNamespace(access="new-account-secret")
|
||||
|
||||
monkeypatch.setattr(oauth, "login_github_copilot", login)
|
||||
monkeypatch.setattr(provider, "get_storage", lambda: SimpleNamespace(save=saved.append))
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
try:
|
||||
flow.start()
|
||||
flow.cancel()
|
||||
approved.set()
|
||||
assert finished.wait(1)
|
||||
with pytest.raises(RuntimeError, match="cancelled"):
|
||||
flow.complete()
|
||||
assert saved == []
|
||||
finally:
|
||||
approved.set()
|
||||
flow.cancel()
|
||||
|
||||
|
||||
def test_device_flow_does_not_expose_upstream_failure_details(monkeypatch):
|
||||
from nanobot.providers import github_copilot_oauth as oauth
|
||||
|
||||
def login(**_kwargs):
|
||||
raise RuntimeError("upstream echoed synthetic-secret")
|
||||
|
||||
monkeypatch.setattr(oauth, "login_github_copilot", login)
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
with pytest.raises(RuntimeError, match="GitHub sign-in failed") as failure:
|
||||
flow.start()
|
||||
assert "synthetic-secret" not in str(failure.value)
|
||||
with pytest.raises(RuntimeError, match="GitHub sign-in failed"):
|
||||
flow.complete()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""The WebUI exposes only user-facing device data and owns cancellation."""
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.webui.settings_models import complete_oauth_provider, login_oauth_provider
|
||||
from nanobot.webui.settings_services import WebUIOAuthFlowRegistry
|
||||
|
||||
|
||||
def test_copilot_prompt_poll_and_owned_cancellation(monkeypatch):
|
||||
stopped = threading.Event()
|
||||
|
||||
def login(*, on_authorization, cancelled, persist, **_kwargs):
|
||||
assert persist is False
|
||||
on_authorization("https://github.com/login/device", "ABCD-EFGH", 60)
|
||||
cancelled.wait(2)
|
||||
stopped.set()
|
||||
raise RuntimeError("cancelled")
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.github_copilot_oauth.login_github_copilot", login)
|
||||
registry = WebUIOAuthFlowRegistry()
|
||||
payload = login_oauth_provider(
|
||||
Config(), {"provider": ["github_copilot"]}, oauth_flows=registry,
|
||||
config_path=None, settings_payload=lambda **_: {},
|
||||
)
|
||||
assert set(payload) == {
|
||||
"status", "provider", "flow_id", "authorization_url", "user_code",
|
||||
"expires_in", "completion_input",
|
||||
}
|
||||
assert payload["user_code"] == "ABCD-EFGH"
|
||||
assert payload["completion_input"] == "device_code"
|
||||
query = {"provider": ["github_copilot"], "flow_id": [payload["flow_id"]]}
|
||||
kwargs = dict(oauth_flows=registry, config_path=None, settings_payload=lambda **_: {})
|
||||
try:
|
||||
assert complete_oauth_provider(query, **kwargs)["status"] == "pending"
|
||||
with pytest.raises(ValueError, match="expired"):
|
||||
complete_oauth_provider({**query, "provider": ["openai_codex"], "cancel": ["true"]}, **kwargs)
|
||||
assert registry.get("github_copilot", payload["flow_id"]) is not None
|
||||
result = complete_oauth_provider({**query, "cancel": ["true"]}, **kwargs)
|
||||
assert result["status"] == "cancelled"
|
||||
assert registry.get("github_copilot", payload["flow_id"]) is None
|
||||
assert stopped.wait(1)
|
||||
finally:
|
||||
registry.clear("github_copilot")
|
||||
@@ -1904,7 +1904,7 @@ def test_github_copilot_oauth_login_reports_missing_oauth_cli_kit(
|
||||
real_import = builtins.__import__
|
||||
|
||||
def fake_import(name, *args, **kwargs):
|
||||
if name == "nanobot.providers.github_copilot_provider":
|
||||
if name == "nanobot.providers.github_copilot_oauth":
|
||||
raise ImportError("missing")
|
||||
return real_import(name, *args, **kwargs)
|
||||
|
||||
@@ -2142,17 +2142,27 @@ def test_provider_models_payload_exposes_catalog_failure_with_usable_models(
|
||||
def test_copilot_explicit_login_does_not_reuse_revoked_credentials(monkeypatch, oauth_flows):
|
||||
from unittest.mock import Mock
|
||||
|
||||
login = Mock(return_value=SimpleNamespace(access="new-token"))
|
||||
from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
|
||||
|
||||
start = Mock()
|
||||
invalidate = Mock()
|
||||
monkeypatch.setattr(
|
||||
"nanobot.providers.github_copilot_provider.get_github_copilot_login_status",
|
||||
lambda: SimpleNamespace(access="revoked-token"),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.providers.github_copilot_provider.login_github_copilot", login)
|
||||
monkeypatch.setattr(GitHubCopilotOAuthFlow, "start", start)
|
||||
monkeypatch.setattr(GitHubCopilotOAuthFlow, "complete", lambda _: SimpleNamespace(access="new-token"))
|
||||
monkeypatch.setattr("nanobot.webui.settings_models.invalidate_oauth_model_catalog", invalidate)
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {"ready": True})
|
||||
assert login_oauth_provider({"provider": ["github-copilot"]}, oauth_flows=oauth_flows) == {"ready": True}
|
||||
login.assert_called_once()
|
||||
payload = login_oauth_provider({"provider": ["github-copilot"]}, oauth_flows=oauth_flows)
|
||||
assert payload["status"] == "authorization_required"
|
||||
assert payload["completion_input"] == "device_code"
|
||||
start.assert_called_once()
|
||||
invalidate.assert_not_called()
|
||||
assert complete_oauth_provider(
|
||||
{"provider": ["github-copilot"], "flow_id": [payload["flow_id"]]},
|
||||
oauth_flows=oauth_flows,
|
||||
) == {"ready": True}
|
||||
invalidate.assert_called_once_with("github_copilot")
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user