mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 03:15:08 +00:00
feat(service): pass a qr code with a login prompt or approval wait
This commit is contained in:
@@ -346,16 +346,19 @@ def test_worker_relays_a_prompt_and_reads_the_answer(monkeypatch: pytest.MonkeyP
|
||||
def answer_on_prompt(update: dict) -> None:
|
||||
"""Answer only once the prompt is out: the prompt discards answers that arrived before it."""
|
||||
updates.append(update)
|
||||
if update["input_prompt"]:
|
||||
if update.get("input_prompt"):
|
||||
os.write(write_fd, (json.dumps("12\n34") + "\n").encode("utf-8"))
|
||||
|
||||
download_worker.relay_prompts(answer_on_prompt)
|
||||
try:
|
||||
assert prompt_user("Enter PIN") == "12\n34"
|
||||
assert prompt_user("Enter PIN", qr="https://login.example/scan") == "12\n34"
|
||||
finally:
|
||||
set_prompt_handler(None)
|
||||
os.close(write_fd)
|
||||
assert updates == [{"input_prompt": "Enter PIN"}, {"input_prompt": None}]
|
||||
assert updates == [
|
||||
{"input_prompt": "Enter PIN", "qr": "https://login.example/scan"},
|
||||
{"input_prompt": None, "qr": None},
|
||||
]
|
||||
|
||||
|
||||
def test_worker_relays_a_notice_as_progress(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@@ -373,13 +376,16 @@ def test_worker_relays_a_notice_as_progress(monkeypatch: pytest.MonkeyPatch) ->
|
||||
|
||||
download_worker.relay_prompts(updates.append)
|
||||
try:
|
||||
show_notice("Enter pair code ABCD")
|
||||
show_notice("Enter pair code ABCD", "https://login.example/pair")
|
||||
show_notice(None)
|
||||
finally:
|
||||
set_prompt_handler(None)
|
||||
set_notice_handler(None)
|
||||
os.close(write_fd)
|
||||
assert updates == [{"notice": "Enter pair code ABCD"}, {"notice": None}]
|
||||
assert updates == [
|
||||
{"notice": "Enter pair code ABCD", "qr": "https://login.example/pair"},
|
||||
{"notice": None, "qr": None},
|
||||
]
|
||||
|
||||
|
||||
def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@@ -530,7 +536,8 @@ async def test_a_notice_reaches_the_job_and_an_event_listener(
|
||||
# The prompt holds the worker open until the test has seen the notice.
|
||||
source = FAKE_PROMPT_WORKER.replace("import prompt_user", "import prompt_user, show_notice").replace(
|
||||
'answers = [prompt_user("Enter OTP"), prompt_user("Enter OTP")]',
|
||||
'show_notice("Enter pair code ABCD")\nanswers = [prompt_user("Continue")]',
|
||||
'show_notice("Enter pair code ABCD", "https://login.example/pair")\n'
|
||||
'answers = [prompt_user("Continue", "https://login.example/pair")]',
|
||||
)
|
||||
assert source.count("show_notice") == 2, "FAKE_PROMPT_WORKER changed; update the replacements"
|
||||
worker.write_text(source, encoding="utf-8")
|
||||
@@ -550,12 +557,13 @@ async def test_a_notice_reaches_the_job_and_an_event_listener(
|
||||
if event and event["data"]["input_prompt"]:
|
||||
assert event["data"]["notice"] == "Enter pair code ABCD"
|
||||
assert job.to_dict()["notice"] == "Enter pair code ABCD"
|
||||
assert event["data"]["qr"] == job.to_dict()["qr"] == "https://login.example/pair"
|
||||
assert manager.submit_input(job, "ok") is True
|
||||
return
|
||||
|
||||
await asyncio.wait_for(answer_after_notice(), timeout=20)
|
||||
assert await asyncio.wait_for(run, timeout=20) == ["ok"]
|
||||
assert job.notice is None
|
||||
assert job.notice is None and job.qr is None
|
||||
|
||||
|
||||
async def test_input_handler_rejects_bad_requests(
|
||||
|
||||
@@ -246,7 +246,20 @@ def test_relayed_server_logs_lose_their_control_characters(monkeypatch: pytest.M
|
||||
|
||||
def test_a_relayed_login_prompt_loses_its_control_characters() -> None:
|
||||
service = RemoteService.__new__(RemoteService)
|
||||
asked: list[str] = []
|
||||
service._input_bridge = SimpleNamespace(request_input=lambda prompt: asked.append(prompt) or "1234")
|
||||
assert ServerMessages(service).ask_user("Code\x1b[2J:\n") == "1234"
|
||||
assert asked == ["Code[2J:\n"]
|
||||
asked: list[tuple[str, str | None]] = []
|
||||
service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: asked.append((prompt, qr)) or "1234")
|
||||
assert ServerMessages(service).ask_user("Code\x1b[2J:\n", {"not": "text"}) == "1234"
|
||||
assert asked == [("Code[2J:\n", None)]
|
||||
|
||||
|
||||
def test_a_relayed_qr_code_too_long_to_draw_still_logs_its_line(monkeypatch) -> None:
|
||||
from unshackle.core import console
|
||||
|
||||
seen: list[str] = []
|
||||
service = RemoteService.__new__(RemoteService)
|
||||
service._input_bridge, service.auth_qr = None, None
|
||||
service.log = SimpleNamespace(log=lambda level, message: seen.append(message))
|
||||
monkeypatch.setattr(console.console, "print", lambda *a, **k: pytest.fail("nothing to draw"))
|
||||
messages = ServerMessages(service)
|
||||
messages.show_logs([{"seq": 1, "level": "INFO", "message": "Scan", "qr": "\u20ac" * 1500}])
|
||||
assert seen == ["Scan"] and messages.log_seq == 1
|
||||
|
||||
@@ -27,9 +27,11 @@ from unshackle.core.api.handlers import api_key_authentication
|
||||
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes
|
||||
from unshackle.core.cdm import client_relay
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.console import console, qr_text
|
||||
from unshackle.core.remote_channel import PollingChannel, WebSocketChannel
|
||||
from unshackle.core.remote_protocol import CHANNEL_ROUTE, LOGS_ROUTE, PROMPT_ROUTE, SESSION_ROUTE, APIErrorCode
|
||||
from unshackle.core.remote_service import RemoteError, RemoteService
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.titles.movie import Movie, Movies
|
||||
from unshackle.core.tracks import Audio, Chapters, Tracks
|
||||
from unshackle.core.tracks.track import Track
|
||||
@@ -174,7 +176,7 @@ def make_client(url: str, cdm: Any = None) -> RemoteService:
|
||||
parent.params = {"no_proxy": True}
|
||||
ctx = click.Context(click.Command("EXAMPLE"), parent=parent, obj=obj)
|
||||
service = RemoteService(ctx, "EXAMPLE", "example-1", url, KEY, {"_auth_headers": ["X-Api-Key", "X-Secret-Key"]})
|
||||
service._input_bridge = SimpleNamespace(request_input=lambda prompt: CODE)
|
||||
service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: CODE)
|
||||
return service
|
||||
|
||||
|
||||
@@ -284,6 +286,65 @@ def test_a_remote_session_runs_end_to_end_over_http(
|
||||
assert [list(r) for reply in logs for r in reply["logs"]][:1] == [["seq", "level", "message", "ts"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["socket", "polling"])
|
||||
def test_a_qr_code_reaches_the_client_terminal_with_its_prompt(
|
||||
server: SimpleNamespace, channel: str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
payload = "https://login.example/scan?code=EXAMPLE"
|
||||
if channel == "polling":
|
||||
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
|
||||
|
||||
def authenticate(self: StubService, cookies: Any, credential: Any) -> None:
|
||||
if self._input_bridge.request_input("Scan the EXAMPLE code, then press Enter", qr=payload) != CODE:
|
||||
raise ValueError("wrong code")
|
||||
|
||||
monkeypatch.setattr(StubService, "authenticate", authenticate)
|
||||
printed: list[Any] = []
|
||||
asked: list[str] = []
|
||||
monkeypatch.setattr(console, "print", lambda *a, **k: printed.extend(a))
|
||||
monkeypatch.setattr(console, "input", lambda prompt: asked.append(str(prompt)) or CODE)
|
||||
service = make_client(server.url)
|
||||
service._input_bridge = None
|
||||
try:
|
||||
service.authenticate()
|
||||
assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel)
|
||||
finally:
|
||||
service.close()
|
||||
assert [p.plain for p in printed if hasattr(p, "plain")] == [qr_text(payload).plain]
|
||||
assert len(asked) == 1 and "Scan the EXAMPLE code" in asked[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["socket", "polling"])
|
||||
def test_a_qr_code_to_approve_reaches_the_client_with_its_log_line(
|
||||
server: SimpleNamespace, channel: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
caplog.set_level(logging.INFO)
|
||||
payload = "https://login.example/approve?code=EXAMPLE"
|
||||
if channel == "polling":
|
||||
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
|
||||
printed: list[Any] = []
|
||||
monkeypatch.setattr(console, "print", lambda *a, **k: printed.extend(a))
|
||||
|
||||
expected = qr_text(payload).plain
|
||||
|
||||
def drawn() -> bool | None:
|
||||
return any(getattr(p, "plain", None) == expected for p in printed) or None
|
||||
|
||||
def authenticate(self: StubService, cookies: Any, credential: Any) -> None:
|
||||
Service.wait_for_approval(self, "Scan the EXAMPLE code", drawn, 10, 0.01, payload)
|
||||
|
||||
monkeypatch.setattr(StubService, "authenticate", authenticate)
|
||||
service = make_client(server.url)
|
||||
service._input_bridge = None
|
||||
try:
|
||||
service.authenticate()
|
||||
assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel)
|
||||
finally:
|
||||
service.close()
|
||||
assert "Scan the EXAMPLE code" in example_messages(caplog)
|
||||
assert [p.plain for p in printed if hasattr(p, "plain")] == [qr_text(payload).plain]
|
||||
|
||||
|
||||
def test_the_session_channel_carries_what_the_server_starts(
|
||||
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
@@ -447,7 +508,7 @@ def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling(
|
||||
|
||||
|
||||
def test_a_prompt_the_client_cannot_answer_fails_the_login_at_once(server: SimpleNamespace) -> None:
|
||||
def refuse(prompt: str) -> str:
|
||||
def refuse(prompt: str, qr: str | None = None) -> str:
|
||||
raise RuntimeError("the EXAMPLE caller left")
|
||||
|
||||
service = make_client(server.url)
|
||||
|
||||
@@ -172,9 +172,9 @@ def test_session_transport_keys_are_the_create_body():
|
||||
@pytest.mark.parametrize(
|
||||
"shape,fields",
|
||||
[
|
||||
(protocol.ChannelPrompt, {"type", "id", "prompt"}),
|
||||
(protocol.ChannelPrompt, {"type", "id", "prompt", "qr"}),
|
||||
(protocol.ChannelCdmCall, {"type", "id", "call"}),
|
||||
(protocol.ChannelLog, {"type", "seq", "level", "message", "ts"}),
|
||||
(protocol.ChannelLog, {"type", "seq", "level", "message", "ts", "qr"}),
|
||||
(protocol.ChannelStatus, {"type", "status", "error"}),
|
||||
(protocol.ChannelDrain, {"type", "draining"}),
|
||||
(protocol.ChannelAnswer, {"type", "id", "response", "error"}),
|
||||
|
||||
@@ -216,7 +216,7 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc
|
||||
from unshackle.core import remote_channel
|
||||
|
||||
shown = []
|
||||
monkeypatch.setattr(remote_channel, "show_notice", shown.append)
|
||||
monkeypatch.setattr(remote_channel, "show_notice", lambda message, qr=None: shown.append(message))
|
||||
monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0)
|
||||
logs = iter([["+ IP Region: CA"], ["+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503"], []])
|
||||
statuses = iter(["authenticating", "authenticating", "authenticating", "authenticated"])
|
||||
@@ -234,7 +234,7 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc
|
||||
|
||||
remote = object.__new__(remote_service.RemoteService)
|
||||
remote.seq = 0
|
||||
remote.client, remote._session_id, remote.auth_notice = Client(), "sid", None
|
||||
remote.client, remote._session_id, remote.auth_notice, remote.auth_qr = Client(), "sid", None, None
|
||||
remote.log = logging.getLogger("test")
|
||||
monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
|
||||
|
||||
@@ -244,11 +244,31 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc
|
||||
assert remote.auth_notice is None
|
||||
|
||||
|
||||
def test_a_relayed_login_keeps_its_qr_code_until_the_login_ends(monkeypatch):
|
||||
import logging
|
||||
|
||||
from unshackle.core import remote_channel
|
||||
|
||||
shown = []
|
||||
monkeypatch.setattr(remote_channel, "show_notice", lambda message, qr=None: shown.append(message))
|
||||
monkeypatch.setattr(remote_channel, "show_qr", lambda data: pytest.fail("a relaying serve has no terminal"))
|
||||
monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
|
||||
remote = object.__new__(remote_service.RemoteService)
|
||||
remote.auth_notice, remote.auth_qr, remote._input_bridge = None, None, object()
|
||||
remote.log = logging.getLogger("test")
|
||||
messages = remote_channel.ServerMessages(remote)
|
||||
messages.show_logs([{"seq": 1, "level": "INFO", "message": "Scan the code", "qr": "https://login.example/scan"}])
|
||||
assert remote.auth_qr == "https://login.example/scan"
|
||||
messages.login_done()
|
||||
assert remote.auth_qr is None and shown == [None]
|
||||
|
||||
|
||||
async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch):
|
||||
import threading as th
|
||||
|
||||
class Remote:
|
||||
auth_notice = None
|
||||
auth_qr = None
|
||||
|
||||
login = handlers.RemoteLogin("owner", "srv", "OTHER", "show", Remote())
|
||||
monkeypatch.setattr(handlers, "_remote_logins", {login.id: login})
|
||||
@@ -256,13 +276,18 @@ async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch):
|
||||
caller = {"key": "owner"}
|
||||
monkeypatch.setattr(handlers, "caller_key", lambda request: caller["key"])
|
||||
got = []
|
||||
asker = th.Thread(target=lambda: got.append(login.bridge.request_input("Enter the code sent to your email")))
|
||||
asker = th.Thread(
|
||||
target=lambda: got.append(
|
||||
login.bridge.request_input("Enter the code sent to your email", qr="https://login.example/scan")
|
||||
)
|
||||
)
|
||||
asker.start()
|
||||
while login.bridge.get_pending_prompt() is None:
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
listed = json.loads((await handlers.remote_logins_handler(None)).text)["logins"]
|
||||
assert listed[0]["prompt"] == "Enter the code sent to your email"
|
||||
assert listed[0]["qr"] == "https://login.example/scan"
|
||||
|
||||
caller["key"] = "someone-else"
|
||||
assert json.loads((await handlers.remote_logins_handler(None)).text)["logins"] == []
|
||||
|
||||
Reference in New Issue
Block a user